hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
b17525b35b4dbd987a2a5c504df131ff75122399
6,256
cc
C++
bin/ui/screencap/main.cc
PowerOlive/garnet
16b5b38b765195699f41ccb6684cc58dd3512793
[ "BSD-3-Clause" ]
null
null
null
bin/ui/screencap/main.cc
PowerOlive/garnet
16b5b38b765195699f41ccb6684cc58dd3512793
[ "BSD-3-Clause" ]
null
null
null
bin/ui/screencap/main.cc
PowerOlive/garnet
16b5b38b765195699f41ccb6684cc58dd3512793
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <cstdlib> #include <iostream> #include <memory> #include <fuchsia/ui/scenic/cpp/fidl.h> #include <lib/async-loop/cpp/loop.h> #include <trace-provider/provider.h> #include "lib/component/cpp/startup_context.h" #include "lib/fsl/vmo/vector.h" #include "lib/fxl/command_line.h" #include "lib/fxl/log_settings_command_line.h" #include "lib/fxl/logging.h" // These are the only values we want to track const int kBlack = 0x000000; const int kWhite = 0xeeeeee; const int kGreen = 0x4dac26; const int kRed = 0xd01c8b; const int kMinExpectedPixels = 950000; // Typical value is ~1.5M const int kMinPixelsForReport = 50000; class ScreenshotTaker { public: explicit ScreenshotTaker(async::Loop* loop, bool output_screen) : loop_(loop), output_screen_(output_screen), context_(component::StartupContext::CreateFromStartupInfo()) { // Connect to the Scenic service. scenic_ = context_->ConnectToEnvironmentService<fuchsia::ui::scenic::Scenic>(); scenic_.set_error_handler([this] { FXL_LOG(ERROR) << "Lost connection to Scenic service."; encountered_error_ = true; loop_->Quit(); }); } bool encountered_error() const { return encountered_error_; } void TakeScreenshot() { FXL_LOG(INFO) << "start TakeScreenshot"; // If we wait for a call back from GetDisplayInfo, we are guaranteed that // the GFX system is initialized, which is a prerequisite for taking a // screenshot. TODO(SCN-678): Remove call to GetDisplayInfo once bug done. scenic_->GetDisplayInfo([this](fuchsia::ui::gfx::DisplayInfo /*unused*/) { TakeScreenshotInternal(); }); } private: void TakeScreenshotInternal() { FXL_LOG(INFO) << "start TakeScreenshotInternal"; scenic_->TakeScreenshot( [this](fuchsia::ui::scenic::ScreenshotData screenshot, bool status) { FXL_LOG(INFO) << "start pixel capture"; std::vector<uint8_t> imgdata; if (!status || !fsl::VectorFromVmo(screenshot.data, &imgdata)) { FXL_LOG(ERROR) << "TakeScreenshot failed"; encountered_error_ = true; loop_->Quit(); return; } std::map<int, int> histogram; if (output_screen_) { std::cout << "P6\n"; std::cout << screenshot.info.width << "\n"; std::cout << screenshot.info.height << "\n"; std::cout << 255 << "\n"; } FXL_LOG(INFO) << "capturing pixels"; const uint8_t* pchannel = &imgdata[0]; for (uint32_t pixel = 0; pixel < screenshot.info.width * screenshot.info.height; pixel++) { uint8_t rgb[] = {pchannel[2], pchannel[1], pchannel[0]}; if (output_screen_) { std::cout.write(reinterpret_cast<const char*>(rgb), 3); } else { int rgb_value = (rgb[0] << 16) + (rgb[1] << 8) + rgb[2]; if (histogram.find(rgb_value) != histogram.end()) { histogram[rgb_value] = histogram[rgb_value] + 1; } else { histogram[rgb_value] = 1; } } pchannel += 4; } if (!output_screen_) { // For success, there should be at least 1M green or red pixels // combined The typical number is > 1.5M if (histogram[kGreen] + histogram[kRed] > kMinExpectedPixels) { FXL_LOG(INFO) << "success"; printf("success\n"); } else { FXL_LOG(INFO) << "failure"; printf("failure\n"); printf("black: %d, white: %d, green: %d, red: %d\n", histogram[kBlack], histogram[kWhite], histogram[kGreen], histogram[kRed]); // To help debug failures, if the majority of values aren't // already expected, output the values that were over a threshold // count. if (histogram[kBlack] + histogram[kWhite] + histogram[kGreen] + histogram[kRed] < kMinExpectedPixels) { const int MIN_REPORT_THRESHOLD = kMinPixelsForReport; std::map<int, int>::iterator it; for (const auto& pair : histogram) { if (pair.second > MIN_REPORT_THRESHOLD) { printf("Pixel 0x%06x occurred %d times\n", pair.first, pair.second); } } } encountered_error_ = true; } } loop_->Quit(); }); } async::Loop* loop_; const bool output_screen_; std::unique_ptr<component::StartupContext> context_; bool encountered_error_ = false; fuchsia::ui::scenic::ScenicPtr scenic_; }; int main(int argc, const char** argv) { FXL_LOG(INFO) << "starting screen capture"; bool output_screen = true; auto command_line = fxl::CommandLineFromArgcArgv(argc, argv); if (!fxl::SetLogSettingsFromCommandLine(command_line)) return 1; const auto& positional_args = command_line.positional_args(); if (!positional_args.empty()) { if (positional_args.size() == 1 && positional_args[0].compare("-histogram") == 0) { output_screen = false; FXL_LOG(INFO) << "in histogram mode"; } else { FXL_LOG(ERROR) << "Usage: screencap\n" << "Takes a screenshot in PPM format and writes it " << "to stdout.\n" << "To write to a file, redirect stdout, e.g.: " << "screencap > \"${DST}\""; return 1; } } FXL_LOG(INFO) << "setting up event loop"; async::Loop loop(&kAsyncLoopConfigAttachToThread); trace::TraceProvider trace_provider(loop.dispatcher()); FXL_LOG(INFO) << "starting taker"; ScreenshotTaker taker(&loop, output_screen); taker.TakeScreenshot(); FXL_LOG(INFO) << "starting Run()"; loop.Run(); FXL_LOG(INFO) << "returning result"; return taker.encountered_error() ? EXIT_FAILURE : EXIT_SUCCESS; }
36.372093
79
0.588235
[ "vector" ]
b17578d38bc26453eecb5862a2eca30ba2abe945
13,551
cc
C++
chrome/browser/ui/views/web_apps/frame_toolbar/web_app_frame_toolbar_view.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/browser/ui/views/web_apps/frame_toolbar/web_app_frame_toolbar_view.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
chrome/browser/ui/views/web_apps/frame_toolbar/web_app_frame_toolbar_view.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/web_apps/frame_toolbar/web_app_frame_toolbar_view.h" #include <memory> #include "chrome/browser/ui/view_ids.h" #include "chrome/browser/ui/views/extensions/extensions_toolbar_button.h" #include "chrome/browser/ui/views/extensions/extensions_toolbar_container.h" #include "chrome/browser/ui/views/frame/browser_non_client_frame_view.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/page_action/page_action_icon_controller.h" #include "chrome/browser/ui/views/toolbar/back_forward_button.h" #include "chrome/browser/ui/views/toolbar/reload_button.h" #include "chrome/browser/ui/views/web_apps/frame_toolbar/web_app_content_settings_container.h" #include "chrome/browser/ui/views/web_apps/frame_toolbar/web_app_menu_button.h" #include "chrome/browser/ui/views/web_apps/frame_toolbar/web_app_navigation_button_container.h" #include "chrome/browser/ui/views/web_apps/frame_toolbar/web_app_toolbar_button_container.h" #include "chrome/browser/ui/views/web_apps/frame_toolbar/window_controls_overlay_toggle_button.h" #include "chrome/browser/ui/web_applications/app_browser_controller.h" #include "ui/base/hit_test.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/views/layout/flex_layout.h" #include "ui/views/view_utils.h" #include "ui/views/window/hit_test_utils.h" WebAppFrameToolbarView::WebAppFrameToolbarView(views::Widget* widget, BrowserView* browser_view) : browser_view_(browser_view) { DCHECK(browser_view_); DCHECK(web_app::AppBrowserController::IsWebApp(browser_view_->browser())); SetID(VIEW_ID_WEB_APP_FRAME_TOOLBAR); SetEventTargeter(std::make_unique<views::ViewTargeter>(this)); { // TODO(tluk) fix the need for both LayoutInContainer() and a layout // manager for frame layout. views::FlexLayout* layout = SetLayoutManager(std::make_unique<views::FlexLayout>()); layout->SetOrientation(views::LayoutOrientation::kHorizontal); layout->SetMainAxisAlignment(views::LayoutAlignment::kEnd); layout->SetCrossAxisAlignment(views::LayoutAlignment::kStretch); } const auto* app_controller = browser_view_->browser()->app_controller(); if (app_controller->HasMinimalUiButtons()) { left_container_ = AddChildView(std::make_unique<WebAppNavigationButtonContainer>( browser_view_, /*toolbar_button_provider=*/this)); left_container_->SetProperty( views::kFlexBehaviorKey, views::FlexSpecification( views::LayoutOrientation::kHorizontal, views::MinimumFlexSizeRule::kScaleToMinimumSnapToZero) .WithOrder(2)); } center_container_ = AddChildView(std::make_unique<views::View>()); center_container_->SetProperty( views::kFlexBehaviorKey, views::FlexSpecification(views::LayoutOrientation::kHorizontal, views::MinimumFlexSizeRule::kScaleToZero, views::MaximumFlexSizeRule::kUnbounded) .WithOrder(3)); right_container_ = AddChildView(std::make_unique<WebAppToolbarButtonContainer>( widget, browser_view, this)); right_container_->SetProperty( views::kFlexBehaviorKey, views::FlexSpecification(right_container_->GetFlexRule()).WithOrder(1)); UpdateStatusIconsVisibility(); DCHECK( !browser_view_->toolbar_button_provider() || views::IsViewClass<WebAppFrameToolbarView>( browser_view_->toolbar_button_provider()->GetAsAccessiblePaneView())) << "This should be the first ToolbarButtorProvider or a replacement for " "an existing instance of this class during a window frame refresh."; browser_view_->SetToolbarButtonProvider(this); if (browser_view_->IsWindowControlsOverlayEnabled()) OnWindowControlsOverlayEnabledChanged(); } WebAppFrameToolbarView::~WebAppFrameToolbarView() = default; void WebAppFrameToolbarView::UpdateStatusIconsVisibility() { right_container_->UpdateStatusIconsVisibility(); } void WebAppFrameToolbarView::UpdateCaptionColors() { // We want to behave differently if this is an update to the color (as opposed // to the first time it's being set). Specifically, updates should pulse the // origin into view. bool color_previously_set = active_background_color_.has_value(); if (color_previously_set) { SkColor old_active_background_color = *active_background_color_; SkColor old_active_foreground_color = *active_foreground_color_; SkColor old_inactive_background_color = *inactive_background_color_; SkColor old_inactive_foreground_color = *inactive_foreground_color_; UpdateCachedColors(); if (old_active_background_color == active_background_color_ && old_active_foreground_color == active_foreground_color_ && old_inactive_background_color == inactive_background_color_ && old_inactive_foreground_color == inactive_foreground_color_) { return; } } else { UpdateCachedColors(); } UpdateChildrenColor(/*color_changed=*/color_previously_set); } void WebAppFrameToolbarView::SetPaintAsActive(bool active) { if (paint_as_active_ == active) return; paint_as_active_ = active; UpdateChildrenColor(/*color_changed=*/false); OnPropertyChanged(&paint_as_active_, views::kPropertyEffectsNone); } bool WebAppFrameToolbarView::GetPaintAsActive() const { return paint_as_active_; } std::pair<int, int> WebAppFrameToolbarView::LayoutInContainer( int leading_x, int trailing_x, int y, int available_height) { SetVisible(available_height > 0); if (available_height == 0) { SetSize(gfx::Size()); return std::pair<int, int>(0, 0); } gfx::Size preferred_size = GetPreferredSize(); const int width = std::max(trailing_x - leading_x, 0); const int height = preferred_size.height(); DCHECK_LE(height, available_height); SetBounds(leading_x, y, width, available_height); Layout(); if (!center_container_->GetVisible()) return std::pair<int, int>(0, 0); // Bounds for remaining inner space, in parent container coordinates. gfx::Rect center_bounds = center_container_->bounds(); DCHECK(center_bounds.x() == 0 || left_container_); center_bounds.Offset(bounds().OffsetFromOrigin()); return std::pair<int, int>(center_bounds.x(), center_bounds.right()); } void WebAppFrameToolbarView::LayoutForWindowControlsOverlay( gfx::Rect available_rect) { DCHECK(!left_container_); // The center_container_ might have been laid out by the frame view such that // it interferes with hit testing in the ToolbarButtonContainer. Ensure that // its bounds are cleared when laying out WCO. center_container_->SetBounds(0, 0, 0, 0); const int width = std::min(available_rect.width(), right_container_->GetPreferredSize().width()); const int x = available_rect.right() - width; SetBounds(x, available_rect.y(), width, available_rect.height()); } ExtensionsToolbarContainer* WebAppFrameToolbarView::GetExtensionsToolbarContainer() { return right_container_->extensions_container(); } gfx::Size WebAppFrameToolbarView::GetToolbarButtonSize() const { const int size = GetLayoutConstant(WEB_APP_MENU_BUTTON_SIZE); return gfx::Size(size, size); } views::View* WebAppFrameToolbarView::GetDefaultExtensionDialogAnchorView() { return right_container_->extensions_container()->GetExtensionsButton(); } PageActionIconView* WebAppFrameToolbarView::GetPageActionIconView( PageActionIconType type) { return right_container_->page_action_icon_controller()->GetIconView(type); } AppMenuButton* WebAppFrameToolbarView::GetAppMenuButton() { return right_container_->web_app_menu_button(); } gfx::Rect WebAppFrameToolbarView::GetFindBarBoundingBox(int contents_bottom) { if (!IsDrawn()) return gfx::Rect(); // If LTR find bar will be right aligned so align to right edge of app menu // button. Otherwise it will be left aligned so align to the left edge of the // app menu button. views::View* anchor_view = GetAnchorView(PageActionIconType::kFind); gfx::Rect anchor_bounds = anchor_view->ConvertRectToWidget(anchor_view->GetLocalBounds()); int x_pos = 0; int width = anchor_bounds.right(); if (base::i18n::IsRTL()) { x_pos = anchor_bounds.x(); width = GetWidget()->GetRootView()->width() - anchor_bounds.x(); } return gfx::Rect(x_pos, anchor_bounds.bottom(), width, contents_bottom - anchor_bounds.bottom()); } void WebAppFrameToolbarView::FocusToolbar() { SetPaneFocus(nullptr); } views::AccessiblePaneView* WebAppFrameToolbarView::GetAsAccessiblePaneView() { return this; } views::View* WebAppFrameToolbarView::GetAnchorView(PageActionIconType type) { views::View* anchor = GetAppMenuButton(); return anchor ? anchor : this; } void WebAppFrameToolbarView::ZoomChangedForActiveTab(bool can_show_bubble) { right_container_->page_action_icon_controller()->ZoomChangedForActiveTab( can_show_bubble); } SidePanelToolbarButton* WebAppFrameToolbarView::GetSidePanelButton() { return nullptr; } AvatarToolbarButton* WebAppFrameToolbarView::GetAvatarToolbarButton() { return nullptr; } ToolbarButton* WebAppFrameToolbarView::GetBackButton() { return left_container_ ? left_container_->back_button() : nullptr; } ReloadButton* WebAppFrameToolbarView::GetReloadButton() { return left_container_ ? left_container_->reload_button() : nullptr; } bool WebAppFrameToolbarView::DoesIntersectRect(const View* target, const gfx::Rect& rect) const { DCHECK_EQ(target, this); if (!views::ViewTargeterDelegate::DoesIntersectRect(this, rect)) return false; // If the rect is inside the bounds of the center_container, do not claim it. // There is no actionable content in the center_container, and it overlaps // tabs in tabbed PWA windows. gfx::RectF rect_in_center_container_coords_f(rect); View::ConvertRectToTarget(this, center_container_, &rect_in_center_container_coords_f); gfx::Rect rect_in_client_view_coords = gfx::ToEnclosingRect(rect_in_center_container_coords_f); return !center_container_->HitTestRect(rect_in_client_view_coords); } void WebAppFrameToolbarView::OnWindowControlsOverlayEnabledChanged() { if (browser_view_->IsWindowControlsOverlayEnabled()) { // The color is not set until the view is added to a widget. if (active_background_color_) { SetBackground(views::CreateSolidBackground( paint_as_active_ ? *active_background_color_ : *inactive_background_color_)); } // BrowserView paints to a layer, so this view must do the same to ensure // that it paints on top of the BrowserView. SetPaintToLayer(); views::SetHitTestComponent(this, static_cast<int>(HTCAPTION)); } else { SetBackground(nullptr); DestroyLayer(); views::SetHitTestComponent(this, static_cast<int>(HTNOWHERE)); } } void WebAppFrameToolbarView::SetWindowControlsOverlayToggleVisible( bool visible) { right_container_->window_controls_overlay_toggle_button()->SetVisible( visible); } PageActionIconController* WebAppFrameToolbarView::GetPageActionIconControllerForTesting() { return right_container_->page_action_icon_controller(); } void WebAppFrameToolbarView::ChildPreferredSizeChanged(views::View* child) { PreferredSizeChanged(); } void WebAppFrameToolbarView::OnThemeChanged() { views::AccessiblePaneView::OnThemeChanged(); UpdateCaptionColors(); } views::View* WebAppFrameToolbarView::GetContentSettingContainerForTesting() { return right_container_->content_settings_container(); } const std::vector<ContentSettingImageView*>& WebAppFrameToolbarView::GetContentSettingViewsForTesting() const { return right_container_->content_settings_container() ->get_content_setting_views(); } void WebAppFrameToolbarView::UpdateCachedColors() { const BrowserNonClientFrameView* frame_view = browser_view_->frame()->GetFrameView(); DCHECK(frame_view); active_background_color_ = frame_view->GetFrameColor(BrowserFrameActiveState::kActive); active_foreground_color_ = frame_view->GetCaptionColor(BrowserFrameActiveState::kActive); inactive_background_color_ = frame_view->GetFrameColor(BrowserFrameActiveState::kInactive); inactive_foreground_color_ = frame_view->GetCaptionColor(BrowserFrameActiveState::kInactive); } void WebAppFrameToolbarView::UpdateChildrenColor(bool color_changed) { const SkColor foreground_color = paint_as_active_ ? *active_foreground_color_ : *inactive_foreground_color_; if (left_container_) left_container_->SetIconColor(foreground_color); const SkColor background_color = paint_as_active_ ? *active_background_color_ : *inactive_background_color_; right_container_->SetColors(foreground_color, background_color, color_changed); if (browser_view_->IsWindowControlsOverlayEnabled()) SetBackground(views::CreateSolidBackground(background_color)); } BEGIN_METADATA(WebAppFrameToolbarView, views::AccessiblePaneView) ADD_PROPERTY_METADATA(bool, PaintAsActive) END_METADATA
38.064607
97
0.74821
[ "vector" ]
b175ea32a4a74536c6b4dfcea34c81820505125a
6,375
cpp
C++
Source/Services/Presence/presence_writer.cpp
CameronGoodwin/xbox-live-api
ee0c3ee2413f2fed6a373df4b26035792e922fe2
[ "MIT" ]
3
2020-07-15T17:50:24.000Z
2021-11-17T11:15:11.000Z
Source/Services/Presence/presence_writer.cpp
CameronGoodwin/xbox-live-api
ee0c3ee2413f2fed6a373df4b26035792e922fe2
[ "MIT" ]
null
null
null
Source/Services/Presence/presence_writer.cpp
CameronGoodwin/xbox-live-api
ee0c3ee2413f2fed6a373df4b26035792e922fe2
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "pch.h" #include "xsapi/presence.h" #include "xsapi/services.h" #include "user_context.h" #include "presence_internal.h" #ifdef __cplusplus_winrt #include "Utils_WinRT.h" #include "utils.h" using namespace Windows::System::Threading; #endif #define PRESENCE_DELAY_IN_MILLISECONDS 60 * 1000 NAMESPACE_MICROSOFT_XBOX_SERVICES_PRESENCE_CPP_BEGIN std::shared_ptr<presence_writer> presence_writer::get_presence_writer_singleton() { return get_xsapi_singleton()->s_presenceWriterSingleton; } presence_writer::presence_writer() : m_writerInProgress(false), m_heartBeatDelayInMins(0), m_isCallInProgress(false) { } #ifdef __cplusplus_winrt void presence_writer::start_timer(_In_ std::weak_ptr<presence_writer> thisWeakPtr) { Windows::Foundation::TimeSpan delay = Microsoft::Xbox::Services::System::UtilsWinRT::ConvertSecondsToTimeSpan<std::chrono::seconds>(std::chrono::minutes(1)); m_timer = ThreadPoolTimer::CreatePeriodicTimer( ref new TimerElapsedHandler([thisWeakPtr](ThreadPoolTimer^ source) { std::shared_ptr<presence_writer> pThis(thisWeakPtr.lock()); if (pThis != nullptr) { pThis->handle_timer_trigger(); } }), delay ); } #else void presence_writer::start_timer( _In_ std::weak_ptr<presence_writer> thisWeakPtr) { m_timerComplete = false; while (true) { if (m_timerComplete) { break; } int delayInMilliseconds = 60 * 1000; // call handle_timer_trigger() every minute utils::sleep(delayInMilliseconds); if (m_timerComplete) { break; } // Do write in the end so that it has the same logic as winrt timer handle_timer_trigger(); } } #endif void presence_writer::start_writer( _In_ std::shared_ptr<presence_service_impl> presenceServiceImpl ) { bool startWriter = false; { std::lock_guard<std::mutex> guard(m_lock.get()); if (!m_writerInProgress) { m_writerInProgress = true; startWriter = true; } const string_t& id = presenceServiceImpl->m_userContext->xbox_user_id(); if (m_presenceServices.find(id) == m_presenceServices.end()) { LOG_INFO("Add new presence service into writer"); m_presenceServices.insert(std::make_pair(id, presenceServiceImpl)); // Skip the first presence write, as we already did it as a part of sign in. } else { LOG_INFO("Presence service for the user already exsit, return"); return; } } if (startWriter) { // Start timer that will write presence after certain time. std::weak_ptr<presence_writer> thisWeakPtr = shared_from_this(); pplx::create_task([thisWeakPtr]() { std::shared_ptr<presence_writer> pThis(thisWeakPtr.lock()); if (pThis != nullptr) { pThis->start_timer(thisWeakPtr); } }); } } void presence_writer::handle_timer_trigger() { LOG_INFO("Start presence writer timer trigger"); m_heartBeatDelayInMins--; if (m_heartBeatDelayInMins > 0) { return; } set_active_in_title(); } void presence_writer::stop_writer( _In_ const string_t& xboxLiveUserId ) { std::lock_guard<std::mutex> guard(m_lock.get()); if (m_writerInProgress) { auto presenceService = m_presenceServices.find(xboxLiveUserId); if (presenceService != m_presenceServices.end()) { set_inactive_in_title(presenceService->second); m_presenceServices.erase(presenceService); } if (m_presenceServices.empty()) { m_writerInProgress = false; m_heartBeatDelayInMins = 0; } #ifdef __cplusplus_winrt if (m_timer) { m_timer->Cancel(); } #else m_timerComplete = true; #endif } } void presence_writer::set_inactive_in_title( _In_ std::shared_ptr<presence_service_impl> presenceServiceImpl ) { // Set the presence to be not in this title try { presenceServiceImpl->set_presence(false); } catch (...) { LOG_ERROR("Set presence inactive fail"); } } void presence_writer::set_active_in_title() { bool expected = false; if (m_isCallInProgress.compare_exchange_strong(expected, true)) { LOG_INFO("Start presence writing."); std::lock_guard<std::mutex> guard(m_lock.get()); std::vector<pplx::task<xbox_live_result<uint32_t>>> writeTasks; for (auto& presencePair : m_presenceServices) { auto& presenceService = presencePair.second; if (presenceService != nullptr) { writeTasks.push_back(pplx::create_task(presenceService->set_presence_helper(true, presence_data()))); } std::weak_ptr<presence_writer> thisWeakPtr = shared_from_this(); pplx::when_all(writeTasks.begin(), writeTasks.end()) .then([thisWeakPtr](std::vector<xbox_live_result<uint32_t>> results) { std::shared_ptr<presence_writer> pThis(thisWeakPtr.lock()); pThis->m_isCallInProgress.store(false); LOG_INFO("Presence writing finish."); // only look at the last result auto heartBeat = (results.end() -1); if (!heartBeat->err()) { pThis->m_heartBeatDelayInMins = heartBeat->payload(); } else { LOGS_ERROR <<"Error detected on presence writing, using default interval for next write:" << heartBeat->err() << ", msg:" << heartBeat->err_message(); // Ignore failures pThis->m_heartBeatDelayInMins = s_defaultHeartBeatDelayInMins; } }); } } else { LOG_INFO("Writting in progress, skip presence writing."); } } NAMESPACE_MICROSOFT_XBOX_SERVICES_PRESENCE_CPP_END
27.478448
161
0.615529
[ "vector" ]
b17ad694cbf11fcc3a108ba4d18e898905be496f
17,287
cc
C++
contrib/binutils-2.27/gold/incremental-dump.cc
lambdaxymox/DragonFlyBSD
6379cf2998a4a073c65b12d99e62988a375b4598
[ "BSD-3-Clause" ]
432
2015-01-03T20:05:29.000Z
2022-03-24T16:39:09.000Z
contrib/binutils-2.27/gold/incremental-dump.cc
lambdaxymox/DragonFlyBSD
6379cf2998a4a073c65b12d99e62988a375b4598
[ "BSD-3-Clause" ]
8
2015-12-03T15:45:38.000Z
2020-12-25T15:42:08.000Z
contrib/binutils-2.27/gold/incremental-dump.cc
lambdaxymox/DragonFlyBSD
6379cf2998a4a073c65b12d99e62988a375b4598
[ "BSD-3-Clause" ]
114
2015-01-07T16:23:00.000Z
2022-03-23T18:26:01.000Z
// incremental.cc -- incremental linking test/debug tool // Copyright (C) 2009-2016 Free Software Foundation, Inc. // Written by Rafael Avila de Espindola <rafael.espindola@gmail.com> // This file is part of gold. // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, // MA 02110-1301, USA. // This file is a (still incomplete) test/debug tool that should display // all information available in the incremental linking sections in a // format that is easy to read. // Once the format is a bit more stable, this should probably be moved to // readelf. Because of that, the use of gold's data structures and functions // is just a short term convenience and not a design decision. #include "gold.h" #include <stdio.h> #include <errno.h> #include <time.h> #include "incremental.h" namespace gold { class Output_file; } using namespace gold; template<int size, bool big_endian> static typename Incremental_inputs_reader<size, big_endian>:: Incremental_input_entry_reader find_input_containing_global( Incremental_inputs_reader<size, big_endian>& incremental_inputs, unsigned int offset, unsigned int* symndx) { typedef Incremental_inputs_reader<size, big_endian> Inputs_reader; static const unsigned int global_sym_entry_size = Incremental_inputs_reader<size, big_endian>::global_sym_entry_size; for (unsigned int i = 0; i < incremental_inputs.input_file_count(); ++i) { typename Inputs_reader::Incremental_input_entry_reader input_file = incremental_inputs.input_file(i); if (input_file.type() != INCREMENTAL_INPUT_OBJECT && input_file.type() != INCREMENTAL_INPUT_ARCHIVE_MEMBER) continue; unsigned int nsyms = input_file.get_global_symbol_count(); if (offset >= input_file.get_symbol_offset(0) && offset < input_file.get_symbol_offset(nsyms)) { *symndx = ((offset - input_file.get_symbol_offset(0)) / global_sym_entry_size); return input_file; } } gold_unreachable(); } template<int size, bool big_endian> static void dump_incremental_inputs(const char* argv0, const char* filename, Sized_incremental_binary<size, big_endian>* inc) { typedef Incremental_binary::Location Location; typedef Incremental_binary::View View; typedef Incremental_inputs_reader<size, big_endian> Inputs_reader; typedef typename Inputs_reader::Incremental_input_entry_reader Entry_reader; if (!inc->has_incremental_info()) { fprintf(stderr, "%s: %s: no .gnu_incremental_inputs section\n", argv0, filename); exit(1); } // Create a reader object for the .gnu_incremental_inputs section. Incremental_inputs_reader<size, big_endian> incremental_inputs(inc->inputs_reader()); if (incremental_inputs.version() != 2) { fprintf(stderr, "%s: %s: unknown incremental version %d\n", argv0, filename, incremental_inputs.version()); exit(1); } const char* command_line = incremental_inputs.command_line(); if (command_line == NULL) { fprintf(stderr, "%s: %s: failed to get link command line\n", argv0, filename); exit(1); } printf("Link command line: %s\n", command_line); printf("\nInput files:\n"); for (unsigned int i = 0; i < incremental_inputs.input_file_count(); ++i) { Entry_reader input_file = incremental_inputs.input_file(i); const char* objname = input_file.filename(); if (objname == NULL) { fprintf(stderr,"%s: %s: failed to get file name for object %u\n", argv0, filename, i); exit(1); } printf("[%d] %s\n", i, objname); Timespec mtime = input_file.get_mtime(); printf(" Timestamp: %llu.%09d %s", static_cast<unsigned long long>(mtime.seconds), mtime.nanoseconds, ctime(&mtime.seconds)); printf(" Serial Number: %d\n", input_file.arg_serial()); printf(" In System Directory: %s\n", input_file.is_in_system_directory() ? "true" : "false"); Incremental_input_type input_type = input_file.type(); printf(" Type: "); switch (input_type) { case INCREMENTAL_INPUT_OBJECT: case INCREMENTAL_INPUT_ARCHIVE_MEMBER: printf("%s\n", (input_type == INCREMENTAL_INPUT_OBJECT ? "Object" : "Archive member")); printf(" Input section count: %d\n", input_file.get_input_section_count()); printf(" Global symbol count: %d\n", input_file.get_global_symbol_count()); printf(" Local symbol offset: %d\n", input_file.get_local_symbol_offset()); printf(" Local symbol count: %d\n", input_file.get_local_symbol_count()); printf(" First dynamic reloc: %d\n", input_file.get_first_dyn_reloc()); printf(" Dynamic reloc count: %d\n", input_file.get_dyn_reloc_count()); printf(" COMDAT group count: %d\n", input_file.get_comdat_group_count()); break; case INCREMENTAL_INPUT_ARCHIVE: printf("Archive\n"); printf(" Member count: %d\n", input_file.get_member_count()); printf(" Unused symbol count: %d\n", input_file.get_unused_symbol_count()); break; case INCREMENTAL_INPUT_SHARED_LIBRARY: printf("Shared library\n"); printf(" As needed: %s\n", input_file.as_needed() ? "true" : "false"); printf(" soname: %s\n", input_file.get_soname()); printf(" Symbol count: %d\n", input_file.get_global_symbol_count()); break; case INCREMENTAL_INPUT_SCRIPT: printf("Linker script\n"); printf(" Object count: %d\n", input_file.get_object_count()); break; default: fprintf(stderr, "%s: invalid file type for object %u: %d\n", argv0, i, input_type); exit(1); } } printf("\nInput sections:\n"); for (unsigned int i = 0; i < incremental_inputs.input_file_count(); ++i) { Entry_reader input_file(incremental_inputs.input_file(i)); if (input_file.type() != INCREMENTAL_INPUT_OBJECT && input_file.type() != INCREMENTAL_INPUT_ARCHIVE_MEMBER) continue; const char* objname = input_file.filename(); if (objname == NULL) { fprintf(stderr,"%s: %s: failed to get file name for object %u\n", argv0, filename, i); exit(1); } printf("[%d] %s\n", i, objname); printf(" %3s %6s %8s %8s %s\n", "n", "outndx", "offset", "size", "name"); unsigned int nsections = input_file.get_input_section_count(); for (unsigned int shndx = 0; shndx < nsections; ++shndx) { typename Entry_reader::Input_section_info info( input_file.get_input_section(shndx)); printf(" %3d %6d %8lld %8lld %s\n", shndx + 1, info.output_shndx, static_cast<long long>(info.sh_offset), static_cast<long long>(info.sh_size), info.name); } unsigned int ncomdat = input_file.get_comdat_group_count(); for (unsigned int i = 0; i < ncomdat; ++i) printf(" Comdat group: %s\n", input_file.get_comdat_group_signature(i)); } // Get a view of the .symtab section. elfcpp::Elf_file<size, big_endian, Incremental_binary> elf_file(inc); unsigned int symtab_shndx = elf_file.find_section_by_type(elfcpp::SHT_SYMTAB); if (symtab_shndx == elfcpp::SHN_UNDEF) // Not found. { fprintf(stderr, "%s: %s: no symbol table section\n", argv0, filename); exit(1); } Location symtab_location(elf_file.section_contents(symtab_shndx)); View symtab_view(inc->view(symtab_location)); // Get a view of the .strtab section. unsigned int strtab_shndx = elf_file.section_link(symtab_shndx); if (strtab_shndx == elfcpp::SHN_UNDEF || strtab_shndx > elf_file.shnum() || elf_file.section_type(strtab_shndx) != elfcpp::SHT_STRTAB) { fprintf(stderr, "%s: %s: no string table section\n", argv0, filename); exit(1); } Location strtab_location(elf_file.section_contents(strtab_shndx)); View strtab_view(inc->view(strtab_location)); elfcpp::Elf_strtab strtab(strtab_view.data(), strtab_location.data_size); // The .gnu_incremental_symtab section contains entries that parallel // the global symbols of the main symbol table. The sh_info field // of the main symbol table's section header tells us how many global // symbols there are, but that count does not include any global // symbols that were forced local during the link. Therefore, we // use the size of the .gnu_incremental_symtab section to deduce // the number of global symbols + forced-local symbols there are // in the symbol table. Incremental_symtab_reader<big_endian> isymtab(inc->symtab_reader()); Incremental_relocs_reader<size, big_endian> irelocs(inc->relocs_reader()); unsigned int sym_size = elfcpp::Elf_sizes<size>::sym_size; unsigned int nsyms = symtab_location.data_size / sym_size; unsigned int nglobals = isymtab.symbol_count(); unsigned int first_global = nsyms - nglobals; unsigned const char* sym_p; printf("\nGlobal symbols per input file:\n"); for (unsigned int i = 0; i < incremental_inputs.input_file_count(); ++i) { Entry_reader input_file(incremental_inputs.input_file(i)); if (input_file.type() != INCREMENTAL_INPUT_OBJECT && input_file.type() != INCREMENTAL_INPUT_ARCHIVE_MEMBER && input_file.type() != INCREMENTAL_INPUT_SHARED_LIBRARY) continue; const char* objname = input_file.filename(); if (objname == NULL) { fprintf(stderr,"%s: %s: failed to get file name for object %u\n", argv0, filename, i); exit(1); } printf("[%d] %s\n", i, objname); unsigned int nsyms = input_file.get_global_symbol_count(); if (nsyms > 0) printf(" %6s %6s %8s %8s %8s %8s\n", "outndx", "shndx", "offset", "chain", "#relocs", "rbase"); if (input_file.type() == INCREMENTAL_INPUT_SHARED_LIBRARY) { for (unsigned int symndx = 0; symndx < nsyms; ++symndx) { bool is_def; bool is_copy; unsigned int output_symndx = input_file.get_output_symbol_index(symndx, &is_def, &is_copy); sym_p = symtab_view.data() + output_symndx * sym_size; elfcpp::Sym<size, big_endian> sym(sym_p); const char* symname; if (!strtab.get_c_string(sym.get_st_name(), &symname)) symname = "<unknown>"; printf(" %6d %6s %8s %8s %8s %8s %-5s %s\n", output_symndx, "", "", "", "", "", is_copy ? "COPY" : (is_def ? "DEF" : "UNDEF"), symname); } } else { for (unsigned int symndx = 0; symndx < nsyms; ++symndx) { Incremental_global_symbol_reader<big_endian> info( input_file.get_global_symbol_reader(symndx)); unsigned int output_symndx = info.output_symndx(); sym_p = symtab_view.data() + output_symndx * sym_size; elfcpp::Sym<size, big_endian> sym(sym_p); const char* symname; if (!strtab.get_c_string(sym.get_st_name(), &symname)) symname = "<unknown>"; printf(" %6d %6d %8d %8d %8d %8d %-5s %s\n", output_symndx, info.shndx() == -1U ? -1 : info.shndx(), input_file.get_symbol_offset(symndx), info.next_offset(), info.reloc_count(), info.reloc_offset(), (info.shndx() == -1U ? "BASE" : info.shndx() == 0 ? "UNDEF" : "DEF"), symname); } } } sym_p = symtab_view.data() + first_global * sym_size; printf("\nGlobal symbol table:\n"); for (unsigned int i = 0; i < nglobals; i++) { elfcpp::Sym<size, big_endian> sym(sym_p); const char* symname; if (!strtab.get_c_string(sym.get_st_name(), &symname)) symname = "<unknown>"; printf("[%d] %s\n", first_global + i, symname); unsigned int offset = isymtab.get_list_head(i); while (offset > 0) { unsigned int sym_ndx; Entry_reader input_file = find_input_containing_global<size, big_endian>(incremental_inputs, offset, &sym_ndx); Incremental_global_symbol_reader<big_endian> sym_info( input_file.get_global_symbol_reader(sym_ndx)); printf(" %s (first reloc: %d, reloc count: %d)", input_file.filename(), sym_info.reloc_offset(), sym_info.reloc_count()); if (sym_info.output_symndx() != first_global + i) printf(" ** wrong output symndx (%d) **", sym_info.output_symndx()); printf("\n"); // Dump the relocations from this input file for this symbol. unsigned int r_off = sym_info.reloc_offset(); for (unsigned int j = 0; j < sym_info.reloc_count(); j++) { printf(" %4d relocation type %3d shndx %2d" " offset %016llx addend %016llx %s\n", r_off, irelocs.get_r_type(r_off), irelocs.get_r_shndx(r_off), static_cast<long long>(irelocs.get_r_offset(r_off)), static_cast<long long>(irelocs.get_r_addend(r_off)), symname); r_off += irelocs.reloc_size; } offset = sym_info.next_offset(); } sym_p += sym_size; } Incremental_got_plt_reader<big_endian> igot_plt(inc->got_plt_reader()); unsigned int ngot = igot_plt.get_got_entry_count(); unsigned int nplt = igot_plt.get_plt_entry_count(); printf("\nGOT entries:\n"); for (unsigned int i = 0; i < ngot; ++i) { unsigned int got_type = igot_plt.get_got_type(i); unsigned int got_symndx = igot_plt.get_got_symndx(i); unsigned int got_input_index = igot_plt.get_got_input_index(i); printf("[%d] type %02x, ", i, got_type & 0x7f); if ((got_type & 0x7f) == 0x7f) printf("reserved"); else if (got_type & 0x80) { Entry_reader input_file = incremental_inputs.input_file(got_input_index); const char* objname = input_file.filename(); printf("local: %s (%d)", objname, got_symndx); } else { sym_p = symtab_view.data() + got_symndx * sym_size; elfcpp::Sym<size, big_endian> sym(sym_p); const char* symname; if (!strtab.get_c_string(sym.get_st_name(), &symname)) symname = "<unknown>"; printf("global %s (%d)", symname, got_symndx); } printf("\n"); } printf("\nPLT entries:\n"); for (unsigned int i = 0; i < nplt; ++i) { unsigned int plt_desc = igot_plt.get_plt_desc(i); printf("[%d] ", i); sym_p = symtab_view.data() + plt_desc * sym_size; elfcpp::Sym<size, big_endian> sym(sym_p); const char* symname; if (!strtab.get_c_string(sym.get_st_name(), &symname)) symname = "<unknown>"; printf("%s (%d)\n", symname, plt_desc); } printf("\nUnused archive symbols:\n"); for (unsigned int i = 0; i < incremental_inputs.input_file_count(); ++i) { Entry_reader input_file(incremental_inputs.input_file(i)); if (input_file.type() != INCREMENTAL_INPUT_ARCHIVE) continue; const char* objname = input_file.filename(); if (objname == NULL) { fprintf(stderr,"%s: %s: failed to get file name for object %u\n", argv0, filename, i); exit(1); } printf("[%d] %s\n", i, objname); unsigned int nsyms = input_file.get_unused_symbol_count(); for (unsigned int symndx = 0; symndx < nsyms; ++symndx) printf(" %s\n", input_file.get_unused_symbol(symndx)); } } int main(int argc, char** argv) { if (argc != 2) { fprintf(stderr, "Usage: %s <file>\n", argv[0]); return 1; } const char* filename = argv[1]; Output_file* file = new Output_file(filename); bool t = file->open_base_file(NULL, false); if (!t) { fprintf(stderr, "%s: open_base_file(%s): %s\n", argv[0], filename, strerror(errno)); return 1; } Incremental_binary* inc = open_incremental_binary(file); if (inc == NULL) { fprintf(stderr, "%s: open_incremental_binary(%s): %s\n", argv[0], filename, strerror(errno)); return 1; } switch (parameters->size_and_endianness()) { #ifdef HAVE_TARGET_32_LITTLE case Parameters::TARGET_32_LITTLE: dump_incremental_inputs<32, false>( argv[0], filename, static_cast<Sized_incremental_binary<32, false>*>(inc)); break; #endif #ifdef HAVE_TARGET_32_BIG case Parameters::TARGET_32_BIG: dump_incremental_inputs<32, true>( argv[0], filename, static_cast<Sized_incremental_binary<32, true>*>(inc)); break; #endif #ifdef HAVE_TARGET_64_LITTLE case Parameters::TARGET_64_LITTLE: dump_incremental_inputs<64, false>( argv[0], filename, static_cast<Sized_incremental_binary<64, false>*>(inc)); break; #endif #ifdef HAVE_TARGET_64_BIG case Parameters::TARGET_64_BIG: dump_incremental_inputs<64, true>( argv[0], filename, static_cast<Sized_incremental_binary<64, true>*>(inc)); break; #endif default: gold_unreachable(); } return 0; }
33.308285
80
0.661364
[ "object", "3d" ]
b17fa1fe5427948a6ecb98ca7d3bd18dfac20a60
6,570
cpp
C++
devtools/tmcdbg/tmcdbgWDlg.cpp
flyingbluefish/tmc
27cf82a3b1b5090fc81dfc82a453ccbc932896ec
[ "BSD-2-Clause" ]
null
null
null
devtools/tmcdbg/tmcdbgWDlg.cpp
flyingbluefish/tmc
27cf82a3b1b5090fc81dfc82a453ccbc932896ec
[ "BSD-2-Clause" ]
null
null
null
devtools/tmcdbg/tmcdbgWDlg.cpp
flyingbluefish/tmc
27cf82a3b1b5090fc81dfc82a453ccbc932896ec
[ "BSD-2-Clause" ]
null
null
null
// tmcdbgWDlg.cpp : implementation file // /* Copyright (C) Shmuel Safonov 2009-2012 All rights reserved. Any usage of this file must be according to TMC License. */ #include "stdafx.h" #include <afxcview.h> #include "tmcdbgW.h" #include "SplitWnd.h" #include "tmcdbgWDlg.h" #ifdef HAS_PLOT_DLL #include "cplot.h" #endif #include "tmcdebugger.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define VERT_SHIFT_PANES 50 //class CTmcMatDoc : public CDocument //{ // // //}; ///////////////////////////////////////////////////////////////////////////// // CTmcdbgWDlg dialog CTmcdbgWDlg::CTmcdbgWDlg(CWnd* pParent /*=NULL*/) : CDialog(CTmcdbgWDlg::IDD, pParent) { //{{AFX_DATA_INIT(CTmcdbgWDlg) m_Addr = _T(""); //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CTmcdbgWDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CTmcdbgWDlg) DDX_Text(pDX, IDC_EDIT_ADDR, m_Addr); DDV_MaxChars(pDX, m_Addr, 100); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CTmcdbgWDlg, CDialog) //{{AFX_MSG_MAP(CTmcdbgWDlg) ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BUTTON_PRINT, OnButtonPrint) ON_BN_CLICKED(IDC_BUTTON_PLOT, OnButtonPlot) ON_WM_SIZE() ON_WM_CANCELMODE() ON_BN_CLICKED(IDC_BUTTON_CLEAR, OnButtonClear) ON_BN_CLICKED(IDC_BUTTON_REFRESH, OnButtonRefresh) //}}AFX_MSG_MAP ON_BN_CLICKED(IDC_BUTTON_IMPORT, &CTmcdbgWDlg::OnBnClickedButtonImport) ON_WM_CLOSE() END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CTmcdbgWDlg message handlers BOOL CTmcdbgWDlg::OnInitDialog() { wchar_t tTitle[] = {0x6708,0}; CDialog::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon this->SetWindowTextW(tTitle); CRect wrect; GetClientRect(&wrect); m_wndSplitter.InitSplitter(this,wrect.right/6,wrect.right/8,wrect.right/2, wrect.right,wrect.bottom,VERT_SHIFT_PANES); OnBnClickedButtonImport(); return TRUE; // return TRUE unless you set the focus to a control } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CTmcdbgWDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this to obtain the cursor to display while the user drags // the minimized window. HCURSOR CTmcdbgWDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; } //HTREEITEM VarRoot; void CTmcdbgWDlg::OnButtonPrint() {// add matrix to TreeView UpdateData(TRUE); if (ConnectTmc()<0) return; m_wndSplitter.OnAddAddr((LPCTSTR)m_Addr); } BOOL CTmcdbgWDlg::DestroyWindow() { // TODO: Add your specialized code here and/or call the base class m_wndSplitter.ClearListMat(); GetMyTreeCtrl()->DestroyWindow(); //try //{ return CDialog::DestroyWindow(); //} //catch (...) //{ //return FALSE; //} } //const double xData[]={1,2,3,4,5}; //const double yData[]={1,4,9,16,4}; long f=0; void CTmcdbgWDlg::OnButtonPlot() { // TODO: Add your control notification handler code here #ifdef HAS_PLOT_DLL HTREEITEM ti; LPARAM x; tmsMatrix *m ; double *times; ti = GetMyTreeCtrl()->GetSelectedItem(); //ti = ((CTreeCtrl*)GetDlgItem(IDC_TREEMAT))->HitTest(NULL); //NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR; //ti = pNMTreeView->itemNew.hItem; if (ti != NULL) { x = (LPARAM)GetItemMatrix(ti); if (x != NULL) { m = (tmsMatrix *)(void*)x; if (_tmcGetType(m) == TYPE_MATRIX) { times = (double*)malloc(sizeof(double) * _tmcNumElem(m)); for (long k=0;k<_tmcNumElem(m);k++) { times[k]=k+1; } Plot(times , m->value.complx.rData , _tmcNumElem(m) , RGB(255,0,0) ,"M" ); SetCurrFigure(++f); if (_tmcHasIm(m)) { Plot(times , m->value.complx.iData , _tmcNumElem(m) , RGB(0,255,0) ,"M"); SetCurrFigure(++f); } free(times); } // long SetCurrFigure(long fig); } } #endif } int hoho; BOOL CTmcdbgWDlg::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult) { // TODO: Add your specialized code here and/or call the base class if ((int)wParam== this->m_wndSplitter.eID ) { hoho = 1; } return CDialog::OnNotify(wParam, lParam, pResult); } void CTmcdbgWDlg::OnSize(UINT nType, int cx, int cy) { CDialog::OnSize(nType, cx, cy); // TODO: Add your message handler code here RECT wrect; GetClientRect(&wrect); CRect rect(0,VERT_SHIFT_PANES,wrect.right,wrect.bottom); if (::IsWindow(m_wndSplitter)) m_wndSplitter.MoveWindow(&rect); } void CTmcdbgWDlg::OnCancelMode() { CDialog::OnCancelMode(); // TODO: Add your message handler code here } void CTmcdbgWDlg::OnButtonClear() { // TODO: Add your control notification handler code here m_wndSplitter.ClearListMat(); GetMyEditCtrl()->SetWindowText(L""); } void CTmcdbgWDlg::OnButtonRefresh() { // TODO: Add your control notification handler code here // 1. must remember selection m_wndSplitter.OnRefresh(); } void CTmcdbgWDlg::OnBnClickedButtonImport() { // LPCTSTR wstr; m_wndSplitter.GetCallStack(); int sel =GetFncListCtrl()->GetSelectionMark(); m_wndSplitter.OnSelectFnc(sel); //CString w_str = GetMyFncListCtrl()->GetItemText(sel,0); //wstr = (LPCTSTR)w_str; // // // GetLocalVars4Fnc(wstr); } void CTmcdbgWDlg::OnClose() { // TODO: Add your message handler code here and/or call default m_wndSplitter.ClearFncListMat(); m_wndSplitter.ClearAllListMat(); m_wndSplitter.ClearListMat(); CDialog::OnClose(); }
21.683168
79
0.654642
[ "model" ]
b184ce0d2abb4cc705a68787bd3cccb535db125b
12,364
cc
C++
sdk/cpp/src/core/entity_proto_converter.cc
lcrh/falken
7545431c7bfa34a9b45c2243cae40dbb58adefaa
[ "Apache-2.0" ]
213
2021-06-11T01:15:16.000Z
2022-02-25T16:18:57.000Z
sdk/cpp/src/core/entity_proto_converter.cc
lcrh/falken
7545431c7bfa34a9b45c2243cae40dbb58adefaa
[ "Apache-2.0" ]
32
2021-06-17T17:58:54.000Z
2022-02-02T05:58:10.000Z
sdk/cpp/src/core/entity_proto_converter.cc
lcrh/falken
7545431c7bfa34a9b45c2243cae40dbb58adefaa
[ "Apache-2.0" ]
28
2021-06-17T17:34:21.000Z
2022-03-24T14:05:20.000Z
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "src/core/entity_proto_converter.h" #include <string.h> #include <string> #include <vector> #include "src/core/assert.h" #include "src/core/attribute_proto_converter.h" #include "src/core/entity_internal.h" #include "src/core/log.h" #include "src/core/protos.h" #include "falken/types.h" namespace falken { proto::EntityFieldType* EntityProtoConverter::ToEntityFieldType( const AttributeBase& attribute, proto::EntityType& entity_type) { proto::EntityFieldType* entity_field_type = entity_type.add_entity_fields(); entity_field_type->set_name(attribute.name()); return entity_field_type; } void EntityProtoConverter::ToCategoryType(const AttributeBase& attribute, proto::EntityType& entity_type) { *ToEntityFieldType(attribute, entity_type)->mutable_category() = AttributeProtoConverter::ToCategoryType(attribute); } proto::EntityType EntityProtoConverter::ToEntityType( const EntityBase& entity_base) { proto::EntityType entity_type; for (const AttributeBase* attribute_base : entity_base.attributes()) { switch (attribute_base->type()) { case AttributeBase::Type::kTypeUnknown: LogError("Unknown Attribute type. Ignoring '%s'.", attribute_base->name()); break; case AttributeBase::Type::kTypeFeelers: *ToEntityFieldType(*attribute_base, entity_type)->mutable_feeler() = AttributeProtoConverter::ToFeelerType(*attribute_base); break; case AttributeBase::Type::kTypePosition: if (strcmp(attribute_base->name(), "position") != 0) { LogWarning("A position attribute already exists. Ignoring '%s'.", attribute_base->name()); } else { FALKEN_DEV_ASSERT(!entity_type.has_position()); entity_type.mutable_position(); } break; case AttributeBase::Type::kTypeRotation: if (strcmp(attribute_base->name(), "rotation") != 0) { LogWarning("A rotation attribute was already parsed. Ignoring '%s'.", attribute_base->name()); } else { FALKEN_DEV_ASSERT(!entity_type.has_rotation()); entity_type.mutable_rotation(); } break; case AttributeBase::Type::kTypeFloat: *ToEntityFieldType(*attribute_base, entity_type)->mutable_number() = AttributeProtoConverter::ToNumberType(*attribute_base); break; case AttributeBase::Type::kTypeBool: ToCategoryType(*attribute_base, entity_type); break; case AttributeBase::Type::kTypeCategorical: ToCategoryType(*attribute_base, entity_type); break; default: LogError("Invalid entity attribute. Ignoring '%s'.", attribute_base->name()); break; } } return entity_type; } void EntityProtoConverter::ToCategory(const AttributeBase& attribute, proto::Entity& entity) { *(entity.add_entity_fields()->mutable_category()) = AttributeProtoConverter::ToCategory(attribute); } proto::Entity EntityProtoConverter::ToEntity(const EntityBase& entity_base) { proto::Entity entity; for (const AttributeBase* attribute_base : entity_base.attributes()) { switch (attribute_base->type()) { case AttributeBase::Type::kTypeUnknown: LogError("Unknown Attribute type. Ignoring '%s'.", attribute_base->name()); break; case AttributeBase::Type::kTypeFeelers: { proto::EntityField* entity_field = entity.add_entity_fields(); proto::Feeler* feeler = entity_field->mutable_feeler(); *feeler = AttributeProtoConverter::ToFeeler(*attribute_base); break; } break; case AttributeBase::Type::kTypePosition: if (strcmp(attribute_base->name(), "position") != 0) { LogWarning("A position attribute already exists. Ignoring '%s'.", attribute_base->name()); } else { FALKEN_DEV_ASSERT(!entity.has_position()); proto::Position* position = entity.mutable_position(); *position = AttributeProtoConverter::ToPosition(*attribute_base); } break; case AttributeBase::Type::kTypeRotation: if (strcmp(attribute_base->name(), "rotation") != 0) { LogWarning("A rotation attribute already exists. Ignoring '%s'.", attribute_base->name()); } else { FALKEN_DEV_ASSERT(!entity.has_rotation()); proto::Rotation* rotation = entity.mutable_rotation(); *rotation = AttributeProtoConverter::ToRotation(*attribute_base); } break; case AttributeBase::Type::kTypeFloat: { proto::EntityField* attribute = entity.add_entity_fields(); proto::Number* number = attribute->mutable_number(); *number = AttributeProtoConverter::ToNumber(*attribute_base); break; } case AttributeBase::Type::kTypeBool: ToCategory(*attribute_base, entity); break; case AttributeBase::Type::kTypeCategorical: { ToCategory(*attribute_base, entity); break; } default: LogError("Invalid entity attribute type. Ignoring '%s'.", attribute_base->name()); break; } } return entity; } void EntityProtoConverter::FromEntityType(const proto::EntityType& entity_type, EntityBase& entity_base) { for (const proto::EntityFieldType& entity_field_type : entity_type.entity_fields()) { AttributeProtoConverter::FromEntityFieldType( entity_field_type, entity_base); } } void EntityProtoConverter::FromEntityType(const proto::EntityType& entity_type, const std::string& entity_name, EntityContainer& entity_container) { entity_container.data_->allocated_entities.emplace_back( EntityBase(entity_container, entity_name.c_str())); EntityProtoConverter::FromEntityType( entity_type, entity_container.data_->allocated_entities.back()); } bool EntityProtoConverter::FromEntity(const proto::Entity& entity, EntityBase& entity_base) { if (!VerifyEntityIntegrity(entity, entity_base)) { LogError("Failed to parse the entity %s. %s.", entity_base.name(), kContactFalkenTeamBug); return false; } bool parsed = true; // Convert position and rotation. parsed = AttributeProtoConverter::FromPosition(entity.position(), entity_base.position); parsed = AttributeProtoConverter::FromRotation(entity.rotation(), entity_base.rotation) && parsed; // Convert attributes. const size_t num_entity_fields = entity.entity_fields_size(); size_t entity_base_index = 0; for (size_t i = 0; i < num_entity_fields; ++i) { // Skip position and rotation attributes as they're not part of the // attributes message in the proto. auto* attribute_base = entity_base.attributes()[entity_base_index]; while (attribute_base == &entity_base.position || attribute_base == &entity_base.rotation) { attribute_base = entity_base.attributes()[++entity_base_index]; } const proto::EntityField& entity_field = entity.entity_fields(i); // Keep parsing even if we find a wrong action to fully log every error // found. parsed = AttributeProtoConverter::FromEntityField(entity_field, *attribute_base) && parsed; ++entity_base_index; } return parsed; } bool EntityProtoConverter::VerifyEntityTypeIntegrity( const proto::EntityType& entity_type, const EntityBase& entity_base) { // We subtract 2 from the entity_base since they are position and rotation, // which are embedded in the EntityType class instead of the attributes array. const size_t num_attributes_entity_base = entity_base.attributes().size() - 2; if (entity_type.entity_fields().size() != num_attributes_entity_base) { std::string entity_type_attributes; for (const proto::EntityFieldType& entity_field_type : entity_type.entity_fields()) { entity_type_attributes += entity_field_type.name() + ", "; } if (!entity_type_attributes.empty()) { // Removing extra ", " added by for loop. entity_type_attributes = entity_type_attributes.substr(0, entity_type_attributes.size() - 2); } std::string entity_base_attributes; for (const AttributeBase* attribute_base : entity_base.attributes()) { if (attribute_base == &entity_base.position || attribute_base == &entity_base.rotation) { continue; } entity_base_attributes += std::string(attribute_base->name()) + ", "; } if (!entity_base_attributes.empty()) { entity_base_attributes = entity_base_attributes.substr(0, entity_base_attributes.size() - 2); } LogWarning( "Entity '%s' is different from the one in the service. The service " "expects %d attribute(s) called [%s] while the application defined " "entity '%s' has %d attribute(s) called [%s].", entity_base.name(), entity_type.entity_fields_size(), entity_type_attributes.c_str(), entity_base.name(), num_attributes_entity_base, entity_base_attributes.c_str()); return false; } bool success = true; for (const proto::EntityFieldType& entity_field_type : entity_type.entity_fields()) { const AttributeBase* attribute_base = entity_base.attribute(entity_field_type.name().c_str()); if (!attribute_base || !AttributeProtoConverter::CompareEntityFieldTypeToAttributeBase( entity_field_type, *attribute_base)) { success = false; LogWarning( "Attribute '%s' in EntityType is different in given EntityBase or " "it does not exists.", entity_field_type.name().c_str()); } } return success; } bool EntityProtoConverter::VerifyEntityIntegrity( const proto::Entity& entity, const EntityBase& entity_base) { // We subtract 2 from the entity_base since they are position and rotation, // which are embedded in the Entity class instead of the attributes array. const size_t num_attributes_entity_base = entity_base.attributes().size() - 2; if (entity.entity_fields().size() != num_attributes_entity_base) { LogWarning( "Entity '%s' is different from the one in the service. In the service " "the entity has '%d' attributes while the local entity has '%d' " "attributes.", entity_base.name(), entity.entity_fields_size(), num_attributes_entity_base); return false; } bool success = true; size_t entity_base_index = 0; for (const proto::EntityField& entity_field : entity.entity_fields()) { // Skip position and rotation attributes as they're not part of the // attributes message in the proto. auto* attribute_base = entity_base.attributes()[entity_base_index]; while (attribute_base == &entity_base.position || attribute_base == &entity_base.rotation) { attribute_base = entity_base.attributes()[++entity_base_index]; } if (!attribute_base || !AttributeProtoConverter::CompareEntityFieldToAttributeBase( entity_field, *attribute_base)) { success = false; LogWarning( "The Attribute '%d' in the entity differs from the one in the " "service or does not exists.", entity_base_index); } ++entity_base_index; } return success; } } // namespace falken
39.628205
80
0.660466
[ "vector" ]
b185db132a5ffec274346c4bd062174873d49440
10,455
cpp
C++
dosyaislemleri.cpp
rutku/uKiris
edabf5ac2fc4d86f4e814b18d0433e8486ee5c37
[ "BSD-2-Clause" ]
3
2017-11-01T08:26:06.000Z
2020-12-20T13:44:07.000Z
dosyaislemleri.cpp
rutku/uKiris
edabf5ac2fc4d86f4e814b18d0433e8486ee5c37
[ "BSD-2-Clause" ]
null
null
null
dosyaislemleri.cpp
rutku/uKiris
edabf5ac2fc4d86f4e814b18d0433e8486ee5c37
[ "BSD-2-Clause" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2017 Ramazan Utku ** Contact: ramazanutku@gmail.com ** ** This file is part of the examples of the Qt Toolkit. ** ** $UKIRIS_BEGIN_LICENSE:BSD$ ** BSD License Usage ** Alternatively, you may use this file under the terms of the BSD license ** as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of The Qt Company Ltd nor the names of its ** contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** TURKISH ** Her hakkı saklıdır. ** Değişiklik yapılarak veya yapılmaksızın, yeniden dağıtmak veya kaynak ve ikili biçimlerde ** kullanmak, aşağıdaki koşullar yerine getirildiği takdirde serbesttir: ** ** * Kaynak kodun yeniden dağıtımı; yukarıdaki telif hakkı uyarısını, şartlar listesini ve ** aşağıdaki ret yazısını muhafaza etmelidir. ** * İkili biçimde yeniden dağıtımında; yukarıdaki telif hakkı uyarısı, şartlar listesi ve ** aşağıdaki ret yazısı dağıtımla birlikte gelen belgelendirmede ve/veya diğer materyallerde ** tekrarlanmalıdır. ** ** İŞBU YAZILIM TELİF HAKKI SAHİPLERİ VE KATKIDA BULUNANLAR TARAFINDAN OLDUĞU GİBİ” SAĞLANMIŞTIR ** VE TİCARETE ELVERİŞLİLİK VE ÖZEL BİR AMACA UYGUNLUK İÇİN KAPALI BİR TAAHHÜT DE DAHİL OLMAK ÜZERE ** VE BUNUNLA KISITLI OLMAKSIZIN HER TÜRLÜ AÇIK YA DA KAPALI TAAHHÜT REDDEDİLMİŞTİR. ** HİÇBİR KOŞULDA TELİF HAKKI SAHİPLERİ VE KATKIDA BULUNANLAR; HER NE SEBEPLE OLUŞMUŞSA VE SÖZLEŞMEDE, ** KUSURSUZ SORUMLULUKTA, VEYA TAZMİNAT YÜKÜMLÜLÜĞÜNDE OLMAK ÜZERE HANGİ YÜKÜMLÜLÜK KURAMINDA ** YER ALIRSA ALSIN,İŞBU YAZILIMIN KULLANIMIYLA ORTAYA ÇIKAN DOĞRUDAN, DOLAYLI, TESADÜFİ, ÖZEL, ** CEZAİ VEYA BİR SEBEP SONUCUNDA OLUŞAN (YEDEK PARÇA VEYA HİZMETLERİN TEMİNİ; KULLANIM, ** VERİ VEYA RANDIMAN KAYBI; YA DA İŞ KESİNTİSİ DE DAHİL OLMAK ÜZERE VE BUNUNLA KISITLI KALMAKSIZIN) ** HERHANGİ BİR ZARAR İÇİN, BU GİBİ HASARLARIN OLASILIĞI HAKKINDA UYARILMIŞ OLSALAR BİLE, SİZE KARŞI ** SORUMLU DEĞİLLERDİR. ** ** $UKIRIS_END_LICENSE$ ** ****************************************************************************/ #include "dosyaislemleri.h" DosyaIslemleri::DosyaIslemleri(QObject *parent) : QObject(parent) { xmlAkisiYaz.setAutoFormatting(true); } void DosyaIslemleri::xmlOlarakKaydet(QIODevice *dosya, QList<CisimModeli *> cisimModeliListesi) { xmlAkisiYaz.setDevice(dosya); xmlAkisiYaz.writeStartDocument(); xmlAkisiYaz.writeDTD("<!DOCTYPE xbel>"); xmlAkisiYaz.writeStartElement("xbel"); xmlAkisiYaz.writeAttribute("version", "1.0"); Ayarlar _ayarlar; QString uzunlugunBirimi = _ayarlar.ayarIsmiAl(Ayarlar::UzunlugunBirimi).replace(" ","_"); QString kuvvetinBirimi = _ayarlar.ayarIsmiAl(Ayarlar::KuvvetinBirimi).replace(" ","_"); QString momentinBirimi = _ayarlar.ayarIsmiAl(Ayarlar::MomentinBirimi).replace(" ","_"); xmlAkisiYaz.writeTextElement(uzunlugunBirimi,"cm"); xmlAkisiYaz.writeTextElement(kuvvetinBirimi,"kN"); xmlAkisiYaz.writeTextElement(momentinBirimi,"kN.m"); foreach (auto cisim, cisimModeliListesi) { QString tipIsmi = cisim->tipIsmiAl().replace(" ","_"); QString sira = cisim->degerIsmiAl(CisimModeli::Sira).replace(" ","_"); QString noktaKonumu = cisim->degerIsmiAl(CisimModeli::NoktaKonumu).replace(" ","_"); QString noktaKuvveti = cisim->degerIsmiAl(CisimModeli::NoktaKuvveti).replace(" ","_"); QString baslangicKonumu = cisim->degerIsmiAl(CisimModeli::BaslangicKonumu).replace(" ","_"); QString baslangicKuvveti = cisim->degerIsmiAl(CisimModeli::BaslangicKuvveti).replace(" ","_"); QString bitisKonumu = cisim->degerIsmiAl(CisimModeli::BitisKonumu).replace(" ","_"); QString bitisKuvveti = cisim->degerIsmiAl(CisimModeli::BitisKuvveti).replace(" ","_"); QString moment = cisim->degerIsmiAl(CisimModeli::Moment).replace(" ","_"); xmlAkisiYaz.writeStartElement(tipIsmi); xmlAkisiYaz.writeTextElement(sira,QString("%1").arg(cisim->siraAl())); xmlAkisiYaz.writeTextElement(noktaKonumu,QString("%1").arg(cisim->noktaKonumuAl())); xmlAkisiYaz.writeTextElement(noktaKuvveti,QString("%1").arg(cisim->noktaKuvvetiAl())); xmlAkisiYaz.writeTextElement(baslangicKonumu,QString("%1").arg(cisim->baslangicKonumuAl())); xmlAkisiYaz.writeTextElement(baslangicKuvveti,QString("%1").arg(cisim->baslangicKuvvetiAl())); xmlAkisiYaz.writeTextElement(bitisKonumu,QString("%1").arg(cisim->bitisKonumuAl())); xmlAkisiYaz.writeTextElement(bitisKuvveti,QString("%1").arg(cisim->bitisKuvvetiAl())); xmlAkisiYaz.writeTextElement(moment,QString("%1").arg(cisim->momentAl())); xmlAkisiYaz.writeEndElement(); } xmlAkisiYaz.writeEndDocument(); } int DosyaIslemleri::xmlAc(QIODevice *dosya) { QString hataMesaji; int hataDizesi; int hataKolonu; if (!domBelgesi.setContent(dosya,true,&hataMesaji,&hataDizesi,&hataKolonu)) { return -1; } QDomElement kok = domBelgesi.documentElement(); if (kok.tagName() != "xbel") { return -2; } else if (kok.hasAttribute("version") && kok.attribute("version") != "1.0") { return -3; } cisimleriOku(kok); return 0; } void DosyaIslemleri::goruntuOlarakKaydet(QString &dosyaYolu, QGraphicsScene *sahne) { sahne->clearSelection(); sahne->setSceneRect(sahne->itemsBoundingRect()); QImage goruntu(sahne->sceneRect().size().toSize(),QImage::Format_ARGB32); goruntu.fill(Qt::white); QPainter boyaci(&goruntu); sahne->render(&boyaci); goruntu.save(dosyaYolu); } void DosyaIslemleri::verileriTemizle() { // qDeleteAll(cisimModelListesi.begin(),cisimModelListesi.end()); cisimModelListesi.clear(); } void DosyaIslemleri::cisimleriOku(QDomElement &kok) { CisimModeli cisim; QDomNode n = ayarlariOku(kok); while(!n.isNull()){ QDomElement eleman = n.toElement(); QString tipIsmi = eleman.tagName(); int tip = cisim.tipIsimleriAl().key(tipIsmi.replace("_"," ")); if (!eleman.isNull()) { CisimModeli *yeniEleman = new CisimModeli(); foreach (auto deger, yeniEleman->degerlerinIsimleriniAl().keys()) { QString isim = yeniEleman->degerlerinIsimleriniAl().value(deger); isim = isim.replace(" ","_"); if (!isim.isEmpty()) { switch (deger) { case CisimModeli::Tip: yeniEleman->tipAta(tip); yeniEleman->tipIsmiAta(cisim.tipIsimleriAl().value(tip)); break; case CisimModeli::Sira: yeniEleman->siraAta(elemaninDegerleriniOku(eleman,isim)); case CisimModeli::NoktaKonumu: yeniEleman->noktaKonumuAta(elemaninDegerleriniOku(eleman,isim)); break; case CisimModeli::NoktaKuvveti: yeniEleman->noktaKuvvetiAta(elemaninDegerleriniOku(eleman,isim)); break; case CisimModeli::BaslangicKonumu: yeniEleman->baslangciKonumuAta(elemaninDegerleriniOku(eleman,isim)); break; case CisimModeli::BaslangicKuvveti: yeniEleman->baslangicKuvvetiAta(elemaninDegerleriniOku(eleman,isim)); break; case CisimModeli::BitisKonumu: yeniEleman->bitisKonumuAta(elemaninDegerleriniOku(eleman,isim)); break; case CisimModeli::BitisKuvveti: yeniEleman->bitisKuvvetiAta(elemaninDegerleriniOku(eleman,isim)); break; case CisimModeli::MomentDegeri: yeniEleman->momentAta(elemaninDegerleriniOku(eleman,isim)); break; default: break; } } } cisimModelListesi.append(yeniEleman); } n = n.nextSibling(); } } double DosyaIslemleri::elemaninDegerleriniOku(QDomElement &eleman,QString &ozellikIsmi) { bool tamam; double deger = eleman.firstChildElement(ozellikIsmi).text().toDouble(&tamam); return deger; } QDomNode DosyaIslemleri::ayarlariOku(QDomElement &kok) { QDomNode n = kok.firstChild(); int ayarSayisi = 0; Ayarlar ayarlarim; while (ayarSayisi < ayarlarim.ayarlarinIsimleriniAl().size()) { QDomElement ayar = n.toElement(); int sira = ayarlarim.ayarlarinIsimleriniAl().key(ayar.tagName().replace("_"," ")); QString ayarinDegeri = ayar.text(); switch (sira) { case Ayarlar::UzunlugunBirimi: case Ayarlar::KuvvetinBirimi: case Ayarlar::MomentinBirimi: ayarlar.insert(sira,ayarinDegeri); break; default: break; } n = n.nextSibling(); ayarSayisi++; } return n; }
41.987952
102
0.659589
[ "render" ]
b1869339219c150beb7505e8eb971757ffc024db
1,468
cpp
C++
examples/gl-ball/paddle_renderer.cpp
EduRenesto/abcg
4f7ab2d02e20e2a9351af03c34360a7629c219d1
[ "MIT" ]
null
null
null
examples/gl-ball/paddle_renderer.cpp
EduRenesto/abcg
4f7ab2d02e20e2a9351af03c34360a7629c219d1
[ "MIT" ]
null
null
null
examples/gl-ball/paddle_renderer.cpp
EduRenesto/abcg
4f7ab2d02e20e2a9351af03c34360a7629c219d1
[ "MIT" ]
null
null
null
#include "paddle_renderer.hpp" #include <glm/gtx/matrix_transform_2d.hpp> glball::PaddleRenderer::PaddleRenderer(GLuint shader) { this->m_paddle_shader = shader; glGenBuffers(1, &this->m_paddle_vbo); glBindBuffer(GL_ARRAY_BUFFER, this->m_paddle_vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 2 * 6, m_paddle_vertices.data(), GL_STATIC_DRAW); glGenVertexArrays(1, &this->m_paddle_vao); glBindVertexArray(this->m_paddle_vao); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr); } void glball::PaddleRenderer::render( Paddle& paddle, glm::mat4 &projection_matrix ) const { const auto translation_matrix = glm::translate(glm::mat3{1.0}, paddle.get_world_position()); const auto scale_matrix = glm::scale(glm::mat3{1.0}, paddle.get_scale()); glUseProgram(this->m_paddle_shader); glBindVertexArray(this->m_paddle_vao); const auto projection_location = glGetUniformLocation(this->m_paddle_shader, "_projection_matrix"); glUniformMatrix4fv(projection_location, 1, GL_FALSE, &projection_matrix[0][0]); const auto scale_location = glGetUniformLocation(this->m_paddle_shader, "_scale_matrix"); glUniformMatrix3fv(scale_location, 1, GL_FALSE, &scale_matrix[0][0]); const auto translation_location = glGetUniformLocation(this->m_paddle_shader, "_translation_matrix"); glUniformMatrix3fv(translation_location, 1, GL_FALSE, &translation_matrix[0][0]); glDrawArrays(GL_TRIANGLES, 0, 6); }
38.631579
103
0.775204
[ "render" ]
b18703de6d8c0f3956c6d35047b6be03012ca83e
95,721
cc
C++
dcmsr/tests/mkreport.cc
liyongjiandegithub/myDCMTK361
2968ddb51d7d2978d2cadea530a316e26784c0e3
[ "Apache-2.0" ]
null
null
null
dcmsr/tests/mkreport.cc
liyongjiandegithub/myDCMTK361
2968ddb51d7d2978d2cadea530a316e26784c0e3
[ "Apache-2.0" ]
null
null
null
dcmsr/tests/mkreport.cc
liyongjiandegithub/myDCMTK361
2968ddb51d7d2978d2cadea530a316e26784c0e3
[ "Apache-2.0" ]
null
null
null
/* * * Copyright (C) 2000-2016, OFFIS e.V. * All rights reserved. See COPYRIGHT file for details. * * This software and supporting documentation were developed by * * OFFIS e.V. * R&D Division Health * Escherweg 2 * D-26121 Oldenburg, Germany * * * Module: dcmsr * * Author: Joerg Riesmeier * * Purpose: Create sample structured reports using the dcmsr API * */ #include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */ #include "dcmtk/ofstd/ofstream.h" #include "dcmtk/dcmsr/dsrdoc.h" #include "dcmtk/dcmdata/dcuid.h" #include "dcmtk/dcmdata/dcfilefo.h" // forward declarations static void generate_ki(DSRDocument *doc, OFString &studyUID_ki); static void generate_si(DSRDocument *doc, OFString &studyUID_ki); static void generate_fk(DSRDocument *doc); static void generate_lp(DSRDocument *doc); static void generate_01(DSRDocument *doc, OFString &studyUID_01); static void generate_02(DSRDocument *doc, OFString &studyUID_01); static void generate_03(DSRDocument *doc); static void generate_04(DSRDocument *doc); static void generate_05(DSRDocument *doc); static void generate_06(DSRDocument *doc); static void generate_07(DSRDocument *doc); static void generate_08(DSRDocument *doc); static void generate_09(DSRDocument *doc); static void generate_10(DSRDocument *doc); static void generate_11(DSRDocument *doc); static void generate_12(DSRDocument *doc); static void generate_13(DSRDocument *doc); static void generate_14(DSRDocument *doc); static void generate_15(DSRDocument *doc); static void generate_16(DSRDocument *doc); static void generate_17(DSRDocument *doc); static void generate_18(DSRDocument *doc); static void generate_19(DSRDocument *doc); // make all reports const int num_reports = 24; const char *all_reports[num_reports] = {"mkreport", "ki", "si", "fk", "lp", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19"}; int main(int argc, char *argv[]) { if (argc < 2) { COUT << "mkreport: Create DICOM SR documents" << OFendl; COUT << "----------------------------------------------------" << OFendl; COUT << " ki = IHE Year 2 key image note (empty)" << OFendl; COUT << " si = IHE Year 2 simple image report (empty)" << OFendl; COUT << " fk = Fake report, C. Iulius Caesar: De bello Gallico" << OFendl; COUT << " lp = Valid comprehensive report with loop/cycle" << OFendl; COUT << OFendl; COUT << " 01 = Consultation report (text only)" << OFendl; COUT << " 02 = Same as 01 but with NUM and PNAME items" << OFendl; COUT << " 03 = Very short report (text only)" << OFendl; COUT << " 04 = Text report with several sections (history)" << OFendl; COUT << " 05 = Text report with several blocks (discharge)" << OFendl; COUT << " 06 = Radiology report with image reference (dentist)" << OFendl; COUT << " 07 = Same as 06 with image/pstate reference" << OFendl; COUT << " 08 = Same as 06 with composite (pstate) reference" << OFendl; COUT << OFendl; COUT << " 09 = RSNA '95: Picker, CT, #3" << OFendl; COUT << " 10 = RSNA '95: Picker, MR, #4" << OFendl; COUT << " 11 = RSNA '95: Kodak, CR, #8" << OFendl; COUT << " 12 = RSNA '95: Acuson, US, #11" << OFendl; COUT << " 13 = RSNA '95: GE, CT, #17" << OFendl; COUT << " 14 = RSNA '95: GE, MR, #21" << OFendl; COUT << " 15 = RSNA '95: Siemens, MR, #26" << OFendl; COUT << " 16 = RSNA '95: Siemens, DS, #29" << OFendl; COUT << " 17 = RSNA '95: Siemens, DR, #31" << OFendl; COUT << " 18 = RSNA '95: Fuji, CR, #32" << OFendl; COUT << " 19 = RSNA '95: ATL, US, #36" << OFendl; COUT << "----------------------------------------------------" << OFendl; COUT << "all = create all abovementioned DICOM SR documents" << OFendl; } else { /* make sure data dictionary is loaded */ if (!dcmDataDict.isDictionaryLoaded()) { CERR << "Warning: no data dictionary loaded, " << "check environment variable: " << DCM_DICT_ENVIRONMENT_VARIABLE << OFendl; } DSRDocument *doc = new DSRDocument(); if (doc != NULL) { OFString studyUID_ki, studyUID_01; OFBool writeFile = OFTrue; /* check whether to create all reports or only selected ones */ const int count = (strcmp(argv[1], "all") == 0) ? num_reports : argc; const char **array = (strcmp(argv[1], "all") == 0) ? all_reports : OFconst_cast(const char **, argv); for (int i = 1; i < count; i++) { writeFile = OFTrue; if (strcmp(array[i], "ki") == 0) generate_ki(doc, studyUID_ki); else if (strcmp(array[i], "si") == 0) generate_si(doc, studyUID_ki); else if (strcmp(array[i], "fk") == 0) generate_fk(doc); else if (strcmp(array[i], "lp") == 0) generate_lp(doc); else if (strcmp(array[i], "01") == 0) generate_01(doc, studyUID_01); else if (strcmp(array[i], "02") == 0) generate_02(doc, studyUID_01); else if (strcmp(array[i], "03") == 0) generate_03(doc); else if (strcmp(array[i], "04") == 0) generate_04(doc); else if (strcmp(array[i], "05") == 0) generate_05(doc); else if (strcmp(array[i], "06") == 0) generate_06(doc); else if (strcmp(array[i], "07") == 0) generate_07(doc); else if (strcmp(array[i], "08") == 0) generate_08(doc); else if (strcmp(array[i], "09") == 0) generate_09(doc); else if (strcmp(array[i], "10") == 0) generate_10(doc); else if (strcmp(array[i], "11") == 0) generate_11(doc); else if (strcmp(array[i], "12") == 0) generate_12(doc); else if (strcmp(array[i], "13") == 0) generate_13(doc); else if (strcmp(array[i], "14") == 0) generate_14(doc); else if (strcmp(array[i], "15") == 0) generate_15(doc); else if (strcmp(array[i], "16") == 0) generate_16(doc); else if (strcmp(array[i], "17") == 0) generate_17(doc); else if (strcmp(array[i], "18") == 0) generate_18(doc); else if (strcmp(array[i], "19") == 0) generate_19(doc); else { writeFile = OFFalse; CERR << "WARNING: unknown document identifier \"" << array[i] << "\" ... ignoring" << OFendl; } if (writeFile) { COUT << OFString(79, '-') << OFendl; COUT << "mkreport: report" << array[i] << ".dcm" << OFendl << OFendl; doc->print(COUT, DSRTypes::PF_shortenLongItemValues); COUT << OFendl; DcmFileFormat *fileformat = new DcmFileFormat(); DcmDataset *dataset = NULL; if (fileformat != NULL) dataset = fileformat->getDataset(); if (dataset != NULL) { doc->getCodingSchemeIdentification().addPrivateDcmtkCodingScheme(); if (doc->write(*dataset).good()) { OFString filename = "report"; filename += array[i]; filename += ".dcm"; fileformat->saveFile(filename.c_str(), EXS_LittleEndianExplicit); } else CERR << "ERROR: could not write SR document into dataset" << OFendl; } } } } delete doc; } return 0; } static void generate_ki(DSRDocument *doc, OFString &studyUID_ki) { doc->createNewDocument(DSRTypes::DT_BasicTextSR); doc->getStudyInstanceUID(studyUID_ki); doc->setStudyDescription("OFFIS Structured Reporting Templates"); doc->setSeriesDescription("IHE Year 2 - Key Image Note"); doc->setSpecificCharacterSetType(DSRTypes::CS_Latin1); doc->setPatientName("Last Name^First Name"); doc->setPatientSex("O"); doc->setManufacturer("OFFIS e.V."); doc->setReferringPhysicianName("Last Name^First Name"); doc->getTree().addContentItem(DSRTypes::RT_isRoot, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.01", OFFIS_CODING_SCHEME_DESIGNATOR, "Document Title")); doc->getTree().addContentItem(DSRTypes::RT_hasObsContext, DSRTypes::VT_Code, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.02", OFFIS_CODING_SCHEME_DESIGNATOR, "Observation Context Mode")); doc->getTree().getCurrentContentItem().setCodeValue(DSRCodedEntryValue("IHE.03", OFFIS_CODING_SCHEME_DESIGNATOR, "DIRECT")); doc->getTree().addContentItem(DSRTypes::RT_hasObsContext, DSRTypes::VT_PName); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.04", OFFIS_CODING_SCHEME_DESIGNATOR, "Recording Observer's Name")); doc->getTree().getCurrentContentItem().setStringValue("Enter text"); doc->getTree().addContentItem(DSRTypes::RT_hasObsContext, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.05", OFFIS_CODING_SCHEME_DESIGNATOR, "Recording Observer's Organization Name")); doc->getTree().getCurrentContentItem().setStringValue("Enter text"); doc->getTree().addContentItem(DSRTypes::RT_hasObsContext, DSRTypes::VT_Code); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.06", OFFIS_CODING_SCHEME_DESIGNATOR, "Observation Context Mode")); doc->getTree().getCurrentContentItem().setCodeValue(DSRCodedEntryValue("IHE.07", OFFIS_CODING_SCHEME_DESIGNATOR, "PATIENT")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.11", OFFIS_CODING_SCHEME_DESIGNATOR, "Key Image Description")); doc->getTree().getCurrentContentItem().setStringValue("Enter text"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Image); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.10", OFFIS_CODING_SCHEME_DESIGNATOR, "Image Reference")); doc->getTree().getCurrentContentItem().setImageReference(DSRImageReferenceValue("0", "0", OFFalse /*check*/), OFFalse /*check*/); } static void generate_si(DSRDocument *doc, OFString &studyUID_ki) { doc->createNewDocument(DSRTypes::DT_BasicTextSR); if (!studyUID_ki.empty()) doc->createNewSeriesInStudy(studyUID_ki); doc->setStudyDescription("OFFIS Structured Reporting Templates"); doc->setSeriesDescription("IHE Year 2 - Simple Image Report"); doc->setSpecificCharacterSetType(DSRTypes::CS_Latin1); doc->setPatientName("Last Name^First Name"); doc->setPatientSex("O"); doc->setManufacturer("OFFIS e.V."); doc->setReferringPhysicianName("Last Name^First Name"); doc->getTree().addContentItem(DSRTypes::RT_isRoot, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.01", OFFIS_CODING_SCHEME_DESIGNATOR, "Document Title")); doc->getTree().addContentItem(DSRTypes::RT_hasObsContext, DSRTypes::VT_Code, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.02", OFFIS_CODING_SCHEME_DESIGNATOR, "Observation Context Mode")); doc->getTree().getCurrentContentItem().setCodeValue(DSRCodedEntryValue("IHE.03", OFFIS_CODING_SCHEME_DESIGNATOR, "DIRECT")); doc->getTree().addContentItem(DSRTypes::RT_hasObsContext, DSRTypes::VT_PName); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.04", OFFIS_CODING_SCHEME_DESIGNATOR, "Recording Observer's Name")); doc->getTree().getCurrentContentItem().setStringValue("Enter text"); doc->getTree().addContentItem(DSRTypes::RT_hasObsContext, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.05", OFFIS_CODING_SCHEME_DESIGNATOR, "Recording Observer's Organization Name")); doc->getTree().getCurrentContentItem().setStringValue("Enter text"); doc->getTree().addContentItem(DSRTypes::RT_hasObsContext, DSRTypes::VT_Code); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.06", OFFIS_CODING_SCHEME_DESIGNATOR, "Observation Context Mode")); doc->getTree().getCurrentContentItem().setCodeValue(DSRCodedEntryValue("IHE.07", OFFIS_CODING_SCHEME_DESIGNATOR, "PATIENT")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.08", OFFIS_CODING_SCHEME_DESIGNATOR, "Section Heading")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.09", OFFIS_CODING_SCHEME_DESIGNATOR, "Report Text")); doc->getTree().getCurrentContentItem().setStringValue("Enter text"); doc->getTree().addContentItem(DSRTypes::RT_inferredFrom, DSRTypes::VT_Image, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.10", OFFIS_CODING_SCHEME_DESIGNATOR, "Image Reference")); doc->getTree().getCurrentContentItem().setImageReference(DSRImageReferenceValue("0", "0", OFFalse /*check*/), OFFalse /*check*/); doc->getTree().goUp(); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Image); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.10", OFFIS_CODING_SCHEME_DESIGNATOR, "Image Reference")); doc->getTree().getCurrentContentItem().setImageReference(DSRImageReferenceValue("0", "0", OFFalse /*check*/), OFFalse /*check*/); } static void generate_fk(DSRDocument *doc) { doc->createNewDocument(DSRTypes::DT_BasicTextSR); doc->createNewSeriesInStudy("1.2.276.0.7230010.3.4.1915765545.18030.917282194.11"); doc->setStudyDescription("OFFIS Structured Reporting Templates"); doc->setSeriesDescription("Fake Report, C. Iulius Caesar: De bello Gallico"); doc->setPatientName("Caesar^Gaius Iulius"); doc->setPatientSex("M"); doc->setReferringPhysicianName("Augustus Caesar^Gaius Iulius Octavianus"); doc->getTree().addContentItem(DSRTypes::RT_isRoot, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CH_0.1", OFFIS_CODING_SCHEME_DESIGNATOR, "De bello Gallico")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Image, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CH_1.1", OFFIS_CODING_SCHEME_DESIGNATOR, "Image of the Author")); doc->getTree().getCurrentContentItem().setImageReference(DSRImageReferenceValue(UID_SecondaryCaptureImageStorage, "1.2.276.0.7230010.3.4.1915765545.18030.917282194.11.1.1", UID_GrayscaleSoftcopyPresentationStateStorage, "1.2.276.0.7230010.3.1.4.1707840890.221.974385531.18")); doc->getCurrentRequestedProcedureEvidence().addItem("1.2.276.0.7230010.3.4.1915765545.18030.917282194.11", "1.2.276.0.7230010.3.4.1915765545.18030.917282194.11.1", UID_SecondaryCaptureImageStorage, "1.2.276.0.7230010.3.4.1915765545.18030.917282194.11.1.1"); doc->getCurrentRequestedProcedureEvidence().setRetrieveAETitle("DCMPSTATE"); doc->getPertinentOtherEvidence().addItem("1.2.276.0.7230010.3.4.1915765545.18030.917282194.11", "1.2.276.0.7230010.3.1.4.1707840890.221.974385403.16", UID_GrayscaleSoftcopyPresentationStateStorage, "1.2.276.0.7230010.3.1.4.1707840890.221.974385531.18"); doc->getPertinentOtherEvidence().setRetrieveAETitle("DCMPSTATE"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CH_2.1", OFFIS_CODING_SCHEME_DESIGNATOR, "Liber primus")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Container, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CH_3.1", OFFIS_CODING_SCHEME_DESIGNATOR, "I")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CH_4.1", OFFIS_CODING_SCHEME_DESIGNATOR, "1")); doc->getTree().getCurrentContentItem().setStringValue("Gallia est omnis divisa in partes tres, quarum unam incolunt Belgae, aliam Aquitani, tertiam, qui ipsorum lingua Celtae, nostra Galli appellantur."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CH_4.2", OFFIS_CODING_SCHEME_DESIGNATOR, "2")); doc->getTree().getCurrentContentItem().setStringValue("Hi omnes lingua, institutis, legibus inter se differunt. Gallos ab Aquitanis Garunna flumen, a Belgis Matrona et Sequana dividit."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CH_4.3", OFFIS_CODING_SCHEME_DESIGNATOR, "3")); doc->getTree().getCurrentContentItem().setStringValue("Horum omnium fortissimi sunt Belgae, propterea quod a cultu atque humanitate provinciae longissime absunt minimeque ad eos mercatores saepe commeant atque ea, quae ad effeminandos animos pertinent, important proximique sunt Germanis, qui trans Rhenum incolunt, quibuscum continenter bellum gerunt."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CH_4.4", OFFIS_CODING_SCHEME_DESIGNATOR, "4")); doc->getTree().getCurrentContentItem().setStringValue("Qua de causa Helvetii quoque reliquos Gallos virtute praecedunt, quod fere cotidianis proeliis cum Germanis contendunt, cum aut suis finibus eos prohibent aut ipsi in eorum finibus bellum gerunt."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CH_4.5", OFFIS_CODING_SCHEME_DESIGNATOR, "5")); doc->getTree().getCurrentContentItem().setStringValue("[Eorum una, pars, quam Gallos obtinere dictum est, initium capit a flumine Rhodano, continetur Garumna flumine, Oceano, finibus Belgarum, attingit etiam ab Sequanis et Helvetiis flumen Rhenum, vergit ad septentriones."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CH_4.6", OFFIS_CODING_SCHEME_DESIGNATOR, "6")); doc->getTree().getCurrentContentItem().setStringValue("Belgae ab extremis Galliae finibus oriuntur, pertinent ad inferiorem partem fluminis Rheni, spectant in septentrionem et orientem solem."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CH_4.7", OFFIS_CODING_SCHEME_DESIGNATOR, "7")); doc->getTree().getCurrentContentItem().setStringValue("Aquitania a Garumna flumine ad Pyrenaeos montes et eam partem Oceani quae est ad Hispaniam pertinet; spectat inter occasum solis et septentriones.]"); doc->getTree().goUp(); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CH_3.2", OFFIS_CODING_SCHEME_DESIGNATOR, "II")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CH_4.1", OFFIS_CODING_SCHEME_DESIGNATOR, "1")); doc->getTree().getCurrentContentItem().setStringValue("Apud Helvetios longe nobilissimus fuit et ditissimus Orgetorix. Is M. Messalla M. Pisone consulibus regni cupiditate inductus coniurationem nobilitatis fecit et civitati persuasit, ut de finibus suis cum omnibus copiis exirent:"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CH_4.2", OFFIS_CODING_SCHEME_DESIGNATOR, "2")); doc->getTree().getCurrentContentItem().setStringValue("Perfacile esse, cum virtute omnibus praestarent, totius Galliae imperio potiri."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CH_4.3", OFFIS_CODING_SCHEME_DESIGNATOR, "3")); doc->getTree().getCurrentContentItem().setStringValue("Id hoc facilius iis persuasit, quod undique loci natura Helvetii continentur: una ex parte flumine Rheno latissimo atque altissimo, qui agrum Helvetium a Germanis dividit, altera ex parte monte Iura altissimo, qui est inter Sequanos et Helvetios, tertia lacu Lemanno et flumine Rhodano, qui provinciam nostram ab Helvetiis dividit."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CH_4.4", OFFIS_CODING_SCHEME_DESIGNATOR, "4")); doc->getTree().getCurrentContentItem().setStringValue("His rebus fiebat, ut et minus late vagarentur et minus facile finitimis bellum inferre possent; qua ex parte homines bellandi cupidi magno dolore afficiebantur. 5 Pro multitudine autem hominum et pro gloria belli atque fortitudinis angustos se fines habere arbitrabantur, qui in longitudinem milia passuum ducenta quadraginta, in latitudinem centum octoginta patebant."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CH_4.5", OFFIS_CODING_SCHEME_DESIGNATOR, "5")); doc->getTree().getCurrentContentItem().setStringValue("Pro multitudine autem hominum et pro gloria belli atque fortitudinis angustos se fines habere arbitrabantur, qui in longitudinem milia passuum ducenta quadraginta, in latitudinem centum octoginta patebant."); doc->completeDocument(); doc->verifyDocument("Augustus Caesar^Gaius Iulius Octavianus", "SPQR"); } static void generate_lp(DSRDocument *doc) { doc->createNewDocument(DSRTypes::DT_ComprehensiveSR); doc->setStudyDescription("OFFIS Structured Reporting Test"); doc->setSeriesDescription("Valid report with loop/cycle"); doc->setPatientName("Loop^Mr"); doc->setPatientSex("M"); doc->getTree().addContentItem(DSRTypes::RT_isRoot, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("TST.01", OFFIS_CODING_SCHEME_DESIGNATOR, "Document Title")); size_t node1 = doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("TST.02", OFFIS_CODING_SCHEME_DESIGNATOR, "First Paragraph")); doc->getTree().getCurrentContentItem().setStringValue("Some text."); size_t node2 = doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("TST.03", OFFIS_CODING_SCHEME_DESIGNATOR, "Second Paragraph")); doc->getTree().getCurrentContentItem().setStringValue("Some more text."); doc->getTree().addByReferenceRelationship(DSRTypes::RT_inferredFrom, node1); doc->getTree().gotoNode(node1); doc->getTree().addByReferenceRelationship(DSRTypes::RT_inferredFrom, node2); } static void generate_01(DSRDocument *doc, OFString &studyUID_01) { doc->createNewDocument(DSRTypes::DT_BasicTextSR); doc->setStudyDescription("OFFIS Structured Reporting Samples"); doc->getStudyInstanceUID(studyUID_01); doc->setSeriesDescription("Basic Text Report"); doc->setPatientName("Osterman^Phillip^B."); doc->setPatientBirthDate("19220909"); doc->setPatientSex("M"); doc->setReferringPhysicianName("Fukuda^Katherine M.^^^M. D."); doc->getTree().addContentItem(DSRTypes::RT_isRoot, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("DT.06", OFFIS_CODING_SCHEME_DESIGNATOR, "Consultation Report")); doc->getTree().addContentItem(DSRTypes::RT_hasObsContext, DSRTypes::VT_PName, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.04", OFFIS_CODING_SCHEME_DESIGNATOR, "Observer Name")); doc->getTree().getCurrentContentItem().setStringValue("Packer^David M.^^^M. D."); doc->getTree().addContentItem(DSRTypes::RT_hasObsContext, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.05", OFFIS_CODING_SCHEME_DESIGNATOR, "Observer Organization Name")); doc->getTree().getCurrentContentItem().setStringValue("Redlands Clinic"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_01", OFFIS_CODING_SCHEME_DESIGNATOR, "Description")); doc->getTree().getCurrentContentItem().setStringValue("This 78-year-old gentleman referred by Dr. Fukuda was also seen by Dr. Mason at the Redlands Clinic. He has been seen in the past by Dr. Klugman.\nThe patient developed a lesion in the concha of the left external ear. Recent biopsy confirmed this as being a squamous cell carcinoma. The patient has had a few other skin cancers.\nOf most significant past history is the fact that this patient has a leukemia that has been treated in standard fashion by Dr. Klugman. The patient was then transferred to the Redlands Clinic and by some experimental protocol which, I guess, includes some sort of lymphocyte electrophoresis, has been placed into remission. He is not currently on any antileukemia drugs and has responded extremely well to his medical management.\nOn examination, the patient is healthy in general appearance. There is a 1.5 cm lesion on the concha of the ear, which is seen well on photograph of the left external ear. There are numerous soft lymph nodes in both sides of the neck, which I presume are related to his leukemia."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_02", OFFIS_CODING_SCHEME_DESIGNATOR, "Diagnosis")); doc->getTree().getCurrentContentItem().setStringValue("Squamous cell carcinoma, relatively superficial, involving the skin of the left external ear, which is seen well on photograph of the left external ear."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_03", OFFIS_CODING_SCHEME_DESIGNATOR, "Treatment")); doc->getTree().getCurrentContentItem().setStringValue("The plan of treatment is as follows: 4500 rad, 15 treatment sessions, using 100 kV radiation.\nThe reason for treatment, expected acute reaction, and remote possibility of complication was discussed with this patient at some length, and he accepted therapy as outlined."); } static void generate_02(DSRDocument *doc, OFString &studyUID_01) { doc->createNewDocument(DSRTypes::DT_EnhancedSR); if (!studyUID_01.empty()) doc->createNewSeriesInStudy(studyUID_01); doc->setStudyDescription("OFFIS Structured Reporting Samples"); doc->setSeriesDescription("Text Report with CODE, NUM and PNAME content items"); doc->setPatientName("Osterman^Phillip B."); doc->setPatientBirthDate("19220909"); doc->setPatientSex("M"); doc->setReferringPhysicianName("Fukuda^Katherine M.^^^M. D."); doc->getTree().addContentItem(DSRTypes::RT_isRoot, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("DT.06", OFFIS_CODING_SCHEME_DESIGNATOR, "Consultation Report")); doc->getTree().addContentItem(DSRTypes::RT_hasObsContext, DSRTypes::VT_PName, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.04", OFFIS_CODING_SCHEME_DESIGNATOR, "Observer Name")); doc->getTree().getCurrentContentItem().setStringValue("Packer^David M.^^^M. D."); doc->getTree().addContentItem(DSRTypes::RT_hasObsContext, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.05", OFFIS_CODING_SCHEME_DESIGNATOR, "Observer Organization Name")); doc->getTree().getCurrentContentItem().setStringValue("Redlands Clinic"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setContinuityOfContent(DSRTypes::COC_Continuous); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_01", OFFIS_CODING_SCHEME_DESIGNATOR, "Description")); doc->getTree().getCurrentContentItem().setStringValue("This 78-year-old gentleman referred by"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_PName); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_04", OFFIS_CODING_SCHEME_DESIGNATOR, "Referring Physician")); doc->getTree().getCurrentContentItem().setStringValue("Fukuda^^^Dr."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_01", OFFIS_CODING_SCHEME_DESIGNATOR, "Description")); doc->getTree().getCurrentContentItem().setStringValue("was also seen by"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_PName); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("OR.01", OFFIS_CODING_SCHEME_DESIGNATOR, "Physician")); doc->getTree().getCurrentContentItem().setStringValue("Mason^^^Dr."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_01", OFFIS_CODING_SCHEME_DESIGNATOR, "Description")); doc->getTree().getCurrentContentItem().setStringValue("at the"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Code); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_05", OFFIS_CODING_SCHEME_DESIGNATOR, "Hospital Name")); doc->getTree().getCurrentContentItem().setCodeValue(DSRCodedEntryValue("CODE_06", OFFIS_CODING_SCHEME_DESIGNATOR, "Redlands Clinic")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_01", OFFIS_CODING_SCHEME_DESIGNATOR, "Description")); doc->getTree().getCurrentContentItem().setStringValue(". He has been seen in the past by"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_PName); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("OR.01", OFFIS_CODING_SCHEME_DESIGNATOR, "Physician")); doc->getTree().getCurrentContentItem().setStringValue("Klugman^^^Dr."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_01", OFFIS_CODING_SCHEME_DESIGNATOR, "Description")); doc->getTree().getCurrentContentItem().setStringValue(".\nThe patient developed a lesion in the concha of the left external ear. Recent biopsy confirmed this as being a squamous cell carcinoma. The patient has had a few other skin cancers.\nOf most significant past history is the fact that this patient has a leukemia that has been treated in standard fashion by"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_PName); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("OR.01", OFFIS_CODING_SCHEME_DESIGNATOR, "Physician")); doc->getTree().getCurrentContentItem().setStringValue("Klugman^^^Dr."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_01", OFFIS_CODING_SCHEME_DESIGNATOR, "Description")); doc->getTree().getCurrentContentItem().setStringValue(". The patient was then transferred to the"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Code); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_05", OFFIS_CODING_SCHEME_DESIGNATOR, "Hospital Name")); doc->getTree().getCurrentContentItem().setCodeValue(DSRCodedEntryValue("CODE_06", OFFIS_CODING_SCHEME_DESIGNATOR, "Redlands Clinic")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_01", OFFIS_CODING_SCHEME_DESIGNATOR, "Description")); doc->getTree().getCurrentContentItem().setStringValue("and by some experimental protocol which, I guess, includes some sort of lymphocyte electrophoresis, has been placed into remission. He is not currently on any antileukemia drugs and has responded extremely well to his medical management.\nOn examination, the patient is healthy in general appearance. There is a"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Num); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("M-02550", "SNM3", "Diameter")); doc->getTree().getCurrentContentItem().setNumericValue(DSRNumericMeasurementValue("1.5", DSRCodedEntryValue("cm", "UCUM", "1.4", "centimeter"))); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_01", OFFIS_CODING_SCHEME_DESIGNATOR, "Description")); doc->getTree().getCurrentContentItem().setStringValue("lesion on the concha of the ear, which is seen well on photograph of the left external ear. There are numerous soft lymph nodes in both sides of the neck, which I presume are related to his leukemia."); doc->getTree().goUp(); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_02", OFFIS_CODING_SCHEME_DESIGNATOR, "Diagnosis")); doc->getTree().getCurrentContentItem().setStringValue("Squamous cell carcinoma, relatively superficial, involving the skin of the left external ear, which is seen well on photograph of the left external ear."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_03", OFFIS_CODING_SCHEME_DESIGNATOR, "Treatment")); doc->getTree().getCurrentContentItem().setStringValue("The plan of treatment is as follows: 4500 rad, 15 treatment sessions, using 100 kV radiation.\nThe reason for treatment, expected acute reaction, and remote possibility of complication was discussed with this patient at some length, and he accepted therapy as outlined."); // add additional information on UCUM coding scheme (UID from CP-372) doc->getCodingSchemeIdentification().addItem("UCUM"); doc->getCodingSchemeIdentification().setCodingSchemeUID("2.16.840.1.113883.6.8"); doc->getCodingSchemeIdentification().setCodingSchemeName("Unified Code for Units of Measure"); doc->getCodingSchemeIdentification().setCodingSchemeVersion("1.4"); doc->getCodingSchemeIdentification().setCodingSchemeResponsibleOrganization("Regenstrief Institute for Health Care, Indianapolis"); } static void generate_03(DSRDocument *doc) { doc->createNewDocument(DSRTypes::DT_BasicTextSR); doc->setStudyDescription("OFFIS Structured Reporting Samples"); doc->setSeriesDescription("Text Report with different sections"); doc->setPatientName("Silverman^Elaine J."); doc->setPatientBirthDate("19811010"); doc->setPatientSex("F"); doc->setReferringPhysicianName("Cooper^Harold B.^^^M. D."); doc->getTree().addContentItem(DSRTypes::RT_isRoot, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("DT.01", OFFIS_CODING_SCHEME_DESIGNATOR, "Radiology Report")); doc->getTree().addContentItem(DSRTypes::RT_hasObsContext, DSRTypes::VT_PName, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.04", OFFIS_CODING_SCHEME_DESIGNATOR, "Observer Name")); doc->getTree().getCurrentContentItem().setStringValue("Skinner^Marian B.^^^M. D."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Container, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("SH.06", OFFIS_CODING_SCHEME_DESIGNATOR, "Findings")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_07", OFFIS_CODING_SCHEME_DESIGNATOR, "PA Chest")); doc->getTree().getCurrentContentItem().setStringValue("Upright PA view of the chest shows the lung fields are clear, without evidence of an active process. Heart size in normal."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.06", OFFIS_CODING_SCHEME_DESIGNATOR, "Impression")); doc->getTree().getCurrentContentItem().setStringValue("Negative chest."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_08", OFFIS_CODING_SCHEME_DESIGNATOR, "Abdomen")); doc->getTree().getCurrentContentItem().setStringValue("Flat and upright views of the abdomen show a normal gas pattern without evidence of obstruction or ileus. There are no calcifications or abnormal masses noted."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.06", OFFIS_CODING_SCHEME_DESIGNATOR, "Impression")); doc->getTree().getCurrentContentItem().setStringValue("Negative study."); } static void generate_04(DSRDocument *doc) { doc->createNewDocument(DSRTypes::DT_BasicTextSR); doc->setStudyDescription("OFFIS Structured Reporting Samples"); doc->setSeriesDescription("Text Report with hierarchical structure"); doc->setPatientName("Mars^Verna Marie^de"); doc->setPatientBirthDate("19320810"); doc->setPatientSex("F"); doc->setPatientID("62789"); doc->getTree().addContentItem(DSRTypes::RT_isRoot, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("SH.01", OFFIS_CODING_SCHEME_DESIGNATOR, "History")); doc->getTree().addContentItem(DSRTypes::RT_hasObsContext, DSRTypes::VT_PName, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.04", OFFIS_CODING_SCHEME_DESIGNATOR, "Observer Name")); doc->getTree().getCurrentContentItem().setStringValue("Struthers^Cortland M.^^^M. D."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_09", OFFIS_CODING_SCHEME_DESIGNATOR, "Chief Complaint")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_09", OFFIS_CODING_SCHEME_DESIGNATOR, "Chief Complaint")); doc->getTree().getCurrentContentItem().setStringValue("Prolapse and bleeding after each bowel movement for the past 3 - 4 months."); doc->getTree().goUp(); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_10", OFFIS_CODING_SCHEME_DESIGNATOR, "Present Illness")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_10", OFFIS_CODING_SCHEME_DESIGNATOR, "Present Illness")); doc->getTree().getCurrentContentItem().setStringValue("This 68 year-old white female says she usually has three bowel movements a day in small amounts, and there has been a recent change in the frequency, size, and type of bowel movement she has been having. She is also having some pain and irritation in this area. She has had no previous anorectal surgery or rectal infection. She denies any blood in the stool itself."); doc->getTree().goUp(); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_11", OFFIS_CODING_SCHEME_DESIGNATOR, "Past History")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_12", OFFIS_CODING_SCHEME_DESIGNATOR, "Illnesses")); doc->getTree().getCurrentContentItem().setStringValue("The patient had polio at age 8, from which she made a remarkable recovery. Apparently, she was paralyzed in both lower extremities but now has adequate use of these. She has had no other serious illnesses."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_13", OFFIS_CODING_SCHEME_DESIGNATOR, "Allergies")); doc->getTree().getCurrentContentItem().setStringValue("ALLERGIC TO PENICILLIN. She denies any other drug or food allergies."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_14", OFFIS_CODING_SCHEME_DESIGNATOR, "Medications")); doc->getTree().getCurrentContentItem().setStringValue("None"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_15", OFFIS_CODING_SCHEME_DESIGNATOR, "Operations")); doc->getTree().getCurrentContentItem().setStringValue("Herniorrhaphy, 25 years ago."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_16", OFFIS_CODING_SCHEME_DESIGNATOR, "Social")); doc->getTree().getCurrentContentItem().setStringValue("She does not smoke or drink. She lives with her husband, who is an invalid and for whom she provides care. She is a retired municipal court judge."); doc->getTree().goUp(); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_17", OFFIS_CODING_SCHEME_DESIGNATOR, "Family History")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_18", OFFIS_CODING_SCHEME_DESIGNATOR, "Family History")); doc->getTree().getCurrentContentItem().setStringValue("One brother died of cancer of the throat; another has cancer of the kidney."); } static void generate_05(DSRDocument *doc) { doc->createNewDocument(DSRTypes::DT_BasicTextSR); doc->setStudyDescription("OFFIS Structured Reporting Samples"); doc->setSeriesDescription("Text Report with different sections"); doc->setSpecificCharacterSetType(DSRTypes::CS_Latin1); doc->setPatientName("Silverman^Elaine J."); doc->setPatientBirthDate("19811010"); doc->setPatientSex("F"); doc->getTree().addContentItem(DSRTypes::RT_isRoot, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_19", OFFIS_CODING_SCHEME_DESIGNATOR, "Discharge Summary")); doc->getTree().addContentItem(DSRTypes::RT_hasObsContext, DSRTypes::VT_PName, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.04", OFFIS_CODING_SCHEME_DESIGNATOR, "Observer Name")); doc->getTree().getCurrentContentItem().setStringValue("Cooper^Harold B.^^^M. D."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_20", OFFIS_CODING_SCHEME_DESIGNATOR, "History of present Illness")); doc->getTree().getCurrentContentItem().setStringValue("This 19-year-old black female, nulligravida, was admitted to the hospital on June 14, 1999 with fever of 102\260, left lower quadrant pain, vaginal discharge, constipation, and a tender left adnexal mass. Her past history and family history were unremarkable. Present pain had started 2 to 3 weeks prior (starting on May 30, 1999) and lasted for 6 days. She had taken contraceptive pills in the past, but had stopped because she was not sexually active."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_21", OFFIS_CODING_SCHEME_DESIGNATOR, "Physical Examination")); doc->getTree().getCurrentContentItem().setStringValue("She appeared well-developed and well-nourished, and in mild distress. The only positive physical findings were limited to the abdomen and pelvis. Her abdomen was mildly distended, and it was tender, especially in the lower left quadrant. At pelvic examination her cervix was tender on motion, and the uterus was of normal size, retroverted, and somewhat fixed. There was a tender cystic mass about 4 - 5 cm in the left adnexa. Rectal examination was negative."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_22", OFFIS_CODING_SCHEME_DESIGNATOR, "Admitting Diagnosis")); doc->getTree().getCurrentContentItem().setStringValue("1. Probable pelvic inflammatory disease (PID).\n2. Rule out ectopic pregnancy."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_23", OFFIS_CODING_SCHEME_DESIGNATOR, "Laboratory Data on Admission")); doc->getTree().getCurrentContentItem().setStringValue("Hb 8.8, Hct 26.5, WBC 8,100 with 80 segs and 18 lymphs. Sedimentation rate 100 mm in one hour. Sickle cell prep + (turned out to be a trait). Urinalysis normal. Electrolytes normal. SMA-12 normal. Chest x-ray negative, 2 hour UCG negative."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_24", OFFIS_CODING_SCHEME_DESIGNATOR, "Hospital Course and Treatment")); doc->getTree().getCurrentContentItem().setStringValue("Initially, she was given cephalothin 2 gm IV q6h, and kanamycin 0.5 gm IM b.i.d. Over the next 2 days the patient's condition improved. Her pain decreased, and her temperature came down to normal int he morning and spiked to 101\260 in the evening. Repeat CBC showed Hb 7.8, Hct 23.5. The pregnancy test was negative. On the second night following the admission, her temperature spiked to 104\260. The patient was started on antituberculosis treatment, consisting of isoniazid 300 mg/day, ethambutol 600 mg b.i.d., and rifampin 600 mg daily. She became afebrile on the sixth postoperative day and was discharged on July 15, 1999, in good condition. She will be seen in the office in one week."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_25", OFFIS_CODING_SCHEME_DESIGNATOR, "Surgical Procedures")); doc->getTree().getCurrentContentItem().setStringValue("Biopsy of omentum for frozen section; culture specimens."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_26", OFFIS_CODING_SCHEME_DESIGNATOR, "Discharge Diagnosis")); doc->getTree().getCurrentContentItem().setStringValue("Genital tuberculosis."); } static void generate_06(DSRDocument *doc) { doc->createNewDocument(DSRTypes::DT_BasicTextSR); doc->createNewSeriesInStudy("1.2.276.0.7230010.3.1.4.123456"); doc->setStudyDescription("OFFIS Structured Reporting Samples"); doc->setSeriesDescription("Report with Image Reference"); doc->setPatientName("Russel^William"); doc->setPatientBirthDate("19900808"); doc->setPatientSex("M"); doc->setPatientID("4523"); doc->setReferringPhysicianName("Smythe^John^^Dr."); doc->getTree().addContentItem(DSRTypes::RT_isRoot, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("DT.01", OFFIS_CODING_SCHEME_DESIGNATOR, "Radiology Report")); doc->getTree().addContentItem(DSRTypes::RT_hasObsContext, DSRTypes::VT_PName, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.04", OFFIS_CODING_SCHEME_DESIGNATOR, "Observer Name")); doc->getTree().getCurrentContentItem().setStringValue("Ruprecht^A.^^^Professor & Director"); doc->getTree().addContentItem(DSRTypes::RT_hasObsContext, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.05", OFFIS_CODING_SCHEME_DESIGNATOR, "Observer Organization Name")); doc->getTree().getCurrentContentItem().setStringValue("University of Iowa"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Image); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_27", OFFIS_CODING_SCHEME_DESIGNATOR, "Teeth Present")); doc->getTree().getCurrentContentItem().setImageReference(DSRImageReferenceValue(UID_SecondaryCaptureImageStorage, "1.2.276.0.7230010.3.1.4.123456.1.1")); doc->getCurrentRequestedProcedureEvidence().addItem("1.2.276.0.7230010.3.1.4.123456", "1.2.276.0.7230010.3.1.4.123456.1", UID_SecondaryCaptureImageStorage, "1.2.276.0.7230010.3.1.4.123456.1.1"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_28", OFFIS_CODING_SCHEME_DESIGNATOR, "Orthodontic/Pediatric Assessment")); doc->getTree().getCurrentContentItem().setStringValue("The dental age and chronological age appear to coincide. The occlusal development is within the range of normal, except for the missing teeth noted above."); /* reference to "missing teeth" (SCOORD)? */ doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_29", OFFIS_CODING_SCHEME_DESIGNATOR, "Other")); doc->getTree().getCurrentContentItem().setStringValue("The borders of the portrayed paranasal sinuses appear to be intact; there is no evidence of pathosis in these sinuses.\nThe airway appears patent, but there is evidence of marked adenoidal hyperplasia.\nPart of the first and second cervical vertebrae are depicted. No gross abnormalities are seen. There is a normal width of prevertebral soft tissue.\nThe generalized bone pattern and jaw morphology are within the range of normal."); } static void generate_07(DSRDocument *doc) { doc->createNewDocument(DSRTypes::DT_BasicTextSR); doc->createNewSeriesInStudy("1.2.276.0.7230010.3.1.4.123456"); doc->setStudyDescription("OFFIS Structured Reporting Samples"); doc->setSeriesDescription("Report with Image and Presentation State Reference"); doc->setPatientName("Russel^William"); doc->setPatientBirthDate("19900808"); doc->setPatientSex("M"); doc->setPatientID("4523"); doc->setReferringPhysicianName("Smythe^John^^Dr."); doc->getTree().addContentItem(DSRTypes::RT_isRoot, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("DT.01", OFFIS_CODING_SCHEME_DESIGNATOR, "Radiology Report")); doc->getTree().addContentItem(DSRTypes::RT_hasObsContext, DSRTypes::VT_PName, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.04", OFFIS_CODING_SCHEME_DESIGNATOR, "Observer Name")); doc->getTree().getCurrentContentItem().setStringValue("Ruprecht^A.^^^Professor & Director"); doc->getTree().addContentItem(DSRTypes::RT_hasObsContext, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.05", OFFIS_CODING_SCHEME_DESIGNATOR, "Observer Organization Name")); doc->getTree().getCurrentContentItem().setStringValue("University of Iowa"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Image); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_27", OFFIS_CODING_SCHEME_DESIGNATOR, "Teeth Present")); doc->getTree().getCurrentContentItem().setImageReference(DSRImageReferenceValue(UID_SecondaryCaptureImageStorage, "1.2.276.0.7230010.3.1.4.123456.1.2", UID_GrayscaleSoftcopyPresentationStateStorage, "1.2.276.0.7230010.3.1.4.123456.2.2")); doc->getCurrentRequestedProcedureEvidence().addItem("1.2.276.0.7230010.3.1.4.123456", "1.2.276.0.7230010.3.1.4.123456.1", UID_SecondaryCaptureImageStorage, "1.2.276.0.7230010.3.1.4.123456.1.2"); doc->getCurrentRequestedProcedureEvidence().addItem("1.2.276.0.7230010.3.1.4.123456", "1.2.276.0.7230010.3.1.4.123456.2", UID_GrayscaleSoftcopyPresentationStateStorage, "1.2.276.0.7230010.3.1.4.123456.2.2"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_28", OFFIS_CODING_SCHEME_DESIGNATOR, "Orthodontic/Pediatric Assessment")); doc->getTree().getCurrentContentItem().setStringValue("The dental age and chronological age appear to coincide. The occlusal development is within the range of normal, except for the missing teeth noted above."); /* reference to "missing teeth" (SCOORD)? */ doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_29", OFFIS_CODING_SCHEME_DESIGNATOR, "Other")); doc->getTree().getCurrentContentItem().setStringValue("The borders of the portrayed paranasal sinuses appear to be intact; there is no evidence of pathosis in these sinuses.\nThe airway appears patent, but there is evidence of marked adenoidal hyperplasia.\nPart of the first and second cervical vertebrae are depicted. No gross abnormalities are seen. There is a normal width of prevertebral soft tissue.\nThe generalized bone pattern and jaw morphology are within the range of normal."); } static void generate_08(DSRDocument *doc) { doc->createNewDocument(DSRTypes::DT_BasicTextSR); doc->createNewSeriesInStudy("1.2.276.0.7230010.3.1.4.123456"); doc->setStudyDescription("OFFIS Structured Reporting Samples"); doc->setSeriesDescription("Report with Presentation State Reference"); doc->setPatientName("Russel^William"); doc->setPatientBirthDate("19900808"); doc->setPatientSex("M"); doc->setPatientID("4523"); doc->setReferringPhysicianName("Smythe^John^^Dr."); doc->getTree().addContentItem(DSRTypes::RT_isRoot, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("DT.01", OFFIS_CODING_SCHEME_DESIGNATOR, "Radiology Report")); doc->getTree().addContentItem(DSRTypes::RT_hasObsContext, DSRTypes::VT_PName, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.04", OFFIS_CODING_SCHEME_DESIGNATOR, "Observer Name")); doc->getTree().getCurrentContentItem().setStringValue("Ruprecht^A.^^^Professor & Director"); doc->getTree().addContentItem(DSRTypes::RT_hasObsContext, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IHE.05", OFFIS_CODING_SCHEME_DESIGNATOR, "Observer Organization Name")); doc->getTree().getCurrentContentItem().setStringValue("University of Iowa"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Composite); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_27", OFFIS_CODING_SCHEME_DESIGNATOR, "Teeth Present")); doc->getTree().getCurrentContentItem().setCompositeReference(DSRCompositeReferenceValue(UID_GrayscaleSoftcopyPresentationStateStorage, "1.2.276.0.7230010.3.1.4.123456.2.2")); doc->getCurrentRequestedProcedureEvidence().addItem("1.2.276.0.7230010.3.1.4.123456", "1.2.276.0.7230010.3.1.4.123456.2", UID_GrayscaleSoftcopyPresentationStateStorage, "1.2.276.0.7230010.3.1.4.123456.2.2"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_28", OFFIS_CODING_SCHEME_DESIGNATOR, "Orthodontic/Pediatric Assessment")); doc->getTree().getCurrentContentItem().setStringValue("The dental age and chronological age appear to coincide. The occlusal development is within the range of normal, except for the missing teeth noted above."); /* reference to "missing teeth" (SCOORD)? */ doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("CODE_29", OFFIS_CODING_SCHEME_DESIGNATOR, "Other")); doc->getTree().getCurrentContentItem().setStringValue("The borders of the portrayed paranasal sinuses appear to be intact; there is no evidence of pathosis in these sinuses.\nThe airway appears patent, but there is evidence of marked adenoidal hyperplasia.\nPart of the first and second cervical vertebrae are depicted. No gross abnormalities are seen. There is a normal width of prevertebral soft tissue.\nThe generalized bone pattern and jaw morphology are within the range of normal."); } static void generate_09(DSRDocument *doc) { doc->createNewDocument(DSRTypes::DT_BasicTextSR); doc->createNewSeriesInStudy("2.16.840.1.113662.2.1.53544936282433.12345.336.16650"); doc->setStudyDescription("OFFIS Structured Reporting Samples"); doc->setSeriesDescription("RSNA '95, Picker, CT"); doc->setPatientName("Smith^Harold"); doc->setPatientSex("M"); doc->setPatientID("PIKR750000"); doc->getTree().addContentItem(DSRTypes::RT_isRoot, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("DT.04", OFFIS_CODING_SCHEME_DESIGNATOR, "CT Report")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.02", OFFIS_CODING_SCHEME_DESIGNATOR, "Request")); doc->getTree().getCurrentContentItem().setStringValue("CT: Spiral Angiography of the Thorax"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.01", OFFIS_CODING_SCHEME_DESIGNATOR, "History")); doc->getTree().getCurrentContentItem().setStringValue("46-year-old male presented to the emergency room with parasternal and epigastric pain. A chest X-ray showed widening of the mediastinum. R/O thoracic aneurysm"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.05", OFFIS_CODING_SCHEME_DESIGNATOR, "Finding")); doc->getTree().getCurrentContentItem().setStringValue("There is an aneurysm of the entire thoracic aorta measuring up to 6.2 cm in diameter. Also, there is an intimal flap creating two lumens which is evident on all views extending from the aortic base through the ascending aorta, the aortic arch, and the descending aorta including that portion of the abdomen which is on the films. There are no pulmonary masses identified. The emergency room was immediately notified on this finding and a copy of the films were given to the emergency room so that they could accompany the patient."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.08", OFFIS_CODING_SCHEME_DESIGNATOR, "Conclusion")); doc->getTree().getCurrentContentItem().setStringValue("Aneurysm of thoracic aorta with dissection affecting ascending and descending aorta."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Image); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IR.02", OFFIS_CODING_SCHEME_DESIGNATOR, "Best illustration of finding")); doc->getTree().getCurrentContentItem().setImageReference(DSRImageReferenceValue(UID_CTImageStorage, "2.16.840.1.113662.2.1.12345.19950126.112629.1900")); doc->getCurrentRequestedProcedureEvidence().addItem("2.16.840.1.113662.2.1.53544936282433.12345.336.16650", "2.16.840.1.113662.2.1.53544936282433.12345.336.1665.9990", UID_CTImageStorage, "2.16.840.1.113662.2.1.12345.19950126.112629.1900"); } static void generate_10(DSRDocument *doc) { doc->createNewDocument(DSRTypes::DT_BasicTextSR); doc->createNewSeriesInStudy("2.16.840.1.113662.4.8796818069641.798806497.93296077602350.10"); doc->setStudyDescription("OFFIS Structured Reporting Samples"); doc->setSeriesDescription("RSNA '95, Picker, MR"); doc->setPatientName("Walz^John^R"); doc->setPatientSex("M"); doc->setPatientBirthDate("19781024"); doc->setPatientID("PIKR752962"); doc->getTree().addContentItem(DSRTypes::RT_isRoot, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("DT.05", OFFIS_CODING_SCHEME_DESIGNATOR, "MR Report")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.02", OFFIS_CODING_SCHEME_DESIGNATOR, "Request")); doc->getTree().getCurrentContentItem().setStringValue("MRI: Knee"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.01", OFFIS_CODING_SCHEME_DESIGNATOR, "History")); doc->getTree().getCurrentContentItem().setStringValue("16 year old with right knee pain after an injury playing basketball."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("SH.06", OFFIS_CODING_SCHEME_DESIGNATOR, "Findings")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.05", OFFIS_CODING_SCHEME_DESIGNATOR, "Finding")); doc->getTree().getCurrentContentItem().setStringValue("The bony structures are intact and normally aligned. There is bruising of the medial femoral condyle with some intrasubstance injury to the medial collateral ligament. The lateral collateral ligament in intact. The anterior cruciate ligament is irregular and slightly lax suggesting a partial tear. It does not appear to be completely torn. The posterior cruciate ligament is intact. The suprapatellar tendons are normal."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.05", OFFIS_CODING_SCHEME_DESIGNATOR, "Finding")); doc->getTree().getCurrentContentItem().setStringValue("There is a tear of the posterior limb of the medial meniscus which communicates with the superior articular surface. The lateral meniscus is intact. There is a Baker's cyst and moderate joint effusion."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.05", OFFIS_CODING_SCHEME_DESIGNATOR, "Finding")); doc->getTree().getCurrentContentItem().setStringValue("Internal derangement of the right knee with marked injury and with partial tear of the ACL; there is a tear of the posterior limb of the medial meniscus. There is a Baker's Cyst and joint effusion and intrasubstance injury to the medial collateral ligament."); doc->getTree().goUp(); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Image); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IR.02", OFFIS_CODING_SCHEME_DESIGNATOR, "Best illustration of finding")); doc->getTree().getCurrentContentItem().setImageReference(DSRImageReferenceValue(UID_MRImageStorage, "2.16.840.1.113662.4.8796818069641.806010667.274350678564784069")); doc->getCurrentRequestedProcedureEvidence().addItem("2.16.840.1.113662.4.8796818069641.798806497.93296077602350.10", "2.16.840.1.113662.4.8796818069641.806010667.284225018829304176", UID_MRImageStorage, "2.16.840.1.113662.4.8796818069641.806010667.274350678564784069"); } static void generate_11(DSRDocument *doc) { doc->createNewDocument(DSRTypes::DT_BasicTextSR); doc->createNewSeriesInStudy("1.2.840.113654.2.4.4.3.4.119950730134200"); doc->setStudyDescription("OFFIS Structured Reporting Samples"); doc->setSeriesDescription("RSNA '95, Kodak, CR"); doc->setPatientName("Gamage^Mary"); doc->setPatientSex("F"); doc->setPatientBirthDate("19950210"); doc->setPatientID("KHIS001"); doc->getTree().addContentItem(DSRTypes::RT_isRoot, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("DT.01", OFFIS_CODING_SCHEME_DESIGNATOR, "Radiology Report")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.02", OFFIS_CODING_SCHEME_DESIGNATOR, "Request")); doc->getTree().getCurrentContentItem().setObservationDateTime("199507301342"); doc->getTree().getCurrentContentItem().setStringValue("Portable chest"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.01", OFFIS_CODING_SCHEME_DESIGNATOR, "History")); doc->getTree().getCurrentContentItem().setStringValue("R/O Pneumothorax s/p chest tube insertion"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.05", OFFIS_CODING_SCHEME_DESIGNATOR, "Finding")); doc->getTree().getCurrentContentItem().setStringValue("Over the interval, there has been placement of a left sided chest tube with significant decrease in the left pleural effusion. There is still a persistent pneumothorax although it likely is smaller as well. The right-sided pneumothorax is slightly bigger."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.06", OFFIS_CODING_SCHEME_DESIGNATOR, "Impression")); doc->getTree().getCurrentContentItem().setStringValue("Left chest tube insertion with significant decrease in left pleural effusion and pneumothorax."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Image); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IR.02", OFFIS_CODING_SCHEME_DESIGNATOR, "Best illustration of finding")); doc->getTree().getCurrentContentItem().setImageReference(DSRImageReferenceValue(UID_ComputedRadiographyImageStorage, "1.2.840.113654.2.4.4.3.6.1.119950730.1807310414")); doc->getCurrentRequestedProcedureEvidence().addItem("1.2.840.113654.2.4.4.3.4.119950730134200", "1.2.840.113654.2.4.4.3.5.119950730134200", UID_ComputedRadiographyImageStorage, "1.2.840.113654.2.4.4.3.6.1.119950730.1807310414"); } static void generate_12(DSRDocument *doc) { doc->createNewDocument(DSRTypes::DT_BasicTextSR); doc->createNewSeriesInStudy("1.2.840.113680.3.103.775.2873347909.282313"); doc->setStudyDescription("OFFIS Structured Reporting Samples"); doc->setSeriesDescription("RSNA '95, Acuson, US"); doc->setPatientName("Napper^Margret"); doc->setPatientSex("F"); doc->setPatientBirthDate("19500420"); doc->setPatientID("ACN000001"); doc->getTree().addContentItem(DSRTypes::RT_isRoot, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("DT.03", OFFIS_CODING_SCHEME_DESIGNATOR, "Ultrasound Report")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.02", OFFIS_CODING_SCHEME_DESIGNATOR, "Request")); doc->getTree().getCurrentContentItem().setStringValue("Ultrasound: Right lower quadrant"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.01", OFFIS_CODING_SCHEME_DESIGNATOR, "History")); doc->getTree().getCurrentContentItem().setStringValue("Right lower quadrant pain r/o appendicitis"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("SH.06", OFFIS_CODING_SCHEME_DESIGNATOR, "Findings")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.05", OFFIS_CODING_SCHEME_DESIGNATOR, "Finding")); doc->getTree().getCurrentContentItem().setStringValue("A retrocecal appendix is present, and markedly enlarged to a diameter of 4.5 mm. There is a central area of decreased echogenicity, possibly representing fluid within the appendix, and there is a somewhat eccentrically placed fluid collection near the appendiceal tip which may represent a very early perforation. There is inflammation of peri-appendiceal fat and a marked increase in blood flow seen on Doppler imaging."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.05", OFFIS_CODING_SCHEME_DESIGNATOR, "Finding")); doc->getTree().getCurrentContentItem().setStringValue("The liver, spleen, kidneys, gallbladder, and pancreas are normal."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.05", OFFIS_CODING_SCHEME_DESIGNATOR, "Finding")); doc->getTree().getCurrentContentItem().setStringValue("Thickening of appendix with surrounding inflammation consistent with appendicitis."); doc->getTree().goUp(); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Image); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IR.02", OFFIS_CODING_SCHEME_DESIGNATOR, "Best illustration of finding")); doc->getTree().getCurrentContentItem().setImageReference(DSRImageReferenceValue(UID_RETIRED_UltrasoundImageStorage, "1.2.840.113680.3.103.775.2873347909.282313.2")); doc->getCurrentRequestedProcedureEvidence().addItem("1.2.840.113680.3.103.775.2873347909.282313", "1.2.840.113680.3.103.775.2873347909.282313", UID_RETIRED_UltrasoundImageStorage, "1.2.840.113680.3.103.775.2873347909.282313.2"); } static void generate_13(DSRDocument *doc) { doc->createNewDocument(DSRTypes::DT_BasicTextSR); doc->createNewSeriesInStudy("1.2.840.113674.514.212.200"); doc->setStudyDescription("OFFIS Structured Reporting Samples"); doc->setSeriesDescription("RSNA '95, GE, CT"); doc->setPatientName("Wilkins^Charles"); doc->setPatientSex("M"); doc->setPatientID("GE0514"); doc->getTree().addContentItem(DSRTypes::RT_isRoot, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("DT.04", OFFIS_CODING_SCHEME_DESIGNATOR, "CT Report")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.02", OFFIS_CODING_SCHEME_DESIGNATOR, "Request")); doc->getTree().getCurrentContentItem().setStringValue("CT: Abdomen"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.01", OFFIS_CODING_SCHEME_DESIGNATOR, "History")); doc->getTree().getCurrentContentItem().setStringValue("Patient is a 45 year old male with abnormal liver function test. Ultrasound evaluation demonstrated a 3 cm lesion in the medial aspect of the right lobe of the liver. The question was raised regarding potential hemangioma."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.03", OFFIS_CODING_SCHEME_DESIGNATOR, "Procedure")); doc->getTree().getCurrentContentItem().setStringValue("Serial imaging was obtained in the upper abdomen with the administration of oral and intravenous contrast."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.05", OFFIS_CODING_SCHEME_DESIGNATOR, "Finding")); doc->getTree().getCurrentContentItem().setStringValue("The examination demonstrates a well circumscribed 3 cm lesion present within the medial aspect of the inferior right liver lobe. Initial evaluation demonstrates lack of contrast enhancement. Subsequent imaging (not shown) demonstrated typical contrast enhancement pattern of a benign hemangioma of the liver. The remaining contrast enhancement pattern in the liver is normal. There is normal appearance of the adrenal glands, spleen, kidneys, and pancreas. There is no evidence of liver metastasis. 3 cm nodule present in the inferior medial aspect of right liver lobe. Contrast enhancement pattern consistent with the diagnosis of hemangioma."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Image); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IR.02", OFFIS_CODING_SCHEME_DESIGNATOR, "Best illustration of finding")); doc->getTree().getCurrentContentItem().setImageReference(DSRImageReferenceValue(UID_CTImageStorage, "1.2.840.113674.950809132337081.100")); doc->getCurrentRequestedProcedureEvidence().addItem("1.2.840.113674.514.212.200", "1.2.840.113674.514.212.82.300", UID_CTImageStorage, "1.2.840.113674.950809132337081.100"); } static void generate_14(DSRDocument *doc) { doc->createNewDocument(DSRTypes::DT_BasicTextSR); doc->createNewSeriesInStudy("1.2.840.113674.1140.196.200"); doc->setStudyDescription("OFFIS Structured Reporting Samples"); doc->setSeriesDescription("RSNA '95, GE, MR"); doc->setPatientName("Tyson^Bradley"); doc->setPatientSex("M"); doc->setPatientID("GE1140"); doc->getTree().addContentItem(DSRTypes::RT_isRoot, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("DT.05", OFFIS_CODING_SCHEME_DESIGNATOR, "MR Report")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.02", OFFIS_CODING_SCHEME_DESIGNATOR, "Request")); doc->getTree().getCurrentContentItem().setStringValue("Rule out internal derangement."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.03", OFFIS_CODING_SCHEME_DESIGNATOR, "Procedure")); doc->getTree().getCurrentContentItem().setStringValue("Sagittal T1 and T2 weighted images and fast spin echo and coronal T2 weighted images are acquired."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.05", OFFIS_CODING_SCHEME_DESIGNATOR, "Finding")); doc->getTree().getCurrentContentItem().setStringValue("Within the posterior horn of the medial meniscus there is minimal increase in signal intensity; however, this does not extend to a joint surface and therefore does not represent a tear. The lateral meniscus is normal. The anterior and posterior cruciate ligaments are visualized and are normal. There is a joint diffusion present with a small superior joint plicae. No interarticular loose bodies are identified. There is no focal marrow edema. The collateral ligaments appear normal."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.06", OFFIS_CODING_SCHEME_DESIGNATOR, "Opinion")); doc->getTree().getCurrentContentItem().setStringValue("Joint diffusion with superior joint plicae. Minimal increased signal within the posterior horn of medial meniscus consistent with intermeniscal degeneration. No evidence of meniscal tear."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Image); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IR.02", OFFIS_CODING_SCHEME_DESIGNATOR, "Best illustration of finding")); doc->getTree().getCurrentContentItem().setImageReference(DSRImageReferenceValue(UID_MRImageStorage, "1.2.840.113674.950809133202037.100")); doc->getCurrentRequestedProcedureEvidence().addItem("1.2.840.113674.1140.196.200", "1.2.840.113674.1140.196.180.300", UID_MRImageStorage, "1.2.840.113674.950809133202037.100"); } static void generate_15(DSRDocument *doc) { doc->createNewDocument(DSRTypes::DT_BasicTextSR); doc->createNewSeriesInStudy("1.3.12.2.1107.5.8.1.123456789.199507271758050705910"); doc->setStudyDescription("OFFIS Structured Reporting Samples"); doc->setSeriesDescription("RSNA '95, Siemens, MR"); doc->setPatientName("Neubauer^Anna"); doc->setPatientSex("F"); doc->setPatientBirthDate("19511104"); doc->setPatientID("SMS511104"); doc->getTree().addContentItem(DSRTypes::RT_isRoot, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("DT.05", OFFIS_CODING_SCHEME_DESIGNATOR, "MR Report")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.02", OFFIS_CODING_SCHEME_DESIGNATOR, "Request")); doc->getTree().getCurrentContentItem().setStringValue("MRI: Pelvis"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.05", OFFIS_CODING_SCHEME_DESIGNATOR, "Finding")); doc->getTree().getCurrentContentItem().setStringValue("Visualization of a cervix carcinoma, almost completely permeating into the anterior and posterior labia and extending into the parametrium on the right side. No indication of bladder or rectal involvement. The pelvic wall is free. The tumor does not extend caudally to the vagina. In the vicinity of the left iliac vessel an approximately 1.5 cm round structure can be seen in today's examination, most probably representing the left ovary. If this has been removed because of the ectopic pregnancy, then it is a pathologically enlarged lymph node. There is an ovarian cyst on the right with individual solid contents. Cervical carcinoma permeating into the anterior and posterior labia and extending into the parametrium on the right side."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Image); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IR.02", OFFIS_CODING_SCHEME_DESIGNATOR, "Best illustration of finding")); doc->getTree().getCurrentContentItem().setImageReference(DSRImageReferenceValue(UID_MRImageStorage, "1.3.12.2.1107.5.8.1.123456789.199507271758050707765")); doc->getCurrentRequestedProcedureEvidence().addItem("1.3.12.2.1107.5.8.1.123456789.199507271758050705910", "1.3.12.2.1107.5.8.1.123456789.199507271758050706635", UID_MRImageStorage, "1.3.12.2.1107.5.8.1.123456789.199507271758050707765"); } static void generate_16(DSRDocument *doc) { doc->createNewDocument(DSRTypes::DT_BasicTextSR); doc->createNewSeriesInStudy("1.3.12.2.1107.5.8.1.123456789.199507271807160007134"); doc->setStudyDescription("OFFIS Structured Reporting Samples"); doc->setSeriesDescription("RSNA '95, Siemens, DS"); doc->setPatientName("Schmidt^Anna"); doc->setPatientSex("F"); doc->setPatientBirthDate("19450102"); doc->setPatientID("SMS450102"); doc->getTree().addContentItem(DSRTypes::RT_isRoot, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("DT.01", OFFIS_CODING_SCHEME_DESIGNATOR, "Radiology Report")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.02", OFFIS_CODING_SCHEME_DESIGNATOR, "Request")); doc->getTree().getCurrentContentItem().setStringValue("MRI Angiography: Renal"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.03", OFFIS_CODING_SCHEME_DESIGNATOR, "Procedure")); doc->getTree().getCurrentContentItem().setStringValue("Puncture of the Right Common femoral artery and advancement of 4F pigtail catheter via a 0.035 inch guide wire into the abdominal aorta at the level of the renal arteries. Three DSA studies with injections of 25 ml Ultravist 300."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.05", OFFIS_CODING_SCHEME_DESIGNATOR, "Finding")); doc->getTree().getCurrentContentItem().setStringValue("Right Renal artery: Normal location, single vessel supply, high-grade renal artery stenosis approximately 5 mm distal from the origin of the aorta. Left Renal artery: Single vessel supply, significantly larger organ size, no apparent stenosis."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.07", OFFIS_CODING_SCHEME_DESIGNATOR, "Recommendation")); doc->getTree().getCurrentContentItem().setStringValue("Documented single hemodynamic resultant stenosis of the right renal artery, Angioplasty suggested."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Image); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IR.02", OFFIS_CODING_SCHEME_DESIGNATOR, "Best illustration of finding")); doc->getTree().getCurrentContentItem().setImageReference(DSRImageReferenceValue(UID_SecondaryCaptureImageStorage, "1.3.12.2.1107.5.8.1.123456789.199507271807160009128")); doc->getCurrentRequestedProcedureEvidence().addItem("1.3.12.2.1107.5.8.1.123456789.199507271807160007134", "1.3.12.2.1107.5.8.1.123456789.199507271807160007847", UID_SecondaryCaptureImageStorage, "1.3.12.2.1107.5.8.1.123456789.199507271807160009128"); } static void generate_17(DSRDocument *doc) { doc->createNewDocument(DSRTypes::DT_BasicTextSR); doc->setSpecificCharacterSetType(DSRTypes::CS_Latin1); doc->createNewSeriesInStudy("1.3.12.2.1107.5.8.1.123456789.199507271803030520282"); doc->setStudyDescription("OFFIS Structured Reporting Samples"); doc->setSeriesDescription("RSNA '95, Siemens, DR"); doc->setPatientName("Offenm\374ller^Peter"); doc->setPatientSex("M"); doc->setPatientBirthDate("19280302"); doc->setPatientID("SMS280302"); doc->getTree().addContentItem(DSRTypes::RT_isRoot, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("DT.01", OFFIS_CODING_SCHEME_DESIGNATOR, "Radiology Report")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.02", OFFIS_CODING_SCHEME_DESIGNATOR, "Request")); doc->getTree().getCurrentContentItem().setStringValue("ERCP"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.01", OFFIS_CODING_SCHEME_DESIGNATOR, "History")); doc->getTree().getCurrentContentItem().setStringValue("67 year old male patient, clinical status: two month Jaundice. Query space occupying lesion of the bile duct."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("SH.06", OFFIS_CODING_SCHEME_DESIGNATOR, "Findings")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.05", OFFIS_CODING_SCHEME_DESIGNATOR, "Finding")); doc->getTree().getCurrentContentItem().setStringValue("The pancreaticus major as well as a small accessory duct are well contrasted. Discrete variations in caliber are visible in the region of the pancreatic duct suggestive of chronic inflammatory changes. Variations in caliber are also visible in the multiple small branches. No indications of contrast media depots suggestive of cysts or pseudocysts. No signs of intraluminal concrements."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.05", OFFIS_CODING_SCHEME_DESIGNATOR, "Finding")); doc->getTree().getCurrentContentItem().setStringValue("Well contrasted bile duct and left and right hepatic ducts. Here there are smooth contours without indication of changes in diameter or stenosis. There are no signs of intraluminal concrements. The discrete changes of caliber in the pancreaticus major, accessory ducts and multiple small branches are suggestive of chronic inflammatory changes."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.05", OFFIS_CODING_SCHEME_DESIGNATOR, "Finding")); doc->getTree().getCurrentContentItem().setStringValue("Normal appearance of the bile duct, cystic duct and gall bladder with good drainage of the contrast medium into the duodenum after the endoscopic examination."); doc->getTree().goUp(); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Image); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IR.02", OFFIS_CODING_SCHEME_DESIGNATOR, "Best illustration of finding")); doc->getTree().getCurrentContentItem().setImageReference(DSRImageReferenceValue(UID_SecondaryCaptureImageStorage, "1.3.12.2.1107.5.8.1.123456789.199507271803030521934")); doc->getCurrentRequestedProcedureEvidence().addItem("1.3.12.2.1107.5.8.1.123456789.199507271803030520282", "1.3.12.2.1107.5.8.1.123456789.199507271803030521007", UID_SecondaryCaptureImageStorage, "1.3.12.2.1107.5.8.1.123456789.199507271803030521934"); } static void generate_18(DSRDocument *doc) { doc->createNewDocument(DSRTypes::DT_BasicTextSR); doc->createNewSeriesInStudy("1.2.392.200036.9125.0.198811291108.7"); doc->setStudyDescription("OFFIS Structured Reporting Samples"); doc->setSeriesDescription("RSNA '95, Fuji, CR"); doc->setPatientName("Tanaka^Hanako"); doc->setPatientSex("M"); doc->setPatientBirthDate("19250824"); doc->setPatientID("FUJI00001"); doc->getTree().addContentItem(DSRTypes::RT_isRoot, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("DT.01", OFFIS_CODING_SCHEME_DESIGNATOR, "Radiology Report")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.02", OFFIS_CODING_SCHEME_DESIGNATOR, "Request")); doc->getTree().getCurrentContentItem().setStringValue("Upper GI - double contrast stomach"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.01", OFFIS_CODING_SCHEME_DESIGNATOR, "History")); doc->getTree().getCurrentContentItem().setStringValue("Gastric pain."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.03", OFFIS_CODING_SCHEME_DESIGNATOR, "Procedure")); doc->getTree().getCurrentContentItem().setStringValue("Double contrast technique of the stomach was performed."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("SH.06", OFFIS_CODING_SCHEME_DESIGNATOR, "Findings")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.05", OFFIS_CODING_SCHEME_DESIGNATOR, "Finding")); doc->getTree().getCurrentContentItem().setStringValue("Demonstrated is a gastric wall lesion along the greater curvature of the stomach. Radiating gastric folds are seen extending into the lesion without significant surrounding edema. No additional abnormalities are detected. Given the lack of surrounding edema of this single lesion within the stomach the primary diagnosis of gastric carcinoma remains the main differential diagnosis and must be excluded. Gastric ulcer, although a possibility, is thought to be less likely given the lack of surrounding edema."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.05", OFFIS_CODING_SCHEME_DESIGNATOR, "Finding")); doc->getTree().getCurrentContentItem().setStringValue("Gastric wall mass lesion along greater curvature of the stomach. Pattern compatible with gastric carcinoma."); doc->getTree().goUp(); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Image); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IR.02", OFFIS_CODING_SCHEME_DESIGNATOR, "Best illustration of finding")); doc->getTree().getCurrentContentItem().setImageReference(DSRImageReferenceValue(UID_ComputedRadiographyImageStorage, "1.2.392.200036.9125.0.19950720093509")); doc->getCurrentRequestedProcedureEvidence().addItem("1.2.392.200036.9125.0.198811291108.7", "1.2.392.200036.9125.0.198811291108.7", UID_ComputedRadiographyImageStorage, "1.2.392.200036.9125.0.19950720093509"); } static void generate_19(DSRDocument *doc) { doc->createNewDocument(DSRTypes::DT_BasicTextSR); doc->createNewSeriesInStudy("1.2.840.113663.19950725.1.0"); doc->setStudyDescription("OFFIS Structured Reporting Samples"); doc->setSeriesDescription("RSNA '95, ATL, US"); doc->setPatientName("Smith^Mary"); doc->setPatientSex("F"); doc->setPatientID("ATL000001"); doc->getTree().addContentItem(DSRTypes::RT_isRoot, DSRTypes::VT_Container); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("DT.03", OFFIS_CODING_SCHEME_DESIGNATOR, "Ultrasound Report")); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text, DSRTypes::AM_belowCurrent); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.02", OFFIS_CODING_SCHEME_DESIGNATOR, "Request")); doc->getTree().getCurrentContentItem().setStringValue("Breast ultrasound"); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.01", OFFIS_CODING_SCHEME_DESIGNATOR, "History")); doc->getTree().getCurrentContentItem().setStringValue("Assess palpable mass detected on mammography in the upper outer quadrant of breast in patient with intermittent bloody breast discharge."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Text); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("RE.05", OFFIS_CODING_SCHEME_DESIGNATOR, "Finding")); doc->getTree().getCurrentContentItem().setStringValue("The mass is identified in the upper outer quadrant on the breast corresponding to the size and location of the palpable mass. There are internal echoes indicating that this is a solid mass. Hyperechoic foci are present likely indicating that calcifications are present (confirmed on magnification mammography). In the retroareolar region there was identified an intraductal mass with proximal mild ductal dilatation. This is consistent with an intraductal pappiloma.\n1. Solid breast mass with calcifications.\n2. Intraductal pappiloma."); doc->getTree().addContentItem(DSRTypes::RT_contains, DSRTypes::VT_Image); doc->getTree().getCurrentContentItem().setConceptName(DSRCodedEntryValue("IR.02", OFFIS_CODING_SCHEME_DESIGNATOR, "Best illustration of finding")); doc->getTree().getCurrentContentItem().setImageReference(DSRImageReferenceValue(UID_RETIRED_UltrasoundImageStorage, "1.2.840.113663.19950725083017.0.0.0")); doc->getCurrentRequestedProcedureEvidence().addItem("1.2.840.113663.19950725.1.0", "1.2.840.113663.19950725.1.0.0", UID_RETIRED_UltrasoundImageStorage, "1.2.840.113663.19950725083017.0.0.0"); }
76.029388
1,102
0.752573
[ "solid" ]
b18d13d4186a3fb2b96cf69938d4f3e78d86fa6a
4,814
cc
C++
src/curl_util.cc
MobSlicer152/breadlauncher
e891c8d80d0bd6a34af8f94ff62877f5accb69c7
[ "Apache-2.0" ]
1
2021-09-15T22:46:12.000Z
2021-09-15T22:46:12.000Z
src/curl_util.cc
MobSlicer152/breadlauncher
e891c8d80d0bd6a34af8f94ff62877f5accb69c7
[ "Apache-2.0" ]
null
null
null
src/curl_util.cc
MobSlicer152/breadlauncher
e891c8d80d0bd6a34af8f94ff62877f5accb69c7
[ "Apache-2.0" ]
null
null
null
#include "curl_util.h" static size_t write_resp_to_mem(void *contents, size_t size, size_t nmemb, void *user) { std::vector<char> *out; size_t i; /* Resize the vector and copy the data in */ out = (std::vector<char> *)user; for (i = 0; i < size * nmemb; i++) { out->push_back(((char *)contents)[i]); } return size * nmemb; } std::vector<char> get_file_in_memory(const std::string &url) { CURL *curl; CURLcode res; std::vector<char> buf; /* Initialize the handle */ curl = curl_easy_init(); if (!curl) { BREAD_LOG("Failed to initialize curl operation\n"); return buf; } /* Set up options */ curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_resp_to_mem); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buf); curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0"); /* Do the request */ res = curl_easy_perform(curl); curl_easy_cleanup(curl); if (res != CURLE_OK) { BREAD_LOG("Failed to get file {}: {}\n", url, curl_easy_strerror(res)); buf.clear(); return buf; } /* Return the buffer */ return buf; } fs::file_time_type get_remote_mtime(const std::string &url) { CURL *curl; CURLcode res; std::vector<char> header_raw; std::string header; std::string mtime_str; chrono::time_point<chrono::system_clock> mtime; fs::file_time_type time; /* Initialize the handle */ curl = curl_easy_init(); if (!curl) { BREAD_LOG("Failed to initialize curl operation\n"); return fs::file_time_type(-1s); } /* Set up the request */ curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_NOBODY, 1); /* We only want the header */ curl_easy_setopt(curl, CURLOPT_HEADER, 1); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_resp_to_mem); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &header_raw); curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0"); /* Do the request */ res = curl_easy_perform(curl); curl_easy_cleanup(curl); if (res != CURLE_OK) { BREAD_LOG("Failed to get header: {}\n", curl_easy_strerror(res)); return fs::file_time_type(-1s); } /* Convert the header to a string */ header = std::string(header_raw.data(), header_raw.size()); /* Now that we have the header, we can parse it */ mtime_str = header.substr(header.find("Last-Modified") + 15, header.size() - 1); mtime_str = mtime_str.substr(0, mtime_str.find_first_of("\r\n")); mtime = parse_net_time(mtime_str); time = CONVERT_TIME(mtime, chrono::system_clock, chrono::file_clock); return time; } std::string get_file(const std::string &url, const std::string &target, bool keep_contents, bool verbose) { std::string raw; fs::file_time_type mtime = get_remote_mtime(url); /* Check on the file */ if (!fs::exists(target) || mtime > fs::last_write_time(target)) { if (fs::exists(target)) { BREAD_LOG2(verbose, "File {} has modification time {:} behind server", target, chrono::time_point<chrono::system_clock>(mtime - fs::last_write_time(target))); } else { BREAD_LOG2(verbose, "File {} is not present", target); } BREAD_LOG2(verbose, ", downloading a new copy from {}\n", url); /* Download the file into memory */ std::vector<char> vec = get_file_in_memory(url); if (!vec.size()) { raw.clear(); return raw; } /* Write out the file */ std::ofstream out; out.open(target, std::ios::binary); if (out.fail()) { BREAD_LOG("Failed to open the file {}\n", target); return raw; } out.write(vec.data(), vec.size()); if (out.fail()) { BREAD_LOG("Failed to write {} bytes to {}\n", vec.size(), target); return raw; } out.close(); /* Get a string */ if (keep_contents) raw = std::string(vec.data(), vec.size()); /* Clear the vector */ vec.clear(); /* Say we have the file */ BREAD_LOG2(verbose, "Finished downloading {}\n", target); } else { if (!keep_contents) return raw; /* Open up the existing file */ BREAD_LOG2(verbose, "Using existing file {}\n", target); std::ifstream in; size_t len; in.open(target, std::ios::binary); in >> std::noskipws; if (in.fail()) { BREAD_LOG("Failed to open {}\n", target); raw.clear(); in.close(); return raw; } /* Get the file's size */ in.seekg(0, std::ios::end); len = in.tellg(); in.seekg(0, std::ios::beg); raw.reserve(len); /* Read the file */ raw.insert(raw.begin(), std::istream_iterator<char>(in), std::istream_iterator<char>()); if (raw.size() < len) { BREAD_LOG("Failed to read {} bytes from {}\n", len, target); raw.clear(); in.close(); return raw; } in.close(); } /* Return the file's contents */ return raw; }
27.508571
106
0.64167
[ "vector" ]
b18d93906c994ebc6d786f20ec608f30a9dd008f
4,459
cpp
C++
bullet/Extras/CDTestFramework/BipartiteBoxPruning.cpp
microaaron/ammo.js
325d13a4bf40c1d490d81f3de40c5a80178390bc
[ "Zlib" ]
2,617
2015-01-01T11:22:33.000Z
2022-03-31T16:15:46.000Z
bullet/Extras/CDTestFramework/BipartiteBoxPruning.cpp
microaaron/ammo.js
325d13a4bf40c1d490d81f3de40c5a80178390bc
[ "Zlib" ]
286
2015-01-13T17:22:49.000Z
2022-03-03T15:10:50.000Z
bullet/Extras/CDTestFramework/BipartiteBoxPruning.cpp
microaaron/ammo.js
325d13a4bf40c1d490d81f3de40c5a80178390bc
[ "Zlib" ]
439
2015-01-12T21:50:57.000Z
2022-03-31T20:59:09.000Z
/* CDTestFramework http://codercorner.com Copyright (c) 2007-2008 Pierre Terdiman, pierre@codercorner.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "stdafx.h" #include "BipartiteBoxPruning.h" #include "RenderingHelpers.h" #include "GLFontRenderer.h" BipartiteBoxPruningTest::BipartiteBoxPruningTest() : mBar (null), mNbBoxes (0), mBoxes (null), mBoxPtrs (null), mBoxTime (null), mSpeed (0.0f), mAmplitude (100.0f) { } BipartiteBoxPruningTest::~BipartiteBoxPruningTest() { DELETEARRAY(mBoxTime); DELETEARRAY(mBoxPtrs); DELETEARRAY(mBoxes); } void BipartiteBoxPruningTest::Init() { mNbBoxes = 1024; mBoxes = new AABB[mNbBoxes]; mBoxPtrs = new const AABB*[mNbBoxes]; mBoxTime = new float[mNbBoxes]; for(udword i=0;i<mNbBoxes;i++) { Point Center, Extents; Center.x = (UnitRandomFloat()-0.5f) * 100.0f; Center.y = (UnitRandomFloat()-0.5f) * 10.0f; Center.z = (UnitRandomFloat()-0.5f) * 100.0f; Extents.x = 2.0f + UnitRandomFloat() * 2.0f; Extents.y = 2.0f + UnitRandomFloat() * 2.0f; Extents.z = 2.0f + UnitRandomFloat() * 2.0f; mBoxes[i].SetCenterExtents(Center, Extents); mBoxPtrs[i] = &mBoxes[i]; mBoxTime[i] = 2000.0f*UnitRandomFloat(); } } void BipartiteBoxPruningTest::Release() { DELETEARRAY(mBoxTime); DELETEARRAY(mBoxes); } void BipartiteBoxPruningTest::Select() { // Create a tweak bar { mBar = TwNewBar("BipartiteBoxPruning"); TwAddVarRW(mBar, "Speed", TW_TYPE_FLOAT, &mSpeed, " min=0.0 max=0.01 step=0.00001"); TwAddVarRW(mBar, "Amplitude", TW_TYPE_FLOAT, &mAmplitude, " min=10.0 max=200.0 step=0.1"); } } void BipartiteBoxPruningTest::Deselect() { if(mBar) { TwDeleteBar(mBar); mBar = null; } } bool BipartiteBoxPruningTest::UpdateBoxes() { for(udword i=0;i<mNbBoxes;i++) { mBoxTime[i] += mSpeed; Point Center,Extents; mBoxes[i].GetExtents(Extents); Center.x = cosf(mBoxTime[i]*2.17f)*mAmplitude + sinf(mBoxTime[i])*mAmplitude*0.5f; Center.y = cosf(mBoxTime[i]*1.38f)*mAmplitude + sinf(mBoxTime[i]*mAmplitude); Center.z = sinf(mBoxTime[i]*0.777f)*mAmplitude; mBoxes[i].SetCenterExtents(Center, Extents); } return true; } void BipartiteBoxPruningTest::PerformTest() { UpdateBoxes(); // We pretend that half the boxes belong to first group, and the other half to the second group. udword Nb0 = mNbBoxes/2; udword Nb1 = mNbBoxes - Nb0; mPairs.ResetPairs(); mProfiler.Start(); BipartiteBoxPruning(Nb0, mBoxPtrs, Nb1, mBoxPtrs+Nb0, mPairs, Axes(AXES_XZY)); mProfiler.End(); mProfiler.Accum(); // printf("%d pairs colliding\r ", mPairs.GetNbPairs()); bool* Flags = (bool*)_alloca(sizeof(bool)*mNbBoxes); ZeroMemory(Flags, sizeof(bool)*mNbBoxes); const Pair* P = mPairs.GetPairs(); for(udword i=0;i<mPairs.GetNbPairs();i++) { // A colliding pair is (i,j) where 0 <= i < Nb0 and 0 <= j < Nb1 Flags[P[i].id0] = true; Flags[P[i].id1+Nb0] = true; } // Render boxes OBB CurrentBox; CurrentBox.mRot.Identity(); for(udword i=0;i<mNbBoxes;i++) { if(Flags[i]) glColor3f(1.0f, 0.0f, 0.0f); else { if(i<Nb0) glColor3f(0.0f, 1.0f, 0.0f); else glColor3f(0.0f, 0.0f, 1.0f); } mBoxes[i].GetCenter(CurrentBox.mCenter); mBoxes[i].GetExtents(CurrentBox.mExtents); DrawOBB(CurrentBox); } char Buffer[4096]; sprintf(Buffer, "BipartiteBoxPruning - %5.1f us (%d cycles) - %d pairs\n", mProfiler.mMsTime, mProfiler.mCycles, mPairs.GetNbPairs()); GLFontRenderer::print(10.0f, 10.0f, 0.02f, Buffer); } void BipartiteBoxPruningTest::KeyboardCallback(unsigned char key, int x, int y) { } void BipartiteBoxPruningTest::MouseCallback(int button, int state, int x, int y) { } void BipartiteBoxPruningTest::MotionCallback(int x, int y) { }
26.700599
243
0.712267
[ "render" ]
b18e99e81dd1d9243cef47b420b60b5340bdf248
2,000
hpp
C++
Sources/Game/Textures.hpp
jpez1432/Project-Monster
a1f74934f4210cfd9ab4dac4875039b33c90d672
[ "Unlicense" ]
1
2021-12-20T09:18:25.000Z
2021-12-20T09:18:25.000Z
Sources/Game/Textures.hpp
jpez1432/Project-Monster
a1f74934f4210cfd9ab4dac4875039b33c90d672
[ "Unlicense" ]
null
null
null
Sources/Game/Textures.hpp
jpez1432/Project-Monster
a1f74934f4210cfd9ab4dac4875039b33c90d672
[ "Unlicense" ]
1
2021-12-15T14:44:34.000Z
2021-12-15T14:44:34.000Z
#ifndef TEXTURES_HPP #define TEXTURES_HPP #define GLEW_STATIC #include <GL/Glew.h> #include <GLFW/Glfw3.h> #include <Soil2/Soil2.h> #include "Pods.hpp" namespace Game { class CTexture { private: bool ActPalette; GLuint GLTexture; std::string Filename; public: CTexture(void); ~CTexture(void); bool LoadRaw(CPodPool &PodPool, std::string Filename, unsigned int *DefaultPalette = NULL); bool LoadBlank(GLuint Dimensions, GLuint Color, GLenum Format); bool LoadImage(std::string Filename, std::string AlternateDir = ""); bool LoadMemory(GLubyte *Data, GLuint Dimensions, GLuint Bpp, GLenum Format); void Destroy(void); void SetParameters(GLint MinFilter, GLint MagFilter, GLint WrapS, GLint WrapT); void Bind(GLuint TextureUnit); void Unbind(void) { glBindTexture(GL_TEXTURE_2D, 0); } GLuint &GetTexture(void) { return GLTexture; } std::string &GetFilename(void) { return Filename; } bool &GetPalette(void) { return ActPalette; } }; class CTexturePool { private: unsigned int DefaultPalette[256]; glm::vec2 TextureCoords[2][2][4][4]; std::vector<CTexture> Textures; public: CTexturePool(void); ~CTexturePool(void); bool Create(CPodPool &PodPool, std::vector<std::string> &Filenames); void Bind(int Index) { Textures[Index].Bind(0); } const GLuint GetTexture(int Index) { return Textures[Index].GetTexture(); } int NumTextures(void) { return Textures.size(); } const std::string &GetFilename(int Index) { return Textures[Index].GetFilename(); } const bool &GetPalette(int Index) { return Textures[Index].GetPalette(); } glm::vec2 &GetTextureCoords(int MirrorX, int MirrorY, int Rotation, int Corner); }; } #endif
18.518519
96
0.6105
[ "vector" ]
b1972fa151759a38b45bf8d7175dee3725e1deea
5,099
cpp
C++
IGC/VectorCompiler/lib/GenXCodeGen/GenXRematerialization.cpp
isabella232/intel-graphics-compiler
1e6e958a2988022e5c67313cbafac855bff2cab0
[ "MIT" ]
null
null
null
IGC/VectorCompiler/lib/GenXCodeGen/GenXRematerialization.cpp
isabella232/intel-graphics-compiler
1e6e958a2988022e5c67313cbafac855bff2cab0
[ "MIT" ]
1
2021-02-24T08:39:15.000Z
2021-02-24T08:39:15.000Z
IGC/VectorCompiler/lib/GenXCodeGen/GenXRematerialization.cpp
isabella232/intel-graphics-compiler
1e6e958a2988022e5c67313cbafac855bff2cab0
[ "MIT" ]
null
null
null
/*===================== begin_copyright_notice ================================== Copyright (c) 2017 Intel Corporation Permission 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE 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. ======================= end_copyright_notice ==================================*/ // /// GenXRematerialization /// --------------------- /// /// This pass performs rematerialization to reduce register pressure. /// //===----------------------------------------------------------------------===// #include "GenX.h" #include "GenXBaling.h" #include "GenXLiveness.h" #include "GenXModule.h" #include "GenXNumbering.h" #include "GenXPressureTracker.h" #include "GenXUtil.h" #include "llvm/Pass.h" #include "Probe/Assertion.h" using namespace llvm; using namespace genx; namespace { class GenXRematerialization : public FunctionGroupPass { GenXBaling *Baling = nullptr; GenXLiveness *Liveness = nullptr; GenXNumbering *Numbering = nullptr; bool Modified = false; public: static char ID; explicit GenXRematerialization() : FunctionGroupPass(ID) {} StringRef getPassName() const override { return "GenX rematerialization pass"; } void getAnalysisUsage(AnalysisUsage &AU) const override; bool runOnFunctionGroup(FunctionGroup &FG) override; private: void remat(Function *F, PressureTracker &RP); }; } // namespace namespace llvm { void initializeGenXRematerializationPass(PassRegistry &); } char GenXRematerialization::ID = 0; INITIALIZE_PASS_BEGIN(GenXRematerialization, "GenXRematerialization", "GenXRematerialization", false, false) INITIALIZE_PASS_DEPENDENCY(GenXGroupBaling) INITIALIZE_PASS_DEPENDENCY(GenXLiveness) INITIALIZE_PASS_DEPENDENCY(GenXNumbering) INITIALIZE_PASS_END(GenXRematerialization, "GenXRematerialization", "GenXRematerialization", false, false) FunctionGroupPass *llvm::createGenXRematerializationPass() { initializeGenXRematerializationPass(*PassRegistry::getPassRegistry()); return new GenXRematerialization; } void GenXRematerialization::getAnalysisUsage(AnalysisUsage &AU) const { FunctionGroupPass::getAnalysisUsage(AU); AU.addRequired<GenXGroupBaling>(); AU.addRequired<GenXLiveness>(); AU.addRequired<GenXNumbering>(); AU.addPreserved<GenXModule>(); AU.addPreserved<FunctionGroupAnalysis>(); AU.setPreservesCFG(); } bool GenXRematerialization::runOnFunctionGroup(FunctionGroup &FG) { if (skipOptWithLargeBlock(FG)) return false; Modified = false; Baling = &getAnalysis<GenXGroupBaling>(); Liveness = &getAnalysis<GenXLiveness>(); Numbering = &getAnalysis<GenXNumbering>(); PressureTracker RP(FG, Liveness); for (auto fgi = FG.begin(), fge = FG.end(); fgi != fge; ++fgi) remat(*fgi, RP); return Modified; } void GenXRematerialization::remat(Function *F, PressureTracker &RP) { // Collect rematerialization candidates. std::vector<Use *> Candidates; for (auto &BB : F->getBasicBlockList()) { for (auto &Inst : BB.getInstList()) { // (1) upward cast if (auto CI = dyn_cast<CastInst>(&Inst)) { if (CI->getOpcode() != Instruction::UIToFP && CI->getOpcode() != Instruction::SIToFP) continue; if (!CI->getType()->isVectorTy()) continue; if (CI->getSrcTy()->getScalarSizeInBits() >= CI->getDestTy()->getScalarSizeInBits()) continue; if (Inst.isUsedOutsideOfBlock(&BB) || Inst.getNumUses() <= 2) continue; LiveRange *LR = Liveness->getLiveRangeOrNull(CI); if (!LR || LR->value_size() != 1) continue; IGC_ASSERT(*LR->value_begin() == CI); unsigned B = Numbering->getNumber(CI); for (auto &U : CI->uses()) { auto UI = U.getUser(); unsigned E = Numbering->getNumber(UI); if (E > B && RP.intersectWithRedRegion(B, E)) Candidates.push_back(&U); } } } } // Do rematerialization. for (auto U : Candidates) { Instruction *Inst = cast<Instruction>(U->get()); Instruction *UI = cast<Instruction>(U->getUser()); Instruction *Clone = Inst->clone(); Clone->insertBefore(UI); U->set(Clone); Modified = true; } }
34.687075
108
0.686997
[ "vector" ]
b1a0935114c9b3de1c2e2c777e1487393cf72a2e
3,882
hpp
C++
Source/3rdParty/PlayRho/Dynamics/Contacts/ContactSolver.hpp
Karshilov/Dorothy-SSR
cce19ed2218d76f941977370f6b3894e2f87236a
[ "MIT" ]
1
2021-07-19T11:30:54.000Z
2021-07-19T11:30:54.000Z
Source/3rdParty/PlayRho/Dynamics/Contacts/ContactSolver.hpp
Jilliana8397/Dorothy-SSR
5ad647909c5e20cb7ebde9a1a054cdb944969dcb
[ "MIT" ]
null
null
null
Source/3rdParty/PlayRho/Dynamics/Contacts/ContactSolver.hpp
Jilliana8397/Dorothy-SSR
5ad647909c5e20cb7ebde9a1a054cdb944969dcb
[ "MIT" ]
null
null
null
/* * Original work Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * Modified work Copyright (c) 2020 Louis Langholtz https://github.com/louis-langholtz/PlayRho * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef PLAYRHO_DYNAMICS_CONTACTS_CONTACTSOLVER_HPP #define PLAYRHO_DYNAMICS_CONTACTS_CONTACTSOLVER_HPP #include "PlayRho/Common/Math.hpp" #include <vector> namespace playrho { struct StepConf; struct ConstraintSolverConf; namespace d2 { class VelocityConstraint; class PositionConstraint; class BodyConstraint; /// @brief Solution for position constraint. struct PositionSolution { Position pos_a; ///< Position A. Position pos_b; ///< Position B. Length min_separation; ///< Min separation. }; /// @brief Addition operator. inline PositionSolution operator+ (PositionSolution lhs, PositionSolution rhs) { return PositionSolution{ lhs.pos_a + rhs.pos_a, lhs.pos_b + rhs.pos_b, lhs.min_separation + rhs.min_separation }; } /// @brief Subtraction operator. inline PositionSolution operator- (PositionSolution lhs, PositionSolution rhs) { return PositionSolution{ lhs.pos_a - rhs.pos_a, lhs.pos_b - rhs.pos_b, lhs.min_separation - rhs.min_separation }; } } // namespace d2 namespace GaussSeidel { /// Solves the velocity constraint. /// /// @details This updates the tangent and normal impulses of the velocity constraint /// points of the given velocity constraint and updates the given velocities. /// /// @warning Behavior is undefined unless the velocity constraint point count is 1 or 2. /// @note Linear velocity is only changed if the inverse mass of either body is non-zero. /// @note Angular velocity is only changed if the inverse rotational inertia of either /// body is non-zero. /// @note Inlining this function may yield a 10% speed boost in the /// <code>World.TilesComesToRest</code> unit test. /// /// @pre The velocity constraint must have a valid normal, a valid tangent, /// valid point relative positions, and valid velocity biases. /// Momentum SolveVelocityConstraint(d2::VelocityConstraint& vc, std::vector<d2::BodyConstraint>& bodies); /// Solves the given position constraint. /// @details /// This pushes apart the two given positions for every point in the contact position constraint /// and returns the minimum separation value from the position solver manifold for each point. /// @see http://allenchou.net/2013/12/game-physics-resolution-contact-constraints/ /// @return Minimum separation distance of the position constraint's manifold points /// (prior to "solving"). d2::PositionSolution SolvePositionConstraint(const d2::PositionConstraint& pc, bool moveA, bool moveB, const std::vector<d2::BodyConstraint>& bodies, const ConstraintSolverConf& conf); } // namespace GaussSidel } // namespace playrho #endif // PLAYRHO_DYNAMICS_CONTACTS_CONTACTSOLVER_HPP
36.622642
96
0.72102
[ "vector" ]
b1a332ac84fa0deeb33d26ac4d7eafca6f15b883
5,722
cpp
C++
library/src/cgfw/gl/vertex_array.cpp
IthronMinya/ProceduralFacadesInStrokeBasedRendering
6bdb2921c5489f44c7db8bce147f1d211608c58f
[ "MIT" ]
null
null
null
library/src/cgfw/gl/vertex_array.cpp
IthronMinya/ProceduralFacadesInStrokeBasedRendering
6bdb2921c5489f44c7db8bce147f1d211608c58f
[ "MIT" ]
null
null
null
library/src/cgfw/gl/vertex_array.cpp
IthronMinya/ProceduralFacadesInStrokeBasedRendering
6bdb2921c5489f44c7db8bce147f1d211608c58f
[ "MIT" ]
null
null
null
#include <cgfw/gl/vertex_array.h> #include <cgfw/debug.h> #include <cgfw/gl/context_utils.h> namespace cgfw { namespace gl { size_t vertext_attrib_type_size(GLenum type) { switch (type) { case GL_BYTE: return sizeof(GLbyte); case GL_UNSIGNED_BYTE: return sizeof(GLubyte); case GL_SHORT: return sizeof(GLshort); case GL_UNSIGNED_SHORT: return sizeof(GLushort); case GL_INT: return sizeof(GLint); case GL_UNSIGNED_INT: return sizeof(GLuint); // case GL_HALF_FLOAT: // return sizeof(GLhalf​​); case GL_FLOAT: return sizeof(GLfloat); case GL_DOUBLE: return sizeof(GLdouble); case GL_FIXED: return sizeof(GLfixed); default: throw std::runtime_error("Unknown type"); // case GL_INT_2_10_10_10_REV: // case GL_UNSIGNED_INT_2_10_10_10_REV: // case GL_UNSIGNED_INT_10F_11F_11F_REV: } } void VertexArray::attribPointer(const std::string& attribName, const std::shared_ptr<BufferBase>& buffer, GLint size, GLenum type, GLboolean normalized, GLsizei stride, std::size_t offset) { m_enabledAttribs[attribName] = { buffer, attribName, 0, 0, size, type, normalized, stride, reinterpret_cast<void*>(offset), 0}; } void VertexArray::attribDivisor(const std::string& attribName, unsigned int divisor) { if (m_enabledAttribs.find(attribName) != m_enabledAttribs.end()) { m_enabledAttribs[attribName].divisor = divisor; } } void VertexArray::prepare(GLuint progId) { /* TODO check if signature of programm equals already used one if not then throw a warning about that the settign had to be changed weak signature should like like that: key 0 value: GL_FLOAT:3 key 1 value: GL_FLOAT:3 strong signartue should look like: map: key 0 value: GL_FLOAT:3:Position key 1 value: GL_FLOAT:3:Normal if the program requires more attribs then presented then an error should be shown otherwise we might show a warning */ auto contextInstance = get_current_context_instance(); auto iter = m_instances.find(contextInstance.get()); VertexArray::Instance* instance; if (iter == m_instances.end()) { instance = new VertexArray::Instance(this); m_instances.insert(std::make_pair(contextInstance.get(), instance)); } else { instance = iter->second; } if (instance->m_id == 0) { glGenVertexArrays(1, &instance->m_id); } glBindVertexArray(instance->m_id); for (auto& attribPair : m_enabledAttribs) { auto& attrib = attribPair.second; /*debug_log(MessageType::kWarning, "detect if buffer id changed and if buffer can be used");*/ glBindBuffer(GL_ARRAY_BUFFER, attrib.buffer->id()); GLint idx = glGetAttribLocation(progId, attrib.name.c_str()); if (idx != -1) { glEnableVertexAttribArray(idx); glVertexAttribDivisor(idx, attrib.divisor); if (attrib.type == GL_BYTE || attrib.type == GL_UNSIGNED_BYTE || attrib.type == GL_SHORT || attrib.type == GL_UNSIGNED_SHORT || attrib.type == GL_INT || attrib.type == GL_UNSIGNED_INT) { glVertexAttribIPointer(idx, attrib.size, attrib.type, attrib.stride, attrib.offset); } else { glVertexAttribPointer(idx, attrib.size, attrib.type, attrib.normalized, attrib.stride, attrib.offset); } } } } void VertexArray::lock() { lock(ResourceLocation::HOST); } void VertexArray::lock(ResourceLocation location) { Resource::lock(); if (lockCount() == 1) { m_lockedForUsageOn = location; } else { if (location != m_lockedForUsageOn) { throw std::runtime_error( "resource already locked on another location."); } } for (auto& pair : m_enabledAttribs) { pair.second.buffer->lock(location); } } void VertexArray::unlock() { for (auto& pair : m_enabledAttribs) { pair.second.buffer->unlock(); } Resource::unlock(); } bool VertexArray::readyToDraw() { bool ready = true; for (auto& pair : m_enabledAttribs) { if (pair.second.buffer->bufferSize() == 0) { ready = false; break; } } return ready; } void VertexArray::bind() { // if (m_dirty || m_id == 0) { // std::cout << "need to recreate vbo " << m_id << std::endl; //} auto contextInstance = get_current_context_instance(); auto iter = m_instances.find(contextInstance.get()); if (iter != m_instances.end()) { glBindVertexArray(iter->second->m_id); } } void VertexArray::unbind() { glBindVertexArray(0); } void delete_vertex_arrays(const std::vector<GLuint>& ids) { glDeleteVertexArrays(static_cast<GLsizei>(ids.size()), ids.data()); } VertexArray::Instance::Instance(VertexArray* va) : m_contextInstance(get_current_context_instance()), m_vertexArray(va), m_id(0), m_dirty(false) {} VertexArray::Instance::~Instance() { if (m_id != 0) { m_contextInstance->deleteResource(typeid(VertexArray::Instance), m_id, delete_vertex_arrays); } } } // namespace gl } // namespace cgfw
30.115789
78
0.592101
[ "vector" ]
b1a50e0a2d113d73901ce55d1c74ee6929cbe659
55,177
cpp
C++
src/serialgraphics.cpp
omniacreator/omniacreator
962b28dfeaffaae27a03dff9053aba4106a244d7
[ "MIT" ]
8
2015-03-04T18:46:07.000Z
2022-01-13T11:50:53.000Z
src/serialgraphics.cpp
omniacreator/omniacreator
962b28dfeaffaae27a03dff9053aba4106a244d7
[ "MIT" ]
null
null
null
src/serialgraphics.cpp
omniacreator/omniacreator
962b28dfeaffaae27a03dff9053aba4106a244d7
[ "MIT" ]
null
null
null
/***************************************************************************//** * @file * Serial Graphics * * @version @n 1.0 * @date @n 12/06/2013 * * @author @n Kwabena W. Agyeman * @copyright @n (c) 2013 Kwabena W. Agyeman * @n All rights reserved - Please see the end of the file for the terms of use * * @par Update History: * @n v1.0 - Original release - 12/06/2013 *******************************************************************************/ #include "serialgraphics.h" #include "ui_serialgraphics.h" SerialGraphics::SerialGraphics(const QString &title, QSettings *settings, QWidget *parent) : SerialWindow(title, settings, parent), m_ui(new Ui::SerialGraphics) { m_ui->setupUi(this); m_ui->statusBar->hide(); m_resize = true; m_widget = new QWidget; m_scene = new QGraphicsScene(-1000000000, -1000000000, +2000000001, +2000000001, this); m_widget->installEventFilter(this); m_scene->installEventFilter(this); m_ui->graphicsView->installEventFilter(this); m_ui->graphicsView->setViewport(m_widget); m_ui->graphicsView->setScene(m_scene); m_coordinateSystem = CS_CARTESIAN; m_angleUnits = AU_DEGREES; m_pen = QPen(QColor(000, 000, 255), 0.0); m_brush = QColor(200, 200, 255); m_rotation = 0.0; m_scale = 1.0; m_rasterWidth = 640; m_rasterHeight = 480; m_rasterSaveViewport = false; m_vectorWidth = 640; m_vectorHeight = 480; m_vectorSaveViewport = false; m_vectorTitle = windowTitle(); m_vectorDescription = tr("By: ") + qgetenv(BY_NAME); connect(m_ui->actionZoom_In, SIGNAL(triggered()), this, SLOT(zoomIn())); connect(m_ui->actionZoom_Out, SIGNAL(triggered()), this, SLOT(zoomOut())); connect(m_ui->actionZoom_Fit, SIGNAL(triggered()), this, SLOT(zoomFit())); connect(m_ui->actionSave_Raster_Image, SIGNAL(triggered()), this, SLOT(saveRasterImage())); connect(m_ui->actionSave_Vector_Image, SIGNAL(triggered()), this, SLOT(saveVectorImage())); connect(m_ui->actionImport_State, SIGNAL(triggered()), this, SLOT(importState())); connect(m_ui->actionExport_State, SIGNAL(triggered()), this, SLOT(exportState())); connect(m_ui->actionClose_Window, SIGNAL(triggered()), this, SLOT(close())); connect(m_ui->actionGeneral_Help, SIGNAL(triggered()), this, SLOT(generalHelp())); connect(m_ui->actionGraphics_Help, SIGNAL(triggered()), this, SLOT(graphicsHelp())); restoreState(); } SerialGraphics::~SerialGraphics() { delete m_ui; } bool SerialGraphics::importExportEnabled() const { return true; } QString SerialGraphics::keyGroup() const { return SERIAL_GRAPHICS_KEY_GROUP; } QString SerialGraphics::keyState() const { return SERIAL_GRAPHICS_KEY_STATE; } QString SerialGraphics::keyGeometry() const { return SERIAL_GRAPHICS_KEY_GEOMETRY; } void SerialGraphics::setBackgroundColor(QRgb rgba) { m_ui->graphicsView->setBackgroundBrush(QColor::fromRgba(rgba)); } QRgb SerialGraphics::getBackgroundColor() const { return m_ui->graphicsView->backgroundBrush().color().rgba(); } bool SerialGraphics::setCoordinateSystem(CoordinateSystem coordinateSystem) { bool ok = notInvalid(__FUNCTION__, "coordinateSystem", coordinateSystem, CS_CARTESIAN, CS_POLAR); if(ok) { m_coordinateSystem = coordinateSystem; } return ok; } CoordinateSystem SerialGraphics::getCoordinateSystem() const { return m_coordinateSystem; } bool SerialGraphics::setAngleUnits(AngleUnits angleUnits) { bool ok = notInvalid(__FUNCTION__, "angleUnits", angleUnits, AU_DEGREES, AU_RADIANS); if(ok) { m_angleUnits = angleUnits; } return ok; } AngleUnits SerialGraphics::getAngleUnits() const { return m_angleUnits; } void SerialGraphics::setLineColor(QRgb rgba) { m_pen.setColor(QColor::fromRgba(rgba)); } QRgb SerialGraphics::getLineColor() const { return m_pen.color().rgba(); } bool SerialGraphics::setLineStyle(Qt::PenStyle lineStyle) { bool ok = notInvalid(__FUNCTION__, "lineStyle", lineStyle, Qt::NoPen, Qt::DashDotDotLine); if(ok) { m_pen.setStyle(lineStyle); } return ok; } Qt::PenStyle SerialGraphics::getLineStyle() const { return m_pen.style(); } void SerialGraphics::setFillColor(QRgb rgba) { m_brush.setColor(QColor::fromRgba(rgba)); } QRgb SerialGraphics::getFillColor() const { return m_brush.color().rgba(); } bool SerialGraphics::setFillStyle(Qt::BrushStyle fillStyle) { int min0 = Qt::NoBrush; int max0 = Qt::SolidPattern; int min1 = Qt::HorPattern; int max1 = Qt::DiagCrossPattern; bool ok = (((min0 <= fillStyle) && (fillStyle <= max0)) || ((min1 <= fillStyle) && (fillStyle <= max1))); if(ok) { m_brush.setStyle(fillStyle); } else { emit errorMessage(QString(metaObject()->className()) + "::" + __FUNCTION__ + "[" + windowTitle() + "] -> " + tr("Argument (%L1 == %L2) is out of the valid range between " "[%L3 : %L4] + [%L5 : %L6]").arg("fillStyle").arg(fillStyle). arg(min0).arg(max0).arg(min1).arg(max1)); } return ok; } Qt::BrushStyle SerialGraphics::getFillStyle() const { return m_brush.style(); } bool SerialGraphics::setRotation(double rotation) { bool ok = notInfinite(__FUNCTION__, "rotation", rotation); if(ok) { if(m_angleUnits == AU_DEGREES) { m_rotation = rotation; } else { m_rotation = qRadiansToDegrees(rotation); } } return ok; } double SerialGraphics::getRotation() const { if(m_angleUnits == AU_DEGREES) { return m_rotation; } else { return qDegreesToRadians(m_rotation); } } bool SerialGraphics::setScale(double scale) { bool ok = notInfinite(__FUNCTION__, "scale", scale); if(ok) { m_scale = scale; } return ok; } double SerialGraphics::getScale() const { return m_scale; } bool SerialGraphics::drawText(double x, double y, const QString &text) { bool ok = (notInfinite(__FUNCTION__, "x", x) && notInfinite(__FUNCTION__, "y", y) && (!text.isEmpty())); if(ok) { QVariantList list; QJsonObject object = toJson("drawText", list << x << y << text); if(m_coordinateSystem == CS_POLAR) { if(m_angleUnits == AU_DEGREES) { x = qDegreesToRadians(x); } x = y * qCos(x); y = y * qSin(x); } /////////////////////////////////////////////////////////////////////// QGraphicsSimpleTextItem *item = m_scene->addSimpleText(text); item->setPos(QPointF(x, y)); item->setPen(m_pen); item->setBrush(m_brush); /////////////////////////////////////////////////////////////////////// item->setRotation(m_rotation); item->setScale(m_scale); item->setData(0, object); if(m_resize) { m_ui->graphicsView->fitInView(m_scene->itemsBoundingRect(), Qt::KeepAspectRatio); } } return ok; } bool SerialGraphics::drawLine(double x1, double y1, double x2, double y2) { bool ok = (notInfinite(__FUNCTION__, "x1", x1) && notInfinite(__FUNCTION__, "y1", y1) && notInfinite(__FUNCTION__, "x2", x2) && notInfinite(__FUNCTION__, "y2", y2)); if(ok) { QVariantList list; QJsonObject object = toJson("drawLine", list << x1 << y1 << x2 << y2); if(m_coordinateSystem == CS_POLAR) { if(m_angleUnits == AU_DEGREES) { x1 = qDegreesToRadians(x1); x2 = qDegreesToRadians(x2); } x1 = y1 * qCos(x1); y1 = y1 * qSin(x1); x2 = y2 * qCos(x2); y2 = y2 * qSin(x2); } /////////////////////////////////////////////////////////////////////// QLineF line(QPointF(x1, y1), QPointF(x2, y2)); QGraphicsLineItem *item = m_scene->addLine(line, m_pen); /////////////////////////////////////////////////////////////////////// item->setRotation(m_rotation); item->setScale(m_scale); item->setData(0, object); if(m_resize) { m_ui->graphicsView->fitInView(m_scene->itemsBoundingRect(), Qt::KeepAspectRatio); } } return ok; } bool SerialGraphics::drawQuadraticLine(double x1, double y1, double x2, double y2, double x3, double y3) { bool ok = (notInfinite(__FUNCTION__, "x1", x1) && notInfinite(__FUNCTION__, "y1", y1) && notInfinite(__FUNCTION__, "x2", x2) && notInfinite(__FUNCTION__, "y2", y2) && notInfinite(__FUNCTION__, "x3", x3) && notInfinite(__FUNCTION__, "y3", y3)); if(ok) { QVariantList list; QJsonObject object = toJson("drawQuadraticLine", list << x1 << y1 << x2 << y2 << x3 << y3); if(m_coordinateSystem == CS_POLAR) { if(m_angleUnits == AU_DEGREES) { x1 = qDegreesToRadians(x1); x2 = qDegreesToRadians(x2); x3 = qDegreesToRadians(x3); } x1 = y1 * qCos(x1); y1 = y1 * qSin(x1); x2 = y2 * qCos(x2); y2 = y2 * qSin(x2); x3 = y3 * qCos(x3); y3 = y3 * qSin(x3); } /////////////////////////////////////////////////////////////////////// QPainterPath path(QPointF(x1, y1)); path.quadTo(QPointF(x2, y2), QPointF(x3, y3)); QGraphicsPathItem *item = m_scene->addPath(path, m_pen); /////////////////////////////////////////////////////////////////////// item->setRotation(m_rotation); item->setScale(m_scale); item->setData(0, object); if(m_resize) { m_ui->graphicsView->fitInView(m_scene->itemsBoundingRect(), Qt::KeepAspectRatio); } } return ok; } bool SerialGraphics::drawCubicLine(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) { bool ok = (notInfinite(__FUNCTION__, "x1", x1) && notInfinite(__FUNCTION__, "y1", y1) && notInfinite(__FUNCTION__, "x2", x2) && notInfinite(__FUNCTION__, "y2", y2) && notInfinite(__FUNCTION__, "x3", x3) && notInfinite(__FUNCTION__, "y3", y3) && notInfinite(__FUNCTION__, "x4", x4) && notInfinite(__FUNCTION__, "y4", y4)); if(ok) { QVariantList list; QJsonObject object = toJson("drawCubicLine", list << x1 << y1 << x2 << y2 << x3 << y3 << x4 << y4); if(m_coordinateSystem == CS_POLAR) { if(m_angleUnits == AU_DEGREES) { x1 = qDegreesToRadians(x1); x2 = qDegreesToRadians(x2); x3 = qDegreesToRadians(x3); x4 = qDegreesToRadians(x4); } x1 = y1 * qCos(x1); y1 = y1 * qSin(x1); x2 = y2 * qCos(x2); y2 = y2 * qSin(x2); x3 = y3 * qCos(x3); y3 = y3 * qSin(x3); x4 = y4 * qCos(x4); y4 = y4 * qSin(x4); } /////////////////////////////////////////////////////////////////////// QPainterPath path(QPointF(x1, y1)); path.cubicTo(QPointF(x2, y2), QPointF(x3, y3), QPointF(x4, y4)); QGraphicsPathItem *item = m_scene->addPath(path, m_pen); /////////////////////////////////////////////////////////////////////// item->setRotation(m_rotation); item->setScale(m_scale); item->setData(0, object); if(m_resize) { m_ui->graphicsView->fitInView(m_scene->itemsBoundingRect(), Qt::KeepAspectRatio); } } return ok; } bool SerialGraphics::drawArc(double x1, double y1, double x2, double y2, double startAngle, double endAngle) { bool ok = (notInfinite(__FUNCTION__, "x1", x1) && notInfinite(__FUNCTION__, "y1", y1) && notInfinite(__FUNCTION__, "x2", x2) && notInfinite(__FUNCTION__, "y2", y2) && notInfinite(__FUNCTION__, "startAngle", startAngle) && notInfinite(__FUNCTION__, "endAngle", endAngle)); if(ok) { QVariantList list; QJsonObject object = toJson("drawArc", list << x1 << y1 << x2 << y2 << startAngle << endAngle); if(m_coordinateSystem == CS_POLAR) { if(m_angleUnits == AU_DEGREES) { x1 = qDegreesToRadians(x1); x2 = qDegreesToRadians(x2); } x1 = y1 * qCos(x1); y1 = y1 * qSin(x1); x2 = y2 * qCos(x2); y2 = y2 * qSin(x2); } /////////////////////////////////////////////////////////////////////// if(m_angleUnits == AU_RADIANS) { startAngle = qRadiansToDegrees(startAngle); endAngle = qRadiansToDegrees(endAngle); } QRectF rect(QPointF(x1, y1), QPointF(x2, y2)); QPainterPath path; path.arcMoveTo(rect, startAngle); path.arcTo(rect, startAngle, endAngle-startAngle); QGraphicsPathItem *item = m_scene->addPath(path, m_pen); /////////////////////////////////////////////////////////////////////// item->setRotation(m_rotation); item->setScale(m_scale); item->setData(0, object); if(m_resize) { m_ui->graphicsView->fitInView(m_scene->itemsBoundingRect(), Qt::KeepAspectRatio); } } return ok; } bool SerialGraphics::drawChord(double x1, double y1, double x2, double y2, double startAngle, double endAngle) { bool ok = (notInfinite(__FUNCTION__, "x1", x1) && notInfinite(__FUNCTION__, "y1", y1) && notInfinite(__FUNCTION__, "x2", x2) && notInfinite(__FUNCTION__, "y2", y2) && notInfinite(__FUNCTION__, "startAngle", startAngle) && notInfinite(__FUNCTION__, "endAngle", endAngle)); if(ok) { QVariantList list; QJsonObject object = toJson("drawChord", list << x1 << y1 << x2 << y2 << startAngle << endAngle); if(m_coordinateSystem == CS_POLAR) { if(m_angleUnits == AU_DEGREES) { x1 = qDegreesToRadians(x1); x2 = qDegreesToRadians(x2); } x1 = y1 * qCos(x1); y1 = y1 * qSin(x1); x2 = y2 * qCos(x2); y2 = y2 * qSin(x2); } /////////////////////////////////////////////////////////////////////// if(m_angleUnits == AU_RADIANS) { startAngle = qRadiansToDegrees(startAngle); endAngle = qRadiansToDegrees(endAngle); } QRectF rect(QPointF(x1, y1), QPointF(x2, y2)); QPainterPath path; path.arcMoveTo(rect, startAngle); path.arcTo(rect, startAngle, endAngle-startAngle); path.closeSubpath(); QGraphicsPathItem *item = m_scene->addPath(path, m_pen, m_brush); /////////////////////////////////////////////////////////////////////// item->setRotation(m_rotation); item->setScale(m_scale); item->setData(0, object); if(m_resize) { m_ui->graphicsView->fitInView(m_scene->itemsBoundingRect(), Qt::KeepAspectRatio); } } return ok; } bool SerialGraphics::drawTriangle(double x1, double y1, double x2, double y2, double x3, double y3) { bool ok = (notInfinite(__FUNCTION__, "x1", x1) && notInfinite(__FUNCTION__, "y1", y1) && notInfinite(__FUNCTION__, "x2", x2) && notInfinite(__FUNCTION__, "y2", y2) && notInfinite(__FUNCTION__, "x3", x3) && notInfinite(__FUNCTION__, "y3", y3)); if(ok) { QVariantList list; QJsonObject object = toJson("drawTriangle", list << x1 << y1 << x2 << y2 << x3 << y3); if(m_coordinateSystem == CS_POLAR) { if(m_angleUnits == AU_DEGREES) { x1 = qDegreesToRadians(x1); x2 = qDegreesToRadians(x2); x3 = qDegreesToRadians(x3); } x1 = y1 * qCos(x1); y1 = y1 * qSin(x1); x2 = y2 * qCos(x2); y2 = y2 * qSin(x2); x3 = y3 * qCos(x3); y3 = y3 * qSin(x3); } /////////////////////////////////////////////////////////////////////// QPolygonF poly; poly.append(QPointF(x1, y1)); poly.append(QPointF(x2, y2)); poly.append(QPointF(x3, y3)); QGraphicsPolygonItem *item = m_scene->addPolygon(poly, m_pen, m_brush); /////////////////////////////////////////////////////////////////////// item->setRotation(m_rotation); item->setScale(m_scale); item->setData(0, object); if(m_resize) { m_ui->graphicsView->fitInView(m_scene->itemsBoundingRect(), Qt::KeepAspectRatio); } } return ok; } bool SerialGraphics::drawQuadrilateral(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) { bool ok = (notInfinite(__FUNCTION__, "x1", x1) && notInfinite(__FUNCTION__, "y1", y1) && notInfinite(__FUNCTION__, "x2", x2) && notInfinite(__FUNCTION__, "y2", y2) && notInfinite(__FUNCTION__, "x3", x3) && notInfinite(__FUNCTION__, "y3", y3) && notInfinite(__FUNCTION__, "x4", x4) && notInfinite(__FUNCTION__, "y4", y4)); if(ok) { QVariantList list; QJsonObject object = toJson("drawQuadrilateral", list << x1 << y1 << x2 << y2 << x3 << y3 << x4 << y4); if(m_coordinateSystem == CS_POLAR) { if(m_angleUnits == AU_DEGREES) { x1 = qDegreesToRadians(x1); x2 = qDegreesToRadians(x2); x3 = qDegreesToRadians(x3); x4 = qDegreesToRadians(x4); } x1 = y1 * qCos(x1); y1 = y1 * qSin(x1); x2 = y2 * qCos(x2); y2 = y2 * qSin(x2); x3 = y3 * qCos(x3); y3 = y3 * qSin(x3); x4 = y4 * qCos(x4); y4 = y4 * qSin(x4); } /////////////////////////////////////////////////////////////////////// QPolygonF poly; poly.append(QPointF(x1, y1)); poly.append(QPointF(x2, y2)); poly.append(QPointF(x3, y3)); poly.append(QPointF(x4, y4)); QGraphicsPolygonItem *item = m_scene->addPolygon(poly, m_pen, m_brush); /////////////////////////////////////////////////////////////////////// item->setRotation(m_rotation); item->setScale(m_scale); item->setData(0, object); if(m_resize) { m_ui->graphicsView->fitInView(m_scene->itemsBoundingRect(), Qt::KeepAspectRatio); } } return ok; } bool SerialGraphics::drawRectangle(double x1, double y1, double x2, double y2, double xRadius, double yRadius) { bool ok = (notInfinite(__FUNCTION__, "x1", x1) && notInfinite(__FUNCTION__, "y1", y1) && notInfinite(__FUNCTION__, "x2", x2) && notInfinite(__FUNCTION__, "y2", y2) && notInvalid(__FUNCTION__, "xRadius", xRadius, 0.0, 100.0) && notInvalid(__FUNCTION__, "yRadius", yRadius, 0.0, 100.0)); if(ok) { QVariantList list; QJsonObject object = toJson("drawRectangle", list << x1 << y1 << x2 << y2 << xRadius << yRadius); if(m_coordinateSystem == CS_POLAR) { if(m_angleUnits == AU_DEGREES) { x1 = qDegreesToRadians(x1); x2 = qDegreesToRadians(x2); } x1 = y1 * qCos(x1); y1 = y1 * qSin(x1); x2 = y2 * qCos(x2); y2 = y2 * qSin(x2); } /////////////////////////////////////////////////////////////////////// QRectF rect(QRectF(QPointF(x1,y1), QPointF(x2,y2))); QPainterPath path; path.addRoundedRect(rect, xRadius, yRadius, Qt::RelativeSize); QGraphicsPathItem *item = m_scene->addPath(path, m_pen, m_brush); /////////////////////////////////////////////////////////////////////// item->setRotation(m_rotation); item->setScale(m_scale); item->setData(0, object); if(m_resize) { m_ui->graphicsView->fitInView(m_scene->itemsBoundingRect(), Qt::KeepAspectRatio); } } return ok; } bool SerialGraphics::drawEllipse(double x1, double y1, double x2, double y2, double startAngle, double endAngle) { bool ok = (notInfinite(__FUNCTION__, "x1", x1) && notInfinite(__FUNCTION__, "y1", y1) && notInfinite(__FUNCTION__, "x2", x2) && notInfinite(__FUNCTION__, "y2", y2) && notInfinite(__FUNCTION__, "startAngle", startAngle) && notInfinite(__FUNCTION__, "endAngle", endAngle)); if(ok) { QVariantList list; QJsonObject object = toJson("drawEllipse", list << x1 << y1 << x2 << y2 << startAngle << endAngle); if(m_coordinateSystem == CS_POLAR) { if(m_angleUnits == AU_DEGREES) { x1 = qDegreesToRadians(x1); x2 = qDegreesToRadians(x2); } x1 = y1 * qCos(x1); y1 = y1 * qSin(x1); x2 = y2 * qCos(x2); y2 = y2 * qSin(x2); } /////////////////////////////////////////////////////////////////////// QRectF rect(QPointF(x1,y1), QPointF(x2,y2)); QGraphicsEllipseItem *item = m_scene->addEllipse(rect, m_pen, m_brush); if(m_angleUnits == AU_RADIANS) { startAngle = qRadiansToDegrees(startAngle); endAngle = qRadiansToDegrees(endAngle); } item->setStartAngle(startAngle); item->setSpanAngle(endAngle - startAngle); /////////////////////////////////////////////////////////////////////// item->setRotation(m_rotation); item->setScale(m_scale); item->setData(0, object); if(m_resize) { m_ui->graphicsView->fitInView(m_scene->itemsBoundingRect(), Qt::KeepAspectRatio); } } return ok; } bool SerialGraphics::clearAll(double x1, double y1, double x2, double y2) { bool ok = (notInfinite(__FUNCTION__, "x1", x1) && notInfinite(__FUNCTION__, "y1", y1) && notInfinite(__FUNCTION__, "x2", x2) && notInfinite(__FUNCTION__, "y2", y2)); if(ok) { if(m_coordinateSystem == CS_POLAR) { if(m_angleUnits == AU_DEGREES) { x1 = qDegreesToRadians(x1); x2 = qDegreesToRadians(x2); } x1 = y1 * qCos(x1); y1 = y1 * qSin(x1); x2 = y2 * qCos(x2); y2 = y2 * qSin(x2); } QRectF rect(QPointF(x1, y1), QPointF(x2, y2)); foreach(QGraphicsItem *item, m_scene->items(rect)) { m_scene->removeItem(item); delete item; } } return ok; } void SerialGraphics::clearAll() { m_scene->clear(); } void SerialGraphics::zoomIn() { QRect geometry = m_ui->graphicsView->geometry(); QPointF localPos(geometry.width()/2.0, geometry.height()/2.0); QPointF globalPos(geometry.x()+localPos.x(), geometry.y()+localPos.y()); QWheelEvent wheelEvent(localPos, globalPos, QPoint(0, +1), QPoint(0, +120), +120, Qt::Vertical, Qt::NoButton, Qt::NoModifier); QApplication::sendEvent(m_ui->graphicsView, &wheelEvent); } void SerialGraphics::zoomOut() { QRect geometry = m_ui->graphicsView->geometry(); QPointF localPos(geometry.width()/2.0, geometry.height()/2.0); QPointF globalPos(geometry.x()+localPos.x(), geometry.y()+localPos.y()); QWheelEvent wheelEvent(localPos, globalPos, QPoint(0, -1), QPoint(0, -120), -120, Qt::Vertical, Qt::NoButton, Qt::NoModifier); QApplication::sendEvent(m_ui->graphicsView, &wheelEvent); } void SerialGraphics::zoomFit() { m_ui->graphicsView->fitInView(m_scene->itemsBoundingRect(), Qt::KeepAspectRatio); m_resize = true; } void SerialGraphics::saveRasterImage() { QSettings settings(settingsFileName(), settingsFormat()); settings.beginGroup(keyGroup()); settings.beginGroup(windowTitle()); QString saveFile = settings.value(SERIAL_GRAPHICS_KEY_SAVE_R_FILE, QDir::homePath()).toString(); QString fileName = QFileDialog::getSaveFileName(this, tr("Save Image"), saveFile, tr("Image Files (*.bmp *.jpg *.jpeg *.png)")); if(!fileName.isEmpty()) { if(fileName.endsWith(".bmp", Qt::CaseInsensitive) || fileName.endsWith(".jpg", Qt::CaseInsensitive) || fileName.endsWith(".jpeg", Qt::CaseInsensitive) || fileName.endsWith(".png", Qt::CaseInsensitive)) { UtilRasterDialog dialog(tr("Save Options"), this); dialog.setWidth(m_rasterWidth); dialog.setHeight(m_rasterHeight); dialog.setSaveCurrentView(m_rasterSaveViewport); if(dialog.exec() == QDialog::Accepted) { QPixmap pixmap(dialog.getWidth(), dialog.getHeight()); pixmap.fill(m_ui->graphicsView->backgroundBrush().color()); QPainter painter; if(!painter.begin(&pixmap)) { QMessageBox::critical(this, tr("Save Image Error"), tr("Painting initialization failed")); return; } if(dialog.getSaveCurrentView()) { m_ui->graphicsView->render(&painter, QRectF(), QRect(), Qt::IgnoreAspectRatio); } else { QRectF rect = m_scene->itemsBoundingRect(); QRectF newRect(QPointF(), rect.size() * 1.2); newRect.moveCenter(rect.center()); m_scene->render(&painter, QRectF(), newRect, Qt::IgnoreAspectRatio); } if((!painter.end()) || (!pixmap.save(fileName))) { QMessageBox::critical(this, tr("Save Image Error"), tr("Painting finalization failed")); return; } QFileInfo fileInfo(fileName); settings.setValue(SERIAL_GRAPHICS_KEY_SAVE_R_FILE, fileInfo.canonicalFilePath()); m_rasterWidth = dialog.getWidth(); m_rasterHeight = dialog.getHeight(); m_rasterSaveViewport = dialog.getSaveCurrentView(); } } else { QMessageBox::critical(this, tr("Save Image Error"), tr("Unsupported file type")); } } } void SerialGraphics::saveVectorImage() { QSettings settings(settingsFileName(), settingsFormat()); settings.beginGroup(keyGroup()); settings.beginGroup(windowTitle()); QString saveFile = settings.value(SERIAL_GRAPHICS_KEY_SAVE_V_FILE, QDir::homePath()).toString(); QString fileName = QFileDialog::getSaveFileName(this, tr("Save Image"), saveFile, tr("Image Files (*.svg *.pdf)")); if(!fileName.isEmpty()) { if(fileName.endsWith(".svg", Qt::CaseInsensitive)) { UtilVectorDialog dialog(tr("Save Options"), this); dialog.setWidth(m_vectorWidth); dialog.setHeight(m_vectorHeight); dialog.setSaveCurrentView(m_vectorSaveViewport); dialog.setFileTitle(m_vectorTitle); dialog.setFileDescription(m_vectorDescription); if(dialog.exec() == QDialog::Accepted) { QSvgGenerator generator; generator.setFileName(fileName); generator.setSize(QSize(dialog.getWidth(), dialog.getHeight())); generator.setViewBox(QRect(0, 0, dialog.getWidth() - 1, dialog.getHeight() - 1)); // QT-BUG: QSvgGenerator should escape strings for me... generator.setTitle(QString(dialog.getFileTitle()). replace("&", "&amp;").replace("\"", "&apos;"). replace("'", "&quot;").replace("<", "&lt;"). replace(">", "&gt;")); generator.setDescription(QString(dialog.getFileDescription()). replace("&", "&amp;").replace("\"", "&apos;"). replace("'", "&quot;").replace("<", "&lt;"). replace(">", "&gt;")); QPainter painter; if(!painter.begin(&generator)) { QMessageBox::critical(this, tr("Save Image Error"), tr("Painting initialization failed")); return; } // TODO: RENDER IS BUGGED!!! if(dialog.getSaveCurrentView()) { m_ui->graphicsView->render(&painter, QRectF(), QRect(), Qt::IgnoreAspectRatio); } else { QRectF rect = m_scene->itemsBoundingRect(); QRectF newRect(QPointF(), rect.size() * 1.2); newRect.moveCenter(rect.center()); m_scene->render(&painter, QRectF(), newRect, Qt::IgnoreAspectRatio); } if(!painter.end()) { QMessageBox::critical(this, tr("Save Image Error"), tr("Painting finalization failed")); return; } QFileInfo fileInfo(fileName); settings.setValue(SERIAL_GRAPHICS_KEY_SAVE_V_FILE, fileInfo.canonicalFilePath()); m_vectorWidth = dialog.getWidth(); m_vectorHeight = dialog.getHeight(); m_vectorSaveViewport = dialog.getSaveCurrentView(); m_vectorTitle = dialog.getFileTitle(); m_vectorDescription = dialog.getFileDescription(); } } else if(fileName.endsWith(".pdf", Qt::CaseInsensitive)) { QPrinter printer; printer.setOutputFormat(QPrinter::NativeFormat); QPageSetupDialog dialog(&printer, this); if(dialog.exec() == QDialog::Accepted) { QPageLayout layout = printer.pageLayout(); printer.setOutputFormat(QPrinter::PdfFormat); printer.setOutputFileName(fileName); printer.setPageLayout(layout); UtilVectorDialogWOWH dialog(tr("Save Options"), this); dialog.setSaveCurrentView(m_vectorSaveViewport); dialog.setFileTitle(m_vectorTitle); dialog.setFileDescription(m_vectorDescription); if(dialog.exec() == QDialog::Accepted) { printer.setCreator(dialog.getFileDescription()); printer.setDocName(dialog.getFileTitle()); QPainter painter; if(!painter.begin(&printer)) { QMessageBox::critical(this, tr("Save Image Error"), tr("Painting initialization failed")); return; } if(dialog.getSaveCurrentView()) { m_ui->graphicsView->render(&painter, QRectF(), QRect(), Qt::IgnoreAspectRatio); } else { QRectF rect = m_scene->itemsBoundingRect(); QRectF newRect(QPointF(), rect.size() * 1.2); newRect.moveCenter(rect.center()); m_scene->render(&painter, QRectF(), newRect, Qt::IgnoreAspectRatio); } if(!painter.end()) { QMessageBox::critical(this, tr("Save Image Error"), tr("Painting finalization failed")); return; } QFileInfo fileInfo(fileName); settings.setValue(SERIAL_GRAPHICS_KEY_SAVE_V_FILE, fileInfo.canonicalFilePath()); m_vectorSaveViewport = dialog.getSaveCurrentView(); m_vectorTitle = dialog.getFileTitle(); m_vectorDescription = dialog.getFileDescription(); } } } else { QMessageBox::critical(this, tr("Save Image Error"), tr("Unsupported file type")); } } } void SerialGraphics::importState(const QString &fileName) { QSettings settings(settingsFileName(), settingsFormat()); settings.beginGroup(keyGroup()); settings.beginGroup(windowTitle()); QString openFile = settings.value(SERIAL_GRAPHICS_KEY_IMPORT_FILE, QDir::homePath()).toString(); QString temp = fileName.isEmpty() ? QFileDialog::getOpenFileName(this, tr("Import State"), openFile, tr("JSON Files (*.json)")) : fileName; if(!temp.isEmpty()) { QFile file(temp); if(file.open(QIODevice::ReadOnly | QIODevice::Text)) { QJsonParseError parseError; QJsonDocument json = QJsonDocument::fromJson(file.readAll(), &parseError); if(parseError.error == QJsonParseError::NoError) { QJsonObject object = json.object(); if(object.value("type").toString() == "graphics") { clearAll(); setWindowTitle(object.value("title").toString()); QString background = object.value("background").toString(); if(QColor::isValidColor(background)) { setBackgroundColor(QColor(background).rgba()); } QJsonArray items = object.value("items").toArray(); for(int i = 0, j = items.size(); i < j; i++) { QJsonObject item = items.at(i).toObject(); setCoordinateSystem(static_cast<CoordinateSystem>(item. value("coorinateSystem").toInt(m_coordinateSystem))); setAngleUnits(static_cast<AngleUnits>(item. value("angleUnits").toInt(m_angleUnits))); QString lineColor = item.value("lineColor").toString(); if(QColor::isValidColor(lineColor)) { setLineColor(QColor(lineColor).rgba()); } setLineStyle(static_cast<Qt::PenStyle>(item. value("lineStyle").toInt(m_pen.style()))); QString fillColor = item.value("fillColor").toString(); if(QColor::isValidColor(fillColor)) { setFillColor(QColor(fillColor).rgba()); } setFillStyle(static_cast<Qt::BrushStyle>(item. value("fillStyle").toInt(m_brush.style()))); setRotation(item. value("rotation").toDouble(m_rotation)); setScale(item. value("scale").toDouble(m_scale)); QString function = item.value("function").toString(); QVariantList args = item.value("args").toArray().toVariantList(); if((function == "drawText") && (args.size() == 3)) { double x = args.takeFirst().toDouble(); double y = args.takeFirst().toDouble(); QString text = args.takeFirst().toString(); drawText(x, y, text); } else if((function == "drawLine") && (args.size() == 4)) { double x1 = args.takeFirst().toDouble(); double y1 = args.takeFirst().toDouble(); double x2 = args.takeFirst().toDouble(); double y2 = args.takeFirst().toDouble(); drawLine(x1, y1, x2, y2); } else if((function == "drawQuadraticLine") && (args.size() == 6)) { double x1 = args.takeFirst().toDouble(); double y1 = args.takeFirst().toDouble(); double x2 = args.takeFirst().toDouble(); double y2 = args.takeFirst().toDouble(); double x3 = args.takeFirst().toDouble(); double y3 = args.takeFirst().toDouble(); drawQuadraticLine(x1, y1, x2, y2, x3, y3); } else if((function == "drawCubicLine") && (args.size() == 8)) { double x1 = args.takeFirst().toDouble(); double y1 = args.takeFirst().toDouble(); double x2 = args.takeFirst().toDouble(); double y2 = args.takeFirst().toDouble(); double x3 = args.takeFirst().toDouble(); double y3 = args.takeFirst().toDouble(); double x4 = args.takeFirst().toDouble(); double y4 = args.takeFirst().toDouble(); drawCubicLine(x1, y1, x2, y2, x3, y3, x4, y4); } else if((function == "drawArc") && (args.size() == 6)) { double x1 = args.takeFirst().toDouble(); double y1 = args.takeFirst().toDouble(); double x2 = args.takeFirst().toDouble(); double y2 = args.takeFirst().toDouble(); double startAngle = args.takeFirst().toDouble(); double endAngle = args.takeFirst().toDouble(); drawArc(x1, y1, x2, y2, startAngle, endAngle); } else if((function == "drawChord") && (args.size() == 6)) { double x1 = args.takeFirst().toDouble(); double y1 = args.takeFirst().toDouble(); double x2 = args.takeFirst().toDouble(); double y2 = args.takeFirst().toDouble(); double startAngle = args.takeFirst().toDouble(); double endAngle = args.takeFirst().toDouble(); drawChord(x1, y1, x2, y2, startAngle, endAngle); } else if((function == "drawTriangle") && (args.size() == 6)) { double x1 = args.takeFirst().toDouble(); double y1 = args.takeFirst().toDouble(); double x2 = args.takeFirst().toDouble(); double y2 = args.takeFirst().toDouble(); double x3 = args.takeFirst().toDouble(); double y3 = args.takeFirst().toDouble(); drawTriangle(x1, y1, x2, y2, x3, y3); } else if((function == "drawQuadrilateral") && (args.size() == 8)) { double x1 = args.takeFirst().toDouble(); double y1 = args.takeFirst().toDouble(); double x2 = args.takeFirst().toDouble(); double y2 = args.takeFirst().toDouble(); double x3 = args.takeFirst().toDouble(); double y3 = args.takeFirst().toDouble(); double x4 = args.takeFirst().toDouble(); double y4 = args.takeFirst().toDouble(); drawQuadrilateral(x1, y1, x2, y2, x3, y3, x4, y4); } else if((function == "drawRectangle") && (args.size() == 6)) { double x1 = args.takeFirst().toDouble(); double y1 = args.takeFirst().toDouble(); double x2 = args.takeFirst().toDouble(); double y2 = args.takeFirst().toDouble(); double xRadius = args.takeFirst().toDouble(); double yRadius = args.takeFirst().toDouble(); drawRectangle(x1, y1, x2, y2, xRadius, yRadius); } else if((function == "drawEllipse") && (args.size() == 6)) { double x1 = args.takeFirst().toDouble(); double y1 = args.takeFirst().toDouble(); double x2 = args.takeFirst().toDouble(); double y2 = args.takeFirst().toDouble(); double startAngle = args.takeFirst().toDouble(); double endAngle = args.takeFirst().toDouble(); drawEllipse(x1, y1, x2, y2, startAngle, endAngle); } } QFileInfo fileInfo(temp); settings.setValue(SERIAL_GRAPHICS_KEY_IMPORT_FILE, fileInfo.canonicalFilePath()); } else { QMessageBox::critical(this, tr("Import State Error"), tr("Incompatible JSON file")); } } else { QMessageBox::critical(this, tr("Import State Error"), parseError.errorString()); } } else { QMessageBox::critical(this, tr("Import State Error"), file.errorString()); } } } void SerialGraphics::exportState(const QString &fileName) { QSettings settings(settingsFileName(), settingsFormat()); settings.beginGroup(keyGroup()); settings.beginGroup(windowTitle()); QString saveFile = settings.value(SERIAL_GRAPHICS_KEY_EXPORT_FILE, QDir::homePath()).toString(); QString temp = fileName.isEmpty() ? QFileDialog::getSaveFileName(this, tr("Export State"), saveFile, tr("JSON Files (*.json)")) : fileName; if(!temp.isEmpty()) { QFile file(temp); if(file.open(QIODevice::WriteOnly | QIODevice::Text)) { QJsonObject object; object.insert("type", QString("graphics")); object.insert("title", windowTitle()); object.insert("background", QColor::fromRgba(getBackgroundColor()).name(QColor::HexArgb)); QJsonArray items; foreach(QGraphicsItem *item, m_scene->items(Qt::AscendingOrder)) { items.append(item->data(0).toJsonObject()); } object.insert("items", items); QByteArray json = QJsonDocument(object).toJson(); if(file.write(json) == json.size()) { QFileInfo fileInfo(temp); settings.setValue(SERIAL_GRAPHICS_KEY_EXPORT_FILE, fileInfo.canonicalFilePath()); } else { QMessageBox::critical(this, tr("Export State Error"), file.errorString()); } } else { QMessageBox::critical(this, tr("Export State Error"), file.errorString()); } } } void SerialGraphics::generalHelp() { if(!QDesktopServices::openUrl(QUrl("http://" PROJECT_DOMAIN_NAME_STR "/" "help/general/"))) { QMessageBox::critical(this, tr("Open General Help Error"), tr("Unable to open the URL to the General Help page")); } } void SerialGraphics::graphicsHelp() { if(!QDesktopServices::openUrl(QUrl("http://" PROJECT_DOMAIN_NAME_STR "/" "help/widgets/graphics/"))) { QMessageBox::critical(this, tr("Open Graphics Help Error"), tr("Unable to open the URL to the Graphics Help page")); } } bool SerialGraphics::eventFilter(QObject *object, QEvent *event) { if((object == m_ui->graphicsView) || (object == m_widget) || (object == m_scene)) { if(event->type() == QEvent::MouseButtonDblClick) { m_ui->graphicsView->fitInView(m_scene->itemsBoundingRect(), Qt::KeepAspectRatio); m_resize = true; } if(event->type() == QEvent::MouseButtonPress) { QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event); if(mouseEvent->buttons() & Qt::LeftButton) { m_resize = false; } } if(event->type() == QEvent::Wheel) { QWheelEvent *wheelEvent = static_cast<QWheelEvent *>(event); double pixelDelta = qPow(1.2, wheelEvent->pixelDelta().y()/001.0); double angleDelta = qPow(1.2, wheelEvent->angleDelta().y()/120.0); Q_UNUSED(pixelDelta); m_ui->graphicsView->scale(angleDelta, angleDelta); m_resize = false; } // if(event->type() == QEvent::GraphicsSceneWheel) // { // QGraphicsSceneWheelEvent *wheelEvent = // static_cast<QGraphicsSceneWheelEvent *>(event); // double delta = qPow(1.2, wheelEvent->delta() / 120.0); // m_ui->graphicsView->scale(delta, delta); // m_resize = false; // return true; // } if(event->type() == QEvent::ToolTip) { QHelpEvent *helpEvent = static_cast<QHelpEvent *>(event); if(m_ui->graphicsView->itemAt(helpEvent->pos())) { QPointF pos = m_ui->graphicsView->mapToScene(helpEvent->pos()); QToolTip::showText(helpEvent->globalPos(), tr("<table>" "<tr>" "<th colspan=\"2\">Point</th>" "</tr>" "<tr>" "<td>X:</td>" "<td>%L1</td>" "</tr>" "<tr>" "<td>Y:</td>" "<td>%L2</td>" "</tr>" "</table>"). arg(pos.x()). arg(pos.y())); } else { QToolTip::hideText(); event->ignore(); } return true; } if(event->type() == QEvent::WhatsThis) { QHelpEvent *helpEvent = static_cast<QHelpEvent *>(event); if(m_ui->graphicsView->itemAt(helpEvent->pos())) { QPointF pos = m_ui->graphicsView->mapToScene(helpEvent->pos()); QWhatsThis::showText(helpEvent->globalPos(), tr("<table>" "<tr>" "<th colspan=\"2\">Point</th>" "</tr>" "<tr>" "<td>X:</td>" "<td>%L1</td>" "</tr>" "<tr>" "<td>Y:</td>" "<td>%L2</td>" "</tr>" "</table>"). arg(pos.x()). arg(pos.y())); } else { QWhatsThis::hideText(); event->ignore(); } return true; } } return SerialWindow::eventFilter(object, event); } void SerialGraphics::resizeEvent(QResizeEvent *event) { if(m_resize) { m_ui->graphicsView->fitInView(m_scene->itemsBoundingRect(), Qt::KeepAspectRatio); } SerialWindow::resizeEvent(event); } QJsonObject SerialGraphics::toJson(const QString &function, const QVariantList &args) { QJsonObject object; object.insert("coorinateSystem", m_coordinateSystem); object.insert("angleUnits", m_angleUnits); object.insert("lineColor", m_pen.color().name(QColor::HexArgb)); object.insert("lineStyle", m_pen.style()); object.insert("fillColor", m_brush.color().name(QColor::HexArgb)); object.insert("fillStyle", m_brush.style()); object.insert("rotation", m_rotation); object.insert("scale", m_scale); object.insert("function", function); object.insert("args", QJsonArray::fromVariantList(args)); return object; } bool SerialGraphics::notInfinite(const QString &FName, const QString &VName, double value) { bool ok = qIsFinite(value); if(!ok) { emit errorMessage(QString(metaObject()->className()) + "::" + FName + "[" + windowTitle() + "] -> " + tr("Argument (%L1 == %L2) is an infinite value"). arg(VName).arg(value)); } return ok; } bool SerialGraphics::notZero(const QString &FName, const QString &VName, double value) { bool ok = !qFuzzyCompare(1.0 + value, 1.0); if(!ok) { emit errorMessage(QString(metaObject()->className()) + "::" + FName + "[" + windowTitle() + "] -> " + tr("Argument (%L1 == %L2) is a zero value"). arg(VName).arg(value)); } return ok; } bool SerialGraphics::notInvalid(const QString &FName, const QString &VName, double value, double minValue, double maxValue) { bool ok = ((minValue <= value) && (value <= maxValue)); if(!ok) { emit errorMessage(QString(metaObject()->className()) + "::" + FName + "[" + windowTitle() + "] -> " + tr("Argument (%L1 == %L2) is out of the valid range between " "[%L3 : %L4]").arg(VName).arg(value).arg(minValue).arg(maxValue)); } return ok; } /***************************************************************************//** * @file * @par MIT License - TERMS OF USE: * @n Permission 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 * @n The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * @n * @n THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE 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. *******************************************************************************/
32.042393
80
0.480436
[ "geometry", "render", "object" ]
b1a7bbc51d4d772c91eeb2f394e99b144b3184ee
2,175
hpp
C++
ext/qstm/OF-QSTM/ptms/qstm/src/testconfig.hpp
roghnin/Montage
40dbd6bb5a506545f01931336bf37b24cdb72a64
[ "MIT" ]
null
null
null
ext/qstm/OF-QSTM/ptms/qstm/src/testconfig.hpp
roghnin/Montage
40dbd6bb5a506545f01931336bf37b24cdb72a64
[ "MIT" ]
1
2020-11-16T02:57:28.000Z
2020-11-16T02:57:28.000Z
ext/qstm/OF-QSTM/ptms/qstm/src/testconfig.hpp
roghnin/Montage
40dbd6bb5a506545f01931336bf37b24cdb72a64
[ "MIT" ]
null
null
null
#ifndef TESTCONFIG_HPP #define TESTCONFIG_HPP #include <iostream> #include <unistd.h> #include <vector> #include <map> #include <hwloc.h> #include <vector> #include "transaction.hpp" #include "concurrentprimitives.hpp" class RingSTMFactory; class QSTMFactory; class OLDQSTMFactory; class TransTestFactory; void errexit(std::string s); class TestConfig{ private: // Affinity functions // a bunch needed because of recursive traversal of topologies. void buildAffinity(); void buildDFSAffinity_helper(hwloc_obj_t obj); void buildDFSAffinity(); int buildDefaultAffinity_findCoresInSocket(hwloc_obj_t obj, std::vector<hwloc_obj_t>* cores); int buildDefaultAffinity_buildPUsInCores(std::vector<hwloc_obj_t>* cores); int buildDefaultAffinity_findAndBuildSockets(hwloc_obj_t obj); void buildDefaultAffinity(); void buildSingleAffinity_helper(hwloc_obj_t obj); void buildSingleAffinity(); public: std::vector<hwloc_obj_t> affinities; // map from tid to CPU id hwloc_topology_t topology; int num_procs=24; std::string affinity; std::vector<TransTestFactory*> tests; std::vector<std::string> test_names; // std::vector<TMFactory*> stms; // std::vector<std::string> stm_names; QSTMFactory* stm; std::string stm_name; std::map<std::string,std::string> environment; unsigned int test = 0; // unsigned int stm = 0; int thread_cnt = 1; bool verbose = 0; void addTest(TransTestFactory* t, std::string name){ tests.push_back(t); test_names.push_back(name); } // void addSTM(TMFactory* s, std::string name){ // stms.push_back(s); // stm_names.push_back(name); // } void help(){ std::cerr<<"usage: [-v][-t thread_cnt][-T test][-d env=val][-h]"<<std::endl; for (unsigned int i = 0; i < tests.size(); i++){ std::cerr<<"Test "<<i<<" : "<<test_names[i]<<std::endl; } // for (unsigned int i = 0; i < stms.size(); i++){ // std::cerr<<"STM "<<i<<" : "<<stm_names[i]<<std::endl; // } } void setEnv(std::string key, std::string value); bool checkEnv(std::string key); std::string getEnv(std::string key); void parseCommandline(int argc, char** argv); QSTMFactory* getTMFactory() { return stm; } ~TestConfig(); }; #endif
24.166667
94
0.709425
[ "vector" ]
b1ab911eb46c4e43541ed5f45ff59081e19ba837
33,644
cpp
C++
source/lib3d/Vulkan/vk_descriptor_set.cpp
Lauvak/ray
906d3991ddd232a7f78f0e51f29aeead008a139a
[ "BSD-3-Clause" ]
113
2015-06-25T06:24:59.000Z
2021-09-26T02:46:02.000Z
source/lib3d/Vulkan/vk_descriptor_set.cpp
Lauvak/ray
906d3991ddd232a7f78f0e51f29aeead008a139a
[ "BSD-3-Clause" ]
2
2015-05-03T07:22:49.000Z
2017-12-11T09:17:20.000Z
source/lib3d/Vulkan/vk_descriptor_set.cpp
Lauvak/ray
906d3991ddd232a7f78f0e51f29aeead008a139a
[ "BSD-3-Clause" ]
17
2015-11-10T15:07:15.000Z
2021-01-19T15:28:16.000Z
// +---------------------------------------------------------------------- // | Project : ray. // | All rights reserved. // +---------------------------------------------------------------------- // | Copyright (c) 2013-2016. // +---------------------------------------------------------------------- // | * Redistribution and use of this software in source and binary forms, // | with or without modification, are permitted provided that the following // | conditions are met: // | // | * Redistributions of source code must retain the above // | copyright notice, this list of conditions and the // | following disclaimer. // | // | * Redistributions in binary form must reproduce the above // | copyright notice, this list of conditions and the // | following disclaimer in the documentation and/or other // | materials provided with the distribution. // | // | * Neither the name of the ray team, nor the names of its // | contributors may be used to endorse or promote products // | derived from this software without specific prior // | written permission of the ray team. // | // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // +---------------------------------------------------------------------- #include "vk_descriptor_set.h" #include "vk_device.h" #include "vk_shader.h" #include "vk_texture.h" #include "vk_graphics_data.h" #include "vk_system.h" _NAME_BEGIN __ImplementSubClass(VulkanGraphicsUniformSet, GraphicsUniformSet, "VulkanGraphicsUniformSet") __ImplementSubClass(VulkanDescriptorPool, GraphicsDescriptorPool, "VulkanDescriptorPool") __ImplementSubClass(VulkanDescriptorSet, GraphicsDescriptorSet, "VulkanDescriptorSet") __ImplementSubClass(VulkanDescriptorSetLayout, GraphicsDescriptorSetLayout, "VulkanDescriptorSetLayout") VulkanGraphicsUniformSet::VulkanGraphicsUniformSet() noexcept : _needUpdate(true) { } VulkanGraphicsUniformSet::~VulkanGraphicsUniformSet() noexcept { } void VulkanGraphicsUniformSet::needUpdate(bool needUpdate) noexcept { _needUpdate = needUpdate; } bool VulkanGraphicsUniformSet::needUpdate() const noexcept { return _needUpdate; } void VulkanGraphicsUniformSet::uniform1b(bool value) noexcept { this->needUpdate(true); _variant.uniform1b(value); } void VulkanGraphicsUniformSet::uniform1i(std::int32_t i1) noexcept { this->needUpdate(true); _variant.uniform1i(i1); } void VulkanGraphicsUniformSet::uniform2i(const int2& value) noexcept { this->needUpdate(true); _variant.uniform2i(value); } void VulkanGraphicsUniformSet::uniform2i(std::int32_t i1, std::int32_t i2) noexcept { this->needUpdate(true); _variant.uniform2i(i1, i2); } void VulkanGraphicsUniformSet::uniform3i(const int3& value) noexcept { this->needUpdate(true); _variant.uniform3i(value); } void VulkanGraphicsUniformSet::uniform3i(std::int32_t i1, std::int32_t i2, std::int32_t i3) noexcept { this->needUpdate(true); _variant.uniform3i(i1, i2, i3); } void VulkanGraphicsUniformSet::uniform4i(const int4& value) noexcept { this->needUpdate(true); _variant.uniform4i(value); } void VulkanGraphicsUniformSet::uniform4i(std::int32_t i1, std::int32_t i2, std::int32_t i3, std::int32_t i4) noexcept { this->needUpdate(true); _variant.uniform4i(i1, i2, i3, i4); } void VulkanGraphicsUniformSet::uniform1ui(std::uint32_t ui1) noexcept { this->needUpdate(true); _variant.uniform1ui(ui1); } void VulkanGraphicsUniformSet::uniform2ui(const uint2& value) noexcept { this->needUpdate(true); _variant.uniform2ui(value); } void VulkanGraphicsUniformSet::uniform2ui(std::uint32_t ui1, std::uint32_t ui2) noexcept { this->needUpdate(true); _variant.uniform2ui(ui1, ui2); } void VulkanGraphicsUniformSet::uniform3ui(const uint3& value) noexcept { this->needUpdate(true); _variant.uniform3ui(value); } void VulkanGraphicsUniformSet::uniform3ui(std::uint32_t ui1, std::uint32_t ui2, std::uint32_t ui3) noexcept { this->needUpdate(true); _variant.uniform3ui(ui1, ui2, ui3); } void VulkanGraphicsUniformSet::uniform4ui(const uint4& value) noexcept { this->needUpdate(true); _variant.uniform4ui(value); } void VulkanGraphicsUniformSet::uniform4ui(std::uint32_t ui1, std::uint32_t ui2, std::uint32_t ui3, std::uint32_t ui4) noexcept { this->needUpdate(true); _variant.uniform4ui(ui1, ui2, ui3, ui4); } void VulkanGraphicsUniformSet::uniform1f(float f1) noexcept { this->needUpdate(true); _variant.uniform1f(f1); } void VulkanGraphicsUniformSet::uniform2f(const float2& value) noexcept { this->needUpdate(true); _variant.uniform2f(value); } void VulkanGraphicsUniformSet::uniform2f(float f1, float f2) noexcept { this->needUpdate(true); _variant.uniform2f(f1, f2); } void VulkanGraphicsUniformSet::uniform3f(const float3& value) noexcept { this->needUpdate(true); _variant.uniform3f(value); } void VulkanGraphicsUniformSet::uniform3f(float f1, float f2, float f3) noexcept { this->needUpdate(true); _variant.uniform3f(f1, f2, f3); } void VulkanGraphicsUniformSet::uniform4f(const float4& value) noexcept { this->needUpdate(true); _variant.uniform4f(value); } void VulkanGraphicsUniformSet::uniform4f(float f1, float f2, float f3, float f4) noexcept { this->needUpdate(true); _variant.uniform4f(f1, f2, f3, f4); } void VulkanGraphicsUniformSet::uniform2fmat(const float2x2& value) noexcept { this->needUpdate(true); _variant.uniform2fmat(value); } void VulkanGraphicsUniformSet::uniform2fmat(const float* mat2) noexcept { this->needUpdate(true); _variant.uniform2fmat(mat2); } void VulkanGraphicsUniformSet::uniform3fmat(const float3x3& value) noexcept { this->needUpdate(true); _variant.uniform3fmat(value); } void VulkanGraphicsUniformSet::uniform3fmat(const float* mat3) noexcept { this->needUpdate(true); _variant.uniform3fmat(mat3); } void VulkanGraphicsUniformSet::uniform4fmat(const float4x4& value) noexcept { this->needUpdate(true); _variant.uniform4fmat(value); } void VulkanGraphicsUniformSet::uniform4fmat(const float* mat4) noexcept { this->needUpdate(true); _variant.uniform4fmat(mat4); } void VulkanGraphicsUniformSet::uniform1iv(const std::vector<int1>& value) noexcept { this->needUpdate(true); _variant.uniform1iv(value); } void VulkanGraphicsUniformSet::uniform1iv(std::size_t num, const std::int32_t* i1v) noexcept { this->needUpdate(true); _variant.uniform1iv(num, i1v); } void VulkanGraphicsUniformSet::uniform2iv(const std::vector<int2>& value) noexcept { this->needUpdate(true); _variant.uniform2iv(value); } void VulkanGraphicsUniformSet::uniform2iv(std::size_t num, const std::int32_t* i2v) noexcept { this->needUpdate(true); _variant.uniform2iv(num, i2v); } void VulkanGraphicsUniformSet::uniform3iv(const std::vector<int3>& value) noexcept { this->needUpdate(true); _variant.uniform3iv(value); } void VulkanGraphicsUniformSet::uniform3iv(std::size_t num, const std::int32_t* i3v) noexcept { this->needUpdate(true); _variant.uniform3iv(num, i3v); } void VulkanGraphicsUniformSet::uniform4iv(const std::vector<int4>& value) noexcept { this->needUpdate(true); _variant.uniform4iv(value); } void VulkanGraphicsUniformSet::uniform4iv(std::size_t num, const std::int32_t* i4v) noexcept { this->needUpdate(true); _variant.uniform4iv(num, i4v); } void VulkanGraphicsUniformSet::uniform1uiv(const std::vector<uint1>& value) noexcept { this->needUpdate(true); _variant.uniform1uiv(value); } void VulkanGraphicsUniformSet::uniform1uiv(std::size_t num, const std::uint32_t* ui1v) noexcept { this->needUpdate(true); _variant.uniform1uiv(num, ui1v); } void VulkanGraphicsUniformSet::uniform2uiv(const std::vector<uint2>& value) noexcept { this->needUpdate(true); _variant.uniform2uiv(value); } void VulkanGraphicsUniformSet::uniform2uiv(std::size_t num, const std::uint32_t* ui2v) noexcept { this->needUpdate(true); _variant.uniform2uiv(num, ui2v); } void VulkanGraphicsUniformSet::uniform3uiv(const std::vector<uint3>& value) noexcept { this->needUpdate(true); _variant.uniform3uiv(value); } void VulkanGraphicsUniformSet::uniform3uiv(std::size_t num, const std::uint32_t* ui3v) noexcept { this->needUpdate(true); _variant.uniform3uiv(num, ui3v); } void VulkanGraphicsUniformSet::uniform4uiv(const std::vector<uint4>& value) noexcept { this->needUpdate(true); _variant.uniform4uiv(value); } void VulkanGraphicsUniformSet::uniform4uiv(std::size_t num, const std::uint32_t* ui4v) noexcept { this->needUpdate(true); _variant.uniform4uiv(num, ui4v); } void VulkanGraphicsUniformSet::uniform1fv(const std::vector<float1>& value) noexcept { this->needUpdate(true); _variant.uniform1fv(value); } void VulkanGraphicsUniformSet::uniform1fv(std::size_t num, const float* f1v) noexcept { this->needUpdate(true); _variant.uniform1fv(num, f1v); } void VulkanGraphicsUniformSet::uniform2fv(const std::vector<float2>& value) noexcept { this->needUpdate(true); _variant.uniform2fv(value); } void VulkanGraphicsUniformSet::uniform2fv(std::size_t num, const float* f2v) noexcept { this->needUpdate(true); _variant.uniform2fv(num, f2v); } void VulkanGraphicsUniformSet::uniform3fv(const std::vector<float3>& value) noexcept { this->needUpdate(true); _variant.uniform3fv(value); } void VulkanGraphicsUniformSet::uniform3fv(std::size_t num, const float* f3v) noexcept { this->needUpdate(true); _variant.uniform3fv(num, f3v); } void VulkanGraphicsUniformSet::uniform4fv(const std::vector<float4>& value) noexcept { this->needUpdate(true); _variant.uniform4fv(value); } void VulkanGraphicsUniformSet::uniform4fv(std::size_t num, const float* f4v) noexcept { this->needUpdate(true); _variant.uniform4fv(num, f4v); } void VulkanGraphicsUniformSet::uniform2fmatv(const std::vector<float2x2>& value) noexcept { this->needUpdate(true); _variant.uniform2fmatv(value); } void VulkanGraphicsUniformSet::uniform2fmatv(std::size_t num, const float* mat2) noexcept { this->needUpdate(true); _variant.uniform2fmatv(num, mat2); } void VulkanGraphicsUniformSet::uniform3fmatv(const std::vector<float3x3>& value) noexcept { this->needUpdate(true); _variant.uniform3fmatv(value); } void VulkanGraphicsUniformSet::uniform3fmatv(std::size_t num, const float* mat3) noexcept { this->needUpdate(true); _variant.uniform3fmatv(num, mat3); } void VulkanGraphicsUniformSet::uniform4fmatv(const std::vector<float4x4>& value) noexcept { this->needUpdate(true); _variant.uniform4fmatv(value); } void VulkanGraphicsUniformSet::uniform4fmatv(std::size_t num, const float* mat4) noexcept { this->needUpdate(true); _variant.uniform4fmatv(num, mat4); } void VulkanGraphicsUniformSet::uniformTexture(GraphicsTexturePtr texture, GraphicsSamplerPtr sampler) noexcept { this->needUpdate(true); _variant.uniformTexture(texture, sampler); } void VulkanGraphicsUniformSet::uniformBuffer(GraphicsDataPtr ubo) noexcept { this->needUpdate(true); _variant.uniformBuffer(ubo); } bool VulkanGraphicsUniformSet::getBool() const noexcept { return _variant.getBool(); } int VulkanGraphicsUniformSet::getInt() const noexcept { return _variant.getInt(); } const int2& VulkanGraphicsUniformSet::getInt2() const noexcept { return _variant.getInt2(); } const int3& VulkanGraphicsUniformSet::getInt3() const noexcept { return _variant.getInt3(); } const int4& VulkanGraphicsUniformSet::getInt4() const noexcept { return _variant.getInt4(); } uint VulkanGraphicsUniformSet::getUInt() const noexcept { return _variant.getUInt(); } const uint2& VulkanGraphicsUniformSet::getUInt2() const noexcept { return _variant.getUInt2(); } const uint3& VulkanGraphicsUniformSet::getUInt3() const noexcept { return _variant.getUInt3(); } const uint4& VulkanGraphicsUniformSet::getUInt4() const noexcept { return _variant.getUInt4(); } float VulkanGraphicsUniformSet::getFloat() const noexcept { return _variant.getFloat(); } const float2& VulkanGraphicsUniformSet::getFloat2() const noexcept { return _variant.getFloat2(); } const float3& VulkanGraphicsUniformSet::getFloat3() const noexcept { return _variant.getFloat3(); } const float4& VulkanGraphicsUniformSet::getFloat4() const noexcept { return _variant.getFloat4(); } const float2x2& VulkanGraphicsUniformSet::getFloat2x2() const noexcept { return _variant.getFloat2x2(); } const float3x3& VulkanGraphicsUniformSet::getFloat3x3() const noexcept { return _variant.getFloat3x3(); } const float4x4& VulkanGraphicsUniformSet::getFloat4x4() const noexcept { return _variant.getFloat4x4(); } const std::vector<int1>& VulkanGraphicsUniformSet::getIntArray() const noexcept { return _variant.getIntArray(); } const std::vector<int2>& VulkanGraphicsUniformSet::getInt2Array() const noexcept { return _variant.getInt2Array(); } const std::vector<int3>& VulkanGraphicsUniformSet::getInt3Array() const noexcept { return _variant.getInt3Array(); } const std::vector<int4>& VulkanGraphicsUniformSet::getInt4Array() const noexcept { return _variant.getInt4Array(); } const std::vector<uint1>& VulkanGraphicsUniformSet::getUIntArray() const noexcept { return _variant.getUIntArray(); } const std::vector<uint2>& VulkanGraphicsUniformSet::getUInt2Array() const noexcept { return _variant.getUInt2Array(); } const std::vector<uint3>& VulkanGraphicsUniformSet::getUInt3Array() const noexcept { return _variant.getUInt3Array(); } const std::vector<uint4>& VulkanGraphicsUniformSet::getUInt4Array() const noexcept { return _variant.getUInt4Array(); } const std::vector<float1>& VulkanGraphicsUniformSet::getFloatArray() const noexcept { return _variant.getFloatArray(); } const std::vector<float2>& VulkanGraphicsUniformSet::getFloat2Array() const noexcept { return _variant.getFloat2Array(); } const std::vector<float3>& VulkanGraphicsUniformSet::getFloat3Array() const noexcept { return _variant.getFloat3Array(); } const std::vector<float4>& VulkanGraphicsUniformSet::getFloat4Array() const noexcept { return _variant.getFloat4Array(); } const std::vector<float2x2>& VulkanGraphicsUniformSet::getFloat2x2Array() const noexcept { return _variant.getFloat2x2Array(); } const std::vector<float3x3>& VulkanGraphicsUniformSet::getFloat3x3Array() const noexcept { return _variant.getFloat3x3Array(); } const std::vector<float4x4>& VulkanGraphicsUniformSet::getFloat4x4Array() const noexcept { return _variant.getFloat4x4Array(); } const GraphicsTexturePtr& VulkanGraphicsUniformSet::getTexture() const noexcept { return _variant.getTexture(); } const GraphicsSamplerPtr& VulkanGraphicsUniformSet::getTextureSampler() const noexcept { return _variant.getTextureSampler(); } const GraphicsDataPtr& VulkanGraphicsUniformSet::getBuffer() const noexcept { return _variant.getBuffer(); } void VulkanGraphicsUniformSet::setGraphicsParam(GraphicsParamPtr param) noexcept { assert(param); _param = param; _variant.setType(param->getType()); } const GraphicsParamPtr& VulkanGraphicsUniformSet::getGraphicsParam() const noexcept { return _param; } VulkanDescriptorPool::VulkanDescriptorPool() noexcept : _descriptorPool(VK_NULL_HANDLE) { } VulkanDescriptorPool::~VulkanDescriptorPool() noexcept { this->close(); } bool VulkanDescriptorPool::setup(const GraphicsDescriptorPoolDesc& descriptorPoolDesc) noexcept { std::vector<VkDescriptorPoolSize> pool; for (const auto& it : descriptorPoolDesc.getGraphicsDescriptorPoolComponents()) { VkDescriptorPoolSize poolSize; poolSize.type = VulkanTypes::asDescriptorType(it.getDescriptorType()); poolSize.descriptorCount = it.getDescriptorNums(); pool.push_back(poolSize); } VkDescriptorPoolCreateInfo info; info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; info.pNext = nullptr; info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; info.maxSets = descriptorPoolDesc.getMaxSets(); info.poolSizeCount = pool.size(); info.pPoolSizes = pool.data(); if (vkCreateDescriptorPool(_device.lock()->getDevice(), &info, nullptr, &_descriptorPool) != VK_SUCCESS) { VK_PLATFORM_LOG("vkCreateDescriptorPool() fail."); return false; } _descriptorPoolDesc = descriptorPoolDesc; return true; } void VulkanDescriptorPool::close() noexcept { if (_descriptorPool != VK_NULL_HANDLE) { vkDestroyDescriptorPool(_device.lock()->getDevice(), _descriptorPool, nullptr); _descriptorPool = VK_NULL_HANDLE; } } VkDescriptorPool VulkanDescriptorPool::getDescriptorPool() const noexcept { return _descriptorPool; } void VulkanDescriptorPool::setDevice(GraphicsDevicePtr device) noexcept { _device = device->downcast_pointer<VulkanDevice>(); } GraphicsDevicePtr VulkanDescriptorPool::getDevice() noexcept { return _device.lock(); } const GraphicsDescriptorPoolDesc& VulkanDescriptorPool::getGraphicsDescriptorPoolDesc() const noexcept { return _descriptorPoolDesc; } VulkanDescriptorSetLayout::VulkanDescriptorSetLayout() noexcept : _vkDescriptorSetLayout(VK_NULL_HANDLE) { } VulkanDescriptorSetLayout::~VulkanDescriptorSetLayout() noexcept { this->close(); } bool VulkanDescriptorSetLayout::setup(const GraphicsDescriptorSetLayoutDesc& descriptorSetLayoutDesc) noexcept { std::vector<VkDescriptorSetLayoutBinding> layouts; const auto& uniforms = descriptorSetLayoutDesc.getUniformComponents(); for (const auto& it : uniforms) { auto type = it->getType(); if (type == GraphicsUniformType::GraphicsUniformTypeStorageImage || type == GraphicsUniformType::GraphicsUniformTypeSamplerImage || type == GraphicsUniformType::GraphicsUniformTypeCombinedImageSampler || type == GraphicsUniformType::GraphicsUniformTypeUniformBuffer || type == GraphicsUniformType::GraphicsUniformTypeUniformBufferDynamic) { VkDescriptorSetLayoutBinding layout; layout.descriptorType = VulkanTypes::asDescriptorType(it->getType()); layout.descriptorCount = 1; layout.pImmutableSamplers = nullptr; layout.binding = it->getBindingPoint(); layout.stageFlags = VulkanTypes::asShaderStageFlags(it->getShaderStageFlags()); layouts.push_back(layout); } } VkDescriptorSetLayoutCreateInfo info; info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; info.pNext = nullptr; info.flags = 0; info.bindingCount = layouts.size(); info.pBindings = layouts.data(); if (vkCreateDescriptorSetLayout(_device.lock()->getDevice(), &info, nullptr, &_vkDescriptorSetLayout) != VK_SUCCESS) { VK_PLATFORM_LOG("vkCreateDescriptorSetLayout() fail."); return false; } _descriptorSetLayoutDesc = descriptorSetLayoutDesc; return true; } void VulkanDescriptorSetLayout::close() noexcept { if (_vkDescriptorSetLayout != VK_NULL_HANDLE) { vkDestroyDescriptorSetLayout(_device.lock()->getDevice(), _vkDescriptorSetLayout, nullptr); _vkDescriptorSetLayout = VK_NULL_HANDLE; } } VkDescriptorSetLayout VulkanDescriptorSetLayout::getDescriptorSetLayout() const noexcept { return _vkDescriptorSetLayout; } const GraphicsDescriptorSetLayoutDesc& VulkanDescriptorSetLayout::getGraphicsDescriptorSetLayoutDesc() const noexcept { return _descriptorSetLayoutDesc; } void VulkanDescriptorSetLayout::setDevice(GraphicsDevicePtr device) noexcept { _device = device->downcast_pointer<VulkanDevice>(); } GraphicsDevicePtr VulkanDescriptorSetLayout::getDevice() noexcept { return _device.lock(); } VulkanDescriptorSet::VulkanDescriptorSet() noexcept : _vkDescriptorSet(VK_NULL_HANDLE) { } VulkanDescriptorSet::~VulkanDescriptorSet() noexcept { this->close(); } bool VulkanDescriptorSet::setup(const GraphicsDescriptorSetDesc& descriptorSetDesc) noexcept { assert(descriptorSetDesc.getGraphicsDescriptorPool()); assert(descriptorSetDesc.getGraphicsDescriptorSetLayout()); assert(_vkDescriptorSet == VK_NULL_HANDLE); auto descriptorPool = descriptorSetDesc.getGraphicsDescriptorPool(); auto descriptorSetLayout = descriptorSetDesc.getGraphicsDescriptorSetLayout(); VkDescriptorPool poolHandle = descriptorPool->downcast<VulkanDescriptorPool>()->getDescriptorPool(); VkDescriptorSetLayout layoutHandle = descriptorSetLayout->downcast<VulkanDescriptorSetLayout>()->getDescriptorSetLayout(); VkDescriptorSetAllocateInfo info; info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; info.pNext = nullptr; info.descriptorSetCount = 1; info.pSetLayouts = &layoutHandle; info.descriptorPool = poolHandle; if (vkAllocateDescriptorSets(_device.lock()->getDevice(), &info, &_vkDescriptorSet) != VK_SUCCESS) { VK_PLATFORM_LOG("vkAllocateDescriptorSets() fail."); return false; } auto& descriptorSetLayoutDesc = descriptorSetDesc.getGraphicsDescriptorSetLayout()->getGraphicsDescriptorSetLayoutDesc(); auto& params = descriptorSetLayoutDesc.getUniformComponents(); for (auto& param : params) { if (param->getType() == GraphicsUniformType::GraphicsUniformTypeUniformBuffer) { auto uniformBlock = param->downcast<VulkanGraphicsUniformBlock>(); auto& name = uniformBlock->getName(); if (name == "Globals") { GraphicsDataDesc uniformBufferDesc; uniformBufferDesc.setType(GraphicsDataType::GraphicsDataTypeUniformBuffer); uniformBufferDesc.setStreamSize(uniformBlock->getBlockSize()); uniformBufferDesc.setUsage(GraphicsUsageFlagBits::GraphicsUsageFlagReadBit | GraphicsUsageFlagBits::GraphicsUsageFlagWriteBit); auto ubo = this->getDevice()->createGraphicsData(uniformBufferDesc); if (!ubo) { VK_PLATFORM_LOG("Can't create uniform buffer"); return false; } auto& uniforms = uniformBlock->getGraphicsUniforms(); for (auto& uniform : uniforms) { auto uniformSet = std::make_shared<VulkanGraphicsUniformSet>(); uniformSet->setGraphicsParam(uniform); _activeUniformSets.push_back(uniformSet); _activeGlobalUniformSets.push_back(uniformSet); } _globalUniformBlock = uniformBlock->downcast_pointer<VulkanGraphicsUniformBlock>(); _globalData = ubo->downcast_pointer<VulkanGraphicsData>(); } } else { auto uniformSet = std::make_shared<VulkanGraphicsUniformSet>(); uniformSet->setGraphicsParam(param); _activeUniformSets.push_back(uniformSet); } } std::vector<VkWriteDescriptorSet> descriptorWrites; if (_globalUniformBlock) { auto uniformBlock = _globalUniformBlock; auto data = _globalData->downcast<VulkanGraphicsData>(); VkDescriptorBufferInfo bufferInfo; bufferInfo.buffer = data->getBuffer(); bufferInfo.offset = 0; bufferInfo.range = data->getGraphicsDataDesc().getStreamSize(); VkWriteDescriptorSet write; write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; write.pNext = nullptr; write.descriptorType = VulkanTypes::asDescriptorType(uniformBlock->getType()); write.descriptorCount = 1; write.dstSet = _vkDescriptorSet; write.dstArrayElement = 0; write.dstBinding = uniformBlock->getBindingPoint(); write.pBufferInfo = &bufferInfo; write.pImageInfo = nullptr; write.pTexelBufferView = nullptr; descriptorWrites.push_back(write); } if (!descriptorWrites.empty()) { vkUpdateDescriptorSets(_device.lock()->getDevice(), descriptorWrites.size(), descriptorWrites.data(), 0, nullptr); } _descriptorSetDesc = descriptorSetDesc; return true; } void VulkanDescriptorSet::close() noexcept { if (_vkDescriptorSet != VK_NULL_HANDLE) { vkFreeDescriptorSets(_device.lock()->getDevice(), _descriptorSetDesc.getGraphicsDescriptorPool()->downcast<VulkanDescriptorPool>()->getDescriptorPool(), 1, &_vkDescriptorSet); _vkDescriptorSet = VK_NULL_HANDLE; } } void VulkanDescriptorSet::update() noexcept { std::uint32_t descriptorWriteCount = 0; VkWriteDescriptorSet descriptorWrites[10]; VkDescriptorImageInfo descriptorImageInfos[10]; for (auto& it : _activeUniformSets) { auto param = it->getGraphicsParam(); auto type = it->getGraphicsParam()->getType(); auto bindingPoint = it->getGraphicsParam()->getBindingPoint(); switch (type) { case GraphicsUniformType::GraphicsUniformTypeSampler: break; case GraphicsUniformType::GraphicsUniformTypeSamplerImage: { auto texture = it->getTexture(); if (texture) { auto vkTexture = texture->downcast<VulkanTexture>(); auto& info = descriptorImageInfos[descriptorWriteCount]; info.imageLayout = VkImageLayout::VK_IMAGE_LAYOUT_GENERAL; info.imageView = vkTexture->getImageView(); info.sampler = VK_NULL_HANDLE; auto& write = descriptorWrites[descriptorWriteCount++]; write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; write.pNext = nullptr; write.descriptorType = VkDescriptorType::VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; write.descriptorCount = 1; write.dstSet = _vkDescriptorSet; write.dstArrayElement = 0; write.dstBinding = bindingPoint; write.pBufferInfo = nullptr; write.pImageInfo = &info; write.pTexelBufferView = nullptr; } } break; case GraphicsUniformType::GraphicsUniformTypeCombinedImageSampler: break; case GraphicsUniformType::GraphicsUniformTypeStorageImage: { auto texture = it->getTexture(); if (texture) { auto vkTexture = texture->downcast<VulkanTexture>(); VkDescriptorImageInfo info; info.imageLayout = VkImageLayout::VK_IMAGE_LAYOUT_GENERAL; info.imageView = vkTexture->getImageView(); info.sampler = VK_NULL_HANDLE; auto& write = descriptorWrites[descriptorWriteCount++]; write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; write.pNext = nullptr; write.descriptorType = VkDescriptorType::VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; write.descriptorCount = 1; write.dstSet = _vkDescriptorSet; write.dstArrayElement = 0; write.dstBinding = bindingPoint; write.pBufferInfo = nullptr; write.pImageInfo = &info; write.pTexelBufferView = nullptr; } } break; case GraphicsUniformType::GraphicsUniformTypeStorageTexelBuffer: break; case GraphicsUniformType::GraphicsUniformTypeStorageBuffer: break; case GraphicsUniformType::GraphicsUniformTypeStorageBufferDynamic: break; case GraphicsUniformType::GraphicsUniformTypeUniformTexelBuffer: break; case GraphicsUniformType::GraphicsUniformTypeUniformBuffer: break; case GraphicsUniformType::GraphicsUniformTypeUniformBufferDynamic: break; case GraphicsUniformType::GraphicsUniformTypeInputAttachment: break; default: break; } } if (descriptorWriteCount > 0) { vkUpdateDescriptorSets(_device.lock()->getDevice(), descriptorWriteCount, descriptorWrites, 0, nullptr); } void* buffer = nullptr; for (auto& activeUniformSet : _activeGlobalUniformSets) { auto uniformSet = activeUniformSet->downcast<VulkanGraphicsUniformSet>(); if (!uniformSet->needUpdate()) continue; if (!buffer) { if (!_globalData->map(0, _globalData->getGraphicsDataDesc().getStreamSize(), &buffer)) break; } auto uniform = uniformSet->getGraphicsParam()->downcast<VulkanGraphicsUniform>(); auto uniformType = uniform->getType(); switch (uniformType) { case GraphicsUniformType::GraphicsUniformTypeBool: (*(int*)((char*)buffer + uniform->getOffset())) = uniformSet->getBool(); break; case GraphicsUniformType::GraphicsUniformTypeInt: (*(int1*)((char*)buffer + uniform->getOffset())) = uniformSet->getInt(); break; case GraphicsUniformType::GraphicsUniformTypeInt2: (*(int2*)((char*)buffer + uniform->getOffset())) = uniformSet->getInt2(); break; case GraphicsUniformType::GraphicsUniformTypeInt3: (*(int3*)((char*)buffer + uniform->getOffset())) = uniformSet->getInt3(); break; case GraphicsUniformType::GraphicsUniformTypeInt4: (*(int4*)((char*)buffer + uniform->getOffset())) = uniformSet->getInt4(); break; case GraphicsUniformType::GraphicsUniformTypeUInt: (*(uint1*)((char*)buffer + uniform->getOffset())) = uniformSet->getUInt(); break; case GraphicsUniformType::GraphicsUniformTypeUInt2: (*(uint2*)((char*)buffer + uniform->getOffset())) = uniformSet->getUInt2(); break; case GraphicsUniformType::GraphicsUniformTypeUInt3: (*(uint3*)((char*)buffer + uniform->getOffset())) = uniformSet->getUInt3(); break; case GraphicsUniformType::GraphicsUniformTypeUInt4: (*(uint4*)((char*)buffer + uniform->getOffset())) = uniformSet->getUInt4(); break; case GraphicsUniformType::GraphicsUniformTypeFloat: (*(float1*)((char*)buffer + uniform->getOffset())) = uniformSet->getFloat(); break; case GraphicsUniformType::GraphicsUniformTypeFloat2: (*(float2*)((char*)buffer + uniform->getOffset())) = uniformSet->getFloat2(); break; case GraphicsUniformType::GraphicsUniformTypeFloat3: (*(float3*)((char*)buffer + uniform->getOffset())) = uniformSet->getFloat3(); break; case GraphicsUniformType::GraphicsUniformTypeFloat4: (*(float4*)((char*)buffer + uniform->getOffset())) = uniformSet->getFloat4(); break; case GraphicsUniformType::GraphicsUniformTypeFloat2x2: (*(float2x2*)((char*)buffer + uniform->getOffset())) = uniformSet->getFloat2x2(); break; case GraphicsUniformType::GraphicsUniformTypeFloat3x3: (*(float3x3*)((char*)buffer + uniform->getOffset())) = uniformSet->getFloat3x3(); break; case GraphicsUniformType::GraphicsUniformTypeFloat4x4: (*(float4x4*)((char*)buffer + uniform->getOffset())) = uniformSet->getFloat4x4(); break; case GraphicsUniformType::GraphicsUniformTypeIntArray: std::memcpy((char*)buffer + uniform->getOffset(), uniformSet->getIntArray().data(), uniformSet->getIntArray().size()* sizeof(int1)); break; case GraphicsUniformType::GraphicsUniformTypeInt2Array: std::memcpy((char*)buffer + uniform->getOffset(), uniformSet->getInt2Array().data(), uniformSet->getInt2Array().size() * sizeof(int2)); break; case GraphicsUniformType::GraphicsUniformTypeInt3Array: std::memcpy((char*)buffer + uniform->getOffset(), uniformSet->getInt3Array().data(), uniformSet->getInt3Array().size() * sizeof(int3)); break; case GraphicsUniformType::GraphicsUniformTypeInt4Array: std::memcpy((char*)buffer + uniform->getOffset(), uniformSet->getInt4Array().data(), uniformSet->getInt4Array().size() * sizeof(int4)); break; case GraphicsUniformType::GraphicsUniformTypeUIntArray: std::memcpy((char*)buffer + uniform->getOffset(), uniformSet->getUIntArray().data(), uniformSet->getUIntArray().size()* sizeof(uint1)); break; case GraphicsUniformType::GraphicsUniformTypeUInt2Array: std::memcpy((char*)buffer + uniform->getOffset(), uniformSet->getUInt2Array().data(), uniformSet->getUInt2Array().size() * sizeof(uint2)); break; case GraphicsUniformType::GraphicsUniformTypeUInt3Array: std::memcpy((char*)buffer + uniform->getOffset(), uniformSet->getUInt3Array().data(), uniformSet->getUInt3Array().size() * sizeof(uint3)); break; case GraphicsUniformType::GraphicsUniformTypeUInt4Array: std::memcpy((char*)buffer + uniform->getOffset(), uniformSet->getUInt4Array().data(), uniformSet->getUInt4Array().size() * sizeof(uint4)); break; case GraphicsUniformType::GraphicsUniformTypeFloatArray: std::memcpy((char*)buffer + uniform->getOffset(), uniformSet->getFloatArray().data(), uniformSet->getFloatArray().size() * sizeof(float1)); break; case GraphicsUniformType::GraphicsUniformTypeFloat2Array: std::memcpy((char*)buffer + uniform->getOffset(), uniformSet->getFloat2Array().data(), uniformSet->getFloat2Array().size() * sizeof(float2)); break; case GraphicsUniformType::GraphicsUniformTypeFloat3Array: std::memcpy((char*)buffer + uniform->getOffset(), uniformSet->getFloat3Array().data(), uniformSet->getFloat3Array().size() * sizeof(float3)); break; case GraphicsUniformType::GraphicsUniformTypeFloat4Array: std::memcpy((char*)buffer + uniform->getOffset(), uniformSet->getFloat4Array().data(), uniformSet->getFloat4Array().size() * sizeof(float4)); break; case GraphicsUniformType::GraphicsUniformTypeFloat2x2Array: std::memcpy((char*)buffer + uniform->getOffset(), uniformSet->getFloat4Array().data(), uniformSet->getFloat4Array().size() * sizeof(float2x2)); break; case GraphicsUniformType::GraphicsUniformTypeFloat3x3Array: std::memcpy((char*)buffer + uniform->getOffset(), uniformSet->getFloat4Array().data(), uniformSet->getFloat4Array().size() * sizeof(float3x3)); break; case GraphicsUniformType::GraphicsUniformTypeFloat4x4Array: std::memcpy((char*)buffer + uniform->getOffset(), uniformSet->getFloat4Array().data(), uniformSet->getFloat4Array().size() * sizeof(float4x4)); break; default: break; } uniformSet->needUpdate(false); } if (buffer) { _globalData->unmap(); } } VkDescriptorSet VulkanDescriptorSet::getDescriptorSet() const noexcept { return _vkDescriptorSet; } const GraphicsUniformSets& VulkanDescriptorSet::getGraphicsUniformSets() const noexcept { return _activeUniformSets; } const GraphicsDescriptorSetDesc& VulkanDescriptorSet::getGraphicsDescriptorSetDesc() const noexcept { return _descriptorSetDesc; } void VulkanDescriptorSet::setDevice(GraphicsDevicePtr device) noexcept { _device = device->downcast_pointer<VulkanDevice>(); } GraphicsDevicePtr VulkanDescriptorSet::getDevice() noexcept { return _device.lock(); } _NAME_END
27.023293
177
0.762454
[ "vector" ]
b1ac2ed6650e50495d987398b5bc6aa9ce67111e
4,804
cc
C++
shell/common/shell_io_manager_unittests.cc
charafau/engine
c4a1a72da5dde44cc6288f8c4c0020b03e1e9279
[ "BSD-3-Clause" ]
null
null
null
shell/common/shell_io_manager_unittests.cc
charafau/engine
c4a1a72da5dde44cc6288f8c4c0020b03e1e9279
[ "BSD-3-Clause" ]
2
2019-05-09T12:15:03.000Z
2020-03-09T09:24:39.000Z
shell/common/shell_io_manager_unittests.cc
charafau/engine
c4a1a72da5dde44cc6288f8c4c0020b03e1e9279
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/common/shell_io_manager.h" #include "flutter/common/task_runners.h" #include "flutter/fml/mapping.h" #include "flutter/lib/ui/painting/multi_frame_codec.h" #include "flutter/testing/dart_isolate_runner.h" #include "flutter/testing/fixture_test.h" #include "flutter/testing/post_task_sync.h" #include "flutter/testing/test_gl_surface.h" #include "flutter/testing/testing.h" namespace flutter { namespace testing { static sk_sp<SkData> OpenFixtureAsSkData(const char* name) { auto fixtures_directory = fml::OpenDirectory(GetFixturesPath(), false, fml::FilePermission::kRead); if (!fixtures_directory.is_valid()) { return nullptr; } auto fixture_mapping = fml::FileMapping::CreateReadOnly(fixtures_directory, name); if (!fixture_mapping) { return nullptr; } SkData::ReleaseProc on_release = [](const void* ptr, void* context) -> void { delete reinterpret_cast<fml::FileMapping*>(context); }; auto data = SkData::MakeWithProc(fixture_mapping->GetMapping(), fixture_mapping->GetSize(), on_release, fixture_mapping.get()); if (!data) { return nullptr; } // The data is now owned by Skia. fixture_mapping.release(); return data; } class ShellIOManagerTest : public FixtureTest {}; // Regression test for https://github.com/flutter/engine/pull/32106. TEST_F(ShellIOManagerTest, ItDoesNotCrashThatSkiaUnrefQueueDrainAfterIOManagerReset) { auto settings = CreateSettingsForFixture(); auto vm_ref = DartVMRef::Create(settings); auto vm_data = vm_ref.GetVMData(); auto gif_mapping = OpenFixtureAsSkData("hello_loop_2.gif"); ASSERT_TRUE(gif_mapping); ImageGeneratorRegistry registry; std::shared_ptr<ImageGenerator> gif_generator = registry.CreateCompatibleGenerator(gif_mapping); ASSERT_TRUE(gif_generator); TaskRunners runners(GetCurrentTestName(), // label CreateNewThread("platform"), // platform CreateNewThread("raster"), // raster CreateNewThread("ui"), // ui CreateNewThread("io") // io ); std::unique_ptr<TestGLSurface> gl_surface; std::unique_ptr<ShellIOManager> io_manager; fml::RefPtr<MultiFrameCodec> codec; // Setup the IO manager. PostTaskSync(runners.GetIOTaskRunner(), [&]() { gl_surface = std::make_unique<TestGLSurface>(SkISize::Make(1, 1)); io_manager = std::make_unique<ShellIOManager>( gl_surface->CreateGrContext(), std::make_shared<fml::SyncSwitch>(), runners.GetIOTaskRunner(), nullptr, fml::TimeDelta::FromMilliseconds(0)); }); auto isolate = RunDartCodeInIsolate(vm_ref, settings, runners, "emptyMain", {}, GetDefaultKernelFilePath(), io_manager->GetWeakIOManager()); PostTaskSync(runners.GetUITaskRunner(), [&]() { fml::AutoResetWaitableEvent isolate_latch; EXPECT_TRUE(isolate->RunInIsolateScope([&]() -> bool { Dart_Handle library = Dart_RootLibrary(); if (Dart_IsError(library)) { isolate_latch.Signal(); return false; } Dart_Handle closure = Dart_GetField(library, Dart_NewStringFromCString("frameCallback")); if (Dart_IsError(closure) || !Dart_IsClosure(closure)) { isolate_latch.Signal(); return false; } codec = fml::MakeRefCounted<MultiFrameCodec>(std::move(gif_generator)); codec->getNextFrame(closure); isolate_latch.Signal(); return true; })); isolate_latch.Wait(); }); // Destroy the IO manager PostTaskSync(runners.GetIOTaskRunner(), [&]() { // 'SkiaUnrefQueue.Drain' will be called after 'io_manager.reset()' in this // test, If the resource context has been destroyed at that time, it will // crash. // // 'Drain()' currently checks whether the weak pointer is still valid or not // before trying to call anything on it. // // However, calling 'unref' on the 'SkImage_Lazy' ends up freeing a // 'GrBackendTexture'. That object seems to assume that something else is // keeping the context alive. This seems like it might be a bad assumption // on Skia's part, but in Skia's defense we're doing something pretty weird // here by keeping GPU resident objects alive without keeping the // 'GrDirectContext' alive ourselves. // // See https://github.com/flutter/flutter/issues/87895 io_manager.reset(); gl_surface.reset(); }); } } // namespace testing } // namespace flutter
35.065693
80
0.673189
[ "object" ]
b1af8415a89c9d19889e43e4ab6e90d807257d2f
2,843
cpp
C++
Convexhull.cpp
chauhan0707/Coding
760aea49bb468e191ec8f5aa3e3bda1e70018908
[ "MIT" ]
2
2020-09-05T18:20:17.000Z
2020-10-06T16:13:11.000Z
Convexhull.cpp
chauhan0707/Coding
760aea49bb468e191ec8f5aa3e3bda1e70018908
[ "MIT" ]
null
null
null
Convexhull.cpp
chauhan0707/Coding
760aea49bb468e191ec8f5aa3e3bda1e70018908
[ "MIT" ]
null
null
null
#include<iostream> #include<stack> #include<algorithm> #include<vector> using namespace std; struct point { //define points for 2d plane int x, y; }; point p0; //used to another two points point secondTop(stack<point> &stk) { point tempPoint = stk.top(); stk.pop(); point res = stk.top(); //get the second top element stk.push(tempPoint); //push previous top again return res; } int squaredDist(point p1, point p2) { return ((p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y)); } int direction(point a, point b, point c) { int val = (b.y-a.y)*(c.x-b.x)-(b.x-a.x)*(c.y-b.y); if (val == 0) return 0; //colinear else if(val < 0) return 2; //anti-clockwise direction return 1; //clockwise direction } int comp(const void *point1, const void*point2) { point *p1 = (point*)point1; point *p2 = (point*)point2; int dir = direction(p0, *p1, *p2); if(dir == 0) return (squaredDist(p0, *p2) >= squaredDist(p0, *p1))?-1 : 1; return (dir==2)? -1 : 1; } vector<point> findConvexHull(point points[], int n) { vector<point> convexHullPoints; int minY = points[0].y, min = 0; for(int i = 1; i<n; i++) { int y = points[i].y; //find bottom most or left most point if((y < minY) || (minY == y) && points[i].x < points[min].x) { minY = points[i].y; min = i; } } swap(points[0], points[min]); //swap min point to 0th location p0 = points[0]; qsort(&points[1], n-1, sizeof(point), comp); //sort points from 1 place to end int arrSize = 1; //used to locate items in modified array for(int i = 1; i<n; i++) { //when the angle of ith and (i+1)th elements are same, remove points while(i < n-1 && direction(p0, points[i], points[i+1]) == 0) i++; points[arrSize] = points[i]; arrSize++; } if(arrSize < 3) return convexHullPoints; stack<point> stk; stk.push(points[0]); stk.push(points[1]); stk.push(points[2]); for(int i = 3; i<arrSize; i++) { //for remaining vertices while(direction(secondTop(stk), stk.top(), points[i]) != 2) stk.pop(); //when top, second top and ith point are not making left turn, remove point stk.push(points[i]); } while(!stk.empty()) { convexHullPoints.push_back(stk.top()); //add points from stack stk.pop(); } } int main() { point points[] = {{-7,8},{-4,6},{2,6},{6,4},{8,6},{7,-2},{4,-6},{8,-7},{0,0}, {3,-2},{6,-10},{0,-6},{-9,-5},{-8,-2},{-8,0},{-10,3},{-2,2},{-10,4}}; int n = 18; vector<point> result; result = findConvexHull(points, n); cout << "Boundary points of convex hull are: "<<endl; vector<point>::iterator it; for(it = result.begin(); it!=result.end(); it++) cout << "(" << it->x << ", " <<it->y <<") "; }
34.253012
98
0.560324
[ "vector" ]
b1b3cd42f33763c9f23223387ee4fd31581f0be6
12,071
cc
C++
device/vr/openvr/test/fake_openvr_impl_api.cc
avaer/overlay
6833fa7793fc1f0fffeea45efdfcfe13662389a3
[ "MIT" ]
null
null
null
device/vr/openvr/test/fake_openvr_impl_api.cc
avaer/overlay
6833fa7793fc1f0fffeea45efdfcfe13662389a3
[ "MIT" ]
null
null
null
device/vr/openvr/test/fake_openvr_impl_api.cc
avaer/overlay
6833fa7793fc1f0fffeea45efdfcfe13662389a3
[ "MIT" ]
2
2021-05-09T13:19:25.000Z
2021-07-03T22:36:08.000Z
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /* cd C:\Users\avaer\Documents\GitHub\metachromium\bin cmake -DCMAKE_GENERATOR_PLATFORM=x64 -DCMAKE_BUILD_TYPE=Release .. msbuild /p:Configuration=Release ALL_BUILD.vcxproj msbuild /p:Configuration=Release /t:Clean ALL_BUILD.vcxproj cd C:\Users\avaer\Documents\GitHub\metachromium\device\vr\build\metachromium\bin set VR_OVERRIDE=C:\Users\avaer\Documents\GitHub\metachromium\device\vr\build\metachromium\ set VR_CONFIG_PATH=C:\Users\avaer\Documents\GitHub\metachromium\device\vr\config\ set VR_LOG_PATH=C:\Users\avaer\Documents\GitHub\metachromium\device\vr\log\ set PATH=%PATH%;C:\Users\avaer\Documents\GitHub\metachromium\device\vr\build\metachromium\bin VR_OVERRIDE=C:\Users\avaer\Documents\GitHub\metachromium\device\vr\build\metachromium\; VR_CONFIG_PATH=C:\Users\avaer\Documents\GitHub\metachromium\device\vr\config\; VR_LOG_PATH=C:\Users\avaer\Documents\GitHub\metachromium\device\vr\log\; cd C:\Users\avaer\AppData\Local\Chromium\Application .\chrome.exe --enable-features="WebXR,OpenVR" --disable-features="WindowsMixedReality" --no-sandbox --test-type --disable-xr-device-consent-prompt-for-testing C:\Users\avaer\Documents\GitHub\metachromium\extension\index.html --app --disable-xr-device-consent-prompt-for-testing --no-sandbox --add-gpu-appcontainer-caps --add-xr-appcontainer-caps --xr_compositing --allow-third-party-modules --allow-unsecure-dlls --allow-sandbox-debugging --gpu-launcher="C:\Users\avaer\Documents\GitHub\metachromium\device\vr\build\metachromium\bin\process2.exe" --gpu-launcher --no-startup-window --gpu-startup-dialog cd C:\Program Files (x86)\Steam\steamapps\common\Space Pirate Trainer VR .\SpacePirateVR.exe cd C:\Program Files (x86)\Steam\steamapps\common\VRChat .\VRChat.exe cd C:\Program Files (x86)\Steam\steamapps\common\Blocks .\Blocks.exe cd C:\Program Files (x86)\obs-studio\data\obs-plugins\win-capture .\get-graphics-offsets64.exe C:\Windows\System32\cmd.exe /c "set VR_OVERRIDE=C:\Users\avaer\Documents\GitHub\metachromium\device\vr\build\metachromium\ && set VR_CONFIG_PATH=C:\Users\avaer\Documents\GitHub\metachromium\device\vr\config\ && set VR_LOG_PATH=C:\Users\avaer\Documents\GitHub\metachromium\device\vr\log\ && C:\Program Files (x86)\Minecraft Launcher\MinecraftLauncher.exe" */ #include <iostream> // #include <chrono> #include <thread> #include <memory> #include <algorithm> #include <filesystem> #include <D3D11_1.h> #include <DXGI1_4.h> // #include <wrl.h> // #include "device/vr/openvr/test/test_helper.h" // #include "device/vr/test/test_hook.h" // #include "device/vr/windows/d3d11_device_helpers.h" // #include "third_party/openvr/src/headers/openvr.h" // #include "third_party/openvr/src/src/ivrclientcore.h" #include "third_party/openvr/src/src/vrcommon/sharedlibtools_public.h" #include "device/vr/openvr/test/fake_openvr_impl_api.h" #include "device/vr/openvr/test/glcontext.h" // #include "device/vr/sample/hellovr_opengl_main.h" #include "device/vr/OpenOVR/Reimpl/static_bases.gen.h" #include "device/vr/openvr/test/out.h" #include "device/vr/openvr/test/fnproxy.h" #include "device/vr/openvr/test/hijack.h" namespace vr { IVRSystem *g_vrsystem = nullptr; IVRCompositor *g_vrcompositor = nullptr; IVRChaperone *g_vrchaperone = nullptr; IVRChaperoneSetup *g_vrchaperonesetup = nullptr; IVROverlay *g_vroverlay = nullptr; IVRRenderModels *vr::g_vrrendermodels = nullptr; IVRScreenshots *vr::g_vrscreenshots = nullptr; IVRSettings *vr::g_vrsettings = nullptr; IVRExtendedDisplay *vr::g_vrextendeddisplay = nullptr; IVRApplications *vr::g_vrapplications = nullptr; IVRInput *g_vrinput = nullptr; PVRClientCore *g_pvrclientcore = nullptr; PVRSystem *g_pvrsystem = nullptr; PVRCompositor *g_pvrcompositor = nullptr; PVRInput *g_pvrinput = nullptr; PVRScreenshots *g_pvrscreenshots = nullptr; PVRChaperone *g_pvrchaperone = nullptr; PVRChaperoneSetup *g_pvrchaperonesetup = nullptr; PVRSettings *g_pvrsettings = nullptr; PVRRenderModels *g_pvrrendermodels = nullptr; PVRApplications *g_pvrapplications = nullptr; PVROverlay *g_pvroverlay = nullptr; QrEngine *g_pqrengine = nullptr; CvEngine *g_pcvengine = nullptr; } std::string dllDir; std::ofstream out; std::ostream &getOut() { // if (!isProcess) { if (!out.is_open()) { std::string logPath = dllDir + std::string("log") + logSuffix + std::string(".txt"); std::cerr << "logging to: " << logPath << std::endl; out.open(logPath.c_str(), std::ofstream::out|std::ofstream::app|std::ofstream::binary); out << "--------------------------------------------------------------------------------" << std::endl; } return out; /* } else { return std::cout; } */ } void getChildEnvBuf(char *pEnvBuf) { LPSTR lpvEnv = GetEnvironmentStringsA(); std::vector<std::string> vars; for (LPSTR lpszVariable = (LPTSTR)lpvEnv; *lpszVariable; lpszVariable++) { std::string var; while (*lpszVariable) { var += *lpszVariable++; } vars.push_back(std::move(var)); } FreeEnvironmentStrings(lpvEnv); char cwdBuf[MAX_PATH]; if (!GetCurrentDirectory(sizeof(cwdBuf), cwdBuf)) { getOut() << "failed to get current directory" << std::endl; abort(); } { std::string vrOverrideString = "VR_OVERRIDE="; vrOverrideString += cwdBuf; vrOverrideString += R"EOF(\..\)EOF"; bool vrOverrideFound = false; for (size_t i = 0; i < vars.size(); i++) { std::string &s = vars[i]; std::string s2 = s; for (auto &c : s2) { c = toupper(c); } if (s2.rfind("VR_OVERRIDE=", 0) == 0) { s = std::move(vrOverrideString); vrOverrideFound = true; break; } } if (!vrOverrideFound) { vars.push_back(std::move(vrOverrideString)); } } for (auto iter : vars) { const std::string &s = iter; // getOut() << "write arg: " << s << std::endl; memcpy(pEnvBuf, s.c_str(), s.size() + 1); pEnvBuf += s.size() + 1; } pEnvBuf[0] = '\0'; } /* void LocalGetDXGIOutputInfo(int32_t *pAdaterIndex) { vr::g_vrsystem->GetDXGIOutputInfo(pAdaterIndex); } */ void ProxyGetDXGIOutputInfo(int32_t *pAdaterIndex) { vr::g_pvrsystem->GetDXGIOutputInfo(pAdaterIndex); } void ProxyGetRecommendedRenderTargetSize(uint32_t *pWidth, uint32_t *pHeight) { vr::g_pvrsystem->GetRecommendedRenderTargetSize(pWidth, pHeight); } void ProxyGetProjectionRaw(vr::EVREye eye, float *pfLeft, float *pfRight, float *pfTop, float *pfBottom) { vr::g_pvrsystem->GetProjectionRaw(eye, pfLeft, pfRight, pfTop, pfBottom); } float ProxyGetFloat(const char *pchSection, const char *pchSettingsKey, vr::EVRSettingsError *peError) { return vr::g_pvrsettings->GetFloat(pchSection, pchSettingsKey, peError); } // constexpr bool tracing = true; constexpr bool tracing = false; void TRACE(const char *module, const std::function<void()> &fn) { if (tracing) { fn(); } } void wrapExternalOpenVr(std::function<void()> &&fn) { std::vector<char> buf(4096); GetEnvironmentVariable("VR_OVERRIDE", buf.data(), buf.size()); SetEnvironmentVariable("VR_OVERRIDE", ""); fn(); SetEnvironmentVariable("VR_OVERRIDE", buf.data()); } void vrShutdownInternal() { getOut() << "vr shutdown internal" << std::endl; } FnProxy *g_fnp = nullptr; Hijacker *g_hijacker = nullptr; Offsets *g_offsets = nullptr; // char p[] = "C:\\Users\\avaer\\Documents\\GitHub\\chromium-79.0.3945.88\\device\\vr\\build\\metachromium\\bin\\process.exe"; void *shMem = nullptr; // bool hijacked = false; bool isChrome = false; // uint64_t *pFrameCount = nullptr; // GLFWwindow **ppWindow; // size_t *pNumClients = nullptr; extern "C" { void *__imp_VR_GetGenericInterface = nullptr; void *__imp_VR_IsInterfaceVersionVersion = nullptr; void *__imp_VR_GetInitToken = nullptr; void *__imp_VR_IsInterfaceVersion = nullptr; void *__imp_VR_InitInternal2 = nullptr; void *__imp_VR_IsInterfaceVersionValid = nullptr; void *__imp_VR_ShutdownInternal = vrShutdownInternal; void *__imp_VR_IsHmdPresent = nullptr; void *__imp_VR_GetVRInitErrorAsSymbol = nullptr; void *__imp_VR_GetVRInitErrorAsEnglishDescription = nullptr; __declspec(dllexport) void* VRClientCoreFactory(const char* interface_name, int* return_code) { getOut() << "get interface " << interface_name << std::endl; // size_t &id = *((size_t *)shMem + 1); // getOut() << "core 1 " << interface_name << std::endl; // getOut() << "init 6 " << interface_name << std::endl; void *iface = CreateInterfaceByName(interface_name); return iface; } } /* TCHAR processExe[4096] = TEXT("C:\\Users\\avaer\\Documents\\GitHub\\chromium-79.0.3945.88\\device\\vr\\build\\metachromium\\bin\\process.exe"); char lol[] = "lol"; char lol2[] = "lol2"; */ BOOL WINAPI DllMain( _In_ HINSTANCE hinstDLL, _In_ DWORD fdwReason, _In_ LPVOID lpvReserved ) { if (fdwReason == DLL_PROCESS_ATTACH) { // getOut() << "loading paths" << std::endl; char dllPath[MAX_PATH]; HMODULE hm = NULL; if (GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCSTR) &VRClientCoreFactory, &hm) == 0) { int ret = GetLastError(); // getOut() << "GetModuleHandle failed, error = " << ret << std::endl; // Return or however you want to handle an error. getOut() << "dll abort 1" << std::endl; abort(); } if (GetModuleFileName(hm, dllPath, sizeof(dllPath)) == 0) { int ret = GetLastError(); // getOut() << "GetModuleFileName failed, error = " << ret << std::endl; getOut() << "dll abort 2" << std::endl; abort(); } char drive[MAX_PATH]; char dir[MAX_PATH]; // char fname[MAX_PATH]; // char ext[MAX_PATH]; _splitpath(dllPath, drive, dir, nullptr, nullptr); dllDir = drive; dllDir += dir; } getOut() << "dll main " << fdwReason << /*" " << DetourIsHelperProcess() << */ std::endl; if (fdwReason == DLL_PROCESS_ATTACH) { shMem = allocateShared("Local\\OpenVrProxyInit", 1024); g_offsets = (Offsets *)shMem; char moduleFileName[MAX_PATH]; if (!GetModuleFileName(NULL, moduleFileName, sizeof(moduleFileName))) { getOut() << "failed to get executable file name: " << (void *)GetLastError() << std::endl; abort(); } std::string moduleString(moduleFileName); // getOut() << "exe file name: " << moduleFileName << std::endl; isChrome = (moduleString.find("chrome.exe") != std::string::npos); g_fnp = new FnProxy(); g_hijacker = new Hijacker(*g_fnp); vr::g_pvrsystem = new vr::PVRSystem(vr::g_vrsystem, *g_fnp); vr::g_pvrcompositor = new vr::PVRCompositor(vr::g_vrcompositor, *g_hijacker, false, *g_fnp); vr::g_pvrclientcore = new vr::PVRClientCore(vr::g_pvrcompositor, *g_fnp); vr::g_pvrinput = new vr::PVRInput(vr::g_vrinput, *g_fnp); vr::g_pvrscreenshots = new vr::PVRScreenshots(vr::g_vrscreenshots, *g_fnp); vr::g_pvrchaperone = new vr::PVRChaperone(vr::g_vrchaperone, *g_fnp); vr::g_pvrchaperonesetup = new vr::PVRChaperoneSetup(vr::g_vrchaperonesetup, *g_fnp); vr::g_pvrsettings = new vr::PVRSettings(vr::g_vrsettings, *g_fnp); vr::g_pvrrendermodels = new vr::PVRRenderModels(vr::g_vrrendermodels, *g_fnp); vr::g_pvrapplications = new vr::PVRApplications(vr::g_vrapplications, *g_fnp); vr::g_pvroverlay = new vr::PVROverlay(vr::g_vroverlay, *g_fnp); // vr::g_pqrengine = new QrEngine(vr::g_pvrcompositor, vr::g_vrsystem); /* g_hijacker->hijackDxgi(hinstDLL); g_hijacker->hijackGl(); */ std::vector<char> buf(4096); GetEnvironmentVariable("VR_OVERRIDE", buf.data(), buf.size()); getOut() << "init dll " << moduleString << " " << buf.data() << std::endl; } else if (fdwReason == DLL_PROCESS_DETACH) { /* g_hijacker->unhijackDxgi(); g_hijacker->unhijackDx(); g_hijacker->unhijackGl(); */ vr::g_pvrclientcore->Cleanup(); } return true; }
38.320635
355
0.698782
[ "vector" ]
b1b4eb97150d227b6d45df501619283bbadc6a1c
3,499
hpp
C++
control/json/actions/count_state_target.hpp
mikecgithub/phosphor-fan-presence
a66d154ed073fda465616a40670c98979c47ee91
[ "Apache-2.0" ]
8
2017-03-20T22:56:15.000Z
2020-10-28T06:45:05.000Z
control/json/actions/count_state_target.hpp
mikecgithub/phosphor-fan-presence
a66d154ed073fda465616a40670c98979c47ee91
[ "Apache-2.0" ]
25
2017-03-03T15:26:43.000Z
2022-02-11T15:00:39.000Z
control/json/actions/count_state_target.hpp
mikecgithub/phosphor-fan-presence
a66d154ed073fda465616a40670c98979c47ee91
[ "Apache-2.0" ]
9
2017-02-13T18:11:49.000Z
2022-01-19T12:12:46.000Z
/** * Copyright © 2021 IBM Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "../zone.hpp" #include "action.hpp" #include "group.hpp" #include <nlohmann/json.hpp> namespace phosphor::fan::control::json { using json = nlohmann::json; /** * @class CountStateTarget - Action to set a target when members are at a state * * Sets the fans to a configured target when a number of members within the * group are at a configured state. Once the number of members at the given * state falls below the configured count, active fan target changes are * allowed. */ class CountStateTarget : public ActionBase, public ActionRegister<CountStateTarget> { public: /* Name of this action */ static constexpr auto name = "count_state_before_target"; CountStateTarget() = delete; CountStateTarget(const CountStateTarget&) = delete; CountStateTarget(CountStateTarget&&) = delete; CountStateTarget& operator=(const CountStateTarget&) = delete; CountStateTarget& operator=(CountStateTarget&&) = delete; ~CountStateTarget() = default; /** * @brief Set target when a number of members are at a given state * * @param[in] jsonObj - JSON configuration of this action * @param[in] groups - Groups of dbus objects the action uses */ CountStateTarget(const json& jsonObj, const std::vector<Group>& groups); /** * @brief Run the action * * Counts the number of members within a group are equal to a given state * and when the number of members are at or above the given state, the fans * within the zone are set to the configured target. The fans are held at * the configured target until the number of members equal to the given * state fall below the provided count. * * @param[in] zone - Zone to run the action on */ void run(Zone& zone) override; protected: /* Instance id for each instance of this action */ static size_t instanceId; private: /* Number of group members */ size_t _count; /* State the members must be at to set the target */ PropertyVariantType _state; /* Target for this action */ uint64_t _target; /* Unique id of this action */ size_t _id; /** * @brief Parse and set the count * * @param[in] jsonObj - JSON object for the action * * Sets the number of members that must equal the state */ void setCount(const json& jsonObj); /** * @brief Parse and set the state * * @param[in] jsonObj - JSON object for the action * * Sets the state for each member to equal to set the target */ void setState(const json& jsonObj); /** * @brief Parse and set the target * * @param[in] jsonObj - JSON object for the action * * Sets the target to use when running the action */ void setTarget(const json& jsonObj); }; } // namespace phosphor::fan::control::json
29.403361
79
0.674478
[ "object", "vector" ]
b1b5bebb22660d4a60d478dfd7c5533307a55e98
19,478
cpp
C++
planning/behavior_velocity_planner/src/scene_module/intersection/util.cpp
yukke42/autoware.universe
a8e2308e0b9acbd66c7e6d13521ea1320e2fa1d5
[ "Apache-2.0" ]
58
2021-11-30T09:03:46.000Z
2022-03-31T15:25:17.000Z
planning/behavior_velocity_planner/src/scene_module/intersection/util.cpp
yukke42/autoware.universe
a8e2308e0b9acbd66c7e6d13521ea1320e2fa1d5
[ "Apache-2.0" ]
425
2021-11-30T02:24:44.000Z
2022-03-31T10:26:37.000Z
planning/behavior_velocity_planner/src/scene_module/intersection/util.cpp
yukke42/autoware.universe
a8e2308e0b9acbd66c7e6d13521ea1320e2fa1d5
[ "Apache-2.0" ]
69
2021-11-30T02:09:18.000Z
2022-03-31T15:38:29.000Z
// Copyright 2020 Tier IV, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <interpolation/spline_interpolation.hpp> #include <lanelet2_extension/regulatory_elements/road_marking.hpp> #include <lanelet2_extension/utility/query.hpp> #include <lanelet2_extension/utility/utilities.hpp> #include <rclcpp/rclcpp.hpp> #include <scene_module/intersection/util.hpp> #include <utilization/path_utilization.hpp> #include <utilization/util.hpp> #include <lanelet2_core/geometry/Polygon.h> #include <lanelet2_core/primitives/BasicRegulatoryElements.h> #include <algorithm> #include <memory> #include <string> #include <vector> namespace behavior_velocity_planner { namespace bg = boost::geometry; namespace util { int insertPoint( const geometry_msgs::msg::Pose & in_pose, autoware_auto_planning_msgs::msg::PathWithLaneId * inout_path) { static constexpr double dist_thr = 10.0; static constexpr double angle_thr = M_PI / 1.5; int closest_idx = -1; if (!planning_utils::calcClosestIndex(*inout_path, in_pose, closest_idx, dist_thr, angle_thr)) { return -1; } int insert_idx = closest_idx; if (isAheadOf(in_pose, inout_path->points.at(closest_idx).point.pose)) { ++insert_idx; } autoware_auto_planning_msgs::msg::PathPointWithLaneId inserted_point; inserted_point = inout_path->points.at(closest_idx); inserted_point.point.pose = in_pose; auto it = inout_path->points.begin() + insert_idx; inout_path->points.insert(it, inserted_point); return insert_idx; } geometry_msgs::msg::Pose getAheadPose( const size_t start_idx, const double ahead_dist, const autoware_auto_planning_msgs::msg::PathWithLaneId & path) { if (path.points.size() == 0) { return geometry_msgs::msg::Pose{}; } double curr_dist = 0.0; double prev_dist = 0.0; for (size_t i = start_idx; i < path.points.size() - 1; ++i) { const geometry_msgs::msg::Pose p0 = path.points.at(i).point.pose; const geometry_msgs::msg::Pose p1 = path.points.at(i + 1).point.pose; curr_dist += planning_utils::calcDist2d(p0, p1); if (curr_dist > ahead_dist) { const double dl = std::max(curr_dist - prev_dist, 0.0001 /* avoid 0 divide */); const double w_p0 = (curr_dist - ahead_dist) / dl; const double w_p1 = (ahead_dist - prev_dist) / dl; geometry_msgs::msg::Pose p; p.position.x = w_p0 * p0.position.x + w_p1 * p1.position.x; p.position.y = w_p0 * p0.position.y + w_p1 * p1.position.y; p.position.z = w_p0 * p0.position.z + w_p1 * p1.position.z; tf2::Quaternion q0_tf, q1_tf; tf2::fromMsg(p0.orientation, q0_tf); tf2::fromMsg(p1.orientation, q1_tf); p.orientation = tf2::toMsg(q0_tf.slerp(q1_tf, w_p1)); return p; } prev_dist = curr_dist; } return path.points.back().point.pose; } bool setVelocityFrom( const size_t idx, const double vel, autoware_auto_planning_msgs::msg::PathWithLaneId * input) { for (size_t i = idx; i < input->points.size(); ++i) { input->points.at(i).point.longitudinal_velocity_mps = std::min(static_cast<float>(vel), input->points.at(i).point.longitudinal_velocity_mps); } return true; } bool isAheadOf(const geometry_msgs::msg::Pose & target, const geometry_msgs::msg::Pose & origin) { geometry_msgs::msg::Pose p = planning_utils::transformRelCoordinate2D(target, origin); bool is_target_ahead = (p.position.x > 0.0); return is_target_ahead; } bool hasLaneId(const autoware_auto_planning_msgs::msg::PathPointWithLaneId & p, const int id) { for (const auto & pid : p.lane_ids) { if (pid == id) { return true; } } return false; } bool hasDuplicatedPoint( const autoware_auto_planning_msgs::msg::PathWithLaneId & path, const geometry_msgs::msg::Point & point, int * duplicated_point_idx) { for (size_t i = 0; i < path.points.size(); i++) { const auto & p = path.points.at(i).point.pose.position; constexpr double min_dist = 0.001; if (planning_utils::calcDist2d(p, point) < min_dist) { *duplicated_point_idx = static_cast<int>(i); return true; } } return false; } int getFirstPointInsidePolygons( const autoware_auto_planning_msgs::msg::PathWithLaneId & path, const std::vector<lanelet::CompoundPolygon3d> & polygons) { int first_idx_inside_lanelet = -1; for (size_t i = 0; i < path.points.size(); ++i) { bool is_in_lanelet = false; auto p = path.points.at(i).point.pose.position; for (const auto & polygon : polygons) { const auto polygon_2d = lanelet::utils::to2D(polygon); is_in_lanelet = bg::within(to_bg2d(p), polygon_2d); if (is_in_lanelet) { first_idx_inside_lanelet = static_cast<int>(i); break; } } if (is_in_lanelet) { break; } } return first_idx_inside_lanelet; } bool generateStopLine( const int lane_id, const std::vector<lanelet::CompoundPolygon3d> detection_areas, const std::shared_ptr<const PlannerData> & planner_data, const double stop_line_margin, autoware_auto_planning_msgs::msg::PathWithLaneId * original_path, const autoware_auto_planning_msgs::msg::PathWithLaneId & target_path, int * stop_line_idx, int * pass_judge_line_idx, int * first_idx_inside_lane, const rclcpp::Logger logger) { /* set judge line dist */ const double current_vel = planner_data->current_velocity->twist.linear.x; const double current_acc = planner_data->current_accel.get(); const double max_acc = planner_data->max_stop_acceleration_threshold; const double max_jerk = planner_data->max_stop_jerk_threshold; const double delay_response_time = planner_data->delay_response_time; const double pass_judge_line_dist = planning_utils::calcJudgeLineDistWithJerkLimit( current_vel, current_acc, max_acc, max_jerk, delay_response_time); /* set parameters */ constexpr double interval = 0.2; const int margin_idx_dist = std::ceil(stop_line_margin / interval); const int base2front_idx_dist = std::ceil(planner_data->vehicle_info_.max_longitudinal_offset_m / interval); const int pass_judge_idx_dist = std::ceil(pass_judge_line_dist / interval); /* spline interpolation */ autoware_auto_planning_msgs::msg::PathWithLaneId path_ip; if (!splineInterpolate(target_path, interval, &path_ip, logger)) { return false; } /* generate stop point */ // If a stop_line is defined in lanelet_map, use it. // else, generates a local stop_line with considering the lane conflicts. int first_idx_ip_inside_lane; // first stop point index for interpolated path. int stop_idx_ip; // stop point index for interpolated path. if (getStopPoseIndexFromMap(path_ip, lane_id, planner_data, stop_idx_ip, 10.0, logger)) { stop_idx_ip = std::max(stop_idx_ip - base2front_idx_dist, 0); } else { // get idx of first_inside_lane point first_idx_ip_inside_lane = getFirstPointInsidePolygons(path_ip, detection_areas); if (first_idx_ip_inside_lane == -1) { RCLCPP_DEBUG(logger, "generate stopline, but no intersect line found."); return false; } // only for visualization const auto first_inside_point = path_ip.points.at(first_idx_ip_inside_lane).point.pose; planning_utils::calcClosestIndex( *original_path, first_inside_point, *first_idx_inside_lane, 10.0); if (*first_idx_inside_lane == 0) { RCLCPP_DEBUG( logger, "path[0] is already in the detection area. This happens if you have " "already crossed the stop line or are very far from the intersection. Ignore computation."); *stop_line_idx = 0; *pass_judge_line_idx = 0; return true; } stop_idx_ip = std::max(first_idx_ip_inside_lane - 1 - margin_idx_dist - base2front_idx_dist, 0); } /* insert stop_point */ const auto inserted_stop_point = path_ip.points.at(stop_idx_ip).point.pose; // if path has too close (= duplicated) point to the stop point, do not insert it // and consider the index of the duplicated point as stop_line_idx if (!util::hasDuplicatedPoint(*original_path, inserted_stop_point.position, stop_line_idx)) { *stop_line_idx = util::insertPoint(inserted_stop_point, original_path); } /* if another stop point exist before intersection stop_line, disable judge_line. */ bool has_prior_stopline = false; for (int i = 0; i < *stop_line_idx; ++i) { if (std::fabs(original_path->points.at(i).point.longitudinal_velocity_mps) < 0.1) { has_prior_stopline = true; break; } } /* insert judge point */ const int pass_judge_idx_ip = std::min( static_cast<int>(path_ip.points.size()) - 1, std::max(stop_idx_ip - pass_judge_idx_dist, 0)); if (has_prior_stopline || stop_idx_ip == pass_judge_idx_ip) { *pass_judge_line_idx = *stop_line_idx; } else { const auto inserted_pass_judge_point = path_ip.points.at(pass_judge_idx_ip).point.pose; // if path has too close (= duplicated) point to the pass judge point, do not insert it // and consider the index of the duplicated point as pass_judge_line_idx if (!util::hasDuplicatedPoint( *original_path, inserted_pass_judge_point.position, pass_judge_line_idx)) { *pass_judge_line_idx = util::insertPoint(inserted_pass_judge_point, original_path); ++(*stop_line_idx); // stop index is incremented by judge line insertion } } RCLCPP_DEBUG( logger, "generateStopLine() : stop_idx = %d, pass_judge_idx = %d, stop_idx_ip = " "%d, pass_judge_idx_ip = %d, has_prior_stopline = %d", *stop_line_idx, *pass_judge_line_idx, stop_idx_ip, pass_judge_idx_ip, has_prior_stopline); return true; } bool getStopPoseIndexFromMap( const autoware_auto_planning_msgs::msg::PathWithLaneId & path, const int lane_id, const std::shared_ptr<const PlannerData> & planner_data, int & stop_idx_ip, int dist_thr, const rclcpp::Logger logger) { lanelet::ConstLanelet lanelet = planner_data->route_handler_->getLaneletMapPtr()->laneletLayer.get(lane_id); const auto road_markings = lanelet.regulatoryElementsAs<lanelet::autoware::RoadMarking>(); lanelet::ConstLineStrings3d stop_line; for (const auto & road_marking : road_markings) { const std::string type = road_marking->roadMarking().attributeOr(lanelet::AttributeName::Type, "none"); if (type == lanelet::AttributeValueString::StopLine) { stop_line.push_back(road_marking->roadMarking()); break; // only one stop_line exists. } } if (stop_line.empty()) { return false; } const auto p_start = stop_line.front().front(); const auto p_end = stop_line.front().back(); const LineString2d extended_stop_line = planning_utils::extendLine(p_start, p_end, planner_data->stop_line_extend_length); for (size_t i = 0; i < path.points.size() - 1; i++) { const auto & p_front = path.points.at(i).point.pose.position; const auto & p_back = path.points.at(i + 1).point.pose.position; const LineString2d path_segment = {{p_front.x, p_front.y}, {p_back.x, p_back.y}}; std::vector<Point2d> collision_points; bg::intersection(extended_stop_line, path_segment, collision_points); if (collision_points.empty()) { continue; } stop_idx_ip = i; RCLCPP_DEBUG(logger, "found collision point"); return true; } geometry_msgs::msg::Point stop_point_from_map; stop_point_from_map.x = 0.5 * (p_start.x() + p_end.x()); stop_point_from_map.y = 0.5 * (p_start.y() + p_end.y()); stop_point_from_map.z = 0.5 * (p_start.z() + p_end.z()); if (!planning_utils::calcClosestIndex(path, stop_point_from_map, stop_idx_ip, dist_thr)) { RCLCPP_DEBUG(logger, "found stop line, but not found stop index"); return false; } RCLCPP_DEBUG(logger, "found stop line and stop index"); return true; } bool getObjectiveLanelets( lanelet::LaneletMapConstPtr lanelet_map_ptr, lanelet::routing::RoutingGraphPtr routing_graph_ptr, const int lane_id, const double detection_area_length, double right_margin, double left_margin, std::vector<lanelet::ConstLanelets> * conflicting_lanelets_result, std::vector<lanelet::ConstLanelets> * objective_lanelets_result, std::vector<lanelet::ConstLanelets> * objective_lanelets_with_margin_result, const rclcpp::Logger logger) { const auto & assigned_lanelet = lanelet_map_ptr->laneletLayer.get(lane_id); lanelet::ConstLanelets yield_lanelets; // for low priority lane // If ego_lane has right of way (i.e. is high priority), // ignore yieldLanelets (i.e. low priority lanes) const auto right_of_ways = assigned_lanelet.regulatoryElementsAs<lanelet::RightOfWay>(); for (const auto & right_of_way : right_of_ways) { if (lanelet::utils::contains(right_of_way->rightOfWayLanelets(), assigned_lanelet)) { for (const auto & yield_lanelet : right_of_way->yieldLanelets()) { yield_lanelets.push_back(yield_lanelet); for (const auto & previous_lanelet : routing_graph_ptr->previous(yield_lanelet)) { yield_lanelets.push_back(previous_lanelet); } } } } lanelet::ConstLanelets ego_lanelets; // for the behind ego-car lane. for (const auto & previous_lanelet : routing_graph_ptr->previous(assigned_lanelet)) { ego_lanelets.push_back(previous_lanelet); for (const auto & following_lanelet : routing_graph_ptr->following(previous_lanelet)) { if (lanelet::utils::contains(ego_lanelets, following_lanelet)) { continue; } ego_lanelets.push_back(following_lanelet); } } // get conflicting lanes on assigned lanelet const auto & conflicting_lanelets = lanelet::utils::getConflictingLanelets(routing_graph_ptr, assigned_lanelet); std::vector<lanelet::ConstLanelets> // conflicting lanes with "lane_id" conflicting_lanelets_ex_yield_ego; // excluding ego lanes and yield lanes std::vector<lanelet::ConstLanelets> objective_lanelets; // final objective lanelets std::vector<lanelet::ConstLanelets> objective_lanelets_with_margin; // final objective lanelets // exclude yield lanelets and ego lanelets from objective_lanelets for (const auto & conflicting_lanelet : conflicting_lanelets) { if (lanelet::utils::contains(yield_lanelets, conflicting_lanelet)) { continue; } if (lanelet::utils::contains(ego_lanelets, conflicting_lanelet)) { continue; } const auto objective_lanelet_with_margin = generateOffsetLanelet(conflicting_lanelet, right_margin, left_margin); conflicting_lanelets_ex_yield_ego.push_back({conflicting_lanelet}); objective_lanelets.push_back({conflicting_lanelet}); objective_lanelets_with_margin.push_back({objective_lanelet_with_margin}); } // get possible lanelet path that reaches conflicting_lane longer than given length const double length = detection_area_length; std::vector<lanelet::ConstLanelets> objective_lanelets_sequences; for (const auto & ll : objective_lanelets) { // Preceding lanes does not include objective_lane so add them at the end objective_lanelets_sequences.push_back(ll); // get preceding lanelets without ego_lanelets // to prevent the detection area from including the ego lanes and its' preceding lanes. const auto lanelet_sequences = lanelet::utils::query::getPrecedingLaneletSequences( routing_graph_ptr, ll.front(), length, ego_lanelets); for (auto & l : lanelet_sequences) { objective_lanelets_sequences.push_back(l); } } *conflicting_lanelets_result = conflicting_lanelets_ex_yield_ego; *objective_lanelets_result = objective_lanelets_sequences; *objective_lanelets_with_margin_result = objective_lanelets_with_margin; std::stringstream ss_c, ss_y, ss_e, ss_o, ss_os; for (const auto & l : conflicting_lanelets) { ss_c << l.id() << ", "; } for (const auto & l : yield_lanelets) { ss_y << l.id() << ", "; } for (const auto & l : ego_lanelets) { ss_e << l.id() << ", "; } for (const auto & l : objective_lanelets) { ss_o << l.front().id() << ", "; } for (const auto & l : objective_lanelets_sequences) { for (const auto & ll : l) { ss_os << ll.id() << ", "; } } RCLCPP_DEBUG( logger, "getObjectiveLanelets() conflict = %s yield = %s ego = %s", ss_c.str().c_str(), ss_y.str().c_str(), ss_e.str().c_str()); RCLCPP_DEBUG( logger, "getObjectiveLanelets() object = %s object_sequences = %s", ss_o.str().c_str(), ss_os.str().c_str()); return true; } std::vector<lanelet::CompoundPolygon3d> getPolygon3dFromLaneletsVec( const std::vector<lanelet::ConstLanelets> & ll_vec, double clip_length) { std::vector<lanelet::CompoundPolygon3d> p_vec; for (const auto & ll : ll_vec) { const double path_length = lanelet::utils::getLaneletLength3d(ll); const auto polygon3d = lanelet::utils::getPolygonFromArcLength(ll, path_length - clip_length, path_length); p_vec.push_back(polygon3d); } return p_vec; } std::vector<int> getLaneletIdsFromLaneletsVec(const std::vector<lanelet::ConstLanelets> & ll_vec) { std::vector<int> id_list; for (const auto & lls : ll_vec) { for (const auto & ll : lls) { id_list.emplace_back(ll.id()); } } return id_list; } double calcArcLengthFromPath( const autoware_auto_planning_msgs::msg::PathWithLaneId & input_path, const size_t src_idx, const size_t dst_idx) { double length{0.0}; for (size_t i = src_idx; i < dst_idx; ++i) { const double dx_wp = input_path.points.at(i + 1).point.pose.position.x - input_path.points.at(i).point.pose.position.x; const double dy_wp = input_path.points.at(i + 1).point.pose.position.y - input_path.points.at(i).point.pose.position.y; length += std::hypot(dx_wp, dy_wp); } return length; } lanelet::ConstLanelet generateOffsetLanelet( const lanelet::ConstLanelet lanelet, double right_margin, double left_margin) { lanelet::Points3d lefts, rights; const double right_offset = right_margin; const double left_offset = left_margin; const auto offset_rightBound = lanelet::utils::getRightBoundWithOffset(lanelet, right_offset); const auto offset_leftBound = lanelet::utils::getLeftBoundWithOffset(lanelet, left_offset); const auto original_left_bound = offset_leftBound; const auto original_right_bound = offset_rightBound; for (const auto & pt : original_left_bound) { lefts.push_back(lanelet::Point3d(pt)); } for (const auto & pt : original_right_bound) { rights.push_back(lanelet::Point3d(pt)); } const auto left_bound = lanelet::LineString3d(lanelet::InvalId, lefts); const auto right_bound = lanelet::LineString3d(lanelet::InvalId, rights); auto lanelet_with_margin = lanelet::Lanelet(lanelet::InvalId, left_bound, right_bound); const auto centerline = lanelet::utils::generateFineCenterline(lanelet_with_margin, 5.0); lanelet_with_margin.setCenterline(centerline); return std::move(lanelet_with_margin); } } // namespace util } // namespace behavior_velocity_planner
38.723658
100
0.720505
[ "geometry", "object", "vector" ]
b1b8fb899c68d13abe820225a641f8941122fcaf
11,183
cpp
C++
common/libex/src/ex_log.cpp
tinygg/teleport
5ac759c707d355767a209e29becaadf250b0e366
[ "Apache-2.0" ]
1
2021-05-28T11:22:15.000Z
2021-05-28T11:22:15.000Z
common/libex/src/ex_log.cpp
tinygg/teleport
5ac759c707d355767a209e29becaadf250b0e366
[ "Apache-2.0" ]
null
null
null
common/libex/src/ex_log.cpp
tinygg/teleport
5ac759c707d355767a209e29becaadf250b0e366
[ "Apache-2.0" ]
null
null
null
#include <ex/ex_log.h> #include <ex/ex_path.h> //#include <ex/ex_thread.h> //#include <vector> //#include <deque> //#include <algorithm> #ifdef EX_OS_WIN32 # include <io.h> # include <stdio.h> # include <direct.h> #else //# include <dirent.h> //# include <sys/time.h> #endif #define EX_LOG_CONTENT_MAX_LEN 2048 //typedef std::deque<unsigned long long> log_file_deque; static ExLogger* g_exlog = NULL; void EXLOG_USE_LOGGER(ExLogger* logger) { g_exlog = logger; } void EXLOG_LEVEL(int min_level) { if(NULL != g_exlog) g_exlog->min_level = min_level; } void EXLOG_DEBUG(bool debug_mode) { if (NULL != g_exlog) g_exlog->debug_mode = debug_mode; } void EXLOG_CONSOLE(bool output_to_console) { if(NULL != g_exlog) g_exlog->to_console = output_to_console; } void EXLOG_FILE(const wchar_t* log_file, const wchar_t* log_path /*= NULL*/, ex_u32 max_filesize /*= EX_LOG_FILE_MAX_SIZE*/, ex_u8 max_filecount /*= EX_LOG_FILE_MAX_COUNT*/) { if(NULL == g_exlog) return; ex_wstr _path; if (NULL == log_path) { ex_exec_file(_path); ex_dirname(_path); ex_path_join(_path, false, L"log", NULL); } else { _path = log_path; } g_exlog->set_log_file(_path, log_file, max_filesize, max_filecount); } ExLogger::ExLogger() { #ifdef EX_OS_WIN32 console_handle = GetStdHandle(STD_OUTPUT_HANDLE); #endif min_level = EX_LOG_LEVEL_INFO; debug_mode = false; to_console = true; m_file = NULL; m_filesize = 0; } ExLogger::~ExLogger() { if (NULL != m_file) { #ifdef EX_OS_WIN32 CloseHandle(m_file); #else fclose(m_file); #endif m_file = NULL; } } void ExLogger::log_a(int level, const char* fmt, va_list valist) { if (NULL == fmt) return; if (0 == strlen(fmt)) return; char szTmp[4096] = { 0 }; size_t offset = 0; if (level == EX_LOG_LEVEL_ERROR) { szTmp[0] = '['; szTmp[1] = 'E'; szTmp[2] = ']'; szTmp[3] = ' '; offset = 4; } #ifdef EX_OS_WIN32 vsnprintf_s(szTmp+offset, 4096-offset, 4095-offset, fmt, valist); if(to_console) { if (NULL != console_handle) { printf_s("%s", szTmp); fflush(stdout); } else { if(debug_mode) OutputDebugStringA(szTmp); } } #else vsnprintf(szTmp+offset, 4095-offset, fmt, valist); if(to_console) { // On linux, the stdout only output the first time output format (char or wchar_t). // e.g.: first time you use printf(), then after that, every wprintf() not work, and vice versa. // so we always use wprintf() to fix that. ex_astr tmp(szTmp); ex_wstr _tmp; ex_astr2wstr(tmp, _tmp); wprintf(L"%ls", _tmp.c_str()); fflush(stdout); // printf("%s", szTmp); // fflush(stdout); } #endif write_a(szTmp); } void ExLogger::log_w(int level, const wchar_t* fmt, va_list valist) { if (NULL == fmt || 0 == wcslen(fmt)) return; wchar_t szTmp[4096] = { 0 }; size_t offset = 0; if (level == EX_LOG_LEVEL_ERROR) { szTmp[0] = L'['; szTmp[1] = L'E'; szTmp[2] = L']'; szTmp[3] = L' '; offset = 4; } #ifdef EX_OS_WIN32 _vsnwprintf_s(szTmp+offset, 4096-offset, 4095-offset, fmt, valist); if(to_console) { if (NULL != console_handle) { wprintf_s(_T("%s"), szTmp); fflush(stdout); } else { if(debug_mode) OutputDebugStringW(szTmp); } } #else vswprintf(szTmp+offset, 4095-offset, fmt, valist); if(to_console) { wprintf(L"%ls", szTmp); fflush(stdout); } #endif write_w(szTmp); } #define EX_PRINTF_XA(fn, level) \ void fn(const char* fmt, ...) \ { \ if(NULL == g_exlog) \ return; \ if (g_exlog->min_level > level) \ return; \ ExThreadSmartLock locker(g_exlog->lock); \ va_list valist; \ va_start(valist, fmt); \ g_exlog->log_a(level, fmt, valist); \ va_end(valist); \ } #define EX_PRINTF_XW(fn, level) \ void fn(const wchar_t* fmt, ...) \ { \ if(NULL == g_exlog) \ return; \ if (g_exlog->min_level > level) \ return; \ ExThreadSmartLock locker(g_exlog->lock); \ va_list valist; \ va_start(valist, fmt); \ g_exlog->log_w(level, fmt, valist); \ va_end(valist); \ } EX_PRINTF_XA(ex_printf_d, EX_LOG_LEVEL_DEBUG) EX_PRINTF_XA(ex_printf_v, EX_LOG_LEVEL_VERBOSE) EX_PRINTF_XA(ex_printf_i, EX_LOG_LEVEL_INFO) EX_PRINTF_XA(ex_printf_w, EX_LOG_LEVEL_WARN) EX_PRINTF_XA(ex_printf_e, EX_LOG_LEVEL_ERROR) EX_PRINTF_XW(ex_printf_d, EX_LOG_LEVEL_DEBUG) EX_PRINTF_XW(ex_printf_v, EX_LOG_LEVEL_VERBOSE) EX_PRINTF_XW(ex_printf_i, EX_LOG_LEVEL_INFO) EX_PRINTF_XW(ex_printf_w, EX_LOG_LEVEL_WARN) EX_PRINTF_XW(ex_printf_e, EX_LOG_LEVEL_ERROR) #ifdef EX_OS_WIN32 void ex_printf_e_lasterror(const char* fmt, ...) { ExThreadSmartLock locker(g_exlog->lock); va_list valist; va_start(valist, fmt); g_exlog->log_a(EX_LOG_LEVEL_ERROR, fmt, valist); va_end(valist); //========================================= LPVOID lpMsgBuf; DWORD dw = GetLastError(); FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&lpMsgBuf, 0, NULL); ex_printf_e(" - WinErr(%d): %s\n", dw, (LPSTR)lpMsgBuf); LocalFree(lpMsgBuf); } void ex_printf_e_lasterror(const wchar_t* fmt, ...) { ExThreadSmartLock locker(g_exlog->lock); va_list valist; va_start(valist, fmt); g_exlog->log_w(EX_LOG_LEVEL_ERROR, fmt, valist); va_end(valist); //========================================= LPVOID lpMsgBuf; DWORD dw = GetLastError(); FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&lpMsgBuf, 0, NULL); ex_printf_e(" - WinErr(%d): %s\n", dw, (LPSTR)lpMsgBuf); LocalFree(lpMsgBuf); } #endif void ex_printf_bin(const ex_u8* bin_data, size_t bin_size, const char* fmt, ...) { if(NULL == g_exlog) return; if (!g_exlog->debug_mode) return; ExThreadSmartLock locker(g_exlog->lock); if (NULL == fmt) return; if (0 == strlen(fmt)) return; char szTmp[128] = { 0 }; // size_t offset = 0; va_list valist; va_start(valist, fmt); #ifdef EX_OS_WIN32 vsnprintf_s(szTmp, 128, 127, fmt, valist); #else vsnprintf(szTmp, 127, fmt, valist); #endif va_end(valist); // // // // // va_list valist; // va_start(valist, fmt); // g_exlog->log_a(EX_LOG_LEVEL_DEBUG, fmt, valist); // va_end(valist); // ex_printf_d("%s (%d/0x%02x Bytes)\n", szTmp, bin_size, bin_size); const ex_u8* line = bin_data; size_t thisline = 0; size_t offset = 0; unsigned int i = 0; // char szTmp[128] = { 0 }; size_t _offset = 0; while (offset < bin_size) { memset(szTmp, 0, 128); _offset = 0; snprintf(szTmp + _offset, 128 - _offset, "%06x ", (int)offset); _offset += 8; thisline = bin_size - offset; if (thisline > 16) thisline = 16; for (i = 0; i < thisline; i++) { snprintf(szTmp + _offset, 128 - _offset, "%02x ", line[i]); _offset += 3; } snprintf(szTmp + _offset, 128 - _offset, " "); _offset += 2; for (; i < 16; i++) { snprintf(szTmp + _offset, 128 - _offset, " "); _offset += 3; } for (i = 0; i < thisline; i++) { snprintf(szTmp + _offset, 128 - _offset, "%c", (line[i] >= 0x20 && line[i] < 0x7f) ? line[i] : '.'); _offset += 1; } snprintf(szTmp + _offset, 128 - _offset, "\n"); _offset += 1; ex_printf_d("%s", szTmp); offset += thisline; line += thisline; } fflush(stdout); } bool ExLogger::set_log_file(const ex_wstr& log_path, const ex_wstr& log_name, ex_u32 max_filesize, ex_u8 max_count) { m_max_filesize = max_filesize; m_max_count = max_count; m_filename = log_name; m_path = log_path; ex_abspath(m_path); ex_mkdirs(m_path); m_fullname = m_path; ex_path_join(m_fullname, false, log_name.c_str(), NULL); return _open_file(); } bool ExLogger::_open_file() { if (m_file) { #ifdef EX_OS_WIN32 CloseHandle(m_file); #else fclose(m_file); #endif m_file = NULL; } #ifdef EX_OS_WIN32 // 注意:这里必须使用 CreateFile() 来打开日志文件,使用FILE指针无法传递给动态库进行操作。 m_file = CreateFileW(m_fullname.c_str(), GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE == m_file) { m_file = NULL; return false; } SetFilePointer(m_file, 0, NULL, FILE_END); m_filesize = GetFileSize(m_file, NULL); #else ex_astr _fullname; ex_wstr2astr(m_fullname, _fullname); m_file = fopen(_fullname.c_str(), "a"); if (NULL == m_file) { return false; } fseek(m_file, 0, SEEK_END); m_filesize = (ex_u32)ftell(m_file); #endif return _rotate_file(); } bool ExLogger::_rotate_file(void) { if (m_filesize < m_max_filesize) return true; if (m_file) { #ifdef EX_OS_WIN32 CloseHandle(m_file); #else fclose(m_file); #endif m_file = NULL; } // make a name for backup file. wchar_t _tmpname[64] = { 0 }; #ifdef EX_OS_WIN32 SYSTEMTIME st; GetLocalTime(&st); swprintf_s(_tmpname, 64, L"%s.%04d%02d%02d%02d%02d%02d.bak", m_filename.c_str(), st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); #else time_t timep; time(&timep); struct tm *p = localtime(&timep); if (p == NULL) return false; ex_wcsformat(_tmpname, 64, L"%ls.%04d%02d%02d%02d%02d%02d.bak", m_filename.c_str(), p->tm_year + 1900, p->tm_mon + 1, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec); #endif ex_wstr _new_fullname(m_path); ex_path_join(_new_fullname, false, _tmpname, NULL); #ifdef EX_OS_WIN32 if (!MoveFileW(m_fullname.c_str(), _new_fullname.c_str())) { EXLOGE_WIN("can not rename log file, remove old one and try again."); DeleteFileW(_new_fullname.c_str()); if (!MoveFileW(m_fullname.c_str(), _new_fullname.c_str())) return false; } #else ex_astr _a_fullname; ex_astr _a_new_fullname; ex_wstr2astr(m_fullname, _a_fullname); ex_wstr2astr(_new_fullname, _a_new_fullname); if (rename(_a_fullname.c_str(), _a_new_fullname.c_str()) != 0) { remove(_a_new_fullname.c_str()); if (0 != (rename(_a_fullname.c_str(), _a_new_fullname.c_str()))) return false; } #endif return _open_file(); } bool ExLogger::write_a(const char* buf) { if (NULL == m_file) return false; size_t len = strlen(buf); if (len > EX_LOG_CONTENT_MAX_LEN) return false; char szTime[100] = { 0 }; #ifdef EX_OS_WIN32 SYSTEMTIME st; GetLocalTime(&st); sprintf_s(szTime, 100, "[%04d-%02d-%02d %02d:%02d:%02d] ", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); int lenTime = strlen(szTime); DWORD dwWritten = 0; WriteFile(m_file, szTime, lenTime, &dwWritten, NULL); m_filesize += lenTime; WriteFile(m_file, buf, len, &dwWritten, NULL); m_filesize += len; FlushFileBuffers(m_file); #else time_t timep; struct tm *p; time(&timep); p = localtime(&timep); if (p == NULL) return false; sprintf(szTime, "[%04d-%02d-%02d %02d:%02d:%02d] ", p->tm_year + 1900, p->tm_mon + 1, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec); size_t lenTime = strlen(szTime); fwrite(szTime, lenTime, 1, m_file); m_filesize += lenTime; fwrite(buf, len, 1, m_file); m_filesize += len; fflush(m_file); #endif return _rotate_file(); } bool ExLogger::write_w(const wchar_t* buf) { ex_astr _buf; ex_wstr2astr(buf, _buf, EX_CODEPAGE_UTF8); return write_a(_buf.c_str()); }
20.632841
173
0.667799
[ "vector" ]
04e24a83f557b9d2b3a69220355ee0bde77e098e
460
hpp
C++
src/Base/Math/Math.hpp
leafwaltz/MoeLP
ac94b17ec404721ece9940be91acf26b8a7f96a3
[ "MIT" ]
null
null
null
src/Base/Math/Math.hpp
leafwaltz/MoeLP
ac94b17ec404721ece9940be91acf26b8a7f96a3
[ "MIT" ]
null
null
null
src/Base/Math/Math.hpp
leafwaltz/MoeLP
ac94b17ec404721ece9940be91acf26b8a7f96a3
[ "MIT" ]
null
null
null
#ifndef MoeLP_Base_Math #define MoeLP_Base_Math #include "Matrix.hpp" #include "Vector.hpp" #include <cmath> #include "../Base.hpp" namespace MoeLP { inline double logSumExp(double x, double y) { const double a = max(x, y); return a + std::log(std::exp(x - a) + std::exp(y - a)); } template<typename ...Other> inline double logSumExp(double arg1, double arg2, Other... other) { return logSumExp(logSumExp(arg1, arg2), other...); } } #endif
16.428571
66
0.671739
[ "vector" ]
04e3d31bcaaad3b416d538170b23bed21d9069d7
21,857
cc
C++
comm/tcp_lstnr.cc
codesloop/codesloop
d66e51c2d898a72624306f611a90364c76deed06
[ "BSD-2-Clause" ]
3
2016-05-09T15:29:29.000Z
2017-11-22T06:16:18.000Z
comm/tcp_lstnr.cc
codesloop/codesloop
d66e51c2d898a72624306f611a90364c76deed06
[ "BSD-2-Clause" ]
null
null
null
comm/tcp_lstnr.cc
codesloop/codesloop
d66e51c2d898a72624306f611a90364c76deed06
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (c) 2008,2009,2010, CodeSLoop Team Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** @file tcp_lstnr.cc @brief TODO: complete description */ #if 0 #ifndef DEBUG #define DEBUG #define DEBUG_ENABLE_INDENT //#define DEBUG_VERBOSE #endif /* DEBUG */ #endif //0 #include "codesloop/common/inpvec.hh" #include "codesloop/common/libev/evwrap.h" #include "codesloop/common/auto_close.hh" #include "codesloop/common/queue.hh" #include "codesloop/common/logger.hh" #include "codesloop/comm/exc.hh" #include "codesloop/comm/tcp_lstnr.hh" #include "codesloop/comm/bfd.hh" #include "codesloop/comm/sai.hh" #include "codesloop/nthread/mutex.hh" #include "codesloop/nthread/thread.hh" #include "codesloop/nthread/thrpool.hh" #include "codesloop/nthread/event.hh" namespace csl { using namespace nthread; using namespace common; namespace comm { namespace tcp { namespace { struct ev_data { ev_io watcher_; struct ev_loop * loop_; connid_t id_; mutex mtx_; bfd bfd_; SAI peer_addr_; ev_data(const ev_data & other) : use_exc_(true) { ENTER_FUNCTION(); THRNORET(exc::rs_not_implemented); LEAVE_FUNCTION(); } ev_data & operator=(const ev_data & other) { ENTER_FUNCTION(); THR(exc::rs_not_implemented,*this); RETURN_FUNCTION(*this); } ev_data( struct ev_loop * loop, int fd, const SAI & sai, connid_t id ) : loop_(loop), id_(id), bfd_(fd), peer_addr_(sai), use_exc_(true) { } CSL_OBJ(csl::comm::anonymous,ev_data); USE_EXC(); }; void lstnr_accept_cb( struct ev_loop *loop, struct ev_io *w, int revents ); void lstnr_wakeup_cb( struct ev_loop *loop, struct ev_async *w, int revents ); void lstnr_timer_cb( struct ev_loop *loop, struct ev_timer *w, int revents ); void lstnr_new_data_cb( struct ev_loop *loop, ev_io *w, int revents ); class conn_queue : public csl::common::queue<ev_data *> { private: mutex mtx_; event evt_; public: void on_new_item() { evt_.notify(); } void on_lock_queue() { mtx_.lock(); } void on_unlock_queue() { mtx_.unlock(); } event & new_item_event() { return evt_; } }; class data_handler : public thread::callback { private: lstnr::impl * lstnr_; conn_queue * queue_; public: data_handler(lstnr::impl * l, conn_queue * q) : lstnr_(l), queue_(q) { } virtual void operator()(void); virtual ~data_handler() { } }; }; struct lstnr::impl { class listener_entry : public thread::callback { private: lstnr::impl * impl_; public: listener_entry(lstnr::impl * i) : impl_(i) { } virtual void operator()(void) { impl_->listener_entry_cb(); } }; typedef inpvec<ev_data> ev_data_vec_t; typedef inpvec<ev_data *> ev_data_ptr_vec_t; SAI addr_; auto_close_socket listener_; struct ev_loop * loop_; ev_io accept_watcher_; ev_async wakeup_watcher_; ev_timer periodic_watcher_; listener_entry entry_; thread listener_thread_; bool stop_me_; mutex mtx_; handler * handler_; ev_data_vec_t ev_pool_; conn_queue new_data_queue_; data_handler new_data_handler_; conn_queue idle_data_queue_; bool stop_me() { bool ret = false; { scoped_mutex m(mtx_); ret = stop_me_; } return ret; } void stop_me(bool yesno) { scoped_mutex m(mtx_); stop_me_ = yesno; } impl() : entry_(this), stop_me_(false), handler_(0), new_data_handler_(this, &new_data_queue_), use_exc_(false) { // create loop object loop_ = ev_loop_new( EVFLAG_AUTO ); // accept watcher init ev_init( &accept_watcher_, lstnr_accept_cb ); accept_watcher_.data = this; // async notifier init ev_async_init( &wakeup_watcher_, lstnr_wakeup_cb ); wakeup_watcher_.data = this; // timer init ev_init( &periodic_watcher_, lstnr_timer_cb ); periodic_watcher_.repeat = 15.0; periodic_watcher_.data = this; // set thread entry listener_thread_.set_entry( entry_ ); } ~impl() { if( loop_ ) ev_loop_destroy( loop_ ); loop_ = 0; } bool init(handler & h, SAI address, int backlog) { ENTER_FUNCTION(); { scoped_mutex m(mtx_); // listener socket and co. init int sock = ::socket( AF_INET, SOCK_STREAM, 0 ); if( sock < 0 ) { THRC(exc::rs_socket_failed,false); } CSL_DEBUGF(L"listener socket:%d created for (%s:%d)", sock, inet_ntoa(address.sin_addr), ntohs(address.sin_port) ); // this ensures that the listener socket will be closed listener_.init(sock); int on = 1; if( ::setsockopt( sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on) ) < 0 ) THRC(exc::rs_setsockopt,false); CSL_DEBUGF(L"setsockopt has set SO_REUSEADDR on %d",sock); if( ::bind( sock, reinterpret_cast<const struct sockaddr *>(&address), sizeof(address) ) < 0 ) THRC(exc::rs_bind_failed,false); CSL_DEBUGF(L"socket %d bound to (%s:%d)", sock, inet_ntoa(address.sin_addr), ntohs(address.sin_port)); if( ::listen( sock, backlog ) < 0 ) THRC(exc::rs_listen_failed,false); CSL_DEBUGF(L"listen(sock:%d,backlog:%d) succeeded",sock,backlog); // set handler handler_ = &h; // save the listener address addr_ = address; // - register async notifier ev_async_start( loop_, &wakeup_watcher_ ); // - register accept watcher ev_io_set( &accept_watcher_, sock, EV_READ ); ev_io_start( loop_, &accept_watcher_ ); } RETURN_FUNCTION(true); } void wakeup_cb( struct ev_async *w, int revents ) { ENTER_FUNCTION(); CSL_DEBUGF( L"wakeup_cb(w,revents:%d)",revents ); // check for stop event if( stop_me() ) { CSL_DEBUGF( L"stop request received" ); remove_all_connections(); // unqueue all event watchers ev_unloop( loop_, EVUNLOOP_ALL ); } else { conn_queue::handler h; // no need to lock internal data here // idle_data_queue_ should be locked by itself while( idle_data_queue_.pop(h) ) { ev_data * dta = *(h.get()); CSL_DEBUGF( L"popped conn_id:%lld from idle connections " "now requeueing it", dta->id_ ); ev_io_start( loop_, &(dta->watcher_) ); if( idle_data_queue_.new_item_event().wait_nb() != true ) { // this should not happen, this shows inconsystency // which should be ironed out of the software THRNORET( exc::rs_internal_state ); } } } LEAVE_FUNCTION(); } void timer_cb( struct ev_timer *w, int revents ) // TODO { ENTER_FUNCTION(); LEAVE_FUNCTION(); } void accept_cb( struct ev_io *w, int revents ) { ENTER_FUNCTION(); CSL_DEBUGF( L"accept conn: fd:%d w->events:%d revents:%d", w->fd, w->events, revents ); SAI addr; socklen_t sz = sizeof(addr); int conn_fd = ::accept( w->fd, reinterpret_cast<struct sockaddr *>(&addr), &sz ); if( conn_fd > 0 ) { ev_data * ed = 0; ev_data_vec_t::iterator * evit_ptr = 0; { scoped_mutex m(mtx_); CSL_DEBUGF( L"accepted conn: %d from %s:%d", conn_fd,inet_ntoa(addr.sin_addr), ntohs(addr.sin_port) ); // initialize iterator ev_data_vec_t::iterator ev_it( ev_pool_.begin() ); // find the first free position ev_data_vec_t::iterator & ev_it_ref( ev_pool_.first_free(ev_it) ); // create the items ed = ev_it_ref.set( loop_, conn_fd, addr, ev_it_ref.get_pos() ); CSL_DEBUG_ASSERT( ed != NULL ); evit_ptr = &ev_it; } // signal connection startup bool cres = false; { scoped_mutex m(ed->mtx_); cres = handler_->on_connected( ed->id_, addr, ed->bfd_ ); } CSL_DEBUG_ASSERT( evit_ptr != 0 ); if( evit_ptr == 0 ) { THRRNORET( exc::rs_internal_state,L"evit_ptr is null" ); } else if( cres == false ) { CSL_DEBUG(L"handler returned FALSE, this tells to close the connection"); scoped_mutex m(mtx_); evit_ptr->free(); } else { CSL_DEBUG(L"handler returned TRUE for connection startup"); // the lock may not neccessary here as libev claims to be threadsafe scoped_mutex m(mtx_); // initialize connection watcher ev_init( &(ed->watcher_), lstnr_new_data_cb ); ed->watcher_.data = this; ev_io_set( &(ed->watcher_), conn_fd, EV_READ ); ev_io_start( loop_, &(ed->watcher_) ); } } else { CSL_DEBUGF( L"accept failed" ); } LEAVE_FUNCTION(); } void process_data_cb( ev_data * dta ) { ENTER_FUNCTION(); bool hres = false; { scoped_mutex m(dta->mtx_); hres = handler_->on_data_arrival( dta->id_, dta->peer_addr_, dta->bfd_ ); } // if( hres == false ) { CSL_DEBUGF( L"handler returned FALSE, this tells to " "remove conn_id:%lld fd:%d", dta->id_, dta->bfd_.file_descriptor() ); remove_connection( dta ); } else { CSL_DEBUGF( L"handler returned TRUE, this tells us to put back " "conn_id:%lld fd:%d into the idle watchers", dta->id_, dta->bfd_.file_descriptor() ); if( dta->bfd_.state() != bfd::ok_ ) { CSL_DEBUGF( L"will not push back conn_id:%lld to idle watchers as " "its state is bad", dta->id_ ); remove_connection( dta ); } else { CSL_DEBUGF( L"pushed conn_id:%lld into the idle watchers queue", dta->id_ ); idle_data_queue_.push( dta ); CSL_DEBUGF( L"waking up the event loop" ); ev_async_send( loop_, &wakeup_watcher_ ); } } LEAVE_FUNCTION(); } void new_data_cb( struct ev_io *w, int revents ) { ENTER_FUNCTION(); ev_data * dta = reinterpret_cast<ev_data *>(w); int fd = dta->bfd_.file_descriptor(); CSL_DEBUGF( L"data arrived on fd:%d conn_id:%lld revents:%d bfd_state:%d", fd, dta->id_, revents, dta->bfd_.state() ); // remove watcher from the loop ev_io_stop( loop_, w ); // try to read data uint32_t timeout_ms = 0; uint64_t res = dta->bfd_.recv_some( timeout_ms ); // check for errors if( dta->bfd_.state() != bfd::ok_ ) { CSL_DEBUGF( L"error during read on fd:%d conn_id:%lld",fd, dta->id_ ); CSL_DEBUGF( L"remove watcher conn_id:%lld from the loop", dta->id_ ); // signal connection close handler_->on_disconnected( dta->id_, dta->peer_addr_ ); // free connection remove_connection( dta ); } else { // hand over the connection to the data handler new_data_queue_.push( dta ); } LEAVE_FUNCTION(); } void remove_connection(ev_data * dta) { ENTER_FUNCTION(); CSL_DEBUG_ASSERT( dta != NULL ); CSL_DEBUGF(L"remove_connection(dta[id:%lld])",dta->id_); scoped_mutex m(mtx_); { dta->mtx_.lock(); ev_pool_.free_at( dta->id_ ); } LEAVE_FUNCTION(); } void remove_all_connections() { ENTER_FUNCTION(); conn_queue::handler h; // remove all idle data here // while( idle_data_queue_.pop(h) ) { ev_data * dta = *(h.get()); CSL_DEBUGF( L"removing idle conn_id:%lld",dta->id_ ); remove_connection( dta ); } // loop through all active connections and remove them { scoped_mutex m(mtx_); ev_data_vec_t::iterator it = ev_pool_.begin(); ev_data * dta = 0; while( (dta=it.next_used()) != 0 ) { CSL_DEBUGF( L"removing active conn_id:%lld",dta->id_ ); remove_connection( dta ); } } LEAVE_FUNCTION(); } void listener_entry_cb( ) { thrpool tpool; // TODO : make these configurable unsigned int min_threads = 1; unsigned int max_threads = 4; unsigned int timeout_ms = 1000; unsigned int attempts = 3; if( tpool.init( min_threads, max_threads, timeout_ms, attempts, new_data_queue_.new_item_event(), new_data_handler_ ) ) { CSL_DEBUGF(L"thread pool started (min:%d max:%d timeout:%d attempts:%d)", min_threads, max_threads, timeout_ms, attempts); CSL_DEBUGF(L"launch loop: %p",loop_); ev_loop( loop_, 0 ); CSL_DEBUGF(L"loop has been stopped: %p",loop_); ev_loop_destroy( loop_ ); loop_ = 0; } else { CSL_DEBUGF(L"not launching loop as the thread pool failed to be started"); } CSL_DEBUGF(L"exiting listener thread"); } bool start() { ENTER_FUNCTION(); bool ret = listener_thread_.start(); if( ret ) { CSL_DEBUGF(L"start waiting for the thread to be really started"); ret = listener_thread_.start_event().wait(); CSL_DEBUGF(L"thread %s",(ret==true?"STARTED":"NOT STARTED")); } CSL_DEBUGF(L"start() => %s",(ret==true?"OK":"FAILED")); RETURN_FUNCTION(ret); } bool stop() { ENTER_FUNCTION(); bool ret = false; // send a wakeup event if not sent before if( stop_me() == false ) { CSL_DEBUGF( L"waking up the event loop" ); stop_me( true ); ev_async_send( loop_, &wakeup_watcher_ ); ev_timer_stop( loop_, &periodic_watcher_ ); } CSL_DEBUGF( L"check if listener_thread_ has exited. if not wait 5 secs" ); if( listener_thread_.exit_event().wait(5000) == false ) { // still running, need insist a bit more CSL_DEBUGF( L"listener thread still running (5s), now shut down the loop" ); ev_unloop( loop_, EVUNLOOP_ALL ); if( listener_thread_.exit_event().wait(3000) == false ) { // listener thread is still running, now close all fds CSL_DEBUGF( L"listener thread still running (8s), now close all connections" ); remove_all_connections( ); if( listener_thread_.exit_event().wait(2000) == false ) { CSL_DEBUGF( L"listener thread still running (10s) kill the thread" ); listener_thread_.stop(); } } } else { CSL_DEBUGF( L"listener exited within 5 secs" ); } RETURN_FUNCTION(ret); } pevent & start_event() { return listener_thread_.start_event(); } pevent & exit_event() { return listener_thread_.exit_event(); } CSL_OBJ(csl::comm, lstnr::impl); USE_EXC(); }; namespace { // // event handlers. these forward the call to the implementation object // void lstnr_accept_cb( struct ev_loop *loop, struct ev_io *w, int revents ) { lstnr::impl * this_ptr = reinterpret_cast<lstnr::impl *>(w->data); this_ptr->accept_cb(w, revents); } void lstnr_wakeup_cb( struct ev_loop *loop, struct ev_async *w, int revents ) { lstnr::impl * this_ptr = reinterpret_cast<lstnr::impl *>(w->data); this_ptr->wakeup_cb(w, revents); } void lstnr_timer_cb( struct ev_loop *loop, struct ev_timer *w, int revents) { lstnr::impl * this_ptr = reinterpret_cast<lstnr::impl *>(w->data); this_ptr->timer_cb(w, revents); } void lstnr_new_data_cb( struct ev_loop *loop, ev_io *w, int revents ) { lstnr::impl * this_ptr = reinterpret_cast<lstnr::impl *>(w->data); this_ptr->new_data_cb(w, revents); } void data_handler::operator()(void) { conn_queue::handler h; if( queue_->pop(h) ) { ev_data * dta = *(h.get()); lstnr_->process_data_cb( dta ); } } } /* forwarding functions */ const SAI & lstnr::own_addr() const { return impl_->addr_; } bool lstnr::init(handler & h, SAI address, int backlog) { return impl_->init(h,address,backlog); } bool lstnr::start() { return impl_->start(); } bool lstnr::stop() { return impl_->stop(); } pevent & lstnr::start_event() { return impl_->start_event(); } pevent & lstnr::exit_event() { return impl_->exit_event(); } /* default constructor, destructor */ lstnr::lstnr() : impl_(new impl()) { } lstnr::~lstnr() { } /* no copy */ lstnr::lstnr(const lstnr & other) : impl_(reinterpret_cast<impl *>(0)) { THRNORET(exc::rs_not_implemented); } lstnr & lstnr::operator=(const lstnr & other) { THR(exc::rs_not_implemented, *this); return *this; } } /* end of ns:tcp */ } /* end of ns:comm */ } /* end of ns::csl */ /* EOF */
30.698034
93
0.505559
[ "object" ]
04e680a9d17277d07ddbd63a47d841a8ef7792f8
14,624
cpp
C++
Samples/4_CUDA_Libraries/cuSolverSp_LowlevelQR/mmio_wrapper.cpp
Study-Repos-Forks/cuda-samples
b312abaa07ffdc1ba6e3d44a9bc1a8e89149c20b
[ "BSD-3-Clause" ]
1
2022-02-10T11:14:31.000Z
2022-02-10T11:14:31.000Z
Samples/4_CUDA_Libraries/cuSolverSp_LowlevelQR/mmio_wrapper.cpp
Study-Repos-Forks/cuda-samples
b312abaa07ffdc1ba6e3d44a9bc1a8e89149c20b
[ "BSD-3-Clause" ]
1
2022-02-28T10:28:48.000Z
2022-02-28T10:28:48.000Z
Samples/4_CUDA_Libraries/cuSolverSp_LowlevelQR/mmio_wrapper.cpp
Study-Repos-Forks/cuda-samples
b312abaa07ffdc1ba6e3d44a9bc1a8e89149c20b
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of NVIDIA CORPORATION nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <cusolverDn.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include "mmio.h" /* avoid Windows warnings (for example: strcpy, fscanf, etc.) */ #if defined(_WIN32) #define _CRT_SECURE_NO_WARNINGS #endif /* various __inline__ __device__ function to initialize a T_ELEM */ template <typename T_ELEM> __inline__ T_ELEM cuGet(int); template <> __inline__ float cuGet<float>(int x) { return float(x); } template <> __inline__ double cuGet<double>(int x) { return double(x); } template <> __inline__ cuComplex cuGet<cuComplex>(int x) { return (make_cuComplex(float(x), 0.0f)); } template <> __inline__ cuDoubleComplex cuGet<cuDoubleComplex>(int x) { return (make_cuDoubleComplex(double(x), 0.0)); } template <typename T_ELEM> __inline__ T_ELEM cuGet(int, int); template <> __inline__ float cuGet<float>(int x, int y) { return float(x); } template <> __inline__ double cuGet<double>(int x, int y) { return double(x); } template <> __inline__ cuComplex cuGet<cuComplex>(int x, int y) { return make_cuComplex(float(x), float(y)); } template <> __inline__ cuDoubleComplex cuGet<cuDoubleComplex>(int x, int y) { return (make_cuDoubleComplex(double(x), double(y))); } template <typename T_ELEM> __inline__ T_ELEM cuGet(float); template <> __inline__ float cuGet<float>(float x) { return float(x); } template <> __inline__ double cuGet<double>(float x) { return double(x); } template <> __inline__ cuComplex cuGet<cuComplex>(float x) { return (make_cuComplex(float(x), 0.0f)); } template <> __inline__ cuDoubleComplex cuGet<cuDoubleComplex>(float x) { return (make_cuDoubleComplex(double(x), 0.0)); } template <typename T_ELEM> __inline__ T_ELEM cuGet(float, float); template <> __inline__ float cuGet<float>(float x, float y) { return float(x); } template <> __inline__ double cuGet<double>(float x, float y) { return double(x); } template <> __inline__ cuComplex cuGet<cuComplex>(float x, float y) { return (make_cuComplex(float(x), float(y))); } template <> __inline__ cuDoubleComplex cuGet<cuDoubleComplex>(float x, float y) { return (make_cuDoubleComplex(double(x), double(y))); } template <typename T_ELEM> __inline__ T_ELEM cuGet(double); template <> __inline__ float cuGet<float>(double x) { return float(x); } template <> __inline__ double cuGet<double>(double x) { return double(x); } template <> __inline__ cuComplex cuGet<cuComplex>(double x) { return (make_cuComplex(float(x), 0.0f)); } template <> __inline__ cuDoubleComplex cuGet<cuDoubleComplex>(double x) { return (make_cuDoubleComplex(double(x), 0.0)); } template <typename T_ELEM> __inline__ T_ELEM cuGet(double, double); template <> __inline__ float cuGet<float>(double x, double y) { return float(x); } template <> __inline__ double cuGet<double>(double x, double y) { return double(x); } template <> __inline__ cuComplex cuGet<cuComplex>(double x, double y) { return (make_cuComplex(float(x), float(y))); } template <> __inline__ cuDoubleComplex cuGet<cuDoubleComplex>(double x, double y) { return (make_cuDoubleComplex(double(x), double(y))); } static void compress_index(const int *Ind, int nnz, int m, int *Ptr, int base) { int i; /* initialize everything to zero */ for (i = 0; i < m + 1; i++) { Ptr[i] = 0; } /* count elements in every row */ Ptr[0] = base; for (i = 0; i < nnz; i++) { Ptr[Ind[i] + (1 - base)]++; } /* add all the values */ for (i = 0; i < m; i++) { Ptr[i + 1] += Ptr[i]; } } struct cooFormat { int i; int j; int p; // permutation }; int cmp_cooFormat_csr(struct cooFormat *s, struct cooFormat *t) { if (s->i < t->i) { return -1; } else if (s->i > t->i) { return 1; } else { return s->j - t->j; } } int cmp_cooFormat_csc(struct cooFormat *s, struct cooFormat *t) { if (s->j < t->j) { return -1; } else if (s->j > t->j) { return 1; } else { return s->i - t->i; } } typedef int (*FUNPTR)(const void *, const void *); typedef int (*FUNPTR2)(struct cooFormat *s, struct cooFormat *t); static FUNPTR2 fptr_array[2] = { cmp_cooFormat_csr, cmp_cooFormat_csc, }; static int verify_pattern(int m, int nnz, int *csrRowPtr, int *csrColInd) { int i, col, start, end, base_index; int error_found = 0; if (nnz != (csrRowPtr[m] - csrRowPtr[0])) { fprintf(stderr, "Error (nnz check failed): (csrRowPtr[%d]=%d - csrRowPtr[%d]=%d) " "!= (nnz=%d)\n", 0, csrRowPtr[0], m, csrRowPtr[m], nnz); error_found = 1; } base_index = csrRowPtr[0]; if ((0 != base_index) && (1 != base_index)) { fprintf(stderr, "Error (base index check failed): base index = %d\n", base_index); error_found = 1; } for (i = 0; (!error_found) && (i < m); i++) { start = csrRowPtr[i] - base_index; end = csrRowPtr[i + 1] - base_index; if (start > end) { fprintf( stderr, "Error (corrupted row): csrRowPtr[%d] (=%d) > csrRowPtr[%d] (=%d)\n", i, start + base_index, i + 1, end + base_index); error_found = 1; } for (col = start; col < end; col++) { if (csrColInd[col] < base_index) { fprintf( stderr, "Error (column vs. base index check failed): csrColInd[%d] < %d\n", col, base_index); error_found = 1; } if ((col < (end - 1)) && (csrColInd[col] >= csrColInd[col + 1])) { fprintf(stderr, "Error (sorting of the column indecis check failed): " "(csrColInd[%d]=%d) >= (csrColInd[%d]=%d)\n", col, csrColInd[col], col + 1, csrColInd[col + 1]); error_found = 1; } } } return error_found; } template <typename T_ELEM> int loadMMSparseMatrix(char *filename, char elem_type, bool csrFormat, int *m, int *n, int *nnz, T_ELEM **aVal, int **aRowInd, int **aColInd, int extendSymMatrix) { MM_typecode matcode; double *tempVal; int *tempRowInd, *tempColInd; double *tval; int *trow, *tcol; int *csrRowPtr, *cscColPtr; int i, j, error, base, count; struct cooFormat *work; /* read the matrix */ error = mm_read_mtx_crd(filename, m, n, nnz, &trow, &tcol, &tval, &matcode); if (error) { fprintf(stderr, "!!!! can not open file: '%s'\n", filename); return 1; } /* start error checking */ if (mm_is_complex(matcode) && ((elem_type != 'z') && (elem_type != 'c'))) { fprintf(stderr, "!!!! complex matrix requires type 'z' or 'c'\n"); return 1; } if (mm_is_dense(matcode) || mm_is_array(matcode) || mm_is_pattern(matcode) /*|| mm_is_integer(matcode)*/) { fprintf( stderr, "!!!! dense, array, pattern and integer matrices are not supported\n"); return 1; } /* if necessary symmetrize the pattern (transform from triangular to full) */ if ((extendSymMatrix) && (mm_is_symmetric(matcode) || mm_is_hermitian(matcode) || mm_is_skew(matcode))) { // count number of non-diagonal elements count = 0; for (i = 0; i < (*nnz); i++) { if (trow[i] != tcol[i]) { count++; } } // allocate space for the symmetrized matrix tempRowInd = (int *)malloc((*nnz + count) * sizeof(int)); tempColInd = (int *)malloc((*nnz + count) * sizeof(int)); if (mm_is_real(matcode) || mm_is_integer(matcode)) { tempVal = (double *)malloc((*nnz + count) * sizeof(double)); } else { tempVal = (double *)malloc(2 * (*nnz + count) * sizeof(double)); } // copy the elements regular and transposed locations for (j = 0, i = 0; i < (*nnz); i++) { tempRowInd[j] = trow[i]; tempColInd[j] = tcol[i]; if (mm_is_real(matcode) || mm_is_integer(matcode)) { tempVal[j] = tval[i]; } else { tempVal[2 * j] = tval[2 * i]; tempVal[2 * j + 1] = tval[2 * i + 1]; } j++; if (trow[i] != tcol[i]) { tempRowInd[j] = tcol[i]; tempColInd[j] = trow[i]; if (mm_is_real(matcode) || mm_is_integer(matcode)) { if (mm_is_skew(matcode)) { tempVal[j] = -tval[i]; } else { tempVal[j] = tval[i]; } } else { if (mm_is_hermitian(matcode)) { tempVal[2 * j] = tval[2 * i]; tempVal[2 * j + 1] = -tval[2 * i + 1]; } else { tempVal[2 * j] = tval[2 * i]; tempVal[2 * j + 1] = tval[2 * i + 1]; } } j++; } } (*nnz) += count; // free temporary storage free(trow); free(tcol); free(tval); } else { tempRowInd = trow; tempColInd = tcol; tempVal = tval; } // life time of (trow, tcol, tval) is over. // please use COO format (tempRowInd, tempColInd, tempVal) // use qsort to sort COO format work = (struct cooFormat *)malloc(sizeof(struct cooFormat) * (*nnz)); if (NULL == work) { fprintf(stderr, "!!!! allocation error, malloc failed\n"); return 1; } for (i = 0; i < (*nnz); i++) { work[i].i = tempRowInd[i]; work[i].j = tempColInd[i]; work[i].p = i; // permutation is identity } if (csrFormat) { /* create row-major ordering of indices (sorted by row and within each row * by column) */ qsort(work, *nnz, sizeof(struct cooFormat), (FUNPTR)fptr_array[0]); } else { /* create column-major ordering of indices (sorted by column and within each * column by row) */ qsort(work, *nnz, sizeof(struct cooFormat), (FUNPTR)fptr_array[1]); } // (tempRowInd, tempColInd) is sorted either by row-major or by col-major for (i = 0; i < (*nnz); i++) { tempRowInd[i] = work[i].i; tempColInd[i] = work[i].j; } // setup base // check if there is any row/col 0, if so base-0 // check if there is any row/col equal to matrix dimension m/n, if so base-1 int base0 = 0; int base1 = 0; for (i = 0; i < (*nnz); i++) { const int row = tempRowInd[i]; const int col = tempColInd[i]; if ((0 == row) || (0 == col)) { base0 = 1; } if ((*m == row) || (*n == col)) { base1 = 1; } } if (base0 && base1) { printf("Error: input matrix is base-0 and base-1 \n"); return 1; } base = 0; if (base1) { base = 1; } /* compress the appropriate indices */ if (csrFormat) { /* CSR format (assuming row-major format) */ csrRowPtr = (int *)malloc(((*m) + 1) * sizeof(csrRowPtr[0])); if (!csrRowPtr) return 1; compress_index(tempRowInd, *nnz, *m, csrRowPtr, base); *aRowInd = csrRowPtr; *aColInd = (int *)malloc((*nnz) * sizeof(int)); } else { /* CSC format (assuming column-major format) */ cscColPtr = (int *)malloc(((*n) + 1) * sizeof(cscColPtr[0])); if (!cscColPtr) return 1; compress_index(tempColInd, *nnz, *n, cscColPtr, base); *aColInd = cscColPtr; *aRowInd = (int *)malloc((*nnz) * sizeof(int)); } /* transfrom the matrix values of type double into one of the cusparse library * types */ *aVal = (T_ELEM *)malloc((*nnz) * sizeof(T_ELEM)); for (i = 0; i < (*nnz); i++) { if (csrFormat) { (*aColInd)[i] = tempColInd[i]; } else { (*aRowInd)[i] = tempRowInd[i]; } if (mm_is_real(matcode) || mm_is_integer(matcode)) { (*aVal)[i] = cuGet<T_ELEM>(tempVal[work[i].p]); } else { (*aVal)[i] = cuGet<T_ELEM>(tempVal[2 * work[i].p], tempVal[2 * work[i].p + 1]); } } /* check for corruption */ int error_found; if (csrFormat) { error_found = verify_pattern(*m, *nnz, *aRowInd, *aColInd); } else { error_found = verify_pattern(*n, *nnz, *aColInd, *aRowInd); } if (error_found) { fprintf(stderr, "!!!! verify_pattern failed\n"); return 1; } /* cleanup and exit */ free(work); free(tempVal); free(tempColInd); free(tempRowInd); return 0; } /* specific instantiation */ template int loadMMSparseMatrix<float>(char *filename, char elem_type, bool csrFormat, int *m, int *n, int *nnz, float **aVal, int **aRowInd, int **aColInd, int extendSymMatrix); template int loadMMSparseMatrix<double>(char *filename, char elem_type, bool csrFormat, int *m, int *n, int *nnz, double **aVal, int **aRowInd, int **aColInd, int extendSymMatrix); template int loadMMSparseMatrix<cuComplex>(char *filename, char elem_type, bool csrFormat, int *m, int *n, int *nnz, cuComplex **aVal, int **aRowInd, int **aColInd, int extendSymMatrix); template int loadMMSparseMatrix<cuDoubleComplex>( char *filename, char elem_type, bool csrFormat, int *m, int *n, int *nnz, cuDoubleComplex **aVal, int **aRowInd, int **aColInd, int extendSymMatrix);
29.131474
80
0.602229
[ "transform" ]
04e8e3b66938f1db81c87205ed4afca0b584e66c
18,199
cpp
C++
samples/deeplearning/gxm/src/LMDBData.cpp
mjanderson09/libxsmm
d8359effcbe456e1e7625c0b9b0cf5533ee0e370
[ "BSD-3-Clause" ]
1
2018-06-29T03:07:54.000Z
2018-06-29T03:07:54.000Z
samples/deeplearning/gxm/src/LMDBData.cpp
qq332982511/libxsmm
e376c569252c042193ad2215857c35cfb598ec45
[ "BSD-3-Clause" ]
4
2018-03-19T18:18:22.000Z
2018-07-05T05:09:09.000Z
samples/deeplearning/gxm/src/LMDBData.cpp
qq332982511/libxsmm
e376c569252c042193ad2215857c35cfb598ec45
[ "BSD-3-Clause" ]
5
2017-06-28T21:48:18.000Z
2018-04-10T04:07:38.000Z
/****************************************************************************** ** Copyright (c) 2017-2018, Intel Corporation ** ** All rights reserved. ** ** ** ** Redistribution and use in source and binary forms, with or without ** ** modification, are permitted provided that the following conditions ** ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** ** notice, this list of conditions and the following disclaimer. ** ** 2. Redistributions in binary form must reproduce the above copyright ** ** notice, this list of conditions and the following disclaimer in the ** ** documentation and/or other materials provided with the distribution. ** ** 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 without specific prior written permission. ** ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** ** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ** ** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ** ** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ** ** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ** ** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ** ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ******************************************************************************/ /* Sasikanth Avancha, Dhiraj Kalamkar (Intel Corp.) ******************************************************************************/ #include "LMDBData.hpp" using namespace std; using namespace gxm; LMDBDataNode::LMDBDataNode(LMDBDataParams* p, MLEngine* e) : NNNode(p, e) { nname_ = p->get_node_name(); ntype_ = p->get_node_type(); mode_ = p->get_mode(); top_ = p->get_top_names(); bp_flag_ = p->get_bprop_flag(); has_weights_ = false; bot_compute_engine_ = p->get_compute_engine(); //Create output tensor tenTop_.resize(top_.size()); tenTopData_.resize(top_.size()); vector<int> vc = p->get_crop_sizes(); vector<int> vo = p->get_orig_sizes(); assert(vo.size() > 0); for(int i=0; i<top_.size(); i++) { tenTop_[i] = new Tensor(top_[i]); assert(tenTop_[i] != NULL); tenTop_[i]->setOwner(this); tenTopData_[i] = tenTop_[i]->getBuf(DATA); if(top_[i].compare("data") == 0) { tenTop_[i]->setType(INPUT); int dtype = p->get_data_type(); tenTopData_[i]->setDataType(dtype); tenTopData_[i]->setBufferType(DATA); Shape tts; shape_setzero(&tts); tts.ndims = 4; tts.dims[0] = p->get_batch_size(); tts.dims[1] = p->get_channels(); if(vc.size() > 0) { tts.dims[2] = vc[0]; tts.dims[3] = vc[1]; } else { tts.dims[2] = vo[0]; tts.dims[3] = vo[1]; } tenTop_[i]->setShape(&tts); long long int size = 1; for(int j=0; j<tts.ndims; j++) size *= tts.dims[j]; // Size of data tensor buffer = batch_size * channels * height * width * sizeof(float/short int) if(dtype == DT_FLOAT) size = size*sizeof(float); else if(dtype == DT_INT16) size = size*sizeof(short int); tenTopData_[i]->setBufferSize(size); // Register output tensor in tensorMap bool inserted = e->register_tensor(top_[i], INPUT, tenTop_[i]); if(!inserted) printf("Warning: Tensor %s already registered\n",NNNode::top_[i].c_str()); } else if(top_[i].compare("label") == 0) { tenTop_[i]->setType(LABEL); int dtype = p->get_label_data_type(); tenTopData_[i]->setDataType(dtype); tenTopData_[i]->setBufferType(DATA); Shape tts; shape_setzero(&tts); tts.ndims = 1; tts.dims[0] = p->get_batch_size(); tenTop_[i]->setShape(&tts); long long int size = 1; for(int j=0; j<tts.ndims; j++) size *= tts.dims[j]; // Size of label tensor buffer = batch_size*sizeof(int) assert(dtype == DT_INT); size = size*sizeof(int); tenTopData_[i]->setBufferSize(size); // Register output tensor in tensorMap bool inserted = e->register_tensor(top_[i], LABEL, tenTop_[i]); if(!inserted) printf("Warning: Tensor %s already registered\n",NNNode::top_[i].c_str()); } } // If training mode, setup training and validation data files, else only latter int mode = p->get_mode(); ap.mirror = p->get_mirror(); ap.vignette = p->get_vignette(); ap.color_bump = p->get_color_bump(); train_source_path_ = p->get_train_source_path(); test_source_path_ = p->get_test_source_path(); split_db_ = p->get_split_db_flag(); num_machines_ = e->get_num_machines(); num_epochs_ = e->get_num_epochs(); batch_size_ = p->get_batch_size(); global_batch_size_ = batch_size_ * num_machines_; e->set_batch_size(batch_size_); gparams_.channels = p->get_channels(); gparams_.orig_sizes = vo; gparams_.crop_sizes = vc.size() > 0 ? vc : vo; gparams_.batch_size = batch_size_; gparams_.threads = e->get_num_threads(); gparams_.lookahead = p->get_lookahead(); if(p->get_mean_values().size() > 0) gparams_.mean_values = p->get_mean_values(); else if(p->get_mean_file().size() > 0) gparams_.mean_file = p->get_mean_file(); gparams_.scale_values = p->get_scale_values(); gparams_.test_views = p->get_num_test_views(); jitters_ = p->get_jitters(); current_epoch_ = 0; ctrain_pf_mb_ = 0; ctest_pf_mb_ = 0; ctrain_proc_mb_ = 0; ctest_proc_mb_ = 0; curr_test_view_ = 0; full_train_prefetch_ = true; full_test_prefetch_ = true; eptr = e; global_node_id_ = e->get_global_node_id(); tempbuf_.resize(gparams_.lookahead); for(int i=0; i < gparams_.lookahead; i++) tempbuf_[i].resize(gparams_.batch_size); if(mode == TRAIN) { num_train_files_ = p->get_num_train_files(); #ifdef DUMP_ACT_DATA train_batches_ = 2; #elif DUMP_WT_DATA train_batches_ = 10; #else train_batches_ = num_train_files_ % global_batch_size_ > 0 ? (((int)(num_train_files_/global_batch_size_)) + 1) : num_train_files_/global_batch_size_; #endif e->set_num_train_batches(train_batches_); num_test_files_ = p->get_num_test_files(); test_batches_ = num_test_files_ % global_batch_size_ > 0 ? (((int)(num_test_files_/global_batch_size_)) + 1) : num_test_files_/global_batch_size_; e->set_num_test_batches(test_batches_); e->set_num_test_views(gparams_.test_views); } else if(mode == TEST) { num_test_files_ = p->get_num_test_files(); test_batches_ = num_test_files_ % global_batch_size_ > 0 ? (((int)(num_test_files_/global_batch_size_)) + 1) : num_test_files_/global_batch_size_; e->set_num_test_batches(test_batches_); e->set_num_test_views(gparams_.test_views); } #ifdef USE_MLSL MLSL::Session *s = e->get_session(); s->SetGlobalMinibatchSize(global_batch_size_); #endif tenSeeds_ = new unsigned int[gparams_.threads*16]; initSeeds(tenSeeds_, gparams_.threads); r_offset = new int[gparams_.batch_size](); c_offset = new int[gparams_.batch_size](); augmentation = new int[gparams_.batch_size](); configure(); #ifdef USE_MLSL node_id_ = MLSL::Environment::GetEnv().GetProcessIdx(); num_nodes_ = MLSL::Environment::GetEnv().GetProcessCount(); #else node_id_ = 0; num_nodes_ = 1; #endif } void LMDBDataNode::configure() { srand48(global_node_id_); train_lmdb_ = new LMDB(); train_lmdb_->Open(train_source_path_); train_cursor_ = train_lmdb_->NewCursor(); #ifdef USE_MLSL if(node_id_ > 0 && !split_db_) train_cursor_->Next(global_node_id_ - 1); // Each node computes num images to skip. #endif test_lmdb_ = new LMDB(); test_lmdb_->Open(test_source_path_); test_cursor_ = test_lmdb_->NewCursor(); #ifdef USE_MLSL if(node_id_ > 0 && !split_db_) test_cursor_->Next(global_node_id_ - 1); // Each node computes num images to skip. #endif } void LMDBDataNode::trainImageTransform(vector<Datum>& v, float* outp) { int nImg = gparams_.batch_size; int nOfm = gparams_.channels; int ofh = gparams_.crop_sizes[0]; int ofw = gparams_.crop_sizes[1]; // vector<float>& mean = gparams_.mean_values; // vector<float>& scale = gparams_.scale_values; float (* __restrict output)[nOfm][ofh][ofw] = (float (*)[*][*][*])outp; #ifdef _OPENMP #pragma omp parallel for #endif for(int img = 0; img < nImg; img++) { for(int ofm = 0; ofm < nOfm; ofm++) { for(int h = 0; h < ofh; h++) { for(int w = 0; w < ofw; w++) { int ifh = v[img].height(); int ifw = v[img].width(); assert(v[img].channels() == nOfm); const unsigned char (* __restrict input)[ifh][ifw] = (unsigned char (*)[*][*])v[img].data().c_str(); int r_off = r_offset[img]; int c_off = c_offset[img]; float inp = (float)input[ofm][h+r_off][w+c_off]; int fm = (gparams_.scale_values.size() == 1) ? 0 : ofm; if((augmentation[img] < 6) && (ap.mirror == true)) output[img][ofm][h][ofw-w-1] = (inp - gparams_.mean_values[ofm]) * gparams_.scale_values[fm]; else output[img][ofm][h][w] = (inp - gparams_.mean_values[ofm]) * gparams_.scale_values[fm]; } } } } } void LMDBDataNode::testImageTransform(vector<Datum>& v, int tv, float* outp) { int nImg = gparams_.batch_size; int nOfm = gparams_.channels; int ofh = gparams_.crop_sizes[0]; int ofw = gparams_.crop_sizes[1]; // vector<float>& mean = gparams_.mean_values; // vector<float>& scale = gparams_.scale_values; float (* __restrict output)[nOfm][ofh][ofw] = (float (*)[*][*][*])outp; int tv2 = tv/2; #ifdef _OPENMP #pragma omp parallel for #endif for(int i=0; i<nImg; i++) { if(tv % 2 == 0) { if(tv2 == 0) { r_offset[i] = (v[i].height() - ofh)/2; c_offset[i] = (v[i].width() - ofw)/2; } else if(tv2 == 1) { r_offset[i] = 0; c_offset[i] = 0; } else if(tv2 == 2) { r_offset[i] = 0; c_offset[i] = (v[i].width() - ofw); } else if(tv2 == 3) { r_offset[i] = (v[i].height() - ofh); c_offset[i] = 0; } else if(tv2 == 4) { r_offset[i] = v[i].height() - ofh; c_offset[i] = v[i].width() - ofw; } else if(tv2 == 5) { if(gparams_.crop_sizes[0] != gparams_.orig_sizes[0] && gparams_.crop_sizes[1] != gparams_.orig_sizes[1]) { int r = v[i].height() - gparams_.crop_sizes[0] + 1; int c = v[i].width() - gparams_.crop_sizes[1] + 1; r_offset[i] = lrand48() % r; c_offset[i] = lrand48() % c; } } } } #ifdef _OPENMP #pragma omp parallel for #endif for(int img = 0; img < nImg; img++) { for(int ofm = 0; ofm < nOfm; ofm++) { for(int h = 0; h < ofh; h++) { for(int w = 0; w < ofw; w++) { int ifh = v[img].height(); int ifw = v[img].width(); assert(v[img].channels() == nOfm); const unsigned char (* __restrict input)[ifh][ifw] = (const unsigned char (*)[*][*])v[img].data().c_str(); int r_off = r_offset[img]; int c_off = c_offset[img]; float inp = (float)input[ofm][h+r_off][w+c_off]; int fm = (gparams_.scale_values.size() == 1) ? 0 : ofm; if(tv % 2 == 0) output[img][ofm][h][w] = (inp - gparams_.mean_values[ofm]) * gparams_.scale_values[fm]; else output[img][ofm][ofh-h-1][ofw-w-1] = (inp - gparams_.mean_values[ofm]) * gparams_.scale_values[fm]; } } } } } void LMDBDataNode::forwardPropagate() { float *topdata = (float*)(tenTopData_[0]->getBuffer()); int* toplabel = (int*)(tenTopData_[1]->getBuffer()); #if 0 //def DEBUG printf("Executing FP %s: Data %p, Label %p\n", NNNode::nname_.c_str(),topdata, toplabel); #endif int em = eptr->get_execution_mode(); gparams_.exec_mode = em; current_epoch_ = eptr->get_current_epoch(); if(em == TRAIN) { if(full_train_prefetch_) { for(int i=0; i<gparams_.lookahead; i++) { for(int img=0; img<gparams_.batch_size; img++) { tempbuf_[i][img].Clear(); tempbuf_[i][img].ParseFromString(train_cursor_->value()); if(tempbuf_[i][img].channels() == 0) DecodeDatumNative(&(tempbuf_[i][img])); #if 0 //def DEBUG printf("filename: %s label: %d\n",train_cursor_->key().c_str(), tempbuf_[i][img].label()); #endif #ifdef USE_MLSL if(!split_db_) train_cursor_->Next(num_nodes_-1); else train_cursor_->Next(); #else train_cursor_->Next(); #endif } } ctrain_pf_mb_ += gparams_.lookahead; full_train_prefetch_ = false; } else { if(ctrain_pf_mb_ < train_batches_) { for(int img=0; img<gparams_.batch_size; img++) { int i = ctrain_pf_mb_ % gparams_.lookahead; tempbuf_[i][img].Clear(); tempbuf_[i][img].ParseFromString(train_cursor_->value()); if(tempbuf_[i][img].channels() == 0) DecodeDatumNative(&(tempbuf_[i][img])); #if 0 //def DEBUG printf("filename: %s label: %d\n",train_cursor_->key().c_str(), tempbuf_[i][img].label()); #endif #ifdef USE_MLSL if(!split_db_) train_cursor_->Next(num_nodes_-1); else train_cursor_->Next(); #else train_cursor_->Next(); #endif } ctrain_pf_mb_++; } } #ifdef RETURNALL return; #endif int mbslot = ctrain_proc_mb_ % gparams_.lookahead; #ifdef _OPENMP #pragma omp parallel for #endif for(int i=0; i<gparams_.batch_size; i++) toplabel[i] = tempbuf_[mbslot][i].label(); #if !defined(DUMP_ACT_DATA) && !defined(DUMP_WT_DATA) if(gparams_.crop_sizes[0] != gparams_.orig_sizes[0] && gparams_.crop_sizes[1] != gparams_.orig_sizes[1]) { #ifdef _OPENMP #pragma omp parallel for #endif for(int i=0; i<gparams_.batch_size; i++) { int r = tempbuf_[mbslot][i].height() - gparams_.crop_sizes[0] + 1; int c = tempbuf_[mbslot][i].width() - gparams_.crop_sizes[1] + 1; r_offset[i] = lrand48() % r; c_offset[i] = lrand48() % c; augmentation[i] = lrand48() % 12; } } #endif trainImageTransform(tempbuf_[mbslot], topdata); #ifdef GETSTATS int crop_img_size = gparams_.crop_sizes[0]*gparams_.crop_sizes[1]*gparams_.channels; MeanOfLayer("Data", topdata, gparams_.batch_size*crop_img_size); #endif ctrain_proc_mb_++; if(ctrain_proc_mb_ == train_batches_) { ctrain_pf_mb_ = 0; ctrain_proc_mb_ = 0; full_train_prefetch_ = true; } } else if(em == TEST) { if(full_test_prefetch_) { for(int i=0; i<gparams_.lookahead; i++) { for(int img=0; img<gparams_.batch_size; img++) { tempbuf_[i][img].Clear(); tempbuf_[i][img].ParseFromString(test_cursor_->value()); if(tempbuf_[i][img].channels() == 0) DecodeDatumNative(&(tempbuf_[i][img])); #if 0 //def DEBUG printf("filename: %s label: %d\n",test_cursor_->key().c_str(), tempbuf_[i][img].label()); #endif #ifdef USE_MLSL if(!split_db_) test_cursor_->Next(num_nodes_-1); else test_cursor_->Next(); #else test_cursor_->Next(); #endif } } ctest_pf_mb_ += gparams_.lookahead; full_test_prefetch_ = false; } else { { if(ctest_pf_mb_ < test_batches_) { for(int img=0; img<gparams_.batch_size; img++) { int i = ctest_pf_mb_ % gparams_.lookahead; tempbuf_[i][img].Clear(); tempbuf_[i][img].ParseFromString(test_cursor_->value()); if(tempbuf_[i][img].channels() == 0) DecodeDatumNative(&(tempbuf_[i][img])); #if 0 //def DEBUG printf("filename: %s label: %d\n",test_cursor_->key().c_str(), tempbuf_[i][img].label()); #endif #ifdef USE_MLSL if(!split_db_) test_cursor_->Next(num_nodes_-1); else test_cursor_->Next(); #else test_cursor_->Next(); #endif } ctest_pf_mb_++; } } } int mbslot = ctest_proc_mb_ % gparams_.lookahead; #ifdef _OPENMP #pragma omp parallel for #endif for(int i=0; i<gparams_.batch_size; i++) toplabel[i] = tempbuf_[mbslot][i].label(); testImageTransform(tempbuf_[mbslot], curr_test_view_, topdata); curr_test_view_++; if(curr_test_view_ == gparams_.test_views) { curr_test_view_ = 0; ctest_proc_mb_++; if(ctest_proc_mb_ == test_batches_) { ctest_pf_mb_ = 0; ctest_proc_mb_ = 0; full_test_prefetch_ = true; } } } #ifdef DUMP_ACT_DATA int iter = eptr->get_current_batch(); int crop_size = gparams_.batch_size * gparams_.crop_sizes[0] * gparams_.crop_sizes[1] * gparams_.channels; string fname = NNNode::nname_ + "_fp_out_" + to_string(iter); FILE *f = fopen(fname.c_str(), "w"); for(int i=0; i<crop_size; i++) fprintf(f, "%10g\n", topdata[i]); fclose(f); fname = NNNode::nname_ + "_fp_label_" + to_string(iter); f = fopen(fname.c_str(), "w"); for(int i=0; i<gparams_.batch_size; i++) fprintf(f, "%d\n", toplabel[i]); fclose(f); #endif }
30.331667
154
0.594648
[ "shape", "vector" ]
04e9356cb522abd40b869917756c95f7552509ef
20,686
cpp
C++
Jit/inline_cache.cpp
penguin-wwy/cinder
2699849639420e1ed77269a671c0d480efe0981d
[ "CNRI-Python-GPL-Compatible" ]
null
null
null
Jit/inline_cache.cpp
penguin-wwy/cinder
2699849639420e1ed77269a671c0d480efe0981d
[ "CNRI-Python-GPL-Compatible" ]
null
null
null
Jit/inline_cache.cpp
penguin-wwy/cinder
2699849639420e1ed77269a671c0d480efe0981d
[ "CNRI-Python-GPL-Compatible" ]
null
null
null
// Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com) #include "Jit/inline_cache.h" #include "Objects/dict-common.h" #include "Python.h" #include "switchboard.h" #include "Jit/codegen/gen_asm.h" #include "Jit/dict_watch.h" #include <algorithm> // clang-format off #include "internal/pycore_pystate.h" #include "internal/pycore_object.h" #include "structmember.h" // clang-format on namespace jit { namespace { template <class T> struct TypeWatcher { std::unordered_map<BorrowedRef<PyTypeObject>, std::vector<T*>> caches; void watch(BorrowedRef<PyTypeObject> type, T* cache) { caches[type].emplace_back(cache); } void typeChanged(BorrowedRef<PyTypeObject> type) { auto it = caches.find(type); if (it == caches.end()) { return; } std::vector<T*> to_notify = std::move(it->second); caches.erase(it); for (T* cache : to_notify) { cache->typeChanged(type); } } }; TypeWatcher<AttributeCache> ac_watcher; TypeWatcher<LoadTypeAttrCache> ltac_watcher; } // namespace AttributeMutator::AttributeMutator() { reset(); } PyTypeObject* AttributeMutator::type() const { return type_; } void AttributeMutator::reset() { kind_ = Kind::kEmpty; type_ = nullptr; } bool AttributeMutator::isEmpty() const { return kind_ == Kind::kEmpty; } void AttributeMutator::set_combined(PyTypeObject* type) { kind_ = Kind::kCombined; type_ = type; combined_.dict_offset = type->tp_dictoffset; } void AttributeMutator::set_split( PyTypeObject* type, Py_ssize_t val_offset, PyDictKeysObject* keys) { kind_ = Kind::kSplit; type_ = type; split_.dict_offset = type->tp_dictoffset; split_.val_offset = val_offset; split_.keys = keys; } void AttributeMutator::set_data_descr(PyTypeObject* type, PyObject* descr) { kind_ = Kind::kDataDescr; type_ = type; data_descr_.descr = descr; } void AttributeMutator::set_member_descr(PyTypeObject* type, PyObject* descr) { kind_ = Kind::kMemberDescr; type_ = type; member_descr_.memberdef = ((PyMemberDescrObject*)descr)->d_member; } void AttributeMutator::set_descr_or_classvar( PyTypeObject* type, PyObject* descr) { kind_ = Kind::kDescrOrClassVar; type_ = type; descr_or_cvar_.descr = descr; descr_or_cvar_.dictoffset = type->tp_dictoffset; } void AttributeCache::typeChanged(PyTypeObject* type) { for (auto& entry : entries_) { if (entry.type() == type) { entry.reset(); } } } void AttributeCache::fill( BorrowedRef<PyTypeObject> type, BorrowedRef<> name, BorrowedRef<> descr) { if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) { // The type must have a valid version tag in order for us to be able to // invalidate the cache when the type is modified. See the comment at // the top of `PyType_Modified` for more details. return; } AttributeMutator* mut = findEmptyEntry(); if (mut == nullptr) { return; } if (descr != nullptr) { BorrowedRef<PyTypeObject> descr_type(Py_TYPE(descr)); if (descr_type->tp_descr_set != nullptr) { // Data descriptor if (descr_type == &PyMemberDescr_Type) { mut->set_member_descr(type, descr); } else { mut->set_data_descr(type, descr); } } else { // Non-data descriptor or class var mut->set_descr_or_classvar(type, descr); } ac_watcher.watch(type, this); return; } if (type->tp_dictoffset < 0 || !PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE)) { // We only support the common case for objects - fixed-size instances // (tp_dictoffset >= 0) of heap types (Py_TPFLAGS_HEAPTYPE). return; } // Instance attribute with no shadowing. Specialize the lookup based on // whether or not the type is using split dictionaries. PyHeapTypeObject* ht = reinterpret_cast<PyHeapTypeObject*>(type.get()); PyDictKeysObject* keys = ht->ht_cached_keys; Py_ssize_t val_offset; if (keys != nullptr && (val_offset = _PyDictKeys_GetSplitIndex(keys, name)) != -1) { mut->set_split(type, val_offset, keys); } else { mut->set_combined(type); } ac_watcher.watch(type, this); } AttributeMutator* AttributeCache::findEmptyEntry() { auto it = std::find_if( entries_.begin(), entries_.end(), [](const AttributeMutator& e) { return e.isEmpty(); }); return it == entries_.end() ? nullptr : it; } inline PyObject* AttributeMutator::setAttr(PyObject* obj, PyObject* name, PyObject* value) { switch (kind_) { case AttributeMutator::Kind::kSplit: return split_.setAttr(obj, name, value); case AttributeMutator::Kind::kCombined: return combined_.setAttr(obj, name, value); case AttributeMutator::Kind::kDataDescr: return data_descr_.setAttr(obj, value); case AttributeMutator::Kind::kMemberDescr: return member_descr_.setAttr(obj, value); case AttributeMutator::Kind::kDescrOrClassVar: return descr_or_cvar_.setAttr(obj, name, value); default: JIT_CHECK( false, "cannot invoke setAttr for attr of kind %d", static_cast<int>(kind_)); } } inline PyObject* AttributeMutator::getAttr(PyObject* obj, PyObject* name) { switch (kind_) { case AttributeMutator::Kind::kSplit: return split_.getAttr(obj, name); case AttributeMutator::Kind::kCombined: return combined_.getAttr(obj, name); case AttributeMutator::Kind::kDataDescr: return data_descr_.getAttr(obj); case AttributeMutator::Kind::kMemberDescr: return member_descr_.getAttr(obj); case AttributeMutator::Kind::kDescrOrClassVar: return descr_or_cvar_.getAttr(obj, name); default: JIT_CHECK( false, "cannot invoke getAttr for attr of kind %d", static_cast<int>(kind_)); } } static inline PyDictObject* get_dict(PyObject* obj, Py_ssize_t dictoffset) { PyObject** dictptr = (PyObject**)((char*)obj + dictoffset); return (PyDictObject*)*dictptr; } static inline PyDictObject* get_or_allocate_dict( PyObject* obj, Py_ssize_t dict_offset) { PyDictObject* dict = get_dict(obj, dict_offset); if (dict == nullptr) { dict = reinterpret_cast<PyDictObject*>(PyObject_GenericGetDict(obj, nullptr)); if (dict == nullptr) { return nullptr; } Py_DECREF(dict); } return dict; } static PyObject* __attribute__((noinline)) raise_attribute_error(PyObject* obj, PyObject* name) { PyErr_Format( PyExc_AttributeError, "'%.50s' object has no attribute '%U'", Py_TYPE(obj)->tp_name, name); return nullptr; } PyObject* SplitMutator::setAttr(PyObject* obj, PyObject* name, PyObject* value) { PyDictObject* dict = get_or_allocate_dict(obj, dict_offset); if (dict == nullptr) { return nullptr; } PyObject* dictobj = reinterpret_cast<PyObject*>(dict); PyObject* result = Py_None; if ((dict->ma_keys == keys) && ((dict->ma_used == val_offset) || (dict->ma_values[val_offset] != nullptr))) { PyObject* old_value = dict->ma_values[val_offset]; if (!_PyObject_GC_IS_TRACKED(dictobj)) { if (_PyObject_GC_MAY_BE_TRACKED(value)) { _PyObject_GC_TRACK(dictobj); } } Py_INCREF(value); dict->ma_values[val_offset] = value; _PyDict_IncVersionForSet(dict, name, value); if (old_value == nullptr) { dict->ma_used++; } else { Py_DECREF(old_value); } } else { Py_INCREF(dictobj); if (PyDict_SetItem(dictobj, name, value) < 0) { result = nullptr; } Py_DECREF(dictobj); } return result; } PyObject* SplitMutator::getAttr(PyObject* obj, PyObject* name) { PyDictObject* dict = get_dict(obj, dict_offset); if (dict == nullptr) { return raise_attribute_error(obj, name); } PyObject* result = nullptr; if (dict->ma_keys == keys) { result = dict->ma_values[val_offset]; } else { auto dictobj = reinterpret_cast<PyObject*>(dict); Py_INCREF(dictobj); result = PyDict_GetItem(dictobj, name); Py_DECREF(dictobj); } if (result == nullptr) { return raise_attribute_error(obj, name); } Py_INCREF(result); return result; } PyObject* CombinedMutator::setAttr(PyObject* obj, PyObject* name, PyObject* value) { PyDictObject* dict = get_or_allocate_dict(obj, dict_offset); if (dict == nullptr) { return nullptr; } PyObject* result = Py_None; auto dictobj = reinterpret_cast<PyObject*>(dict); Py_INCREF(dictobj); if (PyDict_SetItem(dictobj, name, value) < 0) { result = nullptr; } Py_DECREF(dictobj); return result; } PyObject* CombinedMutator::getAttr(PyObject* obj, PyObject* name) { auto dict = reinterpret_cast<PyObject*>(get_dict(obj, dict_offset)); if (dict == nullptr) { return raise_attribute_error(obj, name); } Py_INCREF(dict); PyObject* result = PyDict_GetItem(dict, name); Py_DECREF(dict); if (result == nullptr) { return raise_attribute_error(obj, name); } Py_INCREF(result); return result; } PyObject* DataDescrMutator::setAttr(PyObject* obj, PyObject* value) { if (Py_TYPE(descr)->tp_descr_set(descr, obj, value)) { return nullptr; } return Py_None; } PyObject* DataDescrMutator::getAttr(PyObject* obj) { return Py_TYPE(descr)->tp_descr_get(descr, obj, (PyObject*)Py_TYPE(obj)); } PyObject* MemberDescrMutator::setAttr(PyObject* obj, PyObject* value) { if (PyMember_SetOne((char*)obj, memberdef, value)) { return nullptr; } return Py_None; } PyObject* MemberDescrMutator::getAttr(PyObject* obj) { return PyMember_GetOne((char*)obj, memberdef); } PyObject* DescrOrClassVarMutator::setAttr( PyObject* obj, PyObject* name, PyObject* value) { descrsetfunc setter = Py_TYPE(descr)->tp_descr_set; if (setter != nullptr) { Ref<> descr_guard(descr); int st = setter(descr, obj, value); return (st == -1) ? nullptr : Py_None; } PyObject** dictptr = _PyObject_GetDictPtrAtOffset(obj, dictoffset); if (dictptr == nullptr) { PyErr_Format( PyExc_AttributeError, "'%.50s' object attribute '%U' is read-only", Py_TYPE(obj)->tp_name, name); return nullptr; } BorrowedRef<PyTypeObject> type(Py_TYPE(obj)); int st = _PyObjectDict_SetItem(type, dictptr, name, value); if (st < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) { PyErr_SetObject(PyExc_AttributeError, name); } _PyType_ClearNoShadowingInstances(type, descr); return (st == -1) ? nullptr : Py_None; } PyObject* DescrOrClassVarMutator::getAttr(PyObject* obj, PyObject* name) { BorrowedRef<PyTypeObject> descr_type(Py_TYPE(descr)); descrsetfunc setter = descr_type->tp_descr_set; descrgetfunc getter = descr_type->tp_descr_get; Ref<> descr_guard(descr); if (setter != nullptr && getter != nullptr) { BorrowedRef<PyTypeObject> type(Py_TYPE(obj)); return getter(descr, obj, type); } Ref<> dict; PyObject** dictptr = _PyObject_GetDictPtrAtOffset(obj, dictoffset); if (dictptr != nullptr) { dict.reset(*dictptr); } // Check instance dict. if (dict != nullptr) { Ref<> res(_PyDict_GetItem_UnicodeExact(dict, name)); if (res != nullptr) { return res.release(); } } if (getter != nullptr) { // Non-data descriptor BorrowedRef<PyTypeObject> type(Py_TYPE(obj)); return getter(descr, obj, type); } // Class var return descr_guard.release(); } // NB: The logic here needs to be kept in sync with // _PyObject_GenericSetAttrWithDict, with the proviso that this will never be // used to delete attributes. PyObject* __attribute__((noinline)) StoreAttrCache::invokeSlowPath(PyObject* obj, PyObject* name, PyObject* value) { BorrowedRef<PyTypeObject> tp(Py_TYPE(obj)); if (tp->tp_dict == nullptr && PyType_Ready(tp) < 0) { return nullptr; } else if (tp->tp_setattro != PyObject_GenericSetAttr) { int st = PyObject_SetAttr(obj, name, value); return st == 0 ? Py_None : nullptr; } Ref<> name_guard(name); Ref<> descr(_PyType_Lookup(tp, name)); if (descr != nullptr) { descrsetfunc f = descr->ob_type->tp_descr_set; if (f != nullptr) { int res = f(descr, obj, value); fill(tp, name, descr); return (res == -1) ? nullptr : Py_None; } } PyObject** dictptr = _PyObject_GetDictPtr(obj); if (dictptr == nullptr) { if (descr == nullptr) { raise_attribute_error(obj, name); } else { PyErr_Format( PyExc_AttributeError, "'%.50s' object attribute '%U' is read-only", tp->tp_name, name); } return nullptr; } int res = _PyObjectDict_SetItem(tp, dictptr, name, value); if (descr != nullptr) { _PyType_ClearNoShadowingInstances(tp, descr); } if (res != -1) { fill(tp, name, descr); } return (res == -1) ? nullptr : Py_None; } PyObject* StoreAttrCache::invoke( StoreAttrCache* cache, PyObject* obj, PyObject* name, PyObject* value) { return cache->doInvoke(obj, name, value); } PyObject* StoreAttrCache::doInvoke(PyObject* obj, PyObject* name, PyObject* value) { PyTypeObject* tp = Py_TYPE(obj); for (auto& entry : entries_) { if (entry.type() == tp) { return entry.setAttr(obj, name, value); } } return invokeSlowPath(obj, name, value); } // NB: The logic here needs to be kept in-sync with PyObject_GenericGetAttr PyObject* __attribute__((noinline)) LoadAttrCache::invokeSlowPath(PyObject* obj, PyObject* name) { BorrowedRef<PyTypeObject> tp(Py_TYPE(obj)); if (tp->tp_getattro != PyObject_GenericGetAttr) { return PyObject_GetAttr(obj, name); } if (tp->tp_dict == nullptr) { if (PyType_Ready(tp) < 0) return nullptr; } Ref<> name_guard(name); Ref<> descr(_PyType_Lookup(tp, name)); descrgetfunc f = nullptr; if (descr != nullptr) { f = descr->ob_type->tp_descr_get; if (f != nullptr && PyDescr_IsData(descr)) { fill(tp, name, descr); return f(descr, obj, tp); } } Ref<> dict; PyObject** dictptr = _PyObject_GetDictPtr(obj); if (dictptr != nullptr) { dict.reset(*dictptr); } if (dict != nullptr) { Ref<> res(PyDict_GetItem(dict, name)); if (res != nullptr) { fill(tp, name, descr); return res.release(); } } if (f != nullptr) { fill(tp, name, descr); return f(descr, obj, tp); } if (descr != nullptr) { fill(tp, name, descr); return descr.release(); } raise_attribute_error(obj, name); return nullptr; } // Sentinel PyObject that must never escape into user code. static PyObject g_emptyTypeAttrCache = {_PyObject_EXTRA_INIT 1, nullptr}; void LoadTypeAttrCache::fill(PyTypeObject* type, PyObject* value) { if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) { // The type must have a valid version tag in order for us to be able to // invalidate the cache when the type is modified. See the comment at // the top of `PyType_Modified` for more details. return; } items[0] = reinterpret_cast<PyObject*>(type); items[1] = value; ltac_watcher.watch(type, this); } void LoadTypeAttrCache::reset() { // We need to return a PyObject* even in the empty case so that subsequent // refcounting operations work correctly. items[0] = &g_emptyTypeAttrCache; items[1] = nullptr; } void LoadTypeAttrCache::typeChanged(PyTypeObject* /* type */) { reset(); } LoadTypeAttrCache::LoadTypeAttrCache() { reset(); } PyObject* LoadAttrCache::invoke(LoadAttrCache* cache, PyObject* obj, PyObject* name) { return cache->doInvoke(obj, name); } PyObject* LoadAttrCache::doInvoke(PyObject* obj, PyObject* name) { PyTypeObject* tp = Py_TYPE(obj); for (auto& entry : entries_) { if (entry.type() == tp) { return entry.getAttr(obj, name); } } return invokeSlowPath(obj, name); } // NB: This needs to be kept in-sync with the logic in type_getattro PyObject* LoadTypeAttrCache::doInvoke(PyObject* obj, PyObject* name) { PyTypeObject* metatype = Py_TYPE(obj); if (metatype->tp_getattro != PyType_Type.tp_getattro) { return PyObject_GetAttr(obj, name); } PyTypeObject* type = reinterpret_cast<PyTypeObject*>(obj); if (type->tp_dict == nullptr) { if (PyType_Ready(type) < 0) { return nullptr; } } descrgetfunc meta_get = nullptr; PyObject* meta_attribute = _PyType_Lookup(metatype, name); if (meta_attribute != nullptr) { Py_INCREF(meta_attribute); meta_get = Py_TYPE(meta_attribute)->tp_descr_get; if (meta_get != nullptr && PyDescr_IsData(meta_attribute)) { /* Data descriptors implement tp_descr_set to intercept * writes. Assume the attribute is not overridden in * type's tp_dict (and bases): call the descriptor now. */ PyObject* res = meta_get( meta_attribute, reinterpret_cast<PyObject*>(type), reinterpret_cast<PyObject*>(metatype)); Py_DECREF(meta_attribute); return res; } } /* No data descriptor found on metatype. Look in tp_dict of this * type and its bases */ PyObject* attribute = _PyType_Lookup(type, name); if (attribute != nullptr) { /* Implement descriptor functionality, if any */ Py_INCREF(attribute); descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get; Py_XDECREF(meta_attribute); if (local_get != nullptr) { /* NULL 2nd argument indicates the descriptor was * found on the target object itself (or a base) */ PyObject* res = local_get(attribute, nullptr, reinterpret_cast<PyObject*>(type)); Py_DECREF(attribute); return res; } fill(type, attribute); return attribute; } /* No attribute found in local __dict__ (or bases): use the * descriptor from the metatype, if any */ if (meta_get != nullptr) { PyObject* res; res = meta_get( meta_attribute, reinterpret_cast<PyObject*>(type), reinterpret_cast<PyObject*>(metatype)); Py_DECREF(meta_attribute); return res; } /* If an ordinary attribute was found on the metatype, return it now */ if (meta_attribute != nullptr) { return meta_attribute; } /* Give up */ PyErr_Format( PyExc_AttributeError, "type object '%.50s' has no attribute '%U'", type->tp_name, name); return NULL; } PyObject* LoadTypeAttrCache::invoke( LoadTypeAttrCache* cache, PyObject* obj, PyObject* name) { return cache->doInvoke(obj, name); } void GlobalCache::init() const { // We want to try and only watch builtins if this is really a // builtin. So we will start only watching globals, and if // the value gets deleted from globals then we'll start // tracking builtins as well. Once we start tracking builtins // we'll never stop rather than trying to handle all of the // transitions. watchDictKey(key().globals, key().name, *this); PyObject* builtins = key().builtins; if (PyObject* globals_value = PyDict_GetItem(key().globals, key().name)) { // But we don't need to immediately watch builtins if it's // defined as a global *valuePtr() = globals_value; } else { *valuePtr() = PyDict_GetItem(builtins, key().name); if (key().globals != builtins) { watchDictKey(builtins, key().name, *this); } } } void GlobalCache::update( PyObject* dict, PyObject* new_value, std::vector<GlobalCache>& to_disable) const { PyObject* builtins = key().builtins; if (dict == key().globals) { if (new_value == nullptr && key().globals != builtins) { if (!_PyDict_CanWatch(builtins)) { // builtins is no longer watchable. Mark this cache for disabling. to_disable.emplace_back(*this); return; } // Fall back to the builtin (which may also be null). *valuePtr() = PyDict_GetItem(builtins, key().name); // it changed, and it changed from something to nothing, so // we weren't watching builtins and need to start now. if (!isWatchedDictKey(builtins, key().name, *this)) { watchDictKey(builtins, key().name, *this); } } else { *valuePtr() = new_value; } } else { JIT_CHECK(dict == builtins, "Unexpected dict"); JIT_CHECK(_PyDict_CanWatch(key().globals), "Bad globals dict"); // Check if this value is shadowed. PyObject* globals_value = PyDict_GetItem(key().globals, key().name); if (globals_value == nullptr) { *valuePtr() = new_value; } } } void GlobalCache::disable() const { *valuePtr() = nullptr; jit::codegen::NativeGeneratorFactory::runtime()->forgetLoadGlobalCache(*this); } void notifyICsTypeChanged(BorrowedRef<PyTypeObject> type) { ac_watcher.typeChanged(type); ltac_watcher.typeChanged(type); } } // namespace jit
27.803763
80
0.669245
[ "object", "vector" ]
04ed6124d668789146ce60a52bf6b6154cd0bd4a
19,433
cpp
C++
libraries/chain/proposal_evaluator.cpp
nathanhourt/peerplays
a5a78dacf143e6b685ff2aab4834f33fa5d0e1df
[ "MIT" ]
null
null
null
libraries/chain/proposal_evaluator.cpp
nathanhourt/peerplays
a5a78dacf143e6b685ff2aab4834f33fa5d0e1df
[ "MIT" ]
1
2021-11-14T15:47:29.000Z
2021-11-14T16:17:53.000Z
libraries/chain/proposal_evaluator.cpp
nathanhourt/peerplays
a5a78dacf143e6b685ff2aab4834f33fa5d0e1df
[ "MIT" ]
2
2021-11-12T00:38:23.000Z
2021-12-04T12:14:16.000Z
/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission 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: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE 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. */ #include <graphene/chain/hardfork.hpp> #include <graphene/chain/proposal_evaluator.hpp> #include <graphene/chain/proposal_object.hpp> #include <graphene/chain/account_object.hpp> #include <graphene/chain/son_proposal_object.hpp> #include <graphene/protocol/account.hpp> #include <graphene/protocol/fee_schedule.hpp> #include <graphene/protocol/tournament.hpp> #include <graphene/chain/exceptions.hpp> #include <graphene/chain/hardfork.hpp> namespace graphene { namespace chain { struct proposal_operation_hardfork_visitor { typedef void result_type; const fc::time_point_sec block_time; proposal_operation_hardfork_visitor( const fc::time_point_sec bt ) : block_time(bt) {} template<typename T> void operator()(const T &v) const {} void operator()(const committee_member_update_global_parameters_operation &op) const {} void operator()(const graphene::chain::tournament_payout_operation &o) const { // TODO: move check into tournament_payout_operation::validate after HARDFORK_999_TIME FC_ASSERT( block_time < HARDFORK_999_TIME, "Not allowed!" ); } void operator()(const graphene::chain::asset_settle_cancel_operation &o) const { // TODO: move check into asset_settle_cancel_operation::validate after HARDFORK_999_TIME FC_ASSERT( block_time < HARDFORK_999_TIME, "Not allowed!" ); } void operator()(const graphene::chain::account_create_operation &aco) const { // TODO: remove after HARDFORK_999_TIME if (block_time < HARDFORK_999_TIME) FC_ASSERT( !aco.extensions.value.affiliate_distributions.valid(), "Affiliate reward distributions not allowed yet" ); } void operator()(const sport_create_operation &v) const { FC_ASSERT( block_time >= HARDFORK_1000_TIME, "sport_create_operation not allowed yet!" ); } void operator()(const sport_update_operation &v) const { FC_ASSERT( block_time >= HARDFORK_1000_TIME, "sport_update_operation not allowed yet!" ); } void operator()(const sport_delete_operation &v) const { FC_ASSERT( block_time >= HARDFORK_1000_TIME, "sport_delete_operation not allowed yet!" ); } void operator()(const event_group_create_operation &v) const { FC_ASSERT( block_time >= HARDFORK_1000_TIME, "event_group_create_operation not allowed yet!" ); } void operator()(const event_group_update_operation &v) const { FC_ASSERT( block_time >= HARDFORK_1000_TIME, "event_group_update_operation not allowed yet!" ); } void operator()(const event_group_delete_operation &v) const { FC_ASSERT( block_time >= HARDFORK_1000_TIME, "event_group_delete_operation not allowed yet!" ); } void operator()(const event_create_operation &v) const { FC_ASSERT( block_time >= HARDFORK_1000_TIME, "event_create_operation not allowed yet!" ); } void operator()(const event_update_operation &v) const { FC_ASSERT( block_time >= HARDFORK_1000_TIME, "event_update_operation not allowed yet!" ); } void operator()(const betting_market_rules_create_operation &v) const { FC_ASSERT( block_time >= HARDFORK_1000_TIME, "betting_market_rules_create_operation not allowed yet!" ); } void operator()(const betting_market_rules_update_operation &v) const { FC_ASSERT( block_time >= HARDFORK_1000_TIME, "betting_market_rules_update_operation not allowed yet!" ); } void operator()(const betting_market_group_create_operation &v) const { FC_ASSERT( block_time >= HARDFORK_1000_TIME, "betting_market_group_create_operation not allowed yet!" ); } void operator()(const betting_market_create_operation &v) const { FC_ASSERT( block_time >= HARDFORK_1000_TIME, "betting_market_create_operation not allowed yet!" ); } void operator()(const bet_place_operation &v) const { FC_ASSERT( block_time >= HARDFORK_1000_TIME, "bet_place_operation not allowed yet!" ); } void operator()(const betting_market_group_resolve_operation &v) const { FC_ASSERT( block_time >= HARDFORK_1000_TIME, "betting_market_group_resolve_operation not allowed yet!" ); } void operator()(const betting_market_group_cancel_unmatched_bets_operation &v) const { FC_ASSERT( block_time >= HARDFORK_1000_TIME, "betting_market_group_cancel_unmatched_bets_operation not allowed yet!" ); } void operator()(const bet_cancel_operation &v) const { FC_ASSERT( block_time >= HARDFORK_1000_TIME, "bet_cancel_operation not allowed yet!" ); } void operator()(const betting_market_group_update_operation &v) const { FC_ASSERT( block_time >= HARDFORK_1000_TIME, "betting_market_group_update_operation not allowed yet!" ); } void operator()(const betting_market_update_operation &v) const { FC_ASSERT( block_time >= HARDFORK_1000_TIME, "betting_market_update_operation not allowed yet!" ); } void operator()(const event_update_status_operation &v) const { FC_ASSERT( block_time >= HARDFORK_1000_TIME, "event_update_status_operation not allowed yet!" ); } void operator()(const vesting_balance_create_operation &vbco) const { if(block_time < HARDFORK_GPOS_TIME) FC_ASSERT( vbco.balance_type == vesting_balance_type::normal, "balance_type in vesting create not allowed yet!" ); } void operator()(const custom_permission_create_operation &v) const { FC_ASSERT( block_time >= HARDFORK_NFT_TIME, "custom_permission_create_operation not allowed yet!" ); } void operator()(const custom_permission_update_operation &v) const { FC_ASSERT( block_time >= HARDFORK_NFT_TIME, "custom_permission_update_operation not allowed yet!" ); } void operator()(const custom_permission_delete_operation &v) const { FC_ASSERT( block_time >= HARDFORK_NFT_TIME, "custom_permission_delete_operation not allowed yet!" ); } void operator()(const custom_account_authority_create_operation &v) const { FC_ASSERT( block_time >= HARDFORK_NFT_TIME, "custom_account_authority_create_operation not allowed yet!" ); } void operator()(const custom_account_authority_update_operation &v) const { FC_ASSERT( block_time >= HARDFORK_NFT_TIME, "custom_account_authority_update_operation not allowed yet!" ); } void operator()(const custom_account_authority_delete_operation &v) const { FC_ASSERT( block_time >= HARDFORK_NFT_TIME, "custom_account_authority_delete_operation not allowed yet!" ); } void operator()(const offer_operation &v) const { FC_ASSERT( block_time >= HARDFORK_NFT_TIME, "offer_operation not allowed yet!" ); } void operator()(const bid_operation &v) const { FC_ASSERT( block_time >= HARDFORK_NFT_TIME, "bid_operation not allowed yet!" ); } void operator()(const cancel_offer_operation &v) const { FC_ASSERT( block_time >= HARDFORK_NFT_TIME, "cancel_offer_operation not allowed yet!" ); } void operator()(const finalize_offer_operation &v) const { FC_ASSERT( block_time >= HARDFORK_NFT_TIME, "finalize_offer_operation not allowed yet!" ); } void operator()(const nft_metadata_create_operation &v) const { FC_ASSERT( block_time >= HARDFORK_NFT_TIME, "nft_metadata_create_operation not allowed yet!" ); } void operator()(const nft_metadata_update_operation &v) const { FC_ASSERT( block_time >= HARDFORK_NFT_TIME, "nft_metadata_update_operation not allowed yet!" ); } void operator()(const nft_mint_operation &v) const { FC_ASSERT( block_time >= HARDFORK_NFT_TIME, "nft_mint_operation not allowed yet!" ); } void operator()(const nft_safe_transfer_from_operation &v) const { FC_ASSERT( block_time >= HARDFORK_NFT_TIME, "nft_safe_transfer_from_operation not allowed yet!" ); } void operator()(const nft_approve_operation &v) const { FC_ASSERT( block_time >= HARDFORK_NFT_TIME, "nft_approve_operation not allowed yet!" ); } void operator()(const nft_set_approval_for_all_operation &v) const { FC_ASSERT( block_time >= HARDFORK_NFT_TIME, "nft_set_approval_for_all_operation not allowed yet!" ); } void operator()(const account_role_create_operation &v) const { FC_ASSERT( block_time >= HARDFORK_NFT_TIME, "account_role_create_operation not allowed yet!" ); } void operator()(const account_role_update_operation &v) const { FC_ASSERT( block_time >= HARDFORK_NFT_TIME, "account_role_update_operation not allowed yet!" ); } void operator()(const account_role_delete_operation &v) const { FC_ASSERT( block_time >= HARDFORK_NFT_TIME, "account_role_delete_operation not allowed yet!" ); } void operator()(const son_create_operation &v) const { FC_ASSERT( block_time >= HARDFORK_SON_TIME, "son_create_operation not allowed yet!" ); } void operator()(const son_update_operation &v) const { FC_ASSERT( block_time >= HARDFORK_SON_TIME, "son_update_operation not allowed yet!" ); } void operator()(const son_deregister_operation &v) const { FC_ASSERT( block_time >= HARDFORK_SON_TIME, "son_deregister_operation not allowed yet!" ); } void operator()(const son_heartbeat_operation &v) const { FC_ASSERT( block_time >= HARDFORK_SON_TIME, "son_heartbeat_operation not allowed yet!" ); } void operator()(const son_report_down_operation &v) const { FC_ASSERT( block_time >= HARDFORK_SON_TIME, "son_report_down_operation not allowed yet!" ); } void operator()(const son_maintenance_operation &v) const { FC_ASSERT( block_time >= HARDFORK_SON_TIME, "son_maintenance_operation not allowed yet!" ); } // loop and self visit in proposals void operator()(const proposal_create_operation &v) const { for (const op_wrapper &op : v.proposed_ops) op.op.visit(*this); } }; void son_hardfork_visitor::operator()( const son_deregister_operation &v ) { db.create<son_proposal_object>([&]( son_proposal_object& son_prop ) { son_prop.proposal_type = son_proposal_type::son_deregister_proposal; son_prop.proposal_id = prop_id; son_prop.son_id = v.son_id; }); } void son_hardfork_visitor::operator()( const son_report_down_operation &v ) { db.create<son_proposal_object>([&]( son_proposal_object& son_prop ) { son_prop.proposal_type = son_proposal_type::son_report_down_proposal; son_prop.proposal_id = prop_id; son_prop.son_id = v.son_id; }); } void_result proposal_create_evaluator::do_evaluate( const proposal_create_operation& o ) { try { const database& d = db(); auto block_time = d.head_block_time(); proposal_operation_hardfork_visitor vtor( block_time ); vtor( o ); const auto& global_parameters = d.get_global_properties().parameters; FC_ASSERT( o.expiration_time > block_time, "Proposal has already expired on creation." ); FC_ASSERT( o.expiration_time <= block_time + global_parameters.maximum_proposal_lifetime, "Proposal expiration time is too far in the future."); FC_ASSERT( !o.review_period_seconds || fc::seconds(*o.review_period_seconds) < (o.expiration_time - block_time), "Proposal review period must be less than its overall lifetime." ); { // If we're dealing with the committee authority, make sure this transaction has a sufficient review period. flat_set<account_id_type> auths; vector<authority> other; for( auto& op : o.proposed_ops ) { operation_get_required_authorities( op.op, auths, auths, other, MUST_IGNORE_CUSTOM_OP_REQD_AUTHS(block_time) ); } FC_ASSERT( other.size() == 0 ); // TODO: what about other??? if( auths.find(GRAPHENE_COMMITTEE_ACCOUNT) != auths.end() ) { GRAPHENE_ASSERT( o.review_period_seconds.valid(), proposal_create_review_period_required, "Review period not given, but at least ${min} required", ("min", global_parameters.committee_proposal_review_period) ); GRAPHENE_ASSERT( *o.review_period_seconds >= global_parameters.committee_proposal_review_period, proposal_create_review_period_insufficient, "Review period of ${t} specified, but at least ${min} required", ("t", *o.review_period_seconds) ("min", global_parameters.committee_proposal_review_period) ); } } for (const op_wrapper& op : o.proposed_ops) _proposed_trx.operations.push_back(op.op); _proposed_trx.validate(); return void_result(); } FC_CAPTURE_AND_RETHROW( (o) ) } object_id_type proposal_create_evaluator::do_apply( const proposal_create_operation& o ) { try { database& d = db(); auto chain_time = d.head_block_time(); const proposal_object& proposal = d.create<proposal_object>( [&o, this, chain_time](proposal_object& proposal) { _proposed_trx.expiration = o.expiration_time; proposal.proposed_transaction = _proposed_trx; proposal.proposer = o.fee_paying_account; proposal.expiration_time = o.expiration_time; if( o.review_period_seconds ) proposal.review_period_time = o.expiration_time - *o.review_period_seconds; //Populate the required approval sets flat_set<account_id_type> required_active; vector<authority> other; // TODO: consider caching values from evaluate? for( auto& op : _proposed_trx.operations ) operation_get_required_authorities( op, required_active, proposal.required_owner_approvals, other, MUST_IGNORE_CUSTOM_OP_REQD_AUTHS(chain_time) ); //All accounts which must provide both owner and active authority should be omitted from the active authority set; //owner authority approval implies active authority approval. std::set_difference(required_active.begin(), required_active.end(), proposal.required_owner_approvals.begin(), proposal.required_owner_approvals.end(), std::inserter(proposal.required_active_approvals, proposal.required_active_approvals.begin())); }); son_hardfork_visitor son_vtor(d, proposal.id); for(auto& op: o.proposed_ops) { op.op.visit(son_vtor); } return proposal.id; } FC_CAPTURE_AND_RETHROW( (o) ) } void_result proposal_update_evaluator::do_evaluate( const proposal_update_operation& o ) { try { database& d = db(); _proposal = &o.proposal(d); if( _proposal->review_period_time && d.head_block_time() >= *_proposal->review_period_time ) FC_ASSERT( o.active_approvals_to_add.empty() && o.owner_approvals_to_add.empty(), "This proposal is in its review period. No new approvals may be added." ); for( account_id_type id : o.active_approvals_to_remove ) { FC_ASSERT( _proposal->available_active_approvals.find(id) != _proposal->available_active_approvals.end(), "", ("id", id)("available", _proposal->available_active_approvals) ); } for( account_id_type id : o.owner_approvals_to_remove ) { FC_ASSERT( _proposal->available_owner_approvals.find(id) != _proposal->available_owner_approvals.end(), "", ("id", id)("available", _proposal->available_owner_approvals) ); } return void_result(); } FC_CAPTURE_AND_RETHROW( (o) ) } void_result proposal_update_evaluator::do_apply(const proposal_update_operation& o) { try { database& d = db(); // Potential optimization: if _executed_proposal is true, we can skip the modify step and make push_proposal skip // signature checks. This isn't done now because I just wrote all the proposals code, and I'm not yet 100% sure the // required approvals are sufficient to authorize the transaction. d.modify(*_proposal, [&o](proposal_object& p) { p.available_active_approvals.insert(o.active_approvals_to_add.begin(), o.active_approvals_to_add.end()); p.available_owner_approvals.insert(o.owner_approvals_to_add.begin(), o.owner_approvals_to_add.end()); for( account_id_type id : o.active_approvals_to_remove ) p.available_active_approvals.erase(id); for( account_id_type id : o.owner_approvals_to_remove ) p.available_owner_approvals.erase(id); for( const auto& id : o.key_approvals_to_add ) p.available_key_approvals.insert(id); for( const auto& id : o.key_approvals_to_remove ) p.available_key_approvals.erase(id); }); // If the proposal has a review period, don't bother attempting to authorize/execute it. // Proposals with a review period may never be executed except at their expiration. if( _proposal->review_period_time ) return void_result(); if( _proposal->is_authorized_to_execute(d) ) { // All required approvals are satisfied. Execute! _executed_proposal = true; try { _processed_transaction = d.push_proposal(*_proposal); } catch(fc::exception& e) { d.modify(*_proposal, [&e](proposal_object& p) { p.fail_reason = e.to_string(fc::log_level(fc::log_level::all)); }); wlog("Proposed transaction ${id} failed to apply once approved with exception:\n----\n${reason}\n----\nWill try again when it expires.", ("id", o.proposal)("reason", e.to_detail_string())); _proposal_failed = true; } } return void_result(); } FC_CAPTURE_AND_RETHROW( (o) ) } void_result proposal_delete_evaluator::do_evaluate(const proposal_delete_operation& o) { try { database& d = db(); _proposal = &o.proposal(d); auto required_approvals = o.using_owner_authority? &_proposal->required_owner_approvals : &_proposal->required_active_approvals; FC_ASSERT( required_approvals->find(o.fee_paying_account) != required_approvals->end(), "Provided authority is not authoritative for this proposal.", ("provided", o.fee_paying_account)("required", *required_approvals)); return void_result(); } FC_CAPTURE_AND_RETHROW( (o) ) } void_result proposal_delete_evaluator::do_apply(const proposal_delete_operation& o) { try { db().remove(*_proposal); return void_result(); } FC_CAPTURE_AND_RETHROW( (o) ) } } } // graphene::chain
42.898455
145
0.719035
[ "vector" ]
04f7346d928ce07cba1ee0de69e188d130e424b6
581
cpp
C++
BinarySearch/BOJ/02417.cpp
chiseungii/Algorithms
f0e7dd1c9fc29e77c97b644e602e94047b9cf887
[ "MIT" ]
null
null
null
BinarySearch/BOJ/02417.cpp
chiseungii/Algorithms
f0e7dd1c9fc29e77c97b644e602e94047b9cf887
[ "MIT" ]
null
null
null
BinarySearch/BOJ/02417.cpp
chiseungii/Algorithms
f0e7dd1c9fc29e77c97b644e602e94047b9cf887
[ "MIT" ]
null
null
null
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <vector> #include <algorithm> #include <map> #include <math.h> using namespace std; int main() { unsigned long long n; cin >> n; if (n == 0) cout << 0 << endl; else if (n == 1) cout << 1 << endl; else { // binary search unsigned long long low = 1, high = min(n, (unsigned long long)3037000500); unsigned long long mid, result; while (low <= high) { mid = (low + high) / 2; if (mid * mid >= n) { result = mid; high = mid - 1; } else low = mid + 1; } cout << result << endl; } }
17.606061
76
0.583477
[ "vector" ]
ca022661adcde36f23d6b4903e5dbe6337ea31f2
969
cpp
C++
aws-cpp-sdk-cloudcontrol/source/model/CancelResourceRequestRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-cloudcontrol/source/model/CancelResourceRequestRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-cloudcontrol/source/model/CancelResourceRequestRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/cloudcontrol/model/CancelResourceRequestRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::CloudControlApi::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; CancelResourceRequestRequest::CancelResourceRequestRequest() : m_requestTokenHasBeenSet(false) { } Aws::String CancelResourceRequestRequest::SerializePayload() const { JsonValue payload; if(m_requestTokenHasBeenSet) { payload.WithString("RequestToken", m_requestToken); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection CancelResourceRequestRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "CloudApiService.CancelResourceRequest")); return headers; }
22.022727
102
0.77193
[ "model" ]
ca03b363e32503b6b49ca002fbad81303ae892c0
5,226
cpp
C++
mcrouter/tools/mcpiper/MessagePrinter.cpp
uubk/mcrouter
c2c8d045e773f23847112c06962748e45afdf6f0
[ "MIT" ]
null
null
null
mcrouter/tools/mcpiper/MessagePrinter.cpp
uubk/mcrouter
c2c8d045e773f23847112c06962748e45afdf6f0
[ "MIT" ]
null
null
null
mcrouter/tools/mcpiper/MessagePrinter.cpp
uubk/mcrouter
c2c8d045e773f23847112c06962748e45afdf6f0
[ "MIT" ]
null
null
null
/* * Copyright (c) 2016-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the LICENSE * file in the root directory of this source tree. * */ #include "MessagePrinter.h" #include <folly/lang/Bits.h> namespace facebook { namespace memcache { namespace { bool matchIPAddress( const folly::IPAddress& expectedIp, const folly::SocketAddress& address) { return !address.empty() && expectedIp == address.getIPAddress(); } bool matchPort(uint16_t expectedPort, const folly::SocketAddress& address) { return !address.empty() && expectedPort == address.getPort(); } std::string describeAddress(const folly::SocketAddress& address) { auto res = address.describe(); if (address.getFamily() == AF_UNIX) { // Check if the path was truncated. if (res.size() >= MessageHeader::kAddressMaxSize - kUnixSocketPrefix.size() - 1) { return res + "..."; } } return res; } } // anonymous namespace MessagePrinter::MessagePrinter( Options options, Filter filter, std::unique_ptr<ValueFormatter> valueFormatter, std::ostream& targetOut) : options_(std::move(options)), filter_(std::move(filter)), valueFormatter_(std::move(valueFormatter)), targetOut_(targetOut) { if (options_.disableColor) { targetOut_.setColorOutput(false); } } bool MessagePrinter::matchAddress( const folly::SocketAddress& from, const folly::SocketAddress& to) const { // Initial filters if (!filter_.host.empty() && !matchIPAddress(filter_.host, from) && !matchIPAddress(filter_.host, to)) { return false; } if (filter_.port != 0 && !matchPort(filter_.port, from) && !matchPort(filter_.port, to)) { return false; } return true; } void MessagePrinter::countStats() { ++stats_.printedMessages; if (options_.maxMessages > 0 && stats_.printedMessages >= options_.maxMessages) { assert(options_.stopRunningFn); options_.stopRunningFn(); } if (options_.numAfterMatch > 0) { --afterMatchCount_; } } void MessagePrinter::printRawMessage( const struct iovec* iovsBegin, size_t iovsCount) { if (iovsBegin == nullptr) { return; } uint64_t rawMessageSize = 0; for (size_t i = 0; i < iovsCount; ++i) { rawMessageSize += iovsBegin[i].iov_len; } StyledString rawMessage; rawMessageSize = folly::Endian::little(rawMessageSize); rawMessage.append( std::string(reinterpret_cast<char*>(&rawMessageSize), sizeof(uint64_t))); for (size_t i = 0; i < iovsCount; ++i) { rawMessage.append(std::string( static_cast<char*>(iovsBegin[i].iov_base), iovsBegin[i].iov_len)); } printMessage(rawMessage); } void MessagePrinter::printMessage(const StyledString& message) { targetOut_ << message; targetOut_.flush(); countStats(); } std::string MessagePrinter::serializeConnectionDetails( const folly::SocketAddress& from, const folly::SocketAddress& to, mc_protocol_t protocol) { std::string out; if (!from.empty()) { if (options_.script) { out.append( folly::sformat(",\n \"from\": \"{}\"", describeAddress(from))); } else { out.append(describeAddress(from)); } } if (!options_.script && (!from.empty() || !to.empty())) { out.append(" -> "); } if (!to.empty()) { if (options_.script) { out.append(folly::sformat(",\n \"to\": \"{}\"", describeAddress(to))); } else { out.append(describeAddress(to)); } } if ((!from.empty() || !to.empty()) && protocol != mc_unknown_protocol) { if (options_.script) { out.append(folly::sformat( ",\n \"protocol\": \"{}\"", mc_protocol_to_string(protocol))); } else { out.append(folly::sformat(" ({})", mc_protocol_to_string(protocol))); } } return out; } std::string MessagePrinter::serializeMessageHeader( folly::StringPiece messageName, mc_res_t result, const std::string& key) { std::string out; if (options_.script) { out.append(folly::sformat("\"type\": \"{}\"", messageName.data())); if (result != mc_res_unknown) { out.append( folly::sformat(",\n \"result\": \"{}\"", mc_res_to_string(result))); } if (!key.empty()) { out.append( folly::sformat(",\n \"key\": \"{}\"", folly::backslashify(key))); } } else { out.append(messageName.data()); if (result != mc_res_unknown) { out.push_back(' '); out.append(mc_res_to_string(result)); } if (!key.empty()) { out.push_back(' '); out.append(folly::backslashify(key)); } } return out; } /** * Matches all the occurences of "pattern" in "text" * * @return A vector of pairs containing the index and size (respectively) * of all ocurrences. */ std::vector<std::pair<size_t, size_t>> MessagePrinter::matchAll( folly::StringPiece text, const boost::regex& pattern) const { std::vector<std::pair<size_t, size_t>> result; boost::cregex_token_iterator it(text.begin(), text.end(), pattern); boost::cregex_token_iterator end; while (it != end) { result.emplace_back(it->first - text.begin(), it->length()); ++it; } return result; } } } // facebook::memcache
26.13
79
0.638347
[ "vector" ]
ca0586f8c04cdf2e09935f1f1a2879e635dc588f
1,107
hpp
C++
Include/GoldenSun/Engine.hpp
gongminmin/GoldenSun
40846589f6a4b35279d2660a064c12c250a951a2
[ "MIT" ]
20
2021-02-23T06:07:44.000Z
2022-02-27T13:32:21.000Z
Include/GoldenSun/Engine.hpp
gongminmin/GoldenSun
40846589f6a4b35279d2660a064c12c250a951a2
[ "MIT" ]
18
2021-02-27T23:24:33.000Z
2021-04-06T05:12:03.000Z
Include/GoldenSun/Engine.hpp
gongminmin/GoldenSun
40846589f6a4b35279d2660a064c12c250a951a2
[ "MIT" ]
null
null
null
#pragma once #include <DirectXMath.h> #include <dxgiformat.h> struct ID3D12Device5; struct ID3D12CommandQueue; struct ID3D12GraphicsCommandList4; struct ID3D12Resource; namespace GoldenSun { class Mesh; class PointLight; class GOLDEN_SUN_API Engine final { DISALLOW_COPY_AND_ASSIGN(Engine) public: Engine(); Engine(ID3D12Device5* device, ID3D12CommandQueue* cmd_queue); ~Engine() noexcept; Engine(Engine&& other) noexcept; Engine& operator=(Engine&& other) noexcept; void RenderTarget(uint32_t width, uint32_t height, DXGI_FORMAT format); void RenderTarget(uint32_t width, uint32_t height, DXGI_FORMAT format, DirectX::XMFLOAT4 const& bg_color); void Meshes(Mesh const* meshes, uint32_t num_meshes); void Lights(PointLight const* lights, uint32_t num_lights); void Camera(Camera const& camera); void Render(ID3D12GraphicsCommandList4* cmd_list); ID3D12Resource* Output() const noexcept; private: class Impl; Impl* impl_; }; } // namespace GoldenSun
25.744186
114
0.692864
[ "mesh", "render" ]
ca0b428fcec8c6d186e25aba9737a0c695a0a0b3
5,656
cc
C++
base/proxydetect_unittest.cc
mostynb/webrtc
24a16656da7249c0d836247bc77dbc475f71f0af
[ "DOC", "BSD-3-Clause" ]
139
2017-06-10T17:23:54.000Z
2022-03-23T21:08:17.000Z
base/proxydetect_unittest.cc
mostynb/webrtc
24a16656da7249c0d836247bc77dbc475f71f0af
[ "DOC", "BSD-3-Clause" ]
72
2017-09-30T17:58:56.000Z
2021-08-16T08:13:01.000Z
base/proxydetect_unittest.cc
mostynb/webrtc
24a16656da7249c0d836247bc77dbc475f71f0af
[ "DOC", "BSD-3-Clause" ]
67
2017-11-28T17:59:19.000Z
2022-02-22T04:09:38.000Z
/* * Copyright 2010 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <string> #include "webrtc/base/fileutils_mock.h" #include "webrtc/base/proxydetect.h" namespace rtc { static const std::string kFirefoxProfilesIni = "[Profile0]\n" "Name=default\n" "IsRelative=1\n" "Path=Profiles/2de53ejb.default\n" "Default=1\n"; static const std::string kFirefoxHeader = "# Mozilla User Preferences\n" "\n" "/* Some Comments\n" "*\n" "*/\n" "\n"; static const std::string kFirefoxCorruptHeader = "iuahueqe32164"; static const std::string kProxyAddress = "proxy.net.com"; // Mocking out platform specific path to firefox prefs file. class FirefoxPrefsFileSystem : public FakeFileSystem { public: explicit FirefoxPrefsFileSystem(const std::vector<File>& all_files) : FakeFileSystem(all_files) { } virtual FileStream* OpenFile(const Pathname& filename, const std::string& mode) { // TODO: We could have a platform dependent check of paths here. std::string name = filename.basename(); name.append(filename.extension()); EXPECT_TRUE(name.compare("prefs.js") == 0 || name.compare("profiles.ini") == 0); FileStream* stream = FakeFileSystem::OpenFile(name, mode); return stream; } }; class ProxyDetectTest : public testing::Test { }; bool GetProxyInfo(const std::string prefs, ProxyInfo* info) { std::vector<rtc::FakeFileSystem::File> files; files.push_back(rtc::FakeFileSystem::File("profiles.ini", kFirefoxProfilesIni)); files.push_back(rtc::FakeFileSystem::File("prefs.js", prefs)); rtc::FilesystemScope fs(new rtc::FirefoxPrefsFileSystem(files)); return GetProxySettingsForUrl("Firefox", "www.google.com", info, false); } // Verifies that an empty Firefox prefs file results in no proxy detected. TEST_F(ProxyDetectTest, DISABLED_TestFirefoxEmptyPrefs) { ProxyInfo proxy_info; EXPECT_TRUE(GetProxyInfo(kFirefoxHeader, &proxy_info)); EXPECT_EQ(PROXY_NONE, proxy_info.type); } // Verifies that corrupted prefs file results in no proxy detected. TEST_F(ProxyDetectTest, DISABLED_TestFirefoxCorruptedPrefs) { ProxyInfo proxy_info; EXPECT_TRUE(GetProxyInfo(kFirefoxCorruptHeader, &proxy_info)); EXPECT_EQ(PROXY_NONE, proxy_info.type); } // Verifies that SOCKS5 proxy is detected if configured. SOCKS uses a // handshake protocol to inform the proxy software about the // connection that the client is trying to make and may be used for // any form of TCP or UDP socket connection. TEST_F(ProxyDetectTest, DISABLED_TestFirefoxProxySocks) { ProxyInfo proxy_info; SocketAddress proxy_address("proxy.socks.com", 6666); std::string prefs(kFirefoxHeader); prefs.append("user_pref(\"network.proxy.socks\", \"proxy.socks.com\");\n"); prefs.append("user_pref(\"network.proxy.socks_port\", 6666);\n"); prefs.append("user_pref(\"network.proxy.type\", 1);\n"); EXPECT_TRUE(GetProxyInfo(prefs, &proxy_info)); EXPECT_EQ(PROXY_SOCKS5, proxy_info.type); EXPECT_EQ(proxy_address, proxy_info.address); } // Verified that SSL proxy is detected if configured. SSL proxy is an // extention of a HTTP proxy to support secure connections. TEST_F(ProxyDetectTest, DISABLED_TestFirefoxProxySsl) { ProxyInfo proxy_info; SocketAddress proxy_address("proxy.ssl.com", 7777); std::string prefs(kFirefoxHeader); prefs.append("user_pref(\"network.proxy.ssl\", \"proxy.ssl.com\");\n"); prefs.append("user_pref(\"network.proxy.ssl_port\", 7777);\n"); prefs.append("user_pref(\"network.proxy.type\", 1);\n"); EXPECT_TRUE(GetProxyInfo(prefs, &proxy_info)); EXPECT_EQ(PROXY_HTTPS, proxy_info.type); EXPECT_EQ(proxy_address, proxy_info.address); } // Verifies that a HTTP proxy is detected if configured. TEST_F(ProxyDetectTest, DISABLED_TestFirefoxProxyHttp) { ProxyInfo proxy_info; SocketAddress proxy_address("proxy.http.com", 8888); std::string prefs(kFirefoxHeader); prefs.append("user_pref(\"network.proxy.http\", \"proxy.http.com\");\n"); prefs.append("user_pref(\"network.proxy.http_port\", 8888);\n"); prefs.append("user_pref(\"network.proxy.type\", 1);\n"); EXPECT_TRUE(GetProxyInfo(prefs, &proxy_info)); EXPECT_EQ(PROXY_HTTPS, proxy_info.type); EXPECT_EQ(proxy_address, proxy_info.address); } // Verifies detection of automatic proxy detection. TEST_F(ProxyDetectTest, DISABLED_TestFirefoxProxyAuto) { ProxyInfo proxy_info; std::string prefs(kFirefoxHeader); prefs.append("user_pref(\"network.proxy.type\", 4);\n"); EXPECT_TRUE(GetProxyInfo(prefs, &proxy_info)); EXPECT_EQ(PROXY_NONE, proxy_info.type); EXPECT_TRUE(proxy_info.autodetect); EXPECT_TRUE(proxy_info.autoconfig_url.empty()); } // Verifies detection of automatic proxy detection using a static url // to config file. TEST_F(ProxyDetectTest, DISABLED_TestFirefoxProxyAutoUrl) { ProxyInfo proxy_info; std::string prefs(kFirefoxHeader); prefs.append( "user_pref(\"network.proxy.autoconfig_url\", \"http://a/b.pac\");\n"); prefs.append("user_pref(\"network.proxy.type\", 2);\n"); EXPECT_TRUE(GetProxyInfo(prefs, &proxy_info)); EXPECT_FALSE(proxy_info.autodetect); EXPECT_EQ(PROXY_NONE, proxy_info.type); EXPECT_EQ(0, proxy_info.autoconfig_url.compare("http://a/b.pac")); } } // namespace rtc
34.278788
77
0.729491
[ "vector" ]
ca11ee53c8fd9565640a17534b6f61687c30efa3
4,499
hxx
C++
opencascade/AppDef_LinearCriteria.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
117
2020-03-07T12:07:05.000Z
2022-03-27T07:35:22.000Z
opencascade/AppDef_LinearCriteria.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
66
2019-12-20T16:07:36.000Z
2022-03-15T21:56:10.000Z
opencascade/AppDef_LinearCriteria.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
76
2020-03-16T01:47:46.000Z
2022-03-21T16:37:07.000Z
// Created on: 1997-09-11 // Created by: Philippe MANGIN // Copyright (c) 1997-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _AppDef_LinearCriteria_HeaderFile #define _AppDef_LinearCriteria_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <AppDef_MultiLine.hxx> #include <TColStd_HArray1OfReal.hxx> #include <Standard_Real.hxx> #include <TColStd_Array1OfReal.hxx> #include <Standard_Integer.hxx> #include <AppDef_SmoothCriterion.hxx> #include <FEmTool_HAssemblyTable.hxx> #include <TColStd_HArray2OfInteger.hxx> #include <math_Vector.hxx> class FEmTool_ElementaryCriterion; class FEmTool_Curve; class Standard_NotImplemented; class Standard_DomainError; class AppDef_MultiLine; class math_Matrix; class AppDef_LinearCriteria; DEFINE_STANDARD_HANDLE(AppDef_LinearCriteria, AppDef_SmoothCriterion) //! defined an Linear Criteria to used in variational //! Smoothing of points. class AppDef_LinearCriteria : public AppDef_SmoothCriterion { public: Standard_EXPORT AppDef_LinearCriteria(const AppDef_MultiLine& SSP, const Standard_Integer FirstPoint, const Standard_Integer LastPoint); Standard_EXPORT void SetParameters (const Handle(TColStd_HArray1OfReal)& Parameters) Standard_OVERRIDE; Standard_EXPORT void SetCurve (const Handle(FEmTool_Curve)& C) Standard_OVERRIDE; Standard_EXPORT void GetCurve (Handle(FEmTool_Curve)& C) const Standard_OVERRIDE; Standard_EXPORT void SetEstimation (const Standard_Real E1, const Standard_Real E2, const Standard_Real E3) Standard_OVERRIDE; Standard_EXPORT Standard_Real& EstLength() Standard_OVERRIDE; Standard_EXPORT void GetEstimation (Standard_Real& E1, Standard_Real& E2, Standard_Real& E3) const Standard_OVERRIDE; Standard_EXPORT Handle(FEmTool_HAssemblyTable) AssemblyTable() const Standard_OVERRIDE; Standard_EXPORT Handle(TColStd_HArray2OfInteger) DependenceTable() const Standard_OVERRIDE; Standard_EXPORT Standard_Integer QualityValues (const Standard_Real J1min, const Standard_Real J2min, const Standard_Real J3min, Standard_Real& J1, Standard_Real& J2, Standard_Real& J3) Standard_OVERRIDE; Standard_EXPORT void ErrorValues (Standard_Real& MaxError, Standard_Real& QuadraticError, Standard_Real& AverageError) Standard_OVERRIDE; Standard_EXPORT void Hessian (const Standard_Integer Element, const Standard_Integer Dimension1, const Standard_Integer Dimension2, math_Matrix& H) Standard_OVERRIDE; Standard_EXPORT void Gradient (const Standard_Integer Element, const Standard_Integer Dimension, math_Vector& G) Standard_OVERRIDE; //! Convert the assembly Vector in an Curve; Standard_EXPORT void InputVector (const math_Vector& X, const Handle(FEmTool_HAssemblyTable)& AssTable) Standard_OVERRIDE; Standard_EXPORT void SetWeight (const Standard_Real QuadraticWeight, const Standard_Real QualityWeight, const Standard_Real percentJ1, const Standard_Real percentJ2, const Standard_Real percentJ3) Standard_OVERRIDE; Standard_EXPORT void GetWeight (Standard_Real& QuadraticWeight, Standard_Real& QualityWeight) const Standard_OVERRIDE; Standard_EXPORT void SetWeight (const TColStd_Array1OfReal& Weight) Standard_OVERRIDE; DEFINE_STANDARD_RTTIEXT(AppDef_LinearCriteria,AppDef_SmoothCriterion) protected: private: Standard_EXPORT void BuildCache (const Standard_Integer E); AppDef_MultiLine mySSP; Handle(TColStd_HArray1OfReal) myParameters; Handle(TColStd_HArray1OfReal) myCache; Handle(FEmTool_ElementaryCriterion) myCriteria[3]; Standard_Real myEstimation[3]; Standard_Real myQuadraticWeight; Standard_Real myQualityWeight; Standard_Real myPercent[3]; TColStd_Array1OfReal myPntWeight; Handle(FEmTool_Curve) myCurve; Standard_Real myLength; Standard_Integer myE; Standard_Integer IF; Standard_Integer IL; }; #endif // _AppDef_LinearCriteria_HeaderFile
35.706349
217
0.81796
[ "vector" ]
ca16a953e8a65335d6729ee415cc0a3e49461777
5,619
hpp
C++
data/text/ustring.hpp
usadson/WebEngine
73f436535a70c6c9d7f3a5c565650b6152effd8d
[ "BSD-2-Clause" ]
3
2020-03-28T01:36:44.000Z
2020-06-19T23:55:08.000Z
data/text/ustring.hpp
usadson/WebEngine
73f436535a70c6c9d7f3a5c565650b6152effd8d
[ "BSD-2-Clause" ]
null
null
null
data/text/ustring.hpp
usadson/WebEngine
73f436535a70c6c9d7f3a5c565650b6152effd8d
[ "BSD-2-Clause" ]
null
null
null
#pragma once /** * Copyright (C) 2020 Tristan. All Rights Reserved. * This file is licensed under the BSD 2-Clause license. * See the COPYING file for licensing information. */ #include <initializer_list> #include <ostream> #include <utility> #include <vector> #include <cstring> #include "unicode.hpp" namespace Unicode { /** * [Warning] * Using case-insensitive functions only works with ASCII characters. These * are characters from the ISO basic Latin alphabet*. These functions are * useful for example for parsing languages with English keywords, like * HTML. Do not use these anywhere except where standards explicitly * permits use. This is to avoid internationalization bugs. * * [Warning] * Using `const char *` inputs is only permitted on ASCII strings. If you * want to use non-ASCII strings or characters inside a UString, use a * TextEncoding::Encoding** for the former, and an Unicode::CodePoint*** * for thelatter. * * * Wikipedia article: * https://en.wikipedia.org/wiki/ISO_basic_Latin_alphabet * ** See the declaration in: data/text/encoder/encoding.hpp * *** See the declaration in: data/text/unicode.hpp */ class UString { /** * The following property should be private but since the functions outside * this class (inside namespace Unicode) need this data. */ private: std::vector<Unicode::CodePoint> data; public: /*** Constructors ***/ UString() noexcept; explicit UString(std::vector<Unicode::CodePoint> const &characters) noexcept : data(characters) { } explicit UString(std::vector<Unicode::CodePoint> &&characters) noexcept : data(std::move(characters)) { } explicit UString(Unicode::CodePoint) noexcept; // cppcheck-suppress noExplicitConstructor inline UString(std::initializer_list<Unicode::CodePoint> list) noexcept : data(list) { } explicit UString(const char *, std::size_t) noexcept; inline explicit UString(const char *ascii) noexcept : UString(ascii, strlen(ascii)) { } /*** Methods ****/ [[nodiscard]] inline const Unicode::CodePoint & operator[](std::size_t index) const noexcept { return data[index]; } [[nodiscard]] inline Unicode::CodePoint & operator[](std::size_t index) noexcept { return data[index]; } [[nodiscard]] inline std::size_t length() const noexcept { return data.size(); } [[nodiscard]] bool operator==(const UString &other) const noexcept; [[nodiscard]] inline bool operator!=(const UString &other) const noexcept { return !operator==(other); } [[nodiscard]] UString operator+(const Unicode::CodePoint &) const noexcept; [[nodiscard]] UString operator+(const UString &) const noexcept; UString & operator+=(Unicode::CodePoint) noexcept; /* Append a strictly-ASCII string */ UString & operator+=(const UString &) noexcept; /* Append a strictly-ASCII string */ UString & operator+=(const char *) noexcept; std::ostream & operator<<(std::ostream &stream) const; [[nodiscard]] int Compare(const UString &) const noexcept; void CopyTo(UString &) const noexcept; [[nodiscard]] inline constexpr bool Empty() const noexcept { return data.empty(); } [[nodiscard]] bool EqualsA(const char *) const noexcept; /* Equals case-sensitivily ASCII at index + length */ [[nodiscard]] bool EqualsAL(std::size_t, const char *, std::size_t) const noexcept; [[nodiscard]] bool EqualsIgnoreCase(const UString &other) const noexcept; /* Equals Ignore-case ASCII at index */ [[nodiscard]] bool EqualsIgnoreCaseA(std::size_t, const char *) const noexcept; /* Equals Ignore-case ASCII at index + length */ [[nodiscard]] bool EqualsIgnoreCaseAL(std::size_t, const char *, std::size_t) const noexcept; /* Is the character at position <std::size_t> an ASCII character? */ [[nodiscard]] bool IsASCIIAlpha(std::size_t) const noexcept; bool RemoveCharacterAt(std::size_t) noexcept; [[nodiscard]] bool StartsWithA(const char *) const noexcept; [[nodiscard]] bool StartsWithIgnoreCaseAL(std::size_t pos, const char *ascii, size_t length) const noexcept; [[nodiscard]] inline constexpr auto begin() noexcept { return std::begin(data); } [[nodiscard]] inline constexpr auto end() noexcept { return std::end(data); } [[nodiscard]] inline constexpr auto begin() const noexcept { return std::begin(data); } [[nodiscard]] inline constexpr auto end() const noexcept { return std::end(data); } [[nodiscard]] inline constexpr auto cbegin() const noexcept { return std::cbegin(data); } [[nodiscard]] inline constexpr auto cend() const noexcept { return std::cend(data); } [[nodiscard]] inline constexpr auto rbegin() noexcept { return std::rbegin(data); } [[nodiscard]] inline constexpr auto rend() noexcept { return std::rend(data); } [[nodiscard]] inline constexpr auto rbegin() const noexcept { return std::rbegin(data); } [[nodiscard]] inline constexpr auto rend() const noexcept { return std::rend(data); } [[nodiscard]] inline constexpr auto crbegin() const noexcept { return std::crbegin(data); } [[nodiscard]] inline constexpr auto crend() const noexcept { return std::crend(data); } }; inline std::ostream & operator<<(std::ostream &stream, const UString &string) { return string.operator<<(stream); } [[nodiscard]] inline bool operator<(const UString &lhs, const UString &rhs) noexcept { return lhs.Compare(rhs) < 0; } } // namespace Unicode
24.862832
105
0.681438
[ "vector" ]
ca1d0b652587217dbe600fec59f5e1837eb3a6b3
1,821
cpp
C++
src/thundersvm/model/nusvr.cpp
masterdoors/thundersvm
71634dacbb9db8cb5f02f7e8a7b77bf4d16e848c
[ "Apache-2.0" ]
null
null
null
src/thundersvm/model/nusvr.cpp
masterdoors/thundersvm
71634dacbb9db8cb5f02f7e8a7b77bf4d16e848c
[ "Apache-2.0" ]
null
null
null
src/thundersvm/model/nusvr.cpp
masterdoors/thundersvm
71634dacbb9db8cb5f02f7e8a7b77bf4d16e848c
[ "Apache-2.0" ]
null
null
null
// // Created by jiashuai on 17-10-30. // #include <thundersvm/model/nusvr.h> #include <thundersvm/solver/nusmosolver.h> void NuSVR::train(const DataSet &dataset, SvmParam param) { model_setup(dataset, param); int n_instances = dataset.n_instances(); //duplicate instances DataSet::node2d instances_2(dataset.instances()); instances_2.insert(instances_2.end(), dataset.instances().begin(), dataset.instances().end()); KernelMatrix kernelMatrix(instances_2, param); SyncArray<float_type> f_val(n_instances * 2); SyncArray<int> y(n_instances * 2); SyncArray<float_type> w(n_instances); SyncArray<float_type> alpha_2(n_instances * 2); float_type *f_val_data = f_val.host_data(); int *y_data = y.host_data(); float_type *w_data = w.host_data(); float_type *alpha_2_data = alpha_2.host_data(); float_type sum = param.C * param.nu * n_instances / 2; for (int i = 0; i < n_instances; ++i) { alpha_2_data[i] = alpha_2_data[i + n_instances] = min(sum, param.C); sum -= alpha_2_data[i]; f_val_data[i] = f_val_data[i + n_instances] = -dataset.y()[i]; y_data[i] = +1; y_data[i + n_instances] = -1; w_data[i] = param.C; } int ws_size = get_working_set_size(n_instances * 2, kernelMatrix.n_features()); NuSMOSolver solver(true); solver.solve(kernelMatrix, y, alpha_2, rho.host_data()[0], f_val, param.epsilon, w, param.C, param.C, ws_size, max_iter); save_svr_coef(alpha_2, dataset.instances()); if(param.kernel_type == SvmParam::LINEAR){ compute_linear_coef_single_model(dataset.n_features(), dataset.is_zero_based()); } } void NuSVR::model_setup(const DataSet &dataset, SvmParam &param) { SVR::model_setup(dataset, param); this->param.svm_type = SvmParam::NU_SVR; }
35.019231
125
0.676002
[ "model" ]
ca1e7c905d799662ee01551c7dc2fc0023406fba
4,582
cpp
C++
Utilities/Open3DMotion/src/Open3DMotion/OpenORM/Mappings/RichBinary/RichBinaryConvertFloat.cpp
mitkof6/BTKCore
d4c03aa9e354be16265d0efe0815c09b35abc642
[ "Barr", "Unlicense" ]
61
2015-04-21T20:40:37.000Z
2022-03-25T03:35:03.000Z
Utilities/Open3DMotion/src/Open3DMotion/OpenORM/Mappings/RichBinary/RichBinaryConvertFloat.cpp
mitkof6/BTKCore
d4c03aa9e354be16265d0efe0815c09b35abc642
[ "Barr", "Unlicense" ]
40
2018-03-11T15:14:50.000Z
2022-03-23T18:13:48.000Z
Utilities/Open3DMotion/src/Open3DMotion/OpenORM/Mappings/RichBinary/RichBinaryConvertFloat.cpp
mitkof6/BTKCore
d4c03aa9e354be16265d0efe0815c09b35abc642
[ "Barr", "Unlicense" ]
56
2015-05-11T11:04:35.000Z
2022-01-15T20:37:04.000Z
/*-- Open3DMotion Copyright (c) 2004-2012. All rights reserved. See LICENSE.txt for more information. --*/ #include "Open3DMotion/OpenORM/Mappings/RichBinary/RichBinary.h" #include "Open3DMotion/OpenORM/Mappings/RichBinary/BinMemFactory.h" #include "RichBinaryConvertFloat.h" namespace Open3DMotion { template<typename OutputType, typename InputType> TreeValue* RichBinaryConvertFields(const TreeValue* input, const char* structure_name, const BinMemFactory& memfactory); template<typename OutputType, typename InputType> TreeValue* RichBinaryConvertFields(const TreeValue* input, const char* structure_name, const BinMemFactory& memfactory) { // read input RichBinary rb_input(structure_name); rb_input.FromTree( input ); if (rb_input.DataStructure().TotalBytes() == 0) return NULL; // find fields to convert std::vector<BinaryFieldSpec> layout_output; const MapArrayCompound<BinaryFieldSpec>& layout_input = rb_input.DataStructure().GetLayout(); for (size_t ifield = 0; ifield < layout_input.NumElements(); ifield++) { const BinaryFieldSpec& field = layout_input[ifield]; if (field.Type.Value().compare(BinaryFieldTypeString<InputType>()) == 0) { layout_output.push_back(BinaryFieldSpec::FromType<OutputType>(field.Name.Value().c_str(), field.Dimension.Value())); } else { layout_output.push_back(field); } } // allocate new binary with new structure RichBinary rb_output(structure_name); size_t num_elements = rb_input.DataSizeBytes() / rb_input.DataStructure().TotalBytes(); rb_output.Allocate(layout_output, num_elements, memfactory); // copy data size_t input_bytes_accum(0); size_t output_bytes_accum(0); const UInt8* data_input = rb_input.Data(); UInt8* data_output = rb_output.Data(); for (size_t ifield = 0; ifield < layout_input.NumElements(); ifield++) { const BinaryFieldSpec& field_input = layout_input[ifield]; const BinaryFieldSpec& field_output = layout_output[ifield]; const UInt8* ptr_input = data_input + input_bytes_accum; UInt8* ptr_output = data_output + output_bytes_accum; size_t field_size_input(field_input.Bytes); size_t field_size_output(field_output.Bytes); size_t non_field_size_input = rb_input.DataStructure().TotalBytes() - field_size_input; size_t non_field_size_output = rb_output.DataStructure().TotalBytes() - field_size_output; if (field_input.Type.Value().compare(BinaryFieldTypeString<InputType>()) == 0) { // conversion size_t ndim = field_input.Dimension; for(size_t ielement = 0; ielement < num_elements; ielement++) { for (size_t idim = 0; idim < ndim; idim++) { *reinterpret_cast<OutputType*>(ptr_output) = static_cast<OutputType>(*reinterpret_cast<const InputType*>(ptr_input)); ptr_input += sizeof(InputType); ptr_output += sizeof(OutputType); } ptr_input += non_field_size_input; ptr_output += non_field_size_output; } } else { // straight copy other fields for(size_t ielement = 0; ielement < num_elements; ielement++) { for (size_t ibyte = 0; ibyte < field_size_input; ibyte++) *ptr_output++ = *ptr_input++; ptr_input += non_field_size_input; ptr_output += non_field_size_output; } } input_bytes_accum += field_size_input; output_bytes_accum += field_size_output; } // output TreeCompound* compound_output = TreeValueCast<TreeCompound> ( rb_output.ToTree() ); // copy any additional items to output const TreeCompound* compound_input = TreeValueCast<const TreeCompound> ( input ); size_t num_nodes = compound_input->NumElements(); for (size_t inode = 0; inode < num_nodes; inode++) { const TreeCompoundNode* node = compound_input->Node(inode); if (compound_output->Get(node->Name().c_str() ) == NULL) { TreeValue* output_value = node->Value()->NewBlank(); output_value->CopyFrom( node->Value() ); compound_output->Set(node->Name().c_str(), output_value); } } return compound_output; } TreeValue* RichBinaryConvertFloat32To64(const TreeValue* input, const char* structure_name, const BinMemFactory& memfactory) { return RichBinaryConvertFields<double, float> (input, structure_name, memfactory); } TreeValue* RichBinaryConvertFloat64To32(const TreeValue* input, const char* structure_name, const BinMemFactory& memfactory) { return RichBinaryConvertFields<float, double> (input, structure_name, memfactory); } }
37.867769
172
0.713226
[ "vector" ]
ca1ef6b86855895e3dd04c6e611fcb98cf7a2863
5,183
cpp
C++
src/widgets/audioportswidget.cpp
dehnhardt/mioconfig
6d1ac1d85379eaf168d2c2fce81b09f020500605
[ "MIT" ]
16
2018-07-16T14:13:10.000Z
2021-02-07T06:43:57.000Z
src/widgets/audioportswidget.cpp
dehnhardt/iconnconfig
6d1ac1d85379eaf168d2c2fce81b09f020500605
[ "MIT" ]
16
2017-09-06T19:38:15.000Z
2021-01-04T17:54:02.000Z
src/widgets/audioportswidget.cpp
dehnhardt/mioconfig
6d1ac1d85379eaf168d2c2fce81b09f020500605
[ "MIT" ]
10
2018-03-03T14:50:03.000Z
2020-09-30T18:08:55.000Z
#include "audioportswidget.h" #include "../sysex/getaudiodeviceparm.h" #include "../sysex/getaudioportparm.h" #include "../sysex/retcommandlist.h" #include "../sysex/retsetaudiodeviceparm.h" #include "../sysex/retsetaudioglobalparm.h" #include "audiocontrolparmwidget.h" #include "audioportparmwidget.h" #include "portdisplayhelper.h" #include <QLabel> #include <QListWidgetItem> #include <QScrollArea> AudioPortsWidget::AudioPortsWidget(MioMain *parent, Device *device, QString windowTitle) : MultiInfoWidget(parent, device, windowTitle) { m_pInfoSections = new std::vector<MultiInfoListEntry *>(); // m_pAudioPortParms = new AudioPortStructure(); if (device->getCommands()->isCommandSupported( Command::GET_AUDIO_PORT_PARM)) { retrieveAudioPorts(); getAudioPortSections(); } } AudioPortsWidget::~AudioPortsWidget() { AudioPortStructure::iterator it; for (it = m_pAudioPortParms->begin(); it != m_pAudioPortParms->end(); ++it) { std::vector<std::shared_ptr<RetSetAudioPortParm>> *audioPortParms = it->second; audioPortParms->clear(); delete audioPortParms; } m_pAudioPortParms->clear(); // delete m_pAudioPortParms; } void AudioPortsWidget::getAudioPorts( std::vector<std::shared_ptr<RetSetAudioPortParm>> *audioPortParms) { std::vector<std::shared_ptr<RetSetAudioPortParm>>::iterator it; for (it = audioPortParms->begin(); it != audioPortParms->end(); ++it) { std::shared_ptr<RetSetAudioPortParm> audioPortParm = *it; MultiInfoListEntry *entry = new MultiInfoListEntry( MultiInfoListEntry::PORT_ROUTING, audioPortParm->getPortName()); entry->icon = PortDisplayHelper::getAudioPortIcon( audioPortParm->getAudioPortType()); entry->message = audioPortParm; entry->enabled = true; m_pInfoSections->push_back(entry); } } void AudioPortsWidget::getAudioPortSections() { AudioPortStructure::iterator it; for (it = m_pAudioPortParms->begin(); it != m_pAudioPortParms->end(); ++it) { int section = it->first; pk::AudioPortType audioPortType = static_cast<pk::AudioPortType>(section); std::string portTypeName = PortDisplayHelper::getAudioPortTypeName(audioPortType); m_pInfoSections->push_back( new MultiInfoListEntry(MultiInfoListEntry::SECTION, portTypeName)); std::vector<std::shared_ptr<RetSetAudioPortParm>> *audioPortParms = it->second; getAudioPorts(audioPortParms); } } void AudioPortsWidget::retrieveAudioPorts() { /* unsigned int numberOfAudioPorts = device->getGlobalAudioParam()->getNumberOfAudioPorts(); std::unique_ptr<GetAudioPortParm> getAudioPortParm = std::make_unique<GetAudioPortParm>(device); getAudioPortParm->setDebug(false); for (unsigned int i = 1; i <= numberOfAudioPorts; i++) { std::vector<std::shared_ptr<RetSetAudioPortParm>> *audioPorts = nullptr; getAudioPortParm->setPortId(i); std::shared_ptr<RetSetAudioPortParm> retSetAudioPortParm = std::dynamic_pointer_cast<RetSetAudioPortParm>( getAudioPortParm->querySmart()); int audioPortType = retSetAudioPortParm->getAudioPortType(); try { audioPorts = m_pAudioPortParms->at(audioPortType); } catch (const std::out_of_range __attribute__((unused)) & oor) { audioPorts = new std::vector<std::shared_ptr<RetSetAudioPortParm>>(); m_pAudioPortParms->insert( std::pair<int, std::vector<std::shared_ptr<RetSetAudioPortParm>> *>( audioPortType, audioPorts)); } audioPorts->push_back(retSetAudioPortParm); } */ m_pAudioPortParms = m_pDevice->getAudioPortStructure(); } QWidget *AudioPortsWidget::createWidget(MultiInfoListEntry *entry) { std::shared_ptr<RetSetAudioPortParm> audioPortParm = std::dynamic_pointer_cast<RetSetAudioPortParm>(entry->message); unsigned int portId = audioPortParm->getPortId(); QTabWidget *audioPortTabWidget = new QTabWidget(this); QWidget *layoutWidget = new QWidget(); QVBoxLayout *layout = new QVBoxLayout(); AudioPortParmWidget *audioPortParmWidget = new AudioPortParmWidget(audioPortParm); connect(audioPortParmWidget, &AudioPortParmWidget::changePortName, entry, &MultiInfoListEntry::changeName); layout->addWidget(audioPortParmWidget); if (m_pDevice->getCommands()->isCommandSupported( Command::GET_AUDIO_DEVICE_PARM)) { std::unique_ptr<GetAudioDeviceParm> getAudioControlParm = std::make_unique<GetAudioDeviceParm>(m_pDevice); getAudioControlParm->setPortId(portId); std::shared_ptr<RetSetAudioDeviceParm> retSetAudioDeviceParm = std::dynamic_pointer_cast<RetSetAudioDeviceParm>( getAudioControlParm->querySmart()); audioPortParmWidget->setAudioDeviceParm(retSetAudioDeviceParm); if (retSetAudioDeviceParm->getMaxControllers() > 0) { AudioControlParmWidget *audioControlParmWidget = new AudioControlParmWidget(m_pDevice, portId, retSetAudioDeviceParm); QSizePolicy sp; sp.setHorizontalPolicy(QSizePolicy::Expanding); sp.setVerticalPolicy(QSizePolicy::Expanding); sp.setVerticalStretch(2); audioControlParmWidget->setSizePolicy(sp); layout->addWidget(audioControlParmWidget); } else { layout->addStretch(); } } layoutWidget->setLayout(layout); audioPortTabWidget->addTab(layoutWidget, "Audio-Port Info"); return audioPortTabWidget; }
36.5
76
0.762686
[ "vector" ]
ca20a75b788eb8b0072b619039291a8e173b8af6
3,758
cpp
C++
utils/examineBinary/examineBinary.cpp
NCIEVS/OPS-Native-Utilities
2ca0803ba1aa2ace8047673afe71d4e1f22d826d
[ "BSD-3-Clause" ]
null
null
null
utils/examineBinary/examineBinary.cpp
NCIEVS/OPS-Native-Utilities
2ca0803ba1aa2ace8047673afe71d4e1f22d826d
[ "BSD-3-Clause" ]
null
null
null
utils/examineBinary/examineBinary.cpp
NCIEVS/OPS-Native-Utilities
2ca0803ba1aa2ace8047673afe71d4e1f22d826d
[ "BSD-3-Clause" ]
null
null
null
// examines non-ascii characters and reports them with different options // #include <fstream> #include <iostream> #include <iomanip> #include <vector> #include <string> #include <cstdlib> // exit() #include "CommandLine.h" using namespace std; void showUsage(string prog) { cout << endl << "Usage:" << endl << "\t" << prog << " -[H|h][l][b][t][c] -f input-file" << endl; return; } void showDetailedUsage(string prog) { showUsage(prog); cout << endl << "where:" << endl << "\t" << "h or H: display this message" << endl << "\t" << "l: outputs line numbers" << endl << "\t" << "b: outputs position in file in bytes" << endl << "\t" << "t: outputs text up to the position in the line where character is found" << endl << "\t" << "c: outputs column position, subsequent chars will be increasingly offset" << endl << "\t" << "f: flag denotes the input-file to analyze" << endl << endl << "The program takes an input-file, examines characters, and outputs to stdout a report of the" << endl << " characters with the high bit set. If no input-file is entered, the program accepts input from stdin" << endl << "(e.g. piped or redirected), and requires a terminating EOF (or ^Z if entering text from keyboard)" << endl << "to process the input." << endl; return; } int main(int argc, char *argv[]) { CommandLine cmd(argc, argv); if( !cmd.hasAllOptionsIn("flbtc") ) { if( cmd.hasOption('H') || cmd.hasOption('h') ) showDetailedUsage(cmd.getProgramName()); else showUsage(cmd.getProgramName()); exit(0); } string inputfilename = ""; if( cmd.optionFlagsArgument('f') ) inputfilename = cmd.getFlaggedVariable('f'); streambuf *backcinstrm, *infilestrm; ifstream inputFile; if( inputfilename != "") { inputFile.open(inputfilename.c_str(), ios::binary | ios::in); if (inputFile.bad()) { cerr << "Can't open \"" << inputfilename.c_str() << ".\" Will EXIT." << endl; exit(0); } backcinstrm = cin.rdbuf(); infilestrm = inputFile.rdbuf(); cin.rdbuf(infilestrm); } bool alreadyFound = false; char tmpChar = 0, lstChar = 0; long filePos = 0; long startPos = 0; long lineNumber = 1; short mask = 0x00ff; vector<char> mStrbuffer; vector<char> linebuffer; while( !cin.eof() ) { lstChar = tmpChar; cin.get(tmpChar); linebuffer.push_back(tmpChar); filePos++; startPos++; if( tmpChar < 0 ) { mStrbuffer.push_back(tmpChar); if( !alreadyFound ) { cout << "! Found encoded character " << endl; alreadyFound = true; } if( lstChar > 0 ) { if( cmd.hasOption('l') ) cout << '\t' << "line " << lineNumber << "; "; if( cmd.hasOption('b') ) cout << "byte "<< filePos << "; "; if( cmd.hasOption('c') ) cout << "col " << startPos << "; "; } } else if( lstChar < 0 ) { // i.e. tmpChar > 0 for(unsigned i = 0; i < mStrbuffer.size(); i++) cout << mStrbuffer[i]; cout << " " << hex ; for(unsigned i = 0; i < mStrbuffer.size(); i++) cout << ' ' << ((static_cast<unsigned short> (mStrbuffer[i])) & mask); cout << dec ; if( cmd.hasOption('t') ) { cout << ": " ; for(unsigned i = 0; i < linebuffer.size(); i++) cout << linebuffer[i]; } cout << endl; mStrbuffer.clear(); } if( tmpChar == 10 ) { // counting LF only lineNumber++; startPos = 0; linebuffer.clear(); } } cout << "! Read " << filePos << " bytes in " << lineNumber << " lines." << endl; if( inputfilename != "") { cin.rdbuf(backcinstrm); inputFile.close(); } return 0; } // *****************************************************************
28.044776
117
0.56413
[ "vector" ]
ca2233a7fda8a09c4761ccddb4639849717b2c5f
9,436
cc
C++
ppapi/native_client/src/trusted/plugin/scriptable_plugin.cc
Scopetta197/chromium
b7bf8e39baadfd9089de2ebdc0c5d982de4a9820
[ "BSD-3-Clause" ]
212
2015-01-31T11:55:58.000Z
2022-02-22T06:35:11.000Z
ppapi/native_client/src/trusted/plugin/scriptable_plugin.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
5
2015-03-27T14:29:23.000Z
2019-09-25T13:23:12.000Z
ppapi/native_client/src/trusted/plugin/scriptable_plugin.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
221
2015-01-07T06:21:24.000Z
2022-02-11T02:51:12.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Scriptable plugin implementation. #include "native_client/src/trusted/plugin/scriptable_plugin.h" #include <string.h> #include <sstream> #include <string> #include <vector> #include "native_client/src/include/nacl_macros.h" #include "native_client/src/include/nacl_string.h" #include "native_client/src/include/portability.h" #include "native_client/src/shared/platform/nacl_check.h" #include "native_client/src/shared/srpc/nacl_srpc.h" #include "native_client/src/trusted/plugin/plugin.h" #include "native_client/src/trusted/plugin/utility.h" namespace plugin { namespace { pp::Var Error(const nacl::string& call_name, const char* caller, const char* error, pp::Var* exception) { nacl::stringstream error_stream; error_stream << call_name << ": " << error; if (!exception->is_undefined()) { error_stream << " - " + exception->AsString(); } // Get the error string in 2 steps; otherwise, the temporary string returned // by the stream is destructed, causing a dangling pointer. std::string str = error_stream.str(); const char* e = str.c_str(); PLUGIN_PRINTF(("ScriptablePlugin::%s (%s)\n", caller, e)); *exception = pp::Var(e); return pp::Var(); } // In JavaScript, foo[1] is equivalent to foo["1"], so map both indexed and // string names to a string. nacl::string NameAsString(const pp::Var& name) { if (name.is_string()) return name.AsString(); CHECK(name.is_int()); nacl::stringstream namestream; namestream << name.AsInt(); return namestream.str(); } // Returns a pp::Var corresponding to |arg| or void. Sets |exception| on error. pp::Var NaClSrpcArgToPPVar(const NaClSrpcArg* arg, pp::Var* exception) { PLUGIN_PRINTF((" NaClSrpcArgToPPVar (arg->tag='%c')\n", arg->tag)); pp::Var var; switch (arg->tag) { case NACL_SRPC_ARG_TYPE_BOOL: var = pp::Var(arg->u.bval != 0); break; case NACL_SRPC_ARG_TYPE_DOUBLE: var = pp::Var(arg->u.dval); break; case NACL_SRPC_ARG_TYPE_INT: var = pp::Var(arg->u.ival); break; case NACL_SRPC_ARG_TYPE_LONG: // PPAPI does not have a 64-bit integral type. Downcast. var = pp::Var(static_cast<int32_t>(arg->u.lval)); break; case NACL_SRPC_ARG_TYPE_STRING: var = pp::Var(arg->arrays.str); break; case NACL_SRPC_ARG_TYPE_CHAR_ARRAY: case NACL_SRPC_ARG_TYPE_DOUBLE_ARRAY: case NACL_SRPC_ARG_TYPE_INT_ARRAY: case NACL_SRPC_ARG_TYPE_LONG_ARRAY: case NACL_SRPC_ARG_TYPE_OBJECT: case NACL_SRPC_ARG_TYPE_HANDLE: case NACL_SRPC_ARG_TYPE_VARIANT_ARRAY: case NACL_SRPC_ARG_TYPE_INVALID: default: *exception = "variant array and invalid argument types are not supported"; } PLUGIN_PRINTF((" NaClSrpcArgToPPVar (return var=%s, exception=%s)\n", var.DebugString().c_str(), exception->DebugString().c_str())); return var; } } // namespace ScriptablePlugin::ScriptablePlugin(Plugin* plugin) : var_(NULL), num_unref_calls_(0), plugin_(plugin) { PLUGIN_PRINTF(("ScriptablePlugin::ScriptablePlugin (this=%p, plugin=%p)\n", static_cast<void*>(this), static_cast<void*>(plugin))); } ScriptablePlugin::~ScriptablePlugin() { PLUGIN_PRINTF(("ScriptablePlugin::~ScriptablePlugin (this=%p)\n", static_cast<void*>(this))); PLUGIN_PRINTF(("ScriptablePlugin::~ScriptablePlugin (this=%p, return)\n", static_cast<void*>(this))); } void ScriptablePlugin::Unref(ScriptablePlugin** handle) { if (*handle != NULL) { (*handle)->Unref(); *handle = NULL; } } ScriptablePlugin* ScriptablePlugin::NewPlugin(Plugin* plugin) { PLUGIN_PRINTF(("ScriptablePlugin::NewPlugin (plugin=%p)\n", static_cast<void*>(plugin))); if (plugin == NULL) { return NULL; } ScriptablePlugin* scriptable_plugin = new ScriptablePlugin(plugin); if (scriptable_plugin == NULL) { return NULL; } PLUGIN_PRINTF(("ScriptablePlugin::NewPlugin (return %p)\n", static_cast<void*>(scriptable_plugin))); return scriptable_plugin; } bool ScriptablePlugin::HasProperty(const pp::Var& name, pp::Var* exception) { UNREFERENCED_PARAMETER(exception); PLUGIN_PRINTF(("ScriptablePlugin::HasProperty (this=%p, name=%s)\n", static_cast<void*>(this), name.DebugString().c_str())); if (plugin_ == NULL) { return false; } if (!name.is_string() && !name.is_int()) return false; bool has_property = plugin_->HasProperty(name.AsString()); PLUGIN_PRINTF(("ScriptablePlugin::HasProperty (has_property=%d)\n", has_property)); return has_property; } bool ScriptablePlugin::HasMethod(const pp::Var& name, pp::Var* exception) { UNREFERENCED_PARAMETER(exception); PLUGIN_PRINTF(("ScriptablePlugin::HasMethod (this=%p, name='%s')\n", static_cast<void*>(this), name.DebugString().c_str())); return false; } pp::Var ScriptablePlugin::GetProperty(const pp::Var& name, pp::Var* exception) { PLUGIN_PRINTF(("ScriptablePlugin::GetProperty (name=%s)\n", name.DebugString().c_str())); if (plugin_ == NULL) { return pp::Var(); } // Get the property. NaClSrpcArg prop_value; nacl::string prop_name = NameAsString(name); if (!plugin_->GetProperty(prop_name, &prop_value)) { return Error(prop_name, "GetProperty", "invocation failed", exception); } PLUGIN_PRINTF(("ScriptablePlugin::GetProperty (invocation done)\n")); // Marshall output parameter. pp::Var property = NaClSrpcArgToPPVar(&prop_value, exception); if (!exception->is_undefined()) { return Error(prop_name, "GetProperty", "output marshalling failed", exception); } PLUGIN_PRINTF(("ScriptablePlugin::GetProperty (property=%s)\n", property.DebugString().c_str())); return property; } void ScriptablePlugin::SetProperty(const pp::Var& name, const pp::Var& value, pp::Var* exception) { PLUGIN_PRINTF(("ScriptablePlugin::SetProperty (name=%s, value=%s)\n", name.DebugString().c_str(), value.DebugString().c_str())); Error("SetProperty", name.DebugString().c_str(), "property setting is not supported", exception); } void ScriptablePlugin::RemoveProperty(const pp::Var& name, pp::Var* exception) { PLUGIN_PRINTF(("ScriptablePlugin::RemoveProperty (name=%s)\n", name.DebugString().c_str())); Error(NameAsString(name), "RemoveProperty", "property removal is not supported", exception); } void ScriptablePlugin::GetAllPropertyNames(std::vector<pp::Var>* properties, pp::Var* exception) { PLUGIN_PRINTF(("ScriptablePlugin::GetAllPropertyNames ()\n")); UNREFERENCED_PARAMETER(properties); UNREFERENCED_PARAMETER(exception); Error("GetAllPropertyNames", "", "GetAllPropertyNames is not supported", exception); } pp::Var ScriptablePlugin::Call(const pp::Var& name, const std::vector<pp::Var>& args, pp::Var* exception) { PLUGIN_PRINTF(("ScriptablePlugin::Call (name=%s, %"NACL_PRIuS " args)\n", name.DebugString().c_str(), args.size())); return Error("Call", name.DebugString().c_str(), "method invocation is not supported", exception); } pp::Var ScriptablePlugin::Construct(const std::vector<pp::Var>& args, pp::Var* exception) { PLUGIN_PRINTF(("ScriptablePlugin::Construct (%"NACL_PRIuS " args)\n", args.size())); return Error("constructor", "Construct", "constructor is not supported", exception); } ScriptablePlugin* ScriptablePlugin::AddRef() { // This is called when we are about to share this object with the browser, // and we need to make sure we have an internal plugin reference, so this // object doesn't get deallocated when the browser discards its references. if (var_ == NULL) { var_ = new pp::VarPrivate(plugin_, this); CHECK(var_ != NULL); } PLUGIN_PRINTF(("ScriptablePlugin::AddRef (this=%p, var=%p)\n", static_cast<void*>(this), static_cast<void*>(var_))); return this; } void ScriptablePlugin::Unref() { // We should have no more than one internal owner of this object, so this // should be called no more than once. CHECK(++num_unref_calls_ == 1); PLUGIN_PRINTF(("ScriptablePlugin::Unref (this=%p, var=%p)\n", static_cast<void*>(this), static_cast<void*>(var_))); if (var_ != NULL) { // We have shared this with the browser while keeping our own var // reference, but we no longer need ours. If the browser has copies, // it will clean things up later, otherwise this object will get // deallocated right away. PLUGIN_PRINTF(("ScriptablePlugin::Unref (delete var)\n")); pp::Var* var = var_; var_ = NULL; delete var; } else { // Neither the browser nor plugin ever var referenced this object, // so it can safely discarded. PLUGIN_PRINTF(("ScriptablePlugin::Unref (delete this)\n")); CHECK(var_ == NULL); delete this; } } } // namespace plugin
35.340824
80
0.656316
[ "object", "vector" ]
ca294fe29d50a02732dc1d97f6f9c15ece2948ed
2,385
cpp
C++
clients/gtest/stedc_gtest.cpp
rkamd/rocSOLVER
de338c6cfc78e9e00be141d11529b8faeaba911f
[ "BSD-2-Clause" ]
null
null
null
clients/gtest/stedc_gtest.cpp
rkamd/rocSOLVER
de338c6cfc78e9e00be141d11529b8faeaba911f
[ "BSD-2-Clause" ]
null
null
null
clients/gtest/stedc_gtest.cpp
rkamd/rocSOLVER
de338c6cfc78e9e00be141d11529b8faeaba911f
[ "BSD-2-Clause" ]
null
null
null
/* ************************************************************************ * Copyright (c) 2020-2022 Advanced Micro Devices, Inc. * * ************************************************************************ */ #include "testing_stedc.hpp" using ::testing::Combine; using ::testing::TestWithParam; using ::testing::Values; using ::testing::ValuesIn; using namespace std; typedef std::tuple<vector<int>, printable_char> stedc_tuple; // each size_range vector is a {N, ldc} // each op_range vector is a {e} // case when N == 0 and evect == N will also execute the bad arguments test // (null handle, null pointers and invalid values) const vector<printable_char> op_range = {'N', 'I', 'V'}; // for checkin_lapack tests const vector<vector<int>> matrix_size_range = { // quick return {0, 1}, // invalid {-1, 1}, // invalid for case evect != N {2, 1}, // normal (valid) samples {12, 12}, {20, 30}, {35, 40}}; // for daily_lapack tests const vector<vector<int>> large_matrix_size_range = {{192, 192}, {256, 270}, {300, 300}}; Arguments stedc_setup_arguments(stedc_tuple tup) { vector<int> size = std::get<0>(tup); char op = std::get<1>(tup); Arguments arg; arg.set<rocblas_int>("n", size[0]); arg.set<rocblas_int>("ldc", size[1]); arg.set<char>("evect", op); arg.timing = 0; return arg; } class STEDC : public ::TestWithParam<stedc_tuple> { protected: STEDC() {} virtual void SetUp() {} virtual void TearDown() {} template <typename T> void run_tests() { Arguments arg = stedc_setup_arguments(GetParam()); if(arg.peek<rocblas_int>("n") == 0 && arg.peek<char>("evect") == 'N') testing_stedc_bad_arg<T>(); testing_stedc<T>(arg); } }; // non-batch tests TEST_P(STEDC, __float) { run_tests<float>(); } TEST_P(STEDC, __double) { run_tests<double>(); } TEST_P(STEDC, __float_complex) { run_tests<rocblas_float_complex>(); } TEST_P(STEDC, __double_complex) { run_tests<rocblas_double_complex>(); } INSTANTIATE_TEST_SUITE_P(daily_lapack, STEDC, Combine(ValuesIn(large_matrix_size_range), ValuesIn(op_range))); INSTANTIATE_TEST_SUITE_P(checkin_lapack, STEDC, Combine(ValuesIn(matrix_size_range), ValuesIn(op_range)));
22.5
89
0.586164
[ "vector" ]
ca2a869bef4eabcf66514527a38189e41299ed6a
5,287
cpp
C++
source/MaterialXRuntime/RtTypeDef.cpp
edgarv/MaterialX
b11267b2920c6645d44be6ff09de79a7eb853de2
[ "BSD-3-Clause" ]
null
null
null
source/MaterialXRuntime/RtTypeDef.cpp
edgarv/MaterialX
b11267b2920c6645d44be6ff09de79a7eb853de2
[ "BSD-3-Clause" ]
null
null
null
source/MaterialXRuntime/RtTypeDef.cpp
edgarv/MaterialX
b11267b2920c6645d44be6ff09de79a7eb853de2
[ "BSD-3-Clause" ]
null
null
null
// // TM & (c) 2017 Lucasfilm Entertainment Company Ltd. and Lucasfilm Ltd. // All rights reserved. See LICENSE.txt for license. // #include <MaterialXRuntime/RtTypeDef.h> #include <MaterialXRuntime/Private/PvtTypeDef.h> namespace MaterialX { const RtToken RtType::BOOLEAN("boolean"); const RtToken RtType::INTEGER("integer"); const RtToken RtType::FLOAT("float"); const RtToken RtType::VECTOR2("vector2"); const RtToken RtType::VECTOR3("vector3"); const RtToken RtType::VECTOR4("vector4"); const RtToken RtType::COLOR2("color2"); const RtToken RtType::COLOR3("color3"); const RtToken RtType::COLOR4("color4"); const RtToken RtType::MATRIX33("matrix33"); const RtToken RtType::MATRIX44("matrix44"); const RtToken RtType::TOKEN("token"); const RtToken RtType::STRING("string"); const RtToken RtType::FILENAME("filename"); const RtToken RtType::INTEGERARRAY("integerarray"); const RtToken RtType::FLOATARRAY("floatarray"); const RtToken RtType::COLOR2ARRAY("color2array"); const RtToken RtType::COLOR3ARRAY("color3array"); const RtToken RtType::COLOR4ARRAY("color4array"); const RtToken RtType::VECTOR2ARRAY("vector2array"); const RtToken RtType::VECTOR3ARRAY("vector3array"); const RtToken RtType::VECTOR4ARRAY("vector4array"); const RtToken RtType::STRINGARRAY("stringarray"); const RtToken RtType::BSDF("BSDF"); const RtToken RtType::EDF("EDF"); const RtToken RtType::VDF("VDF"); const RtToken RtType::SURFACESHADER("surfaceshader"); const RtToken RtType::VOLUMESHADER("volumeshader"); const RtToken RtType::DISPLACEMENTSHADER("displacementshader"); const RtToken RtType::LIGHTSHADER("lightshader"); const RtToken RtType::MATERIAL("material"); const RtToken RtType::AUTO("auto"); const RtToken RtTypeDef::BASETYPE_NONE("none"); const RtToken RtTypeDef::BASETYPE_BOOLEAN("boolean"); const RtToken RtTypeDef::BASETYPE_FLOAT("float"); const RtToken RtTypeDef::BASETYPE_INTEGER("integer"); const RtToken RtTypeDef::BASETYPE_STRING("string"); const RtToken RtTypeDef::BASETYPE_STRUCT("struct"); const RtToken RtTypeDef::SEMANTIC_NONE("none"); const RtToken RtTypeDef::SEMANTIC_COLOR("color"); const RtToken RtTypeDef::SEMANTIC_VECTOR("vector"); const RtToken RtTypeDef::SEMANTIC_MATRIX("matrix"); const RtToken RtTypeDef::SEMANTIC_FILENAME("filename"); const RtToken RtTypeDef::SEMANTIC_CLOSURE("closure"); const RtToken RtTypeDef::SEMANTIC_SHADER("shader"); const RtToken RtTypeDef::SEMANTIC_MATERIAL("material"); RtTypeDef::RtTypeDef(const RtToken& name, const RtToken& basetype, const RtValueFuncs& funcs, const RtToken& semantic, size_t size) : _ptr(new PvtTypeDef(name, basetype, funcs, semantic, size)) { } RtTypeDef::~RtTypeDef() { delete static_cast<PvtTypeDef*>(_ptr); } RtValue RtTypeDef::createValue(RtObject& owner) const { return static_cast<PvtTypeDef*>(_ptr)->getValueFuncs().create(owner); } void RtTypeDef::copyValue(const RtValue& src, RtValue& dest) const { static_cast<PvtTypeDef*>(_ptr)->getValueFuncs().copy(src, dest); } bool RtTypeDef::compareValue(const RtValue& a, const RtValue& b) const { return static_cast<PvtTypeDef*>(_ptr)->getValueFuncs().compare(a, b); } void RtTypeDef::toStringValue(const RtValue& src, string& dest) const { static_cast<PvtTypeDef*>(_ptr)->getValueFuncs().toString(src, dest); } void RtTypeDef::fromStringValue(const string& src, RtValue& dest) const { static_cast<PvtTypeDef*>(_ptr)->getValueFuncs().fromString(src, dest); } const RtToken& RtTypeDef::getName() const { return static_cast<PvtTypeDef*>(_ptr)->getName(); } const RtToken& RtTypeDef::getBaseType() const { return static_cast<PvtTypeDef*>(_ptr)->getBaseType(); } const RtToken& RtTypeDef::getSemantic() const { return static_cast<PvtTypeDef*>(_ptr)->getSemantic(); } size_t RtTypeDef::getSize() const { return static_cast<PvtTypeDef*>(_ptr)->getSize(); } void RtTypeDef::setComponent(size_t index, const RtToken& name, const RtToken& basetype) { static_cast<PvtTypeDef*>(_ptr)->setComponent(index, name, basetype); } size_t RtTypeDef::getComponentIndex(const RtToken& name) const { return static_cast<PvtTypeDef*>(_ptr)->getComponentIndex(name); } const RtToken& RtTypeDef::getComponentName(size_t index) const { return static_cast<PvtTypeDef*>(_ptr)->getComponentName(index); } const RtToken& RtTypeDef::getComponentBaseType(size_t index) const { return static_cast<PvtTypeDef*>(_ptr)->getComponentBaseType(index); } const RtTokenSet& RtTypeDef::getValidConnectionTypes() const { return static_cast<PvtTypeDef*>(_ptr)->getValidConnectionTypes(); } RtTypeDef* RtTypeDef::registerType(const RtToken& name, const RtToken& basetype, const RtValueFuncs& funcs, const RtToken& semantic, size_t size) { if (PvtTypeDefRegistry::get().findType(name)) { throw ExceptionRuntimeError("A type named '" + name.str() + "' is already registered"); } return PvtTypeDefRegistry::get().newType(name, basetype, funcs, semantic, size); } size_t RtTypeDef::numTypes() { return PvtTypeDefRegistry::get().numTypes(); } const RtTypeDef* RtTypeDef::getType(size_t index) { return PvtTypeDefRegistry::get().getType(index); } const RtTypeDef* RtTypeDef::findType(const RtToken& name) { return PvtTypeDefRegistry::get().findType(name); } }
31.470238
133
0.752601
[ "vector" ]
ca2aa83b9c10c4d1557c99feb9f3e7f8ea9721ef
9,039
cpp
C++
tests/extension/extension.cpp
jpmaloney/basic
13f4bb3643c2ff83577bf1bd3672e84b12bd613d
[ "Apache-2.0" ]
null
null
null
tests/extension/extension.cpp
jpmaloney/basic
13f4bb3643c2ff83577bf1bd3672e84b12bd613d
[ "Apache-2.0" ]
null
null
null
tests/extension/extension.cpp
jpmaloney/basic
13f4bb3643c2ff83577bf1bd3672e84b12bd613d
[ "Apache-2.0" ]
null
null
null
// Copyright 2012 John P. Maloney // // Distributed under the Apache License, Version 2.0. // (See accompanying file LICENSE_2_0 or copy at // http://www.apache.org/licenses/LICENSE-2.0) #include <array> #include <cstdlib> #include <iostream> #include <memory> #include <string> #include <vector> #include "extension.hpp" using std::array; using std::cout; using std::endl; using std::string; using std::vector; namespace { void usage() { cout << "Usage: extension [integer ...]\n" "Output for each integer: integer+1, 2*integer\n" << endl; } } // End local namespace. namespace example1 { auto const desc = "No substitution"; inline int f_increment( int i ) { return i + 1; } inline int f_double( int i ) { return i + i; } void test_f_increment( int i ) { cout << "example1: f_increment( " << i << " ) -> " << f_increment( i ) << endl; } void test_f_double( int i ) { cout << "example1: f_double( " << i << " ) -> " << f_double( i ) << endl; } void test( int i ) { test_f_increment( i ); test_f_double( i ); } template<typename Sequence> void main( Sequence s ) { for ( auto const value : s ) test( value ); } } // End namespace example1. namespace example2 { auto const desc = "Run-time substitution via pointer-to-function"; namespace library { typedef int (*func_t)( int ); void test( func_t f, int i ) { cout << "example2: fx( " << i << " ) -> " << f( i ) << endl; } } // End namespace library. namespace application { inline int f_increment( int i ) { return i + 1; } inline int f_double( int i ) { return i + i; } void test( int i ) { library::test( f_increment, i ); library::test( f_double, i ); } } // End namespace application. template<typename Sequence> void main( Sequence s ) { for ( auto const value : s ) application::test( value ); } } // End namespace example2. namespace example3 { auto const desc = "Run-time substitution via virtual function"; namespace library { class abstract_f { public: virtual ~abstract_f() {} virtual int operator()( int ) const = 0; }; void test( abstract_f const& f, int i ) { cout << "example3: fx( " << i << " ) -> " << f( i ) << endl; } } // End namespace library. namespace application { class f_increment : public library::abstract_f { public: virtual int operator()( int i ) const { return i + 1; } }; class f_double : public library::abstract_f { public: virtual int operator()( int i ) const { return i + i; } }; void test( int i ) { library::test( f_increment(), i ); library::test( f_double(), i ); } } // End namespace application. template<typename Sequence> void main( Sequence s ) { for ( auto const value : s ) application::test( value ); } } // End namespace example3. namespace example4 { auto const desc = "Compile-time substitution via function-as-template-parameter"; namespace library { template<typename Func> void test( Func f, int i ) { cout << "example4: fx( " << i << " ) -> " << f( i ) << endl; } } // End namespace library. namespace application { inline int f_increment( int i ) { return i + 1; } inline int f_double( int i ) { return i + i; } void test( int i ) { library::test( f_increment, i ); library::test( f_double, i ); } } // End namespace application. template<typename Sequence> void main( Sequence s ) { for ( auto const value : s ) application::test( value ); } } // End namespace example4. namespace example5 { auto const desc = "Compile-time substitution via function object"; namespace library { template<typename Func> void test( Func f, int i ) { cout << "example5: fx( " << i << " ) -> " << f( i ) << endl; } } // End namespace library. namespace application { class f_increment { public: int operator()( int i ) const { return i + 1; } }; class f_double { public: int operator()( int i ) const { return i + i; } }; void test( int i ) { library::test( f_increment(), i ); library::test( f_double(), i ); } } // End namespace application. template<typename Sequence> void main( Sequence s ) { for ( auto const value : s ) application::test( value ); } } // End namespace example5. namespace example6 { auto const desc = "Compile-time substitution via argument dependent lookup (ADL)"; namespace library { template<typename Arg> void test( Arg a ) { // In all cases, this function calls the function 'f' without // a namespace specifier. cout << "example6: fx( " << a << " ) -> " << f( a ) << endl; } //---------------------------- string f( int i ) { return __PRETTY_FUNCTION__; } //---------------------------- class arg_lib_only { public: int i; }; std::ostream& operator<<( std::ostream& os, arg_lib_only const& rhs ) { return os << __PRETTY_FUNCTION__; } string f( arg_lib_only a ) { return __PRETTY_FUNCTION__; } //---------------------------- class arg_both { public: int i; }; std::ostream& operator<<( std::ostream& os, arg_both const& rhs ) { return os << __PRETTY_FUNCTION__; } string f( arg_both a ) { return __PRETTY_FUNCTION__; } //---------------------------- class arg_lib_func_lib { public: int i; }; std::ostream& operator<<( std::ostream& os, arg_lib_func_lib const& rhs ) { return os << __PRETTY_FUNCTION__; } string f( arg_lib_func_lib a ) { return __PRETTY_FUNCTION__; } //---------------------------- class arg_lib_func_both { public: int i; }; std::ostream& operator<<( std::ostream& os, arg_lib_func_both const& rhs ) { return os << __PRETTY_FUNCTION__; } string f( arg_lib_func_both a ) { return __PRETTY_FUNCTION__; } } // End namespace library. namespace application { string f( int i ) { return __PRETTY_FUNCTION__; } //---------------------------- class arg_app_only { public: int i; }; std::ostream& operator<<( std::ostream& os, arg_app_only const& rhs ) { return os << __PRETTY_FUNCTION__; } string f( arg_app_only a ) { return __PRETTY_FUNCTION__; } //---------------------------- class arg_both { public: int i; }; std::ostream& operator<<( std::ostream& os, arg_both const& rhs ) { return os << __PRETTY_FUNCTION__; } string f( arg_both a ) { return __PRETTY_FUNCTION__; } //---------------------------- // class arg_lib_func_both is defined in the library. std::ostream& operator<<( std::ostream& os, library::arg_lib_func_both const& rhs ) { return os << __PRETTY_FUNCTION__; } string f( library::arg_lib_func_both a ) { return __PRETTY_FUNCTION__; } //---------------------------- void test( int i ) { library::test( i ); library::test( library::arg_lib_only{ i } ); library::test( application::arg_app_only{ i } ); library::test( library::arg_both{ i } ); library::test( application::arg_both{ i } ); library::test( library::arg_lib_func_lib{ i } ); library::test( library::arg_lib_func_both{ i } ); } } // End namespace application. template<typename Sequence> void main( Sequence s ) { for ( auto const value : s ) application::test( value ); } } // End namespace example6. namespace { template<typename Func, typename Sequence, typename Desc> void test( Func f, Sequence s, Desc d ) { auto const line = "==========================================="; cout << line << endl; cout << d << endl; f( s ); cout << line << endl; } vector<int> parse( int argc, char* argv[] ) { vector<int> result; if ( argc <= 1 ) { result = { 1, 2 }; } else { for ( auto i = 1; i != argc; ++i ) result.push_back( atoi( argv[i] ) ); } return result; } } // End local namespace. int main( int argc, char* argv[] ) { if ( argc <= 1 ) usage(); auto const values = parse( argc, argv ); test( example1::main<decltype(values)>, values, example1::desc ); test( example2::main<decltype(values)>, values, example2::desc ); test( example3::main<decltype(values)>, values, example3::desc ); test( example4::main<decltype(values)>, values, example4::desc ); test( example5::main<decltype(values)>, values, example5::desc ); test( example6::main<decltype(values)>, values, example6::desc ); return 0; }
18.637113
87
0.554597
[ "object", "vector" ]
ca2e8e06e67760130416a855866f953864f3112a
848
cpp
C++
watchman/Shutdown.cpp
chadaustin/watchman
b01a841f3eca5ebaf5ce4a62e1937c95851f450e
[ "MIT" ]
9,308
2015-01-03T13:33:47.000Z
2022-03-31T06:45:26.000Z
watchman/Shutdown.cpp
00mjk/watchman
eb22a60e74f04065e24eb51ba1dd1342d66f2ad6
[ "MIT" ]
878
2015-01-07T15:28:33.000Z
2022-03-30T09:30:10.000Z
watchman/Shutdown.cpp
00mjk/watchman
eb22a60e74f04065e24eb51ba1dd1342d66f2ad6
[ "MIT" ]
932
2015-01-05T08:25:00.000Z
2022-03-25T11:11:42.000Z
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "watchman/Shutdown.h" #include <atomic> #include <vector> #include "watchman/watchman_stream.h" namespace { static std::vector<std::shared_ptr<watchman_event>> listener_thread_events; static std::atomic<bool> stopping = false; } // namespace bool w_is_stopping() { return stopping.load(std::memory_order_relaxed); } void w_request_shutdown() { stopping.store(true, std::memory_order_relaxed); // Knock listener thread out of poll/accept for (auto& evt : listener_thread_events) { evt->notify(); } } void w_push_listener_thread_event(std::shared_ptr<watchman_event> event) { listener_thread_events.push_back(std::move(event)); }
24.228571
75
0.744104
[ "vector" ]
ca32b9c88a59dc0038e6aadbf44a518fd8744af4
400
cpp
C++
455_Assign_Cookies.cpp
onlyless/leetcode
6ef9ab502dec94e94cc23e13f69fffce1f508c24
[ "Apache-2.0" ]
null
null
null
455_Assign_Cookies.cpp
onlyless/leetcode
6ef9ab502dec94e94cc23e13f69fffce1f508c24
[ "Apache-2.0" ]
null
null
null
455_Assign_Cookies.cpp
onlyless/leetcode
6ef9ab502dec94e94cc23e13f69fffce1f508c24
[ "Apache-2.0" ]
null
null
null
class Solution { public: int findContentChildren(vector<int>& g, vector<int>& s) { sort(g.begin(),g.end()); sort(s.begin(),s.end()); int ans=0; int index=0; for(int i=0;i<s.size();i++){ if(g[index]<=s[i]){ ans++; index++; } if(index>=g.size())break; } return ans; } };
23.529412
61
0.41
[ "vector" ]
ca35ea129d31753c871b92fdaad19b7194e93f07
8,800
cpp
C++
moveitCpp/rviz/environment.cpp
awied1404/COPING
0fe36c1835928db15fb36f752ca83f8d2c2e33d4
[ "MIT" ]
null
null
null
moveitCpp/rviz/environment.cpp
awied1404/COPING
0fe36c1835928db15fb36f752ca83f8d2c2e33d4
[ "MIT" ]
null
null
null
moveitCpp/rviz/environment.cpp
awied1404/COPING
0fe36c1835928db15fb36f752ca83f8d2c2e33d4
[ "MIT" ]
null
null
null
// // Created by andreas on 06.11.20. // #include "environment.h" #include <tf2_eigen/tf2_eigen.h> #ifdef LOG_RESULTS extern LogFile logFile; #endif /*LOG_RESULTS*/ moveit_msgs::CollisionObject Environment::objectToGrip; double Environment::positionPrinterX; double Environment::positionPrinterY; std::string Environment::sObjectToGripName; char* Environment::pcRobotPosition; /** * @fn void Environment::init(moveit::planning_interface::MoveGroupInterface &moveGroup, char ** argv) * @brief init environment with all objects to be gripped and obstacles * @param moveGroup moveit group interface with information about frame names * @param argv arguments with name of object to grip */ void Environment::init(moveit::planning_interface::MoveGroupInterface &moveGroup, char ** argv) { pcRobotPosition = argv[3]; moveit_msgs::CollisionObject printer; printer.header.frame_id = moveGroup.getPlanningFrame(); printer.id = "printer"; shapes::Mesh* m = shapes::createMeshFromResource("file://" + std::string(argv[8])); shape_msgs::Mesh printerMesh; shapes::ShapeMsg printerMeshMsg; shapes::constructMsgFromShape(m,printerMeshMsg); printerMesh = boost::get<shape_msgs::Mesh>(printerMeshMsg); printer.meshes.resize(1); printer.meshes[0] = printerMesh; printer.mesh_poses.resize(1); if(std::strcmp(pcRobotPosition, "right") == 0) { positionPrinterX = 0.0; if(bSoftGripperUsed) { positionPrinterY = -0.42; /* to get better results the robot needs to be further away */ } else { positionPrinterY = -0.35; } orientationPrinterZ = -0.707; orientationPrinterW = 0.707; } else if(std::strcmp(pcRobotPosition, "front") == 0) { positionPrinterX = 0.035; if(bSoftGripperUsed) { positionPrinterY = -0.45; /* to get better results the robot needs to be further away */ } else { positionPrinterY = -0.37; } } else if(std::strcmp(pcRobotPosition, "left") == 0) { positionPrinterX = 0; if(bSoftGripperUsed) { positionPrinterY = -0.40; /* to get better results the robot needs to be further away */ } else { positionPrinterY = -0.31; } orientationPrinterZ = 0.707; orientationPrinterW = 0.707; } else { std::cerr << "No position of robot defined" << std::endl; } #ifdef LOG_RESULTS std::string string = ROBOT_POSITION; string.append(pcRobotPosition); logFile.write(string, true); #endif /*LOG_RESULTS*/ printer.mesh_poses[0].position.x = positionPrinterX; printer.mesh_poses[0].position.y = positionPrinterY; printer.mesh_poses[0].position.z = positionPrinterZ; printer.mesh_poses[0].orientation.w= orientationPrinterW; printer.mesh_poses[0].orientation.x= 0.0; printer.mesh_poses[0].orientation.y= 0.0; printer.mesh_poses[0].orientation.z= orientationPrinterZ; printer.meshes.push_back(printerMesh); printer.mesh_poses.push_back(printer.mesh_poses[0]); printer.operation = printer.ADD; collisionObjects.push_back(printer); objectToGrip.header.frame_id = moveGroup.getPlanningFrame(); objectToGrip.id = "object"; /* if we scale the shape by a factor of 0.001 (which means a conversion from mm to m) we only need one stl file: * the one for grasp planning component which needs in mm and moveit which needs the objects in m */ Eigen::Vector3d scalingVector; scalingVector[0] = 0.001; scalingVector[1] = 0.001; scalingVector[2] = 0.001; shapes::Mesh* cubeM = shapes::createMeshFromResource("file://" + std::string(argv[1]), scalingVector); shape_msgs::Mesh cubeMesh; shapes::ShapeMsg cubeMeshMsg; shapes::constructMsgFromShape(cubeM,cubeMeshMsg); cubeMesh = boost::get<shape_msgs::Mesh>(cubeMeshMsg); objectToGrip.meshes.resize(1); objectToGrip.meshes[0] = cubeMesh; objectToGrip.mesh_poses.resize(1); objectToGrip.mesh_poses[0].position.x = positionPrinterX + positionObjectX; objectToGrip.mesh_poses[0].position.y = positionPrinterY + positionObjectY; objectToGrip.mesh_poses[0].position.z = positionPrinterZ + positionObjectZ; objectToGrip.mesh_poses[0].orientation.w= orientationPrinterW; objectToGrip.mesh_poses[0].orientation.x= 0.0; objectToGrip.mesh_poses[0].orientation.y= 0.0; objectToGrip.mesh_poses[0].orientation.z= orientationPrinterZ; objectToGrip.meshes.push_back(cubeMesh); objectToGrip.mesh_poses.push_back(objectToGrip.mesh_poses[0]); objectToGrip.operation = objectToGrip.ADD; Eigen::Isometry3d eigenBoxPose; tf2::fromMsg(objectToGrip.mesh_poses[0], eigenBoxPose); collisionObjects.push_back(objectToGrip); moveit_msgs::CollisionObject table; table.header.frame_id = moveGroup.getPlanningFrame(); table.id = "table"; shape_msgs::SolidPrimitive tableSolid; tableSolid.type = tableSolid.BOX; tableSolid.dimensions.resize(3); tableSolid.dimensions[0] = 1.62; tableSolid.dimensions[1] = 1.0; tableSolid.dimensions[2] = 0.01; geometry_msgs::Pose tablePose; tablePose.orientation.y = 1.5708; tablePose.position.x = 0; tablePose.position.y = 0; tablePose.position.z = -0.04 + 0.03182; table.primitives.push_back(tableSolid); table.primitive_poses.push_back(tablePose); table.operation = table.ADD; collisionObjects.push_back(table); objectToPlace.header.frame_id = moveGroup.getPlanningFrame(); objectToPlace.id = "boxToPlaceObject"; shapes::Mesh* tableM = shapes::createMeshFromResource("file://" + std::string(argv[7])); shape_msgs::Mesh tableMesh; shapes::ShapeMsg tableMeshMsg; shapes::constructMsgFromShape(tableM,tableMeshMsg); tableMesh = boost::get<shape_msgs::Mesh>(tableMeshMsg); objectToPlace.meshes.resize(1); objectToPlace.meshes[0] = tableMesh; objectToPlace.mesh_poses.resize(1); objectToPlace.mesh_poses[0].position.x = 0.5; objectToPlace.mesh_poses[0].position.y = 0.34; objectToPlace.mesh_poses[0].position.z = 0.13 - HEIGHT_YOUBOT_PLATE; objectToPlace.mesh_poses[0].orientation.w= 1; objectToPlace.mesh_poses[0].orientation.x= 0.0; objectToPlace.mesh_poses[0].orientation.y= 0.0; objectToPlace.mesh_poses[0].orientation.z= 0.0; objectToPlace.meshes.push_back(tableMesh); objectToPlace.mesh_poses.push_back(objectToPlace.mesh_poses[0]); objectToPlace.operation = objectToPlace.ADD; collisionObjects.push_back(objectToPlace); extractObjectNameFromFilePath(argv[1]); } /** * @fn std::vector<moveit_msgs::CollisionObject> Environment::getEnvironment() * @brief environment with all collision objects in this world * @return vector with all collision objects */ std::vector<moveit_msgs::CollisionObject> Environment::getEnvironment() { return collisionObjects; } /** * @fn moveit_msgs::CollisionObject Environment::getObjectToGrip() * @brief returns object that should be gripped as a moveit collision object * @return object to grip */ moveit_msgs::CollisionObject Environment::getObjectToGrip() { return objectToGrip; } /** * @fn Environment::Environment() * @brief constructor where environment finds out whether softgripper is used or not */ Environment::Environment() { char * pcUsedRobot = getenv(USED_ROBOT_ENV); if(pcUsedRobot == NULL) { std::cerr << "You have to define the robot used with env variable " << USED_ROBOT_ENV << std::endl; std::cerr << "You can either use" << USED_ROBOT_YOUBOT << " or " << USED_ROBOT_YOUBOT_SOFT << std::endl; exit(-1); } else if(strcmp(pcUsedRobot, USED_ROBOT_YOUBOT) == 0) { bSoftGripperUsed = false; } else if(strcmp(pcUsedRobot, USED_ROBOT_YOUBOT_SOFT) == 0) { bSoftGripperUsed = true; } } std::string Environment::getRobotPosition() { std::string returnValue(pcRobotPosition); return returnValue; } void Environment::extractObjectNameFromFilePath(char * pcFilePath) { char * pcTokens = strtok(pcFilePath, "/"); std::string sWholeString(pcTokens); while(pcTokens) { pcTokens = strtok(NULL, "/"); if(pcTokens != NULL) { sWholeString = pcTokens; } } char * pcSubstring = ".stl"; std::string sSubString(pcSubstring); int iPosFound = sWholeString.find(sSubString); sObjectToGripName = sWholeString.substr(0, iPosFound); } std::string Environment::getObjectName() { return sObjectToGripName; } void Environment::getPrinterPosition(double &dX, double &dY) { dX = positionPrinterX; dY = positionPrinterY; }
32.958801
116
0.692955
[ "mesh", "object", "shape", "vector" ]
ca381e53aaf70d607b730107af33459dc4ba27fb
10,179
cpp
C++
library/cge/src/filters/cgeMultipleEffects.cpp
Rahulclaritaz/rahul
c2a11d584895362ec2b6ca8cff0b94acdf4408c4
[ "MIT" ]
null
null
null
library/cge/src/filters/cgeMultipleEffects.cpp
Rahulclaritaz/rahul
c2a11d584895362ec2b6ca8cff0b94acdf4408c4
[ "MIT" ]
116
2017-05-04T14:10:36.000Z
2017-10-13T12:00:21.000Z
library/cge/src/filters/cgeMultipleEffects.cpp
Rahulclaritaz/rahul
c2a11d584895362ec2b6ca8cff0b94acdf4408c4
[ "MIT" ]
1
2019-10-17T04:10:34.000Z
2019-10-17T04:10:34.000Z
/* * cgeMultipleEffects.cpp * * Created on: 2013-12-13 * Author: Wang Yang * Mail: admin@wysaid.org */ #include "cgeMultipleEffects.h" #include "cgeDataParsingEngine.h" #include <cmath> #include <cctype> static CGEConstString s_fshHTFilterMix = CGE_SHADER_STRING_PRECISION_M ( varying vec2 textureCoordinate; uniform sampler2D inputImageTexture; uniform sampler2D originImageTexture; uniform float intensity; void main() { vec4 src = texture2D(inputImageTexture, textureCoordinate); vec4 origin = texture2D(originImageTexture, textureCoordinate); gl_FragColor = mix(origin, src, intensity); } ); namespace CGE { CGEConstString CGEMutipleMixFilter::paramIntensityName = "intensity"; CGEConstString CGEMutipleMixFilter::paramOriginImageName = "originImageTexture"; bool CGEMutipleMixFilter::init() { if(initShadersFromString(g_vshDefaultWithoutTexCoord, s_fshHTFilterMix)) { m_program.bind(); m_program.sendUniformi(paramOriginImageName, 1); setIntensity(1.0f); return true; } return false; } void CGEMutipleMixFilter::setIntensity(float value) { m_intensity = value; m_program.bind(); m_program.sendUniformf(paramIntensityName, m_intensity); } void CGEMutipleMixFilter::render2Texture(CGEImageHandlerInterface* handler, GLuint srcTexture, GLuint vertexBufferID) { handler->setAsTarget(); m_program.bind(); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, handler->getBufferTextureID()); if(m_uniformParam != nullptr) m_uniformParam->assignUniforms(handler, m_program.programID()); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, srcTexture); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); cgeCheckGLError("glDrawArrays"); } bool CGEMutipleMixFilter::needToMix() { return fabsf(m_intensity - 1.0f) > 0.01f; } bool CGEMutipleMixFilter::noIntensity() { return fabsf(m_intensity) < 0.01f; } ////////////////////////////////////////////////////////////////////////// CGEMutipleEffectFilter::CGEMutipleEffectFilter() : m_loadFunc(nullptr), m_unloadFunc(nullptr), m_loadParam(nullptr), m_unloadParam(nullptr), m_texCache(0), m_isWrapper(false), m_texLoadFunc(nullptr), m_texLoadParam(nullptr) { } CGEMutipleEffectFilter::~CGEMutipleEffectFilter() { clearFilters(); glDeleteTextures(1, &m_texCache); CGE_LOG_INFO("CGEMutipleEffectFilter Release...\n"); } void CGEMutipleEffectFilter::clearFilters() { for(std::vector<CGEImageFilterInterface*>::iterator iter = m_vecFilters.begin(); iter != m_vecFilters.end(); ++iter) { delete *iter; } m_vecFilters.clear(); } void CGEMutipleEffectFilter::setBufferLoadFunction(CGEBufferLoadFun fLoad, void* loadParam, CGEBufferUnloadFun fUnload, void* unloadParam) { m_loadFunc = fLoad; m_loadParam = loadParam; m_unloadFunc = fUnload; m_unloadParam = unloadParam; } void CGEMutipleEffectFilter::setTextureLoadFunction(CGETextureLoadFun texLoader, void* arg) { m_texLoadFunc = texLoader; m_texLoadParam = arg; } GLuint CGEMutipleEffectFilter::loadResources(const char* textureName, int* width, int* height) { int w, h; //优先使用texture loader. if(m_texLoadFunc != nullptr) { GLuint tex = m_texLoadFunc(textureName, &w, &h, m_texLoadParam); if(tex != 0) { if(width != nullptr) *width = w; if(height != nullptr) *height = h; return tex; } } //不存在tex loader或者 tex loader调用失败尝试buffer loader void* bufferData = nullptr; CGEBufferLoadFun loadFunc = m_loadFunc; CGEBufferUnloadFun unloadFunc = m_unloadFunc; void* loadArg = m_loadParam; void* unloadArg = m_unloadParam; if(loadFunc == nullptr) { loadFunc = cgeGetCommonLoadFunc(); loadArg = cgeGetCommonLoadArg(); unloadFunc = cgeGetCommonUnloadFunc(); unloadArg = cgeGetCommonUnloadArg(); } CGEBufferFormat fmt; void* pArg; if(loadFunc == nullptr || (pArg = loadFunc(textureName, &bufferData, &w, &h, &fmt, loadArg)) == nullptr) { CGE_LOG_ERROR("Load texture %s failed!\n", textureName); return 0; } GLenum dataFmt, channelFmt; cgeGetDataAndChannelByFormat(fmt, &dataFmt, &channelFmt, nullptr); GLuint texture = cgeGenTextureWithBuffer(bufferData, w, h, channelFmt, dataFmt); if(width != nullptr) *width = w; if(height != nullptr) *height = h; if(unloadFunc != nullptr) unloadFunc(pArg, unloadArg); return texture; } // bool CGEMutipleEffectFilter::initWithEffectID(int index) // { // const char* effectData = CGEEffectsDataSet::cgeGetEffectStringByID(index); // return initWithEffectString(effectData); // } bool CGEMutipleEffectFilter::initCustomize() { return m_mixFilter.init(); } bool CGEMutipleEffectFilter::initWithEffectString(const char* effectString) { const char* ptr = effectString; if(ptr == nullptr || *ptr == '\0' || strncmp(ptr, "@unavailable", 12) == 0) return false; ////////////////////////////////////////////////////////////////////////// //Hardcode for parsing the common effects. ////////////////////////////////////////////////////////////////////////// char buffer[128]; m_isWrapper = false; if(*ptr == '#') { char *pBuffer = buffer; ++ptr; while(*ptr != '\0' && !isspace(*ptr) && (pBuffer - buffer) < sizeof(buffer)) { *pBuffer++ = *ptr++; } *pBuffer = '\0'; if(strcmp(buffer, "unpack") == 0) { m_isWrapper = true; } } if(!m_isWrapper && !m_mixFilter.init()) { return false; } while(*ptr != '\0') { while(*ptr != '\0' && *ptr != '@') ++ptr; while(*ptr != '\0' && (*ptr == '@' || *ptr == ' ' || *ptr == '\t')) ++ptr; if(*ptr == '\0') break; //2015-1-29 隐患fix, 将下一条指令直接取出再进行判断 char *pBuffer = buffer; while(*ptr != '\0' && !isspace(*ptr) && (pBuffer - buffer) < sizeof(buffer)) { *pBuffer++ = *ptr++; } *pBuffer = '\0'; if(strcmp(buffer, "blend") == 0) { CGEDataParsingEngine::blendParser(ptr, this); } else if(strcmp(buffer, "curve") == 0) { CGEDataParsingEngine::curveParser(ptr, this); } else if(strcmp(buffer, "adjust") == 0) { CGEDataParsingEngine::adjustParser(ptr, this); } else if(strcmp(buffer, "cvlomo") == 0) { CGEDataParsingEngine::lomoWithCurveParser(ptr, this); } else if(strcmp(buffer, "lomo") == 0) { CGEDataParsingEngine::lomoParser(ptr, this); } else if(strcmp(buffer, "colorscale") == 0) { CGEDataParsingEngine::colorScaleParser(ptr, this); } else if(strcmp(buffer, "pixblend") == 0) { CGEDataParsingEngine::pixblendParser(ptr, this); } else if(strcmp(buffer, "krblend") == 0) { CGEDataParsingEngine::krblendParser(ptr, this); } else if(strcmp(buffer, "vignette") == 0) { CGEDataParsingEngine::vignetteParser(ptr, this); } else if(strcmp(buffer, "selfblend") == 0) { CGEDataParsingEngine::selfblendParser(ptr, this); } else if(strcmp(buffer, "colormul") == 0) { CGEDataParsingEngine::colorMulParser(ptr, this); } else if(strcmp(buffer, "vigblend") == 0) { CGEDataParsingEngine::vignetteBlendParser(ptr, this); } else if(strcmp(buffer, "selcolor") == 0) { CGEDataParsingEngine::selectiveColorParser(ptr, this); } else if(strcmp(buffer, "tileblend") == 0) { CGEDataParsingEngine::blendTileParser(ptr, this); } else if(strcmp(buffer, "style") == 0) { CGEDataParsingEngine::advancedStyleParser(ptr, this); } else if(strcmp(buffer, "beautify") == 0) { CGEDataParsingEngine::beautifyParser(ptr, this); } else if(strcmp(buffer, "blur") == 0) { CGEDataParsingEngine::blurParser(ptr, this); } else if(strcmp(buffer, "dynamic") == 0) { CGEDataParsingEngine::dynamicParser(ptr, this); } //Add more parsing rules before this one else { CGE_LOG_ERROR("指令未被解析(Invalid parameters):%s", ptr); } } if(m_vecFilters.empty()) { CGE_LOG_ERROR("特效指令 \"%s\" 无法生成任何特效!\n", effectString); return false; } return true; } void CGEMutipleEffectFilter::setIntensity(float value) { if(!m_isWrapper) m_mixFilter.setIntensity(value); } void CGEMutipleEffectFilter::render2Texture(CGEImageHandlerInterface* handler, GLuint srcTexture, GLuint vertexBufferID) { if(m_vecFilters.empty() || m_mixFilter.noIntensity() CGE_LOG_CODE( || m_isWrapper) ) { CGE_LOG_CODE ( if(m_vecFilters.empty()) { CGE_LOG_ERROR("CGEMutipleEffectFilter::render2Texture did nothing!\n"); } if(m_isWrapper) { CGE_LOG_ERROR("Invalid usage!! A wrapper should not be directly rendered!\n"); assert(0); } ) handler->swapBufferFBO(); return; } const auto& sz = handler->getOutputFBOSize(); bool needMix = m_mixFilter.needToMix(); if(needMix) { if(m_texCache == 0 || sz != m_currentSize) { m_currentSize = sz; glDeleteTextures(1, &m_texCache); m_texCache = cgeGenTextureWithBuffer(nullptr, m_currentSize.width, m_currentSize.height, GL_RGBA, GL_UNSIGNED_BYTE, 4, 0, GL_NEAREST, GL_CLAMP_TO_EDGE); } handler->copyLastResultTexture(m_texCache); } std::vector<CGEImageFilterInterface*>::iterator iter = m_vecFilters.begin(); for(;;) { glBindBuffer(GL_ARRAY_BUFFER, vertexBufferID); (*iter)->render2Texture(handler, handler->getBufferTextureID(), vertexBufferID); if(++iter != m_vecFilters.end()) { handler->swapBufferFBO(); } else break; } if(needMix) { handler->swapBufferFBO(); glBindBuffer(GL_ARRAY_BUFFER, vertexBufferID); m_mixFilter.render2Texture(handler, m_texCache, vertexBufferID); } } std::vector<CGEImageFilterInterface*> CGEMutipleEffectFilter::getFilters(bool bMove) { if(!bMove) return m_vecFilters; decltype(m_vecFilters) filter = m_vecFilters; m_vecFilters.clear(); return filter; } }
25.258065
227
0.649573
[ "vector" ]
ca3a0948de5b85b9f170462a47849c3656564da6
11,879
cpp
C++
libvast/test/table_slice.cpp
laozhudetui/vast
3b41c8ef62df19f7e950d27e87ca9267c261706f
[ "BSD-3-Clause" ]
null
null
null
libvast/test/table_slice.cpp
laozhudetui/vast
3b41c8ef62df19f7e950d27e87ca9267c261706f
[ "BSD-3-Clause" ]
8
2021-10-15T09:12:56.000Z
2022-03-04T09:16:06.000Z
libvast/test/table_slice.cpp
laozhudetui/vast
3b41c8ef62df19f7e950d27e87ca9267c261706f
[ "BSD-3-Clause" ]
null
null
null
// _ _____ __________ // | | / / _ | / __/_ __/ Visibility // | |/ / __ |_\ \ / / Across // |___/_/ |_/___/ /_/ Space and Time // // SPDX-FileCopyrightText: (c) 2018 The VAST Contributors // SPDX-License-Identifier: BSD-3-Clause #define SUITE table_slice #include "vast/table_slice.hpp" #include "vast/concept/parseable/to.hpp" #include "vast/concept/parseable/vast/expression.hpp" #include "vast/expression.hpp" #include "vast/ids.hpp" #include "vast/project.hpp" #include "vast/table_slice_column.hpp" #include "vast/table_slice_row.hpp" #include "vast/test/fixtures/table_slices.hpp" #include "vast/test/test.hpp" #include <caf/make_copy_on_write.hpp> #include <caf/test/dsl.hpp> using namespace vast; using namespace std::string_literals; FIXTURE_SCOPE(table_slice_tests, fixtures::table_slices) TEST(random integer slices) { auto t = integer_type{}.attributes({{"default", "uniform(100,200)"}}); record_type layout{{"i", t}}; layout.name("test.integers"); auto slices = unbox(make_random_table_slices(10, 10, layout)); CHECK_EQUAL(slices.size(), 10u); CHECK(std::all_of(slices.begin(), slices.end(), [](auto& slice) { return slice.rows() == 10; })); std::vector<integer> values; for (auto& slice : slices) for (size_t row = 0; row < slice.rows(); ++row) values.emplace_back(get<integer>(slice.at(row, 0, t))); auto [lowest, highest] = std::minmax_element(values.begin(), values.end()); CHECK_GREATER_EQUAL(*lowest, integer{100}); CHECK_LESS_EQUAL(*highest, integer{200}); } TEST(column view) { auto sut = zeek_conn_log[0]; auto ts_cview = table_slice_column::make(sut, "ts"); REQUIRE(ts_cview); auto flat_layout = flatten(sut.layout()); CHECK_EQUAL(ts_cview->index(), 0u); for (size_t column = 0; column < sut.columns(); ++column) { auto cview = table_slice_column{ sut, column, qualified_record_field{flat_layout.name(), flat_layout.fields[column]}}; REQUIRE_NOT_EQUAL(cview.size(), 0u); CHECK_EQUAL(cview.index(), column); CHECK_EQUAL(cview.size(), sut.rows()); for (size_t row = 0; row < cview.size(); ++row) CHECK_EQUAL(cview[row], sut.at(row, column, flat_layout.fields[column].type)); } } TEST(row view) { auto sut = zeek_conn_log[0]; auto flat_layout = flatten(sut.layout()); for (size_t row = 0; row < sut.rows(); ++row) { auto rview = table_slice_row{sut, row}; REQUIRE_NOT_EQUAL(rview.size(), 0u); CHECK_EQUAL(rview.index(), row); CHECK_EQUAL(rview.size(), sut.columns()); for (size_t column = 0; column < rview.size(); ++column) CHECK_EQUAL(rview[column], sut.at(row, column, flat_layout.fields[column].type)); } } TEST(select all) { auto sut = zeek_conn_log_full[0]; sut.offset(100); auto xs = select(sut, make_ids({{100, 200}})); REQUIRE_EQUAL(xs.size(), 1u); CHECK_EQUAL(xs[0], sut); } TEST(select none) { auto sut = zeek_conn_log_full[0]; sut.offset(100); auto xs = select(sut, make_ids({{200, 300}})); CHECK_EQUAL(xs.size(), 0u); } TEST(select prefix) { auto sut = zeek_conn_log_full[0]; sut.offset(100); auto xs = select(sut, make_ids({{0, 150}})); REQUIRE_EQUAL(xs.size(), 1u); CHECK_EQUAL(xs[0].rows(), 50u); CHECK_EQUAL(make_data(xs[0]), make_data(sut, 0, 50)); } TEST(select off by one prefix) { auto sut = zeek_conn_log_full[0]; sut.offset(100); auto xs = select(sut, make_ids({{101, 151}})); REQUIRE_EQUAL(xs.size(), 1u); CHECK_EQUAL(xs[0].rows(), 50u); CHECK_EQUAL(make_data(xs[0]), make_data(sut, 1, 50)); } TEST(select intermediates) { auto sut = zeek_conn_log_full[0]; sut.offset(100); auto xs = select(sut, make_ids({{110, 120}, {170, 180}})); REQUIRE_EQUAL(xs.size(), 2u); CHECK_EQUAL(xs[0].rows(), 10u); CHECK_EQUAL(make_data(xs[0]), make_data(sut, 10, 10)); CHECK_EQUAL(xs[1].rows(), 10u); CHECK_EQUAL(make_data(xs[1]), make_data(sut, 70, 10)); } TEST(select off by one suffix) { auto sut = zeek_conn_log_full[0]; sut.offset(100); auto xs = select(sut, make_ids({{149, 199}})); REQUIRE_EQUAL(xs.size(), 1u); CHECK_EQUAL(xs[0].rows(), 50u); CHECK_EQUAL(make_data(xs[0]), make_data(sut, 49, 50)); } TEST(select suffix) { auto sut = zeek_conn_log_full[0]; sut.offset(100); auto xs = select(sut, make_ids({{150, 300}})); REQUIRE_EQUAL(xs.size(), 1u); CHECK_EQUAL(xs[0].rows(), 50u); CHECK_EQUAL(make_data(xs[0]), make_data(sut, 50, 50)); } TEST(truncate) { auto sut = zeek_conn_log[0]; REQUIRE_EQUAL(sut.rows(), 8u); sut.offset(100); auto truncated_events = [&](size_t num_rows) { auto sub_slice = truncate(sut, num_rows); if (sub_slice.rows() != num_rows) FAIL("expected " << num_rows << " rows, got " << sub_slice.rows()); return make_data(sub_slice); }; auto sub_slice = truncate(sut, 8); CHECK_EQUAL(sub_slice, sut); CHECK_EQUAL(truncated_events(7), make_data(sut, 0, 7)); CHECK_EQUAL(truncated_events(6), make_data(sut, 0, 6)); CHECK_EQUAL(truncated_events(5), make_data(sut, 0, 5)); CHECK_EQUAL(truncated_events(4), make_data(sut, 0, 4)); CHECK_EQUAL(truncated_events(3), make_data(sut, 0, 3)); CHECK_EQUAL(truncated_events(2), make_data(sut, 0, 2)); CHECK_EQUAL(truncated_events(1), make_data(sut, 0, 1)); } TEST(split) { auto sut = zeek_conn_log[0]; REQUIRE_EQUAL(sut.rows(), 8u); sut.offset(100); // Splits `sut` using make_data. auto manual_split_sut = [&](size_t parition_point) { return std::pair{make_data(sut, 0, parition_point), make_data(sut, parition_point)}; }; // Splits `sut` using split() and then converting to events. auto split_sut = [&](size_t parition_point) { auto [first, second] = split(sut, parition_point); if (first.rows() + second.rows() != 8) FAIL("expected 8 rows in total, got " << (first.rows() + second.rows())); return std::pair{make_data(first), make_data(second)}; }; // We compare the results of the two lambdas, meaning that it should make no // difference whether we split via `make_data` or `split`. CHECK_EQUAL(split_sut(1), manual_split_sut(1)); CHECK_EQUAL(split_sut(2), manual_split_sut(2)); CHECK_EQUAL(split_sut(3), manual_split_sut(3)); CHECK_EQUAL(split_sut(4), manual_split_sut(4)); CHECK_EQUAL(split_sut(5), manual_split_sut(5)); CHECK_EQUAL(split_sut(6), manual_split_sut(6)); CHECK_EQUAL(split_sut(7), manual_split_sut(7)); } TEST(filter - expression overload) { auto sut = zeek_conn_log[0]; // sut.offset(0); auto check_eval = [&](std::string_view expr, size_t x) { auto exp = unbox(tailor(unbox(to<expression>(expr)), sut.layout())); CHECK_EQUAL(filter(sut, exp)->rows(), x); }; check_eval("id.orig_h != 192.168.1.102", 5); } TEST(filter - hints only) { auto sut = zeek_conn_log[0]; // sut.offset(0); auto check_eval = [&](std::initializer_list<id_range> id_init, size_t x) { auto hints = make_ids(id_init, sut.offset() + sut.rows()); CHECK_EQUAL(filter(sut, hints)->rows(), x); }; check_eval({{2, 7}}, 5); } TEST(filter - expression with hints) { auto sut = zeek_conn_log[0]; // sut.offset(0); auto check_eval = [&](std::string_view expr, std::initializer_list<id_range> id_init, size_t x) { auto exp = unbox(tailor(unbox(to<expression>(expr)), sut.layout())); auto hints = make_ids(id_init, sut.offset() + sut.rows()); CHECK_EQUAL(filter(sut, exp, hints)->rows(), x); }; check_eval("id.orig_h != 192.168.1.102", {{0, 8}}, 5); } TEST(evaluate) { auto sut = zeek_conn_log[0]; sut.offset(0); auto check_eval = [&](std::string_view expr, std::initializer_list<id_range> id_init) { auto ids = make_ids(id_init, sut.offset() + sut.rows()); auto exp = unbox(to<expression>(expr)); CHECK_EQUAL(evaluate(exp, sut), ids); }; check_eval("#type == \"zeek.conn\"", {{0, 8}}); check_eval("#type != \"zeek.conn\"", {}); check_eval("#field == \"orig_pkts\"", {{0, 8}}); check_eval("#field != \"orig_pkts\"", {}); } TEST(project column flat index) { auto sut = truncate(zeek_conn_log[0], 3); auto proj = project<vast::time, std::string>(sut, 0, 6); CHECK(proj); CHECK_NOT_EQUAL(proj.begin(), proj.end()); for (auto&& [ts, proto] : proj) { REQUIRE(ts); CHECK_GREATER_EQUAL(*ts, vast::time{}); REQUIRE(proto); CHECK_EQUAL(*proto, "udp"); } } TEST(project column full name) { auto sut = zeek_conn_log[0]; auto proj = project<vast::time, std::string>(sut, "zeek.conn.ts", "zeek.conn.proto"); CHECK(proj); CHECK_NOT_EQUAL(proj.begin(), proj.end()); for (auto&& [ts, proto] : proj) { REQUIRE(ts); CHECK_GREATER_EQUAL(*ts, vast::time{}); REQUIRE(proto); CHECK_EQUAL(*proto, "udp"); } } TEST(project column name) { auto sut = zeek_conn_log[0]; auto proj = project<vast::time, std::string>(sut, "ts", "proto"); CHECK(proj); CHECK_NOT_EQUAL(proj.begin(), proj.end()); for (auto&& [ts, proto] : proj) { REQUIRE(ts); CHECK_GREATER_EQUAL(*ts, vast::time{}); REQUIRE(proto); CHECK_EQUAL(*proto, "udp"); } } TEST(project column mixed access) { auto sut = zeek_conn_log[0]; auto proj = project<vast::time, std::string>(sut, 0, "proto"); CHECK(proj); CHECK_NOT_EQUAL(proj.begin(), proj.end()); for (auto&& [ts, proto] : proj) { REQUIRE(ts); CHECK_GREATER_EQUAL(*ts, vast::time{}); REQUIRE(proto); CHECK_EQUAL(*proto, "udp"); } } TEST(project column order independence) { auto sut = zeek_conn_log[0]; auto proj = project<std::string, vast::time>(sut, "proto", "ts"); CHECK(proj); CHECK_NOT_EQUAL(proj.begin(), proj.end()); for (auto&& [proto, ts] : proj) { REQUIRE(proto); CHECK_EQUAL(*proto, "udp"); REQUIRE(ts); CHECK_GREATER_EQUAL(*ts, vast::time{}); } } TEST(project column detect type mismatches) { auto sut = zeek_conn_log[0]; auto proj = project<bool, vast::time>(sut, "proto", "ts"); CHECK(!proj); CHECK_EQUAL(proj.begin(), proj.end()); } TEST(project column detect wrong field names) { auto sut = zeek_conn_log[0]; auto proj = project<std::string, vast::time>(sut, "porto", "ts"); CHECK(!proj); CHECK_EQUAL(proj.begin(), proj.end()); } TEST(project column detect wrong flat indices) { auto sut = zeek_conn_log[0]; auto proj = project<std::string, vast::time>(sut, 123, "ts"); CHECK(!proj); CHECK_EQUAL(proj.begin(), proj.end()); } TEST(project column unspecified types) { auto sut = zeek_conn_log[0]; auto proj = project<vast::data, vast::time>(sut, "proto", "ts"); CHECK(proj); CHECK_NOT_EQUAL(proj.begin(), proj.end()); for (auto&& [proto, ts] : proj) { REQUIRE(proto); CHECK(!caf::holds_alternative<caf::none_t>(*proto)); REQUIRE(caf::holds_alternative<view<std::string>>(*proto)); CHECK_EQUAL(caf::get<vast::view<std::string>>(*proto), "udp"); REQUIRE(ts); CHECK_GREATER_EQUAL(*ts, vast::time{}); } } TEST(project column lists) { auto sut = zeek_dns_log[0]; auto proj = project<vast::list>(sut, "answers"); CHECK(proj); CHECK_NOT_EQUAL(proj.begin(), proj.end()); CHECK_EQUAL(proj.size(), sut.rows()); size_t answers = 0; for (auto&& [answer] : proj) { if (answer) { answers++; for (auto entry : *answer) { CHECK(!caf::holds_alternative<caf::none_t>(entry)); CHECK(caf::holds_alternative<view<std::string>>(entry)); } } } CHECK_EQUAL(answers, 4u); } TEST(roundtrip) { auto slice = zeek_dns_log[0]; slice.offset(42u); table_slice slice_copy; std::vector<char> buf; caf::binary_serializer sink{nullptr, buf}; CHECK_EQUAL(inspect(sink, slice), caf::none); caf::binary_deserializer source{nullptr, buf}; CHECK_EQUAL(inspect(source, slice_copy), caf::none); CHECK_EQUAL(slice_copy.offset(), 42u); CHECK_EQUAL(slice, slice_copy); } FIXTURE_SCOPE_END()
31.847185
79
0.649381
[ "vector" ]
ca3d047f906161cb96ee8028b087b12c408bd257
3,169
cpp
C++
samples/BLE/BLE_Broadcast_and_Scan/BLE_Broadcast_and_Scan_Sample.cpp
letssteam/codal-stm32-B-L475E-IOT01A
dcaf35777195e8ca194398fd553f91f8c56099b0
[ "MIT" ]
null
null
null
samples/BLE/BLE_Broadcast_and_Scan/BLE_Broadcast_and_Scan_Sample.cpp
letssteam/codal-stm32-B-L475E-IOT01A
dcaf35777195e8ca194398fd553f91f8c56099b0
[ "MIT" ]
null
null
null
samples/BLE/BLE_Broadcast_and_Scan/BLE_Broadcast_and_Scan_Sample.cpp
letssteam/codal-stm32-B-L475E-IOT01A
dcaf35777195e8ca194398fd553f91f8c56099b0
[ "MIT" ]
null
null
null
#include "BLE_Broadcast_and_Scan_Sample.h" #include <string> #include "STM32AdvertisingBLE.h" #include "STM32duinoBLE.h" codal::STM32DISCO_L475VG_IOT_IO io; codal::STM32SPI spi3(io.miso3, io.mosi3, io.sclk3); HCISpiTransportClass hci(&spi3, SPBTLE_RF, pinNametoDigitalPin(PD_13), pinNametoDigitalPin(PE_6), pinNametoDigitalPin(PA_8), 8000000, 0); BLELocalDevice BLEObj(&hci); BLELocalDevice& BLE = BLEObj; codal::STM32AdvertisingBLE advertising; #define ADVERTISING_UUID 0x181C char get_safe_char(uint8_t c) { if (c >= 32 && c <= 126) { return (char)c; } else { return '?'; } } void print_message(std::vector<uint8_t> data) { for (auto d : data) { printf("%02X ", d); } printf("\r\n"); } void print_message_as_string(std::vector<uint8_t> data) { for (auto c : data) { printf("%c", get_safe_char(c)); } printf("\r\n"); } void print_scan_result() { if (advertising.hasReceivedMessage()) { auto results = advertising.getAllReceivedMessage(); for (auto res : results) { printf("%s\n\r", res.address.c_str()); printf("\tRSSI: %d dbm\r\n", res.rssi); printf("\tName: %s\r\n", res.name.c_str()); printf("\tUUID: %s\r\n", res.uuid.c_str()); printf("\tData (raw): "); print_message(res.message); printf("\tData (UTF-8): "); print_message_as_string(res.message); printf("\r\n"); } printf("\n\r===================================================================\n\r\n\r"); } } void BLE_Broadcast_and_Scan_sample(codal::STM32DISCO_L475VG_IOT& discoL475VgIot) { unsigned ms = 0; discoL475VgIot.serial.init(115200); printf("\r\n"); printf("*******************************************\r\n"); printf("* Demonstration du BLE *\r\n"); printf("*******************************************\r\n"); if (BLE.begin() != 0) { printf("BLE Initialized !\r\n"); } else { printf("Failed to initialize BLE !!\r\n"); bool state = false; while (true) { io.led2.setDigitalValue(state ? 1 : 0); io.led1.setDigitalValue(state ? 1 : 0); state = !state; discoL475VgIot.sleep(50); } } advertising.setLocalName("It Work's !"); advertising.setServiceData(ADVERTISING_UUID, (uint8_t*)"Start counter !", 15); advertising.begin(); int size; char message[22]; BLEDevice buffer[16]; while (true) { io.led1.setDigitalValue(advertising.isEmitting() ? 1 : 0); io.led2.setDigitalValue(advertising.isScanning() ? 1 : 0); if (ms % 1000 && advertising.isScanning()) { print_scan_result(); } if (ms % 1000 && advertising.isEmitting()) { size = sprintf(message, "Time: %02d", ms / 1000); if (size >= 0) { advertising.setServiceData(ADVERTISING_UUID, (uint8_t*)message, size); } } ms += 100; discoL475VgIot.sleep(100); } }
26.190083
98
0.535816
[ "vector" ]
ca4263365f70cb26e9f123e6c71b943228f4ceb5
1,880
cpp
C++
boj/_boj14500.cpp
Oxymoron957/Algorithm_Stduy_Cpp
1c7219bd42ac337426120bf29359ca0bae104590
[ "MIT" ]
null
null
null
boj/_boj14500.cpp
Oxymoron957/Algorithm_Stduy_Cpp
1c7219bd42ac337426120bf29359ca0bae104590
[ "MIT" ]
null
null
null
boj/_boj14500.cpp
Oxymoron957/Algorithm_Stduy_Cpp
1c7219bd42ac337426120bf29359ca0bae104590
[ "MIT" ]
null
null
null
/* 테트로미노 https://www.acmicpc.net/problem/14500 tip : ㅗㅜㅏㅓ의 경우 dfs로 해결이 안되는 것을 유의! */ #include <iostream> #include <vector> #include <algorithm> #include <cstring> using namespace std; #define MAX 501 int N, M; int board[MAX][MAX]; bool visited[MAX][MAX]; int max_value; int dx[4] = {1, -1, 0, 0}; int dy[4] = {0, 0, 1, -1}; void dfs(int y, int x, int level, int cost) { visited[y][x] = true; if (level == 4) { if (cost > max_value) max_value = cost; return ; } for (int i=0; i<4; i++) { int ny = y + dy[i]; int nx = x + dx[i]; if (0<=ny && ny<N && 0<=nx && nx<M && visited[ny][nx] == false) { if (level != 4) { dfs(ny, nx, level+1, cost+board[ny][nx]); visited[ny][nx] = false; } } } } void case1(int y, int x) { int temp = board[y][x] + board[y][x+1] + board[y][x+2] + board[y-1][x+1]; if (temp > max_value) max_value = temp; } void case2(int y, int x) { int temp = board[y][x] + board[y][x+1] + board[y][x+2] + board[y+1][x+1]; if (temp > max_value) max_value = temp; } void case3(int y, int x) { int temp = board[y][x] + board[y+1][x] + board[y+2][x] + board[y+1][x+1]; if (temp > max_value) max_value = temp; } void case4(int y, int x) { int temp = board[y][x] + board[y-1][x+1] + board[y][x+1] + board[y+1][x+1]; if (temp > max_value) max_value = temp; } int main(void) { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); // input cin >> N >> M; for (int i=0; i<N; i++) for(int j=0; j<M; j++) cin >> board[i][j]; for (int i=0; i<N; i++) { for(int j=0; j<M; j++) { memset(visited, false, sizeof(visited)); dfs(i, j, 1, board[i][j]); if (i - 1 >= 0 && j + 2 < M) case1(i, j); if (j + 2 < M && i + 1 < N) case2(i, j); if (i + 2 < N && j + 1 < M) case3(i, j); if (i + 1 < N && i - 1 >= 0 && j + 1 < M) case4(i, j); } } cout << max_value << "\n"; }
21.363636
76
0.518617
[ "vector" ]
ca42c8ec5302db2f2650cdbd104fb644776e0b25
2,753
cpp
C++
test/sql/decimal_functions_sql_test.cpp
phisiart/peloton
c2becb9d6f2e2c8f48696a371b0d7c0ff79d56fc
[ "Apache-2.0" ]
1
2017-04-17T15:19:36.000Z
2017-04-17T15:19:36.000Z
test/sql/decimal_functions_sql_test.cpp
phisiart/peloton
c2becb9d6f2e2c8f48696a371b0d7c0ff79d56fc
[ "Apache-2.0" ]
5
2017-04-23T17:16:14.000Z
2017-04-25T03:14:16.000Z
test/sql/decimal_functions_sql_test.cpp
phisiart/peloton-p3
c2becb9d6f2e2c8f48696a371b0d7c0ff79d56fc
[ "Apache-2.0" ]
null
null
null
//===----------------------------------------------------------------------===// // // Peloton // // decimal_functions_sql_test.cpp // // Identification: test/sql/decimal_functions_sql_test.cpp // // Copyright (c) 2015-2017, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <memory> #include "sql/testing_sql_util.h" #include "catalog/catalog.h" #include "common/harness.h" #include "concurrency/transaction_manager_factory.h" namespace peloton { namespace test { class DecimalFunctionsSQLTest : public PelotonTest {}; TEST_F(DecimalFunctionsSQLTest, FloorTest) { auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(); auto txn = txn_manager.BeginTransaction(); catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, txn); catalog::Catalog::GetInstance()->Bootstrap(); txn_manager.CommitTransaction(txn); // Create a t txn = txn_manager.BeginTransaction(); TestingSQLUtil::ExecuteSQLQuery( "CREATE TABLE foo(id integer, income decimal);"); // Adding in 2500 random decimal inputs between [-500, 500] int i; std::vector<double> inputs; int lo = -500; int hi = 500; int numEntries = 500; // Setting a seed std::srand(std::time(0)); for (i = 0; i < numEntries; i++) { double num = 0.45 + (std::rand() % (hi - lo)); inputs.push_back(num); std::ostringstream os; os << "insert into foo values(" << i << ", " << num << ");"; TestingSQLUtil::ExecuteSQLQuery(os.str()); } EXPECT_EQ(i, numEntries); txn_manager.CommitTransaction(txn); // Fetch values from the table std::vector<StatementResult> result; std::vector<FieldInfo> tuple_descriptor; std::string error_message; int rows_affected; std::string testQuery = "select id, floor(income) from foo;"; TestingSQLUtil::ExecuteSQLQuery(testQuery.c_str(), result, tuple_descriptor, rows_affected, error_message); for (i = 0; i < numEntries; i++) { std::string result_id( TestingSQLUtil::GetResultValueAsString(result, (2 * i))); std::string result_income( TestingSQLUtil::GetResultValueAsString(result, (2 * i) + 1)); int id = std::stoi(result_id); double income = std::stod(result_income); EXPECT_EQ(id, i); EXPECT_DOUBLE_EQ(income, floor(inputs[i])); } // free the database just created txn = txn_manager.BeginTransaction(); catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn); txn_manager.CommitTransaction(txn); } } // namespace test } // namespace peloton
33.573171
80
0.618235
[ "vector" ]
ca43bcbbd3330b88ac042fd3f5db4d11861769e6
6,470
hpp
C++
src/Utility.hpp
charlie-lee/slam_demo
0bb6cc6d20c6a728eea502a61456f83881144e59
[ "MIT" ]
null
null
null
src/Utility.hpp
charlie-lee/slam_demo
0bb6cc6d20c6a728eea502a61456f83881144e59
[ "MIT" ]
null
null
null
src/Utility.hpp
charlie-lee/slam_demo
0bb6cc6d20c6a728eea502a61456f83881144e59
[ "MIT" ]
null
null
null
/** * @file Utility.hpp * @brief Header of utility class in SLAM system for general functions. * @author Charlie Li * @date 2019.10.25 */ #ifndef UTILITY_HPP #define UTILITY_HPP #include <memory> #include <vector> #include <opencv2/core.hpp> #include <opencv2/features2d.hpp> namespace SLAM_demo { // forward declarations class CamPose; class FrameBase; /** * @class Utility * @brief Some general operations. */ class Utility { public: // public members /// Reprojection error computation scheme. enum class ReprojErrScheme { F, ///< Fundamental matrix as reprojection transformation. H, ///< Homography as reprojection transformation. }; public: // public member functions /// Default constructor. Utility() = default; /// Do not allow copying. Utility(const Utility& rhs) = delete; /// Do not allow copy-assignment. Utility& operator=(const Utility& rhs) = delete; /** * @brief Check whether a \f$2 \times 1\f$ cv::Mat point is inside * the border of an undistorted image. * @param[in] pt \f$2 \times 1\f$ point of cv::Mat type. * @return True if the 2D point is inside the border. */ static bool is2DPtInBorder(const cv::Mat& pt); /** * @brief Triangulate 3D points in world coordinate frame. * @param[in] pF2 Pointer to frame 2 (newer, querying set). * @param[in] pF1 Pointer to frame 1 (older, training set). * @param[in] vMatches21 2D-to-2D matching result between KF2 and KF1. * @return A std::vector of cv::Mat \f$3 \times 1\f$ triangulated points. * @note The returned std::vector should have same size with @p vMatches21. */ static std::vector<cv::Mat> triangulate3DPts( const std::shared_ptr<FrameBase>& pF2, const std::shared_ptr<FrameBase>& pF1, const std::vector<cv::DMatch>& vMatches21); /** * @brief Check whether a triangulated 3D world point is good enough * to be included to the map. * * Basically there're 5 things to check: * - The depth of the 3D camera coordinates in both views (whether the depth * is negative) * - The parallax of the 2 views (the angle oP-Xw-oC where oP and oC are * the camera origins in previous and current frame, Xw is the * triangulated point) (whether the parallax is too low), * - The position of reprojected 2D image point (whether it is outside the * image border); * - The reprojection errors in both views (whether it is too high). * - Epipolar constriant for the keypoint pair. * * @param[in] Xw \f$3 \times 1\f$ triangulated 3D world point in * inhomogeneous coordinate. * @param[in] kpt1 2D keypoint in previous frame. * @param[in] kpt2 corresponding 2D keypoint in current frame. * @param[in] pose1 Camera pose for view 1. * @param[in] pose2 Camera pose for view 2. * @param[in] thCosParallax Max cosine of the parallax. * @return True if the triangulated point is good enough, otherwise false. */ static bool checkTriangulatedPt(const cv::Mat& Xw, const cv::KeyPoint& kpt1, const cv::KeyPoint& kpt2, const CamPose& pose1, const CamPose& pose2, float thCosParallax = 0.9999f); /** * @brief Compute fundamental matrix F21 of 2 views (from view 1 to view 2) * based on their relative poses T1 & T2. * @param[in] CP1 Camera pose of the 1st view. * @param[in] CP2 Camera pose of the 2nd view. * @return Fundamental matrix F21. */ static cv::Mat computeFundamental(const CamPose& CP1, const CamPose& CP2); /** * @brief Compute reprojection error based on transformation matrix * @p T21 (reproject @p p1 from view 1 to view 2) and @p T12 * (reproject @p p2 from view 2 to view 1). * * Given 2D-to-2D match \f$p_1 = (x_1, y_1, 1)\f$, * \f$p_2 = (x_2, y_2, 1)\f$, and transformation matrix \f$T_{21}\f$, * \f$T_{12}\f$, * * Reprojection error \f$e_F\f$ for \f$F\f$ where \f$T_{21} = F_{21}\f$ and * \f$T_{12} = F_{12} = F_{21}^T\f$: * \f{align}{ * e_F &= d(p_2, F_{21} p_1)^2 + d(p_1, F_{12} p_2)^2 \\ * &= d(p_2, l_2)^2 + d(p_1, l_1)^2 \\ * &= \frac{a_2 x_2 + b_2 y_2 + c_2}{a_2^2 + b_2^2} + * \frac{a_1 x_1 + b_1 y_1 + c_1}{a_1^2 + b_1^2} * \f} * where \f$l_1 = (a_1, b_1, c_1)\f$ and \f$l_2 = (a_2, b_2, c_2)\f$ are * the epipolar lines of triangulated point \f$P\f$ based on \f$p_1\f$, * \f$p_2\f$ in view 1 and 2, respectively. * * Reprojection error \f$e_H\f$ for \f$H\f$ where \f$T_{21} = H_{21}\f$ and * \f$T_{12} = H_{12} = H_{21}^{-1}\f$: * \f{align}{ * e_H &= d(p_2, H_{21} p_1)^2 + d(p_1, H_{12} p_2)^2 \\ * &= d(p_2, p_2')^2 + d(p_1, p_1')^2 \\ * &= |x_2 - x_2'|^2 + |y_2 - y_2'|^2 + * |x_1 - x_1'|^2 + |y_1 - y_1'|^2 * \f} * where \f$p_1' = (x_1', y_1')\f$, \f$p_2' = (x_2', y_2')\f$. * * @param[in] T21 Transformation matrix from view 1 to view 2. * @param[in] T12 Transformation matrix from view 2 to view 1. * @param[in] p1 Point in view 1. * @param[in] p2 Point in view 2. * @param[in] eScheme Computation scheme based on different transformation * matrices (see Tracker::ReprojErrScheme for details). * @return Reprojection error (square form) in FP32 precision. */ static float computeReprojErr(const cv::Mat& T21, const cv::Mat& T12, const cv::Mat& p1, const cv::Mat& p2, ReprojErrScheme eScheme); /** * @brief Compute cosine of parallax between 2 frames given a 3D * world coordinate. * @param[in] Xw 3D world coordinate. * @param[in] pose1 Camera pose of frame 1. * @param[in] pose2 Camera pose of frame 2. * @return Cosine of parallax between 2 frames. */ static float computeCosParallax(const cv::Mat& Xw, const CamPose& pose1, const CamPose& pose2); }; } // namespace SLAM_demo #endif // UTILITY_HPP
41.741935
80
0.574961
[ "vector", "3d" ]
ca444f0b05726ebdc99d799e85ab2ae5b4aba92b
19,534
cpp
C++
NaoTHSoccer/Source/Motion/Engine/InverseKinematicsMotion/Motions/Walk2018/FootStepPlanner2018.cpp
BerlinUnited/NaoTH
02848ac10c16a5349f1735da8122a64d601a5c75
[ "ECL-2.0", "Apache-2.0" ]
15
2015-01-12T10:46:29.000Z
2022-03-28T05:13:14.000Z
NaoTHSoccer/Source/Motion/Engine/InverseKinematicsMotion/Motions/Walk2018/FootStepPlanner2018.cpp
BerlinUnited/NaoTH
02848ac10c16a5349f1735da8122a64d601a5c75
[ "ECL-2.0", "Apache-2.0" ]
2
2019-01-20T21:07:50.000Z
2020-01-22T14:00:28.000Z
NaoTHSoccer/Source/Motion/Engine/InverseKinematicsMotion/Motions/Walk2018/FootStepPlanner2018.cpp
BerlinUnited/NaoTH
02848ac10c16a5349f1735da8122a64d601a5c75
[ "ECL-2.0", "Apache-2.0" ]
5
2018-02-07T18:18:10.000Z
2019-10-15T17:01:41.000Z
/** * @file FootStepPlanner.cpp * * @author <a href="mailto:xu@informatik.hu-berlin.de">Xu, Yuan</a> * plan the foot step according to motion request */ #include "FootStepPlanner2018.h" using namespace InverseKinematic; using namespace std; FootStepPlanner2018::FootStepPlanner2018() : parameters(getWalk2018Parameters().footStepPlanner2018Params), theFootOffsetY(0.0), emergencyCounter(0) {} void FootStepPlanner2018::updateParameters() { theFootOffsetY = NaoInfo::HipOffsetY + parameters.footOffsetY; } void FootStepPlanner2018::init(size_t initial_number_of_cycles, FeetPose initialFeetPose) { Step& initialStep = getStepBuffer().add(); initialStep.footStep = FootStep(initialFeetPose, FootStep::NONE); initialStep.numberOfCycles = static_cast<int>(initial_number_of_cycles) - 1; // TODO: why? initialStep.planningCycle = initialStep.numberOfCycles; initialStep.samplesDoubleSupport = std::max(0, (int) (parameters.step.doubleSupportTime / getRobotInfo().basicTimeStep)); initialStep.samplesSingleSupport = initialStep.numberOfCycles - initialStep.samplesDoubleSupport; ASSERT(initialStep.samplesSingleSupport >= 0 && initialStep.samplesDoubleSupport >= 0); } void FootStepPlanner2018::execute() { static int delayed_frames = 0; bool ready_to_switch_support; if(getStepBuffer().first().footStep.liftingFoot() == FootStep::LEFT){ // weight shifting from right to left ready_to_switch_support = getCentreOfPressure().in_kinematic_chain_origin.valid && getCentreOfPressure().in_kinematic_chain_origin.CoP.y > parameters.stabilization.switching_offset; } else if(getStepBuffer().first().footStep.liftingFoot() == FootStep::RIGHT){ // weight shifting from left to right ready_to_switch_support = getCentreOfPressure().in_kinematic_chain_origin.valid && getCentreOfPressure().in_kinematic_chain_origin.CoP.y < -1 * parameters.stabilization.switching_offset; } else { // both feet on the ground ready_to_switch_support = true; } PLOT("FootStepPlanner2018:ready_to_switch", ready_to_switch_support); PLOT("FootStepPlanner2018:centre_of_pressure_y", getCentreOfPressure().in_kinematic_chain_origin.CoP.y); // current step has been executed, remove if (getStepBuffer().first().isExecuted() && (!parameters.stabilization.use_step_feedback || ready_to_switch_support || delayed_frames > parameters.stabilization.max_frames)) { getStepBuffer().remove(); delayed_frames = 0; } else if(parameters.stabilization.use_step_feedback && getStepBuffer().first().isExecuted()){ delayed_frames++; } PLOT("FootStepPlanner2018:exceedExecutionCycle", getStepBuffer().first().isExecuted()); PLOT("FootStepPlanner2018:delayed_frames", delayed_frames); // add a new step if(getStepBuffer().last().isPlanned()) { const Step& lastStep = getStepBuffer().last(); Step& step = getStepBuffer().add(); calculateNewStep(lastStep, step, getMotionRequest().walkRequest); } } void FootStepPlanner2018::calculateNewStep(const Step& lastStep, Step& newStep, const WalkRequest& walkRequest) //const { // update the parameters in case they have changed updateParameters(); newStep.walkRequest = walkRequest; // STABILIZATION bool do_emergency_stop = getCoMErrors().absolute2.isFull() && getCoMErrors().absolute2.getAverage() > parameters.stabilization.emergencyStopError; // NOTE: set the walk_emergency_stop below only in the case if it's actually executed getMotionStatus().walk_emergency_stop = false; // TODO: maybe move the check back to walk2018 and call a special function for finishing the motion if ( getMotionRequest().id != motion::walk /*getId()*/ || (do_emergency_stop && !walkRequest.stepControl.isProtected)) { // TODO: find reason for deadlock // current fix: force leaving emergency_stop after some cycles if(do_emergency_stop) { emergencyCounter++; getMotionStatus().walk_emergency_stop = do_emergency_stop; } PLOT("Walk:emergencyCounter",emergencyCounter); if(emergencyCounter > parameters.stabilization.maxEmergencyCounter) { emergencyCounter = 0; getCoMErrors().absolute2.clear(); } // try to make a last step to align the feet if it is required if ( getMotionRequest().standardStand ) { newStep.footStep = finalStep(lastStep.footStep, walkRequest); } else { newStep.footStep = zeroStep(lastStep.footStep); } if(newStep.footStep.liftingFoot() == FootStep::NONE) { newStep.numberOfCycles = 1; newStep.samplesDoubleSupport = 1; newStep.samplesSingleSupport = 0; } else { newStep.numberOfCycles = parameters.step.duration/getRobotInfo().basicTimeStep; newStep.samplesDoubleSupport = std::max(0, (int) (parameters.step.doubleSupportTime / getRobotInfo().basicTimeStep)); newStep.samplesSingleSupport = newStep.numberOfCycles - newStep.samplesDoubleSupport; } ASSERT(newStep.samplesSingleSupport >= 0 && newStep.samplesDoubleSupport >= 0); newStep.type = Step::STEP_WALK; // print it only once if(newStep.footStep.liftingFoot() == FootStep::NONE && lastStep.footStep.liftingFoot() != FootStep::NONE) { //std::cout << "walk stopping ..." << std::endl; } return; } else { // reset emergencyCounter if the stop was succesful (no deadlock case) emergencyCounter = 0; } if (walkRequest.stepControl.stepRequestID == getMotionStatus().stepControl.stepRequestID + 1) { // return the accepted stepRequestID getMotionStatus().stepControl.stepRequestID += 1; switch (walkRequest.stepControl.type) { case WalkRequest::StepControlRequest::ZEROSTEP: newStep.footStep = zeroStep(lastStep.footStep); newStep.numberOfCycles = walkRequest.stepControl.time / getRobotInfo().basicTimeStep; newStep.type = Step::STEP_CONTROL; break; case WalkRequest::StepControlRequest::KICKSTEP: newStep.footStep = controlStep(lastStep.footStep, walkRequest); newStep.numberOfCycles = walkRequest.stepControl.time / getRobotInfo().basicTimeStep; newStep.type = Step::STEP_CONTROL; break; case WalkRequest::StepControlRequest::WALKSTEP: { newStep.footStep = controlStep(lastStep.footStep, walkRequest); int duration = parameters.step.duration; if(parameters.step.dynamicDuration.on) { if(walkRequest.character <= 0.3) { duration = parameters.step.dynamicDuration.stable; //300; } else if(walkRequest.character <= 0.7) { duration = parameters.step.dynamicDuration.normal; //280; } else {// if(walkRequest.character == 1) { duration = parameters.step.dynamicDuration.fast; //260; } } //newStep.numberOfCycles = parameters().step.duration / getRobotInfo().basicTimeStep; newStep.numberOfCycles = duration / getRobotInfo().basicTimeStep; newStep.type = Step::STEP_CONTROL; PLOT("Walk:after_adaptStepSize_x", newStep.footStep.footEnd().translation.x); PLOT("Walk:after_adaptStepSize_y", newStep.footStep.footEnd().translation.y); break; } default: ASSERT(false); } } else // regular walk { newStep.footStep = nextStep(lastStep.footStep, walkRequest); int duration = parameters.step.duration; if(parameters.step.dynamicDuration.on) { if(walkRequest.character <= 0.3) { duration = parameters.step.dynamicDuration.stable; //300; } else if(walkRequest.character <= 0.7) { duration = parameters.step.dynamicDuration.normal; //280; } else {// if(walkRequest.character == 1) { duration = parameters.step.dynamicDuration.fast; //260; } } newStep.numberOfCycles = duration / getRobotInfo().basicTimeStep; newStep.type = Step::STEP_WALK; PLOT("Walk:XABSL_after_adaptStepSize_x", newStep.footStep.footEnd().translation.x); PLOT("Walk:XABSL_after_adaptStepSize_y", newStep.footStep.footEnd().translation.y); } // TODO: is the following assert always hold by special steps if doubleSupportTime != 0 ? newStep.samplesDoubleSupport = std::max(0, (int) (parameters.step.doubleSupportTime / getRobotInfo().basicTimeStep)); newStep.samplesSingleSupport = newStep.numberOfCycles - newStep.samplesDoubleSupport; ASSERT(newStep.samplesSingleSupport >= 0 && newStep.samplesDoubleSupport >= 0); // STABILIZATION if (parameters.stabilization.dynamicStepSize && !walkRequest.stepControl.isProtected) { adaptStepSize(newStep.footStep); getCoMErrors().e.clear(); } } void FootStepPlanner2018::adaptStepSize(FootStep& step) const { // only do something when the buffer is not empty if(getCoMErrors().e.size() > 0) { Vector3d errorCoM = getCoMErrors().e.getAverage(); static Vector3d lastCoMError = errorCoM; Vector3d comCorrection = errorCoM * parameters.stabilization.dynamicStepSizeP + (errorCoM - lastCoMError) * parameters.stabilization.dynamicStepSizeD; Vector3d stepCorrection = step.supFoot().rotation * comCorrection; step.footEnd().translation.x += stepCorrection.x; step.footEnd().translation.y += stepCorrection.y; lastCoMError = errorCoM; } }//end adaptStepSize FootStep FootStepPlanner2018::finalStep(const FootStep& lastStep, const WalkRequest& /*req*/) const { // don't move the feet if they stoped moving once if(lastStep.liftingFoot() == FootStep::NONE) { return zeroStep(lastStep); } // TODO: check if an actual step is necessary based on the last step // => calculate an actual step only if necessary // try to plan a real last step with an empty walk request FootStep footStep = nextStep(lastStep, WalkRequest()); // how much did the foot move in this step Pose3D diff = footStep.footBegin().invert() * footStep.footEnd(); // planed step almost didn't move the foot, i.e., is was almost a zero step if(diff.translation.abs2() < 1 && diff.rotation.getZAngle() < Math::fromDegrees(1)) { return zeroStep(lastStep); } else { return footStep; } } FootStep FootStepPlanner2018::controlStep(const FootStep& lastStep, const WalkRequest& req) const { WalkRequest myReq = req; myReq.target = req.stepControl.target;//HACK FootStep::Foot liftingFoot = req.stepControl.moveLeftFoot?FootStep::LEFT:FootStep::RIGHT; return calculateNextWalkStep(lastStep.end(), lastStep.offset(), lastStep.stepRequest(), liftingFoot, myReq, true); } FootStep FootStepPlanner2018::zeroStep(const FootStep& lastStep) const { return FootStep(lastStep.end(), FootStep::NONE); } FootStep FootStepPlanner2018::nextStep(const FootStep& lastStep, const WalkRequest& req) const { if ( lastStep.liftingFoot() == FootStep::NONE ) { return firstStep(lastStep.end(), lastStep.offset(), lastStep.stepRequest(), req); } else { FootStep::Foot liftingFoot = (lastStep.liftingFoot()==FootStep::LEFT)?FootStep::RIGHT:FootStep::LEFT; return calculateNextWalkStep(lastStep.end(), lastStep.offset(), lastStep.stepRequest(), liftingFoot, req, false); } } FootStep FootStepPlanner2018::firstStep(const InverseKinematic::FeetPose& pose, const Pose2D& offset, const Pose2D& lastStepRequest, const WalkRequest& req) const { FootStep firstStepLeft = calculateNextWalkStep(pose, offset, lastStepRequest, FootStep::LEFT, req); FootStep firstStepRight = calculateNextWalkStep(pose, offset, lastStepRequest, FootStep::RIGHT, req); Pose3D leftMove = firstStepLeft.footBegin().invert() * firstStepLeft.footEnd(); Pose3D rightMove = firstStepRight.footBegin().invert() * firstStepRight.footEnd(); // TODO: think about criteria, it should be better to always take the step which aligns the rotation at most // proposal: remove else part if ( fabs(req.target.rotation) > parameters.limits.maxTurnInner ) { // choose foot by rotation double leftTurn = leftMove.rotation.getZAngle(); double rightTurn = rightMove.rotation.getZAngle(); if ( fabs(leftTurn) > fabs(rightTurn) ) { return firstStepLeft; } else { return firstStepRight; } } else { // choose foot by distance if ( leftMove.translation.abs2() > rightMove.translation.abs2() ) { return firstStepLeft; } else { return firstStepRight; } } }//end firstStep // TODO: parameter for the foot to move FootStep FootStepPlanner2018::calculateNextWalkStep(const InverseKinematic::FeetPose& pose, const Pose2D& offset, const Pose2D& lastStepRequest, FootStep::Foot movingFoot, const WalkRequest& req, bool stepControl) const { // TODO: how to deal with zero steps properly ASSERT(movingFoot != FootStep::NONE); // transform between the foot coordinates and the corresponding origin const Pose2D supportOriginOffset = offset * Pose2D(0, theFootOffsetY); const Pose2D targetOriginOffset = req.offset * Pose2D(0, theFootOffsetY); // transform between the global odometry coordinates and the origin of the support foot const Pose2D supportOrigin = (movingFoot == FootStep::RIGHT)? pose.left.projectXY() * supportOriginOffset.invert() : pose.right.projectXY() * supportOriginOffset; // transform the request in the coordinates of the support origin Pose2D stepRequest = req.target; if (req.coordinate == WalkRequest::LFoot) { stepRequest = supportOrigin.invert() * pose.left.projectXY() * stepRequest * targetOriginOffset.invert(); } else if(req.coordinate == WalkRequest::RFoot) { stepRequest = supportOrigin.invert() * pose.right.projectXY() * stepRequest * targetOriginOffset; } // apply restriction mode if (stepControl && req.stepControl.restriction == WalkRequest::StepControlRequest::RestrictionMode::SOFT) { restrictStepSize(stepRequest, req.character, true); } // the stepControl with restriction mode HARD behaves the same way as regular walk request else if (stepControl && req.stepControl.restriction == WalkRequest::StepControlRequest::RestrictionMode::HARD) { restrictStepSize(stepRequest, req.character, false); restrictStepChange(stepRequest, lastStepRequest, true); } else // regular walk request { restrictStepSize(stepRequest, req.character, false); restrictStepChange(stepRequest, lastStepRequest, false); } // create a new step FootStep newStep(pose, movingFoot); newStep.offset() = req.offset; // HACK: save the step request before geometrical restrictions // TODO: why? newStep.stepRequest() = stepRequest; // apply geometric restrictions to the step request if(movingFoot == FootStep::RIGHT) { stepRequest = Pose2D(min(parameters.limits.maxTurnInner, stepRequest.rotation), stepRequest.translation.x, min(0.0, stepRequest.translation.y)); } else { stepRequest = Pose2D(max(-parameters.limits.maxTurnInner, stepRequest.rotation), stepRequest.translation.x, max(0.0, stepRequest.translation.y)); } // apply the planed motion and calculate the coordinates of the moving foot Pose2D footStepTarget = supportOrigin * stepRequest * ((movingFoot == FootStep::RIGHT) ? targetOriginOffset.invert() : targetOriginOffset); newStep.footEnd() = Pose3D::embedXY(footStepTarget); return newStep; }//end calculateNextWalkStep //TODO: do we really need different parameters for normal and step control steps? void FootStepPlanner2018::restrictStepSize(Pose2D& step, double character, bool stepControl) const { // scale the character: [0, 1] --> [0.5, 1] character = 0.5*character + 0.5; double maxTurn, maxStepLength, maxStepLengthBack, maxStepWidth; if(stepControl) { maxTurn = parameters.limits.maxCtrlTurn * character; maxStepLength = parameters.limits.maxCtrlLength * character; maxStepWidth = parameters.limits.maxCtrlWidth * character; } else { maxTurn = parameters.limits.maxStepTurn * character; maxStepLength = parameters.limits.maxStepLength * character; maxStepWidth = parameters.limits.maxStepWidth * character; } maxStepLengthBack = parameters.limits.maxStepLengthBack * character; if ( step.translation.x < 0 ) { maxStepLength = maxStepLengthBack; } // limit translation if ( maxStepLength > 0.5 && maxStepWidth > 0.5 ) { // restrict the step size in an ellipse double alpha = step.translation.angle(); double cosa = cos(alpha); double sina = sin(alpha); const double maxStepLength2 = Math::sqr(maxStepLength); const double maxStepWidth2 = Math::sqr(maxStepWidth); double length = sqrt((maxStepLength2 * maxStepWidth2) / (maxStepLength2 * Math::sqr(sina) + maxStepWidth2 * Math::sqr(cosa))); if (step.translation.abs2() > Math::sqr(length)) { step.translation.x = length * cosa; step.translation.y = length * sina; } } else { step.translation.x = Math::clamp(step.translation.x, -maxStepLengthBack, maxStepLength); step.translation.y = Math::clamp(step.translation.y, -maxStepWidth, maxStepWidth); } ASSERT( step.translation.x >= -maxStepLengthBack); ASSERT( step.translation.x <= maxStepLength); ASSERT( fabs(step.translation.y) <= maxStepWidth); // limit rotation step.rotation = Math::clamp(step.rotation, -maxTurn, maxTurn); // limit the rotation // limit translation depending on rotation if not doing a stepControl if (!stepControl && maxTurn > Math::fromDegrees(1.0) ) { step.translation *= cos( step.rotation/maxTurn * Math::pi / 2); } }//end restrictStepSize void FootStepPlanner2018::restrictStepChange(Pose2D& step, const Pose2D& lastStep, bool stepControl) const { double maxChangeDownX, maxChangeDownY, maxChangeDownTurn, maxChangeX, maxChangeY, maxChangeTurn; if(stepControl){ maxChangeDownX = parameters.limits.maxCtrlLength * parameters.limits.maxCtrlChangeDown; maxChangeDownY = parameters.limits.maxCtrlWidth * parameters.limits.maxCtrlChangeDown; maxChangeDownTurn = parameters.limits.maxCtrlTurn * parameters.limits.maxCtrlChangeDown; maxChangeX = parameters.limits.maxCtrlLength * parameters.limits.maxCtrlChange; maxChangeY = parameters.limits.maxCtrlWidth * parameters.limits.maxCtrlChange; maxChangeTurn = parameters.limits.maxCtrlTurn * parameters.limits.maxCtrlChange; } else { maxChangeDownX = parameters.limits.maxStepLength * parameters.limits.maxStepChangeDown; maxChangeDownY = parameters.limits.maxStepWidth * parameters.limits.maxStepChangeDown; maxChangeDownTurn = parameters.limits.maxStepTurn * parameters.limits.maxStepChangeDown; maxChangeX = parameters.limits.maxStepLength * parameters.limits.maxStepChange; maxChangeY = parameters.limits.maxStepWidth * parameters.limits.maxStepChange; maxChangeTurn = parameters.limits.maxStepTurn * parameters.limits.maxStepChange; } Pose2D change; change.translation = step.translation - lastStep.translation; change.rotation = Math::normalize(step.rotation - lastStep.rotation); change.translation.x = Math::clamp(change.translation.x, -maxChangeDownX, maxChangeX); change.translation.y = Math::clamp(change.translation.y, -maxChangeDownY, maxChangeY); change.rotation = Math::clamp(change.rotation, -maxChangeDownTurn, maxChangeTurn); step.translation = lastStep.translation + change.translation; step.rotation = Math::normalize(lastStep.rotation + change.rotation); }
42.650655
219
0.72274
[ "transform" ]
ca45108b698bc2a18c19f93739f02171e778b60d
9,133
cpp
C++
searchcore/src/tests/proton/feed_and_search/feed_and_search.cpp
homerredroc/vespa
0a66f8f17eba82f9c0cbfbbbe37c2fcdefe93063
[ "Apache-2.0" ]
null
null
null
searchcore/src/tests/proton/feed_and_search/feed_and_search.cpp
homerredroc/vespa
0a66f8f17eba82f9c0cbfbbbe37c2fcdefe93063
[ "Apache-2.0" ]
null
null
null
searchcore/src/tests/proton/feed_and_search/feed_and_search.cpp
homerredroc/vespa
0a66f8f17eba82f9c0cbfbbbe37c2fcdefe93063
[ "Apache-2.0" ]
null
null
null
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/document/datatype/datatype.h> #include <vespa/document/fieldvalue/document.h> #include <vespa/document/fieldvalue/fieldvalue.h> #include <vespa/searchlib/common/documentsummary.h> #include <vespa/searchlib/common/sequencedtaskexecutor.h> #include <vespa/searchlib/diskindex/diskindex.h> #include <vespa/searchlib/diskindex/fusion.h> #include <vespa/searchlib/diskindex/indexbuilder.h> #include <vespa/searchlib/fef/fef.h> #include <vespa/searchlib/index/docbuilder.h> #include <vespa/searchlib/index/dummyfileheadercontext.h> #include <vespa/searchlib/memoryindex/memory_index.h> #include <vespa/searchlib/test/index/mock_field_length_inspector.h> #include <vespa/searchlib/query/base.h> #include <vespa/searchlib/query/tree/simplequery.h> #include <vespa/searchlib/queryeval/blueprint.h> #include <vespa/searchlib/queryeval/fake_requestcontext.h> #include <vespa/searchlib/queryeval/searchiterator.h> #include <vespa/vespalib/testkit/testapp.h> #include <vespa/vespalib/util/threadstackexecutor.h> #include <sstream> #include <vespa/log/log.h> LOG_SETUP("feed_and_search_test"); using document::DataType; using document::Document; using document::FieldValue; using search::DocumentIdT; using search::TuneFileIndexing; using search::TuneFileSearch; using search::diskindex::DiskIndex; using search::diskindex::IndexBuilder; using search::diskindex::SelectorArray; using search::docsummary::DocumentSummary; using search::fef::FieldPositionsIterator; using search::fef::MatchData; using search::fef::MatchDataLayout; using search::fef::TermFieldHandle; using search::fef::TermFieldMatchData; using search::index::DocBuilder; using search::index::DummyFileHeaderContext; using search::index::Schema; using search::index::test::MockFieldLengthInspector; using search::memoryindex::MemoryIndex; using search::query::SimpleStringTerm; using search::queryeval::Blueprint; using search::queryeval::FakeRequestContext; using search::queryeval::FieldSpec; using search::queryeval::FieldSpecList; using search::queryeval::SearchIterator; using search::queryeval::Searchable; using std::ostringstream; using vespalib::string; namespace { class Test : public vespalib::TestApp { const char *current_state; void DumpState(bool) { fprintf(stderr, "%s: ERROR: in %s\n", GetName(), current_state); } void requireThatMemoryIndexCanBeDumpedAndSearched(); void testSearch(Searchable &source, const string &term, uint32_t doc_id); public: int Main() override; }; #define TEST_CALL(func) \ current_state = #func; \ func(); int Test::Main() { TEST_INIT("feed_and_search_test"); if (_argc > 0) { DummyFileHeaderContext::setCreator(_argv[0]); } TEST_CALL(requireThatMemoryIndexCanBeDumpedAndSearched); TEST_DONE(); } const string field_name = "string_field"; const string noise = "noise"; const string word1 = "foo"; const string word2 = "bar"; const DocumentIdT doc_id1 = 1; const DocumentIdT doc_id2 = 2; Schema getSchema() { Schema schema; schema.addIndexField(Schema::IndexField(field_name, search::index::schema::DataType::STRING)); return schema; } Document::UP buildDocument(DocBuilder & doc_builder, int id, const string &word) { ostringstream ost; ost << "id:ns:searchdocument::" << id; doc_builder.startDocument(ost.str()); doc_builder.startIndexField(field_name) .addStr(noise).addStr(word).endField(); return doc_builder.endDocument(); } // Performs a search using a Searchable. void Test::testSearch(Searchable &source, const string &term, uint32_t doc_id) { FakeRequestContext requestContext; uint32_t fieldId = 0; MatchDataLayout mdl; TermFieldHandle handle = mdl.allocTermField(fieldId); MatchData::UP match_data = mdl.createMatchData(); SimpleStringTerm node(term, field_name, 0, search::query::Weight(0)); Blueprint::UP result = source.createBlueprint(requestContext, FieldSpecList().add(FieldSpec(field_name, 0, handle)), node); result->fetchPostings(search::queryeval::ExecuteInfo::TRUE); SearchIterator::UP search_iterator = result->createSearch(*match_data, true); search_iterator->initFullRange(); ASSERT_TRUE(search_iterator.get()); ASSERT_TRUE(search_iterator->seek(doc_id)); EXPECT_EQUAL(doc_id, search_iterator->getDocId()); search_iterator->unpack(doc_id); FieldPositionsIterator it = match_data->resolveTermField(handle)->getIterator(); ASSERT_TRUE(it.valid()); EXPECT_EQUAL(1u, it.size()); EXPECT_EQUAL(1u, it.getPosition()); // All hits are at pos 1 in this index EXPECT_TRUE(!search_iterator->seek(doc_id + 1)); EXPECT_TRUE(search_iterator->isAtEnd()); } // Creates a memory index, inserts documents, performs a few // searches, dumps the index to disk, and performs the searches // again. void Test::requireThatMemoryIndexCanBeDumpedAndSearched() { Schema schema = getSchema(); vespalib::ThreadStackExecutor sharedExecutor(2, 0x10000); search::SequencedTaskExecutor indexFieldInverter(2); search::SequencedTaskExecutor indexFieldWriter(2); MemoryIndex memory_index(schema, MockFieldLengthInspector(), indexFieldInverter, indexFieldWriter); DocBuilder doc_builder(schema); Document::UP doc = buildDocument(doc_builder, doc_id1, word1); memory_index.insertDocument(doc_id1, *doc.get()); doc = buildDocument(doc_builder, doc_id2, word2); memory_index.insertDocument(doc_id2, *doc.get()); memory_index.commit(std::shared_ptr<search::IDestructorCallback>()); indexFieldWriter.sync(); testSearch(memory_index, word1, doc_id1); testSearch(memory_index, word2, doc_id2); const string index_dir = "test_index"; IndexBuilder index_builder(schema); index_builder.setPrefix(index_dir); const uint32_t docIdLimit = memory_index.getDocIdLimit(); const uint64_t num_words = memory_index.getNumWords(); search::TuneFileIndexing tuneFileIndexing; DummyFileHeaderContext fileHeaderContext; index_builder.open(docIdLimit, num_words, MockFieldLengthInspector(), tuneFileIndexing, fileHeaderContext); memory_index.dump(index_builder); index_builder.close(); // Fusion test. Keep all documents to get an "indentical" copy. const string index_dir2 = "test_index2"; std::vector<string> fusionInputs; fusionInputs.push_back(index_dir); uint32_t fusionDocIdLimit = 0; using Fusion = search::diskindex::Fusion; bool fret1 = DocumentSummary::readDocIdLimit(index_dir, fusionDocIdLimit); ASSERT_TRUE(fret1); SelectorArray selector(fusionDocIdLimit, 0); bool fret2 = Fusion::merge(schema, index_dir2, fusionInputs, selector, false /* dynamicKPosOccFormat */, tuneFileIndexing, fileHeaderContext, sharedExecutor); ASSERT_TRUE(fret2); // Fusion test with all docs removed in output (doesn't affect word list) const string index_dir3 = "test_index3"; fusionInputs.clear(); fusionInputs.push_back(index_dir); fusionDocIdLimit = 0; bool fret3 = DocumentSummary::readDocIdLimit(index_dir, fusionDocIdLimit); ASSERT_TRUE(fret3); SelectorArray selector2(fusionDocIdLimit, 1); bool fret4 = Fusion::merge(schema, index_dir3, fusionInputs, selector2, false /* dynamicKPosOccFormat */, tuneFileIndexing, fileHeaderContext, sharedExecutor); ASSERT_TRUE(fret4); // Fusion test with all docs removed in input (affects word list) const string index_dir4 = "test_index4"; fusionInputs.clear(); fusionInputs.push_back(index_dir3); fusionDocIdLimit = 0; bool fret5 = DocumentSummary::readDocIdLimit(index_dir3, fusionDocIdLimit); ASSERT_TRUE(fret5); SelectorArray selector3(fusionDocIdLimit, 0); bool fret6 = Fusion::merge(schema, index_dir4, fusionInputs, selector3, false /* dynamicKPosOccFormat */, tuneFileIndexing, fileHeaderContext, sharedExecutor); ASSERT_TRUE(fret6); DiskIndex disk_index(index_dir); ASSERT_TRUE(disk_index.setup(TuneFileSearch())); testSearch(disk_index, word1, doc_id1); testSearch(disk_index, word2, doc_id2); DiskIndex disk_index2(index_dir2); ASSERT_TRUE(disk_index2.setup(TuneFileSearch())); testSearch(disk_index2, word1, doc_id1); testSearch(disk_index2, word2, doc_id2); } } // namespace TEST_APPHOOK(Test);
37.126016
118
0.696595
[ "vector" ]
ca45a93c8831ee55d518f851d1051ec4a103dcac
818
cpp
C++
Source/Core/Managers/network_manager.cpp
mlavik1/HikariOnline
47fb9457a1c5329859a4d41cb06442109bc507fa
[ "MIT" ]
null
null
null
Source/Core/Managers/network_manager.cpp
mlavik1/HikariOnline
47fb9457a1c5329859a4d41cb06442109bc507fa
[ "MIT" ]
null
null
null
Source/Core/Managers/network_manager.cpp
mlavik1/HikariOnline
47fb9457a1c5329859a4d41cb06442109bc507fa
[ "MIT" ]
null
null
null
#include "network_manager.h" #include "Core/Debug/st_assert.h" namespace Hikari { Hikari::Object* NetworkManager::GetObjectByGUID(NetGUID arg_guid) { auto objIter = mNetworkObjects.find(arg_guid); Hikari::Object* obj = (objIter != mNetworkObjects.end()) ? (*objIter).second : nullptr; return obj; } #if defined(HIKARI_GAMESERVER) || defined(HIKARI_WORLDSERVER) void NetworkManager::GenerateNetGUID(Hikari::Object* arg_object) { arg_object->SetNetGUID(mNetGUIDSequence++); } #endif void NetworkManager::RegisterObject(Hikari::Object* arg_object) { const NetGUID& guid = arg_object->GetNetGUID(); __Assert(guid != NetGUIDNone); mNetworkObjects[guid] = arg_object; } void NetworkManager::UnRegisterObject(Hikari::Object* arg_object) { mNetworkObjects.erase(arg_object->GetNetGUID()); } }
24.787879
89
0.748166
[ "object" ]
ca45fff994c13369e1ee0821377b4d5a87cacbfe
6,350
cpp
C++
3rdparty/jsonrpc-cpp-0.4/src/jsonrpc_handler.cpp
wohaaitinciu/zpublic
0e4896b16e774d2f87e1fa80f1b9c5650b85c57e
[ "Unlicense" ]
50
2015-01-07T01:54:54.000Z
2021-01-15T00:41:48.000Z
3rdparty/jsonrpc-cpp-0.4/src/jsonrpc_handler.cpp
lib1256/zpublic
64c2be9ef1abab878288680bb58122dcc25df81d
[ "Unlicense" ]
1
2015-05-26T07:40:19.000Z
2015-05-26T07:40:19.000Z
3rdparty/jsonrpc-cpp-0.4/src/jsonrpc_handler.cpp
lib1256/zpublic
64c2be9ef1abab878288680bb58122dcc25df81d
[ "Unlicense" ]
39
2015-01-07T02:03:15.000Z
2021-01-15T00:41:50.000Z
/* * JsonRpc-Cpp - JSON-RPC implementation. * Copyright (C) 2008-2011 Sebastien Vincent <sebastien.vincent@cppextrem.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * \file jsonrpc_handler.cpp * \brief JSON-RPC server processor engine. * \author Sebastien Vincent */ #include "jsonrpc_handler.h" namespace Json { namespace Rpc { CallbackMethod::~CallbackMethod() { } Handler::Handler() { /* add a RPC method that list the actual RPC methods contained in the Handler */ Json::Value root; root["description"] = "List the RPC methods available"; root["parameters"] = Json::Value::null; root["returns"] = "Object that contains description of all methods registered"; AddMethod(new RpcMethod<Handler>(*this, &Handler::SystemDescribe, std::string("system.describe"), root)); } Handler::~Handler() { /* delete all objects from the list */ for(std::list<CallbackMethod*>::const_iterator it = m_methods.begin() ; it != m_methods.end() ; it++) { delete (*it); } m_methods.clear(); } void Handler::AddMethod(CallbackMethod* method) { m_methods.push_back(method); } void Handler::DeleteMethod(const std::string& name) { /* do not delete system defined method */ if(name == "system.describe") { return; } for(std::list<CallbackMethod*>::iterator it = m_methods.begin() ; it != m_methods.end() ; it++) { if((*it)->GetName() == name) { delete (*it); m_methods.erase(it); break; } } } bool Handler::SystemDescribe(const Json::Value& msg, Json::Value& response) { Json::Value methods; response["jsonrpc"] = "2.0"; response["id"] = msg["id"]; for(std::list<CallbackMethod*>::iterator it = m_methods.begin() ; it != m_methods.end() ; it++) { methods[(*it)->GetName()] = (*it)->GetDescription(); } response["result"] = methods; return true; } std::string Handler::GetString(Json::Value value) { return m_writer.write(value); } bool Handler::Check(const Json::Value& root, Json::Value& error) { Json::Value err; /* check the JSON-RPC version => 2.0 */ if(!root.isObject() || !root.isMember("jsonrpc") || root["jsonrpc"] != "2.0") { error["id"] = Json::Value::null; error["jsonrpc"] = "2.0"; err["code"] = INVALID_REQUEST; err["message"] = "Invalid JSON-RPC request."; error["error"] = err; return false; } if(root.isMember("id") && (root["id"].isArray() || root["id"].isObject())) { error["id"] = Json::Value::null; error["jsonrpc"] = "2.0"; err["code"] = INVALID_REQUEST; err["message"] = "Invalid JSON-RPC request."; error["error"] = err; return false; } /* extract "method" attribute */ if(!root.isMember("method") || !root["method"].isString()) { error["id"] = Json::Value::null; error["jsonrpc"] = "2.0"; err["code"] = INVALID_REQUEST; err["message"] = "Invalid JSON-RPC request."; error["error"] = err; return false; } return true; } bool Handler::Process(const Json::Value& root, Json::Value& response) { Json::Value error; std::string method; if(!Check(root, error)) { response = error; return false; } method = root["method"].asString(); if(method != "") { CallbackMethod* rpc = Lookup(method); if(rpc) { return rpc->Call(root, response); } } /* forge an error response */ response["id"] = root.isMember("id") ? root["id"] : Json::Value::null; response["jsonrpc"] = "2.0"; error["code"] = METHOD_NOT_FOUND; error["message"] = "Method not found."; response["error"] = error; return false; } bool Handler::Process(const std::string& msg, Json::Value& response) { Json::Value root; Json::Value error; bool parsing = false; /* parsing */ parsing = m_reader.parse(msg, root); if(!parsing) { /* request or batched call is not in JSON format */ response["id"] = Json::Value::null; response["jsonrpc"] = "2.0"; error["code"] = PARSING_ERROR; error["message"] = "Parse error."; response["error"] = error; return false; } if(root.isArray()) { /* batched call */ Json::Value::ArrayIndex i = 0; Json::Value::ArrayIndex j = 0; for(i = 0 ; i < root.size() ; i++) { Json::Value ret; Process(root[i], ret); if(ret != Json::Value::null) { /* it is not a notification, add to array of responses */ response[j] = ret; j++; } } return true; } else { return Process(root, response); } } bool Handler::Process(const char* msg, Json::Value& response) { std::string str(msg); return Process(str, response); } CallbackMethod* Handler::Lookup(const std::string& name) const { for(std::list<CallbackMethod*>::const_iterator it = m_methods.begin() ; it != m_methods.end() ; it++) { if((*it)->GetName() == name) { return (*it); } } return 0; } } /* namespace Rpc */ } /* namespace Json */
25.502008
111
0.545512
[ "object" ]
ca46e14c2b312046e5e3a3f27e342e40b3aa634b
1,452
cxx
C++
rdpfuzz-winafl/cmake-3.16.0/Source/cmMarkAsAdvancedCommand.cxx
fengjixuchui/rdpfuzz
4561b6fbf73ada553ce78ad44918fd0930ee4e85
[ "Apache-2.0" ]
107
2021-08-28T20:08:42.000Z
2022-03-22T08:02:16.000Z
rdpfuzz-winafl/cmake-3.16.0/Source/cmMarkAsAdvancedCommand.cxx
fengjixuchui/rdpfuzz
4561b6fbf73ada553ce78ad44918fd0930ee4e85
[ "Apache-2.0" ]
null
null
null
rdpfuzz-winafl/cmake-3.16.0/Source/cmMarkAsAdvancedCommand.cxx
fengjixuchui/rdpfuzz
4561b6fbf73ada553ce78ad44918fd0930ee4e85
[ "Apache-2.0" ]
16
2021-08-30T06:57:36.000Z
2022-03-22T08:05:52.000Z
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmMarkAsAdvancedCommand.h" #include "cmExecutionStatus.h" #include "cmMakefile.h" #include "cmState.h" #include "cmStateTypes.h" #include "cmSystemTools.h" #include "cmake.h" // cmMarkAsAdvancedCommand bool cmMarkAsAdvancedCommand(std::vector<std::string> const& args, cmExecutionStatus& status) { if (args.empty()) { status.SetError("called with incorrect number of arguments"); return false; } unsigned int i = 0; const char* value = "1"; bool overwrite = false; if (args[0] == "CLEAR" || args[0] == "FORCE") { overwrite = true; if (args[0] == "CLEAR") { value = "0"; } i = 1; } for (; i < args.size(); ++i) { std::string const& variable = args[i]; cmState* state = status.GetMakefile().GetState(); if (!state->GetCacheEntryValue(variable)) { status.GetMakefile().GetCMakeInstance()->AddCacheEntry( variable, nullptr, nullptr, cmStateEnums::UNINITIALIZED); overwrite = true; } if (!state->GetCacheEntryValue(variable)) { cmSystemTools::Error("This should never happen..."); return false; } if (!state->GetCacheEntryProperty(variable, "ADVANCED") || overwrite) { state->SetCacheEntryProperty(variable, "ADVANCED", value); } } return true; }
29.632653
77
0.645317
[ "vector" ]
ca4ac8db9ff17a305dcd93a8bf95d8b6ae66afe7
9,468
hpp
C++
include/System/IPv6AddressHelper.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
include/System/IPv6AddressHelper.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
include/System/IPv6AddressHelper.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: KeyValuePair`2<TKey, TValue> template<typename TKey, typename TValue> struct KeyValuePair_2; } // Completed forward declares // Type namespace: System namespace System { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: System.IPv6AddressHelper // [TokenAttribute] Offset: FFFFFFFF class IPv6AddressHelper : public ::Il2CppObject { public: // Creating value type constructor for type: IPv6AddressHelper IPv6AddressHelper() noexcept {} // static System.String ParseCanonicalName(System.String str, System.Int32 start, ref System.Boolean isLoopback, ref System.String scopeId) // Offset: 0x15295C0 static ::Il2CppString* ParseCanonicalName(::Il2CppString* str, int start, ByRef<bool> isLoopback, ByRef<::Il2CppString*> scopeId); // static System.String CreateCanonicalName(System.UInt16* numbers) // Offset: 0x1529B70 static ::Il2CppString* CreateCanonicalName(uint16_t* numbers); // static private System.Collections.Generic.KeyValuePair`2<System.Int32,System.Int32> FindCompressionRange(System.UInt16* numbers) // Offset: 0x152A17C static System::Collections::Generic::KeyValuePair_2<int, int> FindCompressionRange(uint16_t* numbers); // static private System.Boolean ShouldHaveIpv4Embedded(System.UInt16* numbers) // Offset: 0x152A254 static bool ShouldHaveIpv4Embedded(uint16_t* numbers); // static private System.Boolean InternalIsValid(System.Char* name, System.Int32 start, ref System.Int32 end, System.Boolean validateStrictAddress) // Offset: 0x152A2E4 static bool InternalIsValid(::Il2CppChar* name, int start, ByRef<int> end, bool validateStrictAddress); // static System.Boolean IsValid(System.Char* name, System.Int32 start, ref System.Int32 end) // Offset: 0x152A5B8 static bool IsValid(::Il2CppChar* name, int start, ByRef<int> end); // static System.Boolean IsValidStrict(System.Char* name, System.Int32 start, ref System.Int32 end) // Offset: 0x152A5C0 static bool IsValidStrict(::Il2CppChar* name, int start, ByRef<int> end); // static System.Boolean Parse(System.String address, System.UInt16* numbers, System.Int32 start, ref System.String scopeId) // Offset: 0x1529684 static bool Parse(::Il2CppString* address, uint16_t* numbers, int start, ByRef<::Il2CppString*> scopeId); }; // System.IPv6AddressHelper #pragma pack(pop) } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(System::IPv6AddressHelper*, "System", "IPv6AddressHelper"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::IPv6AddressHelper::ParseCanonicalName // Il2CppName: ParseCanonicalName template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (*)(::Il2CppString*, int, ByRef<bool>, ByRef<::Il2CppString*>)>(&System::IPv6AddressHelper::ParseCanonicalName)> { static const MethodInfo* get() { static auto* str = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* start = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* isLoopback = &::il2cpp_utils::GetClassFromName("System", "Boolean")->this_arg; static auto* scopeId = &::il2cpp_utils::GetClassFromName("System", "String")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::IPv6AddressHelper*), "ParseCanonicalName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{str, start, isLoopback, scopeId}); } }; // Writing MetadataGetter for method: System::IPv6AddressHelper::CreateCanonicalName // Il2CppName: CreateCanonicalName template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (*)(uint16_t*)>(&System::IPv6AddressHelper::CreateCanonicalName)> { static const MethodInfo* get() { static auto* numbers = &il2cpp_functions::Class_GetPtrClass(::il2cpp_utils::GetClassFromName("System", "UInt16"))->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::IPv6AddressHelper*), "CreateCanonicalName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{numbers}); } }; // Writing MetadataGetter for method: System::IPv6AddressHelper::FindCompressionRange // Il2CppName: FindCompressionRange template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Collections::Generic::KeyValuePair_2<int, int> (*)(uint16_t*)>(&System::IPv6AddressHelper::FindCompressionRange)> { static const MethodInfo* get() { static auto* numbers = &il2cpp_functions::Class_GetPtrClass(::il2cpp_utils::GetClassFromName("System", "UInt16"))->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::IPv6AddressHelper*), "FindCompressionRange", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{numbers}); } }; // Writing MetadataGetter for method: System::IPv6AddressHelper::ShouldHaveIpv4Embedded // Il2CppName: ShouldHaveIpv4Embedded template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(uint16_t*)>(&System::IPv6AddressHelper::ShouldHaveIpv4Embedded)> { static const MethodInfo* get() { static auto* numbers = &il2cpp_functions::Class_GetPtrClass(::il2cpp_utils::GetClassFromName("System", "UInt16"))->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::IPv6AddressHelper*), "ShouldHaveIpv4Embedded", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{numbers}); } }; // Writing MetadataGetter for method: System::IPv6AddressHelper::InternalIsValid // Il2CppName: InternalIsValid template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::Il2CppChar*, int, ByRef<int>, bool)>(&System::IPv6AddressHelper::InternalIsValid)> { static const MethodInfo* get() { static auto* name = &il2cpp_functions::Class_GetPtrClass(::il2cpp_utils::GetClassFromName("System", "Char"))->byval_arg; static auto* start = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* end = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg; static auto* validateStrictAddress = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::IPv6AddressHelper*), "InternalIsValid", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{name, start, end, validateStrictAddress}); } }; // Writing MetadataGetter for method: System::IPv6AddressHelper::IsValid // Il2CppName: IsValid template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::Il2CppChar*, int, ByRef<int>)>(&System::IPv6AddressHelper::IsValid)> { static const MethodInfo* get() { static auto* name = &il2cpp_functions::Class_GetPtrClass(::il2cpp_utils::GetClassFromName("System", "Char"))->byval_arg; static auto* start = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* end = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::IPv6AddressHelper*), "IsValid", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{name, start, end}); } }; // Writing MetadataGetter for method: System::IPv6AddressHelper::IsValidStrict // Il2CppName: IsValidStrict template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::Il2CppChar*, int, ByRef<int>)>(&System::IPv6AddressHelper::IsValidStrict)> { static const MethodInfo* get() { static auto* name = &il2cpp_functions::Class_GetPtrClass(::il2cpp_utils::GetClassFromName("System", "Char"))->byval_arg; static auto* start = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* end = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::IPv6AddressHelper*), "IsValidStrict", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{name, start, end}); } }; // Writing MetadataGetter for method: System::IPv6AddressHelper::Parse // Il2CppName: Parse template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::Il2CppString*, uint16_t*, int, ByRef<::Il2CppString*>)>(&System::IPv6AddressHelper::Parse)> { static const MethodInfo* get() { static auto* address = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* numbers = &il2cpp_functions::Class_GetPtrClass(::il2cpp_utils::GetClassFromName("System", "UInt16"))->byval_arg; static auto* start = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* scopeId = &::il2cpp_utils::GetClassFromName("System", "String")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::IPv6AddressHelper*), "Parse", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{address, numbers, start, scopeId}); } };
66.676056
200
0.734157
[ "vector" ]
ca5139a6219a3702be00b50000f6f8cfff376021
590
cpp
C++
Other OJs/Random/Contest/NowCoder28/E.cpp
lxdlam/ACM
cde519ef9732ff9e4e9e3f53c00fb30d07bdb306
[ "MIT" ]
1
2019-11-12T15:08:16.000Z
2019-11-12T15:08:16.000Z
Other OJs/Random/Contest/NowCoder28/E.cpp
lxdlam/ACM
cde519ef9732ff9e4e9e3f53c00fb30d07bdb306
[ "MIT" ]
null
null
null
Other OJs/Random/Contest/NowCoder28/E.cpp
lxdlam/ACM
cde519ef9732ff9e4e9e3f53c00fb30d07bdb306
[ "MIT" ]
1
2018-01-22T08:06:11.000Z
2018-01-22T08:06:11.000Z
#include <algorithm> #include <cstring> #include <iostream> #include <map> #include <queue> #include <set> #include <sstream> #include <string> #include <vector> using namespace std; typedef long long ll; typedef pair<int, int> pii; typedef vector<int> vi; typedef vector<ll> vll; typedef set<int> si; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int T; cin >> T; cin.get(); ll res; string t; int k; while (T--) { res = 0; getline(cin, t); stringstream ss(t); while (ss >> k) res += k; cout << res << endl; } return 0; }
15.526316
30
0.615254
[ "vector" ]
ca589f8733d9dfb89bdf4a2d6200cf65cc6b2b62
2,291
hpp
C++
include/physicsengine/PhysicsEngine.hpp
ThePythonator/Rocket-Manager
61489a9df2ac25b96ac337afd5cb58375533c748
[ "MIT" ]
2
2022-03-17T18:11:07.000Z
2022-03-17T19:55:35.000Z
include/physicsengine/PhysicsEngine.hpp
ThePythonator/Rocket-Manager
61489a9df2ac25b96ac337afd5cb58375533c748
[ "MIT" ]
null
null
null
include/physicsengine/PhysicsEngine.hpp
ThePythonator/Rocket-Manager
61489a9df2ac25b96ac337afd5cb58375533c748
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include "Collisions.hpp" #include "Constraints.hpp" namespace PhysicsEngine { // This struct can be used by the user to store the pointers. struct PhysicsData { PhysicsData(); ~PhysicsData(); std::vector<Shape*> shapes; std::vector<RigidBody*> bodies; std::vector<Constraint*> constraints; std::vector<Material*> materials; }; class PhysicsManager { public: struct Constants { // Number of iterations shouldn't really be used (i.e. keep as 1) since it doesn't recalculate collision data uint8_t iterations = 1; // increasing this may or may not make the sim work better // Bias factor scales the extra impulse used for positional correction. Don't set it much higher than 0.1, otherwise too much kinetic energy is added to the system phyflt bias_factor = 0.1; // The amount of penetration we allow before applying the positional correction impulse phyflt penetration_slop = 0.005; phyflt gravitational_constant = G; }; PhysicsManager(); void set_constants(Constants _constants); Constants get_constants(); void update(phyflt dt); void step(phyflt dt); // Returns the index of the item in the vector uint16_t add_body(RigidBody* body); uint16_t add_constraint(Constraint* constraint); //void clear_bodies(); std::vector<RigidBody*>& get_bodies(); std::vector<Constraint*>& get_constraints(); void remove_constraint(uint32_t index); // Clear everything void clear(); private: void update_velocity(RigidBody* body, phyflt dt); void update_position(RigidBody* body, phyflt dt); void add_impulse(RigidBody* body, const phyvec& impulse, const phyvec& vector_to_contact); void update_forces(); void update_constraints(); void update_velocities(phyflt dt); void update_positions(phyflt dt); void handle_collisions(phyflt dt); CollisionInformation detect_collision(RigidBody* a, RigidBody* b); void resolve_collision(RigidBody* a, RigidBody* b, const CollisionInformation& collision_information, phyflt dt); struct CollisionPacket { CollisionInformation collision_information; // Index of each body in bodies uint16_t index_a, index_b; }; std::vector<RigidBody*> bodies; std::vector<Constraint*> constraints; Constants constants; }; }
28.6375
166
0.741598
[ "shape", "vector" ]
3ed14a7fedec50933fd816b24c350a085f06b5b3
1,318
cpp
C++
Leetcode/C++ Solutions/Arrays/longestConsecutiveSequence.cpp
Mostofa-Najmus-Sakib/Applied-Algorithm
bc656fd655617407856e0ce45b68585fa81c5035
[ "MIT" ]
1
2020-01-06T02:21:56.000Z
2020-01-06T02:21:56.000Z
Leetcode/C++ Solutions/Arrays/longestConsecutiveSequence.cpp
Mostofa-Najmus-Sakib/Applied-Algorithm
bc656fd655617407856e0ce45b68585fa81c5035
[ "MIT" ]
null
null
null
Leetcode/C++ Solutions/Arrays/longestConsecutiveSequence.cpp
Mostofa-Najmus-Sakib/Applied-Algorithm
bc656fd655617407856e0ce45b68585fa81c5035
[ "MIT" ]
3
2021-02-22T17:41:01.000Z
2022-01-13T05:03:19.000Z
/* LeetCode Problem 128. Longest Consecutive Sequence Link: https://leetcode.com/problems/longest-consecutive-sequence/ Written by: Mostofa Adib Shakib Language: C++ */ class Solution { public: int getMaximum(int x, int y) { return (x > y) ? x:y; } int longestConsecutive(vector<int>& nums) { unordered_set <int> hashSet; unordered_set <int> visited; int length = nums.size(); int ans = 0; for (int i = 0; i < length; i++) { hashSet.insert(nums[i]); } for (int i = 0; i < length; i++) { int streak = 1; int currentLeft = nums[i]; int currentRight = nums[i]; while ( hashSet.find(currentLeft-1) != hashSet.end() && visited.find(currentLeft-1) == visited.end()) { visited.insert(currentLeft-1); streak++; currentLeft -= 1; } while ( hashSet.find(currentRight+1) != hashSet.end() && visited.find(currentRight+1) == visited.end()) { visited.insert(currentRight+1); streak++; currentRight += 1; } ans = getMaximum(ans, streak); } return ans; } };
28.042553
117
0.492413
[ "vector" ]
3ed2940a2ab0369b2eea84a623e58df4cde779fe
14,682
cpp
C++
example/json.cpp
tzlaine/parser
095aa362d777a480fffef415d27d214cd6ffec4a
[ "BSL-1.0" ]
7
2020-08-29T02:10:20.000Z
2022-03-29T20:31:59.000Z
example/json.cpp
tzlaine/parser
095aa362d777a480fffef415d27d214cd6ffec4a
[ "BSL-1.0" ]
16
2020-08-29T21:33:08.000Z
2022-03-22T03:01:02.000Z
example/json.cpp
tzlaine/parser
095aa362d777a480fffef415d27d214cd6ffec4a
[ "BSL-1.0" ]
1
2021-09-22T08:15:57.000Z
2021-09-22T08:15:57.000Z
// Copyright (C) 2020 T. Zachary Laine // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //[ extended_json_example // This header includes a type called json::value that acts as a // Javascript-like polymorphic value type. #include "json.hpp" #include <boost/parser/parser.hpp> #include <boost/container/small_vector.hpp> #include <fstream> #include <climits> namespace json { namespace bp = ::boost::parser; using namespace bp::literals; // The JSON spec imposes a limit on how deeply JSON data structures are // allowed to nest. This exception is thrown when that limit is exceeded // during the parse. template<typename Iter> struct excessive_nesting : std::runtime_error { excessive_nesting(Iter it) : runtime_error("excessive_nesting"), iter(it) {} Iter iter; }; // The only globals we need to parse JSON are: "How many data structures // deep are we?", and "What is the limit of open data structures // allowed?". struct global_state { int recursive_open_count = 0; int max_recursive_open_count = 0; }; // When matching paired UTF-16 surrogates, we need to track a bit of state // between matching the first and second UTF-16 code units: namely, the // value of the first code unit. struct double_escape_locals { int first_surrogate = 0; }; // Here are all the rules declared. I've given them names that are // end-user friendly, so that if there is a parse error, you get a message // like "expected four hexidecimal digits here:", instead of "expected // hex_4 here:". bp::rule<class ws> const ws = "whitespace"; bp::rule<class string_char, uint32_t> const string_char = "code point (code points <= U+001F must be escaped)"; bp::rule<class four_hex_digits, uint32_t> const hex_4 = "four hexidecimal digits"; bp::rule<class escape_seq, uint32_t> const escape_seq = "\\uXXXX hexidecimal escape sequence"; bp::rule<class escape_double_seq, uint32_t, double_escape_locals> const escape_double_seq = "\\uXXXX hexidecimal escape sequence"; bp::rule<class single_escaped_char, uint32_t> const single_escaped_char = "'\"', '\\', '/', 'b', 'f', 'n', 'r', or 't'"; bp::rule<class null, value> const null = "null"; bp::rule<class string, std::string> const string = "string"; bp::rule<class number, double> const number = "number"; bp::rule<class object_element, boost::parser::tuple<std::string, value>> const object_element = "object-element"; bp::rule<class object_tag, value> const object_p = "object"; bp::rule<class array_tag, value> const array_p = "array"; bp::rule<class value_tag, value> const value_p = "value"; // JSON limits whitespace to just these four characters. auto const ws_def = '\x09'_l | '\x0a' | '\x0d' | '\x20'; // Since our json object representation, json::value, is polymorphic, and // since its default-constructed state represents the JSON value "null", // we need to tell a json::value that it is an object (similar to a map) // before we start inserting values into it. That's why we need // object_init. auto object_init = [](auto & ctx) { auto & globals = _globals(ctx); if (globals.max_recursive_open_count < ++globals.recursive_open_count) throw excessive_nesting(_where(ctx).begin()); _val(ctx) = object(); }; // We need object_insert because we can't just insert into the json::value // itself. The json::value does not have an insert() member, because if // it is currently holding a number, that makes no sense. So, for a // json::value x, we need to call get<object>(x) to get the object // interface. auto object_insert = [](auto & ctx) { value & v = _val(ctx); get<object>(v).insert(std::make_pair( std::move(_attr(ctx))[0_c], std::move(_attr(ctx)[1_c]))); }; // These are the array analogues of the object semantic actions above. auto array_init = [](auto & ctx) { auto & globals = _globals(ctx); if (globals.max_recursive_open_count < ++globals.recursive_open_count) throw excessive_nesting(_where(ctx).begin()); _val(ctx) = array(); }; auto array_append = [](auto & ctx) { value & v = _val(ctx); get<array>(v).push_back(std::move(_attr(ctx))); }; // escape_double_seq is used to match pairs of UTF-16 surrogates that form // a single code point. So, after matching one UTF-16 code unit c, we // only want to keep going if c is a lead/high surrogate. auto first_hex_escape = [](auto & ctx) { auto & locals = _locals(ctx); uint32_t const cu = _attr(ctx); if (!boost::parser::detail::text::high_surrogate(cu)) _pass(ctx) = false; // Not a high surrogate; explicitly fail the parse. else locals.first_surrogate = cu; // Save this initial code unit for later. }; // This is also used in escape_double_seq. When we get to this action, we // know we've already matched a high surrogate, and so this one had better // be a low surrogate, or we have a (local) parse failure. auto second_hex_escape = [](auto & ctx) { auto & locals = _locals(ctx); uint32_t const cu = _attr(ctx); if (!boost::parser::detail::text::low_surrogate(cu)) { _pass(ctx) = false; // Not a low surrogate; explicitly fail the parse. } else { // Success! Write to the rule's attribute the code point that the // first and second code points form. uint32_t const high_surrogate_min = 0xd800; uint32_t const low_surrogate_min = 0xdc00; uint32_t const surrogate_offset = 0x10000 - (high_surrogate_min << 10) - low_surrogate_min; uint32_t const first_cu = locals.first_surrogate; _val(ctx) = (first_cu << 10) + cu + surrogate_offset; } }; // This is the verbose form of declaration for the integer and unsigned // integer parsers int_parser and uint_parser. In this case, we don't // want to use boost::parser::hex directly, since it has a variable number // of digits. We want to match exactly 4 digits, and this is how we // declare a hexidecimal parser that matches exactly 4. bp::parser_interface<bp::uint_parser<uint32_t, 16, 4, 4>> const hex_4_def; // We use > here instead of >>, because once we see \u, we know that // exactly four hex digits must follow -- no other production rule starts // with \u. auto const escape_seq_def = "\\u" > hex_4; // This uses the actions above and the simpler rule escape_seq to find // matched UTF-16 surrogate pairs. auto const escape_double_seq_def = escape_seq[first_hex_escape] >> escape_seq[second_hex_escape]; // This symbol table recognizes each character that can appear right after // an escaping backslash, and, if it finds one, produces the associated // code point as its attribute. bp::symbols<uint32_t> const single_escaped_char_def = { {"\"", 0x0022u}, {"\\", 0x005cu}, {"/", 0x002fu}, {"b", 0x0008u}, {"f", 0x000cu}, {"n", 0x000au}, {"r", 0x000du}, {"t", 0x0009u}}; // A string may be a matched UTF-16 escaped surrogate pair, a single // escaped UTF-16 code uint treated as a whole code point, a single // escaped character like \f, or any other code point outside the range // [0x0000u, 0x001fu]. Note that we had to put escape_double_seq before // escape_seq. Otherwise, escape_seq would eat all the escape sequences // before escape_double_seq could try to match them. auto const string_char_def = escape_double_seq | escape_seq | ('\\'_l > single_escaped_char) | (bp::cp - bp::char_(0x0000u, 0x001fu)); // If we see the special token null, treat that as a default-constructed // json::value. Note that we could have done this with a semantic action, // but it is best to do everything you can without semantic actions; // they're a lot of code. auto const null_def = "null" >> bp::attr(value()); auto const string_def = bp::lexeme['"' >> *(string_char - '"') > '"']; // Since the JSON format for numbers is not exactly what // boost::parser::double_ accepts (double_ accepts too much), we need to // parse a JSON number as a sequence of characters, and then pass the // result to double_ to actually get the numeric value. This action does // that. The parser uses boost::parser::raw to produce the subrange of // the input that covers the number as an attribute, which is used here. auto parse_double = [](auto & ctx) { auto const cp_range = _attr(ctx); auto cp_first = cp_range.begin(); auto const cp_last = cp_range.end(); auto const result = bp::parse(cp_first, cp_last, bp::double_); if (result) { _val(ctx) = *result; } else { boost::container::small_vector<char, 128> chars(cp_first, cp_last); auto const chars_first = &*chars.begin(); auto chars_last = chars_first + chars.size(); _val(ctx) = std::strtod(chars_first, &chars_last); } }; // As indicated above, we want to match the specific formats JSON allows, // and then re-parse the resulting matched range within the semantic // action. auto const number_def = bp::raw [bp::lexeme [-bp::char_('-') >> (bp::char_('1', '9') >> *bp::ascii::digit | bp::char_('0')) >> -(bp::char_('.') >> +bp::ascii::digit) >> -(bp::char_("eE") >> -bp::char_("+-") >> +bp::ascii::digit)]] [parse_double]; // Note how, in the next three parsers, we turn off backtracking by using // > instead of >>, once we know that there is no backtracking alternative // that might match if we fail to match the next element. This produces // much better error messages than if you always use >>. auto const object_element_def = string > ':' > value_p; auto const object_p_def = '{'_l[object_init] >> -(object_element[object_insert] % ',') > '}'; auto const array_p_def = '['_l[array_init] >> -(value_p[array_append] % ',') > ']'; // This is the top-level parser. auto const value_p_def = number | bp::bool_ | null | string | array_p | object_p; // Here, we define all the rules we've declared about, which also connects // each rule to its _def-suffixed parser. BOOST_PARSER_DEFINE_RULES( ws, hex_4, escape_seq, escape_double_seq, single_escaped_char, string_char, null, string, number, object_element, object_p, array_p, value_p); // json::parse() takes a string_view as input. It takes an optional // callback to use for error reporting, which defaults to a no-op that // ignores all errors. It also takes an optional max recursion depth // limit, which defaults to the one from the JSON spec, 512. std::optional<value> parse( std::string_view str, diagnostic_function errors_callback = diagnostic_function(), int max_recursion = 512) { // Turn the input range into a UTF-32 range, so that we can be sure // that we fall into the Unicode-aware parsing path inside parse() // below. auto const range = boost::parser::detail::text::as_utf32(str); using iter_t = decltype(range.begin()); if (max_recursion <= 0) max_recursion = INT_MAX; // Initialize our globals to the current depth (0), and the max depth // (max_recursion). global_state globals{0, max_recursion}; bp::callback_error_handler error_handler(errors_callback); // Make a new parser that includes the globals and error handler. auto const parser = bp::with_error_handler( bp::with_globals(value_p, globals), error_handler); try { // Parse. If no exception is thrown, due to: a failed expectation // (such as foo > bar, where foo matches the input, but then bar // cannot); or because the nesting depth is exceeded; we simply // return the result of the parse. The result will contextually // convert to false if the parse failed. Note that the // failed-expectation exception is caught internally, and used to // generate an error message. return bp::parse(range, parser, ws); } catch (excessive_nesting<iter_t> const & e) { // If we catch an excessive_nesting exception, just reported it // and return an empty/failure result. if (errors_callback) { std::string const message = "error: Exceeded maximum number (" + std::to_string(max_recursion) + ") of open arrays and/or objects"; std::stringstream ss; bp::write_formatted_message( ss, "", range.begin(), e.iter, range.end(), message); errors_callback(ss.str()); } } return {}; } } std::string file_slurp(std::ifstream & ifs) { std::string retval; while (ifs) { char const c = ifs.get(); retval += c; } if (!retval.empty() && retval[retval.back() == -1]) retval.pop_back(); return retval; } int main(int argc, char * argv[]) { if (argc < 2) { std::cerr << "A filename to parse is required.\n"; exit(1); } std::ifstream ifs(argv[1]); if (!ifs) { std::cerr << "Unable to read file '" << argv[1] << "'.\n"; exit(1); } // Read in the entire file. std::string const file_contents = file_slurp(ifs); // Parse the contents. If there is an error, just stream it to cerr. auto json = json::parse( file_contents, [](std::string const & msg) { std::cerr << msg; }); if (!json) { std::cerr << "Parse failure.\n"; exit(1); } std::cout << "Parse successful; contents:\n" << *json << "\n"; return 0; } //]
40.335165
83
0.615243
[ "object" ]
3edbdb0ec4bb75a77120d73f136507cd7d798aaa
1,272
cpp
C++
src/hotrod/impl/operations/PingOperation.cpp
rigazilla/cpp-client
db7b1de589f4e227ee5b2b0a86913e036e17ca7a
[ "Apache-2.0" ]
null
null
null
src/hotrod/impl/operations/PingOperation.cpp
rigazilla/cpp-client
db7b1de589f4e227ee5b2b0a86913e036e17ca7a
[ "Apache-2.0" ]
null
null
null
src/hotrod/impl/operations/PingOperation.cpp
rigazilla/cpp-client
db7b1de589f4e227ee5b2b0a86913e036e17ca7a
[ "Apache-2.0" ]
null
null
null
#include "hotrod/impl/operations/PingOperation.h" #include "hotrod/impl/protocol/HeaderParams.h" #include "hotrod/impl/transport/Transport.h" namespace infinispan { namespace hotrod { using namespace protocol; using transport::Transport; namespace operations { PingOperation::PingOperation(const Codec& c, Topology& id, Transport& t, const std::vector<char>& n) : HotRodOperation<PingResult>(c, 0, n, id), transport(t) {} PingOperation::PingOperation(const Codec& c, Topology& id, Transport& t) : HotRodOperation<PingResult>(c, 0, std::vector<char>(), id), transport(t) {} PingResult PingOperation::execute() { std::unique_ptr<infinispan::hotrod::protocol::HeaderParams> params(&writeHeader(transport, HotRodConstants::PING_REQUEST)); transport.flush(); uint8_t respStatus = readHeaderAndValidate(transport, *params); if (HotRodConstants::isSuccess(respStatus)) { TRACE("Ping successful!"); if (HotRodConstants::hasCompatibility(respStatus)) { WARN("Server has compatibility mode enabled. Inconsistency in hash calculation may occur"); return PingResult::SUCCESS_WITH_COMPAT; } else { return PingResult::SUCCESS; } } else { TRACE("Ping failed!"); return FAIL; } } }}} // namespace
28.909091
124
0.715409
[ "vector" ]
3edd6bdc8a5879f96a27f9b1829cf7fe148f7a39
13,820
cc
C++
src/chrome_frame/test/dll_redirector_test.cc
jxjnjjn/chromium
435c1d02fd1b99001dc9e1e831632c894523580d
[ "Apache-2.0" ]
9
2018-09-21T05:36:12.000Z
2021-11-15T15:14:36.000Z
chrome_frame/test/dll_redirector_test.cc
devasia1000/chromium
919a8a666862fb866a6bb7aa7f3ae8c0442b4828
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2015-02-02T06:55:08.000Z
2016-01-20T06:11:59.000Z
chrome_frame/test/dll_redirector_test.cc
devasia1000/chromium
919a8a666862fb866a6bb7aa7f3ae8c0442b4828
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
6
2016-11-14T10:13:35.000Z
2021-01-23T15:29:53.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome_frame/dll_redirector.h" #include "base/shared_memory.h" #include "base/utf_string_conversions.h" #include "base/version.h" #include "base/win/scoped_handle.h" #include "base/win/windows_version.h" #include "chrome_frame/test/chrome_frame_test_utils.h" #include "gtest/gtest.h" extern "C" IMAGE_DOS_HEADER __ImageBase; const char kMockVersionString[] = "42.42.42.42"; const char kMockVersionString2[] = "133.33.33.7"; const HMODULE kMockModuleHandle = reinterpret_cast<HMODULE>(42); const HMODULE kMockModuleHandle2 = reinterpret_cast<HMODULE>(43); const char kTestVersionBeaconName[] = "DllRedirectorTestVersionBeacon"; const uint32 kSharedMemorySize = 128; // The maximum amount of time we are willing to let a test that Waits timeout // before failing. const uint32 kWaitTestTimeout = 20000; class MockDllRedirector : public DllRedirector { public: explicit MockDllRedirector(const char* beacon_name) : DllRedirector(beacon_name) {} virtual HMODULE LoadVersionedModule() { return kMockModuleHandle; } virtual Version* GetCurrentModuleVersion() { return new Version(kMockVersionString); } virtual HMODULE GetFirstModule() { return DllRedirector::GetFirstModule(); } Version* GetFirstModuleVersion() { // Lazy man's copy. return new Version(dll_version_->GetString()); } base::SharedMemory* shared_memory() { return shared_memory_.get(); } }; class MockDllRedirector2 : public MockDllRedirector { public: explicit MockDllRedirector2(const char* beacon_name) : MockDllRedirector(beacon_name) {} virtual HMODULE LoadVersionedModule() { return kMockModuleHandle2; } virtual Version* GetCurrentModuleVersion() { return new Version(kMockVersionString2); } }; class MockDllRedirectorNoPermissions : public MockDllRedirector { public: explicit MockDllRedirectorNoPermissions(const char* beacon_name) : MockDllRedirector(beacon_name) {} virtual bool BuildSecurityAttributesForLock( ATL::CSecurityAttributes* sec_attr) { return false; } virtual bool SetFileMappingToReadOnly(base::SharedMemoryHandle mapping) { return true; } }; class DllRedirectorTest : public testing::Test { public: virtual void SetUp() { shared_memory_.reset(new base::SharedMemory); mock_version_.reset(new Version(kMockVersionString)); mock_version2_.reset(new Version(kMockVersionString2)); } virtual void TearDown() { CloseBeacon(); } void CreateVersionBeacon(const std::string& name, const std::string& version_string) { // Abort the test if we can't create and map a new named memory object. EXPECT_TRUE(shared_memory_->CreateNamed(name, false, kSharedMemorySize)); EXPECT_TRUE(shared_memory_->Map(0)); EXPECT_TRUE(shared_memory_->memory()); if (shared_memory_->memory()) { memcpy(shared_memory_->memory(), version_string.c_str(), std::min(kSharedMemorySize, version_string.length() + 1)); } } // Opens the named beacon and returns the version. Version* OpenAndReadVersionFromBeacon(const std::string& name) { // Abort the test if we can't open and map the named memory object. EXPECT_TRUE(shared_memory_->Open(name, true /* read_only */)); EXPECT_TRUE(shared_memory_->Map(0)); EXPECT_TRUE(shared_memory_->memory()); char buffer[kSharedMemorySize] = {0}; memcpy(buffer, shared_memory_->memory(), kSharedMemorySize - 1); scoped_ptr<Version> version(new Version(buffer)); if (!version->IsValid()) version.reset(); return version.release(); } void CloseBeacon() { shared_memory_->Close(); } // Shared memory segment that contains the version beacon. scoped_ptr<base::SharedMemory> shared_memory_; scoped_ptr<Version> mock_version_; scoped_ptr<Version> mock_version2_; }; TEST_F(DllRedirectorTest, RegisterAsFirstModule) { scoped_ptr<MockDllRedirector> redirector( new MockDllRedirector(kTestVersionBeaconName)); EXPECT_TRUE(redirector->RegisterAsFirstCFModule()); base::SharedMemory* redirector_memory = redirector->shared_memory(); char buffer[kSharedMemorySize] = {0}; memcpy(buffer, redirector_memory->memory(), kSharedMemorySize - 1); Version redirector_version(buffer); ASSERT_TRUE(redirector_version.IsValid()); EXPECT_TRUE(redirector_version.Equals(*mock_version_.get())); redirector_memory = NULL; scoped_ptr<Version> memory_version( OpenAndReadVersionFromBeacon(kTestVersionBeaconName)); ASSERT_TRUE(memory_version.get()); EXPECT_TRUE(redirector_version.Equals(*memory_version.get())); CloseBeacon(); redirector.reset(); EXPECT_FALSE(shared_memory_->Open(kTestVersionBeaconName, true)); } TEST_F(DllRedirectorTest, SecondModuleLoading) { scoped_ptr<MockDllRedirector> first_redirector( new MockDllRedirector(kTestVersionBeaconName)); EXPECT_TRUE(first_redirector->RegisterAsFirstCFModule()); scoped_ptr<MockDllRedirector2> second_redirector( new MockDllRedirector2(kTestVersionBeaconName)); EXPECT_FALSE(second_redirector->RegisterAsFirstCFModule()); scoped_ptr<Version> first_redirector_version( first_redirector->GetFirstModuleVersion()); scoped_ptr<Version> second_redirector_version( second_redirector->GetFirstModuleVersion()); EXPECT_TRUE( second_redirector_version->Equals(*first_redirector_version.get())); EXPECT_TRUE( second_redirector_version->Equals(*mock_version_.get())); } // This test ensures that the beacon remains alive as long as there is a single // module that used it to determine its version still loaded. TEST_F(DllRedirectorTest, TestBeaconOwnershipHandoff) { scoped_ptr<MockDllRedirector> first_redirector( new MockDllRedirector(kTestVersionBeaconName)); EXPECT_TRUE(first_redirector->RegisterAsFirstCFModule()); scoped_ptr<MockDllRedirector2> second_redirector( new MockDllRedirector2(kTestVersionBeaconName)); EXPECT_FALSE(second_redirector->RegisterAsFirstCFModule()); scoped_ptr<Version> first_redirector_version( first_redirector->GetFirstModuleVersion()); scoped_ptr<Version> second_redirector_version( second_redirector->GetFirstModuleVersion()); EXPECT_TRUE( second_redirector_version->Equals(*first_redirector_version.get())); EXPECT_TRUE( second_redirector_version->Equals(*mock_version_.get())); // Clear out the first redirector. The second, still holding a reference // to the shared memory should ensure that the beacon stays alive. first_redirector.reset(); scoped_ptr<MockDllRedirector2> third_redirector( new MockDllRedirector2(kTestVersionBeaconName)); EXPECT_FALSE(third_redirector->RegisterAsFirstCFModule()); scoped_ptr<Version> third_redirector_version( third_redirector->GetFirstModuleVersion()); EXPECT_TRUE( third_redirector_version->Equals(*second_redirector_version.get())); EXPECT_TRUE( third_redirector_version->Equals(*mock_version_.get())); // Now close all remaining redirectors, which should destroy the beacon. second_redirector.reset(); third_redirector.reset(); // Now create a fourth, expecting that this time it should be the first in. scoped_ptr<MockDllRedirector2> fourth_redirector( new MockDllRedirector2(kTestVersionBeaconName)); EXPECT_TRUE(fourth_redirector->RegisterAsFirstCFModule()); scoped_ptr<Version> fourth_redirector_version( fourth_redirector->GetFirstModuleVersion()); EXPECT_TRUE( fourth_redirector_version->Equals(*mock_version2_.get())); } struct LockSquattingThreadParams { base::win::ScopedHandle is_squatting; base::win::ScopedHandle time_to_die; }; DWORD WINAPI LockSquattingThread(void* in_params) { LockSquattingThreadParams* params = reinterpret_cast<LockSquattingThreadParams*>(in_params); DCHECK(params); // Grab the lock for the shared memory region and hold onto it. base::SharedMemory squatter(ASCIIToWide(kTestVersionBeaconName)); base::SharedMemoryAutoLock squatter_lock(&squatter); // Notify our caller that we're squatting. BOOL ret = ::SetEvent(params->is_squatting); DCHECK(ret); // And then wait to be told to shut down. DWORD result = ::WaitForSingleObject(params->time_to_die, kWaitTestTimeout); EXPECT_EQ(WAIT_OBJECT_0, result); return 0; } // Test that the Right Thing happens when someone else is holding onto the // beacon lock and not letting go. (The Right Thing being that the redirector // assumes that it is the right version and doesn't attempt to use the shared // memory region.) TEST_F(DllRedirectorTest, LockSquatting) { scoped_ptr<MockDllRedirector> first_redirector( new MockDllRedirector(kTestVersionBeaconName)); EXPECT_TRUE(first_redirector->RegisterAsFirstCFModule()); LockSquattingThreadParams params; params.is_squatting.Set(::CreateEvent(NULL, FALSE, FALSE, NULL)); params.time_to_die.Set(::CreateEvent(NULL, FALSE, FALSE, NULL)); DWORD tid = 0; base::win::ScopedHandle lock_squat_thread( ::CreateThread(NULL, 0, LockSquattingThread, &params, 0, &tid)); // Make sure the squatter has started squatting. DWORD wait_result = ::WaitForSingleObject(params.is_squatting, kWaitTestTimeout); EXPECT_EQ(WAIT_OBJECT_0, wait_result); scoped_ptr<MockDllRedirector2> second_redirector( new MockDllRedirector2(kTestVersionBeaconName)); EXPECT_TRUE(second_redirector->RegisterAsFirstCFModule()); scoped_ptr<Version> second_redirector_version( second_redirector->GetFirstModuleVersion()); EXPECT_TRUE( second_redirector_version->Equals(*mock_version2_.get())); // Shut down the squatting thread. DWORD ret = ::SetEvent(params.time_to_die); DCHECK(ret); wait_result = ::WaitForSingleObject(lock_squat_thread, kWaitTestTimeout); EXPECT_EQ(WAIT_OBJECT_0, wait_result); } TEST_F(DllRedirectorTest, BadVersionNumber) { std::string bad_version("I am not a version number"); CreateVersionBeacon(kTestVersionBeaconName, bad_version); // The redirector should fail to read the version number and defer to // its own version. scoped_ptr<MockDllRedirector> first_redirector( new MockDllRedirector(kTestVersionBeaconName)); EXPECT_TRUE(first_redirector->RegisterAsFirstCFModule()); HMODULE first_module = first_redirector->GetFirstModule(); EXPECT_EQ(NULL, first_module); } // TODO(robertshield): These tests rely on simulating access checks from a low // integrity process using impersonation. This may not be exactly identical to // actually having a separate low integrity process. TEST_F(DllRedirectorTest, LowIntegrityAccess) { scoped_ptr<MockDllRedirector> first_redirector( new MockDllRedirector(kTestVersionBeaconName)); EXPECT_TRUE(first_redirector->RegisterAsFirstCFModule()); // Ensure that we can acquire the mutex from medium integrity: { base::SharedMemory shared_memory(ASCIIToWide(kTestVersionBeaconName)); bool mutex_locked = shared_memory.Lock(kWaitTestTimeout, NULL); EXPECT_TRUE(mutex_locked); // Ensure that the shared memory is read-only: EXPECT_FALSE(shared_memory.Open(kTestVersionBeaconName, false)); shared_memory.Close(); EXPECT_TRUE(shared_memory.Open(kTestVersionBeaconName, true)); shared_memory.Close(); if (mutex_locked) shared_memory.Unlock(); } if (base::win::GetVersion() >= base::win::VERSION_VISTA) { // Now move to low integrity chrome_frame_test::LowIntegrityToken low_integrity_token; ASSERT_TRUE(low_integrity_token.Impersonate()); // Ensure that we can also acquire the mutex from low integrity. base::SharedMemory shared_memory(ASCIIToWide(kTestVersionBeaconName)); bool mutex_locked = shared_memory.Lock(kWaitTestTimeout, NULL); EXPECT_TRUE(mutex_locked); // Ensure that the shared memory is read-only: EXPECT_FALSE(shared_memory.Open(kTestVersionBeaconName, false)); shared_memory.Close(); EXPECT_TRUE(shared_memory.Open(kTestVersionBeaconName, true)); shared_memory.Close(); if (mutex_locked) shared_memory.Unlock(); } } TEST_F(DllRedirectorTest, LowIntegrityAccessDenied) { // Run this test with a mock DllRedirector that doesn't set permissions // on the shared memory. scoped_ptr<MockDllRedirectorNoPermissions> first_redirector( new MockDllRedirectorNoPermissions(kTestVersionBeaconName)); EXPECT_TRUE(first_redirector->RegisterAsFirstCFModule()); // Ensure that we can acquire the mutex from medium integrity: { base::SharedMemory shared_memory(ASCIIToWide(kTestVersionBeaconName)); bool mutex_locked = shared_memory.Lock(kWaitTestTimeout, NULL); EXPECT_TRUE(mutex_locked); // We should be able to open the memory as read/write. EXPECT_TRUE(shared_memory.Open(kTestVersionBeaconName, false)); shared_memory.Close(); if (mutex_locked) shared_memory.Unlock(); } if (base::win::GetVersion() >= base::win::VERSION_VISTA) { // Now move to low integrity chrome_frame_test::LowIntegrityToken low_integrity_token; low_integrity_token.Impersonate(); // Ensure that we can't acquire the mutex without having set the // Low Integrity ACE in the SACL. base::SharedMemory shared_memory(ASCIIToWide(kTestVersionBeaconName)); bool mutex_locked = shared_memory.Lock(kWaitTestTimeout, NULL); EXPECT_FALSE(mutex_locked); // We shouldn't be able to open the memory. EXPECT_FALSE(shared_memory.Open(kTestVersionBeaconName, false)); shared_memory.Close(); if (mutex_locked) shared_memory.Unlock(); } }
34.89899
79
0.753763
[ "object" ]
3ee3354c1e8d7b0e4ec9697acee13b6513478f39
9,987
cc
C++
peridot/tests/benchmarks/story/modular_benchmark_story_session_shell.cc
yanyushr/fuchsia
98e70672a81a206d235503e398f37b7b65581f79
[ "BSD-3-Clause" ]
1
2019-10-09T10:50:57.000Z
2019-10-09T10:50:57.000Z
peridot/tests/benchmarks/story/modular_benchmark_story_session_shell.cc
bootingman/fuchsia2
04012f0aa1edd1d4108a2ac647a65e59730fc4c2
[ "BSD-3-Clause" ]
null
null
null
peridot/tests/benchmarks/story/modular_benchmark_story_session_shell.cc
bootingman/fuchsia2
04012f0aa1edd1d4108a2ac647a65e59730fc4c2
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2017 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <memory> #include <utility> #include <fuchsia/modular/cpp/fidl.h> #include <fuchsia/sys/cpp/fidl.h> #include <lib/async/cpp/task.h> #include <lib/async/default.h> #include <lib/component/cpp/startup_context.h> #include <lib/fidl/cpp/binding.h> #include <lib/fsl/vmo/strings.h> #include <src/lib/fxl/command_line.h> #include <src/lib/fxl/logging.h> #include <src/lib/fxl/macros.h> #include <src/lib/fxl/strings/string_number_conversions.h> #include <trace-provider/provider.h> #include <trace/event.h> #include <trace/observer.h> #include "peridot/lib/fidl/single_service_app.h" #include "peridot/lib/testing/component_main.h" #include "peridot/lib/testing/session_shell_impl.h" #include "peridot/public/lib/integration_testing/cpp/reporting.h" #include "peridot/public/lib/integration_testing/cpp/testing.h" #include "peridot/tests/benchmarks/story/tracing_waiter.h" namespace { const char kStoryNamePrefix[] = "story-"; const char kRootModuleName[] = "root"; class Settings { public: explicit Settings(const fxl::CommandLine& command_line) { const auto story_count_str = command_line.GetOptionValueWithDefault("story_count", "1"); if (!fxl::StringToNumberWithError(story_count_str, &story_count)) { FXL_LOG(ERROR) << "Unrecognized value [--story_count=" << story_count_str << "]: Using 0."; } module_url = command_line.GetOptionValueWithDefault( "module_url", "fuchsia-pkg://fuchsia.com/modular_benchmark_story_module#meta/" "modular_benchmark_story_module.cmx"); } int story_count{0}; std::string module_url; }; // A simple story watcher implementation that invokes a "continue" callback when // it sees the watched story transition to the given state. Used to push the // test sequence forward when the test story reaches the next state. class StoryWatcherImpl : fuchsia::modular::StoryWatcher { public: StoryWatcherImpl() : binding_(this) {} ~StoryWatcherImpl() override = default; // Registers itself as a watcher on the given story. Only one story at a time // can be watched. void Watch(fuchsia::modular::StoryController* const story_controller) { story_controller->Watch(binding_.NewBinding()); } // Deregisters itself from the watched story. void Reset() { binding_.Unbind(); } // Sets the function where to continue when the story is observed to be done. void Continue(fuchsia::modular::StoryState state, fit::function<void()> at) { continue_state_ = state; continue_ = std::move(at); } private: // |fuchsia::modular::StoryWatcher| void OnStateChange(fuchsia::modular::StoryState state) override { if (state != continue_state_) { return; } continue_(); } // |fuchsia::modular::StoryWatcher| void OnModuleAdded(fuchsia::modular::ModuleData module_data) override {} // |fuchsia::modular::StoryWatcher| void OnModuleFocused(std::vector<std::string> module_path) override {} fidl::Binding<fuchsia::modular::StoryWatcher> binding_; fuchsia::modular::StoryState continue_state_{ fuchsia::modular::StoryState::STOPPED}; fit::function<void()> continue_{[] {}}; FXL_DISALLOW_COPY_AND_ASSIGN(StoryWatcherImpl); }; // A simple link watcher implementation that invokes a "continue" callback when // it sees the watched link change. class LinkWatcherImpl : fuchsia::modular::LinkWatcher { public: LinkWatcherImpl() : binding_(this) {} ~LinkWatcherImpl() override = default; // Registers itself as a watcher on the given link. Only one story at a time // can be watched. void Watch(fuchsia::modular::Link* const link) { link->WatchAll(binding_.NewBinding()); } // Deregisters itself from the watched story. void Reset() { binding_.Unbind(); } // Sets the function where to continue when the story is observed to be done. void Continue(fit::function<void(fidl::StringPtr)> at) { continue_ = std::move(at); } private: // |fuchsia::modular::LinkWatcher| void Notify(fuchsia::mem::Buffer value) override { std::string json; FXL_CHECK(fsl::StringFromVmo(value, &json)); continue_(json); } fidl::Binding<fuchsia::modular::LinkWatcher> binding_; fit::function<void(fidl::StringPtr)> continue_{[](fidl::StringPtr) {}}; FXL_DISALLOW_COPY_AND_ASSIGN(LinkWatcherImpl); }; // Measures timing the machinery available to a session shell implementation. // This is invoked as a session shell from basemgr and executes a predefined // sequence of steps, rather than to expose a UI to be driven by user // interaction, as a session shell normally would. class TestApp : public modular::ViewApp { public: TestApp(component::StartupContext* const startup_context, Settings settings) : ViewApp(startup_context), settings_(std::move(settings)) { startup_context->ConnectToEnvironmentService( session_shell_context_.NewRequest()); session_shell_context_->GetStoryProvider(story_provider_.NewRequest()); startup_context->ConnectToEnvironmentService(puppet_master_.NewRequest()); startup_context->outgoing().AddPublicService( session_shell_impl_.GetHandler()); tracing_waiter_.WaitForTracing([this] { Loop(); }); } ~TestApp() override = default; // Called by AppDriver in ComponentMain(). NOTE(mesch): Even though it // overrides SingleServiceApp::Terminate(), it is called directly on TestApp // by AppDriver, so it must not be private. void Terminate(fit::function<void()> done) override { // The corresponding BEGIN() call is in Loop(), below. TRACE_ASYNC_END("benchmark", "user/logout", 0); done(); } private: void Loop() { if (story_count_ < settings_.story_count) { FXL_LOG(INFO) << "Loop at " << story_count_ << " of " << settings_.story_count; async::PostTask(async_get_default_dispatcher(), [this] { StoryCreate(); }); } else { TRACE_ASYNC_BEGIN("benchmark", "user/logout", 0); session_shell_context_->Logout(); } } void StoryCreate() { FXL_LOG(INFO) << "StoryCreate()"; TRACE_ASYNC_BEGIN("benchmark", "story/create", 0); std::string story_name = std::string(kStoryNamePrefix) + std::to_string(story_count_); puppet_master_->ControlStory(story_name, story_puppet_master_.NewRequest()); std::vector<fuchsia::modular::StoryCommand> commands; fuchsia::modular::AddMod add_mod; add_mod.mod_name_transitional = "root"; add_mod.intent.handler = settings_.module_url; add_mod.intent.action = "action"; fuchsia::modular::StoryCommand command; command.set_add_mod(std::move(add_mod)); commands.push_back(std::move(command)); story_puppet_master_->Enqueue(std::move(commands)); story_puppet_master_->Execute( [this, story_name](fuchsia::modular::ExecuteResult result) { TRACE_ASYNC_END("benchmark", "story/create", 0); StoryInfo(story_name); }); } void StoryInfo(fidl::StringPtr story_id) { FXL_LOG(INFO) << "StoryInfo()"; story_provider_->GetController(story_id, story_controller_.NewRequest()); TRACE_ASYNC_BEGIN("benchmark", "story/info", 0); story_controller_->GetInfo([this](fuchsia::modular::StoryInfo story_info, fuchsia::modular::StoryState state) { TRACE_ASYNC_END("benchmark", "story/info", 0); Link(); }); } void Link() { FXL_LOG(INFO) << "Link()"; fuchsia::modular::LinkPath link_path = fuchsia::modular::LinkPath(); std::vector<std::string> root_module_path; root_module_path.push_back(kRootModuleName); link_path.module_path = std::move(root_module_path); link_path.link_name = nullptr; story_controller_->GetLink(std::move(link_path), link_.NewRequest()); link_watcher_.Watch(link_.get()); link_watcher_.Continue([this](fidl::StringPtr json) { FXL_LOG(INFO) << "Link() Watch: " << json; if (json == "") { return; } const int count = fxl::StringToNumber<int>(json.get()); // Corresponding TRACE_FLOW_BEGIN() is in the module. TRACE_FLOW_END("benchmark", "link/trans", count); if (count == 100) { StoryStop(); } }); StoryStart(); } void StoryStart() { FXL_LOG(INFO) << "StoryStart()"; TRACE_ASYNC_BEGIN("benchmark", "story/start", 0); story_watcher_.Continue(fuchsia::modular::StoryState::RUNNING, [this] { TRACE_ASYNC_END("benchmark", "story/start", 0); }); story_watcher_.Watch(story_controller_.get()); story_controller_->RequestStart(); } void StoryStop() { FXL_LOG(INFO) << "StoryStop()"; TRACE_ASYNC_BEGIN("benchmark", "story/stop", 0); story_controller_->Stop([this] { TRACE_ASYNC_END("benchmark", "story/stop", 0); MaybeRepeat(); }); } void MaybeRepeat() { FXL_LOG(INFO) << "MaybeRepeat()"; story_watcher_.Reset(); story_controller_.Unbind(); story_count_++; Loop(); } modular::TracingWaiter tracing_waiter_; const Settings settings_; int story_count_{}; StoryWatcherImpl story_watcher_; LinkWatcherImpl link_watcher_; modular::testing::SessionShellImpl session_shell_impl_; fuchsia::modular::PuppetMasterPtr puppet_master_; fuchsia::modular::StoryPuppetMasterPtr story_puppet_master_; fuchsia::modular::SessionShellContextPtr session_shell_context_; fuchsia::modular::StoryProviderPtr story_provider_; fuchsia::modular::StoryControllerPtr story_controller_; fuchsia::modular::LinkPtr link_; FXL_DISALLOW_COPY_AND_ASSIGN(TestApp); }; } // namespace int main(int argc, const char** argv) { auto command_line = fxl::CommandLineFromArgcArgv(argc, argv); Settings settings(command_line); modular::testing::ComponentMain<TestApp, Settings>(std::move(settings)); return 0; }
32.320388
80
0.701212
[ "vector" ]
3ee3699bb3561baf2465d02c4bbbd7482ccf9dbe
3,678
cpp
C++
test/ModuleTests/DVRStageTest.cpp
RWTHmediTEC/Carna
51a77304428ef7913c7006ed979d5d427fe5b1d3
[ "BSD-3-Clause" ]
null
null
null
test/ModuleTests/DVRStageTest.cpp
RWTHmediTEC/Carna
51a77304428ef7913c7006ed979d5d427fe5b1d3
[ "BSD-3-Clause" ]
null
null
null
test/ModuleTests/DVRStageTest.cpp
RWTHmediTEC/Carna
51a77304428ef7913c7006ed979d5d427fe5b1d3
[ "BSD-3-Clause" ]
3
2015-07-23T12:10:14.000Z
2021-06-08T16:07:05.000Z
/* * Copyright (C) 2010 - 2015 Leonid Kostrykin * * Chair of Medical Engineering (mediTEC) * RWTH Aachen University * Pauwelsstr. 20 * 52074 Aachen * Germany * */ #include "DVRStageTest.h" #include <Carna/base/Node.h> #include <Carna/base/FrameRenderer.h> #include <Carna/helpers/VolumeGridHelper.h> #include <Carna/presets/DVRStage.h> // ---------------------------------------------------------------------------------- // DVRStageTest // ---------------------------------------------------------------------------------- void DVRStageTest::initTestCase() { const unsigned int width = 640; const unsigned int height = 480; qglContextHolder.reset( new QGLContextHolder() ); testFramebuffer.reset( new TestFramebuffer( qglContextHolder->glContext(), width, height ) ); /* Load test volume data. */ data.reset( HUGZSceneFactory::importVolume( SOURCE_PATH + "/res/pelves_reduced.hugz", dataSpacings ) ); } void DVRStageTest::cleanupTestCase() { testFramebuffer.reset(); qglContextHolder.reset(); } void DVRStageTest::init() { renderer.reset( new base::FrameRenderer( qglContextHolder->glContext(), testFramebuffer->width(), testFramebuffer->height(), true ) ); root.reset( new base::Node() ); //! [dvr_instantiation] dvr = new presets::DVRStage( GEOMETRY_TYPE_VOLUMETRIC ); renderer->appendStage( dvr ); //! [dvr_instantiation] /* Configure camera. */ cam = new base::Camera(); cam->localTransform = base::math::rotation4f( 0, 1, 0, base::math::deg2rad( 20 ) ) * base::math::translation4f( 0, 0, 350 ); cam->setProjection( base::math::frustum4f( base::math::deg2rad( 45 ), 1, 10, 2000 ) ); root->attachChild( cam ); } void DVRStageTest::cleanup() { renderer.reset(); root.reset(); } void DVRStageTest::test_withLighting() { /* Add volume data to scene. */ typedef helpers::VolumeGridHelper< base::HUVolumeUInt16, base::NormalMap3DInt8 > GridHelper; GridHelper gridHelper( data->size ); gridHelper.loadData( *data ); root->attachChild( gridHelper.createNode( GEOMETRY_TYPE_VOLUMETRIC, GridHelper::Spacing( dataSpacings ) ) ); /* Configure DVR stage. */ //! [dvr_setup_with_lighting] dvr->writeColorMap( -400, 0, base::Color:: BLUE_NO_ALPHA, base::Color:: BLUE ); dvr->writeColorMap( 0, 400, base::Color::GREEN_NO_ALPHA, base::Color::GREEN ); dvr->setSampleRate( 500 ); dvr->setTranslucence( 2 ); //! [dvr_setup_with_lighting] /* Render and verify. */ renderer->render( *cam, *root ); VERIFY_FRAMEBUFFER( *testFramebuffer ); } void DVRStageTest::test_withoutLighting() { /* Add volume data to scene. */ typedef helpers::VolumeGridHelper< base::HUVolumeUInt16 > GridHelper; GridHelper gridHelper( data->size ); gridHelper.loadData( *data ); root->attachChild( gridHelper.createNode( GEOMETRY_TYPE_VOLUMETRIC, GridHelper::Spacing( dataSpacings ) ) ); /* Configure DVR stage. */ //! [dvr_setup_without_lighting] dvr->writeColorMap( -400, 0, base::Color:: BLUE_NO_ALPHA, base::Color:: BLUE ); dvr->writeColorMap( 0, 400, base::Color::GREEN_NO_ALPHA, base::Color::GREEN ); //! [dvr_setup_without_lighting] /* Render and verify. */ renderer->render( *cam, *root ); VERIFY_FRAMEBUFFER( *testFramebuffer ); } void DVRStageTest::test_withoutColormap() { /* Add volume data to scene. */ test_withoutLighting(); /* Configure DVR stage. */ dvr->clearColorMap(); /* Render and verify. */ renderer->render( *cam, *root ); VERIFY_FRAMEBUFFER( *testFramebuffer ); }
27.447761
138
0.633496
[ "render" ]
3ee73736fbfec650fcd7f543f731e74fcf70eec8
13,585
cpp
C++
src/chrono/physics/ChConveyor.cpp
lucasw/chrono
e79d8c761c718ecb4c796725cff37026f357da8c
[ "BSD-3-Clause" ]
null
null
null
src/chrono/physics/ChConveyor.cpp
lucasw/chrono
e79d8c761c718ecb4c796725cff37026f357da8c
[ "BSD-3-Clause" ]
null
null
null
src/chrono/physics/ChConveyor.cpp
lucasw/chrono
e79d8c761c718ecb4c796725cff37026f357da8c
[ "BSD-3-Clause" ]
null
null
null
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Alessandro Tasora, Radu Serban // ============================================================================= #include <cstdlib> #include <algorithm> #include "chrono/core/ChTransform.h" #include "chrono/physics/ChConveyor.h" #include "chrono/physics/ChSystem.h" namespace chrono { using namespace collision; using namespace geometry; // Register into the object factory, to enable run-time dynamic creation and persistence CH_FACTORY_REGISTER(ChConveyor) ChConveyor::ChConveyor(double xlength, double ythick, double zwidth) : conveyor_speed(1) { conveyor_truss = new ChBody; conveyor_plate = new ChBody; conveyor_mat = chrono_types::make_shared<ChMaterialSurfaceNSC>(); conveyor_plate->GetCollisionModel()->ClearModel(); conveyor_plate->GetCollisionModel()->AddBox(conveyor_mat, xlength * 0.5, ythick * 0.5, zwidth * 0.5); conveyor_plate->GetCollisionModel()->BuildModel(); conveyor_plate->SetCollide(true); internal_link = new ChLinkLockLock; internal_link->SetMotion_X(chrono_types::make_shared<ChFunction_Ramp>()); std::shared_ptr<ChMarker> mmark1(new ChMarker); std::shared_ptr<ChMarker> mmark2(new ChMarker); conveyor_truss->AddMarker(mmark1); conveyor_plate->AddMarker(mmark2); internal_link->ReferenceMarkers(mmark1.get(), mmark2.get()); } ChConveyor::ChConveyor(const ChConveyor& other) : ChPhysicsItem(other) { conveyor_speed = other.conveyor_speed; internal_link = other.internal_link->Clone(); conveyor_plate = other.conveyor_plate->Clone(); conveyor_truss = other.conveyor_truss->Clone(); //// RADU: more to do here } ChConveyor::~ChConveyor() { if (internal_link) delete internal_link; if (conveyor_plate) delete conveyor_plate; if (conveyor_truss) delete conveyor_truss; } //// STATE BOOKKEEPING FUNCTIONS void ChConveyor::IntStateGather(const unsigned int off_x, // offset in x state vector ChState& x, // state vector, position part const unsigned int off_v, // offset in v state vector ChStateDelta& v, // state vector, speed part double& T // time ) { conveyor_truss->IntStateGather(off_x, x, off_v, v, T); conveyor_plate->IntStateGather(off_x + 7, x, off_v + 6, v, T); } void ChConveyor::IntStateScatter(const unsigned int off_x, // offset in x state vector const ChState& x, // state vector, position part const unsigned int off_v, // offset in v state vector const ChStateDelta& v, // state vector, speed part const double T, // time bool full_update // perform complete update ) { conveyor_truss->IntStateScatter(off_x, x, off_v, v, T, full_update); conveyor_plate->IntStateScatter(off_x + 7, x, off_v + 6, v, T, full_update); this->Update(T, full_update); } void ChConveyor::IntStateGatherAcceleration(const unsigned int off_a, ChStateDelta& a) { conveyor_truss->IntStateGatherAcceleration(off_a, a); conveyor_plate->IntStateGatherAcceleration(off_a + 6, a); } void ChConveyor::IntStateScatterAcceleration(const unsigned int off_a, const ChStateDelta& a) { conveyor_truss->IntStateScatterAcceleration(off_a, a); conveyor_plate->IntStateScatterAcceleration(off_a + 6, a); } void ChConveyor::IntStateGatherReactions(const unsigned int off_L, ChVectorDynamic<>& L) { internal_link->IntStateGatherReactions(off_L, L); } void ChConveyor::IntStateScatterReactions(const unsigned int off_L, const ChVectorDynamic<>& L) { internal_link->IntStateScatterReactions(off_L, L); } void ChConveyor::IntStateIncrement(const unsigned int off_x, // offset in x state vector ChState& x_new, // state vector, position part, incremented result const ChState& x, // state vector, initial position part const unsigned int off_v, // offset in v state vector const ChStateDelta& Dv // state vector, increment ) { conveyor_truss->IntStateIncrement(off_x, x_new, x, off_v, Dv); conveyor_plate->IntStateIncrement(off_x + 7, x_new, x, off_v + 6, Dv); } void ChConveyor::IntStateGetIncrement(const unsigned int off_x, // offset in x state vector const ChState& x_new, // state vector, position part, incremented result const ChState& x, // state vector, initial position part const unsigned int off_v, // offset in v state vector ChStateDelta& Dv // state vector, increment ) { conveyor_truss->IntStateGetIncrement(off_x, x_new, x, off_v, Dv); conveyor_plate->IntStateGetIncrement(off_x + 7, x_new, x, off_v + 6, Dv); } void ChConveyor::IntLoadResidual_F(const unsigned int off, // offset in R residual ChVectorDynamic<>& R, // result: the R residual, R += c*F const double c // a scaling factor ) { conveyor_truss->IntLoadResidual_F(off, R, c); conveyor_plate->IntLoadResidual_F(off + 6, R, c); } void ChConveyor::IntLoadResidual_Mv(const unsigned int off, // offset in R residual ChVectorDynamic<>& R, // result: the R residual, R += c*M*v const ChVectorDynamic<>& w, // the w vector const double c // a scaling factor ) { conveyor_truss->IntLoadResidual_Mv(off, R, w, c); conveyor_plate->IntLoadResidual_Mv(off + 6, R, w, c); } void ChConveyor::IntToDescriptor(const unsigned int off_v, const ChStateDelta& v, const ChVectorDynamic<>& R, const unsigned int off_L, const ChVectorDynamic<>& L, const ChVectorDynamic<>& Qc) { conveyor_truss->IntToDescriptor(off_v, v, R, off_L, L, Qc); conveyor_plate->IntToDescriptor(off_v + 6, v, R, off_L, L, Qc); internal_link->IntToDescriptor(off_v, v, R, off_L, L, Qc); } void ChConveyor::IntFromDescriptor(const unsigned int off_v, // offset in v ChStateDelta& v, const unsigned int off_L, // offset in L ChVectorDynamic<>& L) { conveyor_truss->IntFromDescriptor(off_v, v, off_L, L); conveyor_plate->IntFromDescriptor(off_v + 6, v, off_L, L); internal_link->IntFromDescriptor(off_v, v, off_L, L); } void ChConveyor::IntLoadResidual_CqL(const unsigned int off_L, ChVectorDynamic<>& R, const ChVectorDynamic<>& L, const double c) { internal_link->IntLoadResidual_CqL(off_L, R, L, c); } void ChConveyor::IntLoadConstraint_C(const unsigned int off, ChVectorDynamic<>& Qc, const double c, bool do_clamp, double recovery_clamp) { internal_link->IntLoadConstraint_C(off, Qc, c, do_clamp, recovery_clamp); } void ChConveyor::IntLoadConstraint_Ct(const unsigned int off, ChVectorDynamic<>& Qc, const double c) { internal_link->IntLoadConstraint_Ct(off, Qc, c); } // SOLVER INTERFACE void ChConveyor::InjectVariables(ChSystemDescriptor& mdescriptor) { conveyor_truss->InjectVariables(mdescriptor); conveyor_plate->InjectVariables(mdescriptor); } void ChConveyor::VariablesFbReset() { conveyor_truss->VariablesFbReset(); conveyor_plate->VariablesFbReset(); } void ChConveyor::VariablesFbLoadForces(double factor) { conveyor_truss->VariablesFbLoadForces(factor); conveyor_plate->VariablesFbLoadForces(factor); } void ChConveyor::VariablesFbIncrementMq() { conveyor_truss->VariablesFbIncrementMq(); conveyor_plate->VariablesFbIncrementMq(); } void ChConveyor::VariablesQbLoadSpeed() { conveyor_truss->VariablesFbIncrementMq(); conveyor_plate->VariablesQbLoadSpeed(); } void ChConveyor::VariablesQbSetSpeed(double step) { conveyor_truss->VariablesQbSetSpeed(step); conveyor_plate->VariablesQbSetSpeed(step); } void ChConveyor::VariablesQbIncrementPosition(double dt_step) { conveyor_truss->VariablesQbIncrementPosition(dt_step); conveyor_plate->VariablesQbIncrementPosition(dt_step); } void ChConveyor::InjectConstraints(ChSystemDescriptor& mdescriptor) { internal_link->InjectConstraints(mdescriptor); } void ChConveyor::ConstraintsBiReset() { internal_link->ConstraintsBiReset(); } void ChConveyor::ConstraintsBiLoad_C(double factor, double recovery_clamp, bool do_clamp) { internal_link->ConstraintsBiLoad_C(factor, recovery_clamp, do_clamp); } void ChConveyor::ConstraintsBiLoad_Ct(double factor) { internal_link->ConstraintsBiLoad_Ct(factor); } void ChConveyor::ConstraintsBiLoad_Qc(double factor) { internal_link->ConstraintsBiLoad_Qc(factor); } void ChConveyor::ConstraintsLoadJacobians() { internal_link->ConstraintsLoadJacobians(); } void ChConveyor::ConstraintsFetch_react(double factor) { internal_link->ConstraintsFetch_react(factor); } void ChConveyor::SetSystem(ChSystem* m_system) { system = m_system; conveyor_truss->SetSystem(m_system); conveyor_plate->SetSystem(m_system); internal_link->SetSystem(m_system); } void ChConveyor::Update(double mytime, bool update_assets) { // inherit parent class function ChPhysicsItem::Update(mytime, update_assets); conveyor_truss->Update(mytime, update_assets); if (conveyor_truss->GetBodyFixed()) { double largemass = 100000; conveyor_plate->SetMass(largemass); conveyor_plate->SetInertiaXX(ChVector<>(largemass, largemass, largemass)); conveyor_plate->SetInertiaXY(ChVector<>(0, 0, 0)); } else { conveyor_plate->SetMass(conveyor_truss->GetMass()); conveyor_plate->SetInertiaXX(conveyor_truss->GetInertiaXX()); conveyor_plate->SetInertiaXY(conveyor_truss->GetInertiaXY()); } // keep the plate always at the same position of the main reference conveyor_plate->SetCoord(conveyor_truss->GetCoord()); conveyor_plate->SetCoord_dt(conveyor_truss->GetCoord_dt()); // keep the plate always at the same speed of the main reference, plus the conveyor speed on X local axis conveyor_plate->SetPos_dt(conveyor_truss->GetPos_dt() + (ChVector<>(conveyor_speed, 0, 0) >> (*conveyor_truss))); conveyor_plate->Update(mytime, update_assets); std::static_pointer_cast<ChFunction_Ramp>(internal_link->GetMotion_X())->Set_ang(-conveyor_speed); // always zero pos. offset (trick): std::static_pointer_cast<ChFunction_Ramp>(internal_link->GetMotion_X())->Set_y0(+conveyor_speed * GetChTime()); internal_link->Update(mytime, update_assets); } void ChConveyor::SyncCollisionModels() { // inherit parent class ChPhysicsItem::SyncCollisionModels(); conveyor_truss->SyncCollisionModels(); conveyor_plate->SyncCollisionModels(); } void ChConveyor::AddCollisionModelsToSystem() { // inherit parent class ChPhysicsItem::AddCollisionModelsToSystem(); // conveyor_truss->AddCollisionModelsToSystem(); // conveyor_plate->AddCollisionModelsToSystem(); } void ChConveyor::RemoveCollisionModelsFromSystem() { // inherit parent class ChPhysicsItem::RemoveCollisionModelsFromSystem(); // conveyor_plate->RemoveCollisionModelsFromSystem(); // conveyor_truss->RemoveCollisionModelsFromSystem(); } // FILE I/O void ChConveyor::ArchiveOUT(ChArchiveOut& marchive) { // version number marchive.VersionWrite<ChConveyor>(); // serialize parent class ChPhysicsItem::ArchiveOUT(marchive); // serialize all member data: marchive << CHNVP(conveyor_speed); marchive << CHNVP(conveyor_truss); marchive << CHNVP(conveyor_plate); marchive << CHNVP(internal_link); } /// Method to allow de serialization of transient data from archives. void ChConveyor::ArchiveIN(ChArchiveIn& marchive) { // version number /*int version =*/ marchive.VersionRead<ChConveyor>(); // deserialize parent class ChPhysicsItem::ArchiveIN(marchive); // stream in all member data: marchive >> CHNVP(conveyor_speed); marchive >> CHNVP(conveyor_truss); marchive >> CHNVP(conveyor_plate); marchive >> CHNVP(internal_link); } } // end namespace chrono
39.263006
117
0.641664
[ "geometry", "object", "vector" ]
3ef2ea069842fc8f40fc7b053af05b8954e2a35b
4,485
cpp
C++
Data Structures and Coding Algorithm/12. OS Algorithms/CPP/Priority_Scheduling/preemptive.cpp
lakhan098/Technocrats-HacktoberFest
33968cf36747ec2342d53b8c38c2a48fc71be017
[ "MIT" ]
11
2021-10-01T15:39:40.000Z
2021-10-12T16:33:03.000Z
Data Structures and Coding Algorithm/12. OS Algorithms/CPP/Priority_Scheduling/preemptive.cpp
lakhan098/Technocrats-HacktoberFest
33968cf36747ec2342d53b8c38c2a48fc71be017
[ "MIT" ]
62
2021-10-01T14:40:32.000Z
2021-10-31T14:47:21.000Z
Data Structures and Coding Algorithm/12. OS Algorithms/CPP/Priority_Scheduling/preemptive.cpp
lakhan098/Technocrats-HacktoberFest
33968cf36747ec2342d53b8c38c2a48fc71be017
[ "MIT" ]
71
2021-10-01T14:42:03.000Z
2021-10-21T15:51:24.000Z
#include<bits/stdc++.h> using namespace std; struct process{ string name; int pid; int arrival_time; int burst_time; int priority; // priority of process int remaining_burst_time; int start_time = -1; int completion_time = -1; int turn_around_time = -1; int response_time = -1; int waiting_time = -1; process(string name, int pid, int arrival_time, int burst_time,int priority) { this->name = name; this->pid = pid; this->arrival_time = arrival_time; this->burst_time = burst_time; this->priority = priority; this->remaining_burst_time = burst_time; } }; bool Priority_comparator(process &p1, process &p2) { if(p1.arrival_time == p2.arrival_time) { if(p1.priority == p2.priority) return p1.pid < p2.pid; return p1.priority < p2.priority; } return p1.arrival_time < p2.arrival_time; } struct Priority_comp { constexpr bool operator()(process const& a,process const& b)const noexcept { if(a.priority == b.priority) return a.arrival_time > b.arrival_time; return a.priority > b.priority; } }; bool sortPID(process &p1, process &p2) { return p1.pid < p2.pid; } void Priority_scheduling(vector<process> &P) { int n = P.size(); priority_queue<process, vector<process>, Priority_comp>pq; vector<process> table; vector<string> gantt; int cur_time = P[0].arrival_time; pq.push(P[0]); int it=1; for(int i=0;i<cur_time;i++) gantt.push_back("idle"); while(!pq.empty()) { process cur_process = pq.top(); pq.pop(); if( cur_process.start_time == -1 ) cur_process.start_time = cur_time; cur_process.remaining_burst_time--; cur_time++; if( cur_process.remaining_burst_time != 0) pq.push(cur_process); else{ cur_process.completion_time = cur_time; cur_process.response_time = cur_process.start_time - cur_process.arrival_time; cur_process.turn_around_time = cur_process.completion_time - cur_process.arrival_time; cur_process.waiting_time = cur_process.turn_around_time - cur_process.burst_time; table.push_back(cur_process); } gantt.push_back(cur_process.name); while(it < n && P[it].arrival_time <= cur_time) { pq.push(P[it]); it++; } if(pq.empty() && it < n) { pq.push(P[it]); for(int i=0;i<P[it].arrival_time - cur_time; i++) gantt.push_back("idle"); cur_time = P[it].arrival_time; it++; } } float TAT = 0, WT = 0; cout<<"========== Priority Scheduling - II ==========\n\n"; cout<<"GANTT CHART\nTime Stamp | Process\n"; for(int i=0;i<gantt.size();) { string cur_pname = gantt[i]; cout<<i<<" - "; while(i<gantt.size() && gantt[i]==cur_pname) i++; cout<<i<<"\t | "<<cur_pname<<"\n"; } cout<<"\nPID\tProcess\tAT\tST\tBT\tCT\tRT\tTAT\tWT\n"; sort(table.begin(), table.end(),sortPID); for(auto it : table) { cout<<it.pid<<"\t"<<it.name<<"\t\t"<<it.arrival_time<<"\t"; cout<<it.start_time<<"\t"<<it.burst_time<<"\t"<<it.completion_time<<"\t"<<it.response_time<<"\t"; cout<<it.turn_around_time<<"\t"<<it.waiting_time<<"\t\t"<<"\n"; WT += it.waiting_time; TAT += it.turn_around_time; } cout<<"\n====================================\n"; cout<<"Avg. Waiting Time : "<<WT/n<<"\n"; cout<<"Avg. Turn Around Time Time : "<<TAT/n<<"\n"; cout<<"\n\n**\n"; cout<<"AT = Arrival Time\nST = Start Time\nCT = Completion Time\nRT = Response Time\n"; cout<<"TAT = Turn Around Time\nWT = Waiting Time\nBT = Burst Time\n\n"; } int main() { vector<process> P; ifstream fin; fin.open("Priority_Input.txt"); int temp_pid = 1; string data; while( getline(fin,data) ) { stringstream str(data); string name; int arrival_time; int burst_time; int priority; str>>name; str>>arrival_time; str>>burst_time; str>>priority; process cur(name,temp_pid,arrival_time,burst_time,priority); P.push_back(cur); temp_pid++; } sort(P.begin(), P.end(), Priority_comparator); Priority_scheduling(P); }
28.75
105
0.568562
[ "vector" ]
3ef76867f7c378d59e3dd787f237700e4c38a964
1,292
cpp
C++
chap4/ex4_11.cpp
ksvbka/pppuc
840962dd612ab4f2b2c638409089cd889c417c8f
[ "MIT" ]
2
2016-05-06T02:08:38.000Z
2016-05-10T02:19:05.000Z
chap4/ex4_11.cpp
ksvbka/pppuc
840962dd612ab4f2b2c638409089cd889c417c8f
[ "MIT" ]
null
null
null
chap4/ex4_11.cpp
ksvbka/pppuc
840962dd612ab4f2b2c638409089cd889c417c8f
[ "MIT" ]
1
2020-11-01T13:06:15.000Z
2020-11-01T13:06:15.000Z
/* Ex 4.11: Create a program to find all the prime numbers between 1 and 100. One way to do this is to write a function that will check if a number is prime (i.e., see if the number can be divided by a prime number smaller than itself) using a vector of primes in order (so that if the vector is called primes, primes[0]==2, primes[1]==3, primes[2]==5, etc.). Then write a loop that goes from 1 to 100, checks each number to see if it is a prime, and stores each prime found in a vector. Write another loop that lists the primes you found. You might check your result by comparing your vector of prime numbers with primes. Consider 2 the first prime. */ #include <iostream> #include <stdexcept> #include <vector> using namespace std; vector<int> primes{2}; /*Vector hold primes number, init with first prime is 2*/ bool Is_prime(int n){ for(auto prime : primes){ if(n % prime == 0) return false; } return true; } int main(int argc, char const *argv[]) { try { for(int i = 3; i < 100; ++i){ if(Is_prime(i)) primes.push_back(i); } for(auto prime : primes) cout << " " << prime; } catch (runtime_error &e) { cout << e.what() << '\n'; } catch (...){ cout << "exiting\n"; } }
30.761905
80
0.633127
[ "vector" ]
41015e5fff889dca334363d8262a339260235816
4,695
hpp
C++
pwiz/data/vendor_readers/Waters/SpectrumList_Waters.hpp
vagisha/pwiz
aa65186bf863cdebde3d15c293d137085365bead
[ "Apache-2.0" ]
null
null
null
pwiz/data/vendor_readers/Waters/SpectrumList_Waters.hpp
vagisha/pwiz
aa65186bf863cdebde3d15c293d137085365bead
[ "Apache-2.0" ]
null
null
null
pwiz/data/vendor_readers/Waters/SpectrumList_Waters.hpp
vagisha/pwiz
aa65186bf863cdebde3d15c293d137085365bead
[ "Apache-2.0" ]
null
null
null
// // $Id$ // // // Original author: Matt Chambers <matt.chambers .@. vanderbilt.edu> // // Copyright 2009 Vanderbilt University - Nashville, TN 37232 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "pwiz/utility/misc/Export.hpp" #include "pwiz/data/msdata/SpectrumListBase.hpp" #include "Reader_Waters_Detail.hpp" #include "pwiz/utility/misc/Container.hpp" #include "pwiz/utility/misc/String.hpp" #include "pwiz/utility/misc/Stream.hpp" #include "pwiz/data/msdata/Reader.hpp" #include "pwiz/analysis/spectrum_processing/SpectrumList_3D.hpp" #include <boost/thread.hpp> using boost::shared_ptr; namespace pwiz { namespace msdata { namespace detail { // // SpectrumList_Waters // class PWIZ_API_DECL SpectrumList_Waters : public SpectrumListIonMobilityBase { public: struct VendorOptions { pwiz::util::IntegerSet msLevelsToCentroid; }; virtual size_t size() const; virtual const SpectrumIdentity& spectrumIdentity(size_t index) const; virtual size_t find(const string& id) const; virtual SpectrumPtr spectrum(size_t index, bool getBinaryData) const; virtual SpectrumPtr spectrum(size_t index, DetailLevel detailLevel) const; // TODO: convert vendor-specific parameters to a single config struct, but all non-vendor wrappers are going to have to pass it along :( virtual SpectrumPtr spectrum(size_t index, bool getBinaryData, const pwiz::util::IntegerSet& msLevelsToCentroid) const; virtual SpectrumPtr spectrum(size_t index, DetailLevel detailLevel, const pwiz::util::IntegerSet& msLevelsToCentroid) const; virtual SpectrumPtr spectrum(size_t index, bool getBinaryData, double lockmassMzPosScans, double lockmassMzNegScans, double lockmassTolerance, const pwiz::util::IntegerSet& msLevelsToCentroid) const; virtual SpectrumPtr spectrum(size_t index, DetailLevel detailLevel, double lockmassMzPosScans, double lockmassMzNegScans, double lockmassTolerance, const pwiz::util::IntegerSet& msLevelsToCentroid) const; virtual pwiz::analysis::Spectrum3DPtr spectrum3d(double scanStartTime, const boost::icl::interval_set<double>& driftTimeRanges) const; /// returns true if any functions are SONAR-enabled virtual bool hasSonarFunctions() const; virtual pair<int, int> sonarMzToBinRange(double precursorMz, double tolerance) const; // If precursor mz is outside SONAR range, returns pair <-1,-1> virtual double sonarBinToPrecursorMz(int bin) const; // If bin is outside SONAR range, returns 0 virtual bool hasIonMobility() const; virtual bool hasCombinedIonMobility() const; virtual bool canConvertIonMobilityAndCCS() const; virtual double ionMobilityToCCS(double ionMobility, double mz, int charge) const; virtual double ccsToIonMobility(double ccs, double mz, int charge) const; #ifdef PWIZ_READER_WATERS SpectrumList_Waters(MSData& msd, RawDataPtr rawdata, const Reader::Config& config); private: MSData& msd_; RawDataPtr rawdata_; size_t size_; Reader::Config config_; struct IndexEntry : public SpectrumIdentity { int function; int process; int scan; int block; // block < 0 is not ion mobility }; mutable vector<IndexEntry> index_; mutable map<string, size_t> idToIndexMap_; mutable boost::container::flat_map<double, vector<pair<int, int> > > scanTimeToFunctionAndBlockMap_; void getCombinedSpectrumData(int function, int block, BinaryData<double>& mz, BinaryData<double>& intensity, BinaryData<double>& driftTimeOrSonarRangeLow, BinaryData<double>& sonarRangeHigh, bool doCentroid) const; void initializeCoefficients() const; double calibrate(const double &mz) const; mutable vector<double> calibrationCoefficients_; mutable vector<double> imsCalibratedMasses_; mutable vector<float> imsMasses_; mutable vector<int> massIndices_; mutable vector<float> imsIntensities_; mutable boost::mutex readMutex; void createIndex(); #endif // PWIZ_READER_WATERS }; } // detail } // msdata } // pwiz
39.788136
219
0.732694
[ "vector" ]
410717dee0f504eaf77a7fee4ecaeca1bb220629
9,495
cc
C++
content/browser/speech/speech_recognition_dispatcher_host.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
content/browser/speech/speech_recognition_dispatcher_host.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
content/browser/speech/speech_recognition_dispatcher_host.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/speech/speech_recognition_dispatcher_host.h" #include <memory> #include "base/bind.h" #include "base/command_line.h" #include "base/lazy_instance.h" #include "content/browser/browser_plugin/browser_plugin_guest.h" #include "content/browser/child_process_security_policy_impl.h" #include "content/browser/frame_host/frame_tree_node.h" #include "content/browser/frame_host/render_frame_host_manager.h" #include "content/browser/speech/speech_recognition_manager_impl.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/speech_recognition_manager_delegate.h" #include "content/public/browser/speech_recognition_session_config.h" #include "content/public/browser/speech_recognition_session_context.h" #include "content/public/common/content_switches.h" #include "mojo/public/cpp/bindings/strong_binding.h" namespace content { SpeechRecognitionDispatcherHost::SpeechRecognitionDispatcherHost( int render_process_id, int render_frame_id, scoped_refptr<net::URLRequestContextGetter> context_getter) : render_process_id_(render_process_id), render_frame_id_(render_frame_id), context_getter_(std::move(context_getter)), weak_factory_(this) { // Do not add any non-trivial initialization here, instead do it lazily when // required (e.g. see the method |SpeechRecognitionManager::GetInstance()|) or // add an Init() method. } // static void SpeechRecognitionDispatcherHost::Create( int render_process_id, int render_frame_id, scoped_refptr<net::URLRequestContextGetter> context_getter, mojom::SpeechRecognizerRequest request) { mojo::MakeStrongBinding( std::make_unique<SpeechRecognitionDispatcherHost>( render_process_id, render_frame_id, std::move(context_getter)), std::move(request)); } SpeechRecognitionDispatcherHost::~SpeechRecognitionDispatcherHost() {} base::WeakPtr<SpeechRecognitionDispatcherHost> SpeechRecognitionDispatcherHost::AsWeakPtr() { return weak_factory_.GetWeakPtr(); } // -------- mojom::SpeechRecognizer interface implementation ------------------ void SpeechRecognitionDispatcherHost::Start( mojom::StartSpeechRecognitionRequestParamsPtr params) { DCHECK_CURRENTLY_ON(BrowserThread::IO); // Check that the origin specified by the renderer process is one // that it is allowed to access. if (!params->origin.unique() && !ChildProcessSecurityPolicyImpl::GetInstance()->CanRequestURL( render_process_id_, params->origin.GetURL())) { LOG(ERROR) << "SRDH::OnStartRequest, disallowed origin: " << params->origin.Serialize(); return; } BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::BindOnce(&SpeechRecognitionDispatcherHost::StartRequestOnUI, AsWeakPtr(), render_process_id_, render_frame_id_, std::move(params))); } // static void SpeechRecognitionDispatcherHost::StartRequestOnUI( base::WeakPtr<SpeechRecognitionDispatcherHost> speech_recognition_dispatcher_host, int render_process_id, int render_frame_id, mojom::StartSpeechRecognitionRequestParamsPtr params) { DCHECK_CURRENTLY_ON(BrowserThread::UI); int embedder_render_process_id = 0; int embedder_render_frame_id = MSG_ROUTING_NONE; WebContentsImpl* web_contents = static_cast<WebContentsImpl*>(WebContentsImpl::FromRenderFrameHostID( render_process_id, render_frame_id)); if (!web_contents) { // The render frame id is renderer-provided. If it's invalid, don't crash. DLOG(ERROR) << "SRDH::OnStartRequest, invalid frame"; return; } // If the speech API request was from an inner WebContents or a guest, save // the context of the outer WebContents or the embedder since we will use it // to decide permission. WebContents* outer_web_contents = web_contents->GetOuterWebContents(); if (outer_web_contents) { RenderFrameHost* embedder_frame = nullptr; FrameTreeNode* embedder_frame_node = web_contents->GetMainFrame() ->frame_tree_node() ->render_manager() ->GetOuterDelegateNode(); if (embedder_frame_node) { embedder_frame = embedder_frame_node->current_frame_host(); } else { // The outer web contents is embedded using the browser plugin. Fall back // to a simple lookup of the main frame. TODO(avi): When the browser // plugin is retired, remove this code. embedder_frame = outer_web_contents->GetMainFrame(); } embedder_render_process_id = embedder_frame->GetProcess()->GetID(); DCHECK_NE(embedder_render_process_id, 0); embedder_render_frame_id = embedder_frame->GetRoutingID(); DCHECK_NE(embedder_render_frame_id, MSG_ROUTING_NONE); } bool filter_profanities = SpeechRecognitionManagerImpl::GetInstance() && SpeechRecognitionManagerImpl::GetInstance()->delegate() && SpeechRecognitionManagerImpl::GetInstance() ->delegate() ->FilterProfanities(embedder_render_process_id); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce(&SpeechRecognitionDispatcherHost::StartSessionOnIO, speech_recognition_dispatcher_host, std::move(params), embedder_render_process_id, embedder_render_frame_id, filter_profanities)); } void SpeechRecognitionDispatcherHost::StartSessionOnIO( mojom::StartSpeechRecognitionRequestParamsPtr params, int embedder_render_process_id, int embedder_render_frame_id, bool filter_profanities) { DCHECK_CURRENTLY_ON(BrowserThread::IO); SpeechRecognitionSessionContext context; context.security_origin = params->origin; context.render_process_id = render_process_id_; context.render_frame_id = render_frame_id_; context.embedder_render_process_id = embedder_render_process_id; context.embedder_render_frame_id = embedder_render_frame_id; auto session = std::make_unique<SpeechRecognitionSession>(std::move(params->client)); SpeechRecognitionSessionConfig config; config.language = params->language; config.max_hypotheses = params->max_hypotheses; config.origin = params->origin; config.initial_context = context; config.url_request_context_getter = context_getter_.get(); config.filter_profanities = filter_profanities; config.continuous = params->continuous; config.interim_results = params->interim_results; config.event_listener = session->AsWeakPtr(); for (mojom::SpeechRecognitionGrammarPtr& grammar_ptr : params->grammars) { config.grammars.push_back(*grammar_ptr); } int session_id = SpeechRecognitionManager::GetInstance()->CreateSession(config); DCHECK_NE(session_id, SpeechRecognitionManager::kSessionIDInvalid); session->SetSessionId(session_id); mojo::MakeStrongBinding(std::move(session), std::move(params->session_request)); SpeechRecognitionManager::GetInstance()->StartSession(session_id); } // ---------------------- SpeechRecognizerSession ----------------------------- SpeechRecognitionSession::SpeechRecognitionSession( mojom::SpeechRecognitionSessionClientPtrInfo client_ptr_info) : session_id_(SpeechRecognitionManager::kSessionIDInvalid), client_(std::move(client_ptr_info)), weak_factory_(this) {} SpeechRecognitionSession::~SpeechRecognitionSession() = default; base::WeakPtr<SpeechRecognitionSession> SpeechRecognitionSession::AsWeakPtr() { return weak_factory_.GetWeakPtr(); } void SpeechRecognitionSession::Abort() { SpeechRecognitionManager::GetInstance()->AbortSession(session_id_); } void SpeechRecognitionSession::StopCapture() { SpeechRecognitionManager::GetInstance()->StopAudioCaptureForSession( session_id_); } // -------- SpeechRecognitionEventListener interface implementation ----------- void SpeechRecognitionSession::OnRecognitionStart(int session_id) { client_->Started(); } void SpeechRecognitionSession::OnAudioStart(int session_id) { client_->AudioStarted(); } void SpeechRecognitionSession::OnSoundStart(int session_id) { client_->SoundStarted(); } void SpeechRecognitionSession::OnSoundEnd(int session_id) { client_->SoundEnded(); } void SpeechRecognitionSession::OnAudioEnd(int session_id) { client_->AudioEnded(); } void SpeechRecognitionSession::OnRecognitionEnd(int session_id) { client_->Ended(); } void SpeechRecognitionSession::OnRecognitionResults( int session_id, const SpeechRecognitionResults& results) { client_->ResultRetrieved(results); } void SpeechRecognitionSession::OnRecognitionError( int session_id, const SpeechRecognitionError& error) { client_->ErrorOccurred(error); } // The events below are currently not used by speech JS APIs implementation. void SpeechRecognitionSession::OnAudioLevelsChange(int session_id, float volume, float noise_volume) {} void SpeechRecognitionSession::OnEnvironmentEstimationComplete(int session_id) { } } // namespace content
37.089844
80
0.739863
[ "render" ]
410e2db81aa7b2cb002cd7f4e63489f643e483de
581
hpp
C++
epoch/ayla/include/ayla/serialization/glm_serializer.hpp
oprogramadorreal/vize
042c16f96d8790303563be6787200558e1ec00b2
[ "MIT" ]
47
2020-03-30T14:36:46.000Z
2022-03-06T07:44:54.000Z
epoch/ayla/include/ayla/serialization/glm_serializer.hpp
oprogramadorreal/vize
042c16f96d8790303563be6787200558e1ec00b2
[ "MIT" ]
null
null
null
epoch/ayla/include/ayla/serialization/glm_serializer.hpp
oprogramadorreal/vize
042c16f96d8790303563be6787200558e1ec00b2
[ "MIT" ]
8
2020-04-01T01:22:45.000Z
2022-01-02T13:06:09.000Z
#ifndef AYLA_GLM_SERIALIZER_HPP #define AYLA_GLM_SERIALIZER_HPP #include <glm/glm.hpp> namespace boost { namespace serialization { template <class Archive> void serialize(Archive &ar, glm::vec2& vector, const unsigned int version); template <class Archive> void serialize(Archive &ar, glm::vec3& vector, const unsigned int version); template <class Archive> void serialize(Archive &ar, glm::vec4& vector, const unsigned int version); template <class Archive> void serialize(Archive &ar, glm::mat4& matrix, const unsigned int version); } } #endif // AYLA_GLM_SERIALIZER_HPP
23.24
75
0.774527
[ "vector" ]
410f4016f865598dac5f8dc600ff9d7fd28e9c5b
1,687
cpp
C++
tests/src/testing_server.cpp
smooresni/grpc-dynamic-client
7be29f78bcc9535e3ba5bb8360885a4b1f02be00
[ "MIT" ]
1
2022-02-25T17:54:32.000Z
2022-02-25T17:54:32.000Z
tests/src/testing_server.cpp
smooresni/grpc-dynamic-client
7be29f78bcc9535e3ba5bb8360885a4b1f02be00
[ "MIT" ]
8
2022-02-15T18:49:18.000Z
2022-03-25T18:27:28.000Z
tests/src/testing_server.cpp
ni/grpc-json-client
7be29f78bcc9535e3ba5bb8360885a4b1f02be00
[ "MIT" ]
null
null
null
#include "testing_server.h" #include <memory> #include <string> #include <vector> #include "grpcpp/grpcpp.h" #include "grpcpp/ext/proto_server_reflection_plugin.h" using grpc::ChannelArguments; using grpc::ServerBuilder; using grpc::ServerBuilderOption; using grpc::ServerBuilderPlugin; using grpc::reflection::ProtoServerReflectionPlugin; using std::string; using std::vector; using std::unique_ptr; namespace ni { namespace grpc_json_client { class RemoveReflectionPlugin : public ServerBuilderOption { void UpdateArguments(ChannelArguments* args) override {} void UpdatePlugins(vector<unique_ptr<ServerBuilderPlugin>>* plugins) override { ProtoServerReflectionPlugin reflection_plugin; auto plugin = plugins->begin(); while (plugin < plugins->end()) { if (plugin->get()->name() == reflection_plugin.name()) { plugin = plugins->erase(plugin); } else { plugin++; } } } }; TestingServer::TestingServer(const string& address) : _address(address), _reflection_enabled(false) {} void TestingServer::EnableReflection() { _reflection_enabled = true; } void TestingServer::Start() { ServerBuilder builder; builder.AddListeningPort(_address, grpc::InsecureServerCredentials()); builder.RegisterService(&_service); if (!_reflection_enabled) { builder.SetOption(std::make_unique<RemoveReflectionPlugin>()); } _server = builder.BuildAndStart(); } void TestingServer::Wait() { _server->Wait(); } void TestingServer::Stop() { _server->Shutdown(); _server->Wait(); } } // namespace grpc_json_client } // namespace ni
24.808824
83
0.692353
[ "vector" ]
4110e06ffc146e68554cb3336abd269358f87a80
4,626
cpp
C++
src/primitives/transaction.cpp
moorecoin/MooreCoinMiningAlgorithm
fe6a153e1392f6e18110b1e69481aa5c3c8b4a1d
[ "MIT" ]
null
null
null
src/primitives/transaction.cpp
moorecoin/MooreCoinMiningAlgorithm
fe6a153e1392f6e18110b1e69481aa5c3c8b4a1d
[ "MIT" ]
null
null
null
src/primitives/transaction.cpp
moorecoin/MooreCoinMiningAlgorithm
fe6a153e1392f6e18110b1e69481aa5c3c8b4a1d
[ "MIT" ]
null
null
null
// copyright (c) 2009-2010 satoshi nakamoto // copyright (c) 2009-2014 the moorecoin core developers // distributed under the mit software license, see the accompanying // file copying or http://www.opensource.org/licenses/mit-license.php. #include "primitives/transaction.h" #include "hash.h" #include "tinyformat.h" #include "utilstrencodings.h" std::string coutpoint::tostring() const { return strprintf("coutpoint(%s, %u)", hash.tostring().substr(0,10), n); } ctxin::ctxin(coutpoint prevoutin, cscript scriptsigin, uint32_t nsequencein) { prevout = prevoutin; scriptsig = scriptsigin; nsequence = nsequencein; } ctxin::ctxin(uint256 hashprevtx, uint32_t nout, cscript scriptsigin, uint32_t nsequencein) { prevout = coutpoint(hashprevtx, nout); scriptsig = scriptsigin; nsequence = nsequencein; } std::string ctxin::tostring() const { std::string str; str += "ctxin("; str += prevout.tostring(); if (prevout.isnull()) str += strprintf(", coinbase %s", hexstr(scriptsig)); else str += strprintf(", scriptsig=%s", scriptsig.tostring().substr(0,24)); if (nsequence != std::numeric_limits<unsigned int>::max()) str += strprintf(", nsequence=%u", nsequence); str += ")"; return str; } ctxout::ctxout(const camount& nvaluein, cscript scriptpubkeyin) { nvalue = nvaluein; scriptpubkey = scriptpubkeyin; } uint256 ctxout::gethash() const { return serializehash(*this); } std::string ctxout::tostring() const { return strprintf("ctxout(nvalue=%d.%08d, scriptpubkey=%s)", nvalue / coin, nvalue % coin, scriptpubkey.tostring().substr(0,30)); } cmutabletransaction::cmutabletransaction() : nversion(ctransaction::current_version), nlocktime(0) {} cmutabletransaction::cmutabletransaction(const ctransaction& tx) : nversion(tx.nversion), vin(tx.vin), vout(tx.vout), nlocktime(tx.nlocktime) {} uint256 cmutabletransaction::gethash() const { return serializehash(*this); } void ctransaction::updatehash() const { *const_cast<uint256*>(&hash) = serializehash(*this); } ctransaction::ctransaction() : nversion(ctransaction::current_version), vin(), vout(), nlocktime(0) { } ctransaction::ctransaction(const cmutabletransaction &tx) : nversion(tx.nversion), vin(tx.vin), vout(tx.vout), nlocktime(tx.nlocktime) { updatehash(); } ctransaction& ctransaction::operator=(const ctransaction &tx) { *const_cast<int*>(&nversion) = tx.nversion; *const_cast<std::vector<ctxin>*>(&vin) = tx.vin; *const_cast<std::vector<ctxout>*>(&vout) = tx.vout; *const_cast<unsigned int*>(&nlocktime) = tx.nlocktime; *const_cast<uint256*>(&hash) = tx.hash; return *this; } camount ctransaction::getvalueout() const { camount nvalueout = 0; for (std::vector<ctxout>::const_iterator it(vout.begin()); it != vout.end(); ++it) { nvalueout += it->nvalue; if (!moneyrange(it->nvalue) || !moneyrange(nvalueout)) throw std::runtime_error("ctransaction::getvalueout(): value out of range"); } return nvalueout; } double ctransaction::computepriority(double dpriorityinputs, unsigned int ntxsize) const { ntxsize = calculatemodifiedsize(ntxsize); if (ntxsize == 0) return 0.0; return dpriorityinputs / ntxsize; } unsigned int ctransaction::calculatemodifiedsize(unsigned int ntxsize) const { // in order to avoid disincentivizing cleaning up the utxo set we don't count // the constant overhead for each txin and up to 110 bytes of scriptsig (which // is enough to cover a compressed pubkey p2sh redemption) for priority. // providing any more cleanup incentive than making additional inputs free would // risk encouraging people to create junk outputs to redeem later. if (ntxsize == 0) ntxsize = ::getserializesize(*this, ser_network, protocol_version); for (std::vector<ctxin>::const_iterator it(vin.begin()); it != vin.end(); ++it) { unsigned int offset = 41u + std::min(110u, (unsigned int)it->scriptsig.size()); if (ntxsize > offset) ntxsize -= offset; } return ntxsize; } std::string ctransaction::tostring() const { std::string str; str += strprintf("ctransaction(hash=%s, ver=%d, vin.size=%u, vout.size=%u, nlocktime=%u)\n", gethash().tostring().substr(0,10), nversion, vin.size(), vout.size(), nlocktime); for (unsigned int i = 0; i < vin.size(); i++) str += " " + vin[i].tostring() + "\n"; for (unsigned int i = 0; i < vout.size(); i++) str += " " + vout[i].tostring() + "\n"; return str; }
32.34965
144
0.670774
[ "vector" ]
4117051a01cc590937034ed51b58a1a7de7f166d
5,853
cpp
C++
client/gamelogic/CPopulationManager.cpp
norelock/Project-MP-1
31dbb5c74b29a47df4cf41280887a66794fdc5ff
[ "MIT" ]
1
2022-02-19T15:52:29.000Z
2022-02-19T15:52:29.000Z
client/gamelogic/CPopulationManager.cpp
cleoppa/norasa
6f8d697922dca2fcc42a5830a384e790c687833a
[ "MIT" ]
2
2020-11-08T08:12:41.000Z
2022-01-08T07:20:45.000Z
client/gamelogic/CPopulationManager.cpp
cleoppa/norasa
6f8d697922dca2fcc42a5830a384e790c687833a
[ "MIT" ]
3
2020-03-23T06:56:35.000Z
2021-06-06T02:30:06.000Z
#include "main.h" int pedModelIds[] = { 7, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35, 36, 37, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 57, 58, 59, 60, 61, 62, 66, 67, 68, 70, 71, 72, 73, 78, 79, 80, 81, 82, 83, 84, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 120, 121, 122, 123, 124, 125, 126, 127, 128, 132, 133, 134, 135, 136, 137, 142, 143, 144, 146, 147, 153, 154, 155, 156, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 170, 171, 173, 174, 175, 176, 177, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 200, 202, 203, 204, 206, 209, 210, 212, 213, 217, 220, 221, 222, 223, 227, 228, 229, 230, 234, 235, 236, 239, 240, 241, 242, 247, 248, 249, 250, 252, 253, 254, 255, 258, 259, 260, 261, 262, 9, 10, 11, 12, 13, 31, 38, 39, 40, 41, 53, 54, 55, 56, 63, 64, 69, 75, 76, 77, 85, 87, 88, 89, 90, 91, 92, 93, 129, 130, 131, 138, 139, 140, 141, 145, 148, 150, 151, 152, 157, 169, 172, 178, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 201, 205, 207, 211, 214, 215, 216, 218, 219, 224, 225, 226, 231, 232, 233, 237, 238, 243, 244, 245, 246, 251, 256, 257, 263 }; int vehModelIds[] = { 400, 401, 402, 404, 405, 410, 411, 412, 413, 414, 415, 418, 419, 420, 421, 422, 424, 426, 429, 436, 438, 439, 445, 451, 458, 461, 462, 463, 466, 467, 468, 471, 474, 475, 477, 478, 479, 480, 482, 489, 491, 492, 496, 500, 505, 506, 507, 516, 517, 518, 521, 522, 526, 527, 529, 533, 534, 535, 536, 540, 541, 542, 542, 543, 545, 546, 547, 549, 550, 551, 554, 555, 558, 559, 560, 561, 562, 565, 566, 567, 568, 575, 576, 579, 580, 581, 585, 586, 587, 589, 600, 602, 603 }; std::list<CPed*> CPopulationManager::m_pPeds; std::list<CVehicle*> CPopulationManager::m_pVehicles; //void(__cdecl* original_CPopulation__AddToPopulation)(float, float, float, float); void __cdecl CPopulation__AddToPopulation_Hook(float a1, float a2, float a3, float a4) { //printf("Game is trying to add a ped to population\n"); CPopulation::AddToPopulation(a1, a2, a3, a4); //return; } //CPed*(__cdecl* original_CPopulation__AddPed)(ePedType, int, CVector*, bool); CPed* __cdecl CPopulation__AddPed_Hook(ePedType pedType, int modelIndex, CVector *posn, bool unknown) { CPed* ped = CPopulation::AddPed(pedType, modelIndex, *posn, unknown); if (ped) { printf("The game added a ped to population\n"); printf("- type: %d | model: %d | bIsCop: %d\n", pedType, modelIndex, unknown); if (ped->m_pVehicle)printf("-- has vehicle\n"); int blip = CRadar::SetEntityBlip(eBlipType::BLIP_CHAR, CPools::GetPedRef(ped), 0, eBlipDisplay::BLIP_DISPLAY_BLIPONLY); CRadar::SetBlipSprite(blip, 0); CRadar::ChangeBlipScale(blip, 1); CRadar::ChangeBlipColour(blip, 0xFFFF00FF); } return ped; } CPed*(__cdecl* original_CPopulation__AddPedInCar)(CVehicle*, bool, int, int, bool, bool); CPed* __cdecl CPopulation__AddPedInCar_Hook(CVehicle *vehicle, bool driver, int a3, int seatNumber, bool male, bool criminal) { /*CPed* ped = original_CPopulation__AddPedInCar(vehicle, driver, a3, seatNumber, male, criminal); if (ped) { printf("The game added a ped to population\n"); printf("- type: %d | model: %d | unk: %d\n", pedType, modelIndex, unknown); if (ped->m_pVehicle)printf("-- has vehicle\n"); }*/ int v6 = 0; CPed* ped = nullptr; CVector pos = vehicle->GetPosition(); int driverModel = CPopulation::FindSpecificDriverModelForCar_ToUse(vehicle->m_nModelIndex); int pedType = 0; if (!driver || driverModel < 0 || CStreaming::ms_aInfoForModel[driverModel].m_nLoadState != 1) { switch (vehicle->m_nModelIndex) { case 407u: pedType = 19; driverModel = CStreaming::GetDefaultFiremanModel(); goto LABEL_23; case 416u: pedType = 18; driverModel = CStreaming::GetDefaultMedicModel(); goto LABEL_23; case 427u: pedType = 6; driverModel = 2; goto LABEL_28; case 430u: case 497u: case 596u: case 597u: case 598u: case 599u: pedType = 6; driverModel = 0; goto LABEL_28; case 432u: case 433u: pedType = 6; driverModel = 5; goto LABEL_28; case 490u: pedType = 6; driverModel = 4; goto LABEL_28; case 523u: pedType = 6; driverModel = 1; goto LABEL_28; case 570u: driverModel = CPopulation::ChooseCivilianOccupation(0, 0, -1, -1, -1, 0, 1, 0, 0); if (driverModel == -1) { goto LABEL_21; } break; default: v6 = 0; if (a3 >= 14 && a3 <= 23) { pedType = a3 - 7; driverModel = 7; goto LABEL_23; } driverModel = CPopulation::ChooseCivilianOccupationForVehicle(male, vehicle); if (driverModel < 0) { LABEL_21: driverModel = 7; } break; } } pedType = CModelInfo::ms_modelInfoPtrs[driverModel][1].m_nRefCount; LABEL_23: if (driverModel < 0) { driverModel = 7; } if (!v6 && !CModelInfo::ms_modelInfoPtrs[driverModel]->m_pRwObject) { pedType = CModelInfo::ms_modelInfoPtrs[7][1].m_nRefCount; driverModel = 7; } LABEL_28: ped = CPopulation::AddPed((ePedType)pedType, driverModel, pos, 0); int door = 0; if (seatNumber >= 0) { door = CCarEnterExit::ComputeTargetDoorToEnterAsPassenger(vehicle, seatNumber); } else { door = 0; } CCarEnterExit::SetPedInCarDirect(ped, vehicle, door, driver); if (criminal) { CPopulation::UpdatePedCount(ped, 1); ped->m_nPedType = 20; CPopulation::UpdatePedCount(ped, 0); } return ped; } /* CPed* vehicle_CPopulation_AddPed(ePedType pedType, int modelIndex, CVector *posn, bool unknown) { }*/ //void(__cdecl* original_CPopulation__Update)(bool); void __cdecl CPopulation__Update_Hook(bool bGeneratePeds) { CPopulation::Update(bGeneratePeds); } //void(__cdecl* original_CCarCtrl__GenerateRandomCars)(); void __cdecl CCarCtrl__GenerateRandomCars_Hook() { CCarCtrl::GenerateRandomCars(); } void CPopulationManager::Init() { }
33.067797
169
0.663079
[ "model" ]
4117a3ffbd540443a4bb2d02ff3abba709809405
4,779
cpp
C++
tests/test_log.cpp
Fabio3rs/cppapiframework
14f1b1b42b77edbbf72d9d7f949ea6c9fcfa06a5
[ "MIT" ]
3
2021-12-27T14:38:53.000Z
2022-02-18T19:38:05.000Z
tests/test_log.cpp
Fabio3rs/cppapiframework
14f1b1b42b77edbbf72d9d7f949ea6c9fcfa06a5
[ "MIT" ]
null
null
null
tests/test_log.cpp
Fabio3rs/cppapiframework
14f1b1b42b77edbbf72d9d7f949ea6c9fcfa06a5
[ "MIT" ]
1
2021-12-27T18:20:32.000Z
2021-12-27T18:20:32.000Z
#include "../src/utils/CLog.hpp" #include "../src/utils/LogUtils.hpp" #include "../src/utils/ProcessHelper.hpp" #include "allocation_count.hpp" #include <chrono> #include <cstddef> #include <cstdlib> #include <filesystem> #include <fstream> #include <gtest/gtest.h> #include <ratio> #include <stdexcept> #include <string> #include <thread> #include <unistd.h> #include <utility> // NOLINTNEXTLINE(hicpp-special-member-functions) TEST(TestLog, Open) { auto &log = CLog::initSingleton("TestLog.log"); for (size_t i = 0; i < 100; i++) { EXPECT_FALSE(log.multiRegister("Teste log %0", i).empty()); } } // NOLINTNEXTLINE(hicpp-special-member-functions) TEST(TestLog, MultiRegisterStrEqual) { auto &log = CLog::initSingleton("TestLogStrEqual.log"); EXPECT_EQ(log.multiRegister("Teste log (%0) AAAAAAAAAAAA", 10), "Teste log (10) AAAAAAAAAAAA"); EXPECT_EQ(log.multiRegister("Teste log (%0) AAAAAAAAAAAA %1 | %2", 10, "Teste", 20), "Teste log (10) AAAAAAAAAAAA Teste | 20"); } // NOLINTNEXTLINE(hicpp-special-member-functions) TEST(TestLog, MultiRegisterAllocationLimit) { auto &log = CLog::initSingleton("TestLogAllocations.log"); std::this_thread::sleep_for(std::chrono::milliseconds(5)); AllocationCount::getAllocationCount() = 0; log.multiRegister("Teste log (%0) AAAAAAAAAAAA", 10); EXPECT_LE(AllocationCount::getAllocationCount(), 3); } static void somelogadd() { auto &log = CLog::initSingleton(); for (size_t i = 0; i < 50000; i++) { log.multiRegister("Teste log %0", i); } } // NOLINTNEXTLINE(hicpp-special-member-functions) TEST(TestLog, SaturateLog) { std::filesystem::remove("Saturate.log"); auto &log = CLog::initSingleton("Saturate.log"); for (size_t i = 0; i < 100; i++) { EXPECT_FALSE(log.multiRegister("Teste log %0", i).empty()); } size_t THREADS = 8; std::vector<std::thread> mthreads; mthreads.reserve(THREADS); for (size_t i = 0; i < THREADS; i++) { mthreads.emplace_back(std::thread(somelogadd)); } std::this_thread::sleep_for(std::chrono::milliseconds(1)); for (auto &thr : mthreads) { if (thr.joinable()) { thr.join(); } } log.FinishLog(); std::filesystem::remove("Saturate.log"); } // NOLINTNEXTLINE(hicpp-special-member-functions) TEST(TestLog, RedirectLog) { std::filesystem::remove("Redirection.log"); std::fstream redirectionlog("Redirection.log", std::ios::out | std::ios::trunc); if (!redirectionlog.is_open()) { throw std::runtime_error("Falha ao abrir o arquivo de log de testes"); } CLog::defaultcfg.filename.clear(); CLog::defaultcfg.stream = &redirectionlog; { auto &log = CLog::initSingleton(CLog::defaultcfg); for (size_t i = 0; i < 100; i++) { EXPECT_FALSE(log.multiRegister("Teste log %0", i).empty()); } log.FinishLog(); } redirectionlog.seekg(0, std::ios::end); EXPECT_GT(redirectionlog.tellg(), 2000); } static void logDebugInsertFork() { auto &log = CLog::log(); log.multiRegister("Before fork"); ProcessHelper phelper; auto forked = phelper.fork(); if (forked == 0) { log.multiRegister("Inside fork"); log.multiRegister("Will exit fork"); log.FinishLog(); exit(0); } else if (forked > 0) { std::this_thread::sleep_for(std::chrono::milliseconds(50)); log.multiRegister("Inside parent"); std::this_thread::sleep_for(std::chrono::milliseconds(50)); phelper.wait(forked, 0); } else { throw std::runtime_error("Error fork"); } log.multiRegister("After fork"); log.FinishLog(); } static auto findLineOnStream(std::fstream &toSearch, const std::string &val) -> bool { toSearch.seekg(0); std::string line; while (std::getline(toSearch, line)) { std::cout << line << std::endl; std::size_t posFound = line.find(val); if (posFound != std::string::npos) { return true; } } return false; } // NOLINTNEXTLINE(hicpp-special-member-functions) TEST(TestLog, ForkAndLog) { signal(SIGCHLD, SIG_IGN); std::fstream fsout("ForkAndLog.log", std::ios::trunc | std::ios::out | std::ios::in); CLog::defaultcfg.filename.clear(); CLog::defaultcfg.stream = &fsout; CLog::initSingleton(CLog::defaultcfg).multiRegister("Before test"); logDebugInsertFork(); fsout.flush(); EXPECT_TRUE(findLineOnStream(fsout, "Inside fork")); EXPECT_TRUE(findLineOnStream(fsout, "Will exit fork")); EXPECT_TRUE(findLineOnStream(fsout, "Inside fork")); }
27.465517
78
0.624817
[ "vector" ]
4118d77cd9f84dc661c4ddbf1b7e046a40d7cdae
11,062
cpp
C++
Editors/ActorEditor_old/UI_MainCommand.cpp
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:19.000Z
2022-03-26T17:00:19.000Z
net.ssa/Editors/ActorEditor_old/UI_MainCommand.cpp
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
null
null
null
net.ssa/Editors/ActorEditor_old/UI_MainCommand.cpp
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:21.000Z
2022-03-26T17:00:21.000Z
//--------------------------------------------------------------------------- #include "stdafx.h" #pragma hdrstop #include "topbar.h" #include "leftbar.h" #include "bottombar.h" #include "EditorPref.h" #include "main.h" #include "UI_Tools.h" #include "Library.h" #include "D3DUtils.h" #include "ImageEditor.h" #include "SceneClassList.h" #include "UI_Main.h" bool TUI::Command( int _Command, int p1, int p2 ){ if ((_Command!=COMMAND_INITIALIZE)&&!m_bReady) return false; bool bRes = true; switch( _Command ){ case COMMAND_INITIALIZE:{ Engine.Initialize (); // make interface fraBottomBar = xr_new<TfraBottomBar>((TComponent*)0); fraLeftBar = xr_new<TfraLeftBar>((TComponent*)0); fraTopBar = xr_new<TfraTopBar>((TComponent*)0); //---------------- if (UI.OnCreate()){ if (!Tools.OnCreate()){ bRes=false; break; } Lib.OnCreate (); Command (COMMAND_CLEAR); Command (COMMAND_RENDER_FOCUS); BeginEState (esEditScene); }else{ bRes = false; } }break; case COMMAND_DESTROY: Tools.OnDestroy (); Lib.OnDestroy (); UI.OnDestroy (); Engine.Destroy (); //---------------- xr_delete(fraLeftBar); xr_delete(fraTopBar); xr_delete(fraBottomBar); //---------------- break; case COMMAND_EVICT_TEXTURES: Device.Shader.Evict(); break; case COMMAND_QUIT: Quit(); break; case COMMAND_EXIT: bRes = Tools.IfModified(); break; case COMMAND_EDITOR_PREF: frmEditorPreferences->ShowModal(); break; case COMMAND_LOAD_MOTIONS:{ if (!Tools.CurrentObject()){ ELog.DlgMsg(mtError,"Scene empty. Load object first."); bRes=false; break; } AnsiString fn; if (Engine.FS.GetOpenName(Engine.FS.m_SMotions,fn)){ Tools.LoadMotions(fn.c_str()); fraLeftBar->UpdateMotionList(); } }break; case COMMAND_SAVE_MOTIONS:{ if (!Tools.CurrentObject()){ ELog.DlgMsg(mtError,"Scene empty. Load object first."); bRes=false; break; } AnsiString fn; if (Engine.FS.GetSaveName(Engine.FS.m_SMotions,fn)) Tools.SaveMotions(fn.c_str()); }break; case COMMAND_SAVE_BACKUP:{ AnsiString fn = AnsiString(Engine.FS.m_UserName)+"_backup.object"; Engine.FS.m_Objects.Update(fn); Command(COMMAND_SAVEAS,(int)fn.c_str()); }break; case COMMAND_SAVEAS:{ AnsiString fn = m_LastFileName; if (p1||Engine.FS.GetSaveName(Engine.FS.m_Objects,fn)){ if (p1) fn= (LPCSTR)p1; bRes=Command(COMMAND_SAVE, (DWORD)fn.c_str()); } if (bRes){ // unlock Engine.FS.UnlockFile(0,m_LastFileName); strcpy(m_LastFileName,fn.c_str()); Command(COMMAND_UPDATE_CAPTION); Engine.FS.LockFile(0,m_LastFileName); fraLeftBar->AppendRecentFile(m_LastFileName); } }break; case COMMAND_SAVE:{ AnsiString fn; if (p1) fn = (char*)p1; else fn = m_LastFileName; Engine.FS.UnlockFile(0,m_LastFileName); if (Tools.Save(fn.c_str())){ Command(COMMAND_UPDATE_CAPTION); fraLeftBar->AppendRecentFile(fn.c_str()); }else{ bRes=false; } Engine.FS.LockFile(0,m_LastFileName); }break; case COMMAND_IMPORT:{ AnsiString fn; if (Engine.FS.GetOpenName(Engine.FS.m_Import,fn)){ if (!Tools.IfModified()){ bRes=false; break; } Command( COMMAND_CLEAR ); if (!Tools.Load(fn.c_str())){ bRes=false; break; } strcpy(m_LastFileName,ExtractFileName(fn).c_str()); if (Command( COMMAND_SAVEAS )){ Engine.FS.MarkFile(fn.c_str(),true); fraLeftBar->UpdateMotionList(); }else{ Command( COMMAND_CLEAR ); } } }break; case COMMAND_EXPORT_SKELETON:{ AnsiString fn; if (Engine.FS.GetSaveName(Engine.FS.m_GameMeshes,fn)) if (Tools.ExportSkeleton(fn.c_str())) ELog.DlgMsg(mtInformation,"Export complete."); else ELog.DlgMsg(mtError,"Export failed."); }break; case COMMAND_EXPORT_OBJECT:{ AnsiString fn; if (Engine.FS.GetSaveName(Engine.FS.m_GameMeshes,fn)) if (Tools.ExportObject(fn.c_str())) ELog.DlgMsg(mtInformation,"Export complete."); else ELog.DlgMsg(mtError,"Export failed."); }break; case COMMAND_LOAD:{ AnsiString fn; if (p1) fn = (char*)p1; else fn = m_LastFileName; if( p1 || Engine.FS.GetOpenName( Engine.FS.m_Objects, fn ) ){ if (!Tools.IfModified()){ bRes=false; break; } if ((0!=stricmp(fn.c_str(),m_LastFileName))&&Engine.FS.CheckLocking(0,fn.c_str(),false,true)){ bRes=false; break; } if ((0==stricmp(fn.c_str(),m_LastFileName))&&Engine.FS.CheckLocking(0,fn.c_str(),true,false)){ Engine.FS.UnlockFile(0,fn.c_str()); } Command( COMMAND_CLEAR ); if (!Tools.Load(fn.c_str())){ bRes=false; break; } strcpy(m_LastFileName,fn.c_str()); fraLeftBar->AppendRecentFile(m_LastFileName); fraLeftBar->UpdateMotionList(); Command(COMMAND_UPDATE_CAPTION); // lock Engine.FS.LockFile(0,m_LastFileName); } }break; case COMMAND_CLEAR: { if (!Tools.IfModified()) return false; // unlock Engine.FS.UnlockFile(0,m_LastFileName); m_LastFileName[0]=0; Device.m_Camera.Reset(); Tools.Clear(); Command(COMMAND_UPDATE_CAPTION); } break; case COMMAND_REFRESH_TEXTURES: Device.RefreshTextures(0); break; case COMMAND_CHECK_TEXTURES: TfrmImageLib::ImportTextures(); break; case COMMAND_IMAGE_EDITOR: TfrmImageLib::EditImageLib(AnsiString("Image Editor")); break; case COMMAND_ZOOM_EXTENTS: Tools.ZoomObject(); break; case COMMAND_RENDER_FOCUS: if (frmMain->Visible&&m_bReady) m_D3DWindow->SetFocus(); break; case COMMAND_UPDATE_CAPTION: frmMain->UpdateCaption(); break; case COMMAND_UPDATE_TOOLBAR: fraLeftBar->UpdateBar(); break; case COMMAND_RESET_ANIMATION: break; case COMMAND_MAKE_PREVIEW: Tools.MakePreview(); break; case COMMAND_PREVIEW_OBJ_PREF: Tools.SetPreviewObjectPrefs(); break; case COMMAND_SELECT_PREVIEW_OBJ: Tools.SelectPreviewObject(p1); break; case COMMAND_TOGGLE_SAFE_RECT: psDeviceFlags.set(rsDrawSafeRect,!psDeviceFlags.is(rsDrawSafeRect)); frmMain->paWindowResize(0); break; case COMMAND_TOGGLE_GRID: psDeviceFlags.set(rsDrawGrid,!psDeviceFlags.is(rsDrawGrid)); break; case COMMAND_UPDATE_GRID: DU::UpdateGrid(frmEditorPreferences->seGridNumberOfCells->Value,frmEditorPreferences->seGridSquareSize->Value); OutGridSize(); break; case COMMAND_GRID_NUMBER_OF_SLOTS: if (p1) frmEditorPreferences->seGridNumberOfCells->Value += frmEditorPreferences->seGridNumberOfCells->Increment; else frmEditorPreferences->seGridNumberOfCells->Value -= frmEditorPreferences->seGridNumberOfCells->Increment; Command(COMMAND_UPDATE_GRID); break; case COMMAND_GRID_SLOT_SIZE:{ float step = frmEditorPreferences->seGridSquareSize->Increment; float val = frmEditorPreferences->seGridSquareSize->Value; if (p1){ if (val<1) step/=10.f; frmEditorPreferences->seGridSquareSize->Value += step; }else{ if (fsimilar(val,1.f)||(val<1)) step/=10.f; frmEditorPreferences->seGridSquareSize->Value -= step; } Command(COMMAND_UPDATE_GRID); }break; case COMMAND_CHECK_MODIFIED: bRes = Tools.IsModified(); break; case COMMAND_CHANGE_ACTION: Tools.ChangeAction(EAction(p1)); break; case COMMAND_CHANGE_AXIS: fraTopBar->ChangeAxis(p1); break; case COMMAND_UNDO: case COMMAND_REDO: // fake break; case COMMAND_LOAD_FIRSTRECENT: if (fraLeftBar->FirstRecentFile()){ bRes = Command(COMMAND_LOAD,(int)fraLeftBar->FirstRecentFile()); } break; default: ELog.DlgMsg( mtError, "Warning: Undefined command: %04d", _Command ); bRes = false; } RedrawScene(); return bRes; } void __fastcall TUI::ApplyShortCut(WORD Key, TShiftState Shift) { VERIFY(m_bReady); if (Shift.Contains(ssCtrl)){ if (Key=='S') Command(COMMAND_SAVE); else if (Key=='N') Command(COMMAND_CLEAR); else if (Key=='O') Command(COMMAND_LOAD); else if (Key=='R') Command(COMMAND_LOAD_FIRSTRECENT); else if (Key=='G') Command(COMMAND_TOGGLE_GRID); else if (Key=='F') Command(COMMAND_TOGGLE_SAFE_RECT); }else{ if (Shift.Contains(ssAlt)){ }else{ if (Key=='P') Command(COMMAND_EDITOR_PREF); else if (Key==VK_OEM_4) Command(COMMAND_GRID_SLOT_SIZE,false); else if (Key==VK_OEM_6) Command(COMMAND_GRID_SLOT_SIZE,true); else if (Key=='S') Command(COMMAND_CHANGE_ACTION, eaSelect); else if (Key=='A') Command(COMMAND_CHANGE_ACTION, eaAdd); else if (Key=='T') Command(COMMAND_CHANGE_ACTION, eaMove); else if (Key=='Y') Command(COMMAND_CHANGE_ACTION, eaRotate); else if (Key=='H') Command(COMMAND_CHANGE_ACTION, eaScale); else if (Key=='Z') Command(COMMAND_CHANGE_AXIS, eAxisX); else if (Key=='X') Command(COMMAND_CHANGE_AXIS, eAxisY); else if (Key=='C') Command(COMMAND_CHANGE_AXIS, eAxisZ); else if (Key=='V') Command(COMMAND_CHANGE_AXIS, eAxisZX); } } } //--------------------------------------------------------------------------- void __fastcall TUI::ApplyGlobalShortCut(WORD Key, TShiftState Shift) { VERIFY(m_bReady); if (Shift.Contains(ssCtrl)){ if (Key=='S') Command(COMMAND_SAVE); else if (Key=='O') Command(COMMAND_LOAD); else if (Key=='G') Command(COMMAND_TOGGLE_GRID); else if (Key=='F') Command(COMMAND_TOGGLE_SAFE_RECT); } if (Key==VK_OEM_3) Command(COMMAND_RENDER_FOCUS); } //--------------------------------------------------------------------------- char* TUI::GetCaption() { VERIFY(m_bReady); return GetEditFileName()[0]?GetEditFileName():"noname"; } char* TUI::GetTitle() { VERIFY(m_bReady); return "Actor Editor"; } LPSTR GetNameByClassID(EObjClass cls_id){ return 0; }
31.971098
119
0.585789
[ "object" ]
411d89b5bf617ff71130020f82a1f3293caf7e81
918
cpp
C++
src/sd_detector.cpp
Sakushun63/sd_raspi_b2021
6eba60523caf4b27b18a94986082184282a120f4
[ "MIT" ]
null
null
null
src/sd_detector.cpp
Sakushun63/sd_raspi_b2021
6eba60523caf4b27b18a94986082184282a120f4
[ "MIT" ]
null
null
null
src/sd_detector.cpp
Sakushun63/sd_raspi_b2021
6eba60523caf4b27b18a94986082184282a120f4
[ "MIT" ]
null
null
null
#include <iostream> #include <unistd.h> #include <ros/ros.h> #include <darknet_ros_msgs/ObjectCount.h> // cunter #include <std_msgs/Int8.h> // velocity using namespace std; darknet_ros_msgs::ObjectCount msg_include_count; //int msg_include_count; const int loop_rate = 10; void detectorCallback(const darknet_ros_msgs::ObjectCount& Objectmsg) { ROS_INFO("Object Detecting!!!%d", Objectmsg.count); msg_include_count = Objectmsg; } int main(int argc, char** argv) { ros::init(argc, argv, "detector"); ros::NodeHandle nh; ros::Subscriber sub = nh.subscribe("darknet_ros/found_object", 10, detectorCallback); //ros::Publisher pub = nh.advertise<std_msgs::Int8>("/detectOrNot", 10); ros::Publisher pub = nh.advertise<darknet_ros_msgs::ObjectCount>("/detectOrNot", 10); ros::Rate r(loop_rate); while (ros::ok()) { pub.publish(msg_include_count); ros::spinOnce(); r.sleep(); } return 0; }
24.157895
87
0.718954
[ "object" ]
411e3adc95383b87fcdf140e216c70f551d01157
2,250
cpp
C++
Kattis/proteins.cpp
hardik0899/Competitive_Programming
199039ad7a26a5f48152fe231a9ca5ac8685a707
[ "MIT" ]
1
2020-10-16T18:14:30.000Z
2020-10-16T18:14:30.000Z
Kattis/proteins.cpp
hardik0899/Competitive_Programming
199039ad7a26a5f48152fe231a9ca5ac8685a707
[ "MIT" ]
null
null
null
Kattis/proteins.cpp
hardik0899/Competitive_Programming
199039ad7a26a5f48152fe231a9ca5ac8685a707
[ "MIT" ]
1
2021-01-06T04:45:38.000Z
2021-01-06T04:45:38.000Z
#define __USE_MINGW_ANSI_STDIO 0 #include <iostream> #include <iomanip> #include <stdio.h> #include <stdlib.h> #include <vector> #include <algorithm> #include <queue> #include <map> #include <unordered_map> #include <set> #include <unordered_set> #include <stack> #include <deque> #include <string.h> #include <sstream> #include <bitset> #include <math.h> #include <assert.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; template <class T> using ordered_set = __gnu_pbds::tree<T, __gnu_pbds::null_type, less<T>, __gnu_pbds::rb_tree_tag, __gnu_pbds::tree_order_statistics_node_update>; template <class T> using ordered_multiset = __gnu_pbds::tree<T, __gnu_pbds::null_type, less_equal<T>, __gnu_pbds::rb_tree_tag, __gnu_pbds::tree_order_statistics_node_update>; #define PI atan2(0, -1) #define epsilon 0.000000001 #define INF 5000000000000000000 #define MOD 1000000007 #define mp make_pair #define pb push_back #define f first #define s second #define lb lower_bound #define ub upper_bound int N, L, dp [1010][2010]; string s; int main(){ //freopen("sort.in", "r", stdin); freopen("sort.out", "w", stdout); ios_base::sync_with_stdio(0); cin.tie(0); cout << fixed << setprecision(10); cin >> N >> s; L = s.length(); s.append("XXX"); for(int j = 0; j <= 2*L; j++){ for(int i = L-1; i > -1; i--){ dp[i][j] = dp[i+3][j]+(s.compare(i, 3, "ATG") == 0); if(j == 0) continue; dp[i][j] = max(dp[i][j], dp[i+2][j-1]+(s.compare(i, 2, "AT") == 0 || s.compare(i, 2, "AG") == 0 || s.compare(i, 2, "TG") == 0)); if(j == 1) continue; dp[i][j] = max(dp[i][j], dp[i+1][j-2]+(s.compare(i, 1, "A") == 0 || s.compare(i, 1, "T") == 0 || s.compare(i, 1, "G") == 0)); if(j == 2) continue; dp[i][j] = max(dp[i][j], dp[i][j-3]+1); } if(dp[0][j] >= N){ cout << j << '\n'; return 0; } } cout << min(min((N-dp[0][2*L])*3+2*L, (N-dp[0][2*L-1])*3+2*L-1), (N-dp[0][2*L-2])*3+2*L-2) << '\n'; return 0; } /****************************** Kateba ii dake no hanashi darou Success is only a victory away - No Game No Life Opening ******************************/
31.25
155
0.581778
[ "vector" ]
4120df1812b4e37ae51a565fe7a3103b3ee3e6e6
6,048
cc
C++
packager/file/local_file.cc
koln67/shaka-packager
5b9fd409a5de502e8af2e46ee12840bd2226874d
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1,288
2016-05-25T01:20:31.000Z
2022-03-02T23:56:56.000Z
packager/file/local_file.cc
koln67/shaka-packager
5b9fd409a5de502e8af2e46ee12840bd2226874d
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
894
2016-05-17T00:39:30.000Z
2022-03-02T18:46:21.000Z
packager/file/local_file.cc
koln67/shaka-packager
5b9fd409a5de502e8af2e46ee12840bd2226874d
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
400
2016-05-25T01:20:35.000Z
2022-03-03T02:12:00.000Z
// Copyright 2014 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd #include "packager/file/local_file.h" #include <stdio.h> #if defined(OS_WIN) #include <windows.h> #else #include <sys/stat.h> #endif // defined(OS_WIN) #include "packager/base/files/file_path.h" #include "packager/base/files/file_util.h" #include "packager/base/logging.h" namespace shaka { namespace { // Check if the directory |path| exists. Returns false if it does not exist or // it is not a directory. On non-Windows, |mode| will be filled with the file // permission bits on success. bool DirectoryExists(const base::FilePath& path, int* mode) { #if defined(OS_WIN) DWORD fileattr = GetFileAttributes(path.value().c_str()); if (fileattr != INVALID_FILE_ATTRIBUTES) return (fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0; #else struct stat info; if (stat(path.value().c_str(), &info) != 0) return false; if (S_ISDIR(info.st_mode)) { const int FILE_PERMISSION_MASK = S_IRWXU | S_IRWXG | S_IRWXO; if (mode) *mode = info.st_mode & FILE_PERMISSION_MASK; return true; } #endif return false; } // Create all the inexistent directories in the path. Returns true on success or // if the directory already exists. bool CreateDirectory(const base::FilePath& full_path) { std::vector<base::FilePath> subpaths; // Collect a list of all parent directories. base::FilePath last_path = full_path; subpaths.push_back(full_path); for (base::FilePath path = full_path.DirName(); path.value() != last_path.value(); path = path.DirName()) { subpaths.push_back(path); last_path = path; } // For non-Windows only. File permission for the new directories. // The file permission will be inherited from the last existing directory in // the file path. If none of the directory exists in the path, it is set to // 0755 by default. int mode = 0755; // Iterate through the parents and create the missing ones. for (auto i = subpaths.rbegin(); i != subpaths.rend(); ++i) { if (DirectoryExists(*i, &mode)) { continue; } #if defined(OS_WIN) if (::CreateDirectory(i->value().c_str(), nullptr)) { continue; } #else if (mkdir(i->value().c_str(), mode) == 0) { continue; } #endif // Mkdir failed, but it might have failed with EEXIST, or some other error // due to the the directory appearing out of thin air. This can occur if // two processes are trying to create the same file system tree at the same // time. Check to see if it exists and make sure it is a directory. const auto saved_error_code = ::logging::GetLastSystemErrorCode(); if (!DirectoryExists(*i, nullptr)) { LOG(ERROR) << "Failed to create directory " << i->value().c_str() << " ErrorCode " << saved_error_code; return false; } } return true; } } // namespace // Always open files in binary mode. const char kAdditionalFileMode[] = "b"; LocalFile::LocalFile(const char* file_name, const char* mode) : File(file_name), file_mode_(mode), internal_file_(NULL) { if (file_mode_.find(kAdditionalFileMode) == std::string::npos) file_mode_ += kAdditionalFileMode; } bool LocalFile::Close() { bool result = true; if (internal_file_) { result = base::CloseFile(internal_file_); internal_file_ = NULL; } delete this; return result; } int64_t LocalFile::Read(void* buffer, uint64_t length) { DCHECK(buffer != NULL); DCHECK(internal_file_ != NULL); size_t bytes_read = fread(buffer, sizeof(char), length, internal_file_); VLOG(2) << "Read " << length << " return " << bytes_read << " error " << ferror(internal_file_); if (bytes_read == 0 && ferror(internal_file_) != 0) { return -1; } return bytes_read; } int64_t LocalFile::Write(const void* buffer, uint64_t length) { DCHECK(buffer != NULL); DCHECK(internal_file_ != NULL); size_t bytes_written = fwrite(buffer, sizeof(char), length, internal_file_); VLOG(2) << "Write " << length << " return " << bytes_written << " error " << ferror(internal_file_); if (bytes_written == 0 && ferror(internal_file_) != 0) { return -1; } return bytes_written; } int64_t LocalFile::Size() { DCHECK(internal_file_ != NULL); // Flush any buffered data, so we get the true file size. if (!Flush()) { LOG(ERROR) << "Cannot flush file."; return -1; } int64_t file_size; if (!base::GetFileSize(base::FilePath::FromUTF8Unsafe(file_name()), &file_size)) { LOG(ERROR) << "Cannot get file size."; return -1; } return file_size; } bool LocalFile::Flush() { DCHECK(internal_file_ != NULL); return ((fflush(internal_file_) == 0) && !ferror(internal_file_)); } bool LocalFile::Seek(uint64_t position) { #if defined(OS_WIN) return _fseeki64(internal_file_, static_cast<__int64>(position), SEEK_SET) == 0; #else return fseeko(internal_file_, position, SEEK_SET) >= 0; #endif // !defined(OS_WIN) } bool LocalFile::Tell(uint64_t* position) { #if defined(OS_WIN) __int64 offset = _ftelli64(internal_file_); #else off_t offset = ftello(internal_file_); #endif // !defined(OS_WIN) if (offset < 0) return false; *position = static_cast<uint64_t>(offset); return true; } LocalFile::~LocalFile() {} bool LocalFile::Open() { base::FilePath file_path(base::FilePath::FromUTF8Unsafe(file_name())); // Create upper level directories for write mode. if (file_mode_.find("w") != std::string::npos) { // The function returns true if the directories already exist. if (!shaka::CreateDirectory(file_path.DirName())) { return false; } } internal_file_ = base::OpenFile(file_path, file_mode_.c_str()); return (internal_file_ != NULL); } bool LocalFile::Delete(const char* file_name) { return base::DeleteFile(base::FilePath::FromUTF8Unsafe(file_name), false); } } // namespace shaka
29.647059
80
0.676753
[ "vector" ]
41229501a6ccab361246d406b918f195016f948d
2,097
cpp
C++
homeworks/task14.cpp
PowerfullChild/NBU
8fd1a26346c2b0509cf33b63965719242bc1d4cb
[ "MIT" ]
null
null
null
homeworks/task14.cpp
PowerfullChild/NBU
8fd1a26346c2b0509cf33b63965719242bc1d4cb
[ "MIT" ]
null
null
null
homeworks/task14.cpp
PowerfullChild/NBU
8fd1a26346c2b0509cf33b63965719242bc1d4cb
[ "MIT" ]
null
null
null
/* NEEDS IMPROVING*/ #include<iostream> #include<string> using namespace std; int get_length(int coordinates_of_c_y, int coordinates_of_b_y) { int length = coordinates_of_c_y - coordinates_of_b_y; return length; } int get_width(int coordinates_of_b_x, int coordinates_of_a_x) { int width = coordinates_of_b_x - coordinates_of_a_x; return width; } double calculate_volume(string type_of_the_shape) { double volume = 0; int coordinates_of_a_x = 0; int coordinates_of_a_y = 0; int coordinates_of_b_x = 0; int coordinates_of_b_y = 0; int coordinates_of_c_x = 0; int coordinates_of_c_y = 0; int coordinates_of_d_x = 0; int coordinates_of_d_y = 0; int height = 0; cout << "Height: " << endl; cin >> height; if (type_of_the_shape == "triangle") { cout << "Coordinates of point A: " << endl; cin >> coordinates_of_a_x; cin >> coordinates_of_a_y; cout << "Coordinates of point B: " << endl; cin >> coordinates_of_b_x; cin >> coordinates_of_b_y; cout << "Coordinates of point C: " << endl; cin >> coordinates_of_c_x; cin >> coordinates_of_c_y; volume = (get_length(coordinates_of_c_y, coordinates_of_b_y) * get_width(coordinates_of_b_x, coordinates_of_a_x) * height) / 2; } else { cout << "Coordinates of point A: " << endl; cin >> coordinates_of_a_x; cin >> coordinates_of_a_y; cout << "Coordinates of point B: " << endl; cin >> coordinates_of_b_x; cin >> coordinates_of_b_y; cout << "Coordinates of point C: " << endl; cin >> coordinates_of_c_x; cin >> coordinates_of_c_y; cout << "Coordinates of point D: " << endl; cin >> coordinates_of_d_x; cin >> coordinates_of_d_y; volume = get_length(coordinates_of_c_y, coordinates_of_b_y) * get_width(coordinates_of_b_x, coordinates_of_a_x) * height; } return volume; } int main() { string type_of_the_shape = ""; cout << "What is the shape of the prism triangle or square ? " << endl; cin >> type_of_the_shape; double volume = calculate_volume(type_of_the_shape); cout << "Volume: " << volume << endl; return 0; }
19.971429
73
0.691464
[ "shape" ]
4122a07b592b504f51d00a66c3b4f741e37c7646
5,057
cc
C++
graphite/src/factory.cc
centreon-lab/centreon-broker
b412470204eedc01422bbfd00bcc306dfb3d2ef5
[ "Apache-2.0" ]
40
2015-03-10T07:55:39.000Z
2021-06-11T10:13:56.000Z
graphite/src/factory.cc
centreon-lab/centreon-broker
b412470204eedc01422bbfd00bcc306dfb3d2ef5
[ "Apache-2.0" ]
297
2015-04-30T10:02:04.000Z
2022-03-09T13:31:54.000Z
graphite/src/factory.cc
centreon-lab/centreon-broker
b412470204eedc01422bbfd00bcc306dfb3d2ef5
[ "Apache-2.0" ]
29
2015-08-03T10:04:15.000Z
2021-11-25T12:21:00.000Z
/* ** Copyright 2011-2017 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. ** ** For more information : contact@centreon.com */ #include "com/centreon/broker/graphite/factory.hh" #include <cstring> #include <memory> #include "com/centreon/broker/config/parser.hh" #include "com/centreon/broker/graphite/connector.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::graphite; using namespace com::centreon::exceptions; /************************************** * * * Static Objects * * * **************************************/ /** * Find a parameter in configuration. * * @param[in] cfg Configuration object. * @param[in] key Property to get. * * @return Property value. */ static std::string find_param(config::endpoint const& cfg, std::string const& key) { std::map<std::string, std::string>::const_iterator it{cfg.params.find(key)}; if (cfg.params.end() == it) throw msg_fmt("graphite: no '{}' defined for endpoint '{}'", key, cfg.name); return it->second; } /** * Get a parameter in configuration, or return a default value. * * @param[in] cfg Configuration object. * @param[in] key Property to get. * @param[in] def The default value if nothing found. * * @return Property value. */ static std::string get_string_param(config::endpoint const& cfg, std::string const& key, std::string const& def) { std::map<std::string, std::string>::const_iterator it(cfg.params.find(key)); if (cfg.params.end() == it) return def; else return it->second; } /** * Get a parameter in configuration, or return a default value. * * @param[in] cfg Configuration object. * @param[in] key Property to get. * @param[in] def The default value if nothing found. * * @return Property value. */ static uint32_t get_uint_param(config::endpoint const& cfg, std::string const& key, uint32_t def) { std::map<std::string, std::string>::const_iterator it(cfg.params.find(key)); if (cfg.params.end() == it) return (def); else { try { return std::stoul(it->second); } catch (std::exception const& ex) { throw msg_fmt("graphite: '{}' must be numeric for endpoint '{}'", key, cfg.name); } } return 0; } /************************************** * * * Public Methods * * * **************************************/ /** * Check if a configuration match the storage layer. * * @param[in] cfg Endpoint configuration. * * @return true if the configuration matches the storage layer. */ bool factory::has_endpoint(config::endpoint& cfg, io::extension* ext) { if (ext) *ext = io::extension("GRAPHITE", false, false); bool is_gpdb{!strncasecmp(cfg.type.c_str(), "graphite", 9)}; if (is_gpdb) { cfg.params["cache"] = "yes"; cfg.cache_enabled = true; } return is_gpdb; } /** * Build a storage endpoint from a configuration. * * @param[in] cfg Endpoint configuration. * @param[out] is_acceptor Will be set to false. * @param[in] cache The persistent cache. * * @return Endpoint matching the given configuration. */ io::endpoint* factory::new_endpoint( config::endpoint& cfg, bool& is_acceptor, std::shared_ptr<persistent_cache> cache) const { std::string db_host(find_param(cfg, "db_host")); unsigned short db_port(get_uint_param(cfg, "db_port", 2003)); std::string db_user(get_string_param(cfg, "db_user", "")); std::string db_password(get_string_param(cfg, "db_password", "")); uint32_t queries_per_transaction( get_uint_param(cfg, "queries_per_transaction", 1)); std::string metric_naming( get_string_param(cfg, "metric_naming", "centreon.metrics.$METRICID$")); std::string status_naming( get_string_param(cfg, "status_naming", "centreon.statuses.$INDEXID$")); std::string escape_string(get_string_param(cfg, "escape_string", "_")); // Connector. std::unique_ptr<graphite::connector> c(new graphite::connector); c->connect_to(metric_naming, status_naming, escape_string, db_user, db_password, db_host, db_port, queries_per_transaction, cache); is_acceptor = false; return (c.release()); }
32.837662
80
0.617164
[ "object" ]
412da658837b1f6884199e48fb64dc1483d38778
39,082
cpp
C++
source/grid/setup_fixed_grid.cpp
jfbucas/PION
e0a66aa301e4d94d581ba4df078f1a3b82faab99
[ "BSD-3-Clause" ]
null
null
null
source/grid/setup_fixed_grid.cpp
jfbucas/PION
e0a66aa301e4d94d581ba4df078f1a3b82faab99
[ "BSD-3-Clause" ]
null
null
null
source/grid/setup_fixed_grid.cpp
jfbucas/PION
e0a66aa301e4d94d581ba4df078f1a3b82faab99
[ "BSD-3-Clause" ]
null
null
null
/// \file setup_fixed_grid.cpp /// /// \brief Class for setting up grids. /// /// \author Jonathan Mackey /// /// /// Modifications: /// - 2015.02.09 JM: Split sim_control class into a setup class and /// a derived class for running simulations. /// - 2017.08.24 JM: moved evolving_RT_sources functions to setup. /// - 2018.01.24 JM: worked on making SimPM non-global #include "defines/functionality_flags.h" #include "defines/testing_flags.h" #include "tools/reporting.h" #include "tools/command_line_interface.h" #include "tools/mem_manage.h" #include "microphysics/microphysics_base.h" #ifdef LEGACY_CODE #include "microphysics/MPv0.h" #include "microphysics/MPv1.h" #include "microphysics/MPv2.h" #include "microphysics/MPv4.h" #endif #ifndef EXCLUDE_HD_MODULE #include "microphysics/MPv9.h" #endif #include "microphysics/mp_only_cooling.h" #ifndef EXCLUDE_MPV3 #include "microphysics/MPv3.h" #endif #include "microphysics/MPv5.h" #include "microphysics/MPv6.h" #include "microphysics/MPv7.h" #include "microphysics/MPv8.h" #include "microphysics/MPv10.h" #ifdef CODE_EXT_HHE #include "future/mpv9_HHe.h" #endif #include "raytracing/raytracer_SC.h" #include "dataIO/dataio_base.h" #include "dataIO/dataio_text.h" #ifdef SILO #include "dataIO/dataio_silo.h" #endif // if SILO #ifdef FITS #include "dataIO/dataio_fits.h" #endif // if FITS #include "spatial_solvers/solver_eqn_hydro_adi.h" #include "spatial_solvers/solver_eqn_mhd_adi.h" #include "setup_fixed_grid.h" #include "grid/grid_base_class.h" #include "grid/uniform_grid.h" #include <iostream> #include <sstream> #include <fstream> #include <string> #include <sys/time.h> #include <time.h> #include <climits> using namespace std; // ################################################################## // ################################################################## setup_fixed_grid::setup_fixed_grid() { FVI_nheat = FVI_nion = 0; FVI_heating_srcs.clear(); FVI_ionising_srcs.clear(); FVI_need_column_densities_4dt = false; spatial_solver=0; dataio=0; textio=0; } // ################################################################## // ################################################################## setup_fixed_grid::~setup_fixed_grid() { #ifdef TESTING cout << "(setup_fixed_grid::Destructor) ..." <<"\n"; #endif if (MP) {delete MP; MP=0;} if (spatial_solver) {delete spatial_solver; spatial_solver=0;} #ifdef TESTING cout << "(setup_fixed_grid::Destructor) Done." <<"\n"; #endif } // ################################################################## // ################################################################## void setup_fixed_grid::setup_cell_extra_data( class SimParams &SimPM ///< pointer to simulation parameters ) { // // Cells can need extra data for ray-tracing optical depths, eta-values for the // H-correction or div(v) for some time-updates and/or viscosity corrections. // int hc_flag = 0, dv_flag=0, gp_flag=0; if (SimPM.artviscosity==AV_LAPIDUS || SimPM.eqntype==EQEUL_EINT) { // Need one var. for Div(v) dv_flag = 1; } if (SimPM.solverType==FLUX_RS_HLLD) { dv_flag = 1; // Need DivV for shock switch in HLLD. gp_flag = 1; } if (SimPM.artviscosity==AV_HCORRECTION || SimPM.artviscosity==AV_HCORR_FKJ98 || SimPM.eqntype==EQEUL_EINT) { // // need one var for each dimension here. For H-correction they // are for the eta values. For EQEUL_EINT we need von Neunamm-Richtmeyer // viscosity which needs storage for the diagonal Q-values along each axis. // hc_flag = SimPM.ndim; } CI.setup_extra_data(SimPM.RS, hc_flag, dv_flag, gp_flag); return; } // ################################################################## // ################################################################## int setup_fixed_grid::setup_grid( vector<class GridBaseClass *> &g, ///< grid pointers. class SimParams &SimPM ///< pointer to simulation parameters ) { cout <<"(pion ug) Setting up computational grid\n"; #ifdef TESTING cout <<"Init::setup_grid: \n"; #endif // TESTING class GridBaseClass **grid = &(g[0]); if (SimPM.ndim <1 || SimPM.ndim>3) rep.error("Only know 1D,2D,3D methods!",SimPM.ndim); // // Nbc is the depth of the boundary layer. // #ifdef TESTING cout <<"Setting number of boundary cells == spatial OOA: "; cout <<SimPM.spOOA<<"\n"; #endif // TESTING if (SimPM.spOOA==OA2) {SimPM.Nbc = 2; SimPM.Nbc_DD = 2;} else if (SimPM.spOOA==OA1) {SimPM.Nbc = 1; SimPM.Nbc_DD = 1;} else rep.error("Spatial order of accuracy unhandled by boundary conditions!",SimPM.spOOA); // Force Nbc=1 if using Lax-Friedrichs flux. if (SimPM.solverType==FLUX_LF) {SimPM.spOOA = SimPM.tmOOA = OA1; SimPM.Nbc=1; SimPM.Nbc_DD = 1;} // // May need to setup extra data in each cell for ray-tracing optical // depths and/or viscosity variables. // setup_cell_extra_data(SimPM); // // Set Cell dx in cell interface class, and also xmin. // double dx((SimPM.Xmax[XX]-SimPM.Xmin[XX])/SimPM.NG[XX]); CI.set_nlevels(dx,SimPM.grid_nlevels); // sets dx on all levels. CI.set_ndim(SimPM.ndim); CI.set_nvar(SimPM.nvar); CI.set_xmin(SimPM.Xmin); // // Now we can setup the grid: // #ifdef TESTING cout <<"(setup_fixed_grid::setup_grid) Setting up grid...\n"; #endif if (*grid) rep.error("Grid already set up!",*grid); if (SimPM.coord_sys==COORD_CRT) *grid = new UniformGrid (SimPM.ndim, SimPM.nvar, SimPM.eqntype, SimPM.Nbc, SimPM.Xmin, SimPM.Xmax, SimPM.NG, SimPM.Xmin, SimPM.Xmax, SimPM.Xmin, SimPM.Xmax); else if (SimPM.coord_sys==COORD_CYL) *grid = new uniform_grid_cyl (SimPM.ndim, SimPM.nvar, SimPM.eqntype, SimPM.Nbc, SimPM.Xmin, SimPM.Xmax, SimPM.NG, SimPM.Xmin, SimPM.Xmax, SimPM.Xmin, SimPM.Xmax); else if (SimPM.coord_sys==COORD_SPH) *grid = new uniform_grid_sph (SimPM.ndim, SimPM.nvar, SimPM.eqntype, SimPM.Nbc, SimPM.Xmin, SimPM.Xmax, SimPM.NG, SimPM.Xmin, SimPM.Xmax, SimPM.Xmin, SimPM.Xmax); else rep.error("Bad Geometry in setup_grid()",SimPM.coord_sys); if (*grid==0) rep.error("(setup_fixed_grid::setup_grid) Couldn't assign data!", *grid); #ifdef TESTING cout <<"(setup_fixed_grid::setup_grid) Done. &grid="<< grid; cout <<", and grid="<<*grid<<"\n"; cout <<"DX = "<<(*grid)->DX()<<"\n"; dp.grid = (*grid); cout <<"------------------------------------------------------\n\n"; #endif return(0); } // setup_grid() // ################################################################## // ################################################################## int setup_fixed_grid::setup_microphysics( class SimParams &SimPM ///< pointer to simulation parameters ) { //cout <<"------------------------------------------------------------\n"; //cout <<"----------------- MICROPHYSICS SETUP -----------------------\n"; //cout <<"------------------------------------------------------------\n"; cout <<"(pion) Setting up microphysics\n"; // // Setup Microphysics class, if needed. // First see if we want the only_cooling class (much simpler), and if // not then check for the one of the bigger microphysics classes. // if (SimPM.EP.cooling && !SimPM.EP.chemistry) { cout <<"\tRequested cooling but no chemistry... setting"; cout <<" up mp_only_cooling() class. \n"; cout <<"\tTimestep limit = "<<SimPM.EP.MP_timestep_limit<<"\n"; MP = new mp_only_cooling(SimPM.nvar,SimPM.ntracer,SimPM.tracers, &(SimPM.EP), &(SimPM.RS)); if (!MP) rep.error("mp_only_cooling() init",MP); } else if (SimPM.EP.chemistry) { // MP = 0; string mptype; mptype = SimPM.chem_code; bool have_set_MP=false; cout <<"setting up MP type: "<<mptype<<"\n"; #ifdef LEGACY_CODE if (mptype=="MPv0") { cout <<"\tsetting up MPv0 module\n"; if (have_set_MP) rep.error("MP already initialised",mptype); MP = new MPv0(SimPM.nvar, SimPM.ntracer, SimPM.chem_code, SimPM.tracers, &(SimPM.EP), &(SimPM.RS)); if (SimPM.EP.MP_timestep_limit <0 || SimPM.EP.MP_timestep_limit >5) rep.error("BAD dt LIMIT",SimPM.EP.MP_timestep_limit); have_set_MP=true; } if (mptype=="MPv1") { cout <<"\tsetting up MPv1 microphysics module\n"; if (have_set_MP) rep.error("MP already initialised",mptype); MP = new MPv1(SimPM.nvar, SimPM.ntracer, SimPM.tracers, &(SimPM.EP), &(SimPM.RS)); cout <<"\t**---** WARNING, THIS MODULE HAS BEEN SUPERSEDED BY MPv4. **--**\n"; have_set_MP=true; } if (mptype=="MPv2") { cout <<"\tsetting up MPv2 module\n"; if (have_set_MP) rep.error("MP already initialised",mptype); MP = new MPv2(SimPM.ndim, SimPM.coord_sys, SimPM.nvar, SimPM.ntracer, SimPM.tracers, &(SimPM.EP), &(SimPM.RS)); SimPM.EP.MP_timestep_limit = 1; have_set_MP=true; } if (mptype=="MPv4") { cout <<"\tsetting up MPv4 module\n"; #if MPV4_DTLIMIT>=5 && MPV4_DTLIMIT<=12 //cout <<"\t******* N.B. dt05-12 Timestep limiting is enforced by #def"; //cout <<" DTLIMIT="<<MPV4_DTLIMIT<<". **\n"; SimPM.EP.MP_timestep_limit =5; #elif MPV4_DTLIMIT>=0 && MPV4_DTLIMIT<=4 //cout <<"\t******* N.B. dt00-04 Timestep limiting is enforced by #def"; //cout <<" MPV4_DTLIMIT="<<MPV4_DTLIMIT<<". **\n"; SimPM.EP.MP_timestep_limit =4; #else #error "No timestep-limiting is defined in source/defines/functionality_flags.h" #endif if (have_set_MP) rep.error("MP already initialised",mptype); MP = new MPv4(SimPM.ndim, SimPM.coord_sys, SimPM.nvar, SimPM.ntracer, SimPM.tracers, &(SimPM.EP), &(SimPM.RS), SimPM.gamma); have_set_MP=true; } if (mptype=="MPv8") { cout <<"\tsetting up MPv8 module\n"; SimPM.EP.MP_timestep_limit = 1; if (have_set_MP) rep.error("MP already initialised",mptype); MP = new MPv8(SimPM.ndim, SimPM.coord_sys, SimPM.nvar, SimPM.ntracer, SimPM.tracers, &(SimPM.EP), &(SimPM.RS), SimPM.gamma); have_set_MP=true; } #endif // LEGACY_CODE #ifndef EXCLUDE_HD_MODULE if (mptype=="MPv9") { cout <<"\tsetting up microphysics_lowz module\n"; if (have_set_MP) rep.error("MP already initialised",mptype); MP = new microphysics_lowz(SimPM.nvar, SimPM.ntracer, SimPM.tracers, &(SimPM.EP), &(SimPM.RS)); have_set_MP=true; } #endif // exclude Harpreet's module if (mptype=="MPv3" || mptype=="MPv3__") { cout <<"\tsetting up MPv3 module\n"; #if MPV3_DTLIMIT>=0 && MPV4_DTLIMIT<=12 //cout <<"\t******* N.B. Timestep limiting is enforced by #def"; //cout <<" MPV3_DTLIMIT="<<MPV3_DTLIMIT<<". **\n"; SimPM.EP.MP_timestep_limit = 1; if (have_set_MP) rep.error("MP already initialised",mptype); #else #error "No timestep-limiting is defined in source/defines/functionality_flags.h" #endif MP = new MPv3(SimPM.ndim, SimPM.coord_sys, SimPM.nvar, SimPM.ntracer, SimPM.tracers, &(SimPM.EP), &(SimPM.RS), SimPM.gamma); //if (SimPM.EP.MP_timestep_limit != 1) // rep.error("BAD dt LIMIT",SimPM.EP.MP_timestep_limit); have_set_MP=true; } if (mptype=="MPv10" || mptype=="MPv10__") { cout <<"\tsetting up MPv10 module\n"; #if MPV3_DTLIMIT>=0 && MPV4_DTLIMIT<=12 //cout <<"\t******* N.B. Timestep limiting is enforced by #def"; //cout <<" MPV10_DTLIMIT="<<MPV3_DTLIMIT<<". **\n"; SimPM.EP.MP_timestep_limit = 1; if (have_set_MP) rep.error("MP already initialised",mptype); #else #error "No timestep-limiting is defined in source/defines/functionality_flags.h" #endif MP = new MPv10(SimPM.ndim, SimPM.coord_sys, SimPM.nvar, SimPM.ntracer, SimPM.tracers, &(SimPM.EP), &(SimPM.RS), SimPM.gamma); //if (SimPM.EP.MP_timestep_limit != 1) // rep.error("BAD dt LIMIT",SimPM.EP.MP_timestep_limit); have_set_MP=true; } if (mptype=="MPv5" || mptype=="MPv5__") { cout <<"\tsetting up MPv5 module\n"; SimPM.EP.MP_timestep_limit = 1; if (have_set_MP) rep.error("MP already initialised",mptype); MP = new MPv5(SimPM.ndim, SimPM.coord_sys, SimPM.nvar, SimPM.ntracer, SimPM.tracers, &(SimPM.EP), &(SimPM.RS), SimPM.gamma); have_set_MP=true; } if (mptype=="MPv6" || mptype=="MPv6__") { cout <<"\tsetting up MPv6 module\n"; SimPM.EP.MP_timestep_limit = 1; if (have_set_MP) rep.error("MP already initialised",mptype); MP = new MPv6(SimPM.ndim, SimPM.coord_sys, SimPM.nvar, SimPM.ntracer, SimPM.tracers, &(SimPM.EP), &(SimPM.RS), SimPM.gamma); have_set_MP=true; } if (mptype=="MPv7" || mptype=="MPv7__") { cout <<"\tsetting up MPv7 module\n"; SimPM.EP.MP_timestep_limit = 1; if (have_set_MP) rep.error("MP already initialised",mptype); MP = new MPv7(SimPM.ndim, SimPM.coord_sys, SimPM.nvar, SimPM.ntracer, SimPM.tracers, &(SimPM.EP), &(SimPM.RS), SimPM.gamma); have_set_MP=true; } #ifdef CODE_EXT_HHE if (mptype=="MPv10") { cout <<"\tsetting up MPv10 module\n"; SimPM.EP.MP_timestep_limit = 1; if (have_set_MP) rep.error("MP already initialised",mptype); MP = new mpv9_HHe(SimPM.nvar, SimPM.ntracer, SimPM.tracers, &(SimPM.EP), SimPM.gamma); have_set_MP=true; } #endif if (!MP) rep.error("microphysics init",MP); if (!have_set_MP) rep.error("have_set_MP",have_set_MP); } else { cout <<"\tno microphysics.\n"; MP=0; } // // If we have a multifrequency ionising source, we can set its properties here. // We can only have one of these, so safe to just loop through... // int err=0; double data[MAX_TAU]; // temp var not used for (int isrc=0; isrc<SimPM.RS.Nsources; isrc++) { if (SimPM.RS.sources[isrc].type==RT_SRC_SINGLE && SimPM.RS.sources[isrc].effect==RT_EFFECT_MFION && MP!=0 && SimPM.RS.sources[isrc].EvoFile=="NONE" ) { err = MP->set_multifreq_source_properties(&SimPM.RS.sources[isrc],data); } } if (err) rep.error("Setting multifreq source properties",err); //cout <<"------------------------------------------------------------\n"; //cout <<"----------------- MICROPHYSICS SETUP -----------------------\n"; //cout <<"------------------------------------------------------------\n"; return 0; } // ################################################################## // ################################################################## int setup_fixed_grid::setup_raytracing( class SimParams &SimPM, ///< pointer to simulation parameters class GridBaseClass *grid ///< pointer to grid ) { if (!SimPM.EP.raytracing) { return 0; } cout <<"(pion) Setting up raytracing on level\n"; if (!MP) rep.error("can't do raytracing without microphysics",MP); #ifdef RT_TESTING cout <<"\n------ RAYTRACER SETUP STARTING --------------\n"; #endif // // If the ionising source is at infinity then set up the simpler parallel // rays tracer. Otherwise the more complicated one is required. // bool parallel_rays=true; for (int isrc=0; isrc<SimPM.RS.Nsources; isrc++) if (!SimPM.RS.sources[isrc].at_infinity) parallel_rays=false; if (parallel_rays) { // // set up single source at infinity tracer, if appropriate // grid->RT = new raytracer_USC_infinity(grid, MP, SimPM.ndim, SimPM.coord_sys, SimPM.nvar, SimPM.ftr); if (!(grid->RT)) rep.error("init pllel-rays raytracer error",grid->RT); } else { // // set up regular tracer if simple one not already set up. // grid->RT = new raytracer_USC(grid, MP, SimPM.ndim, SimPM.coord_sys, SimPM.nvar, SimPM.ftr, SimPM.RS.Nsources); if (!(grid->RT)) rep.error("init raytracer error 2",grid->RT); } // // Now add the sources to the tracer. Note that both the implicit // and explicit integrators can still only handle a single ionising // source, so we do a check for this and bug out if there is more // than one. // int ion_count=0, uv_count=0, dif_count=0; for (int isrc=0; isrc<SimPM.RS.Nsources; isrc++) { // see if source is on the domain or not. Set flag accordingly. SimPM.RS.sources[isrc].ongrid = true; for (int d=0;d<SimPM.ndim;d++) { if (SimPM.RS.sources[isrc].pos[d]<SimPM.levels[0].Xmin[d] || SimPM.RS.sources[isrc].pos[d]>SimPM.levels[0].Xmax[d]) SimPM.RS.sources[isrc].ongrid = false; } // source types if (SimPM.RS.sources[isrc].type==RT_SRC_SINGLE) { // // single sources have a flux (if at infinity) or a luminosity (if point // sources. // int s = grid->RT->Add_Source(&(SimPM.RS.sources[isrc])); #ifdef RT_TESTING cout <<"Adding IONISING or UV single-source with id: "; cout << s <<"\n"; #endif if (SimPM.RS.sources[isrc].effect==RT_EFFECT_PION_MONO || SimPM.RS.sources[isrc].effect==RT_EFFECT_MFION) ion_count++; else uv_count++; } // if ionising source else { // note that diffuse radiation must be at infinity, and the strength is assumed to // be an intensity not a flux, so it is multiplied by a solid angle appropriate // to its location in order to get a flux. int s = grid->RT->Add_Source(&(SimPM.RS.sources[isrc])); #ifdef RT_TESTING cout <<"Adding DIFFUSE radiation source with id: "; cout << s <<"\n"; #endif uv_count++; dif_count++; } // if diffuse source } // loop over sources if (ion_count>1) { rep.error("Can only have one ionising source for currently implemented method",ion_count); } #ifdef RT_TESTING cout <<"Added "<<ion_count<<" ionising and "<<uv_count<<" non-ionising"; cout <<" radiation sources, of which "<<dif_count<<" are diffuse radiation.\n"; #endif grid->RT->Print_SourceList(); // // Now that we have added all of the sources, we query the raytracer to get // all of the source properties into structs for the microphysics calls. // NOTE THAT IF THE NUMBER OF SOURCES OR THEIR PROPERTIES CHANGE OVER TIME, // I WILL HAVE TO WRITE NEW CODE TO UPDATE THIS! // FVI_nheat = grid->RT->N_heating_sources(); FVI_nion = grid->RT->N_ionising_sources(); FVI_heating_srcs.resize(FVI_nheat); FVI_ionising_srcs.resize(FVI_nion); grid->RT->populate_UVheating_src_list(FVI_heating_srcs); grid->RT->populate_ionising_src_list( FVI_ionising_srcs); // // See if we need column densities for the timestep calculation // if (grid->RT->type_of_RT_integration()==RT_UPDATE_EXPLICIT) { FVI_need_column_densities_4dt = true; } else if (grid->RT && grid->RT->type_of_RT_integration()==RT_UPDATE_IMPLICIT && SimPM.EP.MP_timestep_limit==5) { // For implicit updates to limit by xdot and/or edot // The raytracing has not already been done, so we call it here. FVI_need_column_densities_4dt = true; } else { FVI_need_column_densities_4dt = false; } #ifdef RT_TESTING cout <<"------------- RAYTRACER SETUP COMPLETE ----------------\n"; #endif return 0; } // ################################################################## // ################################################################## int setup_fixed_grid::setup_evolving_RT_sources( class SimParams &SimPM ///< pointer to simulation parameters ) { // // Loop through list of sources, and see if any of them have an // evolution file (if none, then the string is set to NOFILE in // the data I/O stage). // int Nevo=0; for (int isrc=0; isrc<SimPM.RS.Nsources; isrc++) { if (SimPM.RS.sources[isrc].EvoFile == "NOFILE") { #ifdef RT_TESTING cout <<"setup_evolving_RT_sources() Source "<<isrc; cout <<" has no evolution file.\n"; #endif } else { Nevo++; struct star istar; #ifdef RT_TESTING cout <<"setup_evolving_RT_sources() Source "<<isrc; cout <<" has EvoFile "<<istar.file_name<<"\n"; #endif istar.file_name = SimPM.RS.sources[isrc].EvoFile; istar.src_id = isrc; SimPM.STAR.push_back(istar); } } // // Now go through each one we found and read the evolution file into arrays // and set the rest of the data in the 'star' struct. // for (int isrc=0; isrc<Nevo; isrc++) { struct star *istar = &(SimPM.STAR[isrc]); istar->Nlines = 0; istar->time.resize(0); istar->Log_L.resize(0); istar->Log_T.resize(0); istar->Log_R.resize(0); istar->Log_V.resize(0); // // Open file // FILE *infile=0; infile = fopen(istar->file_name.c_str(), "r"); if (!infile) rep.error("can't open wind evolving radiation source file", infile); // Skip first two lines char line[512]; char *rval = 0; rval = fgets(line,512,infile); if (!rval) rep.error("setup_fixed_grid, RS, file read 1",line); rval = fgets(line,512,infile); if (!rval) rep.error("setup_fixed_grid, RS, file read 2",line); // Temporary variables for column values // Columns are time, M, L, Teff, Mdot, vrot, vcrit, vinf double t1=0.0, t2=0.0, t3=0.0, t4=0.0, t5=0.0, t6=0.0, t7=0.0; size_t iline=0; while ( (rval = fgets(line,512,infile)) != 0 ) { //printf("rval= %s\n",rval); sscanf(line, " %lE %lE %lE %lE %lE %lE %lE", &t1, &t2, &t3, &t4, &t5, &t6, &t7); //cout.precision(16); //cout <<t1 <<" "<<t2 <<" "<< t3 <<" "<< t4 <<" "<< t5 <<" "<< t6 <<"\n"; //cout <<t1 <<" "<< t3 <<" "<< t4 <<" "<< t5 <<" "<< t6 <<"\n"; istar->Nlines ++; istar->time.push_back(t1); istar->Log_L.push_back( log10(t3/pconst.Lsun()) ); istar->Log_T.push_back( log10(t4) ); istar->Log_V.push_back( log10(t6/1.0e5) ); // Stellar radius, from Stefan Boltzmann Law. t6 = sqrt( pow(10.0,istar->Log_L[iline])*pconst.Lsun()/ (4.0*pconst.pi()*pconst.StefanBoltzmannConst()*pow(t4, 4.0))); istar->Log_R.push_back( log10(t6/pconst.Rsun() )); iline ++; //cout <<istar->Log_L.back()<<"\n"; } fclose(infile); // // set the last_line counter to be the array index // nearest to (but less than) the current time. // iline=0; while (istar->time[iline] < SimPM.simtime) iline++; istar->last_line = iline-1; //cout <<"last line="<<iline-1<<"\n"; // initialise to zero. istar->Lnow = istar->Tnow = istar->Rnow = istar->Vnow = 0.0; } return 0; } // ################################################################## // ################################################################## int setup_fixed_grid::update_evolving_RT_sources( class SimParams &SimPM, ///< simulation parameters const double time, ///< current simulation time class RayTracingBase *RT ///< pointer to raytracing class ) { bool updated=false; // // Loop over all sources with Evolution files. // for (unsigned int isrc=0; isrc<SimPM.STAR.size(); isrc++) { //cout <<"isrc="<<isrc<<" of "<<SimPM.STAR.size()<<"\n"; struct star *istar = &(SimPM.STAR[isrc]); istar->t_now = time; size_t i = istar->last_line; // Check if we have reached the last line of the file! if (i==(istar->Nlines-1)) { cout <<"\n\n*#*#* WARNING #*#*#* update_evolving_RT_sources()"; cout <<" Last line, assuming constant Lum from now on!\n\n"; return 0; } // Check if we have moved forward one line in table, in which // case we need to increment i. while (istar->t_now > istar->time[i+1]) { i++; istar->last_line = i; } // The star properties are bracketed by line i and line i+1, // so we can do a simple interpolation between them. double Lnow, Tnow, Rnow, Vnow; Lnow = istar->Log_L[i] +(istar->t_now-istar->time[i])* (istar->Log_L[i+1]-istar->Log_L[i])/ (istar->time[i+1]-istar->time[i]); Tnow = istar->Log_T[i] +(istar->t_now-istar->time[i])* (istar->Log_T[i+1]-istar->Log_T[i])/ (istar->time[i+1]-istar->time[i]); Rnow = istar->Log_R[i] +(istar->t_now-istar->time[i])* (istar->Log_R[i+1]-istar->Log_R[i])/ (istar->time[i+1]-istar->time[i]); Vnow = istar->Log_V[i] +(istar->t_now-istar->time[i])* (istar->Log_V[i+1]-istar->Log_V[i])/ (istar->time[i+1]-istar->time[i]); // convert units Lnow = exp(pconst.ln10()*(Lnow))*pconst.Lsun(); // erg/s Tnow = exp(pconst.ln10()*(Tnow)); // K Rnow = exp(pconst.ln10()*(Rnow)); // Rsun Vnow = exp(pconst.ln10()*(Vnow)); // km/s // If L or T change by more than 1% then update them; otherwise // leave as they are. if ( fabs(Lnow-istar->Lnow)/istar->Lnow >0.01 || fabs(Tnow-istar->Tnow)/istar->Tnow >0.01 ) { cout <<"update_evolving_RT_sources() NOW: t="<<istar->t_now; cout <<"\tL="<< Lnow; cout <<"\tT="<< Tnow; cout <<"\tR="<< Rnow; //cout <<"\tV="<< Vnow; cout <<"\n"; istar->Lnow = Lnow; istar->Tnow = Tnow; istar->Rnow = Rnow; istar->Vnow = Vnow; // Copy new data into SimPM.RS, send updates to RayTracing and // microphysics classes. struct rad_src_info *rs = &(SimPM.RS.sources[istar->src_id]); rs->strength = istar->Lnow; rs->Rstar = istar->Rnow; rs->Tstar = istar->Tnow; // This is a hack, fix it to something sensible if (rs->effect == RT_EFFECT_UV_HEATING) { rs->strength = 1.0e48*(rs->strength/1.989e38)* exp(-1e4/rs->Tstar); //cout <<"FUV source: strength="<<rs->strength<<"\n"; } RT->update_RT_source_properties(rs); updated=true; } else { //cout <<"not updating source: L="<<istar->Lnow<<", T="<<istar->Tnow<<"\n"; } } // // Get the data back from RT into the structs for MP updates. // if (updated) { RT->populate_UVheating_src_list(FVI_heating_srcs); RT->populate_ionising_src_list( FVI_ionising_srcs); } return 0; } // ################################################################## // ################################################################## int setup_fixed_grid::boundary_conditions( class SimParams &par, ///< simulation parameters vector<class GridBaseClass *> &grid ///< grid pointers. //class GridBaseClass *grid ///< pointer to grid. ) { // For uniform fixed cartesian grid. #ifdef TESTING cout <<"Setting up BCs in Grid with Nbc="<<par.Nbc<<"\n"; #endif // // Choose what BCs to set up based on BC strings. // int err = setup_boundary_structs(par,grid[0],0); rep.errorTest("sfg::boundary_conditions::sb_structs",0,err); // // Ask grid to set up data for external boundaries. // err = grid[0]->SetupBCs(par); rep.errorTest("sfg::boundary_conditions::SetupBCs",0,err); #ifdef TESTING cout <<"(setup_fixed_grid::boundary_conditions) Done.\n"; #endif return 0; } // ################################################################## // ################################################################## int setup_fixed_grid::setup_boundary_structs( class SimParams &par, ///< simulation parameters class GridBaseClass *grid, ///< pointer to grid. const int ) { #ifdef TESTING cout <<"Set BC types...\n"; #endif // Set number of boundaries: 2 for each dimension, plus internal. int len = 2*par.ndim + par.BC_Nint; #ifdef TESTING cout <<"Got "<<len<<" boundaries to set up.\n"; #endif if (grid->BC_bd.size() == 0) { #ifdef TESTING cout <<"size="<<grid->BC_bd.size()<<" allocating boundaries\n"; #endif for (int b=0;b<len;b++) { struct boundary_data *bd = new boundary_data; if (b<2*par.ndim) bd->depth = grid->boundary_depth(static_cast<enum direction>(b)); grid->BC_bd.push_back(bd); } } else { // assume this has already been called so quit (happens for // MPI Nested Grid algorithm) #ifdef TESTING cout <<"already set up boundaries, so returning here.\n"; #endif return 0; } // // First the 2N external boundaries. Put the strings into an array. // std::vector<std::string> bc_strings(2*par.ndim); bc_strings[0] = par.BC_XN; bc_strings[1] = par.BC_XP; if (par.ndim>1) { bc_strings[2] = par.BC_YN; bc_strings[3] = par.BC_YP; } if (par.ndim>2) { bc_strings[4] = par.BC_ZN; bc_strings[5] = par.BC_ZP; } // // Now go through each boundary and assign everything needed. // int i=0; for (i=0; i<2*par.ndim; i++) { grid->BC_bd[i]->dir = static_cast<direction>(i); //XN=0,XP=1,YN=2,YP=3,ZN=4,ZP=5 grid->BC_bd[i]->ondir = grid->OppDir(grid->BC_bd[i]->dir); #ifdef TESTING cout <<"i="<<i<<", dir = "<<grid->BC_bd[i]->dir<<", ondir="<< grid->BC_bd[i]->ondir<<"\n"; #endif grid->BC_bd[i]->baxis = static_cast<axes>(i/2); // // odd values of i are positive boundaries, others are negative. // if ((i+2)%2 !=0) { grid->BC_bd[i]->bloc = grid->Xmax(grid->BC_bd[i]->baxis); grid->BC_bd[i]->bpos = true; } else { grid->BC_bd[i]->bloc = grid->Xmin(grid->BC_bd[i]->baxis); grid->BC_bd[i]->bpos = false; } // // find boundary condition specified: // grid->BC_bd[i]->type = bc_strings[i]; if (grid->BC_bd[i]->type=="periodic") { grid->BC_bd[i]->itype=PERIODIC; grid->BC_bd[i]->type="PERIODIC"; } else if (grid->BC_bd[i]->type=="outflow" || grid->BC_bd[i]->type=="zero-gradient") { grid->BC_bd[i]->itype=OUTFLOW; grid->BC_bd[i]->type="OUTFLOW"; } else if (grid->BC_bd[i]->type=="one-way-outflow") { grid->BC_bd[i]->itype=ONEWAY_OUT; grid->BC_bd[i]->type="ONEWAY_OUT"; } else if (grid->BC_bd[i]->type=="inflow") { grid->BC_bd[i]->itype=INFLOW ; grid->BC_bd[i]->type="INFLOW"; } else if (grid->BC_bd[i]->type=="reflecting") { grid->BC_bd[i]->itype=REFLECTING; grid->BC_bd[i]->type="REFLECTING"; } else if (grid->BC_bd[i]->type=="axisymmetric") { grid->BC_bd[i]->itype=AXISYMMETRIC; grid->BC_bd[i]->type="AXISYMMETRIC"; } else if (grid->BC_bd[i]->type=="equator-reflect") { grid->BC_bd[i]->itype=JETREFLECT; grid->BC_bd[i]->type="JETREFLECT"; } else if (grid->BC_bd[i]->type=="fixed") { grid->BC_bd[i]->itype=FIXED; grid->BC_bd[i]->type="FIXED"; } else if (grid->BC_bd[i]->type=="DMR") { grid->BC_bd[i]->itype=DMACH; grid->BC_bd[i]->type="DMACH"; } else { rep.error("Don't know this BC type",grid->BC_bd[i]->type); } if(!grid->BC_bd[i]->data.empty()) rep.error("Boundary data not empty in constructor!", grid->BC_bd[i]->data.size()); grid->BC_bd[i]->refval=0; #ifdef TESTING cout <<"\tBoundary type "<<i<<" is "<<grid->BC_bd[i]->type<<"\n"; #endif } if (i<len) { #ifdef TESTING cout <<"Got "<<i<<" boundaries, but have "<<len<<" boundaries.\n"; cout <<"Must have extra BCs... checking for internal BCs\n"; #endif do { grid->BC_bd[i]->dir = NO; if (par.BC_Nint < i-2*par.ndim) { rep.error("Bad Number of boundaries",par.BC_Nint); } else { grid->BC_bd[i]->type = par.BC_INT[i-2*par.ndim]; } if (grid->BC_bd[i]->type=="jet") { grid->BC_bd[i]->itype=JETBC; grid->BC_bd[i]->type="JETBC"; } else if (grid->BC_bd[i]->type=="DMR2") { grid->BC_bd[i]->itype=DMACH2; grid->BC_bd[i]->type="DMACH2"; } else if (grid->BC_bd[i]->type=="stellar-wind") { grid->BC_bd[i]->itype=STWIND; grid->BC_bd[i]->type="STWIND"; } else { rep.error("Don't know this BC type",grid->BC_bd[i]->type); } if(!grid->BC_bd[i]->data.empty()) { rep.error("Boundary data not empty in constructor!", grid->BC_bd[i]->data.size()); } grid->BC_bd[i]->refval=0; #ifdef TESTING cout <<"\tBoundary type "<<i<<" is "<<grid->BC_bd[i]->type<<"\n"; #endif i++; } while (i<len); } #ifdef TESTING cout <<len<<" BC structs set up.\n"; #endif return 0; } // ################################################################## // ################################################################## void setup_fixed_grid::setup_dataio_class( class SimParams &par, ///< simulation parameters const int typeOfFile ///< type of I/O: 1=text,2=fits,5=silo ) { // // set up the right kind of data I/O class depending on the input. // switch (typeOfFile) { case 1: // Start From ASCII Parameterfile. dataio = new dataio_text(par); if (!dataio) rep.error("dataio_text initialisation",dataio); break; #ifdef FITS case 2: // Start from FITS restartfile. dataio = new DataIOFits(par); break; case 4: // fits +ascii dataio = new DataIOFits(par); textio = new dataio_text(par); break; #endif // if FITS #ifdef SILO case 5: // Start from Silo snapshot. dataio = new dataio_silo (par, "DOUBLE"); break; case 6: // silo + text dataio = new dataio_silo (par, "DOUBLE"); textio = new dataio_text (par); if (!textio) rep.error("INIT:: textio initialisation",par.typeofop); break; #endif // if SILO default: rep.error("setup_fixed_grid::Init unhandled filetype", typeOfFile); } return; } // ################################################################## // ################################################################## int setup_fixed_grid::set_equations( class SimParams &par ///< simulation parameters ) { cout <<"(pion) Setting up solver for equations\n"; if (par.solverType <0) rep.error("set_equations: solverType not set yet.", par.solverType); if (par.eqntype <=0) rep.error("set_equations: eqntype not set yet.",par.eqntype); if (par.eqnNDim !=3) rep.error("set_equations: eqnNDim not set right.",par.eqnNDim); if (par.nvar <=0) rep.error("set_equations: nvar not set yet.",par.nvar); if (par.ndim <=0) rep.error("set_equations: ndim not set yet.",par.ndim); if (par.artviscosity <0) rep.error("set_equations: artviscosity not set yet.", par.artviscosity); if (par.coord_sys <0) rep.error("set_equations: coordinate system not set.", par.coord_sys); if (spatial_solver) { delete spatial_solver; spatial_solver=0; } if (par.coord_sys==COORD_CRT) { cout <<"\tset_equations() Using Cartesian coord. system.\n"; switch (par.eqntype) { case EQEUL: cout <<"\tset_equations() Using Euler Equations.\n"; spatial_solver = new class FV_solver_Hydro_Euler( par.nvar, par.ndim, par.CFL, par.gamma, par.RefVec, par.etav, par.ntracer); if (!spatial_solver) rep.error("Couldn't set up solver/equations class.",EQEUL); break; case EQMHD: cout <<"\tset_equations() Using Ideal MHD Equations.\n"; spatial_solver = new class FV_solver_mhd_ideal_adi( par.nvar, par.ndim, par.CFL, par.gamma, par.RefVec, par.etav, par.ntracer); if (!spatial_solver) rep.error("Couldn't set up solver/equations class.",EQMHD); break; case EQGLM: cout <<"\tset_equations() Using GLM MHD Equations.\n"; spatial_solver = new class FV_solver_mhd_mixedGLM_adi( par.nvar, par.ndim, par.CFL, par.gamma, par.RefVec, par.etav, par.ntracer); if (!spatial_solver) rep.error("Couldn't set up solver/equations class.",EQGLM); break; case EQFCD: cout <<"\tset_equations() Using Field-CD MHD Equations.\n"; rep.error("Field CD got lost in some code updates",EQFCD); break; default: rep.error("Don't know the specified equations...",par.eqntype); break; } } // cartesian else if (par.coord_sys==COORD_CYL) { cout <<"\tset_equations() Using Cylindrical coord. system.\n"; switch (par.eqntype) { case EQEUL: cout <<"\tset_equations() Using Euler Equations.\n"; spatial_solver = new class cyl_FV_solver_Hydro_Euler( par.nvar, par.ndim, par.CFL, par.gamma, par.RefVec, par.etav, par.ntracer); if (!spatial_solver) rep.error("Couldn't set up solver/equations class.",EQEUL); break; case EQMHD: cout <<"\tset_equations() Using Ideal MHD Equations.\n"; spatial_solver = new class cyl_FV_solver_mhd_ideal_adi( par.nvar, par.ndim, par.CFL, par.gamma, par.RefVec, par.etav, par.ntracer); if (!spatial_solver) rep.error("Couldn't set up solver/equations class.",EQMHD); break; case EQGLM: cout <<"\tset_equations() Using GLM MHD Equations.\n"; spatial_solver = new class cyl_FV_solver_mhd_mixedGLM_adi( par.nvar, par.ndim, par.CFL, par.gamma, par.RefVec, par.etav, par.ntracer); if (!spatial_solver) rep.error("Couldn't set up solver/equations class.",EQGLM); break; default: rep.error("not implemented yet for axisymmetry",par.eqntype); } } // axisymmetric else if (par.coord_sys==COORD_SPH) { cout <<"\tset_equations() Using Spherical coordinate system.\n"; switch (par.eqntype) { case EQEUL: cout <<"\tset_equations() Using Euler Equations.\n"; spatial_solver = new class sph_FV_solver_Hydro_Euler( par.nvar, par.ndim, par.CFL, par.gamma, par.RefVec, par.etav, par.ntracer); if (!spatial_solver) rep.error("Couldn't set up solver/equations class.",EQEUL); break; default: rep.error("not implemented yet for spherical",par.eqntype); } } // spherically symmetric // // Check that we set up an equations class! // if (!spatial_solver) rep.error("setup_fixed_grid::set_equations() Failed", spatial_solver); //cout <<"------------------------------------------------------\n\n"; return(0); } // set_equations. // ################################################################## // ##################################################################
31.851671
117
0.573487
[ "geometry", "vector", "3d", "solid" ]
412e2429c7aa87b15a371f4248a469e12099e8d3
5,472
cc
C++
SimCalorimetry/HcalSimAlgos/src/HcalSiPM.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
SimCalorimetry/HcalSimAlgos/src/HcalSiPM.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
SimCalorimetry/HcalSimAlgos/src/HcalSiPM.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#include "SimCalorimetry/HcalSimAlgos/interface/HcalSiPM.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "CLHEP/Random/RandGaussQ.h" #include "CLHEP/Random/RandPoissonQ.h" #include "CLHEP/Random/RandFlat.h" #include "TMath.h" #include <cmath> #include <cassert> #include <utility> using std::vector; //345678911234567892123456789312345678941234567895123456789612345678971234567898 HcalSiPM::HcalSiPM(int nCells, double tau) : theCellCount(nCells), theSiPM(nCells,1.), theCrossTalk(0.), theTempDep(0.), theLastHitTime(-1.), nonlin(nullptr) { setTau(tau); assert(theCellCount>0); resetSiPM(); } HcalSiPM::~HcalSiPM() { if (nonlin) delete nonlin; } //================================================================================ //implementation of Borel-Tanner distribution double HcalSiPM::Borel(unsigned int n, double lambda, unsigned int k){ if(n<k) return 0; double dn = double(n); double dk = double(k); double dnk = dn-dk; double ldn = lambda * dn; double logb = -ldn + dnk*log(ldn) - TMath::LnGamma(dnk+1); double b=0; if (logb >= -20) { // protect against underflow b=(dk/dn); if ((n-k)<100) b *= (exp(-ldn)*pow(ldn,dnk))/TMath::Factorial(n-k); else b *= exp( logb ); } return b; } const HcalSiPM::cdfpair& HcalSiPM::BorelCDF(unsigned int k){ // EPSILON determines the min and max # of xtalk cells that can be // simulated. static const double EPSILON = 1e-6; typename cdfmap::const_iterator it; it = borelcdfs.find(k); if (it == borelcdfs.end()) { vector<double> cdf; // Find the first n=k+i value for which cdf[i] > EPSILON unsigned int i; double b=0., sumb=0.; for (i=0; ; i++) { b = Borel(k+i,theCrossTalk,k); sumb += b; if (sumb >= EPSILON) break; } cdf.push_back(sumb); unsigned int borelstartn = i; // calculate cdf[i] for(++i; ; ++i){ b = Borel(k+i,theCrossTalk,k); sumb += b; cdf.push_back(sumb); if (1-sumb < EPSILON) break; } it = (borelcdfs.emplace(k,make_pair(borelstartn, cdf))).first; } return it->second; } unsigned int HcalSiPM::addCrossTalkCells(CLHEP::HepRandomEngine* engine, unsigned int in_pes) { const cdfpair& cdf = BorelCDF(in_pes); double U = CLHEP::RandFlat::shoot(engine); std::vector<double>::const_iterator up; up= std::lower_bound (cdf.second.cbegin(), cdf.second.cend(), U); LogDebug("HcalSiPM") << "cdf size = " << cdf.second.size() << ", U = " << U << ", in_pes = " << in_pes << ", 2ndary_pes = " << (up-cdf.second.cbegin()+cdf.first); // returns the number of secondary pes produced return (up - cdf.second.cbegin() + cdf.first); } //================================================================================ double HcalSiPM::hitCells(CLHEP::HepRandomEngine* engine, unsigned int pes, double tempDiff, double photonTime) { // response to light impulse with pes input photons. The return is the number // of micro-pixels hit. If a fraction other than 0. is supplied then the // micro-pixel doesn't fully discharge. The tempDiff is the temperature // difference from nominal and is used to modify the relative strength of a // hit pixel. Pixels which are fractionally charged return a fractional // number of hit pixels. if ((theCrossTalk > 0.) && (theCrossTalk < 1.)) pes += addCrossTalkCells(engine, pes); // Account for saturation - disabled in lieu of recovery model below //pes = nonlin->getPixelsFired(pes); //disable saturation/recovery model for bad tau values if(theTau<=0) return pes; unsigned int pixel; double sum(0.), hit(0.); for (unsigned int pe(0); pe < pes; ++pe) { pixel = CLHEP::RandFlat::shootInt(engine, theCellCount); hit = (theSiPM[pixel] < 0.) ? 1.0 : (cellCharge(photonTime - theSiPM[pixel])); sum += hit*(1 + (tempDiff*theTempDep)); theSiPM[pixel] = photonTime; } theLastHitTime = photonTime; return sum; } double HcalSiPM::totalCharge(double time) const { // sum of the micro-pixels. NP is a fully charged device. // 0 is a fullly depleted device. double tot(0.), hit(0.); for(unsigned int i=0; i<theCellCount; ++i) { hit = (theSiPM[i] < 0.) ? 1. : cellCharge(time - theSiPM[i]); tot += hit; } return tot; } void HcalSiPM::setNCells(int nCells) { assert(nCells>0); theCellCount = nCells; theSiPM.resize(nCells); resetSiPM(); } void HcalSiPM::setTau(double tau) { theTau = tau; if(theTau > 0) theTauInv = 1./theTau; else theTauInv = 0; } void HcalSiPM::setCrossTalk(double xTalk) { // set the cross-talk probability double oldCrossTalk = theCrossTalk; if((xTalk < 0) || (xTalk >= 1)) { theCrossTalk = 0.; } else { theCrossTalk = xTalk; } // Recalculate the crosstalk CDFs if (theCrossTalk != oldCrossTalk) { borelcdfs.clear(); if (theCrossTalk > 0) for (int k=1; k<=100; k++) BorelCDF(k); } } void HcalSiPM::setTemperatureDependence(double dTemp) { // set the temperature dependence theTempDep = dTemp; } double HcalSiPM::cellCharge(double deltaTime) const { if (deltaTime <= 0.) return 0.; if (deltaTime*theTauInv > 10.) return 1.; double result(1. - std::exp(-deltaTime*theTauInv)); return (result > 0.99) ? 1.0 : result; } void HcalSiPM::setSaturationPars(const std::vector<float>& pars) { if (nonlin) delete nonlin; nonlin = new HcalSiPMnonlinearity(pars); }
27.77665
92
0.636148
[ "vector", "model" ]
413ac45445e4b345c006ad6ab875d43e75200c32
8,418
cpp
C++
physics/checkpointer_test.cpp
net-lisias-ksp/Principia
9292ea1fc2e4b4f0ce7a717e2f507168519f5f8a
[ "MIT" ]
2
2016-02-14T21:18:48.000Z
2017-02-11T23:23:20.000Z
physics/checkpointer_test.cpp
net-lisias-ksp/Principia
9292ea1fc2e4b4f0ce7a717e2f507168519f5f8a
[ "MIT" ]
1
2015-07-27T21:27:46.000Z
2015-07-27T21:27:46.000Z
physics/checkpointer_test.cpp
pleroy/Principia
64c4c6c124f4744381b6489e39e6b53e2a440ce9
[ "MIT" ]
null
null
null
#include "physics/checkpointer.hpp" #include "base/status_utilities.hpp" #include "geometry/named_quantities.hpp" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "testing_utilities/matchers.hpp" namespace principia { namespace physics { using base::not_null; using geometry::InfinitePast; using geometry::Instant; using quantities::si::Second; using testing_utilities::StatusIs; using ::testing::ElementsAre; using ::testing::Field; using ::testing::InSequence; using ::testing::IsEmpty; using ::testing::MockFunction; using ::testing::Ref; using ::testing::Return; using ::testing::_; ACTION_P(SetPayload, payload) { arg0->payload = payload; } struct Message { class Checkpoint { public: serialization::Point* mutable_time() { return &time_; } const serialization::Point& time() const { return time_; } int payload = 0; private: serialization::Point time_; }; google::protobuf::RepeatedPtrField<Checkpoint> checkpoint; }; class CheckpointerTest : public ::testing::Test { protected: CheckpointerTest() : checkpointer_(writer_.AsStdFunction(), reader_.AsStdFunction()) {} MockFunction<absl::Status(Message::Checkpoint const&)> reader_; MockFunction<void(not_null<Message::Checkpoint*>)> writer_; Checkpointer<Message> checkpointer_; }; TEST_F(CheckpointerTest, WriteToCheckpoint) { Instant const t = Instant() + 10 * Second; EXPECT_CALL(writer_, Call(_)); checkpointer_.WriteToCheckpoint(t); } TEST_F(CheckpointerTest, WriteToCheckpointIfNeeded) { Instant const t1 = Instant() + 10 * Second; EXPECT_CALL(writer_, Call(_)); checkpointer_.WriteToCheckpoint(t1); EXPECT_EQ(t1, checkpointer_.oldest_checkpoint()); EXPECT_EQ(t1, checkpointer_.newest_checkpoint()); EXPECT_THAT(checkpointer_.all_checkpoints(), ElementsAre(t1)); Instant const t2 = t1 + 8 * Second; EXPECT_CALL(writer_, Call(_)).Times(0); EXPECT_FALSE(checkpointer_.WriteToCheckpointIfNeeded( t2, /*max_time_between_checkpoints=*/10 * Second)); EXPECT_EQ(t1, checkpointer_.oldest_checkpoint()); EXPECT_EQ(t1, checkpointer_.newest_checkpoint()); EXPECT_THAT(checkpointer_.all_checkpoints(), ElementsAre(t1)); EXPECT_CALL(writer_, Call(_)); Instant const t3 = t2 + 3 * Second; EXPECT_TRUE(checkpointer_.WriteToCheckpointIfNeeded( t3, /*max_time_between_checkpoints=*/10 * Second)); EXPECT_EQ(t1, checkpointer_.oldest_checkpoint()); EXPECT_EQ(t3, checkpointer_.newest_checkpoint()); EXPECT_THAT(checkpointer_.all_checkpoints(), ElementsAre(t1, t3)); } TEST_F(CheckpointerTest, ReadFromOldestCheckpoint) { EXPECT_THAT(checkpointer_.ReadFromOldestCheckpoint(), StatusIs(absl::StatusCode::kNotFound)); Instant const t1 = Instant() + 10 * Second; EXPECT_CALL(writer_, Call(_)); checkpointer_.WriteToCheckpoint(t1); EXPECT_CALL(reader_, Call(_)) .WillOnce(Return(absl::CancelledError())) .WillOnce(Return(absl::OkStatus())); EXPECT_THAT(checkpointer_.ReadFromOldestCheckpoint(), StatusIs(absl::StatusCode::kCancelled)); EXPECT_OK(checkpointer_.ReadFromOldestCheckpoint()); } TEST_F(CheckpointerTest, ReadFromNewestCheckpoint) { EXPECT_THAT(checkpointer_.ReadFromNewestCheckpoint(), StatusIs(absl::StatusCode::kNotFound)); Instant const t1 = Instant() + 10 * Second; EXPECT_CALL(writer_, Call(_)); checkpointer_.WriteToCheckpoint(t1); EXPECT_CALL(reader_, Call(_)) .WillOnce(Return(absl::CancelledError())) .WillOnce(Return(absl::OkStatus())); EXPECT_THAT(checkpointer_.ReadFromNewestCheckpoint(), StatusIs(absl::StatusCode::kCancelled)); EXPECT_OK(checkpointer_.ReadFromNewestCheckpoint()); } TEST_F(CheckpointerTest, ReadFromCheckpointAtOrBefore) { Instant const t1 = Instant() + 10 * Second; EXPECT_CALL(writer_, Call(_)).WillOnce(SetPayload(1)); checkpointer_.WriteToCheckpoint(t1); Instant const t2 = t1 + 11 * Second; EXPECT_CALL(writer_, Call(_)).WillOnce(SetPayload(2)); checkpointer_.WriteToCheckpoint(t2); Instant const t3 = t2 + 11 * Second; EXPECT_CALL(writer_, Call(_)).WillOnce(SetPayload(3)); checkpointer_.WriteToCheckpoint(t3); EXPECT_EQ(InfinitePast, checkpointer_.checkpoint_at_or_before(Instant() + 1 * Second)); EXPECT_EQ(t1, checkpointer_.checkpoint_at_or_before(t1)); EXPECT_EQ(t2, checkpointer_.checkpoint_at_or_before(t2 + 1 * Second)); EXPECT_THAT( checkpointer_.all_checkpoints_at_or_before(Instant() + 1 * Second), IsEmpty()); EXPECT_THAT(checkpointer_.all_checkpoints_at_or_before(t1), ElementsAre(t1)); EXPECT_THAT(checkpointer_.all_checkpoints_at_or_before(t2 + 1 * Second), ElementsAre(t1, t2)); EXPECT_THAT(checkpointer_.all_checkpoints_between(Instant() + 1 * Second, Instant() + 3 * Second), IsEmpty()); EXPECT_THAT(checkpointer_.all_checkpoints_between(Instant() + 1 * Second, t1), ElementsAre(t1)); EXPECT_THAT(checkpointer_.all_checkpoints_between(Instant() + 1 * Second, t2 + 1 * Second), ElementsAre(t1, t2)); EXPECT_THAT(checkpointer_.all_checkpoints_between(t1, t2), ElementsAre(t1, t2)); EXPECT_THAT(checkpointer_.all_checkpoints_between(t1 - 1 * Second, t2 + 1 * Second), ElementsAre(t1, t2)); EXPECT_THAT(checkpointer_.all_checkpoints_between(t3, t1), IsEmpty()); EXPECT_THAT(checkpointer_.all_checkpoints_between(t2, t2), ElementsAre(t2)); EXPECT_THAT(checkpointer_.all_checkpoints_between(t1 + 1 * Second, t1 + 1 * Second), IsEmpty()); EXPECT_THAT( checkpointer_.ReadFromCheckpointAtOrBefore(Instant() + 1 * Second), StatusIs(absl::StatusCode::kNotFound)); EXPECT_CALL(reader_, Call(Field(&Message::Checkpoint::payload, 1))); EXPECT_OK(checkpointer_.ReadFromCheckpointAtOrBefore(t1)); EXPECT_CALL(reader_, Call(Field(&Message::Checkpoint::payload, 2))); EXPECT_OK(checkpointer_.ReadFromCheckpointAtOrBefore(t2 + 1 * Second)); EXPECT_CALL(reader_, Call(Field(&Message::Checkpoint::payload, 3))) .WillOnce(Return(absl::CancelledError())); EXPECT_THAT(checkpointer_.ReadFromCheckpointAtOrBefore(t3), StatusIs(absl::StatusCode::kCancelled)); } TEST_F(CheckpointerTest, ReadFromCheckpointAt) { Instant const t1 = Instant() + 10 * Second; EXPECT_CALL(writer_, Call(_)).WillOnce(SetPayload(1)); checkpointer_.WriteToCheckpoint(t1); Instant const t2 = t1 + 11 * Second; EXPECT_CALL(writer_, Call(_)).WillOnce(SetPayload(2)); checkpointer_.WriteToCheckpoint(t2); Instant const t3 = t2 + 11 * Second; EXPECT_CALL(writer_, Call(_)).WillOnce(SetPayload(3)); checkpointer_.WriteToCheckpoint(t3); EXPECT_THAT(checkpointer_.ReadFromCheckpointAt(t1 + 1 * Second, reader_.AsStdFunction()), StatusIs(absl::StatusCode::kNotFound)); EXPECT_CALL(reader_, Call(Field(&Message::Checkpoint::payload, 2))); EXPECT_OK(checkpointer_.ReadFromCheckpointAt(t2, reader_.AsStdFunction())); EXPECT_CALL(reader_, Call(Field(&Message::Checkpoint::payload, 3))) .WillOnce(Return(absl::CancelledError())); EXPECT_THAT(checkpointer_.ReadFromCheckpointAt(t3, reader_.AsStdFunction()), StatusIs(absl::StatusCode::kCancelled)); } TEST_F(CheckpointerTest, Serialization) { Instant t = Instant() + 10 * Second; EXPECT_CALL(writer_, Call(_)).Times(2); checkpointer_.WriteToCheckpoint(t); t += 13 * Second; checkpointer_.WriteToCheckpoint(t); Message m; checkpointer_.WriteToMessage(&m.checkpoint); EXPECT_EQ(2, m.checkpoint.size()); EXPECT_EQ(10, m.checkpoint[0].time().scalar().magnitude()); EXPECT_EQ(23, m.checkpoint[1].time().scalar().magnitude()); auto const checkpointer = Checkpointer<Message>::ReadFromMessage(writer_.AsStdFunction(), reader_.AsStdFunction(), m.checkpoint); EXPECT_EQ(Instant() + 10 * Second, checkpointer->oldest_checkpoint()); } } // namespace physics } // namespace principia
35.669492
78
0.686505
[ "geometry" ]
413bd049125c883391bdf93493be22f065367e3a
2,011
cc
C++
ui/views/controls/dot_indicator.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-10-18T02:33:40.000Z
2020-10-18T02:33:40.000Z
ui/views/controls/dot_indicator.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2021-05-17T16:28:52.000Z
2021-05-21T22:42:22.000Z
ui/views/controls/dot_indicator.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/dot_indicator.h" #include <algorithm> #include <utility> #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/base/resource/resource_bundle.h" #include "ui/compositor/layer.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/point_f.h" #include "ui/gfx/geometry/rect_f.h" namespace views { DotIndicator::~DotIndicator() = default; // static DotIndicator* DotIndicator::Install(View* parent) { auto dot = base::WrapUnique<DotIndicator>(new DotIndicator()); dot->SetPaintToLayer(); dot->layer()->SetFillsBoundsOpaquely(false); dot->SetVisible(false); return parent->AddChildView(std::move(dot)); } void DotIndicator::SetColor(SkColor dot_color, SkColor border_color) { dot_color_ = dot_color; border_color_ = border_color; SchedulePaint(); } void DotIndicator::Show() { SetVisible(true); } void DotIndicator::Hide() { SetVisible(false); } DotIndicator::DotIndicator() { // Don't allow the view to process events. SetCanProcessEventsWithinSubtree(false); } void DotIndicator::OnPaint(gfx::Canvas* canvas) { canvas->SaveLayerAlpha(SK_AlphaOPAQUE); DCHECK_EQ(width(), height()); float radius = width() / 2.0f; const float scale = canvas->UndoDeviceScaleFactor(); const int kStrokeWidthPx = 1; gfx::PointF center = gfx::RectF(GetLocalBounds()).CenterPoint(); center.Scale(scale); // Fill the center. cc::PaintFlags flags; flags.setColor(dot_color_); flags.setAntiAlias(true); canvas->DrawCircle(center, scale * radius - kStrokeWidthPx, flags); // Draw the border. flags.setColor(border_color_); flags.setStyle(cc::PaintFlags::kStroke_Style); flags.setStrokeWidth(kStrokeWidthPx * scale); canvas->DrawCircle(center, scale * radius - kStrokeWidthPx / 2.0f, flags); } BEGIN_METADATA(DotIndicator, View) END_METADATA } // namespace views
26.460526
76
0.737444
[ "geometry" ]
413d81409a98169aa35c6ef99ff82e106fa210d6
5,613
hpp
C++
iRODS/server/re/include/reGlobalsExtern.hpp
PlantandFoodResearch/irods
9dfe7ffe5aa0760b7493bd9392ea1270df9335d4
[ "BSD-3-Clause" ]
null
null
null
iRODS/server/re/include/reGlobalsExtern.hpp
PlantandFoodResearch/irods
9dfe7ffe5aa0760b7493bd9392ea1270df9335d4
[ "BSD-3-Clause" ]
null
null
null
iRODS/server/re/include/reGlobalsExtern.hpp
PlantandFoodResearch/irods
9dfe7ffe5aa0760b7493bd9392ea1270df9335d4
[ "BSD-3-Clause" ]
null
null
null
/*** Copyright (c), The Regents of the University of California *** *** For more information please refer to files in the COPYRIGHT directory ***/ /* reGlobalsExtern.h - header file for global extern declaration for the * rule engine modules */ #ifndef RE_GLOBALS_EXTERN_HPP #define RE_GLOBALS_EXTERN_HPP /**** #ifdef MALLOC_TESTING / * Include the following code to log each malloc and free. This can be useful in testing/debugging of memory allocation problems. * / #define MYMALLOC 1 #define malloc(x) mymalloc(__FILE__, __LINE__ , x) extern void* mymalloc(char* file, int line, int x); #define free(x) myfree(__FILE__, __LINE__ , x) extern void myfree(char* file, int line, void *x); #endif ***/ #include "rodsUser.hpp" #include "rods.hpp" #include "rcGlobalExtern.hpp" #include "objInfo.hpp" #include "fileOpen.hpp" #include "regExpMatch.hpp" #include "reDefines.hpp" #include "ruleExecSubmit.hpp" #include "ruleExecDel.hpp" #include "dataObjInpOut.hpp" #include "msParam.hpp" #include "modAccessControl.hpp" /***** IMPORTANT IMPORTANT IMPORTANT *****/ /***** If you are changing the RuleExecInfo *****/ /***** You need to modify the maintenance *****/ /***** functions. Please refer to the file *****/ /***** WhatToDoWhenYouChangeREIStructure.txt *****/ /***** for more details. *****/ /***** ALSO, if any structure in RuleExecInfo *****/ /***** has its definition changed there need *****/ /***** correspomding changes in maintenace *****/ /***** files. Please refer to the file *****/ /***** WhatToDoWhenYouChangeREIStructure.txt *****/ /***** for more details. *****/ /***** IMPORTANT IMPORTANT IMPORTANT *****/ typedef struct RuleExecInfo { int status; char statusStr[MAX_NAME_LEN]; char ruleName[NAME_LEN]; /* name of rule */ rsComm_t *rsComm; char pluginInstanceName[MAX_NAME_LEN]; msParamArray_t *msParamArray; msParamArray_t inOutMsParamArray; int l1descInx; dataObjInp_t *doinp; /* data object type input */ dataObjInfo_t *doi; rescGrpInfo_t *rgi; /* resource group */ userInfo_t *uoic; /* client XXXX should get this from rsComm->clientUser */ userInfo_t *uoip; /* proxy XXXX should get this from rsComm->proxyUser */ collInfo_t *coi; userInfo_t *uoio; /* other user info */ keyValPair_t *condInputData; /**** IF YOU ARE MAKING CHANGES CHECK BELOW OR ABOVE FOR IMPORTANT INFORMATION ****/ char ruleSet[RULE_SET_DEF_LENGTH]; struct RuleExecInfo *next; } ruleExecInfo_t; /***** IMPORTANT IMPORTANT IMPORTANT *****/ /***** If you are changing the RuleExecInfo *****/ /***** You need to modify the maintenance *****/ /***** functions. Please refer to the file *****/ /***** WhatToDoWhenYouChangeREIStructure.txt *****/ /***** for more details. *****/ /***** ALSO, if any structure in RuleExecInfo *****/ /***** has its definition changed there need *****/ /***** correspomding changes in maintenace *****/ /***** files. Please refer to the file *****/ /***** WhatToDoWhenYouChangeREIStructure.txt *****/ /***** for more details. *****/ /***** IMPORTANT IMPORTANT IMPORTANT *****/ struct reDebugStack { char *step; int label; }; typedef struct ReArg { int myArgc; char **myArgv; } reArg_t; typedef struct RuleExecInfoAndArg { ruleExecInfo_t *rei; reArg_t reArg; } ruleExecInfoAndArg_t; typedef struct { int MaxNumOfRules; char *ruleBase[MAX_NUM_OF_RULES]; char *action[MAX_NUM_OF_RULES]; char *ruleHead[MAX_NUM_OF_RULES]; char *ruleCondition[MAX_NUM_OF_RULES]; char *ruleAction[MAX_NUM_OF_RULES]; char *ruleRecovery[MAX_NUM_OF_RULES]; long int ruleId[MAX_NUM_OF_RULES]; } ruleStruct_t; typedef struct { int MaxNumOfDVars; char *varName[MAX_NUM_OF_DVARS]; char *action[MAX_NUM_OF_DVARS]; char *var2CMap[MAX_NUM_OF_DVARS]; long int varId[MAX_NUM_OF_DVARS]; } rulevardef_t; typedef rulevardef_t dvmStruct_t; typedef struct { int MaxNumOfFMaps; char *funcName[MAX_NUM_OF_FMAPS]; char *func2CMap[MAX_NUM_OF_FMAPS]; long int fmapId[MAX_NUM_OF_FMAPS]; } rulefmapdef_t; typedef rulefmapdef_t fnmapStruct_t; typedef struct { int MaxNumOfMsrvcs; long int msrvcId[MAX_NUM_OF_MSRVCS]; char *moduleName[MAX_NUM_OF_MSRVCS]; char *msrvcName[MAX_NUM_OF_MSRVCS]; char *msrvcSignature[MAX_NUM_OF_MSRVCS]; char *msrvcVersion[MAX_NUM_OF_MSRVCS]; char *msrvcHost[MAX_NUM_OF_MSRVCS]; char *msrvcLocation[MAX_NUM_OF_MSRVCS]; char *msrvcLanguage[MAX_NUM_OF_MSRVCS]; char *msrvcTypeName[MAX_NUM_OF_MSRVCS]; long int msrvcStatus[MAX_NUM_OF_MSRVCS]; } msrvcStruct_t; extern ruleStruct_t coreRuleStrct; extern rulevardef_t coreRuleVarDef; extern rulefmapdef_t coreRuleFuncMapDef; extern msrvcStruct_t coreMsrvcStruct; extern ruleStruct_t appRuleStrct; extern rulevardef_t appRuleVarDef; extern rulefmapdef_t appRuleFuncMapDef; extern msrvcStruct_t appMsrvcStruct; extern int reTestFlag; extern int reLoopBackFlag; extern int GlobalREDebugFlag; extern int GlobalREAuditFlag; extern char *reDebugStackFull[REDEBUG_STACK_SIZE_FULL]; extern struct reDebugStack reDebugStackCurr[REDEBUG_STACK_SIZE_CURR]; extern int reDebugStackFullPtr; extern int reDebugStackCurrPtr; extern char tmpStr[]; extern strArray_t delayStack; extern strArray_t msParamStack; #include "reFuncDefs.hpp" #include "reHelpers1.hpp" #endif /* RE_GLOBALS_EXTERN_H */
33.610778
80
0.687689
[ "object" ]
4140e9b8b69d1ba6e8d58bf7747dd0dfd2dbdd59
4,676
cpp
C++
TZXTool/TZXFile/main.cpp
MrReeMachine/TzxTool
a0685726b996a244e0f67790165bf7599fa5d535
[ "MIT" ]
7
2020-04-12T10:33:05.000Z
2021-01-20T13:48:20.000Z
TZXTool/TZXFile/main.cpp
MrReeMachine/TzxTool
a0685726b996a244e0f67790165bf7599fa5d535
[ "MIT" ]
1
2021-01-31T09:09:56.000Z
2021-02-11T19:36:27.000Z
TZXTool/TZXFile/main.cpp
MrReeMachine/TzxTool
a0685726b996a244e0f67790165bf7599fa5d535
[ "MIT" ]
1
2021-01-20T13:48:48.000Z
2021-01-20T13:48:48.000Z
// // main.cpp // Tzx2Wav // // Created by Richard Baxter on 31/10/2019. // Copyright © 2019 Richard Baxter. All rights reserved. // #include <iostream> #include "TZXFile.h" TZXFile *g_pTzxFile = NULL; #define BLOCKSIZE 22050 bool ConvertTzxFileToWav(const char *filePath, const char *outputPath) { //if (g_sndTzxAudio != 0) agk::DeleteSound(g_sndTzxAudio); FILE *hFile = NULL; hFile = fopen(filePath, "rb"); if(hFile == NULL) { printf("Error reading input file: %s\n", filePath); return false; } fseek(hFile, SEEK_SET, SEEK_END); unsigned int nFileLength = (unsigned int)ftell(hFile); fseek(hFile, SEEK_SET, SEEK_SET); if(nFileLength < 7) { printf("Input file is empty\n"); fclose(hFile); return false; } char *pData = new char[nFileLength]; if (fread(pData, nFileLength, 1, hFile)==1) { g_pTzxFile = new TZXFile(); if(g_pTzxFile->Decode((unsigned char *)pData, nFileLength) != TZX_SUCCESS) { printf("Error decoding input file: %s\n", filePath); delete[] pData; fclose(hFile); return false; } g_pTzxFile->GenerateAudioData(); if(!g_pTzxFile->WriteAudioToUncompressedWavFile(outputPath)) { printf("Error writing output file: %s\n", outputPath); delete[] pData; fclose(hFile); return false; } } else { printf("Error reading input file: %s\n", filePath); delete[] pData; fclose(hFile); return false; } delete[] pData; fclose(hFile); return true; } bool ConvertTapFileToWav(const char *input, const char *output) { // Load the tap file and turn it into a tzx object FILE *hFile = NULL; hFile = fopen(input, "rb"); if(hFile == NULL) { printf("Error reading input file: %s\n", input); return false; } fseek(hFile, SEEK_SET, SEEK_END); unsigned int nFileLength = (unsigned int)ftell(hFile); fseek(hFile, SEEK_SET, SEEK_SET); if(nFileLength < 2) { printf("Input file is empty\n"); fclose(hFile); return false; } char *pData = new char[nFileLength]; if (fread(pData, nFileLength, 1, hFile)==1) { g_pTzxFile = new TZXFile(); if(g_pTzxFile->DecodeTapFileData((unsigned char *)pData, nFileLength) != TZX_SUCCESS) { printf("Error decoding input file: %s\n", input); delete[] pData; fclose(hFile); return false; } g_pTzxFile->GenerateAudioData(); if(!g_pTzxFile->WriteAudioToUncompressedWavFile(output)) { printf("Error writing output file: %s\n", output); delete[] pData; fclose(hFile); return false; } } else { printf("Error reading input file: %s\n", input); delete[] pData; fclose(hFile); return false; } delete[] pData; fclose(hFile); return true; } void DisplayHelp() { printf("Usage:\nTzxConv <inputfile.tzx>\nTzxCov <inputfile.tzx> <outputfile.wav>\n\nIf no output file is specified then the output file will have the same name as the input file but with .wav extension appended to the end.\n"); } int main(int argc, const char * argv[]) { // insert code here... printf("TzxConv - (c)2019 Richard Baxter\n\n"); //LoadTzxFile((char *)"Bigfoot.tzx"); char *output = NULL; bool result = false; if(argc < 2) { printf("Invalid number of parameters.\n"); DisplayHelp(); return 2; } // Convert string to uppercase bool istapfile = false; char temp[8096]; strcpy(temp,argv[1]); for(int i=0;i<strlen(temp);i++) { temp[i] = toupper(temp[i]); } int len = (int)strlen(temp); if(strcmp(temp+len-4, ".TAP")==0) { istapfile = true; } if(argc==2) { output = new char[strlen(argv[1])+5]; strcpy(output, argv[1]); strcat(output,".wav"); if(istapfile) { result = ConvertTapFileToWav(argv[1], output); } else { result = ConvertTzxFileToWav(argv[1], output); } delete[] output; } else { if(istapfile) { result = ConvertTapFileToWav(argv[1], argv[2]); } else { result = ConvertTzxFileToWav(argv[1], argv[2]); } } if(!result) return 1; printf("File successfully converted.\n"); return 0; }
25.005348
231
0.556459
[ "object" ]
4144c542b449cd77b64ec6075f1625645161666b
1,010
cpp
C++
MyFiles/PCYCLE.cpp
manishSRM/solvedProblems
78492e51488605e46fd19bba472736825a2faf32
[ "Apache-2.0" ]
null
null
null
MyFiles/PCYCLE.cpp
manishSRM/solvedProblems
78492e51488605e46fd19bba472736825a2faf32
[ "Apache-2.0" ]
null
null
null
MyFiles/PCYCLE.cpp
manishSRM/solvedProblems
78492e51488605e46fd19bba472736825a2faf32
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include <algorithm> #include <vector> using namespace std; int countCycles (vector<bool> &CHECK , int N, const vector <int> &P) { int count = 0; for (int i = 1; i <= N; i++) { if (CHECK[i] == true) continue; count++; CHECK[i] = true; for (int j = P[i]; j <= N;) { if (CHECK[j] == true) break; CHECK[j] = true; j = P[j]; } } return count; } void printCycles (vector <bool> &CHECK2, int N, const vector <int> &P) { for (int i = 1; i <= N; i++) { if (CHECK2[i] == true) continue; CHECK2[i] = true; printf("%d ", i); for (int j = P[i]; j <= N;) { printf("%d ", j); if (CHECK2[j] == true) break; CHECK2[j] = true; j = P[j]; } printf("\n"); } } int main () { int N; scanf ("%d", &N); vector <int> P (N + 1); for (int i = 1; i <= N; i++) scanf ("%d", &P[i]); vector <bool> CHECK (N + 1, false); printf("%d\n", countCycles (CHECK, N, P)); vector <bool> CHECK2 (N + 1, false); printCycles (CHECK2, N, P); return 0; }
19.423077
72
0.513861
[ "vector" ]
41455059fe043686374faee491cb9afde3a76cb0
1,308
cpp
C++
TrainingGround/src/stl/iterator_test.cpp
elloop/algorithm
5485be0aedbc18968f775cff9533a2d444dbdcb5
[ "MIT" ]
15
2015-11-04T12:53:23.000Z
2021-08-10T09:53:12.000Z
TrainingGround/src/stl/iterator_test.cpp
elloop/algorithm
5485be0aedbc18968f775cff9533a2d444dbdcb5
[ "MIT" ]
null
null
null
TrainingGround/src/stl/iterator_test.cpp
elloop/algorithm
5485be0aedbc18968f775cff9533a2d444dbdcb5
[ "MIT" ]
6
2015-11-13T10:17:01.000Z
2020-05-14T07:25:48.000Z
#include "gtest/gtest.h" #include "inc.h" #include <functional> #include <type_traits> #include <fstream> #include <string> #include <streambuf> NS_BEGIN(elloop); using namespace std; using namespace std::placeholders; BEGIN_TEST(IteratorTest, AdapterBackInserter, @); //pcln("IteratorTest --> AdapterBackInserter"); //vector<string> vs; //pln("input some strings(one per line), ctrl-z to terminate input:"); //// read strings from standard input. //copy(istream_iterator<string>(cin), istream_iterator<string>(), // back_inserter(vs)); //// don't do this, error. ////copy(istream_iterator<string>(cin), istream_iterator<string>(), vs.begin()); //// sort //sort(vs.begin(), vs.end(), greater<string>()); //// output by line. //copy(vs.begin(), vs.end(), ostream_iterator<string>(cout, "\n")); END_TEST; BEGIN_TEST(IteratorTest, ISTREAMBUF_ITERATORTEST, @); pcln("IteratorTest --> AdapterBackInserter"); ifstream in("iterator_test.h", ios::in); // read char by char from file stream. string data((istreambuf_iterator<char>(in)), istreambuf_iterator<char>()); // see effective stl item6 for reason why following codes don't work. //string data(istreambuf_iterator<char>(in), istreambuf_iterator<char>()); pln(data); in.close(); END_TEST; NS_END(elloop);
26.16
82
0.696483
[ "vector" ]
4146b2b8c30b88b02d8fa9a235578c70490c07a7
16,384
hpp
C++
.venv/Lib/site-packages/ipopt-0.1.9/Ipopt-3.11.1-win64-intel13.1/include/coin/IpDenseVector.hpp
AI-Assistant/FEMAG-Python
ff86e8f41485ae9df6034e6b8e810b59f8094c70
[ "MIT" ]
null
null
null
.venv/Lib/site-packages/ipopt-0.1.9/Ipopt-3.11.1-win64-intel13.1/include/coin/IpDenseVector.hpp
AI-Assistant/FEMAG-Python
ff86e8f41485ae9df6034e6b8e810b59f8094c70
[ "MIT" ]
null
null
null
.venv/Lib/site-packages/ipopt-0.1.9/Ipopt-3.11.1-win64-intel13.1/include/coin/IpDenseVector.hpp
AI-Assistant/FEMAG-Python
ff86e8f41485ae9df6034e6b8e810b59f8094c70
[ "MIT" ]
null
null
null
// Copyright (C) 2004, 2009 International Business Machines and others. // All Rights Reserved. // This code is published under the Eclipse Public License. // // $Id: IpDenseVector.hpp 2161 2013-01-01 20:39:05Z stefan $ // // Authors: Carl Laird, Andreas Waechter IBM 2004-08-13 #ifndef __IPDENSEVECTOR_HPP__ #define __IPDENSEVECTOR_HPP__ #include "IpUtils.hpp" #include "IpVector.hpp" #include <map> namespace Ipopt { /* forward declarations */ class DenseVectorSpace; /** @name Exceptions */ //@{ DECLARE_STD_EXCEPTION(METADATA_ERROR); //@} /** Dense Vector Implementation. This is the default Vector class * in Ipopt. It stores vectors in contiguous Number arrays, unless * the vector has the same value in all entires. In the latter * case, we call the vector "homogeneous", and we store only the * values that is repeated in all elements. If you want to obtain * the values of vector, use the IsHomogeneous() method to find out * what status the vector is in, and then use either Values() const * or Scalar() const methods to get the values. To set the values * of a homogeneous method, use the Set method. To set the values * of a non-homogeneous vector, use the SetValues method, or use * the non-const Values method to get an array that you can * overwrite. In the latter case, storage is ensured. */ class DenseVector : public Vector { public: /**@name Constructors / Destructors */ //@{ /** Default Constructor */ DenseVector(const DenseVectorSpace* owner_space); /** Destructor */ virtual ~DenseVector(); //@} /** @name Additional public methods not in Vector base class. */ //@{ /** Create a new DenseVector from same VectorSpace */ SmartPtr<DenseVector> MakeNewDenseVector() const; /** Set elements in the vector to the Number array x. */ void SetValues(const Number *x); /** Obtain pointer to the internal Number array with vector * elements with the indention to change the vector data (USE * WITH CARE!). This does not produce a copy, and lifetime is not * guaranteed!. */ inline Number* Values(); /** Obtain pointer to the internal Number array with vector * elements without the intention to change the vector data (USE * WITH CARE!). This does not produce a copy, and lifetime is not * guaranteed! IMPORTANT: If this method is currently * homogeneous (i.e. IsHomogeneous returns true), then you cannot * call this method. Instead, you need to use the Scalar() * method. */ inline const Number* Values() const; /** The same as the const version of Values, but we ensure that we * always return a valid array, even if IsHomogeneous returns * true. */ const Number* ExpandedValues() const; /** This is the same as Values, but we add it here so that * ExpandedValues can also be used for the non-const case. */ inline Number* ExpandedValues() { return Values(); } /** Indicates if the vector is homogeneous (i.e., all entries have * the value Scalar() */ bool IsHomogeneous() const { return homogeneous_; } /** Scalar value of all entries in a homogeneous vector */ Number Scalar() const { DBG_ASSERT(homogeneous_); return scalar_; } //@} /** @name Modifying subranges of the vector. */ //@{ /** Copy the data in x into the subrange of this vector starting * at position Pos in this vector. Position count starts at 0. */ void CopyToPos(Index Pos, const Vector& x); /** Copy a subrange of x, starting at Pos, into the full data of * this vector. Position count starts at 0. */ void CopyFromPos(Index Pos, const Vector& x); //@} protected: /** @name Overloaded methods from Vector base class */ //@{ /** Copy the data of the vector x into this vector (DCOPY). */ virtual void CopyImpl(const Vector& x); /** Scales the vector by scalar alpha (DSCAL) */ virtual void ScalImpl(Number alpha); /** Add the multiple alpha of vector x to this vector (DAXPY) */ virtual void AxpyImpl(Number alpha, const Vector &x); /** Computes inner product of vector x with this (DDOT) */ virtual Number DotImpl(const Vector &x) const; /** Computes the 2-norm of this vector (DNRM2) */ virtual Number Nrm2Impl() const; /** Computes the 1-norm of this vector (DASUM) */ virtual Number AsumImpl() const; /** Computes the max-norm of this vector (based on IDAMAX) */ virtual Number AmaxImpl() const; /** Set each element in the vector to the scalar alpha. */ virtual void SetImpl(Number value); /** Element-wise division \f$y_i \gets y_i/x_i\f$.*/ virtual void ElementWiseDivideImpl(const Vector& x); /** Element-wise multiplication \f$y_i \gets y_i*x_i\f$.*/ virtual void ElementWiseMultiplyImpl(const Vector& x); /** Set entry to max of itself and the corresponding element in x */ virtual void ElementWiseMaxImpl(const Vector& x); /** Set entry to min of itself and the corresponding element in x */ virtual void ElementWiseMinImpl(const Vector& x); /** reciprocates the elements of the vector */ virtual void ElementWiseReciprocalImpl(); /** take abs of the elements of the vector */ virtual void ElementWiseAbsImpl(); /** take square-root of the elements of the vector */ virtual void ElementWiseSqrtImpl(); /** Changes each entry in the vector to its sgn value */ virtual void ElementWiseSgnImpl(); /** Add scalar to every component of the vector.*/ virtual void AddScalarImpl(Number scalar); /** Max value in the vector */ virtual Number MaxImpl() const; /** Min value in the vector */ virtual Number MinImpl() const; /** Computes the sum of the lements of vector */ virtual Number SumImpl() const; /** Computes the sum of the logs of the elements of vector */ virtual Number SumLogsImpl() const; /** @name Implemented specialized functions */ //@{ /** Add two vectors (a * v1 + b * v2). Result is stored in this vector. */ void AddTwoVectorsImpl(Number a, const Vector& v1, Number b, const Vector& v2, Number c); /** Fraction to the boundary parameter. */ Number FracToBoundImpl(const Vector& delta, Number tau) const; /** Add the quotient of two vectors, y = a * z/s + c * y. */ void AddVectorQuotientImpl(Number a, const Vector& z, const Vector& s, Number c); //@} /** @name Output methods */ //@{ /* Print the entire vector with padding */ virtual void PrintImpl(const Journalist& jnlst, EJournalLevel level, EJournalCategory category, const std::string& name, Index indent, const std::string& prefix) const { PrintImplOffset(jnlst, level, category, name, indent, prefix, 1); } /* Print the entire vector with padding, and start counting with an offset. */ void PrintImplOffset(const Journalist& jnlst, EJournalLevel level, EJournalCategory category, const std::string& name, Index indent, const std::string& prefix, Index offset) const; //@} friend class ParVector; private: /**@name Default Compiler Generated Methods * (Hidden to avoid implicit creation/calling). * These methods are not implemented and * we do not want the compiler to implement * them for us, so we declare them private * and do not define them. This ensures that * they will not be implicitly created/called. */ //@{ /** Default Constructor */ DenseVector(); /** Copy Constructor */ DenseVector(const DenseVector&); /** Overloaded Equals Operator */ void operator=(const DenseVector&); //@} /** Copy of the owner_space ptr as a DenseVectorSpace instead * of a VectorSpace */ const DenseVectorSpace* owner_space_; /** Dense Number array of vector values. */ Number* values_; /** Dense Number array pointer that is used for ExpandedValues */ mutable Number* expanded_values_; /** Method of getting the internal values array, making sure that * memory has been allocated */ inline Number* values_allocated(); /** Flag for Initialization. This flag is false, if the data has not yet been initialized. */ bool initialized_; /** Flag indicating whether the vector is currently homogeneous * (that is, all elements have the same value). This flag is used * to determine whether the elements of the vector are stored in * values_ or in scalar_ */ bool homogeneous_; /** Homogeneous value of all elements if the vector is currently * homogenous */ Number scalar_; /** Auxilliary method for setting explicitly all elements in * values_ to the current scalar value. */ void set_values_from_scalar(); }; /** typedefs for the map variables that define meta data for the * DenseVectorSpace */ typedef std::map<std::string, std::vector<std::string> > StringMetaDataMapType; typedef std::map<std::string, std::vector<Index> > IntegerMetaDataMapType; typedef std::map<std::string, std::vector<Number> > NumericMetaDataMapType; /** This vectors space is the vector space for DenseVector. */ class DenseVectorSpace : public VectorSpace { public: /** @name Constructors/Destructors. */ //@{ /** Constructor, requires dimension of all vector for this * VectorSpace */ DenseVectorSpace(Index dim) : VectorSpace(dim) {} /** Destructor */ ~DenseVectorSpace() {} //@} /** Method for creating a new vector of this specific type. */ inline DenseVector* MakeNewDenseVector() const { return new DenseVector(this); } /** Instantiation of the generate MakeNew method for the * VectorSpace base class. */ virtual Vector* MakeNew() const { return MakeNewDenseVector(); } /**@name Methods called by DenseVector for memory management. * This could allow to have sophisticated memory management in the * VectorSpace. */ //@{ /** Allocate internal storage for the DenseVector */ inline Number* AllocateInternalStorage() const; /** Deallocate internal storage for the DenseVector */ inline void FreeInternalStorage(Number* values) const; //@} /**@name Methods for dealing with meta data on the vector */ //@{ /** Check if string meta exists for tag */ inline bool HasStringMetaData(const std::string tag) const; /** Check if Integer meta exists for tag */ inline bool HasIntegerMetaData(const std::string tag) const; /** Check if Numeric meta exists for tag */ inline bool HasNumericMetaData(const std::string tag) const; /** Get meta data of type std::string by tag */ inline const std::vector<std::string>& GetStringMetaData(const std::string& tag) const; /** Get meta data of type Index by tag */ inline const std::vector<Index>& GetIntegerMetaData(const std::string& tag) const; /** Get meta data of type Number by tag */ inline const std::vector<Number>& GetNumericMetaData(const std::string& tag) const; /** Set meta data of type std::string by tag */ inline void SetStringMetaData(std::string tag, std::vector<std::string> meta_data); /** Set meta data of type Index by tag */ inline void SetIntegerMetaData(std::string tag, std::vector<Index> meta_data); /** Set meta data of type Number by tag */ inline void SetNumericMetaData(std::string tag, std::vector<Number> meta_data); /** Get map of meta data of type Number */ inline const StringMetaDataMapType& GetStringMetaData() const; /** Get map of meta data of type Number */ inline const IntegerMetaDataMapType& GetIntegerMetaData() const; /** Get map of meta data of type Number */ inline const NumericMetaDataMapType& GetNumericMetaData() const; //@} private: // variables to store vector meta data StringMetaDataMapType string_meta_data_; IntegerMetaDataMapType integer_meta_data_; NumericMetaDataMapType numeric_meta_data_; }; // inline functions inline Number* DenseVector::Values() { // Here we assume that every time someone requests this direct raw // pointer, the data is going to change and the Tag for this // vector has to be updated. if (initialized_ && homogeneous_) { // If currently the vector is a homogeneous vector, set all elements // explicitly to this value set_values_from_scalar(); } ObjectChanged(); initialized_= true; homogeneous_ = false; return values_allocated(); } inline const Number* DenseVector::Values() const { DBG_ASSERT(initialized_ && (Dim()==0 || values_)); return values_; } inline Number* DenseVector::values_allocated() { if (values_==NULL) { values_ = owner_space_->AllocateInternalStorage(); } return values_; } inline Number* DenseVectorSpace::AllocateInternalStorage() const { if (Dim()>0) { return new Number[Dim()]; } else { return NULL; } } inline void DenseVectorSpace::FreeInternalStorage(Number* values) const { delete [] values; } inline SmartPtr<DenseVector> DenseVector::MakeNewDenseVector() const { return owner_space_->MakeNewDenseVector(); } inline bool DenseVectorSpace::HasStringMetaData(const std::string tag) const { StringMetaDataMapType::const_iterator iter; iter = string_meta_data_.find(tag); if (iter != string_meta_data_.end()) { return true; } return false; } inline bool DenseVectorSpace::HasIntegerMetaData(const std::string tag) const { IntegerMetaDataMapType::const_iterator iter; iter = integer_meta_data_.find(tag); if (iter != integer_meta_data_.end()) { return true; } return false; } inline bool DenseVectorSpace::HasNumericMetaData(const std::string tag) const { NumericMetaDataMapType::const_iterator iter; iter = numeric_meta_data_.find(tag); if (iter != numeric_meta_data_.end()) { return true; } return false; } inline const std::vector<std::string>& DenseVectorSpace::GetStringMetaData(const std::string& tag) const { DBG_ASSERT(HasStringMetaData(tag)); StringMetaDataMapType::const_iterator iter; iter = string_meta_data_.find(tag); return iter->second; } inline const std::vector<Index>& DenseVectorSpace::GetIntegerMetaData(const std::string& tag) const { DBG_ASSERT(HasIntegerMetaData(tag)); IntegerMetaDataMapType::const_iterator iter; iter = integer_meta_data_.find(tag); return iter->second; } inline const std::vector<Number>& DenseVectorSpace::GetNumericMetaData(const std::string& tag) const { DBG_ASSERT(HasNumericMetaData(tag)); NumericMetaDataMapType::const_iterator iter; iter = numeric_meta_data_.find(tag); return iter->second; } inline void DenseVectorSpace::SetStringMetaData(std::string tag, std::vector<std::string> meta_data) { string_meta_data_[tag] = meta_data; } inline void DenseVectorSpace::SetIntegerMetaData(std::string tag, std::vector<Index> meta_data) { integer_meta_data_[tag] = meta_data; } inline void DenseVectorSpace::SetNumericMetaData(std::string tag, std::vector<Number> meta_data) { numeric_meta_data_[tag] = meta_data; } inline const StringMetaDataMapType& DenseVectorSpace::GetStringMetaData() const { return string_meta_data_; } inline const IntegerMetaDataMapType& DenseVectorSpace::GetIntegerMetaData() const { return integer_meta_data_; } inline const NumericMetaDataMapType& DenseVectorSpace::GetNumericMetaData() const { return numeric_meta_data_; } } // namespace Ipopt #endif
29.735027
99
0.658386
[ "vector" ]
a991d7997bc45bec6b99c636014812c323987145
6,351
cpp
C++
src/Layers/xrRender/SkeletonRigid.cpp
acidicMercury8/xray-1.5
ae094d82b76a8ce916e196654c163894bbf00146
[ "Linux-OpenIB" ]
5
2021-10-30T09:36:07.000Z
2021-12-30T08:14:32.000Z
src/Layers/xrRender/SkeletonRigid.cpp
Samsuper12/ixray-1.5
8070f833f8216d4ead294a9f19b7cd123bb76ba3
[ "Linux-OpenIB" ]
null
null
null
src/Layers/xrRender/SkeletonRigid.cpp
Samsuper12/ixray-1.5
8070f833f8216d4ead294a9f19b7cd123bb76ba3
[ "Linux-OpenIB" ]
2
2020-08-04T17:23:16.000Z
2020-10-16T16:53:38.000Z
//--------------------------------------------------------------------------- #include "stdafx.h" #pragma hdrstop #include "SkeletonCustom.h" extern int psSkeletonUpdate; #ifdef DEBUG void check_kinematics(CKinematics* _k, LPCSTR s); #endif void CKinematics::CalculateBones (BOOL bForceExact) { // early out. // check if the info is still relevant // skip all the computations - assume nothing changes in a small period of time :) if (Device.dwTimeGlobal == UCalc_Time) return; // early out for "fast" update UCalc_mtlock lock ; OnCalculateBones (); if (!bForceExact && (Device.dwTimeGlobal < (UCalc_Time + UCalc_Interval))) return; // early out for "slow" update if (Update_Visibility) Visibility_Update (); _DBG_SINGLE_USE_MARKER; // here we have either: // 1: timeout elapsed // 2: exact computation required UCalc_Time = Device.dwTimeGlobal; // exact computation // Calculate bones #ifdef DEBUG Device.Statistic->Animation.Begin(); #endif Bone_Calculate (bones->at(iRoot),&Fidentity); #ifdef DEBUG check_kinematics (this, dbg_name.c_str() ); Device.Statistic->Animation.End (); #endif VERIFY( LL_GetBonesVisible()!=0 ); // Calculate BOXes/Spheres if needed UCalc_Visibox++; if (UCalc_Visibox>=psSkeletonUpdate) { // mark UCalc_Visibox = -(::Random.randI(psSkeletonUpdate-1)); // the update itself Fbox Box; Box.invalidate(); for (u32 b=0; b<bones->size(); b++) { if (!LL_GetBoneVisible(u16(b))) continue; Fobb& obb = (*bones)[b]->obb; Fmatrix& Mbone = bone_instances[b].mTransform; Fmatrix Mbox; obb.xform_get(Mbox); Fmatrix X; X.mul_43(Mbone,Mbox); Fvector& S = obb.m_halfsize; Fvector P,A; A.set( -S.x, -S.y, -S.z ); X.transform_tiny(P,A); Box.modify(P); A.set( -S.x, -S.y, S.z ); X.transform_tiny(P,A); Box.modify(P); A.set( S.x, -S.y, S.z ); X.transform_tiny(P,A); Box.modify(P); A.set( S.x, -S.y, -S.z ); X.transform_tiny(P,A); Box.modify(P); A.set( -S.x, S.y, -S.z ); X.transform_tiny(P,A); Box.modify(P); A.set( -S.x, S.y, S.z ); X.transform_tiny(P,A); Box.modify(P); A.set( S.x, S.y, S.z ); X.transform_tiny(P,A); Box.modify(P); A.set( S.x, S.y, -S.z ); X.transform_tiny(P,A); Box.modify(P); } if(bones->size()) { // previous frame we have updated box - update sphere vis.box.min = (Box.min); vis.box.max = (Box.max); vis.box.getsphere (vis.sphere.P,vis.sphere.R); } #ifdef DEBUG // Validate VERIFY3 (_valid(vis.box.min)&&_valid(vis.box.max), "Invalid bones-xform in model", dbg_name.c_str()); if(vis.sphere.R>1000.f) { for(u16 ii=0; ii<LL_BoneCount();++ii){ Fmatrix tr; tr = LL_GetTransform(ii); Log("bone ",LL_BoneName_dbg(ii)); Log("bone_matrix",tr); } Log("end-------"); } VERIFY3 (vis.sphere.R<1000.f, "Invalid bones-xform in model", dbg_name.c_str()); #endif } // if (Update_Callback) Update_Callback(this); } #ifdef DEBUG void check_kinematics(CKinematics* _k, LPCSTR s) { CKinematics* K = _k; Fmatrix& MrootBone = K->LL_GetBoneInstance(K->LL_GetBoneRoot()).mTransform; if(MrootBone.c.y >10000) { Msg("all bones transform:--------[%s]",s); for(u16 ii=0; ii<K->LL_BoneCount();++ii){ Fmatrix tr; tr = K->LL_GetTransform(ii); Log("bone ",K->LL_BoneName_dbg(ii)); Log("bone_matrix",tr); } Log("end-------"); VERIFY3(0,"check_kinematics failed for ", s); } } #endif void CKinematics:: BuildBoneMatrix ( const CBoneData* bd, CBoneInstance &bi, const Fmatrix *parent, u8 channel_mask/* = (1<<0)*/ ) { bi.mTransform.mul_43 (*parent,bd->bind_transform); } void CKinematics::CLBone( const CBoneData* bd, CBoneInstance &bi, const Fmatrix *parent, u8 channel_mask /*= (1<<0)*/) { u16 SelfID = bd->GetSelfID(); if ( LL_GetBoneVisible(SelfID) ){ if ( bi.callback_overwrite() ){ if ( bi.callback() ) bi.callback()( &bi ); } else { BuildBoneMatrix( bd, bi, parent, channel_mask ); #ifndef MASTER_GOLD R_ASSERT2( _valid( bi.mTransform ), "anim kils bone matrix" ); #endif // #ifndef MASTER_GOLD if (bi.callback()) { bi.callback()(&bi); #ifndef MASTER_GOLD R_ASSERT2( _valid( bi.mTransform ), make_string( "callback kils bone matrix bone: %s " , bd->name.c_str() ) ); #endif // #ifndef MASTER_GOLD } } bi.mRenderTransform.mul_43(bi.mTransform,bd->m2b_transform); } } void CKinematics::Bone_GetAnimPos(Fmatrix& pos,u16 id,u8 mask_channel, bool ignore_callbacks) { R_ASSERT(id<LL_BoneCount()); CBoneInstance bi = LL_GetBoneInstance(id); BoneChain_Calculate(&LL_GetData(id),bi,mask_channel,ignore_callbacks); #ifndef MASTER_GOLD R_ASSERT( _valid( bi.mTransform ) ); #endif pos.set( bi.mTransform ); } void CKinematics::Bone_Calculate(CBoneData* bd, Fmatrix *parent) { u16 SelfID = bd->GetSelfID(); CBoneInstance &BONE_INST = LL_GetBoneInstance(SelfID); CLBone( bd, BONE_INST, parent, u8(-1) ); // Calculate children for (xr_vector<CBoneData*>::iterator C=bd->children.begin(); C!=bd->children.end(); C++) Bone_Calculate( *C, &BONE_INST.mTransform ); } void CKinematics::BoneChain_Calculate (const CBoneData* bd, CBoneInstance &bi, u8 mask_channel, bool ignore_callbacks) { u16 SelfID = bd->GetSelfID(); //CBlendInstance& BLEND_INST = LL_GetBlendInstance(SelfID); //CBlendInstance::BlendSVec &Blend = BLEND_INST.blend_vector(); //ignore callbacks BoneCallback bc = bi.callback(); BOOL ow = bi.callback_overwrite(); if(ignore_callbacks) { bi.set_callback( bi.callback_type(), 0, bi.callback_param(), 0 ); } if(SelfID==LL_GetBoneRoot()) { CLBone( bd, bi, &Fidentity, mask_channel ); //restore callback bi.set_callback( bi.callback_type(), bc, bi.callback_param(), ow ); return; } u16 ParentID = bd->GetParentID(); R_ASSERT( ParentID != BI_NONE ); CBoneData* ParrentDT = &LL_GetData(ParentID); CBoneInstance parrent_bi = LL_GetBoneInstance(ParentID); BoneChain_Calculate(ParrentDT, parrent_bi, mask_channel, ignore_callbacks); CLBone( bd, bi, &parrent_bi.mTransform, mask_channel ); //restore callback bi.set_callback( bi.callback_type(), bc, bi.callback_param(), ow ); }
31.132353
135
0.642104
[ "model", "transform" ]
a9929839c3f5d458f78b208acf9b512e0f980f06
865
cpp
C++
src/processor.cpp
b-ilya/CppND-System-Monitor-Project-Updated
7d0c0279520c2059a2f8176ad33328ac50ca9fff
[ "MIT" ]
null
null
null
src/processor.cpp
b-ilya/CppND-System-Monitor-Project-Updated
7d0c0279520c2059a2f8176ad33328ac50ca9fff
[ "MIT" ]
null
null
null
src/processor.cpp
b-ilya/CppND-System-Monitor-Project-Updated
7d0c0279520c2059a2f8176ad33328ac50ca9fff
[ "MIT" ]
null
null
null
#include "processor.h" #include <vector> #include "linux_parser.h" using LinuxParser::CPUStates; Processor::Processor() { Update(); } long Processor::Update() { auto currentJiffies = LinuxParser::CpuUtilization(); auto deltas = currentJiffies; if (!lastTotalJiffies.empty()) { for (unsigned i = 0; i < lastTotalJiffies.size(); i++) { deltas[i] = deltas[i] - lastTotalJiffies[i]; } } long idle = deltas[CPUStates::kIdle_] + deltas[CPUStates::kIOwait_]; long busy = deltas[CPUStates::kUser_] + deltas[CPUStates::kNice_] + deltas[CPUStates::kSystem_] + deltas[CPUStates::kIRQ_] + deltas[CPUStates::kSoftIRQ_] + deltas[CPUStates::kSteal_]; utilization = 1.0 * busy / (busy + idle); lastTotalJiffies = currentJiffies; return busy + idle; } float Processor::Utilization() const { return utilization; }
27.03125
72
0.671676
[ "vector" ]
a993903f0b3e41b4f5cce14a37f08f8585dc1299
4,252
cpp
C++
Applications/DataExplorer/VtkVis/VtkSurfacesSource.cpp
ufz/ogs
97d0249e0c578c3055730f4e9d994b9970885098
[ "BSD-3-Clause" ]
111
2015-03-20T22:54:17.000Z
2022-03-30T04:37:21.000Z
Applications/DataExplorer/VtkVis/VtkSurfacesSource.cpp
ufz/ogs
97d0249e0c578c3055730f4e9d994b9970885098
[ "BSD-3-Clause" ]
3,015
2015-01-05T21:55:16.000Z
2021-02-15T01:09:17.000Z
Applications/DataExplorer/VtkVis/VtkSurfacesSource.cpp
ufz/ogs
97d0249e0c578c3055730f4e9d994b9970885098
[ "BSD-3-Clause" ]
250
2015-02-10T15:43:57.000Z
2022-03-30T04:37:20.000Z
/** * \file * \author Lars Bilke * \date 2010-02-03 * \brief Implementation of the VtkSurfacesSource class. * * \copyright * Copyright (c) 2012-2021, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ // ** INCLUDES ** #include "VtkSurfacesSource.h" #include <vtkCellArray.h> #include <vtkCellData.h> #include <vtkInformation.h> #include <vtkInformationVector.h> #include <vtkObjectFactory.h> #include <vtkPolyData.h> #include <vtkProperty.h> #include <vtkSmartPointer.h> #include <vtkStreamingDemandDrivenPipeline.h> #include <vtkTriangle.h> #include <limits> #include "Applications/DataHolderLib/Color.h" #include "GeoLib/Triangle.h" vtkStandardNewMacro(VtkSurfacesSource); VtkSurfacesSource::VtkSurfacesSource() { _removable = false; // From VtkAlgorithmProperties this->SetNumberOfInputPorts(0); // this->SetColorBySurface(true); const DataHolderLib::Color c = DataHolderLib::getRandomColor(); vtkProperty* vtkProps = GetProperties(); vtkProps->SetColor(c[0] / 255.0, c[1] / 255.0, c[2] / 255.0); vtkProps->SetEdgeVisibility(0); } void VtkSurfacesSource::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); if (_surfaces->empty()) { return; } os << indent << "== VtkSurfacesSource ==" << "\n"; } int VtkSurfacesSource::RequestData(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { (void)request; (void)inputVector; const int nSurfaces = _surfaces->size(); if (nSurfaces == 0) { return 0; } const std::vector<GeoLib::Point*>* surfacePoints = (*_surfaces)[0]->getPointVec(); std::size_t nPoints = surfacePoints->size(); vtkSmartPointer<vtkInformation> outInfo = outputVector->GetInformationObject(0); vtkSmartPointer<vtkPolyData> output = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); if (outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) > 0) { return 1; } vtkSmartPointer<vtkPoints> newPoints = vtkSmartPointer<vtkPoints>::New(); newPoints->SetNumberOfPoints(nPoints); vtkSmartPointer<vtkCellArray> newPolygons = vtkSmartPointer<vtkCellArray>::New(); // newPolygons->Allocate(nSurfaces); vtkSmartPointer<vtkIntArray> sfcIDs = vtkSmartPointer<vtkIntArray>::New(); sfcIDs->SetNumberOfComponents(1); sfcIDs->SetName("SurfaceIDs"); for (std::size_t i = 0; i < nPoints; ++i) { const double* coords = const_cast<double*>((*surfacePoints)[i]->getCoords()); newPoints->SetPoint(i, coords); } int count(0); for (auto surface : *_surfaces) { const std::size_t nTriangles = surface->getNumberOfTriangles(); for (std::size_t i = 0; i < nTriangles; ++i) { vtkTriangle* new_tri = vtkTriangle::New(); new_tri->GetPointIds()->SetNumberOfIds(3); const GeoLib::Triangle* triangle = (*surface)[i]; for (std::size_t j = 0; j < 3; ++j) { new_tri->GetPointIds()->SetId(j, ((*triangle)[j])); } newPolygons->InsertNextCell(new_tri); sfcIDs->InsertNextValue(count); new_tri->Delete(); } count++; } output->SetPoints(newPoints); output->SetPolys(newPolygons); output->GetCellData()->AddArray(sfcIDs); output->GetCellData()->SetActiveAttribute("SurfaceIDs", vtkDataSetAttributes::SCALARS); output->Squeeze(); return 1; } int VtkSurfacesSource::RequestInformation( vtkInformation* /*request*/, vtkInformationVector** /*inputVector*/, vtkInformationVector* /*outputVector*/) { return 1; } void VtkSurfacesSource::SetUserProperty(QString name, QVariant value) { VtkAlgorithmProperties::SetUserProperty(name, value); (*_algorithmUserProperties)[name] = value; }
28.15894
79
0.637347
[ "vector" ]
a99941d4bb71f9dbfb6efe0ecccb458509c08d7a
5,451
cpp
C++
vpc/src/v2/model/Privateip.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
5
2021-03-03T08:23:43.000Z
2022-02-16T02:16:39.000Z
vpc/src/v2/model/Privateip.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
null
null
null
vpc/src/v2/model/Privateip.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
7
2021-02-26T13:53:35.000Z
2022-03-18T02:36:43.000Z
#include "huaweicloud/vpc/v2/model/Privateip.h" namespace HuaweiCloud { namespace Sdk { namespace Vpc { namespace V2 { namespace Model { Privateip::Privateip() { status_ = ""; statusIsSet_ = false; id_ = ""; idIsSet_ = false; subnetId_ = ""; subnetIdIsSet_ = false; tenantId_ = ""; tenantIdIsSet_ = false; deviceOwner_ = ""; deviceOwnerIsSet_ = false; ipAddress_ = ""; ipAddressIsSet_ = false; } Privateip::~Privateip() = default; void Privateip::validate() { } web::json::value Privateip::toJson() const { web::json::value val = web::json::value::object(); if(statusIsSet_) { val[utility::conversions::to_string_t("status")] = ModelBase::toJson(status_); } if(idIsSet_) { val[utility::conversions::to_string_t("id")] = ModelBase::toJson(id_); } if(subnetIdIsSet_) { val[utility::conversions::to_string_t("subnet_id")] = ModelBase::toJson(subnetId_); } if(tenantIdIsSet_) { val[utility::conversions::to_string_t("tenant_id")] = ModelBase::toJson(tenantId_); } if(deviceOwnerIsSet_) { val[utility::conversions::to_string_t("device_owner")] = ModelBase::toJson(deviceOwner_); } if(ipAddressIsSet_) { val[utility::conversions::to_string_t("ip_address")] = ModelBase::toJson(ipAddress_); } return val; } bool Privateip::fromJson(const web::json::value& val) { bool ok = true; if(val.has_field(utility::conversions::to_string_t("status"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("status")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setStatus(refVal); } } if(val.has_field(utility::conversions::to_string_t("id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("id")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setId(refVal); } } if(val.has_field(utility::conversions::to_string_t("subnet_id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("subnet_id")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setSubnetId(refVal); } } if(val.has_field(utility::conversions::to_string_t("tenant_id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("tenant_id")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setTenantId(refVal); } } if(val.has_field(utility::conversions::to_string_t("device_owner"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("device_owner")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setDeviceOwner(refVal); } } if(val.has_field(utility::conversions::to_string_t("ip_address"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("ip_address")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setIpAddress(refVal); } } return ok; } std::string Privateip::getStatus() const { return status_; } void Privateip::setStatus(const std::string& value) { status_ = value; statusIsSet_ = true; } bool Privateip::statusIsSet() const { return statusIsSet_; } void Privateip::unsetstatus() { statusIsSet_ = false; } std::string Privateip::getId() const { return id_; } void Privateip::setId(const std::string& value) { id_ = value; idIsSet_ = true; } bool Privateip::idIsSet() const { return idIsSet_; } void Privateip::unsetid() { idIsSet_ = false; } std::string Privateip::getSubnetId() const { return subnetId_; } void Privateip::setSubnetId(const std::string& value) { subnetId_ = value; subnetIdIsSet_ = true; } bool Privateip::subnetIdIsSet() const { return subnetIdIsSet_; } void Privateip::unsetsubnetId() { subnetIdIsSet_ = false; } std::string Privateip::getTenantId() const { return tenantId_; } void Privateip::setTenantId(const std::string& value) { tenantId_ = value; tenantIdIsSet_ = true; } bool Privateip::tenantIdIsSet() const { return tenantIdIsSet_; } void Privateip::unsettenantId() { tenantIdIsSet_ = false; } std::string Privateip::getDeviceOwner() const { return deviceOwner_; } void Privateip::setDeviceOwner(const std::string& value) { deviceOwner_ = value; deviceOwnerIsSet_ = true; } bool Privateip::deviceOwnerIsSet() const { return deviceOwnerIsSet_; } void Privateip::unsetdeviceOwner() { deviceOwnerIsSet_ = false; } std::string Privateip::getIpAddress() const { return ipAddress_; } void Privateip::setIpAddress(const std::string& value) { ipAddress_ = value; ipAddressIsSet_ = true; } bool Privateip::ipAddressIsSet() const { return ipAddressIsSet_; } void Privateip::unsetipAddress() { ipAddressIsSet_ = false; } } } } } }
21.210117
103
0.633278
[ "object", "model" ]
a999c0cb67174114d9fef40cc088c67660de108e
4,067
hpp
C++
src/include/duckdb/common/row_operations/row_operations.hpp
linkensphere201/duckdb
b77b1fa65290adfbad1bac4c44079718e6850497
[ "MIT" ]
null
null
null
src/include/duckdb/common/row_operations/row_operations.hpp
linkensphere201/duckdb
b77b1fa65290adfbad1bac4c44079718e6850497
[ "MIT" ]
null
null
null
src/include/duckdb/common/row_operations/row_operations.hpp
linkensphere201/duckdb
b77b1fa65290adfbad1bac4c44079718e6850497
[ "MIT" ]
null
null
null
//===----------------------------------------------------------------------===// // DuckDB // // duckdb/common/row_operations/row_operations.hpp // // //===----------------------------------------------------------------------===// #pragma once #include "duckdb/common/enums/expression_type.hpp" #include "duckdb/common/vector.hpp" namespace duckdb { struct AggregateObject; class DataChunk; class RowLayout; class RowDataCollection; struct SelectionVector; class StringHeap; class Vector; struct VectorData; // RowOperations contains a set of operations that operate on data using a RowLayout struct RowOperations { //===--------------------------------------------------------------------===// // Aggregation Operators //===--------------------------------------------------------------------===// //! initialize - unaligned addresses static void InitializeStates(RowLayout &layout, Vector &addresses, const SelectionVector &sel, idx_t count); //! destructor - unaligned addresses, updated static void DestroyStates(RowLayout &layout, Vector &addresses, idx_t count); //! update - aligned addresses static void UpdateStates(AggregateObject &aggr, Vector &addresses, DataChunk &payload, idx_t arg_idx, idx_t count); //! filtered update - aligned addresses static void UpdateFilteredStates(AggregateObject &aggr, Vector &addresses, DataChunk &payload, idx_t arg_idx); //! combine - unaligned addresses, updated static void CombineStates(RowLayout &layout, Vector &sources, Vector &targets, idx_t count); //! finalize - unaligned addresses, updated static void FinalizeStates(RowLayout &layout, Vector &addresses, DataChunk &result, idx_t aggr_idx); //===--------------------------------------------------------------------===// // Read/Write Operators //===--------------------------------------------------------------------===// //! Scatter group data to the rows. Initialises the ValidityMask. static void Scatter(DataChunk &columns, VectorData col_data[], const RowLayout &layout, Vector &rows, RowDataCollection &string_heap, const SelectionVector &sel, idx_t count); //! Gather a single column static void Gather(Vector &rows, const SelectionVector &row_sel, Vector &col, const SelectionVector &col_sel, const idx_t count, const idx_t col_offset, const idx_t col_no); //===--------------------------------------------------------------------===// // Comparison Operators //===--------------------------------------------------------------------===// //! Compare a block of key data against the row values to produce an updated selection that matches //! and a second (optional) selection of non-matching values. //! Returns the number of matches remaining in the selection. using Predicates = vector<ExpressionType>; static idx_t Match(DataChunk &columns, VectorData col_data[], const RowLayout &layout, Vector &rows, const Predicates &predicates, SelectionVector &sel, idx_t count, SelectionVector *no_match, idx_t &no_match_count); //===--------------------------------------------------------------------===// // Out-of-Core Operators //===--------------------------------------------------------------------===// //! Swizzles blob pointers to offset within heap row static void SwizzleColumns(const RowLayout &layout, const data_ptr_t base_row_ptr, const idx_t count); //! Swizzles the base pointer of each row to offset within heap block static void SwizzleHeapPointer(const RowLayout &layout, data_ptr_t row_ptr, const data_ptr_t heap_base_ptr, const idx_t count); //! Swizzles the base offset of each row back to a pointer static void UnswizzleHeapPointer(const RowLayout &layout, data_ptr_t row_ptr, const data_ptr_t heap_base_ptr, const idx_t count); //! Unswizzles offsets back to pointers to blobs static void UnswizzleColumns(const RowLayout &layout, const data_ptr_t base_row_ptr, const idx_t count); }; } // namespace duckdb
50.209877
116
0.598476
[ "vector" ]
a99aa256842001575282dd7c70df4a61cdb8a972
1,283
hpp
C++
include/codegen/include/System/Runtime/Serialization/IObjectReference.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/System/Runtime/Serialization/IObjectReference.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/System/Runtime/Serialization/IObjectReference.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes // Completed includes // Begin forward declares // Forward declaring namespace: System::Runtime::Serialization namespace System::Runtime::Serialization { // Forward declaring type: StreamingContext struct StreamingContext; } // Completed forward declares // Begin il2cpp-utils forward declares struct Il2CppObject; // Completed il2cpp-utils forward declares // Type namespace: System.Runtime.Serialization namespace System::Runtime::Serialization { // Autogenerated type: System.Runtime.Serialization.IObjectReference class IObjectReference { public: // public System.Object GetRealObject(System.Runtime.Serialization.StreamingContext context) // Offset: 0xFFFFFFFF ::Il2CppObject* System_Runtime_Serialization_IObjectReference_GetRealObject(System::Runtime::Serialization::StreamingContext context); }; // System.Runtime.Serialization.IObjectReference } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(System::Runtime::Serialization::IObjectReference*, "System.Runtime.Serialization", "IObjectReference"); #pragma pack(pop)
41.387097
138
0.752923
[ "object" ]
a99fe63a763a4c3eefcfc744dfc1db05d057cca3
33,487
cc
C++
third_party/blink/renderer/modules/crypto/subtle_crypto.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-10-18T02:33:40.000Z
2020-10-18T02:33:40.000Z
third_party/blink/renderer/modules/crypto/subtle_crypto.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2021-05-17T16:28:52.000Z
2021-05-21T22:42:22.000Z
third_party/blink/renderer/modules/crypto/subtle_crypto.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "third_party/blink/renderer/modules/crypto/subtle_crypto.h" #include "base/single_thread_task_runner.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/task_type.h" #include "third_party/blink/public/platform/web_crypto.h" #include "third_party/blink/public/platform/web_crypto_algorithm.h" #include "third_party/blink/public/platform/web_crypto_algorithm_params.h" #include "third_party/blink/renderer/bindings/core/v8/dictionary.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_json_web_key.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_union_arraybuffer_arraybufferview_jsonwebkey.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/core/frame/deprecation.h" #include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h" #include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer_view.h" #include "third_party/blink/renderer/core/typed_arrays/dom_array_piece.h" #include "third_party/blink/renderer/modules/crypto/crypto_histograms.h" #include "third_party/blink/renderer/modules/crypto/crypto_key.h" #include "third_party/blink/renderer/modules/crypto/crypto_result_impl.h" #include "third_party/blink/renderer/modules/crypto/crypto_utilities.h" #include "third_party/blink/renderer/modules/crypto/normalize_algorithm.h" #include "third_party/blink/renderer/platform/json/json_values.h" namespace blink { // Parses a JsonWebKey dictionary. On success writes the result to // |jsonUtf8| as a UTF8-encoded JSON octet string and returns true. // On failure sets an error on |result| and returns false. // // Note: The choice of output as an octet string is to facilitate interop // with the non-JWK formats, but does mean there is a second parsing step. // This design choice should be revisited after crbug.com/614385). static bool ParseJsonWebKey(const JsonWebKey& key, WebVector<uint8_t>& json_utf8, CryptoResult* result) { auto json_object = std::make_unique<JSONObject>(); if (key.hasKty()) json_object->SetString("kty", key.kty()); if (key.hasUse()) json_object->SetString("use", key.use()); if (key.hasKeyOps()) { auto json_array = std::make_unique<JSONArray>(); for (auto&& value : key.keyOps()) json_array->PushString(value); json_object->SetArray("key_ops", std::move(json_array)); } if (key.hasAlg()) json_object->SetString("alg", key.alg()); if (key.hasExt()) json_object->SetBoolean("ext", key.ext()); if (key.hasCrv()) json_object->SetString("crv", key.crv()); if (key.hasX()) json_object->SetString("x", key.x()); if (key.hasY()) json_object->SetString("y", key.y()); if (key.hasD()) json_object->SetString("d", key.d()); if (key.hasN()) json_object->SetString("n", key.n()); if (key.hasE()) json_object->SetString("e", key.e()); if (key.hasP()) json_object->SetString("p", key.p()); if (key.hasQ()) json_object->SetString("q", key.q()); if (key.hasDp()) json_object->SetString("dp", key.dp()); if (key.hasDq()) json_object->SetString("dq", key.dq()); if (key.hasQi()) json_object->SetString("qi", key.qi()); // TODO(eroman): Parse "oth" (crbug.com/441396) if (key.hasK()) json_object->SetString("k", key.k()); String json = json_object->ToJSONString(); json_utf8 = WebVector<uint8_t>(json.Utf8().c_str(), json.Utf8().length()); return true; } SubtleCrypto::SubtleCrypto() = default; ScriptPromise SubtleCrypto::encrypt( ScriptState* script_state, const V8AlgorithmIdentifier* raw_algorithm, CryptoKey* key, const V8BufferSource* raw_data, ExceptionState& exception_state ) { // Method described by: // https://w3c.github.io/webcrypto/Overview.html#dfn-SubtleCrypto-method-encrypt // 14.3.1.2: Let data be the result of getting a copy of the bytes held by // the data parameter passed to the encrypt method. WebVector<uint8_t> data = CopyBytes(raw_data); // 14.3.1.3: Let normalizedAlgorithm be the result of normalizing an // algorithm, with alg set to algorithm and op set to "encrypt". WebCryptoAlgorithm normalized_algorithm; if (!NormalizeAlgorithm(script_state->GetIsolate(), raw_algorithm, kWebCryptoOperationEncrypt, normalized_algorithm, exception_state)) return ScriptPromise(); auto* result = MakeGarbageCollected<CryptoResultImpl>(script_state); ScriptPromise promise = result->Promise(); // 14.3.1.8: If the name member of normalizedAlgorithm is not equal to the // name attribute of the [[algorithm]] internal slot of key then // throw an InvalidAccessError. // // 14.3.1.9: If the [[usages]] internal slot of key does not contain an // entry that is "encrypt", then throw an InvalidAccessError. if (!key->CanBeUsedForAlgorithm(normalized_algorithm, kWebCryptoKeyUsageEncrypt, result)) return promise; HistogramAlgorithmAndKey(ExecutionContext::From(script_state), normalized_algorithm, key->Key()); scoped_refptr<base::SingleThreadTaskRunner> task_runner = ExecutionContext::From(script_state) ->GetTaskRunner(blink::TaskType::kInternalWebCrypto); Platform::Current()->Crypto()->Encrypt(normalized_algorithm, key->Key(), std::move(data), result->Result(), std::move(task_runner)); return promise; } ScriptPromise SubtleCrypto::decrypt( ScriptState* script_state, const V8AlgorithmIdentifier* raw_algorithm, CryptoKey* key, const V8BufferSource* raw_data, ExceptionState& exception_state ) { // Method described by: // https://w3c.github.io/webcrypto/Overview.html#dfn-SubtleCrypto-method-decrypt // 14.3.2.2: Let data be the result of getting a copy of the bytes held by // the data parameter passed to the decrypt method. WebVector<uint8_t> data = CopyBytes(raw_data); // 14.3.2.3: Let normalizedAlgorithm be the result of normalizing an // algorithm, with alg set to algorithm and op set to "decrypt". WebCryptoAlgorithm normalized_algorithm; if (!NormalizeAlgorithm(script_state->GetIsolate(), raw_algorithm, kWebCryptoOperationDecrypt, normalized_algorithm, exception_state)) return ScriptPromise(); auto* result = MakeGarbageCollected<CryptoResultImpl>(script_state); ScriptPromise promise = result->Promise(); // 14.3.2.8: If the name member of normalizedAlgorithm is not equal to the // name attribute of the [[algorithm]] internal slot of key then // throw an InvalidAccessError. // // 14.3.2.9: If the [[usages]] internal slot of key does not contain an // entry that is "decrypt", then throw an InvalidAccessError. if (!key->CanBeUsedForAlgorithm(normalized_algorithm, kWebCryptoKeyUsageDecrypt, result)) return promise; HistogramAlgorithmAndKey(ExecutionContext::From(script_state), normalized_algorithm, key->Key()); scoped_refptr<base::SingleThreadTaskRunner> task_runner = ExecutionContext::From(script_state) ->GetTaskRunner(blink::TaskType::kInternalWebCrypto); Platform::Current()->Crypto()->Decrypt(normalized_algorithm, key->Key(), std::move(data), result->Result(), std::move(task_runner)); return promise; } ScriptPromise SubtleCrypto::sign( ScriptState* script_state, const V8AlgorithmIdentifier* raw_algorithm, CryptoKey* key, const V8BufferSource* raw_data, ExceptionState& exception_state ) { // Method described by: // https://w3c.github.io/webcrypto/Overview.html#dfn-SubtleCrypto-method-sign // 14.3.3.2: Let data be the result of getting a copy of the bytes held by // the data parameter passed to the sign method. WebVector<uint8_t> data = CopyBytes(raw_data); // 14.3.3.3: Let normalizedAlgorithm be the result of normalizing an // algorithm, with alg set to algorithm and op set to "sign". WebCryptoAlgorithm normalized_algorithm; if (!NormalizeAlgorithm(script_state->GetIsolate(), raw_algorithm, kWebCryptoOperationSign, normalized_algorithm, exception_state)) return ScriptPromise(); auto* result = MakeGarbageCollected<CryptoResultImpl>(script_state); ScriptPromise promise = result->Promise(); // 14.3.3.8: If the name member of normalizedAlgorithm is not equal to the // name attribute of the [[algorithm]] internal slot of key then // throw an InvalidAccessError. // // 14.3.3.9: If the [[usages]] internal slot of key does not contain an // entry that is "sign", then throw an InvalidAccessError. if (!key->CanBeUsedForAlgorithm(normalized_algorithm, kWebCryptoKeyUsageSign, result)) return promise; HistogramAlgorithmAndKey(ExecutionContext::From(script_state), normalized_algorithm, key->Key()); scoped_refptr<base::SingleThreadTaskRunner> task_runner = ExecutionContext::From(script_state) ->GetTaskRunner(blink::TaskType::kInternalWebCrypto); Platform::Current()->Crypto()->Sign(normalized_algorithm, key->Key(), std::move(data), result->Result(), std::move(task_runner)); return promise; } ScriptPromise SubtleCrypto::verifySignature( ScriptState* script_state, const V8AlgorithmIdentifier* raw_algorithm, CryptoKey* key, const V8BufferSource* raw_signature, const V8BufferSource* raw_data, ExceptionState& exception_state ) { // Method described by: // https://w3c.github.io/webcrypto/Overview.html#SubtleCrypto-method-verify // 14.3.4.2: Let signature be the result of getting a copy of the bytes // held by the signature parameter passed to the verify method. WebVector<uint8_t> signature = CopyBytes(raw_signature); // 14.3.4.3: Let data be the result of getting a copy of the bytes held by // the data parameter passed to the verify method. WebVector<uint8_t> data = CopyBytes(raw_data); // 14.3.4.4: Let normalizedAlgorithm be the result of normalizing an // algorithm, with alg set to algorithm and op set to "verify". WebCryptoAlgorithm normalized_algorithm; if (!NormalizeAlgorithm(script_state->GetIsolate(), raw_algorithm, kWebCryptoOperationVerify, normalized_algorithm, exception_state)) return ScriptPromise(); auto* result = MakeGarbageCollected<CryptoResultImpl>(script_state); ScriptPromise promise = result->Promise(); // 14.3.4.9: If the name member of normalizedAlgorithm is not equal to the // name attribute of the [[algorithm]] internal slot of key then // throw an InvalidAccessError. // // 14.3.4.10: If the [[usages]] internal slot of key does not contain an // entry that is "verify", then throw an InvalidAccessError. if (!key->CanBeUsedForAlgorithm(normalized_algorithm, kWebCryptoKeyUsageVerify, result)) return promise; HistogramAlgorithmAndKey(ExecutionContext::From(script_state), normalized_algorithm, key->Key()); scoped_refptr<base::SingleThreadTaskRunner> task_runner = ExecutionContext::From(script_state) ->GetTaskRunner(blink::TaskType::kInternalWebCrypto); Platform::Current()->Crypto()->VerifySignature( normalized_algorithm, key->Key(), std::move(signature), std::move(data), result->Result(), std::move(task_runner)); return promise; } ScriptPromise SubtleCrypto::digest( ScriptState* script_state, const V8AlgorithmIdentifier* raw_algorithm, const V8BufferSource* raw_data, ExceptionState& exception_state ) { // Method described by: // https://w3c.github.io/webcrypto/Overview.html#SubtleCrypto-method-digest // 14.3.5.2: Let data be the result of getting a copy of the bytes held // by the data parameter passed to the digest method. WebVector<uint8_t> data = CopyBytes(raw_data); // 14.3.5.3: Let normalizedAlgorithm be the result of normalizing an // algorithm, with alg set to algorithm and op set to "digest". WebCryptoAlgorithm normalized_algorithm; if (!NormalizeAlgorithm(script_state->GetIsolate(), raw_algorithm, kWebCryptoOperationDigest, normalized_algorithm, exception_state)) return ScriptPromise(); auto* result = MakeGarbageCollected<CryptoResultImpl>(script_state); HistogramAlgorithm(ExecutionContext::From(script_state), normalized_algorithm); scoped_refptr<base::SingleThreadTaskRunner> task_runner = ExecutionContext::From(script_state) ->GetTaskRunner(blink::TaskType::kInternalWebCrypto); Platform::Current()->Crypto()->Digest(normalized_algorithm, std::move(data), result->Result(), std::move(task_runner)); return result->Promise(); } ScriptPromise SubtleCrypto::generateKey( ScriptState* script_state, const V8AlgorithmIdentifier* raw_algorithm, bool extractable, const Vector<String>& raw_key_usages, ExceptionState& exception_state ) { // Method described by: // https://w3c.github.io/webcrypto/Overview.html#SubtleCrypto-method-generateKey auto* result = MakeGarbageCollected<CryptoResultImpl>(script_state); ScriptPromise promise = result->Promise(); WebCryptoKeyUsageMask key_usages; if (!CryptoKey::ParseUsageMask(raw_key_usages, key_usages, result)) return promise; // 14.3.6.2: Let normalizedAlgorithm be the result of normalizing an // algorithm, with alg set to algorithm and op set to // "generateKey". WebCryptoAlgorithm normalized_algorithm; if (!NormalizeAlgorithm(script_state->GetIsolate(), raw_algorithm, kWebCryptoOperationGenerateKey, normalized_algorithm, exception_state)) return ScriptPromise(); // NOTE: Steps (8) and (9) disallow empty usages on secret and private // keys. This normative requirement is enforced by the platform // implementation in the call below. HistogramAlgorithm(ExecutionContext::From(script_state), normalized_algorithm); scoped_refptr<base::SingleThreadTaskRunner> task_runner = ExecutionContext::From(script_state) ->GetTaskRunner(blink::TaskType::kInternalWebCrypto); Platform::Current()->Crypto()->GenerateKey(normalized_algorithm, extractable, key_usages, result->Result(), std::move(task_runner)); return promise; } ScriptPromise SubtleCrypto::importKey( ScriptState* script_state, const String& raw_format, const V8UnionBufferSourceOrJsonWebKey* raw_key_data, const V8AlgorithmIdentifier* raw_algorithm, bool extractable, const Vector<String>& raw_key_usages, ExceptionState& exception_state ) { // Method described by: // https://w3c.github.io/webcrypto/Overview.html#SubtleCrypto-method-importKey auto* result = MakeGarbageCollected<CryptoResultImpl>(script_state); ScriptPromise promise = result->Promise(); WebCryptoKeyFormat format; if (!CryptoKey::ParseFormat(raw_format, format, result)) return promise; WebCryptoKeyUsageMask key_usages; if (!CryptoKey::ParseUsageMask(raw_key_usages, key_usages, result)) return promise; // In the case of JWK keyData will hold the UTF8-encoded JSON for the // JsonWebKey, otherwise it holds a copy of the BufferSource. WebVector<uint8_t> key_data; switch (format) { // 14.3.9.2: If format is equal to the string "raw", "pkcs8", or "spki": // // (1) If the keyData parameter passed to the importKey method is a // JsonWebKey dictionary, throw a TypeError. // // (2) Let keyData be the result of getting a copy of the bytes held by // the keyData parameter passed to the importKey method. case kWebCryptoKeyFormatRaw: case kWebCryptoKeyFormatPkcs8: case kWebCryptoKeyFormatSpki: switch (raw_key_data->GetContentType()) { case V8UnionBufferSourceOrJsonWebKey::ContentType::kArrayBuffer: key_data = CopyBytes(raw_key_data->GetAsArrayBuffer()); break; case V8UnionBufferSourceOrJsonWebKey::ContentType::kArrayBufferView: key_data = CopyBytes(raw_key_data->GetAsArrayBufferView().Get()); break; case V8UnionBufferSourceOrJsonWebKey::ContentType::kJsonWebKey: result->CompleteWithError( kWebCryptoErrorTypeType, "Key data must be a BufferSource for non-JWK formats"); return promise; } break; // 14.3.9.2: If format is equal to the string "jwk": // // (1) If the keyData parameter passed to the importKey method is not a // JsonWebKey dictionary, throw a TypeError. // // (2) Let keyData be the keyData parameter passed to the importKey // method. case kWebCryptoKeyFormatJwk: if (!raw_key_data->IsJsonWebKey()) { result->CompleteWithError(kWebCryptoErrorTypeType, "Key data must be an object for JWK import"); return promise; } if (!ParseJsonWebKey(*raw_key_data->GetAsJsonWebKey(), key_data, result)) return promise; break; } // 14.3.9.3: Let normalizedAlgorithm be the result of normalizing an // algorithm, with alg set to algorithm and op set to // "importKey". WebCryptoAlgorithm normalized_algorithm; if (!NormalizeAlgorithm(script_state->GetIsolate(), raw_algorithm, kWebCryptoOperationImportKey, normalized_algorithm, exception_state)) return ScriptPromise(); HistogramAlgorithm(ExecutionContext::From(script_state), normalized_algorithm); scoped_refptr<base::SingleThreadTaskRunner> task_runner = ExecutionContext::From(script_state) ->GetTaskRunner(blink::TaskType::kInternalWebCrypto); Platform::Current()->Crypto()->ImportKey( format, std::move(key_data), normalized_algorithm, extractable, key_usages, result->Result(), std::move(task_runner)); return promise; } ScriptPromise SubtleCrypto::exportKey(ScriptState* script_state, const String& raw_format, CryptoKey* key) { // Method described by: // https://w3c.github.io/webcrypto/Overview.html#dfn-SubtleCrypto-method-exportKey auto* result = MakeGarbageCollected<CryptoResultImpl>(script_state); ScriptPromise promise = result->Promise(); WebCryptoKeyFormat format; if (!CryptoKey::ParseFormat(raw_format, format, result)) return promise; // 14.3.10.6: If the [[extractable]] internal slot of key is false, then // throw an InvalidAccessError. if (!key->extractable()) { result->CompleteWithError(kWebCryptoErrorTypeInvalidAccess, "key is not extractable"); return promise; } HistogramKey(ExecutionContext::From(script_state), key->Key()); scoped_refptr<base::SingleThreadTaskRunner> task_runner = ExecutionContext::From(script_state) ->GetTaskRunner(blink::TaskType::kInternalWebCrypto); Platform::Current()->Crypto()->ExportKey(format, key->Key(), result->Result(), std::move(task_runner)); return promise; } ScriptPromise SubtleCrypto::wrapKey( ScriptState* script_state, const String& raw_format, CryptoKey* key, CryptoKey* wrapping_key, const V8AlgorithmIdentifier* raw_wrap_algorithm, ExceptionState& exception_state) { // Method described by: // https://w3c.github.io/webcrypto/Overview.html#SubtleCrypto-method-wrapKey auto* result = MakeGarbageCollected<CryptoResultImpl>(script_state); ScriptPromise promise = result->Promise(); WebCryptoKeyFormat format; if (!CryptoKey::ParseFormat(raw_format, format, result)) return promise; // 14.3.11.2: Let normalizedAlgorithm be the result of normalizing an // algorithm, with alg set to algorithm and op set to "wrapKey". // // 14.3.11.3: If an error occurred, let normalizedAlgorithm be the result // of normalizing an algorithm, with alg set to algorithm and op // set to "encrypt". WebCryptoAlgorithm normalized_algorithm; if (!NormalizeAlgorithm(script_state->GetIsolate(), raw_wrap_algorithm, kWebCryptoOperationWrapKey, normalized_algorithm, exception_state)) return ScriptPromise(); // 14.3.11.9: If the name member of normalizedAlgorithm is not equal to the // name attribute of the [[algorithm]] internal slot of // wrappingKey then throw an InvalidAccessError. // // 14.3.11.10: If the [[usages]] internal slot of wrappingKey does not // contain an entry that is "wrapKey", then throw an // InvalidAccessError. if (!wrapping_key->CanBeUsedForAlgorithm(normalized_algorithm, kWebCryptoKeyUsageWrapKey, result)) return promise; // TODO(crbug.com/628416): The error from step 11 // (NotSupportedError) is thrown after step 12 which does not match // the spec order. // 14.3.11.12: If the [[extractable]] internal slot of key is false, then // throw an InvalidAccessError. if (!key->extractable()) { result->CompleteWithError(kWebCryptoErrorTypeInvalidAccess, "key is not extractable"); return promise; } HistogramAlgorithmAndKey(ExecutionContext::From(script_state), normalized_algorithm, wrapping_key->Key()); HistogramKey(ExecutionContext::From(script_state), key->Key()); scoped_refptr<base::SingleThreadTaskRunner> task_runner = ExecutionContext::From(script_state) ->GetTaskRunner(blink::TaskType::kInternalWebCrypto); Platform::Current()->Crypto()->WrapKey( format, key->Key(), wrapping_key->Key(), normalized_algorithm, result->Result(), std::move(task_runner)); return promise; } ScriptPromise SubtleCrypto::unwrapKey( ScriptState* script_state, const String& raw_format, const V8BufferSource* raw_wrapped_key, CryptoKey* unwrapping_key, const V8AlgorithmIdentifier* raw_unwrap_algorithm, const V8AlgorithmIdentifier* raw_unwrapped_key_algorithm, bool extractable, const Vector<String>& raw_key_usages, ExceptionState& exception_state ) { // Method described by: // https://w3c.github.io/webcrypto/Overview.html#SubtleCrypto-method-unwrapKey auto* result = MakeGarbageCollected<CryptoResultImpl>(script_state); ScriptPromise promise = result->Promise(); WebCryptoKeyFormat format; if (!CryptoKey::ParseFormat(raw_format, format, result)) return promise; WebCryptoKeyUsageMask key_usages; if (!CryptoKey::ParseUsageMask(raw_key_usages, key_usages, result)) return promise; // 14.3.12.2: Let wrappedKey be the result of getting a copy of the bytes // held by the wrappedKey parameter passed to the unwrapKey // method. WebVector<uint8_t> wrapped_key = CopyBytes(raw_wrapped_key); // 14.3.12.3: Let normalizedAlgorithm be the result of normalizing an // algorithm, with alg set to algorithm and op set to // "unwrapKey". // // 14.3.12.4: If an error occurred, let normalizedAlgorithm be the result // of normalizing an algorithm, with alg set to algorithm and op // set to "decrypt". WebCryptoAlgorithm normalized_algorithm; if (!NormalizeAlgorithm(script_state->GetIsolate(), raw_unwrap_algorithm, kWebCryptoOperationUnwrapKey, normalized_algorithm, exception_state)) return ScriptPromise(); // 14.3.12.6: Let normalizedKeyAlgorithm be the result of normalizing an // algorithm, with alg set to unwrappedKeyAlgorithm and op set // to "importKey". WebCryptoAlgorithm normalized_key_algorithm; if (!NormalizeAlgorithm(script_state->GetIsolate(), raw_unwrapped_key_algorithm, kWebCryptoOperationImportKey, normalized_key_algorithm, exception_state)) return ScriptPromise(); // 14.3.12.11: If the name member of normalizedAlgorithm is not equal to // the name attribute of the [[algorithm]] internal slot of // unwrappingKey then throw an InvalidAccessError. // // 14.3.12.12: If the [[usages]] internal slot of unwrappingKey does not // contain an entry that is "unwrapKey", then throw an // InvalidAccessError. if (!unwrapping_key->CanBeUsedForAlgorithm( normalized_algorithm, kWebCryptoKeyUsageUnwrapKey, result)) return promise; // NOTE: Step (16) disallows empty usages on secret and private keys. This // normative requirement is enforced by the platform implementation in the // call below. HistogramAlgorithmAndKey(ExecutionContext::From(script_state), normalized_algorithm, unwrapping_key->Key()); HistogramAlgorithm(ExecutionContext::From(script_state), normalized_key_algorithm); scoped_refptr<base::SingleThreadTaskRunner> task_runner = ExecutionContext::From(script_state) ->GetTaskRunner(blink::TaskType::kInternalWebCrypto); Platform::Current()->Crypto()->UnwrapKey( format, std::move(wrapped_key), unwrapping_key->Key(), normalized_algorithm, normalized_key_algorithm, extractable, key_usages, result->Result(), std::move(task_runner)); return promise; } ScriptPromise SubtleCrypto::deriveBits( ScriptState* script_state, const V8AlgorithmIdentifier* raw_algorithm, CryptoKey* base_key, unsigned length_bits, ExceptionState& exception_state) { // Method described by: // https://w3c.github.io/webcrypto/Overview.html#dfn-SubtleCrypto-method-deriveBits // 14.3.8.2: Let normalizedAlgorithm be the result of normalizing an // algorithm, with alg set to algorithm and op set to // "deriveBits". WebCryptoAlgorithm normalized_algorithm; if (!NormalizeAlgorithm(script_state->GetIsolate(), raw_algorithm, kWebCryptoOperationDeriveBits, normalized_algorithm, exception_state)) return ScriptPromise(); // 14.3.8.7: If the name member of normalizedAlgorithm is not equal to the // name attribute of the [[algorithm]] internal slot of baseKey // then throw an InvalidAccessError. // // 14.3.8.8: If the [[usages]] internal slot of baseKey does not contain an // entry that is "deriveBits", then throw an InvalidAccessError. auto* result = MakeGarbageCollected<CryptoResultImpl>(script_state); ScriptPromise promise = result->Promise(); if (!base_key->CanBeUsedForAlgorithm(normalized_algorithm, kWebCryptoKeyUsageDeriveBits, result)) return promise; HistogramAlgorithmAndKey(ExecutionContext::From(script_state), normalized_algorithm, base_key->Key()); scoped_refptr<base::SingleThreadTaskRunner> task_runner = ExecutionContext::From(script_state) ->GetTaskRunner(blink::TaskType::kInternalWebCrypto); Platform::Current()->Crypto()->DeriveBits( normalized_algorithm, base_key->Key(), length_bits, result->Result(), std::move(task_runner)); return promise; } ScriptPromise SubtleCrypto::deriveKey( ScriptState* script_state, const V8AlgorithmIdentifier* raw_algorithm, CryptoKey* base_key, const V8AlgorithmIdentifier* raw_derived_key_type, bool extractable, const Vector<String>& raw_key_usages, ExceptionState& exception_state ) { // Method described by: // https://w3c.github.io/webcrypto/Overview.html#SubtleCrypto-method-deriveKey auto* result = MakeGarbageCollected<CryptoResultImpl>(script_state); ScriptPromise promise = result->Promise(); WebCryptoKeyUsageMask key_usages; if (!CryptoKey::ParseUsageMask(raw_key_usages, key_usages, result)) return promise; // 14.3.7.2: Let normalizedAlgorithm be the result of normalizing an // algorithm, with alg set to algorithm and op set to // "deriveBits". WebCryptoAlgorithm normalized_algorithm; if (!NormalizeAlgorithm(script_state->GetIsolate(), raw_algorithm, kWebCryptoOperationDeriveBits, normalized_algorithm, exception_state)) return ScriptPromise(); // 14.3.7.4: Let normalizedDerivedKeyAlgorithm be the result of normalizing // an algorithm, with alg set to derivedKeyType and op set to // "importKey". WebCryptoAlgorithm normalized_derived_key_algorithm; if (!NormalizeAlgorithm(script_state->GetIsolate(), raw_derived_key_type, kWebCryptoOperationImportKey, normalized_derived_key_algorithm, exception_state)) return ScriptPromise(); // TODO(eroman): The description in the spec needs to be updated as // it doesn't describe algorithm normalization for the Get Key // Length parameters (https://github.com/w3c/webcrypto/issues/127) // For now reference step 10 which is the closest. // // 14.3.7.10: If the name member of normalizedDerivedKeyAlgorithm does not // identify a registered algorithm that supports the get key length // operation, then throw a NotSupportedError. WebCryptoAlgorithm key_length_algorithm; if (!NormalizeAlgorithm(script_state->GetIsolate(), raw_derived_key_type, kWebCryptoOperationGetKeyLength, key_length_algorithm, exception_state)) return ScriptPromise(); // 14.3.7.11: If the name member of normalizedAlgorithm is not equal to the // name attribute of the [[algorithm]] internal slot of baseKey // then throw an InvalidAccessError. // // 14.3.7.12: If the [[usages]] internal slot of baseKey does not contain // an entry that is "deriveKey", then throw an InvalidAccessError. if (!base_key->CanBeUsedForAlgorithm(normalized_algorithm, kWebCryptoKeyUsageDeriveKey, result)) return promise; // NOTE: Step (16) disallows empty usages on secret and private keys. This // normative requirement is enforced by the platform implementation in the // call below. HistogramAlgorithmAndKey(ExecutionContext::From(script_state), normalized_algorithm, base_key->Key()); HistogramAlgorithm(ExecutionContext::From(script_state), normalized_derived_key_algorithm); scoped_refptr<base::SingleThreadTaskRunner> task_runner = ExecutionContext::From(script_state) ->GetTaskRunner(blink::TaskType::kInternalWebCrypto); Platform::Current()->Crypto()->DeriveKey( normalized_algorithm, base_key->Key(), normalized_derived_key_algorithm, key_length_algorithm, extractable, key_usages, result->Result(), std::move(task_runner)); return promise; } } // namespace blink
43.659713
107
0.687998
[ "object", "vector" ]