blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
e2ea6fe62c559782c55c52d18eff09c4610bdca2
d0fb46aecc3b69983e7f6244331a81dff42d9595
/drds/src/model/DescribeDrdsInstanceLevelTasksRequest.cc
9f9b7efbd8a4b7f3a7385538852f4d766c8b2d9d
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-cpp-sdk
3d8d051d44ad00753a429817dd03957614c0c66a
e862bd03c844bcb7ccaa90571bceaa2802c7f135
refs/heads/master
2023-08-29T11:54:00.525102
2023-08-29T03:32:48
2023-08-29T03:32:48
115,379,460
104
82
NOASSERTION
2023-09-14T06:13:33
2017-12-26T02:53:27
C++
UTF-8
C++
false
false
1,645
cc
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/drds/model/DescribeDrdsInstanceLevelTasksRequest.h> using AlibabaCloud::Drds::Model::DescribeDrdsInstanceLevelTasksRequest; DescribeDrdsInstanceLevelTasksRequest::DescribeDrdsInstanceLevelTasksRequest() : RpcServiceRequest("drds", "2019-01-23", "DescribeDrdsInstanceLevelTasks") { setMethod(HttpRequest::Method::Post); } DescribeDrdsInstanceLevelTasksRequest::~DescribeDrdsInstanceLevelTasksRequest() {} std::string DescribeDrdsInstanceLevelTasksRequest::getDrdsInstanceId()const { return drdsInstanceId_; } void DescribeDrdsInstanceLevelTasksRequest::setDrdsInstanceId(const std::string& drdsInstanceId) { drdsInstanceId_ = drdsInstanceId; setParameter("DrdsInstanceId", drdsInstanceId); } std::string DescribeDrdsInstanceLevelTasksRequest::getAccessKeyId()const { return accessKeyId_; } void DescribeDrdsInstanceLevelTasksRequest::setAccessKeyId(const std::string& accessKeyId) { accessKeyId_ = accessKeyId; setParameter("AccessKeyId", accessKeyId); }
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
a8bbafaea5020dab1d7f48ef0ff11c815cab34d0
17216697080c5afdd5549aff14f42c39c420d33a
/src/src/Share/ShareLib/LinuxPublic/ACE_wrappers/examples/APG/Misc_IPC/UDP_Unicast.cpp
6d08e55a8cd0e9c712eccfa564d4daf6c77edb66
[ "MIT" ]
permissive
AI549654033/RDHelp
9c8b0cc196de98bcd81b2ccc4fc352bdc3783159
0f5f9c7d098635c7216713d7137c845c0d999226
refs/heads/master
2022-07-03T16:04:58.026641
2020-05-18T06:04:36
2020-05-18T06:04:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,818
cpp
/** * $Id: UDP_Unicast.cpp 80826 2008-03-04 14:51:23Z wotte $ * * Sample code from The ACE Programmer's Guide, * Copyright 2003 Addison-Wesley. All Rights Reserved. */ // Listing 1 code/ch09 #include "ace/OS_NS_string.h" #include "ace/Log_Msg.h" #include "ace/INET_Addr.h" #include "ace/SOCK_Dgram.h" int send_unicast (const ACE_INET_Addr &to) { const char *message = "this is the message!\n"; ACE_INET_Addr my_addr (static_cast<u_short> (10101)); ACE_SOCK_Dgram udp (my_addr); ssize_t sent = udp.send (message, ACE_OS::strlen (message) + 1, to); udp.close (); if (sent == -1) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("send")), -1); return 0; } // Listing 1 // Listing 2 code/ch09 void echo_dgram (void) { ACE_INET_Addr my_addr (static_cast<u_short> (10102)); ACE_INET_Addr your_addr; ACE_SOCK_Dgram udp (my_addr); char buff[BUFSIZ]; size_t buflen = sizeof (buff); ssize_t recv_cnt = udp.recv (buff, buflen, your_addr); if (recv_cnt > 0) udp.send (buff, static_cast<size_t> (buflen), your_addr); udp.close (); return; } // Listing 2 // Listing 3 code/ch09 #include "ace/SOCK_CODgram.h" // Exclude 3 static void show_codgram (void) { char buff[BUFSIZ]; size_t buflen = sizeof (buff); // Exclude 3 const ACE_TCHAR *peer = ACE_TEXT ("other_host:8042"); ACE_INET_Addr peer_addr (peer); ACE_SOCK_CODgram udp; if (0 != udp.open (peer_addr)) ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), peer)); // ... if (-1 == udp.send (buff, buflen)) ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("send"))); // Listing 3 } int ACE_TMAIN (int, ACE_TCHAR *[]) { show_codgram (); return 0; }
[ "jim_xie@trendmicro.com" ]
jim_xie@trendmicro.com
10b3f5dde4be683414b5e066635e093551c0cbe3
88ae8695987ada722184307301e221e1ba3cc2fa
/chrome/browser/ui/web_applications/app_browser_controller.cc
f47307596cc1185ec2b42ff739a35bc516aaf917
[ "BSD-3-Clause" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
23,246
cc
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/web_applications/app_browser_controller.h" #include "base/feature_list.h" #include "base/functional/bind.h" #include "base/strings/escape.h" #include "base/strings/string_piece.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ssl/security_state_tab_helper.h" #include "chrome/browser/themes/browser_theme_pack.h" #include "chrome/browser/themes/theme_properties.h" #include "chrome/browser/themes/theme_service.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/browser_window_state.h" #include "chrome/browser/ui/color/chrome_color_id.h" #include "chrome/browser/ui/tabs/tab_menu_model_factory.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_features.h" #include "chrome/common/pref_names.h" #include "chrome/common/themes/autogenerated_theme_util.h" #include "chrome/grit/generated_resources.h" #include "chromeos/constants/chromeos_features.h" #include "components/security_state/core/security_state.h" #include "components/url_formatter/url_formatter.h" #include "components/webapps/browser/installable/installable_manager.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/web_contents.h" #include "content/public/common/url_constants.h" #include "extensions/common/constants.h" #include "third_party/blink/public/common/features.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/models/image_model.h" #include "ui/color/color_id.h" #include "ui/color/color_recipe.h" #include "ui/color/color_transform.h" #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/favicon_size.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/resize_utils.h" #include "ui/gfx/image/image_skia.h" #include "ui/native_theme/native_theme.h" #include "url/gurl.h" #include "url/origin.h" #if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/apps/icon_standardizer.h" #include "chrome/browser/ash/system_web_apps/types/system_web_app_delegate.h" #include "chromeos/ui/base/chromeos_ui_constants.h" #endif namespace { SkColor GetAltColor(SkColor color) { return color_utils::BlendForMinContrast( color, color, absl::nullopt, kAutogeneratedThemeActiveTabPreferredContrast) .color; } } // namespace namespace web_app { // static bool AppBrowserController::IsWebApp(const Browser* browser) { return browser && browser->app_controller(); } // static bool AppBrowserController::IsForWebApp(const Browser* browser, const AppId& app_id) { return IsWebApp(browser) && browser->app_controller()->app_id() == app_id; } // static Browser* AppBrowserController::FindForWebApp(const Profile& profile, const AppId& app_id) { const BrowserList* browser_list = BrowserList::GetInstance(); for (auto it = browser_list->begin_browsers_ordered_by_activation(); it != browser_list->end_browsers_ordered_by_activation(); ++it) { Browser* browser = *it; if (browser->type() == Browser::TYPE_POPUP) continue; if (browser->profile() != &profile) continue; if (!IsForWebApp(browser, app_id)) continue; return browser; } return nullptr; } // static std::u16string AppBrowserController::FormatUrlOrigin( const GURL& url, url_formatter::FormatUrlTypes format_types) { auto origin = url::Origin::Create(url); return url_formatter::FormatUrl(origin.opaque() ? url : origin.GetURL(), format_types, base::UnescapeRule::SPACES, nullptr, nullptr, nullptr); } const ui::ThemeProvider* AppBrowserController::GetThemeProvider() const { return theme_provider_.get(); } AppBrowserController::AppBrowserController( Browser* browser, AppId app_id, bool has_tab_strip) : content::WebContentsObserver(nullptr), browser_(browser), app_id_(std::move(app_id)), has_tab_strip_(has_tab_strip), theme_provider_( ThemeService::CreateBoundThemeProvider(browser_->profile(), this)) { browser->tab_strip_model()->AddObserver(this); } AppBrowserController::AppBrowserController(Browser* browser, AppId app_id) : AppBrowserController(browser, std::move(app_id), false) {} void AppBrowserController::Init() { UpdateThemePack(); } AppBrowserController::~AppBrowserController() { browser()->tab_strip_model()->RemoveObserver(this); } bool AppBrowserController::ShouldShowCustomTabBar() const { if (!IsInstalled()) return false; content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); if (!web_contents) return false; GURL start_url = GetAppStartUrl(); base::StringPiece start_url_scheme = start_url.scheme_piece(); bool is_internal_start_url_scheme = start_url_scheme == extensions::kExtensionScheme || start_url_scheme == content::kChromeUIScheme || start_url_scheme == content::kChromeUIUntrustedScheme; auto should_show_toolbar_for_url = [&](const GURL& url) -> bool { // If the url is unset, it doesn't give a signal as to whether the toolbar // should be shown or not. In lieu of more information, do not show the // toolbar. if (url.is_empty()) return false; // Show toolbar when not using 'https', unless this is an internal app, // or origin is secure (e.g. localhost). if (!is_internal_start_url_scheme && !url.SchemeIs(url::kHttpsScheme) && !webapps::InstallableManager::IsOriginConsideredSecure(url)) { return true; } // Page URLs that are not within scope // (https://www.w3.org/TR/appmanifest/#dfn-within-scope) of the app // corresponding to |start_url| show the toolbar. return !IsUrlInAppScope(url); }; GURL visible_url = web_contents->GetVisibleURL(); GURL last_committed_url = web_contents->GetLastCommittedURL(); if (last_committed_url.is_empty() && visible_url.is_empty()) return should_show_toolbar_for_url(initial_url()); if (should_show_toolbar_for_url(visible_url) || should_show_toolbar_for_url(last_committed_url)) { return true; } // Insecure external web sites show the toolbar. // Note: IsContentSecure is false until a navigation is committed. if (!last_committed_url.is_empty() && !is_internal_start_url_scheme && !webapps::InstallableManager::IsContentSecure(web_contents)) { return true; } return false; } bool AppBrowserController::has_tab_strip() const { return has_tab_strip_; } bool AppBrowserController::HasTitlebarMenuButton() const { #if BUILDFLAG(IS_CHROMEOS_ASH) // Hide for system apps. return !system_app(); #else return true; #endif // BUILDFLAG(IS_CHROMEOS_ASH) } bool AppBrowserController::HasTitlebarAppOriginText() const { bool hide = base::FeatureList::IsEnabled(features::kHideWebAppOriginText); #if BUILDFLAG(IS_CHROMEOS_ASH) // Do not show origin text for System Apps. if (system_app()) hide = true; #endif // BUILDFLAG(IS_CHROMEOS_ASH) return !hide; } bool AppBrowserController::HasTitlebarContentSettings() const { #if BUILDFLAG(IS_CHROMEOS_ASH) // Do not show content settings for System Apps. return !system_app(); #else return true; #endif // BUILDFLAG(IS_CHROMEOS_ASH) } std::vector<PageActionIconType> AppBrowserController::GetTitleBarPageActions() const { #if BUILDFLAG(IS_CHROMEOS_ASH) if (system_app()) { return {PageActionIconType::kFind, PageActionIconType::kZoom}; } #endif // BUILDFLAG(IS_CHROMEOS_ASH) std::vector<PageActionIconType> types_enabled; types_enabled.push_back(PageActionIconType::kFind); types_enabled.push_back(PageActionIconType::kManagePasswords); types_enabled.push_back(PageActionIconType::kTranslate); types_enabled.push_back(PageActionIconType::kZoom); types_enabled.push_back(PageActionIconType::kFileSystemAccess); types_enabled.push_back(PageActionIconType::kCookieControls); types_enabled.push_back(PageActionIconType::kLocalCardMigration); types_enabled.push_back(PageActionIconType::kSaveCard); return types_enabled; } bool AppBrowserController::IsInstalled() const { return false; } std::unique_ptr<TabMenuModelFactory> AppBrowserController::GetTabMenuModelFactory() const { return nullptr; } bool AppBrowserController::AppUsesWindowControlsOverlay() const { return false; } bool AppBrowserController::AppUsesBorderlessMode() const { return false; } bool AppBrowserController::AppUsesTabbed() const { return false; } bool AppBrowserController::IsIsolatedWebApp() const { return false; } void AppBrowserController::SetIsolatedWebAppTrueForTesting() {} bool AppBrowserController::IsWindowControlsOverlayEnabled() const { return false; } void AppBrowserController::ToggleWindowControlsOverlayEnabled( base::OnceClosure on_complete) { std::move(on_complete).Run(); } gfx::Rect AppBrowserController::GetDefaultBounds() const { return gfx::Rect(); } bool AppBrowserController::HasReloadButton() const { return true; } #if !BUILDFLAG(IS_CHROMEOS) bool AppBrowserController::HasProfileMenuButton() const { return false; } #endif // !BUILDFLAG(IS_CHROMEOS) #if BUILDFLAG(IS_CHROMEOS_ASH) const ash::SystemWebAppDelegate* AppBrowserController::system_app() const { return nullptr; } #endif // BUILDFLAG(IS_CHROMEOS_ASH) std::u16string AppBrowserController::GetLaunchFlashText() const { // Isolated Web Apps should show the app's name instead of the origin. // App Short Name is considered trustworthy because manifest comes from signed // web bundle. // TODO:(crbug.com/b/1394199) Disable IWA launch flash text for OSs that // already display name on title bar. if (IsIsolatedWebApp()) { return GetAppShortName(); } return GetFormattedUrlOrigin(); } bool AppBrowserController::IsHostedApp() const { return false; } WebAppBrowserController* AppBrowserController::AsWebAppBrowserController() { return nullptr; } bool AppBrowserController::CanUserUninstall() const { return false; } void AppBrowserController::Uninstall( webapps::WebappUninstallSource webapp_uninstall_source) { NOTREACHED(); } void AppBrowserController::UpdateCustomTabBarVisibility(bool animate) const { browser()->window()->UpdateCustomTabBarVisibility(ShouldShowCustomTabBar(), animate); } void AppBrowserController::DidStartNavigation( content::NavigationHandle* navigation_handle) { if (!initial_url().is_empty()) return; if (!navigation_handle->IsInPrimaryMainFrame()) return; if (navigation_handle->GetURL().is_empty()) return; SetInitialURL(navigation_handle->GetURL()); } void AppBrowserController::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (!navigation_handle->IsInPrimaryMainFrame() || navigation_handle->IsSameDocument()) return; // For borderless mode when we navigate out of scope and then back to scope, // the draggable regions stay same and nothing triggers to re-initialize them. // So if they are cleared, they don't work anymore when coming back to scope. if (AppUsesBorderlessMode()) return; // Reset the draggable regions so they are not cached on navigation. draggable_region_ = absl::nullopt; } void AppBrowserController::DOMContentLoaded( content::RenderFrameHost* render_frame_host) { // We hold off changing theme color for a new tab until the page is loaded. UpdateThemePack(); } void AppBrowserController::DidChangeThemeColor() { UpdateThemePack(); } void AppBrowserController::OnBackgroundColorChanged() { UpdateThemePack(); } absl::optional<SkColor> AppBrowserController::GetThemeColor() const { ui::NativeTheme* native_theme = ui::NativeTheme::GetInstanceForNativeUi(); if (native_theme->InForcedColorsMode()) { // use system [Window ThemeColor] when enable high contrast return native_theme->GetSystemThemeColor( ui::NativeTheme::SystemThemeColor::kWindow); } absl::optional<SkColor> result; // HTML meta theme-color tag overrides manifest theme_color, see spec: // https://www.w3.org/TR/appmanifest/#theme_color-member content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); if (web_contents) { absl::optional<SkColor> color = web_contents->GetThemeColor(); if (color) result = color; } if (!result) return absl::nullopt; // The frame/tabstrip code expects an opaque color. return SkColorSetA(*result, SK_AlphaOPAQUE); } absl::optional<SkColor> AppBrowserController::GetBackgroundColor() const { absl::optional<SkColor> color; if (auto* web_contents = browser()->tab_strip_model()->GetActiveWebContents()) color = web_contents->GetBackgroundColor(); return color ? SkColorSetA(*color, SK_AlphaOPAQUE) : color; } std::u16string AppBrowserController::GetTitle() const { content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); if (!web_contents) return std::u16string(); content::NavigationEntry* entry = web_contents->GetController().GetVisibleEntry(); return entry ? entry->GetTitle() : std::u16string(); } std::string AppBrowserController::GetTitleForMediaControls() const { #if BUILDFLAG(IS_CHROMEOS_ASH) // Only return the app name if we're a System Web App. if (system_app()) return base::UTF16ToUTF8(GetAppShortName()); #endif // BUILDFLAG(IS_CHROMEOS_ASH) return std::string(); } GURL AppBrowserController::GetAppNewTabUrl() const { return GetAppStartUrl(); } bool AppBrowserController::IsUrlInHomeTabScope(const GURL& url) const { return false; } bool AppBrowserController::ShouldShowAppIconOnTab(int index) const { return false; } #if BUILDFLAG(IS_MAC) bool AppBrowserController::AlwaysShowToolbarInFullscreen() const { return true; } void AppBrowserController::ToggleAlwaysShowToolbarInFullscreen() {} #endif void AppBrowserController::OnTabStripModelChanged( TabStripModel* tab_strip_model, const TabStripModelChange& change, const TabStripSelectionChange& selection) { if (selection.active_tab_changed()) { content::WebContentsObserver::Observe(selection.new_contents); // Update theme when tabs change unless there are no tabs, or if the tab has // not finished loading, we will update later in DOMContentLoaded(). if (tab_strip_model->count() > 0 && selection.new_contents->IsDocumentOnLoadCompletedInPrimaryMainFrame()) { UpdateThemePack(); } } if (change.type() == TabStripModelChange::kInserted) { for (const auto& contents : change.GetInsert()->contents) OnTabInserted(contents.contents); } else if (change.type() == TabStripModelChange::kRemoved) { for (const auto& contents : change.GetRemove()->contents) OnTabRemoved(contents.contents); // WebContents should be null when the last tab is closed. DCHECK_EQ(web_contents() == nullptr, tab_strip_model->empty()); } // Do not update the UI during window shutdown. if (!selection.new_contents) { return; } UpdateCustomTabBarVisibility(/*animate=*/false); } CustomThemeSupplier* AppBrowserController::GetThemeSupplier() const { return theme_pack_.get(); } bool AppBrowserController::ShouldUseCustomFrame() const { return true; } void AppBrowserController::AddColorMixers( ui::ColorProvider* provider, const ui::ColorProviderManager::Key& key) const { constexpr SkAlpha kSeparatorOpacity = 0.15f * 255.0f; #if !BUILDFLAG(IS_CHROMEOS_ASH) // This color is the same as the default active frame color. const absl::optional<SkColor> theme_color = GetThemeColor(); ui::ColorTransform default_background = key.color_mode == ui::ColorProviderManager::ColorMode::kLight ? ui::ColorTransform(ui::kColorFrameActiveUnthemed) : ui::HSLShift(ui::kColorFrameActiveUnthemed, ThemeProperties::GetDefaultTint( ThemeProperties::TINT_FRAME, true)); #endif ui::ColorMixer& mixer = provider->AddMixer(); absl::optional<SkColor> bg_color = GetBackgroundColor(); // TODO(kylixrd): The definition of kColorPwaBackground isn't fully fleshed // out yet. Whether or not the PWA background color is set is used in many // locations to derive other colors. Those specific locations would need to be // addressed in their own context. if (bg_color) mixer[kColorPwaBackground] = {bg_color.value()}; mixer[kColorPwaMenuButtonIcon] = {kColorToolbarButtonIcon}; mixer[kColorPwaSecurityChipForeground] = {ui::kColorSecondaryForeground}; mixer[kColorPwaSecurityChipForegroundDangerous] = { ui::kColorAlertHighSeverity}; mixer[kColorPwaSecurityChipForegroundPolicyCert] = { ui::kColorDisabledForeground}; mixer[kColorPwaSecurityChipForegroundSecure] = { kColorPwaSecurityChipForeground}; auto separator_color = ui::GetColorWithMaxContrast(kColorPwaToolbarBackground); mixer[kColorPwaTabBarBottomSeparator] = ui::AlphaBlend( separator_color, kColorPwaToolbarBackground, kSeparatorOpacity); mixer[kColorPwaTabBarTopSeparator] = ui::AlphaBlend(separator_color, kColorPwaTheme, kSeparatorOpacity); #if BUILDFLAG(IS_CHROMEOS_ASH) // Ash system frames differ from ChromeOS browser frames. mixer[kColorPwaTheme] = {chromeos::kDefaultFrameColor}; #else mixer[kColorPwaTheme] = theme_color ? ui::ColorTransform(theme_color.value()) : default_background; #endif mixer[kColorPwaToolbarBackground] = {ui::kColorEndpointBackground}; mixer[kColorPwaToolbarButtonIcon] = ui::DeriveDefaultIconColor(ui::kColorEndpointForeground); mixer[kColorPwaToolbarButtonIconDisabled] = ui::SetAlpha(kColorPwaToolbarButtonIcon, gfx::kDisabledControlAlpha); if (bg_color) mixer[kColorWebContentsBackground] = {kColorPwaBackground}; mixer[kColorInfoBarBackground] = {kColorPwaToolbarBackground}; mixer[kColorInfoBarForeground] = {kColorPwaToolbarButtonIcon}; } void AppBrowserController::OnReceivedInitialURL() { UpdateCustomTabBarVisibility(/*animate=*/false); // If the window bounds have not been overridden, there is no need to resize // the window. if (!browser()->bounds_overridden()) return; // The saved bounds will only be wrong if they are content bounds. if (!chrome::SavedBoundsAreContentBounds(browser())) return; // TODO(crbug.com/964825): Correctly set the window size at creation time. // This is currently not possible because the current url is not easily known // at popup construction time. browser()->window()->SetContentsSize(browser()->override_bounds().size()); } void AppBrowserController::OnTabInserted(content::WebContents* contents) { if (!contents->GetVisibleURL().is_empty() && initial_url_.is_empty()) SetInitialURL(contents->GetVisibleURL()); } void AppBrowserController::OnTabRemoved(content::WebContents* contents) {} ui::ImageModel AppBrowserController::GetFallbackAppIcon() const { gfx::ImageSkia page_icon = browser()->GetCurrentPageIcon().AsImageSkia(); if (!page_icon.isNull()) { #if BUILDFLAG(IS_CHROMEOS_ASH) return ui::ImageModel::FromImageSkia( apps::CreateStandardIconImage(page_icon)); #else return ui::ImageModel::FromImageSkia(page_icon); #endif } // The icon may be loading still. Return a transparent icon rather // than using a placeholder to avoid flickering. SkBitmap bitmap; bitmap.allocN32Pixels(gfx::kFaviconSize, gfx::kFaviconSize); bitmap.eraseColor(SK_ColorTRANSPARENT); return ui::ImageModel::FromImageSkia( gfx::ImageSkia::CreateFrom1xBitmap(bitmap)); } void AppBrowserController::UpdateDraggableRegion(const SkRegion& region) { draggable_region_ = region; if (on_draggable_region_set_for_testing_) std::move(on_draggable_region_set_for_testing_).Run(); } void AppBrowserController::SetOnUpdateDraggableRegionForTesting( base::OnceClosure done) { on_draggable_region_set_for_testing_ = std::move(done); } void AppBrowserController::UpdateThemePack() { absl::optional<SkColor> theme_color = GetThemeColor(); AutogeneratedThemeColors colors; // TODO(crbug.com/1053823): Add tests for theme properties being set in this // branch. absl::optional<SkColor> background_color = GetBackgroundColor(); if (theme_color == last_theme_color_ && background_color == last_background_color_) { return; } last_theme_color_ = theme_color; last_background_color_ = background_color; bool ignore_custom_colors = false; #if BUILDFLAG(IS_CHROMEOS_ASH) // Some system web apps use the system theme color, and should not update // the theme pack here. Otherwise the colorIds for the window caption bar will // be remapped through `BrowserThemePack::BuildFromColors`, and colors will be // resolved differently than the colors set in the function `AddUiColorMixer`. if (chromeos::features::IsJellyrollEnabled() && system_app() && system_app()->UseSystemThemeColor()) { ignore_custom_colors = true; } #endif // BUILDFLAG(IS_CHROMEOS_ASH) bool no_custom_colors = !theme_color && !background_color; bool non_tabbed_no_frame_color = !has_tab_strip_ && !theme_color; if (ignore_custom_colors || no_custom_colors || non_tabbed_no_frame_color) { theme_pack_ = nullptr; if (browser_->window()) { browser_->window()->UserChangedTheme( BrowserThemeChangeType::kWebAppTheme); } return; } if (!theme_color) { theme_color = GetAltColor(*background_color); } else if (!background_color) { background_color = ui::NativeTheme::GetInstanceForNativeUi()->ShouldUseDarkColors() ? gfx::kGoogleGrey900 : SK_ColorWHITE; } // For regular web apps, frame gets theme color and active tab gets // background color. colors.frame_color = *theme_color; colors.active_tab_color = *background_color; colors.ntp_color = *background_color; colors.frame_text_color = color_utils::GetColorWithMaxContrast(colors.frame_color); colors.active_tab_text_color = color_utils::GetColorWithMaxContrast(colors.active_tab_color); theme_pack_ = base::MakeRefCounted<BrowserThemePack>( ui::ColorProviderManager::ThemeInitializerSupplier::ThemeType:: kAutogenerated); BrowserThemePack::BuildFromColors(colors, theme_pack_.get()); if (browser_->window()) browser_->window()->UserChangedTheme(BrowserThemeChangeType::kWebAppTheme); } void AppBrowserController::SetInitialURL(const GURL& initial_url) { DCHECK(initial_url_.is_empty()); initial_url_ = initial_url; OnReceivedInitialURL(); } } // namespace web_app
[ "jengelh@inai.de" ]
jengelh@inai.de
f2ca57acd8c2b09eb1f35848190c799adb978035
110eaf9fdd50707f8ae6aefb88ba54e5a3fd8cd1
/workspace/webrtc/api/peer_connection_interface.h
17d9004eb252b7a0337de92b88946e1b3f7ee75a
[]
no_license
DaHuMao/gn-build-workspace
9d6047a80863d94bb8c39f62c217ecacf109eabb
e99582662cf912638bd703b0cc5887e6c3c44ec2
refs/heads/main
2023-07-15T11:41:54.189847
2021-08-29T04:50:54
2021-08-29T04:50:54
375,058,361
0
0
null
null
null
null
UTF-8
C++
false
false
70,775
h
/* * Copyright 2012 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. */ // This file contains the PeerConnection interface as defined in // https://w3c.github.io/webrtc-pc/#peer-to-peer-connections // // The PeerConnectionFactory class provides factory methods to create // PeerConnection, MediaStream and MediaStreamTrack objects. // // The following steps are needed to setup a typical call using WebRTC: // // 1. Create a PeerConnectionFactoryInterface. Check constructors for more // information about input parameters. // // 2. Create a PeerConnection object. Provide a configuration struct which // points to STUN and/or TURN servers used to generate ICE candidates, and // provide an object that implements the PeerConnectionObserver interface, // which is used to receive callbacks from the PeerConnection. // // 3. Create local MediaStreamTracks using the PeerConnectionFactory and add // them to PeerConnection by calling AddTrack (or legacy method, AddStream). // // 4. Create an offer, call SetLocalDescription with it, serialize it, and send // it to the remote peer // // 5. Once an ICE candidate has been gathered, the PeerConnection will call the // observer function OnIceCandidate. The candidates must also be serialized and // sent to the remote peer. // // 6. Once an answer is received from the remote peer, call // SetRemoteDescription with the remote answer. // // 7. Once a remote candidate is received from the remote peer, provide it to // the PeerConnection by calling AddIceCandidate. // // The receiver of a call (assuming the application is "call"-based) can decide // to accept or reject the call; this decision will be taken by the application, // not the PeerConnection. // // If the application decides to accept the call, it should: // // 1. Create PeerConnectionFactoryInterface if it doesn't exist. // // 2. Create a new PeerConnection. // // 3. Provide the remote offer to the new PeerConnection object by calling // SetRemoteDescription. // // 4. Generate an answer to the remote offer by calling CreateAnswer and send it // back to the remote peer. // // 5. Provide the local answer to the new PeerConnection by calling // SetLocalDescription with the answer. // // 6. Provide the remote ICE candidates by calling AddIceCandidate. // // 7. Once a candidate has been gathered, the PeerConnection will call the // observer function OnIceCandidate. Send these candidates to the remote peer. #ifndef API_PEER_CONNECTION_INTERFACE_H_ #define API_PEER_CONNECTION_INTERFACE_H_ #include <stdio.h> #include <memory> #include <string> #include <vector> #include "api/adaptation/resource.h" #include "api/async_dns_resolver.h" #include "api/async_resolver_factory.h" #include "api/audio/audio_mixer.h" #include "api/audio_codecs/audio_decoder_factory.h" #include "api/audio_codecs/audio_encoder_factory.h" #include "api/audio_options.h" #include "api/call/call_factory_interface.h" #include "api/crypto/crypto_options.h" #include "api/data_channel_interface.h" #include "api/dtls_transport_interface.h" #include "api/fec_controller.h" #include "api/ice_transport_interface.h" #include "api/jsep.h" #include "api/media_stream_interface.h" #include "api/neteq/neteq_factory.h" #include "api/network_state_predictor.h" #include "api/packet_socket_factory.h" #include "api/rtc_error.h" #include "api/rtc_event_log/rtc_event_log_factory_interface.h" #include "api/rtc_event_log_output.h" #include "api/rtp_receiver_interface.h" #include "api/rtp_sender_interface.h" #include "api/rtp_transceiver_interface.h" #include "api/sctp_transport_interface.h" #include "api/set_local_description_observer_interface.h" #include "api/set_remote_description_observer_interface.h" #include "api/stats/rtc_stats_collector_callback.h" #include "api/stats_types.h" #include "api/task_queue/task_queue_factory.h" #include "api/transport/bitrate_settings.h" #include "api/transport/enums.h" #include "api/transport/network_control.h" #include "api/transport/sctp_transport_factory_interface.h" #include "api/transport/webrtc_key_value_config.h" #include "api/turn_customizer.h" #include "media/base/media_config.h" #include "media/base/media_engine.h" // TODO(bugs.webrtc.org/7447): We plan to provide a way to let applications // inject a PacketSocketFactory and/or NetworkManager, and not expose // PortAllocator in the PeerConnection api. #include "p2p/base/port_allocator.h" // nogncheck #include "rtc_base/network_monitor_factory.h" #include "rtc_base/rtc_certificate.h" #include "rtc_base/rtc_certificate_generator.h" #include "rtc_base/socket_address.h" #include "rtc_base/ssl_certificate.h" #include "rtc_base/ssl_stream_adapter.h" #include "rtc_base/system/rtc_export.h" namespace rtc { class Thread; } // namespace rtc namespace webrtc { // MediaStream container interface. class StreamCollectionInterface : public rtc::RefCountInterface { public: // TODO(ronghuawu): Update the function names to c++ style, e.g. find -> Find. virtual size_t count() = 0; virtual MediaStreamInterface* at(size_t index) = 0; virtual MediaStreamInterface* find(const std::string& label) = 0; virtual MediaStreamTrackInterface* FindAudioTrack(const std::string& id) = 0; virtual MediaStreamTrackInterface* FindVideoTrack(const std::string& id) = 0; protected: // Dtor protected as objects shouldn't be deleted via this interface. ~StreamCollectionInterface() override = default; }; class StatsObserver : public rtc::RefCountInterface { public: virtual void OnComplete(const StatsReports& reports) = 0; protected: ~StatsObserver() override = default; }; enum class SdpSemantics { kPlanB, kUnifiedPlan }; class RTC_EXPORT PeerConnectionInterface : public rtc::RefCountInterface { public: // See https://w3c.github.io/webrtc-pc/#dom-rtcsignalingstate enum SignalingState { kStable, kHaveLocalOffer, kHaveLocalPrAnswer, kHaveRemoteOffer, kHaveRemotePrAnswer, kClosed, }; // See https://w3c.github.io/webrtc-pc/#dom-rtcicegatheringstate enum IceGatheringState { kIceGatheringNew, kIceGatheringGathering, kIceGatheringComplete }; // See https://w3c.github.io/webrtc-pc/#dom-rtcpeerconnectionstate enum class PeerConnectionState { kNew, kConnecting, kConnected, kDisconnected, kFailed, kClosed, }; // See https://w3c.github.io/webrtc-pc/#dom-rtciceconnectionstate enum IceConnectionState { kIceConnectionNew, kIceConnectionChecking, kIceConnectionConnected, kIceConnectionCompleted, kIceConnectionFailed, kIceConnectionDisconnected, kIceConnectionClosed, kIceConnectionMax, }; // TLS certificate policy. enum TlsCertPolicy { // For TLS based protocols, ensure the connection is secure by not // circumventing certificate validation. kTlsCertPolicySecure, // For TLS based protocols, disregard security completely by skipping // certificate validation. This is insecure and should never be used unless // security is irrelevant in that particular context. kTlsCertPolicyInsecureNoCheck, }; struct RTC_EXPORT IceServer { IceServer(); IceServer(const IceServer&); ~IceServer(); // TODO(jbauch): Remove uri when all code using it has switched to urls. // List of URIs associated with this server. Valid formats are described // in RFC7064 and RFC7065, and more may be added in the future. The "host" // part of the URI may contain either an IP address or a hostname. std::string uri; std::vector<std::string> urls; std::string username; std::string password; TlsCertPolicy tls_cert_policy = kTlsCertPolicySecure; // If the URIs in |urls| only contain IP addresses, this field can be used // to indicate the hostname, which may be necessary for TLS (using the SNI // extension). If |urls| itself contains the hostname, this isn't // necessary. std::string hostname; // List of protocols to be used in the TLS ALPN extension. std::vector<std::string> tls_alpn_protocols; // List of elliptic curves to be used in the TLS elliptic curves extension. std::vector<std::string> tls_elliptic_curves; bool operator==(const IceServer& o) const { return uri == o.uri && urls == o.urls && username == o.username && password == o.password && tls_cert_policy == o.tls_cert_policy && hostname == o.hostname && tls_alpn_protocols == o.tls_alpn_protocols && tls_elliptic_curves == o.tls_elliptic_curves; } bool operator!=(const IceServer& o) const { return !(*this == o); } }; typedef std::vector<IceServer> IceServers; enum IceTransportsType { // TODO(pthatcher): Rename these kTransporTypeXXX, but update // Chromium at the same time. kNone, kRelay, kNoHost, kAll }; // https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-24#section-4.1.1 enum BundlePolicy { kBundlePolicyBalanced, kBundlePolicyMaxBundle, kBundlePolicyMaxCompat }; // https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-24#section-4.1.1 enum RtcpMuxPolicy { kRtcpMuxPolicyNegotiate, kRtcpMuxPolicyRequire, }; enum TcpCandidatePolicy { kTcpCandidatePolicyEnabled, kTcpCandidatePolicyDisabled }; enum CandidateNetworkPolicy { kCandidateNetworkPolicyAll, kCandidateNetworkPolicyLowCost }; enum ContinualGatheringPolicy { GATHER_ONCE, GATHER_CONTINUALLY }; enum class RTCConfigurationType { // A configuration that is safer to use, despite not having the best // performance. Currently this is the default configuration. kSafe, // An aggressive configuration that has better performance, although it // may be riskier and may need extra support in the application. kAggressive }; // TODO(hbos): Change into class with private data and public getters. // TODO(nisse): In particular, accessing fields directly from an // application is brittle, since the organization mirrors the // organization of the implementation, which isn't stable. So we // need getters and setters at least for fields which applications // are interested in. struct RTC_EXPORT RTCConfiguration { // This struct is subject to reorganization, both for naming // consistency, and to group settings to match where they are used // in the implementation. To do that, we need getter and setter // methods for all settings which are of interest to applications, // Chrome in particular. RTCConfiguration(); RTCConfiguration(const RTCConfiguration&); explicit RTCConfiguration(RTCConfigurationType type); ~RTCConfiguration(); bool operator==(const RTCConfiguration& o) const; bool operator!=(const RTCConfiguration& o) const; bool dscp() const { return media_config.enable_dscp; } void set_dscp(bool enable) { media_config.enable_dscp = enable; } bool cpu_adaptation() const { return media_config.video.enable_cpu_adaptation; } void set_cpu_adaptation(bool enable) { media_config.video.enable_cpu_adaptation = enable; } bool suspend_below_min_bitrate() const { return media_config.video.suspend_below_min_bitrate; } void set_suspend_below_min_bitrate(bool enable) { media_config.video.suspend_below_min_bitrate = enable; } bool prerenderer_smoothing() const { return media_config.video.enable_prerenderer_smoothing; } void set_prerenderer_smoothing(bool enable) { media_config.video.enable_prerenderer_smoothing = enable; } bool experiment_cpu_load_estimator() const { return media_config.video.experiment_cpu_load_estimator; } void set_experiment_cpu_load_estimator(bool enable) { media_config.video.experiment_cpu_load_estimator = enable; } int audio_rtcp_report_interval_ms() const { return media_config.audio.rtcp_report_interval_ms; } void set_audio_rtcp_report_interval_ms(int audio_rtcp_report_interval_ms) { media_config.audio.rtcp_report_interval_ms = audio_rtcp_report_interval_ms; } int video_rtcp_report_interval_ms() const { return media_config.video.rtcp_report_interval_ms; } void set_video_rtcp_report_interval_ms(int video_rtcp_report_interval_ms) { media_config.video.rtcp_report_interval_ms = video_rtcp_report_interval_ms; } static const int kUndefined = -1; // Default maximum number of packets in the audio jitter buffer. static const int kAudioJitterBufferMaxPackets = 200; // ICE connection receiving timeout for aggressive configuration. static const int kAggressiveIceConnectionReceivingTimeout = 1000; //////////////////////////////////////////////////////////////////////// // The below few fields mirror the standard RTCConfiguration dictionary: // https://w3c.github.io/webrtc-pc/#rtcconfiguration-dictionary //////////////////////////////////////////////////////////////////////// // TODO(pthatcher): Rename this ice_servers, but update Chromium // at the same time. IceServers servers; // TODO(pthatcher): Rename this ice_transport_type, but update // Chromium at the same time. IceTransportsType type = kAll; BundlePolicy bundle_policy = kBundlePolicyBalanced; RtcpMuxPolicy rtcp_mux_policy = kRtcpMuxPolicyRequire; std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates; int ice_candidate_pool_size = 0; ////////////////////////////////////////////////////////////////////////// // The below fields correspond to constraints from the deprecated // constraints interface for constructing a PeerConnection. // // absl::optional fields can be "missing", in which case the implementation // default will be used. ////////////////////////////////////////////////////////////////////////// // If set to true, don't gather IPv6 ICE candidates. // TODO(deadbeef): Remove this? IPv6 support has long stopped being // experimental bool disable_ipv6 = false; // If set to true, don't gather IPv6 ICE candidates on Wi-Fi. // Only intended to be used on specific devices. Certain phones disable IPv6 // when the screen is turned off and it would be better to just disable the // IPv6 ICE candidates on Wi-Fi in those cases. bool disable_ipv6_on_wifi = false; // By default, the PeerConnection will use a limited number of IPv6 network // interfaces, in order to avoid too many ICE candidate pairs being created // and delaying ICE completion. // // Can be set to INT_MAX to effectively disable the limit. int max_ipv6_networks = cricket::kDefaultMaxIPv6Networks; // Exclude link-local network interfaces // from consideration for gathering ICE candidates. bool disable_link_local_networks = false; // If set to true, use RTP data channels instead of SCTP. // TODO(deadbeef): Remove this. We no longer commit to supporting RTP data // channels, though some applications are still working on moving off of // them. bool enable_rtp_data_channel = false; // Minimum bitrate at which screencast video tracks will be encoded at. // This means adding padding bits up to this bitrate, which can help // when switching from a static scene to one with motion. absl::optional<int> screencast_min_bitrate; // Use new combined audio/video bandwidth estimation? absl::optional<bool> combined_audio_video_bwe; // TODO(bugs.webrtc.org/9891) - Move to crypto_options // Can be used to disable DTLS-SRTP. This should never be done, but can be // useful for testing purposes, for example in setting up a loopback call // with a single PeerConnection. absl::optional<bool> enable_dtls_srtp; ///////////////////////////////////////////////// // The below fields are not part of the standard. ///////////////////////////////////////////////// // Can be used to disable TCP candidate generation. TcpCandidatePolicy tcp_candidate_policy = kTcpCandidatePolicyEnabled; // Can be used to avoid gathering candidates for a "higher cost" network, // if a lower cost one exists. For example, if both Wi-Fi and cellular // interfaces are available, this could be used to avoid using the cellular // interface. CandidateNetworkPolicy candidate_network_policy = kCandidateNetworkPolicyAll; // The maximum number of packets that can be stored in the NetEq audio // jitter buffer. Can be reduced to lower tolerated audio latency. int audio_jitter_buffer_max_packets = kAudioJitterBufferMaxPackets; // Whether to use the NetEq "fast mode" which will accelerate audio quicker // if it falls behind. bool audio_jitter_buffer_fast_accelerate = false; // The minimum delay in milliseconds for the audio jitter buffer. int audio_jitter_buffer_min_delay_ms = 0; // Whether the audio jitter buffer adapts the delay to retransmitted // packets. bool audio_jitter_buffer_enable_rtx_handling = false; // Timeout in milliseconds before an ICE candidate pair is considered to be // "not receiving", after which a lower priority candidate pair may be // selected. int ice_connection_receiving_timeout = kUndefined; // Interval in milliseconds at which an ICE "backup" candidate pair will be // pinged. This is a candidate pair which is not actively in use, but may // be switched to if the active candidate pair becomes unusable. // // This is relevant mainly to Wi-Fi/cell handoff; the application may not // want this backup cellular candidate pair pinged frequently, since it // consumes data/battery. int ice_backup_candidate_pair_ping_interval = kUndefined; // Can be used to enable continual gathering, which means new candidates // will be gathered as network interfaces change. Note that if continual // gathering is used, the candidate removal API should also be used, to // avoid an ever-growing list of candidates. ContinualGatheringPolicy continual_gathering_policy = GATHER_ONCE; // If set to true, candidate pairs will be pinged in order of most likely // to work (which means using a TURN server, generally), rather than in // standard priority order. bool prioritize_most_likely_ice_candidate_pairs = false; // Implementation defined settings. A public member only for the benefit of // the implementation. Applications must not access it directly, and should // instead use provided accessor methods, e.g., set_cpu_adaptation. struct cricket::MediaConfig media_config; // If set to true, only one preferred TURN allocation will be used per // network interface. UDP is preferred over TCP and IPv6 over IPv4. This // can be used to cut down on the number of candidate pairings. // Deprecated. TODO(webrtc:11026) Remove this flag once the downstream // dependency is removed. bool prune_turn_ports = false; // The policy used to prune turn port. PortPrunePolicy turn_port_prune_policy = NO_PRUNE; PortPrunePolicy GetTurnPortPrunePolicy() const { return prune_turn_ports ? PRUNE_BASED_ON_PRIORITY : turn_port_prune_policy; } // If set to true, this means the ICE transport should presume TURN-to-TURN // candidate pairs will succeed, even before a binding response is received. // This can be used to optimize the initial connection time, since the DTLS // handshake can begin immediately. bool presume_writable_when_fully_relayed = false; // If true, "renomination" will be added to the ice options in the transport // description. // See: https://tools.ietf.org/html/draft-thatcher-ice-renomination-00 bool enable_ice_renomination = false; // If true, the ICE role is re-determined when the PeerConnection sets a // local transport description that indicates an ICE restart. // // This is standard RFC5245 ICE behavior, but causes unnecessary role // thrashing, so an application may wish to avoid it. This role // re-determining was removed in ICEbis (ICE v2). bool redetermine_role_on_ice_restart = true; // This flag is only effective when |continual_gathering_policy| is // GATHER_CONTINUALLY. // // If true, after the ICE transport type is changed such that new types of // ICE candidates are allowed by the new transport type, e.g. from // IceTransportsType::kRelay to IceTransportsType::kAll, candidates that // have been gathered by the ICE transport but not matching the previous // transport type and as a result not observed by PeerConnectionObserver, // will be surfaced to the observer. bool surface_ice_candidates_on_ice_transport_type_changed = false; // The following fields define intervals in milliseconds at which ICE // connectivity checks are sent. // // We consider ICE is "strongly connected" for an agent when there is at // least one candidate pair that currently succeeds in connectivity check // from its direction i.e. sending a STUN ping and receives a STUN ping // response, AND all candidate pairs have sent a minimum number of pings for // connectivity (this number is implementation-specific). Otherwise, ICE is // considered in "weak connectivity". // // Note that the above notion of strong and weak connectivity is not defined // in RFC 5245, and they apply to our current ICE implementation only. // // 1) ice_check_interval_strong_connectivity defines the interval applied to // ALL candidate pairs when ICE is strongly connected, and it overrides the // default value of this interval in the ICE implementation; // 2) ice_check_interval_weak_connectivity defines the counterpart for ALL // pairs when ICE is weakly connected, and it overrides the default value of // this interval in the ICE implementation; // 3) ice_check_min_interval defines the minimal interval (equivalently the // maximum rate) that overrides the above two intervals when either of them // is less. absl::optional<int> ice_check_interval_strong_connectivity; absl::optional<int> ice_check_interval_weak_connectivity; absl::optional<int> ice_check_min_interval; // The min time period for which a candidate pair must wait for response to // connectivity checks before it becomes unwritable. This parameter // overrides the default value in the ICE implementation if set. absl::optional<int> ice_unwritable_timeout; // The min number of connectivity checks that a candidate pair must sent // without receiving response before it becomes unwritable. This parameter // overrides the default value in the ICE implementation if set. absl::optional<int> ice_unwritable_min_checks; // The min time period for which a candidate pair must wait for response to // connectivity checks it becomes inactive. This parameter overrides the // default value in the ICE implementation if set. absl::optional<int> ice_inactive_timeout; // The interval in milliseconds at which STUN candidates will resend STUN // binding requests to keep NAT bindings open. absl::optional<int> stun_candidate_keepalive_interval; // Optional TurnCustomizer. // With this class one can modify outgoing TURN messages. // The object passed in must remain valid until PeerConnection::Close() is // called. webrtc::TurnCustomizer* turn_customizer = nullptr; // Preferred network interface. // A candidate pair on a preferred network has a higher precedence in ICE // than one on an un-preferred network, regardless of priority or network // cost. absl::optional<rtc::AdapterType> network_preference; // Configure the SDP semantics used by this PeerConnection. Note that the // WebRTC 1.0 specification requires kUnifiedPlan semantics. The // RtpTransceiver API is only available with kUnifiedPlan semantics. // // kPlanB will cause PeerConnection to create offers and answers with at // most one audio and one video m= section with multiple RtpSenders and // RtpReceivers specified as multiple a=ssrc lines within the section. This // will also cause PeerConnection to ignore all but the first m= section of // the same media type. // // kUnifiedPlan will cause PeerConnection to create offers and answers with // multiple m= sections where each m= section maps to one RtpSender and one // RtpReceiver (an RtpTransceiver), either both audio or both video. This // will also cause PeerConnection to ignore all but the first a=ssrc lines // that form a Plan B stream. // // For users who wish to send multiple audio/video streams and need to stay // interoperable with legacy WebRTC implementations or use legacy APIs, // specify kPlanB. // // For all other users, specify kUnifiedPlan. SdpSemantics sdp_semantics = SdpSemantics::kPlanB; // TODO(bugs.webrtc.org/9891) - Move to crypto_options or remove. // Actively reset the SRTP parameters whenever the DTLS transports // underneath are reset for every offer/answer negotiation. // This is only intended to be a workaround for crbug.com/835958 // WARNING: This would cause RTP/RTCP packets decryption failure if not used // correctly. This flag will be deprecated soon. Do not rely on it. bool active_reset_srtp_params = false; // Defines advanced optional cryptographic settings related to SRTP and // frame encryption for native WebRTC. Setting this will overwrite any // settings set in PeerConnectionFactory (which is deprecated). absl::optional<CryptoOptions> crypto_options; // Configure if we should include the SDP attribute extmap-allow-mixed in // our offer on session level. bool offer_extmap_allow_mixed = true; // TURN logging identifier. // This identifier is added to a TURN allocation // and it intended to be used to be able to match client side // logs with TURN server logs. It will not be added if it's an empty string. std::string turn_logging_id; // Added to be able to control rollout of this feature. bool enable_implicit_rollback = false; // Whether network condition based codec switching is allowed. absl::optional<bool> allow_codec_switching; // The delay before doing a usage histogram report for long-lived // PeerConnections. Used for testing only. absl::optional<int> report_usage_pattern_delay_ms; // // Don't forget to update operator== if adding something. // }; // See: https://www.w3.org/TR/webrtc/#idl-def-rtcofferansweroptions struct RTCOfferAnswerOptions { static const int kUndefined = -1; static const int kMaxOfferToReceiveMedia = 1; // The default value for constraint offerToReceiveX:true. static const int kOfferToReceiveMediaTrue = 1; // These options are left as backwards compatibility for clients who need // "Plan B" semantics. Clients who have switched to "Unified Plan" semantics // should use the RtpTransceiver API (AddTransceiver) instead. // // offer_to_receive_X set to 1 will cause a media description to be // generated in the offer, even if no tracks of that type have been added. // Values greater than 1 are treated the same. // // If set to 0, the generated directional attribute will not include the // "recv" direction (meaning it will be "sendonly" or "inactive". int offer_to_receive_video = kUndefined; int offer_to_receive_audio = kUndefined; bool voice_activity_detection = true; bool ice_restart = false; // If true, will offer to BUNDLE audio/video/data together. Not to be // confused with RTCP mux (multiplexing RTP and RTCP together). bool use_rtp_mux = true; // If true, "a=packetization:<payload_type> raw" attribute will be offered // in the SDP for all video payload and accepted in the answer if offered. bool raw_packetization_for_video = false; // This will apply to all video tracks with a Plan B SDP offer/answer. int num_simulcast_layers = 1; // If true: Use SDP format from draft-ietf-mmusic-scdp-sdp-03 // If false: Use SDP format from draft-ietf-mmusic-sdp-sdp-26 or later bool use_obsolete_sctp_sdp = false; RTCOfferAnswerOptions() = default; RTCOfferAnswerOptions(int offer_to_receive_video, int offer_to_receive_audio, bool voice_activity_detection, bool ice_restart, bool use_rtp_mux) : offer_to_receive_video(offer_to_receive_video), offer_to_receive_audio(offer_to_receive_audio), voice_activity_detection(voice_activity_detection), ice_restart(ice_restart), use_rtp_mux(use_rtp_mux) {} }; // Used by GetStats to decide which stats to include in the stats reports. // |kStatsOutputLevelStandard| includes the standard stats for Javascript API; // |kStatsOutputLevelDebug| includes both the standard stats and additional // stats for debugging purposes. enum StatsOutputLevel { kStatsOutputLevelStandard, kStatsOutputLevelDebug, }; // Accessor methods to active local streams. // This method is not supported with kUnifiedPlan semantics. Please use // GetSenders() instead. virtual rtc::scoped_refptr<StreamCollectionInterface> local_streams() = 0; // Accessor methods to remote streams. // This method is not supported with kUnifiedPlan semantics. Please use // GetReceivers() instead. virtual rtc::scoped_refptr<StreamCollectionInterface> remote_streams() = 0; // Add a new MediaStream to be sent on this PeerConnection. // Note that a SessionDescription negotiation is needed before the // remote peer can receive the stream. // // This has been removed from the standard in favor of a track-based API. So, // this is equivalent to simply calling AddTrack for each track within the // stream, with the one difference that if "stream->AddTrack(...)" is called // later, the PeerConnection will automatically pick up the new track. Though // this functionality will be deprecated in the future. // // This method is not supported with kUnifiedPlan semantics. Please use // AddTrack instead. virtual bool AddStream(MediaStreamInterface* stream) = 0; // Remove a MediaStream from this PeerConnection. // Note that a SessionDescription negotiation is needed before the // remote peer is notified. // // This method is not supported with kUnifiedPlan semantics. Please use // RemoveTrack instead. virtual void RemoveStream(MediaStreamInterface* stream) = 0; // Add a new MediaStreamTrack to be sent on this PeerConnection, and return // the newly created RtpSender. The RtpSender will be associated with the // streams specified in the |stream_ids| list. // // Errors: // - INVALID_PARAMETER: |track| is null, has a kind other than audio or video, // or a sender already exists for the track. // - INVALID_STATE: The PeerConnection is closed. virtual RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> AddTrack( rtc::scoped_refptr<MediaStreamTrackInterface> track, const std::vector<std::string>& stream_ids) = 0; // Remove an RtpSender from this PeerConnection. // Returns true on success. // TODO(steveanton): Replace with signature that returns RTCError. virtual bool RemoveTrack(RtpSenderInterface* sender) = 0; // Plan B semantics: Removes the RtpSender from this PeerConnection. // Unified Plan semantics: Stop sending on the RtpSender and mark the // corresponding RtpTransceiver direction as no longer sending. // // Errors: // - INVALID_PARAMETER: |sender| is null or (Plan B only) the sender is not // associated with this PeerConnection. // - INVALID_STATE: PeerConnection is closed. // TODO(bugs.webrtc.org/9534): Rename to RemoveTrack once the other signature // is removed. virtual RTCError RemoveTrackNew( rtc::scoped_refptr<RtpSenderInterface> sender); // AddTransceiver creates a new RtpTransceiver and adds it to the set of // transceivers. Adding a transceiver will cause future calls to CreateOffer // to add a media description for the corresponding transceiver. // // The initial value of |mid| in the returned transceiver is null. Setting a // new session description may change it to a non-null value. // // https://w3c.github.io/webrtc-pc/#dom-rtcpeerconnection-addtransceiver // // Optionally, an RtpTransceiverInit structure can be specified to configure // the transceiver from construction. If not specified, the transceiver will // default to having a direction of kSendRecv and not be part of any streams. // // These methods are only available when Unified Plan is enabled (see // RTCConfiguration). // // Common errors: // - INTERNAL_ERROR: The configuration does not have Unified Plan enabled. // Adds a transceiver with a sender set to transmit the given track. The kind // of the transceiver (and sender/receiver) will be derived from the kind of // the track. // Errors: // - INVALID_PARAMETER: |track| is null. virtual RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>> AddTransceiver(rtc::scoped_refptr<MediaStreamTrackInterface> track) = 0; virtual RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>> AddTransceiver(rtc::scoped_refptr<MediaStreamTrackInterface> track, const RtpTransceiverInit& init) = 0; // Adds a transceiver with the given kind. Can either be MEDIA_TYPE_AUDIO or // MEDIA_TYPE_VIDEO. // Errors: // - INVALID_PARAMETER: |media_type| is not MEDIA_TYPE_AUDIO or // MEDIA_TYPE_VIDEO. virtual RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>> AddTransceiver(cricket::MediaType media_type) = 0; virtual RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>> AddTransceiver(cricket::MediaType media_type, const RtpTransceiverInit& init) = 0; // Creates a sender without a track. Can be used for "early media"/"warmup" // use cases, where the application may want to negotiate video attributes // before a track is available to send. // // The standard way to do this would be through "addTransceiver", but we // don't support that API yet. // // |kind| must be "audio" or "video". // // |stream_id| is used to populate the msid attribute; if empty, one will // be generated automatically. // // This method is not supported with kUnifiedPlan semantics. Please use // AddTransceiver instead. virtual rtc::scoped_refptr<RtpSenderInterface> CreateSender( const std::string& kind, const std::string& stream_id) = 0; // If Plan B semantics are specified, gets all RtpSenders, created either // through AddStream, AddTrack, or CreateSender. All senders of a specific // media type share the same media description. // // If Unified Plan semantics are specified, gets the RtpSender for each // RtpTransceiver. virtual std::vector<rtc::scoped_refptr<RtpSenderInterface>> GetSenders() const = 0; // If Plan B semantics are specified, gets all RtpReceivers created when a // remote description is applied. All receivers of a specific media type share // the same media description. It is also possible to have a media description // with no associated RtpReceivers, if the directional attribute does not // indicate that the remote peer is sending any media. // // If Unified Plan semantics are specified, gets the RtpReceiver for each // RtpTransceiver. virtual std::vector<rtc::scoped_refptr<RtpReceiverInterface>> GetReceivers() const = 0; // Get all RtpTransceivers, created either through AddTransceiver, AddTrack or // by a remote description applied with SetRemoteDescription. // // Note: This method is only available when Unified Plan is enabled (see // RTCConfiguration). virtual std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> GetTransceivers() const = 0; // The legacy non-compliant GetStats() API. This correspond to the // callback-based version of getStats() in JavaScript. The returned metrics // are UNDOCUMENTED and many of them rely on implementation-specific details. // The goal is to DELETE THIS VERSION but we can't today because it is heavily // relied upon by third parties. See https://crbug.com/822696. // // This version is wired up into Chrome. Any stats implemented are // automatically exposed to the Web Platform. This has BYPASSED the Chrome // release processes for years and lead to cross-browser incompatibility // issues and web application reliance on Chrome-only behavior. // // This API is in "maintenance mode", serious regressions should be fixed but // adding new stats is highly discouraged. // // TODO(hbos): Deprecate and remove this when third parties have migrated to // the spec-compliant GetStats() API. https://crbug.com/822696 virtual bool GetStats(StatsObserver* observer, MediaStreamTrackInterface* track, // Optional StatsOutputLevel level) = 0; // The spec-compliant GetStats() API. This correspond to the promise-based // version of getStats() in JavaScript. Implementation status is described in // api/stats/rtcstats_objects.h. For more details on stats, see spec: // https://w3c.github.io/webrtc-pc/#dom-rtcpeerconnection-getstats // TODO(hbos): Takes shared ownership, use rtc::scoped_refptr<> instead. This // requires stop overriding the current version in third party or making third // party calls explicit to avoid ambiguity during switch. Make the future // version abstract as soon as third party projects implement it. virtual void GetStats(RTCStatsCollectorCallback* callback) = 0; // Spec-compliant getStats() performing the stats selection algorithm with the // sender. https://w3c.github.io/webrtc-pc/#dom-rtcrtpsender-getstats virtual void GetStats( rtc::scoped_refptr<RtpSenderInterface> selector, rtc::scoped_refptr<RTCStatsCollectorCallback> callback) = 0; // Spec-compliant getStats() performing the stats selection algorithm with the // receiver. https://w3c.github.io/webrtc-pc/#dom-rtcrtpreceiver-getstats virtual void GetStats( rtc::scoped_refptr<RtpReceiverInterface> selector, rtc::scoped_refptr<RTCStatsCollectorCallback> callback) = 0; // Clear cached stats in the RTCStatsCollector. // Exposed for testing while waiting for automatic cache clear to work. // https://bugs.webrtc.org/8693 virtual void ClearStatsCache() {} // Create a data channel with the provided config, or default config if none // is provided. Note that an offer/answer negotiation is still necessary // before the data channel can be used. // // Also, calling CreateDataChannel is the only way to get a data "m=" section // in SDP, so it should be done before CreateOffer is called, if the // application plans to use data channels. virtual rtc::scoped_refptr<DataChannelInterface> CreateDataChannel( const std::string& label, const DataChannelInit* config) = 0; // NOTE: For the following 6 methods, it's only safe to dereference the // SessionDescriptionInterface on signaling_thread() (for example, calling // ToString). // Returns the more recently applied description; "pending" if it exists, and // otherwise "current". See below. virtual const SessionDescriptionInterface* local_description() const = 0; virtual const SessionDescriptionInterface* remote_description() const = 0; // A "current" description the one currently negotiated from a complete // offer/answer exchange. virtual const SessionDescriptionInterface* current_local_description() const = 0; virtual const SessionDescriptionInterface* current_remote_description() const = 0; // A "pending" description is one that's part of an incomplete offer/answer // exchange (thus, either an offer or a pranswer). Once the offer/answer // exchange is finished, the "pending" description will become "current". virtual const SessionDescriptionInterface* pending_local_description() const = 0; virtual const SessionDescriptionInterface* pending_remote_description() const = 0; // Tells the PeerConnection that ICE should be restarted. This triggers a need // for negotiation and subsequent CreateOffer() calls will act as if // RTCOfferAnswerOptions::ice_restart is true. // https://w3c.github.io/webrtc-pc/#dom-rtcpeerconnection-restartice // TODO(hbos): Remove default implementation when downstream projects // implement this. virtual void RestartIce() = 0; // Create a new offer. // The CreateSessionDescriptionObserver callback will be called when done. virtual void CreateOffer(CreateSessionDescriptionObserver* observer, const RTCOfferAnswerOptions& options) = 0; // Create an answer to an offer. // The CreateSessionDescriptionObserver callback will be called when done. virtual void CreateAnswer(CreateSessionDescriptionObserver* observer, const RTCOfferAnswerOptions& options) = 0; // Sets the local session description. // // According to spec, the local session description MUST be the same as was // returned by CreateOffer() or CreateAnswer() or else the operation should // fail. Our implementation however allows some amount of "SDP munging", but // please note that this is HIGHLY DISCOURAGED. If you do not intent to munge // SDP, the method below that doesn't take |desc| as an argument will create // the offer or answer for you. // // The observer is invoked as soon as the operation completes, which could be // before or after the SetLocalDescription() method has exited. virtual void SetLocalDescription( std::unique_ptr<SessionDescriptionInterface> desc, rtc::scoped_refptr<SetLocalDescriptionObserverInterface> observer) {} // Creates an offer or answer (depending on current signaling state) and sets // it as the local session description. // // The observer is invoked as soon as the operation completes, which could be // before or after the SetLocalDescription() method has exited. virtual void SetLocalDescription( rtc::scoped_refptr<SetLocalDescriptionObserverInterface> observer) {} // Like SetLocalDescription() above, but the observer is invoked with a delay // after the operation completes. This helps avoid recursive calls by the // observer but also makes it possible for states to change in-between the // operation completing and the observer getting called. This makes them racy // for synchronizing peer connection states to the application. // TODO(https://crbug.com/webrtc/11798): Delete these methods in favor of the // ones taking SetLocalDescriptionObserverInterface as argument. virtual void SetLocalDescription(SetSessionDescriptionObserver* observer, SessionDescriptionInterface* desc) = 0; virtual void SetLocalDescription(SetSessionDescriptionObserver* observer) {} // Sets the remote session description. // // (Unlike "SDP munging" before SetLocalDescription(), modifying a remote // offer or answer is allowed by the spec.) // // The observer is invoked as soon as the operation completes, which could be // before or after the SetRemoteDescription() method has exited. virtual void SetRemoteDescription( std::unique_ptr<SessionDescriptionInterface> desc, rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) = 0; // Like SetRemoteDescription() above, but the observer is invoked with a delay // after the operation completes. This helps avoid recursive calls by the // observer but also makes it possible for states to change in-between the // operation completing and the observer getting called. This makes them racy // for synchronizing peer connection states to the application. // TODO(https://crbug.com/webrtc/11798): Delete this method in favor of the // ones taking SetRemoteDescriptionObserverInterface as argument. virtual void SetRemoteDescription(SetSessionDescriptionObserver* observer, SessionDescriptionInterface* desc) {} // According to spec, we must only fire "negotiationneeded" if the Operations // Chain is empty. This method takes care of validating an event previously // generated with PeerConnectionObserver::OnNegotiationNeededEvent() to make // sure that even if there was a delay (e.g. due to a PostTask) between the // event being generated and the time of firing, the Operations Chain is empty // and the event is still valid to be fired. virtual bool ShouldFireNegotiationNeededEvent(uint32_t event_id) { return true; } virtual PeerConnectionInterface::RTCConfiguration GetConfiguration() = 0; // Sets the PeerConnection's global configuration to |config|. // // The members of |config| that may be changed are |type|, |servers|, // |ice_candidate_pool_size| and |prune_turn_ports| (though the candidate // pool size can't be changed after the first call to SetLocalDescription). // Note that this means the BUNDLE and RTCP-multiplexing policies cannot be // changed with this method. // // Any changes to STUN/TURN servers or ICE candidate policy will affect the // next gathering phase, and cause the next call to createOffer to generate // new ICE credentials, as described in JSEP. This also occurs when // |prune_turn_ports| changes, for the same reasoning. // // If an error occurs, returns false and populates |error| if non-null: // - INVALID_MODIFICATION if |config| contains a modified parameter other // than one of the parameters listed above. // - INVALID_RANGE if |ice_candidate_pool_size| is out of range. // - SYNTAX_ERROR if parsing an ICE server URL failed. // - INVALID_PARAMETER if a TURN server is missing |username| or |password|. // - INTERNAL_ERROR if an unexpected error occurred. // // TODO(nisse): Make this pure virtual once all Chrome subclasses of // PeerConnectionInterface implement it. virtual RTCError SetConfiguration( const PeerConnectionInterface::RTCConfiguration& config); // Provides a remote candidate to the ICE Agent. // A copy of the |candidate| will be created and added to the remote // description. So the caller of this method still has the ownership of the // |candidate|. // TODO(hbos): The spec mandates chaining this operation onto the operations // chain; deprecate and remove this version in favor of the callback-based // signature. virtual bool AddIceCandidate(const IceCandidateInterface* candidate) = 0; // TODO(hbos): Remove default implementation once implemented by downstream // projects. virtual void AddIceCandidate(std::unique_ptr<IceCandidateInterface> candidate, std::function<void(RTCError)> callback) {} // Removes a group of remote candidates from the ICE agent. Needed mainly for // continual gathering, to avoid an ever-growing list of candidates as // networks come and go. Note that the candidates' transport_name must be set // to the MID of the m= section that generated the candidate. // TODO(bugs.webrtc.org/8395): Use IceCandidateInterface instead of // cricket::Candidate, which would avoid the transport_name oddity. virtual bool RemoveIceCandidates( const std::vector<cricket::Candidate>& candidates) = 0; // SetBitrate limits the bandwidth allocated for all RTP streams sent by // this PeerConnection. Other limitations might affect these limits and // are respected (for example "b=AS" in SDP). // // Setting |current_bitrate_bps| will reset the current bitrate estimate // to the provided value. virtual RTCError SetBitrate(const BitrateSettings& bitrate) = 0; // Enable/disable playout of received audio streams. Enabled by default. Note // that even if playout is enabled, streams will only be played out if the // appropriate SDP is also applied. Setting |playout| to false will stop // playout of the underlying audio device but starts a task which will poll // for audio data every 10ms to ensure that audio processing happens and the // audio statistics are updated. // TODO(henrika): deprecate and remove this. virtual void SetAudioPlayout(bool playout) {} // Enable/disable recording of transmitted audio streams. Enabled by default. // Note that even if recording is enabled, streams will only be recorded if // the appropriate SDP is also applied. // TODO(henrika): deprecate and remove this. virtual void SetAudioRecording(bool recording) {} // Looks up the DtlsTransport associated with a MID value. // In the Javascript API, DtlsTransport is a property of a sender, but // because the PeerConnection owns the DtlsTransport in this implementation, // it is better to look them up on the PeerConnection. virtual rtc::scoped_refptr<DtlsTransportInterface> LookupDtlsTransportByMid( const std::string& mid) = 0; // Returns the SCTP transport, if any. virtual rtc::scoped_refptr<SctpTransportInterface> GetSctpTransport() const = 0; // Returns the current SignalingState. virtual SignalingState signaling_state() = 0; // Returns an aggregate state of all ICE *and* DTLS transports. // This is left in place to avoid breaking native clients who expect our old, // nonstandard behavior. // TODO(jonasolsson): deprecate and remove this. virtual IceConnectionState ice_connection_state() = 0; // Returns an aggregated state of all ICE transports. virtual IceConnectionState standardized_ice_connection_state() = 0; // Returns an aggregated state of all ICE and DTLS transports. virtual PeerConnectionState peer_connection_state() = 0; virtual IceGatheringState ice_gathering_state() = 0; // Returns the current state of canTrickleIceCandidates per // https://w3c.github.io/webrtc-pc/#attributes-1 virtual absl::optional<bool> can_trickle_ice_candidates() { // TODO(crbug.com/708484): Remove default implementation. return absl::nullopt; } // When a resource is overused, the PeerConnection will try to reduce the load // on the sysem, for example by reducing the resolution or frame rate of // encoded streams. The Resource API allows injecting platform-specific usage // measurements. The conditions to trigger kOveruse or kUnderuse are up to the // implementation. // TODO(hbos): Make pure virtual when implemented by downstream projects. virtual void AddAdaptationResource(rtc::scoped_refptr<Resource> resource) {} // Start RtcEventLog using an existing output-sink. Takes ownership of // |output| and passes it on to Call, which will take the ownership. If the // operation fails the output will be closed and deallocated. The event log // will send serialized events to the output object every |output_period_ms|. // Applications using the event log should generally make their own trade-off // regarding the output period. A long period is generally more efficient, // with potential drawbacks being more bursty thread usage, and more events // lost in case the application crashes. If the |output_period_ms| argument is // omitted, webrtc selects a default deemed to be workable in most cases. virtual bool StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output, int64_t output_period_ms) = 0; virtual bool StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output) = 0; // Stops logging the RtcEventLog. virtual void StopRtcEventLog() = 0; // Terminates all media, closes the transports, and in general releases any // resources used by the PeerConnection. This is an irreversible operation. // // Note that after this method completes, the PeerConnection will no longer // use the PeerConnectionObserver interface passed in on construction, and // thus the observer object can be safely destroyed. virtual void Close() = 0; // The thread on which all PeerConnectionObserver callbacks will be invoked, // as well as callbacks for other classes such as DataChannelObserver. // // Also the only thread on which it's safe to use SessionDescriptionInterface // pointers. // TODO(deadbeef): Make pure virtual when all subclasses implement it. virtual rtc::Thread* signaling_thread() const { return nullptr; } protected: // Dtor protected as objects shouldn't be deleted via this interface. ~PeerConnectionInterface() override = default; }; // PeerConnection callback interface, used for RTCPeerConnection events. // Application should implement these methods. class PeerConnectionObserver { public: virtual ~PeerConnectionObserver() = default; // Triggered when the SignalingState changed. virtual void OnSignalingChange( PeerConnectionInterface::SignalingState new_state) = 0; // Triggered when media is received on a new stream from remote peer. virtual void OnAddStream(rtc::scoped_refptr<MediaStreamInterface> stream) {} // Triggered when a remote peer closes a stream. virtual void OnRemoveStream(rtc::scoped_refptr<MediaStreamInterface> stream) { } // Triggered when a remote peer opens a data channel. virtual void OnDataChannel( rtc::scoped_refptr<DataChannelInterface> data_channel) = 0; // Triggered when renegotiation is needed. For example, an ICE restart // has begun. // TODO(hbos): Delete in favor of OnNegotiationNeededEvent() when downstream // projects have migrated. virtual void OnRenegotiationNeeded() {} // Used to fire spec-compliant onnegotiationneeded events, which should only // fire when the Operations Chain is empty. The observer is responsible for // queuing a task (e.g. Chromium: jump to main thread) to maybe fire the // event. The event identified using |event_id| must only fire if // PeerConnection::ShouldFireNegotiationNeededEvent() returns true since it is // possible for the event to become invalidated by operations subsequently // chained. virtual void OnNegotiationNeededEvent(uint32_t event_id) {} // Called any time the legacy IceConnectionState changes. // // Note that our ICE states lag behind the standard slightly. The most // notable differences include the fact that "failed" occurs after 15 // seconds, not 30, and this actually represents a combination ICE + DTLS // state, so it may be "failed" if DTLS fails while ICE succeeds. // // TODO(jonasolsson): deprecate and remove this. virtual void OnIceConnectionChange( PeerConnectionInterface::IceConnectionState new_state) {} // Called any time the standards-compliant IceConnectionState changes. virtual void OnStandardizedIceConnectionChange( PeerConnectionInterface::IceConnectionState new_state) {} // Called any time the PeerConnectionState changes. virtual void OnConnectionChange( PeerConnectionInterface::PeerConnectionState new_state) {} // Called any time the IceGatheringState changes. virtual void OnIceGatheringChange( PeerConnectionInterface::IceGatheringState new_state) = 0; // A new ICE candidate has been gathered. virtual void OnIceCandidate(const IceCandidateInterface* candidate) = 0; // Gathering of an ICE candidate failed. // See https://w3c.github.io/webrtc-pc/#event-icecandidateerror // |host_candidate| is a stringified socket address. virtual void OnIceCandidateError(const std::string& host_candidate, const std::string& url, int error_code, const std::string& error_text) {} // Gathering of an ICE candidate failed. // See https://w3c.github.io/webrtc-pc/#event-icecandidateerror virtual void OnIceCandidateError(const std::string& address, int port, const std::string& url, int error_code, const std::string& error_text) {} // Ice candidates have been removed. // TODO(honghaiz): Make this a pure virtual method when all its subclasses // implement it. virtual void OnIceCandidatesRemoved( const std::vector<cricket::Candidate>& candidates) {} // Called when the ICE connection receiving status changes. virtual void OnIceConnectionReceivingChange(bool receiving) {} // Called when the selected candidate pair for the ICE connection changes. virtual void OnIceSelectedCandidatePairChanged( const cricket::CandidatePairChangeEvent& event) {} // This is called when a receiver and its track are created. // TODO(zhihuang): Make this pure virtual when all subclasses implement it. // Note: This is called with both Plan B and Unified Plan semantics. Unified // Plan users should prefer OnTrack, OnAddTrack is only called as backwards // compatibility (and is called in the exact same situations as OnTrack). virtual void OnAddTrack( rtc::scoped_refptr<RtpReceiverInterface> receiver, const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& streams) {} // This is called when signaling indicates a transceiver will be receiving // media from the remote endpoint. This is fired during a call to // SetRemoteDescription. The receiving track can be accessed by: // |transceiver->receiver()->track()| and its associated streams by // |transceiver->receiver()->streams()|. // Note: This will only be called if Unified Plan semantics are specified. // This behavior is specified in section 2.2.8.2.5 of the "Set the // RTCSessionDescription" algorithm: // https://w3c.github.io/webrtc-pc/#set-description virtual void OnTrack( rtc::scoped_refptr<RtpTransceiverInterface> transceiver) {} // Called when signaling indicates that media will no longer be received on a // track. // With Plan B semantics, the given receiver will have been removed from the // PeerConnection and the track muted. // With Unified Plan semantics, the receiver will remain but the transceiver // will have changed direction to either sendonly or inactive. // https://w3c.github.io/webrtc-pc/#process-remote-track-removal // TODO(hbos,deadbeef): Make pure virtual when all subclasses implement it. virtual void OnRemoveTrack( rtc::scoped_refptr<RtpReceiverInterface> receiver) {} // Called when an interesting usage is detected by WebRTC. // An appropriate action is to add information about the context of the // PeerConnection and write the event to some kind of "interesting events" // log function. // The heuristics for defining what constitutes "interesting" are // implementation-defined. virtual void OnInterestingUsage(int usage_pattern) {} }; // PeerConnectionDependencies holds all of PeerConnections dependencies. // A dependency is distinct from a configuration as it defines significant // executable code that can be provided by a user of the API. // // All new dependencies should be added as a unique_ptr to allow the // PeerConnection object to be the definitive owner of the dependencies // lifetime making injection safer. struct RTC_EXPORT PeerConnectionDependencies final { explicit PeerConnectionDependencies(PeerConnectionObserver* observer_in); // This object is not copyable or assignable. PeerConnectionDependencies(const PeerConnectionDependencies&) = delete; PeerConnectionDependencies& operator=(const PeerConnectionDependencies&) = delete; // This object is only moveable. PeerConnectionDependencies(PeerConnectionDependencies&&); PeerConnectionDependencies& operator=(PeerConnectionDependencies&&) = default; ~PeerConnectionDependencies(); // Mandatory dependencies PeerConnectionObserver* observer = nullptr; // Optional dependencies // TODO(bugs.webrtc.org/7447): remove port allocator once downstream is // updated. For now, you can only set one of allocator and // packet_socket_factory, not both. std::unique_ptr<cricket::PortAllocator> allocator; std::unique_ptr<rtc::PacketSocketFactory> packet_socket_factory; // Factory for creating resolvers that look up hostnames in DNS std::unique_ptr<webrtc::AsyncDnsResolverFactoryInterface> async_dns_resolver_factory; // Deprecated - use async_dns_resolver_factory std::unique_ptr<webrtc::AsyncResolverFactory> async_resolver_factory; std::unique_ptr<webrtc::IceTransportFactory> ice_transport_factory; std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator; std::unique_ptr<rtc::SSLCertificateVerifier> tls_cert_verifier; std::unique_ptr<webrtc::VideoBitrateAllocatorFactory> video_bitrate_allocator_factory; }; // PeerConnectionFactoryDependencies holds all of the PeerConnectionFactory // dependencies. All new dependencies should be added here instead of // overloading the function. This simplifies dependency injection and makes it // clear which are mandatory and optional. If possible please allow the peer // connection factory to take ownership of the dependency by adding a unique_ptr // to this structure. struct RTC_EXPORT PeerConnectionFactoryDependencies final { PeerConnectionFactoryDependencies(); // This object is not copyable or assignable. PeerConnectionFactoryDependencies(const PeerConnectionFactoryDependencies&) = delete; PeerConnectionFactoryDependencies& operator=( const PeerConnectionFactoryDependencies&) = delete; // This object is only moveable. PeerConnectionFactoryDependencies(PeerConnectionFactoryDependencies&&); PeerConnectionFactoryDependencies& operator=( PeerConnectionFactoryDependencies&&) = default; ~PeerConnectionFactoryDependencies(); // Optional dependencies rtc::Thread* network_thread = nullptr; rtc::Thread* worker_thread = nullptr; rtc::Thread* signaling_thread = nullptr; std::unique_ptr<TaskQueueFactory> task_queue_factory; std::unique_ptr<cricket::MediaEngineInterface> media_engine; std::unique_ptr<CallFactoryInterface> call_factory; std::unique_ptr<RtcEventLogFactoryInterface> event_log_factory; std::unique_ptr<FecControllerFactoryInterface> fec_controller_factory; std::unique_ptr<NetworkStatePredictorFactoryInterface> network_state_predictor_factory; std::unique_ptr<NetworkControllerFactoryInterface> network_controller_factory; // This will only be used if CreatePeerConnection is called without a // |port_allocator|, causing the default allocator and network manager to be // used. std::unique_ptr<rtc::NetworkMonitorFactory> network_monitor_factory; std::unique_ptr<NetEqFactory> neteq_factory; std::unique_ptr<SctpTransportFactoryInterface> sctp_factory; std::unique_ptr<WebRtcKeyValueConfig> trials; }; // PeerConnectionFactoryInterface is the factory interface used for creating // PeerConnection, MediaStream and MediaStreamTrack objects. // // The simplest method for obtaiing one, CreatePeerConnectionFactory will // create the required libjingle threads, socket and network manager factory // classes for networking if none are provided, though it requires that the // application runs a message loop on the thread that called the method (see // explanation below) // // If an application decides to provide its own threads and/or implementation // of networking classes, it should use the alternate // CreatePeerConnectionFactory method which accepts threads as input, and use // the CreatePeerConnection version that takes a PortAllocator as an argument. class RTC_EXPORT PeerConnectionFactoryInterface : public rtc::RefCountInterface { public: class Options { public: Options() {} // If set to true, created PeerConnections won't enforce any SRTP // requirement, allowing unsecured media. Should only be used for // testing/debugging. bool disable_encryption = false; // Deprecated. The only effect of setting this to true is that // CreateDataChannel will fail, which is not that useful. bool disable_sctp_data_channels = false; // If set to true, any platform-supported network monitoring capability // won't be used, and instead networks will only be updated via polling. // // This only has an effect if a PeerConnection is created with the default // PortAllocator implementation. bool disable_network_monitor = false; // Sets the network types to ignore. For instance, calling this with // ADAPTER_TYPE_ETHERNET | ADAPTER_TYPE_LOOPBACK will ignore Ethernet and // loopback interfaces. int network_ignore_mask = rtc::kDefaultNetworkIgnoreMask; // Sets the maximum supported protocol version. The highest version // supported by both ends will be used for the connection, i.e. if one // party supports DTLS 1.0 and the other DTLS 1.2, DTLS 1.0 will be used. rtc::SSLProtocolVersion ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12; // Sets crypto related options, e.g. enabled cipher suites. CryptoOptions crypto_options = CryptoOptions::NoGcm(); }; // Set the options to be used for subsequently created PeerConnections. virtual void SetOptions(const Options& options) = 0; // The preferred way to create a new peer connection. Simply provide the // configuration and a PeerConnectionDependencies structure. // TODO(benwright): Make pure virtual once downstream mock PC factory classes // are updated. virtual RTCErrorOr<rtc::scoped_refptr<PeerConnectionInterface>> CreatePeerConnectionOrError( const PeerConnectionInterface::RTCConfiguration& configuration, PeerConnectionDependencies dependencies); // Deprecated creator - does not return an error code on error. // TODO(bugs.webrtc.org:12238): Deprecate and remove. virtual rtc::scoped_refptr<PeerConnectionInterface> CreatePeerConnection( const PeerConnectionInterface::RTCConfiguration& configuration, PeerConnectionDependencies dependencies); // Deprecated; |allocator| and |cert_generator| may be null, in which case // default implementations will be used. // // |observer| must not be null. // // Note that this method does not take ownership of |observer|; it's the // responsibility of the caller to delete it. It can be safely deleted after // Close has been called on the returned PeerConnection, which ensures no // more observer callbacks will be invoked. virtual rtc::scoped_refptr<PeerConnectionInterface> CreatePeerConnection( const PeerConnectionInterface::RTCConfiguration& configuration, std::unique_ptr<cricket::PortAllocator> allocator, std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator, PeerConnectionObserver* observer); // Returns the capabilities of an RTP sender of type |kind|. // If for some reason you pass in MEDIA_TYPE_DATA, returns an empty structure. // TODO(orphis): Make pure virtual when all subclasses implement it. virtual RtpCapabilities GetRtpSenderCapabilities( cricket::MediaType kind) const; // Returns the capabilities of an RTP receiver of type |kind|. // If for some reason you pass in MEDIA_TYPE_DATA, returns an empty structure. // TODO(orphis): Make pure virtual when all subclasses implement it. virtual RtpCapabilities GetRtpReceiverCapabilities( cricket::MediaType kind) const; virtual rtc::scoped_refptr<MediaStreamInterface> CreateLocalMediaStream( const std::string& stream_id) = 0; // Creates an AudioSourceInterface. // |options| decides audio processing settings. virtual rtc::scoped_refptr<AudioSourceInterface> CreateAudioSource( const cricket::AudioOptions& options) = 0; // Creates a new local VideoTrack. The same |source| can be used in several // tracks. virtual rtc::scoped_refptr<VideoTrackInterface> CreateVideoTrack( const std::string& label, VideoTrackSourceInterface* source) = 0; // Creates an new AudioTrack. At the moment |source| can be null. virtual rtc::scoped_refptr<AudioTrackInterface> CreateAudioTrack( const std::string& label, AudioSourceInterface* source) = 0; // Starts AEC dump using existing file. Takes ownership of |file| and passes // it on to VoiceEngine (via other objects) immediately, which will take // the ownerhip. If the operation fails, the file will be closed. // A maximum file size in bytes can be specified. When the file size limit is // reached, logging is stopped automatically. If max_size_bytes is set to a // value <= 0, no limit will be used, and logging will continue until the // StopAecDump function is called. // TODO(webrtc:6463): Delete default implementation when downstream mocks // classes are updated. virtual bool StartAecDump(FILE* file, int64_t max_size_bytes) { return false; } // Stops logging the AEC dump. virtual void StopAecDump() = 0; protected: // Dtor and ctor protected as objects shouldn't be created or deleted via // this interface. PeerConnectionFactoryInterface() {} ~PeerConnectionFactoryInterface() override = default; }; // CreateModularPeerConnectionFactory is implemented in the "peerconnection" // build target, which doesn't pull in the implementations of every module // webrtc may use. // // If an application knows it will only require certain modules, it can reduce // webrtc's impact on its binary size by depending only on the "peerconnection" // target and the modules the application requires, using // CreateModularPeerConnectionFactory. For example, if an application // only uses WebRTC for audio, it can pass in null pointers for the // video-specific interfaces, and omit the corresponding modules from its // build. // // If |network_thread| or |worker_thread| are null, the PeerConnectionFactory // will create the necessary thread internally. If |signaling_thread| is null, // the PeerConnectionFactory will use the thread on which this method is called // as the signaling thread, wrapping it in an rtc::Thread object if needed. RTC_EXPORT rtc::scoped_refptr<PeerConnectionFactoryInterface> CreateModularPeerConnectionFactory( PeerConnectionFactoryDependencies dependencies); } // namespace webrtc #endif // API_PEER_CONNECTION_INTERFACE_H_
[ "zhangtongxiao@fenbi.com" ]
zhangtongxiao@fenbi.com
531a161257e59c93e70149173e31799d121bb93c
3480576fb99c23fd9e0923b7779aacf79cc8d715
/test1/8.cpp
e1d008c43e0d731fd5a974cf1983d6d2faa15db5
[]
no_license
podobry-m/2sem
0ee7dbb46fe123cff51d44696499ae56f25f0c8f
96f3f2ebf9e004190a9620f2b610810194a37f00
refs/heads/master
2023-04-26T12:15:08.127371
2021-05-22T14:45:16
2021-05-22T14:45:16
337,356,595
0
0
null
null
null
null
UTF-8
C++
false
false
298
cpp
void fix_list(BehaviorPattern *root) { BehaviorPattern *t = root; if (root != NULL) { root->prev = NULL; do { if (t->next == NULL) break; (t->next)->prev = t; t = t->next; } while (t != root); } }
[ "podobrii.ma@phystech.edu" ]
podobrii.ma@phystech.edu
6937e89d6a0c19e6a4c8843368cd8f531504cb30
a1abe87ee9e276ba60d26a63378c4ea3e35d7517
/Source/SpriteRender/INTERFACE/Material/MaterialInstanceFactory.cpp
9f6f74a1c3cd5baab241cae36d0f4838a6c58f22
[]
no_license
AlexeyOgurtsov/SpriteRender
c3b1f855c4f869d3b60091a048beecf270577908
f3eb9945dbc1f059fd0b0398ffc5557f7c086f13
refs/heads/master
2020-03-30T23:29:59.105528
2019-02-14T08:05:01
2019-02-14T08:05:01
151,702,572
0
0
null
null
null
null
UTF-8
C++
false
false
982
cpp
#include "MaterialInstanceFactory.h" #include "ISprite/SpriteMaterialSystemConstants.h" #include "SpriteRender/Material/DefaultMaterialInstanceRS.h" #include "SpriteRender/Material/DefaultSpriteMaterial.h" #include "SpriteRender/INTERFACE/ISpriteRenderSubsystem.h" #include "ISpriteMaterialManager.h" #include <boost/assert.hpp> namespace Dv { namespace Spr { namespace Ren { std::shared_ptr<SpriteMaterialInstanceRenderState> CreateMatInst_Default(ISpriteRenderSubsystem* pInRenderSubsystem, ID3D11ShaderResourceView* pInTexture2D) { auto const pMaterial = dynamic_cast<IMPL::DefaultSpriteMaterial*>(pInRenderSubsystem->GetMaterials()->FindById(DEFAULT_MATERIAL_ID)); IMPL::DefaultShaderConfigId ShaderConfigId = PrepareShader_ForDefaultMaterialInstance(pMaterial, pInTexture2D); return std::make_shared<IMPL::DefaultMaterialInstanceRS> ( IMPL::SDefaultMaterialInstanceRSInitializer{pMaterial, pInTexture2D, ShaderConfigId } ); } } // Dv::Spr::Ren } // Dv::Spr } // Dv
[ "alexey_eng@mail.ru" ]
alexey_eng@mail.ru
8fa7e1dd79173b06ace44c763e7ecb98ef63f8d2
b96b500e7e56a8b819bfdb4aac0d328aa1171715
/torch_glow/src/FusingOptimizer.h
72ccdc093515c1ac03ab240ffeba4ac511a4eb20
[ "Apache-2.0" ]
permissive
Bensonlp/glow
d6fb02dbdbb214278fbf49d28fac7fa5abe7d86d
daf9c6a45ef61b92ad754306567dc45758394727
refs/heads/master
2020-06-30T07:30:16.464629
2019-08-06T01:15:46
2019-08-06T01:18:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
867
h
/** * Copyright (c) 2017-present, Facebook, 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. */ #ifndef GLOW_TORCH_GLOW_SRC_FUSINGOPTIMIZER_H #define GLOW_TORCH_GLOW_SRC_FUSINGOPTIMIZER_H #include <torch/csrc/jit/ir.h> namespace glow { void FuseLinear(std::shared_ptr<torch::jit::Graph> &graph); } #endif // GLOW_TORCH_GLOW_SRC_FUSINGOPTIMIZER_H
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
61f12f051d6c820cd28509148782400836a6c6ff
429d3a2db68a73a0d287b82c11f341351e020141
/supervisor.h
9d581b1ccb05b6b31b7086ecdc228bdc2e2d651f
[]
no_license
nwmiller/CS2303-Assignment6
711f821a72ad1773f50d31bde9f4e9f0635931d2
9de7c5a477a41f6c9534c6b67d0b7ef180228a43
refs/heads/master
2021-01-10T19:56:36.433492
2012-10-27T20:44:01
2012-10-27T20:44:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,302
h
/** File supervisor.h * * @author Nathaniel Miller * * Holds the Supervisor class and * any function headers associated with the Supervisor class. * This class is subclass of the Employee class. */ #ifndef SUPERVISOR_H #define SUPERVISOR_H #include <string> #include <iostream> #include <stdio.h> #include "empl.h" using namespace std; /** The Supervisor subclass of the Employee class. * This class holds more detail/extra information * about an Employee. */ class Supervisor: public Employee { public: /* Constructs a supervisor with fields initially empty. */ Supervisor(); /* function prototypes */ /* Constructs a supervisor with the given name, salary, * department and number of subordinates. * @param name The supervisor's name. * @param salary The supervisor's salary. * @param super_dept The supervisor's department. * @param subords The number of suboridnates. */ Supervisor(string name, int salary, string dept, int subords); /* prints a supervisor and all its information */ void print_super(); /* prints a supervisor and its information, virtual declaration version */ virtual void printv(); protected: string department; // data field for the department int subordinates; // data field for the # of subordinates }; #endif
[ "n.william.m@gmail.com" ]
n.william.m@gmail.com
10d7b6308f48dd63e96a733d92e792065951b2ef
b22588340d7925b614a735bbbde1b351ad657ffc
/athena/PhysicsAnalysis/ElectronPhotonID/ElectronPhotonSelectorTools/util/EGIdentification_mem_check.cxx
44cd4cd017577e52bdfb48f10c049dcacb7d52c6
[]
no_license
rushioda/PIXELVALID_athena
90befe12042c1249cbb3655dde1428bb9b9a42ce
22df23187ef85e9c3120122c8375ea0e7d8ea440
refs/heads/master
2020-12-14T22:01:15.365949
2020-01-19T03:59:35
2020-01-19T03:59:35
234,836,993
1
0
null
null
null
null
UTF-8
C++
false
false
1,145
cxx
/* Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration */ /* To run with something like valgrind --tool=memcheck --leak-check=full --suppressions=$ROOTSYS/etc/valgrind-root.supp --error-limit=no --track-origins=yes --smc-check=all --trace-children=yes --track-fds=yes --num-callers=30 $ROOTCOREBIN/bin/x86_64-slc6-gcc49-opt/EGIdentification_mem_check>valgrind.log 2>&1 & In order to identify memory leaks in out methods Look here: http://valgrind.org/docs/manual/faq.html#faq.deflost */ #include "EgammaAnalysisInterfaces/IAsgPhotonIsEMSelector.h" #include "EgammaAnalysisInterfaces/IAsgForwardElectronIsEMSelector.h" #include "EgammaAnalysisInterfaces/IAsgElectronIsEMSelector.h" #include "EgammaAnalysisInterfaces/IAsgElectronLikelihoodTool.h" #include "AsgTools/AnaToolHandle.h" #include "AsgTools/MessageCheck.h" int main(){ using namespace asg::msgUserCode; ANA_CHECK_SET_TYPE (int); asg::AnaToolHandle<IAsgElectronLikelihoodTool> MediumLH("AsgElectronLikelihoodTool/MediumLH"); ANA_CHECK(MediumLH.setProperty("WorkingPoint", "MediumLHElectron")); ANA_CHECK(MediumLH.initialize()); return 0; }
[ "rushioda@lxplus754.cern.ch" ]
rushioda@lxplus754.cern.ch
dc87e02b2bafe1f36cc3fd4a552d605354e636bd
b128d5b4f9abaa65055665e5ee64c49d797f51df
/CommonHardware/ButtonPad.h
1ec8e45f195727e97bdfc3065d981c1a8ea7963e
[ "MIT" ]
permissive
casparkleijne/majorproblem
14ac03ba74f9e6f8f57449b2f5ad8f5a8a987d7e
a5854a9e8e12125d709b28f3f5025ee0996bf18f
refs/heads/master
2020-04-15T02:27:03.737683
2019-01-19T11:32:06
2019-01-19T11:32:06
164,315,213
1
0
null
null
null
null
UTF-8
C++
false
false
117
h
#pragma once #include <Arduino.h> class ButtonPad { public: ButtonPad(); ~ButtonPad(); uint8_t Listen(); };
[ "caspar.kleijne@hyperdata.nl" ]
caspar.kleijne@hyperdata.nl
0b525721b405fd1ab3f27640276e34b2c801731d
dd129fb6461d1b44dceb196caaa220e9f8398d18
/topics/eventloop/eventloop-two-timers.cc
22c7e1d8ed6f653bcdde3cb196fd38a3cd4fa793
[]
no_license
jfasch/jf-linux-trainings
3af777b4c603dd5c3f6832c0034be44a062b493a
aebff2e6e0f98680aa14e1b7ad4a22e73a6f31b4
refs/heads/master
2020-04-29T19:13:33.398276
2020-03-29T20:45:33
2020-03-29T20:45:33
176,347,614
0
1
null
2019-10-01T06:02:49
2019-03-18T18:35:28
C++
UTF-8
C++
false
false
1,482
cc
#include <jf/eventloop-epoll.h> #include <jf/timerfd.h> #include <jf/graceful-termination.h> #include <iostream> int main() { try { jf::EventLoop_epoll loop; jf::GracefulTermination graceful_termination({SIGTERM, SIGINT, SIGQUIT}); jf::PeriodicTimerFD timer1(/*initial: 1s*/{1, 0}, /*interval: 1s*/{1, 0}); jf::PeriodicTimerFD timer2(/*initial: 2s*/{2, 0}, /*interval: 2s*/{2, 0}); auto graceful_termination_callback = [&graceful_termination](int, jf::EventLoop*) { graceful_termination.set_requested(); }; auto timer1_callback = [&timer1](int, jf::EventLoop*) { std::cout << "Timer 1 expired " << timer1.reap_expirations() << " times" << std::endl; }; auto timer2_callback = [&timer2](int, jf::EventLoop*) { std::cout << "Timer 2 expired " << timer2.reap_expirations() << " times" << std::endl; }; loop.watch_in(graceful_termination.fd(), graceful_termination_callback); loop.watch_in(timer1.fd(), timer1_callback); loop.watch_in(timer2.fd(), timer2_callback); timer1.start(); timer2.start(); // run while (! graceful_termination.requested()) loop.run_one(); std::cout << "Shutdown ..." << std::endl; } catch (const std::exception& e) { std::cerr << e.what() << std::endl; exit(1); } }
[ "jf@faschingbauer.co.at" ]
jf@faschingbauer.co.at
4c08faf7b46f203e19e6116d0b8b53acb547f4aa
3886504fcbb5d7b12397998592cbafb874c470eb
/sdk/src/client/AsyncCallerContext.cc
5bf3e7faefa7d71be6f605179ed1fc9bff0fe9e7
[ "Apache-2.0" ]
permissive
OpenInspur/inspur-oss-cpp-sdk
1c9ff9c4de58f42db780a165059862bf52a2be8b
a0932232aaf46aab7c5a2079f72d80cc5d634ba2
refs/heads/master
2022-12-04T15:14:11.657799
2020-08-13T03:29:37
2020-08-13T03:29:37
286,946,985
0
0
null
null
null
null
UTF-8
C++
false
false
481
cc
#include <inspurcloud/oss/client/AsyncCallerContext.h> #include "../utils/Utils.h" using namespace InspurCloud::OSS; AsyncCallerContext::AsyncCallerContext() : uuid_(GenerateUuid()) { } AsyncCallerContext::AsyncCallerContext(const std::string &uuid) : uuid_(uuid) { } AsyncCallerContext::~AsyncCallerContext() { } const std::string &AsyncCallerContext::Uuid()const { return uuid_; } void AsyncCallerContext::setUuid(const std::string &uuid) { uuid_ = uuid; }
[ "wangtengfei@inspur.com" ]
wangtengfei@inspur.com
94e669be9b40a1f541158b0e955e9253ba4db318
9916fcf60ec7699108a95cc4d6b891463d7910eb
/tests/when_all.h
b5c66703450723ce0fd1269d9f599993f98354b9
[ "Apache-2.0" ]
permissive
dgu123/club
2c29dad187a1d2607aa09dc8d3832305111c978e
b542772f88d5030c575c4165f92ca4a8561c942e
refs/heads/master
2021-01-20T23:18:09.167808
2016-06-21T12:25:00
2016-06-21T12:25:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,486
h
// Copyright 2016 Peter Jankuliak // // 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. #ifndef __WHEN_ALL_H__ #define __WHEN_ALL_H__ class WhenAll { using Handler = std::function<void()>; public: template<class H> WhenAll(H handler) : _instance_count(new size_t(0)) , _handler(std::make_shared<Handler>(std::move(handler))) {} WhenAll() : _instance_count(new size_t(0)) , _handler(std::make_shared<Handler>()) {} WhenAll(const WhenAll&) = delete; void operator=(const WhenAll&) = delete; std::function<void()> make_continuation() { auto handler = _handler; auto count = _instance_count; ++*count; return [handler, count]() { if (--*count == 0) { (*handler)(); } }; } template<class F> void on_complete(F on_complete) { *_handler = std::move(on_complete); } private: std::shared_ptr<size_t> _instance_count; std::shared_ptr<Handler> _handler; }; #endif // ifndef __WHEN_ALL_H__
[ "p.jankuliak@gmail.com" ]
p.jankuliak@gmail.com
5b35a1aecaef850758742ab2a145d1e01768eb09
cb393fe99ef421b9ea87f1a91d8fff7a74e2ddaa
/C言語プログラミング/3-1if文_List3-3.cpp
7b46a8b4e6c7807f705ef6f6b0cd080865c9e84e
[]
no_license
yutatanaka/C_Programing
d1e8f8f5a88f53f7bc01375eb8f8c5a41faed6f7
df8e2249ca512a76f0fd843f72b9c771da7e3a33
refs/heads/master
2021-01-20T19:19:35.239946
2017-02-02T15:09:23
2017-02-02T15:09:23
63,483,652
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
385
cpp
/* if文・その2 読み込んだ整数値は5で割り切れないか */ #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> int main() { int no; printf("整数を入力してください:"); scanf("%d", &no); if (no % 5) { puts("その数は5で割り切れません。"); } else { puts("その数は5で割り切れます。"); } getchar(); return 0; }
[ "koryotennis99@gmail.com" ]
koryotennis99@gmail.com
17083dfae08bf0975fc97cd625df1a43a4fe8472
b85b494c0e8c1776d7b4643553693c1563df4b0b
/Chapter 15/task4.h
59ed6f00de439e99a71853b4824cb383cd02dff4
[]
no_license
lut1y/Stephen_Prata_Ansi_C_plusplus-6thE-Code-Example-and-Answers
c9d1f79b66ac7ed7f48b3ce85de3c7ae9337cb58
e14dd78639b1016ed8f842e8adaa597347c4446e
refs/heads/master
2023-07-05T13:08:51.860207
2021-08-12T16:02:34
2021-08-12T16:02:34
393,147,210
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
3,111
h
#ifndef TASK4_H_ #define TASK4_H_ #include <stdexcept> #include <string> using std::string; namespace TASK4 { class Sales { public: enum {MONTHS = 12}; // может быть статической константой class bad_index : public std::logic_error { private: int bi; // недопустимое значение индекса public: explicit bad_index(int ix, const std::string & s = "Index error in Sales object\n"); int bi_val() const {return bi;} virtual ~bad_index() throw() {} }; explicit Sales(int yy = 0); Sales(int yy, const double * gr, int n); virtual ~Sales() { } int Year() const { return year; } virtual double operator[](int i) const; virtual double & operator[](int i); private: double gross[MONTHS]; int year; }; class LabeledSales : public Sales { public: class nbad_index : public Sales::bad_index { private: std::string lbl; public: nbad_index(const std::string & lb, int ix, const std::string & s = "Index error in LabeledSales object\n"); const std::string & label_val() const {return lbl;} virtual ~nbad_index() throw() {} }; explicit LabeledSales(const std::string & lb = "none", int yy = 0); LabeledSales(const std::string & lb, int yy, const double * gr, int n); virtual ~LabeledSales() { } const std::string & Label() const {return label;} virtual double operator[](int i) const; virtual double & operator[](int i); private: std::string label; }; // ***** Описание методов ***** Sales::bad_index::bad_index(int ix, const string & s ) : std::logic_error(s), bi(ix) {} Sales::Sales(int yy) { year = yy; for (int i = 0; i < MONTHS; ++i) gross[i] = 0; } Sales::Sales(int yy, const double * gr, int n) { year = yy; int lim = (n < MONTHS)? n : MONTHS; int i; for (i = 0; i < lim; ++i) gross[i] = gr[i]; // для i > n и i < MONTHS for ( ; i < MONTHS; ++i) gross[i] = 0; } double Sales::operator[](int i) const { if(i < 0 || i >= MONTHS) throw bad_index(i); return gross[i]; } double & Sales::operator[](int i) { if(i < 0 || i >= MONTHS) throw bad_index(i); return gross[i]; } LabeledSales::nbad_index::nbad_index(const string & lb, int ix, const string & s ) : Sales::bad_index(ix, s) { lbl = lb; } LabeledSales::LabeledSales(const string & lb, int yy) : Sales(yy) { label = lb; } LabeledSales::LabeledSales(const string & lb, int yy, const double * gr, int n) : Sales(yy, gr, n) { label = lb; } double LabeledSales::operator[](int i) const { if(i < 0 || i >= MONTHS) throw nbad_index(Label(), i); return Sales::operator[](i); } double & LabeledSales::operator[](int i) { if(i < 0 || i >= MONTHS) throw nbad_index(Label(), i); return Sales::operator[](i); } } #endif
[ "lut1y@mail.ru" ]
lut1y@mail.ru
34cdc075c39565c356c6f88fde1c5ca397e7e225
1711ba6906fcfbebe0f5e6b91c5a388bf694f88f
/DHL_yk/RegDlg.cpp
9aa3ab5173bbb12dfe0e78e79074be66e00eb43a
[]
no_license
killvxk/remotectrl-1
00a19b6aeb006eb587d6b225e26bf8d5cf56a491
c17fb3961918b624262e76f14a7cfb8ba226a311
refs/heads/master
2021-05-27T15:41:38.169865
2014-06-20T14:12:47
2014-06-20T14:12:47
null
0
0
null
null
null
null
GB18030
C++
false
false
22,927
cpp
// RegDlg.cpp : implementation file // #include "stdafx.h" #include "DHL_yk.h" #include "RegDlg.h" #include "RegDataDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CRegDlg dialog CRegDlg::CRegDlg(CWnd* pParent, CIOCPServer* pIOCPServer, ClientContext *pContext) : CDialog(CRegDlg::IDD, pParent) { //{{AFX_DATA_INIT(CRegDlg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT m_iocpServer = pIOCPServer; m_pContext = pContext; m_hIcon = AfxGetApp()->LoadIcon(IDI_REG_ICON); how=0; isEnable=true; isEdit=false; } void CRegDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CRegDlg) DDX_Control(pDX, IDC_LIST, m_list); DDX_Control(pDX, IDC_TREE, m_tree); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CRegDlg, CDialog) //{{AFX_MSG_MAP(CRegDlg) ON_WM_SIZE() ON_NOTIFY(TVN_SELCHANGED, IDC_TREE, OnSelchangedTree) ON_WM_CLOSE() ON_NOTIFY(NM_RCLICK, IDC_TREE, OnRclickTree) ON_COMMAND(IDM_REGT_DEL, OnRegtDel) ON_COMMAND(IDM_REGT_CREAT, OnRegtCreat) ON_NOTIFY(NM_RCLICK, IDC_LIST, OnRclickList) ON_COMMAND(IDM_REGL_EDIT, OnReglEdit) ON_COMMAND(IDM_REGL_DELKEY, OnReglDelkey) ON_COMMAND(IDM_REGL_STR, OnReglStr) ON_COMMAND(IDM_REGL_DWORD, OnReglDword) ON_COMMAND(IDM_REGL_EXSTR, OnReglExstr) ON_NOTIFY(NM_DBLCLK, IDC_LIST, OnDblclkList) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CRegDlg message handlers BOOL CRegDlg::OnInitDialog() { CDialog::OnInitDialog(); // TODO: Add extra initialization here SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon CString str; sockaddr_in sockAddr; memset(&sockAddr, 0, sizeof(sockAddr)); int nSockAddrLen = sizeof(sockAddr); BOOL bResult = getpeername(m_pContext->m_Socket, (SOCKADDR*)&sockAddr, &nSockAddrLen); str.Format("\\\\%s - 注册表管理", bResult != INVALID_SOCKET ? inet_ntoa(sockAddr.sin_addr) : ""); SetWindowText(str); size[0]=120;size[1]=80;size[2]=310; m_list.InsertColumn(0,"名称",LVCFMT_LEFT,size[0],-1); m_list.InsertColumn(1,"类型",LVCFMT_LEFT,size[1],-1); m_list.InsertColumn(2,"数据",LVCFMT_LEFT,size[2],-1); m_list.SetExtendedStyle(LVS_EX_FULLROWSELECT); //////添加图标////// m_HeadIcon.Create(16,16,TRUE,2,2); m_HeadIcon.Add(AfxGetApp()->LoadIcon(IDI_STR_ICON)); m_HeadIcon.Add(AfxGetApp()->LoadIcon(IDI_DWORD_ICON)); m_list.SetImageList(&m_HeadIcon,LVSIL_SMALL); //树控件设置 HICON hIcon = NULL; m_ImageList_tree.Create(18, 18, ILC_COLOR16,10, 0); hIcon = (HICON)::LoadImage(::AfxGetInstanceHandle(),MAKEINTRESOURCE(IDI_FATHER_ICON), IMAGE_ICON, 18, 18, 0); m_ImageList_tree.Add(hIcon); hIcon = (HICON)::LoadImage(::AfxGetInstanceHandle(),MAKEINTRESOURCE(IDI_DIR_ICON), IMAGE_ICON, 32, 32, 0); m_ImageList_tree.Add(hIcon); hIcon = (HICON)::LoadImage(::AfxGetInstanceHandle(),MAKEINTRESOURCE(IDI_DIR_ICON2), IMAGE_ICON, 32, 32, 0); m_ImageList_tree.Add(hIcon); m_tree.SetImageList ( &m_ImageList_tree,TVSIL_NORMAL ); DWORD dwStyle = GetWindowLong(m_tree.m_hWnd,GWL_STYLE); dwStyle |=TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT; SetWindowLong(m_tree.m_hWnd,GWL_STYLE,dwStyle); m_hRoot = m_tree.InsertItem("注册表管理",0,0,0,0); /* HKCU=m_tree.InsertItem("HKEY_CURRENT_USER",1,2,m_hRoot,0); HKLM=m_tree.InsertItem("HKEY_LOCAL_MACHINE",1,2,m_hRoot,0); HKUS=m_tree.InsertItem("HKEY_USERS",1,2,m_hRoot,0); HKCC=m_tree.InsertItem("HKEY_CURRENT_CONFIG",1,2,m_hRoot,0); HKCR=m_tree.InsertItem("HKEY_CLASSES_ROOT",1,2,m_hRoot,0); */ HKCR=m_tree.InsertItem("HKEY_CLASSES_ROOT",1,2,m_hRoot,0); HKCU=m_tree.InsertItem("HKEY_CURRENT_USER",1,2,m_hRoot,0); HKLM=m_tree.InsertItem("HKEY_LOCAL_MACHINE",1,2,m_hRoot,0); HKUS=m_tree.InsertItem("HKEY_USERS",1,2,m_hRoot,0); HKCC=m_tree.InsertItem("HKEY_CURRENT_CONFIG",1,2,m_hRoot,0); m_tree.Expand(m_hRoot,TVE_EXPAND); CreatStatusBar(); CRect rect; GetWindowRect(&rect); rect.bottom+=20; MoveWindow(&rect,true); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } // 创建状态条 static UINT indicators[] = { ID_SEPARATOR }; void CRegDlg::CreatStatusBar() { if (!m_wndStatusBar.Create(this) || !m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT))) { TRACE0("Failed to create status bar\n"); return ; // fail to create } m_wndStatusBar.SetPaneInfo(0, m_wndStatusBar.GetItemID(0), SBPS_STRETCH, 120); RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST, 0); //显示状态栏 CRect rc; ::GetWindowRect(this->m_hWnd,rc); //rc.top=rc.bottom-30; m_wndStatusBar.MoveWindow(rc); CString str; m_wndStatusBar.SetPaneText(0,str); } void CRegDlg::OnSize(UINT nType, int cx, int cy) { CDialog::OnSize(nType, cx, cy); // TODO: Add your message handler code here if(m_list.m_hWnd==NULL)return; if(m_tree.m_hWnd==NULL)return; CRect treeRec,listRec; treeRec.top=treeRec.left=0; //dlgrc.right=cx; //dlgrc.bottom=cy; treeRec.right=cx*0.3; treeRec.bottom=cy-20; m_tree.MoveWindow(treeRec); listRec.top=0; listRec.left =treeRec.right+10; listRec.right=cx; listRec.bottom=cy-20; m_list.MoveWindow(listRec); int dcx=cx-treeRec.right-15; for(int i=0;i<3;i++){ double dd=size[i]; dd/=510; dd*=dcx; int lenth=dd; m_list.SetColumnWidth(i,(lenth)); } if(m_wndStatusBar.m_hWnd!=NULL){ CRect rc; rc.top=cy-20; rc.left=0; rc.right=cx; rc.bottom=cy; m_wndStatusBar.MoveWindow(rc); } } void CRegDlg::OnReceiveComplete() { //BYTE b=m_pContext->m_DeCompressionBuffer.GetBuffer(0)[0]; switch (m_pContext->m_DeCompressionBuffer.GetBuffer(0)[0]) { case TOKEN_REG_PATH: //接收项 addPath((char*)(m_pContext->m_DeCompressionBuffer.GetBuffer(1))); EnableCursor(true); break; case TOKEN_REG_KEY: //接收键 ,值 addKey((char*)(m_pContext->m_DeCompressionBuffer.GetBuffer(1))); EnableCursor(true); break; case TOKEN_REG_OK: TestOK(); isEdit=false; EnableCursor(true); break; default: EnableCursor(true); isEdit=false; break; } } void CRegDlg::addPath(char *tmp) { if(tmp==NULL) return; int msgsize=sizeof(REGMSG); REGMSG msg; memcpy((void*)&msg,tmp,msgsize); DWORD size =msg.size; int count=msg.count; if(size>0&&count>0){ //一点保护措施 for(int i=0;i<count;i++){ char* szKeyName=tmp+size*i+msgsize; m_tree.InsertItem(szKeyName,1,2,SelectNode,0);//插入子键名称 m_tree.Expand(SelectNode,TVE_EXPAND); } } } void CRegDlg::addKey(char *buf) { m_list.DeleteAllItems(); int nitem=m_list.InsertItem(0,"(默认)",0); m_list.SetItemText(nitem,1,"REG_SZ"); m_list.SetItemText(nitem,2,"(数值未设置)"); if(buf==NULL) return; REGMSG msg; memcpy((void*)&msg,buf,sizeof(msg)); char* tmp=buf+sizeof(msg); for(int i=0;i<msg.count;i++) { BYTE Type=tmp[0]; //取出标志头 tmp+=sizeof(BYTE); char* szValueName=tmp; //取出名字 tmp+=msg.size; BYTE* szValueDate=(BYTE*)tmp; //取出值 tmp+=msg.valsize; if(Type==MREG_SZ) { int nitem=m_list.InsertItem(0,szValueName,0); m_list.SetItemText(nitem,1,"REG_SZ"); m_list.SetItemText(nitem,2,(char*)szValueDate); } if(Type==MREG_DWORD) { char ValueDate[256]; DWORD d=(DWORD)szValueDate; memcpy((void*)&d,szValueDate,sizeof(DWORD)); CString value; value.Format("0x%x",d); sprintf(ValueDate," (%wd)",d); value+=" "; value+=ValueDate; int nitem=m_list.InsertItem(0,szValueName,1); m_list.SetItemText(nitem,1,"REG_DWORD"); m_list.SetItemText(nitem,2,value); } if(Type==MREG_BINARY) { char ValueDate[256]; sprintf(ValueDate,"%wd",szValueDate); int nitem=m_list.InsertItem(0,szValueName,1); m_list.SetItemText(nitem,1,"REG_BINARY"); m_list.SetItemText(nitem,2,ValueDate); } if(Type==MREG_EXPAND_SZ) { int nitem=m_list.InsertItem(0,szValueName,0); m_list.SetItemText(nitem,1,"REG_EXPAND_SZ"); m_list.SetItemText(nitem,2,(char*)szValueDate); } } } char CRegDlg::getFatherPath(CString &FullPath) { char bToken; if(!FullPath.Find("HKEY_CLASSES_ROOT")) //判断主键 { //MKEY=HKEY_CLASSES_ROOT; bToken=MHKEY_CLASSES_ROOT; FullPath.Delete(0,sizeof("HKEY_CLASSES_ROOT")); }else if(!FullPath.Find("HKEY_CURRENT_USER")) { bToken=MHKEY_CURRENT_USER; FullPath.Delete(0,sizeof("HKEY_CURRENT_USER")); }else if(!FullPath.Find("HKEY_LOCAL_MACHINE")) { bToken=MHKEY_LOCAL_MACHINE; FullPath.Delete(0,sizeof("HKEY_LOCAL_MACHINE")); }else if(!FullPath.Find("HKEY_USERS")) { bToken=MHKEY_USERS; FullPath.Delete(0,sizeof("HKEY_USERS")); }else if(!FullPath.Find("HKEY_CURRENT_CONFIG")) { bToken=MHKEY_CURRENT_CONFIG; FullPath.Delete(0,sizeof("HKEY_CURRENT_CONFIG")); } return bToken; } void CRegDlg::OnSelchangedTree(NMHDR* pNMHDR, LRESULT* pResult) { NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR; // TODO: Add your control notification handler code here if(!isEnable) return; TVITEM item = pNMTreeView->itemNew; if(item.hItem == m_hRoot) { return; } SelectNode=item.hItem; //保存用户打开的子树节点句柄 m_list.DeleteAllItems(); CString FullPath=GetFullPath(SelectNode); m_wndStatusBar.SetPaneText(0,FullPath); HTREEITEM CurrentNode = item.hItem; //取得此节点的全路径 while(m_tree.GetChildItem(CurrentNode)!=NULL) { m_tree.DeleteItem(m_tree.GetChildItem(CurrentNode)); //删除 会产生 OnSelchangingTree事件 *** } char bToken=getFatherPath(FullPath); //愈加一个键 int nitem=m_list.InsertItem(0,"(默认)",0); m_list.SetItemText(nitem,1,"REG_SZ"); m_list.SetItemText(nitem,2,"(数值未设置)"); //BeginWaitCursor(); //char *buf=new char[FullPath.GetLength] FullPath.Insert(0,bToken);//插入 那个根键 bToken=COMMAND_REG_FIND; FullPath.Insert(0,bToken); //插入查询命令 EnableCursor(false); m_iocpServer->Send(m_pContext, (LPBYTE)(FullPath.GetBuffer(0)), FullPath.GetLength()+1); *pResult = 0; } void CRegDlg::TestOK() { //执行了什么操作 1,删除项 2,新建项 3,删除键 4, 新建键 5,编辑键 if(how==1){ while(m_tree.GetChildItem(SelectNode)!=NULL) { m_tree.DeleteItem(m_tree.GetChildItem(SelectNode)); //删除 会产生 OnSelchangingTree事件 *** } m_tree.DeleteItem(SelectNode); how=0; }else if(how==2) { m_tree.InsertItem(Path,1,2,SelectNode,0);//插入子键名称 m_tree.Expand(SelectNode,TVE_EXPAND); Path=""; }else if(how==3){ m_list.DeleteItem(index); index=0; }else if(how==4){ int nitem; DWORD d; char ValueDate[256]; CString value; ZeroMemory(ValueDate,256); switch(type){ case MREG_SZ: //加了字串 nitem=m_list.InsertItem(0,Key,0); m_list.SetItemText(nitem,1,"REG_SZ"); m_list.SetItemText(nitem,2,Value); break; case MREG_DWORD: //加了DWORD d=atod(Value.GetBuffer(0)); //Value.ReleaseBuffer(); value.Format("0x%x",d); sprintf(ValueDate," (%wd)",d); value+=" "; value+=ValueDate; nitem=m_list.InsertItem(0,Key,1); m_list.SetItemText(nitem,1,"REG_DWORD"); m_list.SetItemText(nitem,2,value); break; case MREG_EXPAND_SZ: nitem=m_list.InsertItem(0,Key,0); m_list.SetItemText(nitem,1,"REG_EXPAND_SZ"); m_list.SetItemText(nitem,2,Value); break; default: break; } }else if(how==5){ // int nitem; DWORD d; char ValueDate[256]; CString value; ZeroMemory(ValueDate,256); switch(type){ case MREG_SZ: //加了字串 m_list.SetItemText(index,2,Value); break; case MREG_DWORD: //加了DWORD d=atod(Value.GetBuffer(0)); //Value.ReleaseBuffer(); value.Format("0x%x",d); sprintf(ValueDate," (%wd)",d); value+=" "; value+=ValueDate; m_list.SetItemText(index,2,value); break; case MREG_EXPAND_SZ: m_list.SetItemText(index,2,Value); break; default: break; } } how=0; } void CRegDlg::EnableCursor(bool b) { if(b){ isEnable=true; ::SetCursor(::LoadCursor(NULL,IDC_ARROW)); }else{ isEnable=false; ::SetCursor(LoadCursor(NULL, IDC_WAIT)); } } CString CRegDlg::GetFullPath(HTREEITEM hCurrent) { CString strTemp; CString strReturn = ""; while(1){ if(hCurrent==m_hRoot) return strReturn; strTemp = m_tree.GetItemText(hCurrent); //得到当前的 if(strTemp.Right(1) != "\\") strTemp += "\\"; strReturn = strTemp + strReturn; hCurrent = m_tree.GetParentItem(hCurrent); //得到父的 } return strReturn; } DWORD CRegDlg::atod(char *ch) { int len=strlen(ch); DWORD d=0; for(int i=0;i<len;i++){ int t=ch[i]-48; //这位上的数字 if(ch[i]>57||ch[i]<48){ //不是数字 return d; } d*=10; d+=t; } return d; } void CRegDlg::OnClose() { // TODO: Add your message handler code here and/or call default closesocket(m_pContext->m_Socket); CDialog::OnClose(); } /* 得到列表的类型 MREG_SZ, MREG_DWORD, MREG_BINARY, MREG_EXPAND_SZ*/ BYTE CRegDlg::getType(int index) { if(index<0) return 100; CString strType=m_list.GetItemText(index,1); //得到类型 if(strType=="REG_SZ") return MREG_SZ; else if(strType=="REG_DWORD") return MREG_DWORD; else if(strType=="REG_EXPAND_SZ") return MREG_EXPAND_SZ; else return 100; } void CRegDlg::OnRclickTree(NMHDR* pNMHDR, LRESULT* pResult) { // TODO: Add your control notification handler code here if(!isEnable) return; CPoint point; GetCursorPos(&point); m_tree.ScreenToClient(&point); UINT uFlags; HTREEITEM hItem = m_tree.HitTest(point, &uFlags); if ((hItem != NULL) && (TVHT_ONITEM & uFlags)) { if(hItem== m_hRoot) { return; } SelectNode=hItem; m_tree.Select(hItem, TVGN_CARET); CMenu popup; popup.LoadMenu(IDR_REGT_MENU); CMenu* pM = popup.GetSubMenu(0); CPoint p; GetCursorPos(&p); pM->TrackPopupMenu(TPM_LEFTALIGN, p.x, p.y, this); } *pResult = 0; } void CRegDlg::OnRegtDel() { // TODO: Add your command handler code here CString FullPath=GetFullPath(SelectNode); //得到全路径 char bToken=getFatherPath(FullPath); // COMMAND_REG_DELPATH FullPath.Insert(0,bToken);//插入 那个根键 bToken=COMMAND_REG_DELPATH; FullPath.Insert(0,bToken); //插入查询命令 how=1; m_iocpServer->Send(m_pContext, (LPBYTE)(FullPath.GetBuffer(0)), FullPath.GetLength()+1); } void CRegDlg::OnRegtCreat() { // TODO: Add your command handler code here CRegDataDlg dlg(this); //dlg.EnableKey(); dlg.EKey=true; dlg.DoModal(); if(dlg.isOK){ //MessageBox(dlg.m_path); COMMAND_REG_CREATEPATH CString FullPath=GetFullPath(SelectNode); //得到全路径 //FullPath+="\\"; FullPath+=dlg.m_path; char bToken=getFatherPath(FullPath); // COMMAND_REG_DELPATH FullPath.Insert(0,bToken);//插入 那个根键 bToken=COMMAND_REG_CREATEPATH; FullPath.Insert(0,bToken); //插入查询命令 how=2; Path=dlg.m_path; m_iocpServer->Send(m_pContext, (LPBYTE)(FullPath.GetBuffer(0)), FullPath.GetLength()+1); } } void CRegDlg::OnRclickList(NMHDR* pNMHDR, LRESULT* pResult) { // TODO: Add your control notification handler code here if(!isEnable) return; if( SelectNode== m_hRoot) { return; } CMenu popup; popup.LoadMenu(IDR_REGL_MENU); CMenu* pM = popup.GetSubMenu(0); CPoint p; GetCursorPos(&p); if (m_list.GetSelectedCount() == 0) //没有选中 { pM->EnableMenuItem(0, MF_BYPOSITION | MF_GRAYED); //编辑 pM->EnableMenuItem(1, MF_BYPOSITION | MF_GRAYED); //删除 }else{ if(getType(m_list.GetSelectionMark())==100) pM->EnableMenuItem(0, MF_BYPOSITION | MF_GRAYED); //编辑 pM->EnableMenuItem(2, MF_BYPOSITION | MF_GRAYED); //新建 } pM->TrackPopupMenu(TPM_LEFTALIGN, p.x, p.y, this); *pResult = 0; } void CRegDlg::OnReglEdit() { // TODO: Add your command handler code here int index=m_list.GetSelectionMark(); if(index<0)return; BYTE b=getType(index); switch(b){ case MREG_SZ: isEdit=true; //变为可编辑状态 Key=m_list.GetItemText(index,0); //得到名 Value=m_list.GetItemText(index,2); //得到值 OnReglStr(); how=5; this->index=index; break; case MREG_DWORD: Key=m_list.GetItemText(index,0); //得到名 Value.Format("%s",m_list.GetItemText(index,2)); //得到值 Value.Delete(0,Value.Find('(')+1); // 去掉括号 Value.Delete(Value.GetLength()-1); // isEdit=true; //变为可编辑状态 OnReglDword(); how=5; this->index=index; break; case MREG_EXPAND_SZ: isEdit=true; //变为可编辑状态 Key=m_list.GetItemText(index,0); //得到名 Value=m_list.GetItemText(index,2); //得到值 OnReglExstr(); how=5; this->index=index; break; default: break; } } //删除键 COMMAND_REG_DELKEY void CRegDlg::OnReglDelkey() { // TODO: Add your command handler code here REGMSG msg; int index=m_list.GetSelectionMark(); CString FullPath=GetFullPath(SelectNode); //得到全路径 char bToken=getFatherPath(FullPath); CString key=m_list.GetItemText(index,0); //得到键名 msg.size=FullPath.GetLength(); // 项名大小 msg.valsize=key.GetLength(); //键名大小 int datasize=sizeof(msg)+msg.size+msg.valsize+4; char *buf=new char[datasize]; ZeroMemory(buf,datasize); buf[0]=COMMAND_REG_DELKEY; //命令头 buf[1]=bToken; //主键 memcpy(buf+2,(void*)&msg,sizeof(msg)); //数据头 if(msg.size>0) //根键 就不用写项了 memcpy(buf+2+sizeof(msg),FullPath.GetBuffer(0),FullPath.GetLength()); //项值 memcpy(buf+2+sizeof(msg)+FullPath.GetLength(),key.GetBuffer(0),key.GetLength()); //键值 how=3; this->index=index; m_iocpServer->Send(m_pContext, (LPBYTE)(buf), datasize); delete[] buf; } void CRegDlg::OnReglStr() { // TODO: Add your command handler code here CRegDataDlg dlg(this); if(isEdit){ //是编辑 dlg.m_path=Key; dlg.m_key=Value; dlg.EPath=true; } dlg.DoModal(); if(dlg.isOK){ CString FullPath=GetFullPath(SelectNode); //得到全路径 char bToken=getFatherPath(FullPath); DWORD size=1+1+1+sizeof(REGMSG)+FullPath.GetLength()+dlg.m_path.GetLength()+dlg.m_key.GetLength()+6; char* buf=new char[size]; //char *buf = (char *)LocalAlloc(LPTR, size); ZeroMemory(buf,size); REGMSG msg; msg.count=FullPath.GetLength(); //项大小 msg.size=dlg.m_path.GetLength(); //键大小 msg.valsize=dlg.m_key.GetLength(); //数据大小 buf[0]= COMMAND_REG_CREATKEY; //数据头 buf[1]=MREG_SZ; //值类型 buf[2]=bToken; //父键 memcpy(buf+3,(void*)&msg,sizeof(msg)); //数据头 char* tmp=buf+3+sizeof(msg); if(msg.count>0) memcpy(tmp,FullPath.GetBuffer(0),msg.count); //项 tmp+=msg.count; memcpy(tmp,dlg.m_path.GetBuffer(0),msg.size); //键名 tmp+=msg.size; memcpy(tmp,dlg.m_key.GetBuffer(0),msg.valsize); //值 tmp=buf+3+sizeof(msg); // 善后 type=MREG_SZ; how=4; Key=dlg.m_path; Value=dlg.m_key; // m_iocpServer->Send(m_pContext, (LPBYTE)(buf), size); delete[] buf; //LocalFree(buf); } } void CRegDlg::OnReglDword() { // TODO: Add your command handler code here CRegDataDlg dlg(this); dlg.isDWORD=true; if(isEdit){ //是编辑 dlg.m_path=Key; dlg.m_key=Value; dlg.EPath=true; } dlg.DoModal(); if(dlg.isOK){ CString FullPath=GetFullPath(SelectNode); //得到全路径 char bToken=getFatherPath(FullPath); DWORD size=1+1+1+sizeof(REGMSG)+FullPath.GetLength()+dlg.m_path.GetLength()+dlg.m_key.GetLength()+6; char* buf=new char[size]; //char *buf = (char *)LocalAlloc(LPTR, size); ZeroMemory(buf,size); REGMSG msg; msg.count=FullPath.GetLength(); //项大小 msg.size=dlg.m_path.GetLength(); //键大小 msg.valsize=dlg.m_key.GetLength(); //数据大小 buf[0]= COMMAND_REG_CREATKEY; //数据头 buf[1]=MREG_DWORD; //值类型 buf[2]=bToken; //父键 memcpy(buf+3,(void*)&msg,sizeof(msg)); //数据头 char* tmp=buf+3+sizeof(msg); if(msg.count>0) memcpy(tmp,FullPath.GetBuffer(0),msg.count); //项 tmp+=msg.count; memcpy(tmp,dlg.m_path.GetBuffer(0),msg.size); //键名 tmp+=msg.size; memcpy(tmp,dlg.m_key.GetBuffer(0),msg.valsize); //值 tmp=buf+3+sizeof(msg); // 善后 type=MREG_DWORD; how=4; Key=dlg.m_path; Value=dlg.m_key; // m_iocpServer->Send(m_pContext, (LPBYTE)(buf), size); delete[] buf; //LocalFree(buf); } } void CRegDlg::OnReglExstr() { // TODO: Add your command handler code here CRegDataDlg dlg(this); if(isEdit){ //是编辑 dlg.m_path=Key; dlg.m_key=Value; dlg.EPath=true; } dlg.DoModal(); if(dlg.isOK){ CString FullPath=GetFullPath(SelectNode); //得到全路径 char bToken=getFatherPath(FullPath); DWORD size=1+1+1+sizeof(REGMSG)+FullPath.GetLength()+dlg.m_path.GetLength()+dlg.m_key.GetLength()+6; char* buf=new char[size]; //char *buf = (char *)LocalAlloc(LPTR, size); ZeroMemory(buf,size); REGMSG msg; msg.count=FullPath.GetLength(); //项大小 msg.size=dlg.m_path.GetLength(); //键大小 msg.valsize=dlg.m_key.GetLength(); //数据大小 buf[0]= COMMAND_REG_CREATKEY; //数据头 buf[1]=MREG_EXPAND_SZ; //值类型 buf[2]=bToken; //父键 memcpy(buf+3,(void*)&msg,sizeof(msg)); //数据头 char* tmp=buf+3+sizeof(msg); if(msg.count>0) memcpy(tmp,FullPath.GetBuffer(0),msg.count); //项 tmp+=msg.count; memcpy(tmp,dlg.m_path.GetBuffer(0),msg.size); //键名 tmp+=msg.size; memcpy(tmp,dlg.m_key.GetBuffer(0),msg.valsize); //值 tmp=buf+3+sizeof(msg); // 善后 type=MREG_EXPAND_SZ; how=4; Key=dlg.m_path; Value=dlg.m_key; // m_iocpServer->Send(m_pContext, (LPBYTE)(buf), size); delete[] buf; //LocalFree(buf); } } void CRegDlg::OnDblclkList(NMHDR* pNMHDR, LRESULT* pResult) { // TODO: Add your control notification handler code here OnReglEdit(); *pResult = 0; }
[ "ouwenniu@qq.com" ]
ouwenniu@qq.com
2b1e324688814e3f271b757d4a352f029bc7be87
c5784387ccf8154a3526c7499d98cb5e3e30b079
/code/themes/string/aho_corasick/DA/KeysTree.h
ae42d711813d9e6d9b07322f43917335cf5f80de
[]
no_license
ArtDu/Algorithms
a858f915338da7c3bb1ef707e39622fe73426b04
18a39e323d483d9cd1322b4b7465212c01fda43a
refs/heads/master
2023-03-04T14:25:42.214472
2022-04-14T18:28:15
2022-04-14T18:28:15
197,545,456
3
3
null
2023-02-27T10:52:36
2019-07-18T08:27:49
C++
UTF-8
C++
false
false
861
h
// // Created by art on 04.03.19. // #ifndef AHOCORASICK_KEYSTREE_H #define AHOCORASICK_KEYSTREE_H #include <iostream> #include <map> #include <vector> #include <string> #include <queue> using namespace std; class KTNode { public: map<string, KTNode *> to; string _key; vector<int32_t> _list; int32_t dist; KTNode *suffLink; KTNode(string key, int32_t list, int32_t dist); KTNode(string key, int32_t dist); }; class KeysTree { public: KeysTree(); void BuildTree(vector<vector<string >> &patterns); void Search(vector<pair<pair<int32_t, int32_t>, string >> &text); void TreePrint(); private: void NodePrint(KTNode *node, int dpth, std::string x); void AddSuffLinks(); void BuildOnePattern(vector<string> &pattern, int32_t &pattNum); KTNode *root; }; #endif //AHOCORASICK_KEYSTREE_H
[ "rusartdub@gmail.com" ]
rusartdub@gmail.com
8008297f428d5fcf1a4946f0ba8c21283ccec3a4
b72989976e21a43752510146101a11e7184a6476
/dbtoaster/dbt_c++/q3Agg.cpp
b832a54705bfbbce2d13e8ab033af77bb69c8aab
[]
no_license
gauravsaxena81/GraphIVM
791c2f90d7a24943664f0e3427ffb26bded20029
d3d1d18206910a41ed6ce4e338488bf53f56ac54
refs/heads/master
2021-01-21T21:54:54.679396
2015-11-20T00:11:24
2015-11-20T00:11:24
34,547,806
0
0
null
null
null
null
UTF-8
C++
false
false
4,368
cpp
#include "q3Agg.hpp" #include <chrono> namespace dbtoaster{ class CustomProgram_1 : public Program { public: void process_stream_event(const event_t& ev) { //cout << "on_" << dbtoaster::event_name[ev.type] << "_"; // cout << get_relation_name(ev.id) << "(" << ev.data << ")" << endl; Program::process_stream_event(ev); } }; class CustomProgram_2 : public Program { public: // CustomProgram_2(int argc = 0, char* argv[] = 0) : Program(argc,argv) {} void process_streams() { Program::process_streams(); int which = 2; int MAX = 50000; long X = 1000000000; if(which == 2) {//JT const STRING_TYPE *s = new STRING_TYPE("2992-01-01"); data.on_insert_USERS(X); for( long i = 1; i <= MAX; ++i ) { data.on_insert_TWEET(X, X + i, *s); } for( long i = 1; i <= MAX; ++i ) { //data.on_insert_RETWEET(X + i, X + i, *s, X + i); } const auto start_time = std::chrono::steady_clock::now(); for( long i = 1; i <= MAX; ++i ) { //data.on_delete_RETWEET(X + i, X + i, *s, X + i); data.on_insert_RETWEET(X + i, X + i, *s, X + i); } double time_in_seconds = std::chrono::duration_cast<std::chrono::milliseconds> (std::chrono::steady_clock::now() - start_time).count(); std::cout << time_in_seconds<<"ms"<<std::endl; api.print(); } if(which == 1) {//PT const STRING_TYPE *s = new STRING_TYPE("2992-01-01"); for( long i = 1; i <= MAX; ++i ) { data.on_insert_RETWEET(X, X + i, *s, 2); } const auto start_time = std::chrono::steady_clock::now(); for( long i = 1; i <= MAX; ++i ) { //data.on_insert_RETWEET(X, X + i, *s, 2); data.on_delete_RETWEET(X, X + i, *s, 2); } double time_in_seconds = std::chrono::duration_cast<std::chrono::milliseconds> (std::chrono::steady_clock::now() - start_time).count(); std::cout << time_in_seconds<<"ms"<<std::endl; } } }; } /** * In order to compile this file one would have to include a header containing * the definition of "dbtoaster::Program" and "dbtoaster::Program::snapshot_t" * as generated by the dbtoaster C++ code generator. Using the "-c" dbtoaster * command line option the generated header file is automatically included and * compiled against this file. */ /** * Determines whether "--async" was specified as a command line argument. * * @param argc * @param argv * @return true if "--async" is one of the command line arguments */ bool async_mode(int argc, char* argv[]) { for(int i = 1; i < argc; ++i) if( !strcmp(argv[i],"--async") ) return true; return false; } /** * Main function that executes the sql program corresponding to the header file * included. If "-async" is among the command line arguments then the execution * is performed asynchronous in a seperate thread, otherwise it is performed in * the same thread. If performed in a separate thread and while not finished it * continuously gets snapshots of the results and prints them in xml format. At * the end of the execution the final results are also printed. * * @param argc * @param argv * @return */ int main(int argc, char* argv[]) { bool async = async_mode(argc,argv); //dbtoaster::Program p;//(argc,argv); //dbtoaster::CustomProgram_1 p; dbtoaster::CustomProgram_2 p; //dbtoaster::Program::snapshot_t snap; dbtoaster::CustomProgram_2::snapshot_t snap; cout << "Initializing program:" << endl; p.init(); p.run( async ); cout << "Running program:" << endl; while( !p.is_finished() ) { snap = p.get_snapshot(); DBT_SERIALIZATION_NVP_OF_PTR(cout, snap); } cout << "Printing final result:" << endl; snap = p.get_snapshot(); //DBT_SERIALIZATION_NVP_OF_PTR(cout, snap); cout << std::endl; return 0; }
[ "gsaxena81@gmail.com" ]
gsaxena81@gmail.com
b60caaf90f106ec11cf3e54835c7188deadcc2d1
8a9bb0bba06a3fb9da06f48b5fb43af6a2a4bb47
/LeetCode/KthSmallestElementInASortedMatrix.cpp
2fbcd9371016bed878ab421685f4eb901a108a75
[]
no_license
ruifshi/LeetCode
4cae3f54e5e5a8ee53c4a7400bb58d177a560be8
11786b6bc379c7b09b3f49fc8743cc15d46b5c0d
refs/heads/master
2022-07-14T09:39:55.001968
2022-06-26T02:06:00
2022-06-26T02:06:00
158,513,101
0
0
null
null
null
null
UTF-8
C++
false
false
1,164
cpp
#include "stdafx.h" #include "KthSmallestElementInASortedMatrix.h" #include <queue> #include <algorithm> struct mycomp { bool operator()(const pair<int, pair<int, int>> &a, const pair<int, pair<int, int>> &b) { return a.first > b.first; } }; // O(K log min(matrix.size(), k) int Solution::kthSmallest(vector<vector<int>>& matrix, int k) { if (matrix.size() == 0) return 0; if (k == 1) return matrix[0][0]; // value to indices // always hold the smallest elements in the front priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int,int>>>, mycomp> q; // matrix is row and column sorted so take the first row values // and then we'll iterate along the columns for (int i = 0; i < min((int)matrix.size(), k); i++) { q.push({ matrix[i][0], { i, 0 } }); } // in k iterations, we will have the kth number since q has smallest // numbers in the front int val = 0; while (k-- > 0) { val = q.top().first; int row = q.top().second.first; int col = q.top().second.second; q.pop(); if (col < matrix[0].size() - 1) { q.push({ matrix[row][col + 1], {row, col + 1} }); } } return val; }
[ "ruifshi@hotmail.com" ]
ruifshi@hotmail.com
ea778f8fdb470c79a0170b94c68c4723fa209c7d
731b465f79940ee90d540e027d083ea30373cc89
/match.h
295992ee3bf857e982b57e965cf3ab5da570601e
[]
no_license
juancarlosfarah/tube-matcher
cfdc468d4d07a587b0ab12b13a436eb65965040b
672c2d5997c66fd9228ec6f79d520f7ff6f131da
refs/heads/master
2021-01-02T14:09:08.058283
2016-02-16T17:51:32
2016-02-16T17:51:32
24,989,820
0
0
null
2014-10-17T11:01:10
2014-10-09T13:14:59
C++
UTF-8
C++
false
false
1,327
h
#ifndef MATCH_H #define MATCH_H /* function: GetPerfectMatches * =========================== * takes a string and an input file stream * and prints the lines in that file that * contain all the characters in the string. */ void GetPerfectMatches( std::string, std::ifstream& ); /* function: GetPerfectUnmatches * ============================= * takes a string and an input file stream * and prints the lines in that file that * contain no characters in the string. */ void GetPerfectUnmatches( std::string s, std::ifstream& file ); /* function: IsPerfectMatch * ======================== * takes two strings and compares them to * see if the characters in the first one * are all in the second. */ bool IsPerfectMatch( std::string matcher, std::string matchee ); /* function: IsCharInString * ======================== * takes a character and a string and * returns true if the character is * in the string. */ bool IsCharInString( char c, std::string s ); /* function: IsPerfectUnmatch * ========================== * takes two strings and compares them * to see if none of the characters of * the first string are in the second. */ bool IsPerfectUnmatch( std::string matcher, std::string matchee ); #endif
[ "farah.juancarlos@gmail.com" ]
farah.juancarlos@gmail.com
4231fcdc52fc78218aff850ac7279c5b20e03e86
1d78efdff80fa91f80b40e80555345c8ece58045
/src/common/test/test_term_emitter.cpp
40fb2edcf6da8b068f7f5c74d536d04b6c89eda5
[]
no_license
monadicus/prologcoin
d40511962cc8d0361f0f04f537ad805b5c0183d2
bece12ebea698b652a1b737e9aa07e22a1647106
refs/heads/master
2020-03-07T16:40:40.676306
2018-03-31T21:18:53
2018-03-31T21:18:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,498
cpp
#include <iostream> #include <iomanip> #include <assert.h> #include <common/term.hpp> #include <common/term_ops.hpp> #include <common/term_emitter.hpp> using namespace prologcoin::common; static void header( const std::string &str ) { std::cout << "\n"; std::cout << "--- [" + str + "] " + std::string(60 - str.length(), '-') << "\n"; std::cout << "\n"; } static void test_simple_term() { header("test_simple_term()"); heap h; term_ops ops; std::stringstream ss; term_emitter emit(ss, h, ops); con_cell h_2("h", 2); con_cell f_1("f", 1); con_cell p_3("p", 3); auto h_2_str = h.new_str(h_2); auto Z = h.arg(h_2_str, 0); auto W = h.arg(h_2_str, 1); auto f_1_str = h.new_str(f_1); h.set_arg(f_1_str, 0, W); auto p_3_str = h.new_str(p_3); h.set_arg(p_3_str, 0, Z); h.set_arg(p_3_str, 1, h_2_str); h.set_arg(p_3_str, 2, f_1_str); emit.print(p_3_str); std::cout << ss.str() << "\n"; assert(ss.str() == "p(C, h(C, D), f(D))"); } static size_t my_rand(size_t bound) { static uint64_t state = 4711; if (bound == 0) { state = 4711; return 0; } state = 13*state + 734672631; return state % bound; } static term new_term(heap &heap, size_t max_depth, size_t depth = 0) { size_t arity = (depth >= max_depth) ? 0 : my_rand(6); char functorName[2]; functorName[0] = 'a' + (char)arity; functorName[1] = '\0'; auto str = heap.new_str(con_cell(functorName, arity)); for (size_t j = 0; j < arity; j++) { auto arg = new_term(heap, max_depth, depth+1); heap.set_arg(str, j, arg); } return str; } const char *BIG_TERM_GOLD = "e(b(e(b(e(a, a, a, a)), b(e(a, a, a, a)), b(e(a, a, a, a)), b(c(a, a)))), \n" " f(e(b(e(a, a, a, a)), f(a, f(a, a, a, a, a), a, f(a, a, a, a, a), a), \n" " b(e(a, a, a, a)), b(e(a, a, a, a))), \n" " d(c(b(a), c(a, a)), f(a, b(a), a, d(a, a, a), e(a, a, a, a)), \n" " f(c(a, a), b(a), c(a, a), f(a, a, a, a, a), a)), \n" " b(e(f(a, a, a, a, a), e(a, a, a, a), b(a), c(a, a))), \n" " f(e(f(a, a, a, a, a), c(a, a), b(a), e(a, a, a, a)), b(c(a, a)), \n" " f(c(a, a), f(a, a, a, a, a), a, b(a), e(a, a, a, a)), \n" " d(a, d(a, a, a), e(a, a, a, a)), b(e(a, a, a, a))), \n" " d(c(b(a), c(a, a)), b(e(a, a, a, a)), d(e(a, a, a, a), d(a, a, a), a))), \n" " b(e(d(e(a, a, a, a), f(a, a, a, a, a), c(a, a)), \n" " f(c(a, a), f(a, a, a, a, a), c(a, a), b(a), e(a, a, a, a)), \n" " b(e(a, a, a, a)), d(e(a, a, a, a), b(a), c(a, a)))), \n" " f(a, \n" " d(a, d(e(a, a, a, a), f(a, a, a, a, a), a), \n" " f(c(a, a), b(a), e(a, a, a, a), b(a), a)), \n" " d(a, d(c(a, a), b(a), c(a, a)), b(e(a, a, a, a))), b(a), \n" " d(a, b(a), \n" " f(e(a, a, a, a), d(a, a, a), c(a, a), d(a, a, a), e(a, a, a, a)))))\n"; static std::string cut(const char *from, const char *to) { std::string r; for (const char *p = from; p < to; p++) { r += (char)*p; } return r; } static void test_big_term() { header("test_big_term()"); heap h; const size_t DEPTH = 5; cell term = new_term(h, DEPTH); std::stringstream ss; term_ops ops; term_emitter emitter(ss, h, ops); emitter.set_max_column(78); emitter.print(term); ss << "\n"; std::string str = ss.str(); const char *goldScan = BIG_TERM_GOLD; const char *actScan = str.c_str(); size_t lineCnt = 0; bool err = false; while (goldScan[0] != '\0') { const char *goldNextLine = strchr(goldScan, '\n'); const char *actNextLine = strchr(actScan, '\n'); if (goldNextLine == NULL && actNextLine != NULL) { std::cout << "There was no next line in gold template.\n"; std::cout << "Actual: " << cut(actScan, actNextLine) << "\n"; err = true; break; } if (goldNextLine != NULL && actNextLine == NULL) { std::cout << "Actual feed terminated to early.\n"; std::cout << "Expect: " << cut(goldScan, goldNextLine) << "\n"; err = true; break; } size_t goldNextLineLen = goldNextLine - goldScan; size_t actNextLineLen = actNextLine - actScan; if (goldNextLineLen != actNextLineLen) { std::cout << "Difference at line " << lineCnt << ":\n"; std::cout << "(Due to different lengths: ExpectLen: " << goldNextLineLen << " ActualLen: "<< actNextLineLen << ")\n"; std::cout << "Actual: " << cut(actScan, actNextLine) << "\n"; std::cout << "Expect: " << cut(goldScan, goldNextLine) << "\n"; err = true; break; } std::string actual = cut(actScan, actNextLine); std::string expect = cut(goldScan, goldNextLine); if (actual != expect) { std::cout << "Difference at line " << lineCnt << ":\n"; for (size_t i = 0; i < actual.length(); i++) { if (actual[i] != expect[i]) { std::cout << "(at column " << i << ")\n"; break; } } std::cout << "Actual: " << actual << "\n"; std::cout << "Expect: " << expect << "\n"; err = true; break; } goldScan = &goldNextLine[1]; actScan = &actNextLine[1]; lineCnt++; } if (!err) { std::cout << str; std::cout << "OK\n"; } std::cout << "\n"; assert(!err); } static void test_ops() { header("test_ops()"); heap h; term_ops ops; std::stringstream ss; term_emitter emit(ss, h, ops); con_cell plus_2("+", 2); con_cell times_2("*", 2); con_cell mod_2("mod", 2); con_cell pow_2("^", 2); con_cell minus_1("-", 1); auto plus_expr = h.new_str(plus_2); auto plus_expr1 = h.new_str(plus_2); h.set_arg(plus_expr1, 0, int_cell(1)); h.set_arg(plus_expr1, 1, int_cell(2)); h.set_arg(plus_expr, 0, plus_expr1); h.set_arg(plus_expr, 1, int_cell(3)); auto times_expr = h.new_str(times_2); h.set_arg(times_expr, 0, int_cell(42)); h.set_arg(times_expr, 1, plus_expr); auto mod_expr = h.new_str(mod_2); h.set_arg(mod_expr, 0, times_expr); h.set_arg(mod_expr, 1, int_cell(100)); auto pow_expr = h.new_str(pow_2); h.set_arg(pow_expr, 0, mod_expr); h.set_arg(pow_expr, 1, int_cell(123)); auto minus1_expr = h.new_str(minus_1); h.set_arg(minus1_expr, 0, pow_expr); auto minus1_expr1 = h.new_str(minus_1); h.set_arg(minus1_expr1, 0, minus1_expr); emit.print(minus1_expr1); std::cout << "Expr: " << ss.str() << "\n"; assert( ss.str() == "- - (42*(1+2+3) mod 100)^123" ); } int main(int argc, char *argv[]) { test_simple_term(); test_big_term(); test_ops(); return 0; }
[ "datavetaren@datavetaren.se" ]
datavetaren@datavetaren.se
3b2ae71c0f69ac779ae9f2bae43a9dd5430b3bb7
4ad2ec9e00f59c0e47d0de95110775a8a987cec2
/_Practice/IOI wcipeg/Balancing Act/main.cpp
e441369534e0cb6ebd396243810be20229ce0ea0
[]
no_license
atatomir/work
2f13cfd328e00275672e077bba1e84328fccf42f
e8444d2e48325476cfbf0d4cfe5a5aa1efbedce9
refs/heads/master
2021-01-23T10:03:44.821372
2021-01-17T18:07:15
2021-01-17T18:07:15
33,084,680
2
1
null
2015-08-02T20:16:02
2015-03-29T18:54:24
C++
UTF-8
C++
false
false
1,448
cpp
#include <iostream> #include <cstdio> #include <vector> #include <algorithm> using namespace std; #define maxN 20011 int n,i,x,y; vector<int> list[maxN]; int dad[maxN],dpDown[maxN],dpUp[maxN],dpMax[maxN]; int ans,ansid; void dfs(int node){ dpDown[node]=1; for(int i=0;i<list[node].size();i++){ int newNode = list[node][i]; if(dad[newNode]!=0) { list[node][i] = list[node][ list[node].size()-1 ]; list[node].pop_back(); i--; continue; } dad[newNode] = node; dfs(newNode); dpDown[node] += dpDown[newNode]; } } void dfsUp(int node){ for(int i =0;i<list[node].size();i++){ int newNode = list[node][i]; dpUp[newNode] = dpUp[node]+ dpDown[node]-dpDown[newNode] ; dfsUp(newNode); } } int main() { #ifndef ONLINE_JUDGE freopen("test.in","r",stdin); #endif // ONLINE_JUDGE scanf("%d",&n); for(i=1;i<n;i++){ scanf("%d%d",&x,&y); list[x].push_back(y); list[y].push_back(x); } dad[1] = -1; dfs(1); dpUp[1] = 0; dfsUp(1); for(i=1;i<=n;i++) for(int j=0;j<list[i].size();j++) dpMax[i] = max(dpMax[i], dpDown[ list[i][j] ] ); ans = 20001; for(i=1;i<=n;i++){ int cc = max(dpUp[i],dpMax[i]); if(cc<ans) { ans = cc; ansid = i; } } printf("%d %d",ansid,ans); return 0; }
[ "atatomir5@gmail.com" ]
atatomir5@gmail.com
b36ad3b4fabd2bc726ab9d2829a1c91b7aefbeeb
32ada5e36b078504926dd55d7138f93adb7776b1
/Library/TrainingFolder2020/amppz2018/k.cpp
6634fe788b1b0cd3c2494a149bf7bf6e8e9f61d1
[]
no_license
SourangshuGhosh/olympiad
007a009adaeb9ecff3e2f5eb5e0b79f71dbca0b4
d8574f07ef733350a55d0b4a705b4418d43437b6
refs/heads/master
2022-11-25T14:32:43.741953
2020-07-28T16:56:23
2020-07-28T16:56:23
283,265,127
4
0
null
2020-07-28T16:15:43
2020-07-28T16:15:42
null
UTF-8
C++
false
false
1,371
cpp
#include <bits/stdc++.h> using namespace std; const int MAXN = 1000005; using lint = long long; int n; char mnv[MAXN], mxv[MAXN], str[MAXN]; int hmax[MAXN], sfxmin[MAXN]; int sgn(char c){ if(c == '0') return 0; if(c == '+') return 1; return -1; } lint validate(char *c){ int csgn = 0; lint ret = 0; for(int i=0; i<n; i++){ csgn += sgn(c[i]); if(csgn < 0){ puts("NIE"); exit(0); } ret += csgn; } if(csgn != 0){ puts("NIE"); exit(0); } return ret; } int main(){ cin >> str; n = strlen(str); for(int i=0; i<n; i++){ char c1 = str[i]; char c2 = str[i]; if(str[i] == '_') c1 = '-', c2 = '+'; hmax[i + 1] = hmax[i] + sgn(c2); } int cur = hmax[n]; memcpy(mxv, str, sizeof(str)); memcpy(mnv, str, sizeof(str)); for(int i=n-1; i>=0; i--){ if(mxv[i] == '_'){ if(cur >= 2) mxv[i] = '-', cur -= 2; else if(cur >= 1) mxv[i] = '0', cur -= 1; else mxv[i] = '+'; } } sfxmin[n+1] = 1e9; for(int i=n; i; i--){ sfxmin[i] = min(sfxmin[i + 1], hmax[i]); } int curh = 0; for(int i=0; i<n; i++){ if(mnv[i] == '_'){ if(curh - 1 + sfxmin[i+1] - hmax[i+1] >= 0) mnv[i] = '-'; else if(curh + sfxmin[i+1] - hmax[i+1] >= 0) mnv[i] = '0'; else mnv[i] = '+'; } curh += sgn(mnv[i]); } // cout << mnv << endl; // cout << mxv << endl; lint v1 = validate(mnv); lint v2 = validate(mxv); printf("%lld %lld\n", v1, v2); }
[ "koosaga@MacBook-Pro.local" ]
koosaga@MacBook-Pro.local
0a05971d92cfcfbb1e472d15677615954462b275
621ea614b1cd8c5c56cddf0a39f14f527e2209e9
/libraries/nRF24L01/Projects/Дистанционное управление с обратной связью/TX_response/TX_response.ino
d976ba5be441b1fea227ac46320eb402fb9c3eac
[]
no_license
koson/ss2s_hub
ce2a1941b006ed02f773e07aa65012d3211d252c
f540acd050979788ef61ad14c456a719bfd66ad6
refs/heads/master
2023-03-19T00:54:31.489150
2020-04-04T00:04:15
2020-04-04T00:04:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,444
ino
//--------------------- НАСТРОЙКИ ---------------------- #define CH_AMOUNT 8 // число каналов (должно совпадать с приёмником) #define CH_NUM 0x60 // номер канала (должен совпадать с приёмником) //--------------------- НАСТРОЙКИ ---------------------- //--------------------- ДЛЯ РАЗРАБОТЧИКОВ ----------------------- // УРОВЕНЬ МОЩНОСТИ ПЕРЕДАТЧИКА // На выбор RF24_PA_MIN, RF24_PA_LOW, RF24_PA_HIGH, RF24_PA_MAX #define SIG_POWER RF24_PA_LOW // СКОРОСТЬ ОБМЕНА // На выбор RF24_2MBPS, RF24_1MBPS, RF24_250KBPS // должна быть одинакова на приёмнике и передатчике! // при самой низкой скорости имеем самую высокую чувствительность и дальность!! // ВНИМАНИЕ!!! enableAckPayload НЕ РАБОТАЕТ НА СКОРОСТИ 250 kbps! #define SIG_SPEED RF24_1MBPS //--------------------- ДЛЯ РАЗРАБОТЧИКОВ ----------------------- //--------------------- БИБЛИОТЕКИ ---------------------- #include <SPI.h> #include "nRF24L01.h" #include "RF24.h" RF24 radio(9, 10); // "создать" модуль на пинах 9 и 10 Для Уно //RF24 radio(9, 53); // для Меги byte address[][6] = {"1Node", "2Node", "3Node", "4Node", "5Node", "6Node"}; // возможные номера труб //--------------------- БИБЛИОТЕКИ ---------------------- //--------------------- ПЕРЕМЕННЫЕ ---------------------- int transmit_data[CH_AMOUNT]; // массив пересылаемых данных int telemetry[2]; // массив принятых от приёмника данных телеметрии byte rssi; int trnsmtd_pack = 1, failed_pack; unsigned long RSSI_timer; //--------------------- ПЕРЕМЕННЫЕ ---------------------- void setup() { Serial.begin(9600); // открываем порт для связи с ПК radioSetup(); } void loop() { if (radio.write(&transmit_data, sizeof(transmit_data))) { // отправка пакета trnsmtd_pack++; if (!radio.available()) { // если получаем пустой ответ } else { while (radio.available() ) { // если в ответе что-то есть radio.read(&telemetry, sizeof(telemetry)); // читаем // получили забитый данными массив telemetry ответа от приёмника } } } else { failed_pack++; } if (millis() - RSSI_timer > 1000) { // таймер RSSI // рассчёт качества связи (0 - 100%) на основе числа ошибок и числа успешных передач rssi = (1 - ((float)failed_pack / trnsmtd_pack)) * 100; // сбросить значения failed_pack = 0; trnsmtd_pack = 0; RSSI_timer = millis(); } } void radioSetup() { radio.begin(); // активировать модуль radio.setAutoAck(1); // режим подтверждения приёма, 1 вкл 0 выкл radio.setRetries(0, 15); // (время между попыткой достучаться, число попыток) radio.enableAckPayload(); // разрешить отсылку данных в ответ на входящий сигнал radio.setPayloadSize(32); // размер пакета, в байтах radio.openWritingPipe(address[0]); // мы - труба 0, открываем канал для передачи данных radio.setChannel(CH_NUM); // выбираем канал (в котором нет шумов!) radio.setPALevel(SIG_POWER); // уровень мощности передатчика radio.setDataRate(SIG_SPEED); // скорость обмена // должна быть одинакова на приёмнике и передатчике! // при самой низкой скорости имеем самую высокую чувствительность и дальность!! radio.powerUp(); // начать работу radio.stopListening(); // не слушаем радиоэфир, мы передатчик }
[ "ss.samsung86@gmail.com" ]
ss.samsung86@gmail.com
4af5e9134fc85f0051366bee500a5cd1f0e59bdc
7ef1d66d1d27831558c2c7b4d756852264302643
/FYP data 参考/Qt windows circel icon/circlebutton/topbutton/widget.h
ff6b3e83ed095076cae9d4af195cd3c67b32021d
[]
no_license
15831944/Plasimo-display-assistant
9598dcba9cda870d2d3a91b1526b59cecd5cb5c5
4bad6f353b4373e033d592ff4af70be1cac36fb4
refs/heads/master
2023-03-16T18:22:07.167578
2018-01-23T14:58:56
2018-01-23T14:58:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
484
h
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QLabel> #include <QButtonGroup> namespace Ui { class Widget; } class Widget : public QWidget { Q_OBJECT public: explicit Widget(QWidget *parent = 0); ~Widget(); private: Ui::Widget *ui; QLabel *labellog;//登录 QLabel *labellogm;//数字 QLabel *labellogmoney;//收银员 QButtonGroup *m_pushButtonGroup; private slots: void buttonslot(int num=0); }; #endif // WIDGET_H
[ "362914124@qq.com" ]
362914124@qq.com
b9e5d4d496763b010fd48042946bce19ae46dde2
e50b837397bd9ad03471de010fbfc09d58285454
/src/iosocketdll/classes/CGenericMessage/CheckCheckSum.cpp
e9ef8c4bdae449a6d63c0818409a5382d4e1fbec
[]
no_license
tomy11245/spgame
568db63706d05434bda0de33509142b03a4b65af
295855b756127c582b9e750058175c4088e30d22
refs/heads/master
2021-01-20T09:41:02.970540
2015-01-15T09:25:50
2015-01-15T09:25:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
195
cpp
bool __thiscall CGenericMessage::CheckCheckSum() //+2440 { DecryptBody( (char *)(this+4) ,*(LPDWORD)this - 4); if ( this->MakeDigest() == *(LPDWORD)(this+0xC) ) return false; return true; }
[ "umehkg@users.noreply.github.com" ]
umehkg@users.noreply.github.com
310601ac771913858c66bca0bea2a7f80230fcaa
5322a839683e485fb6778d1a0b3849601c34bb19
/VBO.cpp
89e092b0d72cbfd442884c68a9e79d5e3763b404
[]
no_license
Patrikgyllvin/Game-Prototype
64a793bb642b36d469dc650eddaa071bb61c546e
db2941e2ef22d294cc3332ec01f125a9e5c8e98f
refs/heads/master
2022-04-09T05:55:14.917957
2020-02-14T19:23:47
2020-02-14T19:23:47
240,491,210
0
0
null
null
null
null
UTF-8
C++
false
false
392
cpp
#include "VBO.h" void VBO::create() { glGenBuffers( 1, &id ); } void VBO::bufferData( GLsizei size, GLvoid* data, GLenum drawMode) { glBufferData( GL_ARRAY_BUFFER, size, data, drawMode ); } void VBO::bind() { glBindBuffer( GL_ARRAY_BUFFER, id ); } void VBO::unbind() { glBindBuffer( GL_ARRAY_BUFFER, 0 ); } void VBO::destroy() { glDeleteBuffers( 1, &id ); }
[ "patrikgyllvin@icloud.com" ]
patrikgyllvin@icloud.com
69195555c3b403abfa801ba143d82229a9c3d031
38e04d83cab701a60729d6b909714075aec21867
/03_day/ex02/FragTrap.cpp
c4c4e81d177eee658f978651236269649c149164
[]
no_license
2ndcouteau/Piscine-Cpp
38bd61159fe5803ae67465b0e7174597f9e65ce1
9219612a0ef037dfcaf8dac0bc0634a6681213dc
refs/heads/master
2020-04-22T11:43:39.955278
2019-02-12T18:02:47
2019-02-12T18:02:47
170,350,999
1
0
null
null
null
null
UTF-8
C++
false
false
2,226
cpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* FragTrap.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: qrosa <qrosa@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/01/11 09:53:57 by qrosa #+# #+# */ /* Updated: 2019/01/11 21:05:58 by qrosa ### ########.fr */ /* */ /* ************************************************************************** */ #include "FragTrap.hpp" // CONSTRUTORS / DESTRUCTORS FragTrap::FragTrap(void) { std::cout << " FragTrap Default Constructor " << std::endl; } FragTrap::FragTrap(std::string name) : ClapTrap(name, 100, 100, 100, 100, 1, 30, 20, 5, 25) { std::cout << " FragTrap Default Constructor : Hellooo, VaultHunter, and thank you for answering Hyperion's summons! " << std::endl; return; } FragTrap::FragTrap(FragTrap const &src) { std::cout << " FragTrap Copy Constructor " << std::endl; *this = src; return; } FragTrap::~FragTrap(void) { std::cout << " FragTrap Destructor : Save Me! Save Me! Oops too late, I'm DEAD. TT" << std::endl; return; } void FragTrap::vaulthunter_dot_exe(std::string const & target) { std::string attacks[5] = { "Brra, Dildo in your face !", "Brrr Brrr Brrr Kalash Kalash!", "Toi et Moi, Octogone, pas d'arbitre...", "I am gonna Clap Clap Clap your Ass Ass Ass !", "MegaPunchOfTheDeath !" }; if (this->_energy_points < this->_energy_cost_attack) std::cout << "Not enough energy point to attack." << std::endl; else { this->_energy_points -= this->_energy_cost_attack; std::cout << "Valhunter's attack on " << target << ": \"" << attacks[std::rand() % 5] << "\"" << std::endl; } } FragTrap& FragTrap::operator=(FragTrap const & rhs) { ClapTrap::operator=(rhs); return(*this); }
[ "qrosa@e2r4p15.42.fr" ]
qrosa@e2r4p15.42.fr
902b252d06174ea73166051cafdcef595d969669
81bba18ddbf8f8d7145ec517f6496d4dc6193f7b
/05_learning/utilities.cpp
365d8189c82d1b6437c56702e6948371a12f139e
[]
no_license
voje/TV
a498fa23284433d844ff7e096f700efcc04cc3d6
cb2ec7be83cf6e7cdbbe9bf9f2aacc815e759e0c
refs/heads/master
2022-12-02T11:53:26.390231
2020-08-06T13:23:52
2020-08-06T13:24:00
54,552,511
0
0
null
null
null
null
UTF-8
C++
false
false
1,077
cpp
#include <sstream> #include <iostream> #include "utilities.h" #ifdef _WIN32 string join(const string& root, const string& path) { if (root[root.size()-1] == '\\') return root + path; else if (path[0] == '\\') return path; else return root + "\\" + path; } #else string join(const string& root, const string& path) { if (path[0] == '/') return path; else if (root[root.size()-1] == '/') return root + path; else return root + "/" + path; } #endif vector<string> &split(const string &s, char delimiter, vector<string> &elements) { stringstream ss(s); string item; while (getline(ss, item, delimiter)) elements.push_back(item); return elements; } vector<string> split(const string &s, char delimiter) { vector<string> elements; split(s, delimiter, elements); return elements; } void read(const FileNode& node, vector<string>& out) { if (node.isSeq()) { for (FileNodeIterator it = node.begin(); it != node.end(); it++) { out.push_back(string(*it)); } } }
[ "kristjan.voje@gmail.com" ]
kristjan.voje@gmail.com
5060b976ec9d56f7dfcd6dac756bcdc4c911ef46
968a4cb2feb13518940f9d125c4d6b5ae2094595
/Applications/AdaptiveParaView/Plugin/vtkGridSampler2.h
c0a26564e0bb0555e778c32348b11dee4c34a780
[ "LicenseRef-scancode-paraview-1.2" ]
permissive
wildmichael/ParaView3-enhancements-old
b4f2327e09cac3f81fa8c5cdb7a56bcdf960b6c1
d889161ab8458787ec7aa3d8163904b8d54f07c5
refs/heads/master
2021-05-26T12:33:58.622473
2009-10-29T09:17:57
2009-10-29T09:17:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,277
h
/*========================================================================= Program: Visualization Toolkit Module: $RCSfile: vtkGridSampler2.h,v $ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkGridSampler2 - A function that maps data extent and requested // resolution and data extent to i,j,k stride choice. // .SECTION Description // Supply this with a whole extent, then give it a resolution request. It // computes stride choices to match that resolution. Resolution of 0.0 is // defined as requesting minimal resolution, resolution of 1.0 is defined // as a request for full resolution (stride = 1,1,1). // // TODO: cache results! // separate out split path and stride determination // allow user specified stride and split determination // publish max splits via a Get method #ifndef __vtkGridSampler2_h #define __vtkGridSampler2_h #include "vtkObject.h" class vtkIntArray; class VTK_EXPORT vtkGridSampler2 : public vtkObject { public: static vtkGridSampler2 *New(); vtkTypeRevisionMacro(vtkGridSampler2,vtkObject); virtual void PrintSelf(ostream& os, vtkIndent indent); void SetWholeExtent(int *); vtkIntArray *GetSplitPath(); void SetSpacing(double *); void ComputeAtResolution(double r); void GetStrides(int *); void GetStridedExtent(int *); void GetStridedSpacing(double *); double GetStridedResolution(); protected: vtkGridSampler2(); ~vtkGridSampler2(); double SuggestSampling(int axis); void ComputeSplits(int *spLen, int **sp); int WholeExtent[6]; double Spacing[3]; double RequestedResolution; bool PathValid; bool SamplingValid; vtkIntArray *SplitPath; int Strides[3]; int StridedExtent[6]; double StridedResolution; double StridedSpacing[3]; private: vtkGridSampler2(const vtkGridSampler2&); // Not implemented. void operator=(const vtkGridSampler2&); }; #endif
[ "dave.demarle" ]
dave.demarle
483e5d73bd20c40b5af894cddef79d459722f374
6185d684498d6003c2fb968a87888a1c6f6fdc56
/EpgDataCap3/EpgDataCap3/Descriptor/BroadcasterNameDesc.cpp
acc65bf8fece09ec1c6ca27e763422353a270871
[]
no_license
Telurin/EDCB10.69_mod5
8a3791f497f20f7a82651fbf5c5615748c1a7e47
7585af187aa8fda74f2bb44bbb685264ecf566e1
refs/heads/master
2016-09-06T21:48:31.866335
2013-03-12T13:54:33
2013-03-12T13:54:33
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,596
cpp
#include "StdAfx.h" #include "BroadcasterNameDesc.h" CBroadcasterNameDesc::CBroadcasterNameDesc(void) { char_nameLength = 0; char_name = NULL; } CBroadcasterNameDesc::~CBroadcasterNameDesc(void) { SAFE_DELETE_ARRAY(char_name); } BOOL CBroadcasterNameDesc::Decode( BYTE* data, DWORD dataSize, DWORD* decodeReadSize ) { if( data == NULL ){ return FALSE; } SAFE_DELETE_ARRAY(char_name); char_nameLength = 0; ////////////////////////////////////////////////////// //サイズのチェック //最低限descriptor_tagとdescriptor_lengthのサイズは必須 if( dataSize < 2 ){ return FALSE; } //->サイズのチェック DWORD readSize = 0; ////////////////////////////////////////////////////// //解析処理 descriptor_tag = data[0]; descriptor_length = data[1]; readSize += 2; if( descriptor_tag != 0xD8 ){ //タグ値がおかしい _OutputDebugString( L"++++CBroadcasterNameDesc:: descriptor_tag err 0xD8 != 0x%02X", descriptor_tag ); return FALSE; } if( readSize+descriptor_length > dataSize ){ //サイズ異常 _OutputDebugString( L"++++CBroadcasterNameDesc:: size err %d > %d", readSize+descriptor_length, dataSize ); return FALSE; } if( descriptor_length > 0 ){ char_nameLength = descriptor_length; char_name = new CHAR[char_nameLength +1]; if( char_nameLength > 0 ){ memcpy(char_name, data+readSize, char_nameLength); } char_name[char_nameLength] = '\0'; readSize += char_nameLength; }else{ return FALSE; } //->解析処理 if( decodeReadSize != NULL ){ *decodeReadSize = 2+descriptor_length; } return TRUE; }
[ "epgdatabap@yahoo.co.jp" ]
epgdatabap@yahoo.co.jp
eac3bfbe5d0d6929ae3ee6ebd25d78440836eff3
b9c1098de9e26cedad92f6071b060dfeb790fbae
/src/formats/packed/pack_utils.h
8067dc027d1cd6815ba594058e0a8455fece4ee0
[]
no_license
vitamin-caig/zxtune
2a6f38a941f3ba2548a0eb8310eb5c61bb934dbe
9940f3f0b0b3b19e94a01cebf803d1a14ba028a1
refs/heads/master
2023-08-31T01:03:45.603265
2023-08-27T11:50:45
2023-08-27T11:51:26
13,986,319
138
13
null
2021-09-13T13:58:32
2013-10-30T12:51:01
C++
UTF-8
C++
false
false
3,905
h
/** * * @file * * @brief Packed-related utilities * * @author vitamin.caig@gmail.com * **/ #pragma once // common includes #include <types.h> // library includes #include <binary/data_builder.h> #include <binary/dump.h> // std includes #include <algorithm> #include <cassert> #include <cstring> class ByteStream { public: ByteStream(const uint8_t* data, std::size_t size) : Data(data) , End(Data + size) , Size(size) {} bool Eof() const { return Data >= End; } uint8_t GetByte() { return Eof() ? 0 : *Data++; } uint_t GetLEWord() { const uint_t lo = GetByte(); const uint_t hi = GetByte(); return 256 * hi + lo; } std::size_t GetRestBytes() const { return End - Data; } std::size_t GetProcessedBytes() const { return Size - GetRestBytes(); } private: const uint8_t* Data; const uint8_t* const End; const std::size_t Size; }; template<class Iterator, class ConstIterator> void RecursiveCopy(ConstIterator srcBegin, ConstIterator srcEnd, Iterator dstBegin) { const ConstIterator constDst = dstBegin; if (std::distance(srcEnd, constDst) >= 0) { std::copy(srcBegin, srcEnd, dstBegin); } else { Iterator dst = dstBegin; for (ConstIterator src = srcBegin; src != srcEnd; ++src, ++dst) { *dst = *src; } } } inline void Reverse(Binary::DataBuilder& data) { auto* start = &data.Get<uint8_t>(0); auto* end = start + data.Size(); std::reverse(start, end); } inline void Fill(Binary::DataBuilder& data, std::size_t count, uint8_t byte) { auto* dst = static_cast<uint8_t*>(data.Allocate(count)); std::fill_n(dst, count, byte); } template<class T> inline void Generate(Binary::DataBuilder& data, std::size_t count, T generator) { auto* dst = static_cast<uint8_t*>(data.Allocate(count)); std::generate_n(dst, count, std::move(generator)); } // offset to back inline bool CopyFromBack(std::size_t offset, Binary::DataBuilder& dst, std::size_t count) { if (offset > dst.Size()) { return false; // invalid backref } auto* dstStart = static_cast<uint8_t*>(dst.Allocate(count)); const auto* srcStart = dstStart - offset; RecursiveCopy(srcStart, srcStart + count, dstStart); return true; } // src - first or last byte of source data to copy (e.g. hl) // dst - first or last byte of target data to copy (e.g. de) // count - count of bytes to copy (e.g. bc) // dirCode - second byte of ldir/lddr operation (0xb8 for lddr, 0xb0 for ldir) class DataMovementChecker { public: DataMovementChecker(uint_t src, uint_t dst, uint_t count, uint_t dirCode) : Forward(0xb0 == dirCode) , Backward(0xb8 == dirCode) , Source(src) , Target(dst) , Size(count) { (void)Source; // to make compiler happy } bool IsValid() const { return Size && (Forward || Backward); // do not check other due to overlap possibility } uint_t FirstOfMovedData() const { assert(Forward != Backward); return Forward ? Target : (Target - Size + 1) & 0xffff; } uint_t LastOfMovedData() const { assert(Forward != Backward); return Backward ? Target : (Target + Size - 1) & 0xffff; } private: const bool Forward; const bool Backward; const uint_t Source; const uint_t Target; const uint_t Size; }; inline std::size_t MatchedSize(const uint8_t* dataBegin, const uint8_t* dataEnd, const uint8_t* patBegin, const uint8_t* patEnd) { const std::size_t dataSize = dataEnd - dataBegin; const std::size_t patSize = patEnd - patBegin; if (dataSize >= patSize) { const std::pair<const uint8_t*, const uint8_t*> mismatch = std::mismatch(patBegin, patEnd, dataBegin); return mismatch.first - patBegin; } else { const std::pair<const uint8_t*, const uint8_t*> mismatch = std::mismatch(dataBegin, dataEnd, patBegin); return mismatch.first - dataBegin; } }
[ "vitamin.caig@gmail.com" ]
vitamin.caig@gmail.com
d7072a09a4498f5974e46e79bf2829e128709100
40f608d1961960345da32c52a143269fe615ee01
/MPR121test/MPR121test.ino
ede715c7d81014f6ef2eaf9a23148bc626a208b9
[]
no_license
awk6873/arduino-elevator-model
c608d27fd2ba2db28baadc4d058d39da1a093398
280cea5cc4090e9a10d879e1d3a6df6087f55109
refs/heads/main
2023-04-20T16:10:08.529325
2021-05-05T16:42:12
2021-05-05T16:42:12
363,899,771
0
0
null
null
null
null
UTF-8
C++
false
false
2,555
ino
/********************************************************* This is a library for the MPR121 12-channel Capacitive touch sensor Designed specifically to work with the MPR121 Breakout in the Adafruit shop ----> https://www.adafruit.com/products/ These sensors use I2C communicate, at least 2 pins are required to interface Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by Limor Fried/Ladyada for Adafruit Industries. BSD license, all text above must be included in any redistribution **********************************************************/ #include <Wire.h> #include "Adafruit_MPR121.h" #ifndef _BV #define _BV(bit) (1 << (bit)) #endif // You can have up to 4 on one i2c bus but one is enough for testing! Adafruit_MPR121 cap = Adafruit_MPR121(); // Keeps track of the last pins touched // so we know when buttons are 'released' uint16_t lasttouched = 0; uint16_t currtouched = 0; void setup() { Serial.begin(9600); while (!Serial) { // needed to keep leonardo/micro from starting too fast! delay(10); } pinMode(A5, INPUT_PULLUP); Serial.println("Adafruit MPR121 Capacitive Touch sensor test"); // Default address is 0x5A, if tied to 3.3V its 0x5B // If tied to SDA its 0x5C and if SCL then 0x5D if (!cap.begin(0x5A)) { Serial.println("MPR121 not found, check wiring?"); while (1); } Serial.println("MPR121 found!"); } void loop() { // Get the currently touched pads currtouched = cap.touched(); for (uint8_t i=0; i<12; i++) { // it if *is* touched and *wasnt* touched before, alert! if ((currtouched & _BV(i)) && !(lasttouched & _BV(i)) ) { Serial.print(i); Serial.println(" touched"); } // if it *was* touched and now *isnt*, alert! if (!(currtouched & _BV(i)) && (lasttouched & _BV(i)) ) { Serial.print(i); Serial.println(" released"); } } // reset our state lasttouched = currtouched; // comment out this line for detailed data from the sensor! return; // debugging info, what Serial.print("\t\t\t\t\t\t\t\t\t\t\t\t\t 0x"); Serial.println(cap.touched(), HEX); Serial.print("Filt: "); for (uint8_t i=0; i<12; i++) { Serial.print(cap.filteredData(i)); Serial.print("\t"); } Serial.println(); Serial.print("Base: "); for (uint8_t i=0; i<12; i++) { Serial.print(cap.baselineData(i)); Serial.print("\t"); } Serial.println(); // put a delay so it isn't overwhelming delay(100); }
[ "akabaev@beeline.ru" ]
akabaev@beeline.ru
b4e00e41d838f1a370a00a88af69c64d6807a4fd
ed0124801e8cea3c955cd35de1e4b7de0c4cc7de
/base_server.h
d0d264611104513d62b9f9aa8195a9c44efe5569
[]
no_license
Pramy/agent
47287b22d75bb74041f68e28d70fc0153957f19c
e8a32ec4af093fc5116fb9331e4497037a06dd1b
refs/heads/master
2022-06-28T17:21:58.279131
2020-05-11T11:12:04
2020-05-11T11:13:36
257,616,156
1
0
null
null
null
null
UTF-8
C++
false
false
2,390
h
// // Created by tuffy on 2020/4/23. // #ifndef AGENT_BASE_SERVER_H #define AGENT_BASE_SERVER_H //#define PRINT(a) (std::cout << a << std::endl) #define ERROR_SOCKET (-1) #include <netdb.h> #include <string> #include <vector> #include <iostream> #include <functional> class BaseServer{ public: typedef int SocketFD; typedef std::function<void(SocketFD)> SocketCallFun; typedef std::function<bool(SocketFD, const addrinfo&)> SocketCreateCallFun; typedef std::function<void(SocketFD, const std::string&)> SocketMsgFun; BaseServer(): after_create_tasks(), after_accept_tasks(), after_connect_tasks(), before_read_tasks(), after_read_tasks(), before_write_tasks(), after_write_tasks() {}; virtual SocketFD CreateServer(const std::string &host, const int &port); virtual SocketFD CreateClient(const std::string &host, const int &port); virtual SocketFD Accept(SocketFD sock,sockaddr_in &remote_addr, socklen_t &len); virtual ssize_t Write(SocketFD socket_fd, const std::string &msg); virtual std::string Read(SocketFD socket_fd); virtual int Close(SocketFD socket_fd); bool IsTowPower(unsigned i); unsigned AdjustSize(unsigned i); void AddAfterCreateTasks(const SocketCallFun &fn); void AddAfterAcceptTasks(const SocketCallFun &fn); void AddAfterConnectTasks(const SocketCallFun &fn); void AddBeforeReadTasks(const SocketCallFun &fn); void AddAfterReadTasks(const SocketMsgFun &fn); void AddBeforeWriteTasks(const SocketMsgFun &fn); void AddAfterWriteTasks(const SocketMsgFun &fn); template <typename T, typename... Args> void RunAllTasks(const std::vector<T>& tasks, Args... args); virtual bool Connect(SocketFD sock, const addrinfo &addr); virtual bool BindAndListen(SocketFD sock, const addrinfo &addr); virtual SocketFD CreateSocket(const std::string &host, const int &port, const SocketCreateCallFun &fn); private: std::vector<SocketCallFun> after_create_tasks{}; std::vector<SocketCallFun> after_accept_tasks{}; std::vector<SocketCallFun> after_connect_tasks{}; std::vector<SocketCallFun> before_read_tasks{}; std::vector<SocketMsgFun> after_read_tasks{}; std::vector<SocketMsgFun> before_write_tasks{}; std::vector<SocketMsgFun> after_write_tasks{}; }; #endif // AGENT_BASE_SERVER_H
[ "tuffychen@tencent.com" ]
tuffychen@tencent.com
e34a540f90900cde3459117bb85a55eaa5f14a8a
cdc4256b1ef1bb68481299afcd7ced34f5c074a2
/PA3-1/src/dynamic_scene/draw_style.h
3fa6d4c2bd5070f3c26bc508fde907c46d125add
[]
no_license
JiyuanLu/CS184_UCB_S18
1ad43ce8e47ff201612960d009dde3c23f7d2634
8245989ae0db7e90a06574973debfb0550016e39
refs/heads/master
2022-12-11T02:30:38.218534
2019-11-11T03:34:56
2019-11-11T03:34:56
220,892,561
3
1
null
2022-12-09T00:57:51
2019-11-11T03:20:50
C
UTF-8
C++
false
false
890
h
#ifndef CGL_DYNAMICSCENE_DRAWSTYLE_H #define CGL_DYNAMICSCENE_DRAWSTYLE_H #include "scene.h" namespace CGL { namespace DynamicScene { /** * Used in rendering to specify how to draw the faces/meshes/lines/etc. */ class DrawStyle { public: void style_reset() const { glLineWidth(1); glPointSize(1); } void style_face() const { glColor4fv(&faceColor.r); } void style_edge() const { glColor4fv(&edgeColor.r); glLineWidth(strokeWidth); } void style_halfedge() const { glColor4fv(&halfedgeColor.r); glLineWidth(strokeWidth); } void style_vertex() const { glColor4fv(&vertexColor.r); glPointSize(vertexRadius); } Color halfedgeColor; Color vertexColor; Color edgeColor; Color faceColor; float strokeWidth; float vertexRadius; }; } // namespace DynamicScene } // namespace CGL #endif //CGL_DYNAMICSCENE_DRAWSTYLE_H
[ "chestnutrupert@gmail.com" ]
chestnutrupert@gmail.com
9ec5bc43e8bd499e50c5d5def012d35e95772856
6a8ffbac8a94c65f5a8e10ec62c6740c8837d952
/CombinedMethod.h
55bf26c8281096cbd11ccce5b4e9aec071fd8358
[]
no_license
gsabbih6/CFD_Practise
228ba7e5dda8f4b051d0461e2dd91ec3d534f31c
bd3c6874828c9c898305706149630b9f311394bc
refs/heads/master
2023-05-15T10:54:48.018904
2021-06-01T06:14:37
2021-06-01T06:14:37
314,637,886
0
0
null
null
null
null
UTF-8
C++
false
false
1,570
h
// // Created by Admin on 11/5/20. // #ifndef HW2_CFD_COMBINEDMETHOD_H #define HW2_CFD_COMBINEDMETHOD_H #include <iostream> #include <vector> using namespace std; class CombinedMethod { public: double simpleExplicit(double current, double prev, double next, double CFL); void crankNickolson(vector<vector<double> > &matrix, int Mdim, int Ndim, // double arow, double brow, double crow, vector<double> rmatrix); double rmsd(vector<double> residualTemp); double exact(double initTemp, double currT, double alpha, double space, double time); vector<vector<double>> computeCrankNicholson(vector<vector<double>> grid, double CFL); vector<vector<double>> computeSimpleExplicit(vector<vector<double>> grid, double CFL); vector<vector<double>> computeExact(vector<vector<double>> grid, double alpha, double deltaX, double deltaT); void myplot(int totalLength = 1, double deltaX = 0.05, int maxT = 3, double alpha = 0.1); void crankNickPlot(double timestep = 0.05, double totalLength = 1.0, double deltaX = 0.05, double maxT = 3, double alpha = 0.1); void simpleExplicPlot(double CFL = 0.45, double totalLength = 1, double deltaX = 0.05, double maxT = 3, double alpha = 0.1); vector<vector<double>> initialize(vector<vector<double>> grid, double solStepSize, double deltaX); double getTimeStep(double CLF, double deltaX, double alpha); }; #endif //HW2_CFD_COMBINEDMETHOD_H
[ "gsabbih5@gmail.comm" ]
gsabbih5@gmail.comm
3b2a8e225bfd25ff3fc2a7aef2fa5fab235c2860
d09945668f19bb4bc17087c0cb8ccbab2b2dd688
/atcoder/agc001-040/agc021/c.cpp
180263dadac3e2ea38540ec22af08bc2685beee8
[]
no_license
kmjp/procon
27270f605f3ae5d80fbdb28708318a6557273a57
8083028ece4be1460150aa3f0e69bdb57e510b53
refs/heads/master
2023-09-04T11:01:09.452170
2023-09-03T15:25:21
2023-09-03T15:25:21
30,825,508
23
2
null
2023-08-18T14:02:07
2015-02-15T11:25:23
C++
UTF-8
C++
false
false
2,240
cpp
#include <bits/stdc++.h> using namespace std; typedef signed long long ll; #undef _P #define _P(...) (void)printf(__VA_ARGS__) #define FOR(x,to) for(x=0;x<(to);x++) #define FORR(x,arr) for(auto& x:arr) #define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++) #define ALL(a) (a.begin()),(a.end()) #define ZERO(a) memset(a,0,sizeof(a)) #define MINUS(a) memset(a,0xff,sizeof(a)) //------------------------------------------------------- int H,W,A,B; int OH,OW,OA,OB; string S[1010]; void output() { int y; cout<<"YES"<<endl; FOR(y,OH) cout<<S[y]<<endl; exit(0); } void solve() { int i,j,k,l,r,x,y; string s; cin>>H>>W>>A>>B; if(H*W<2*(A+B)) return _P("NO\n"); OH=H,OW=W,OA=A,OB=B; FOR(y,H) S[y]=string(W,'.'); if(H%2==1) { for(x=0;x<W-1&&A;x+=2) S[H-1][x]='<', S[H-1][x+1]='>', A--; H--; } if(W%2==1) { for(y=0;y<H-1&&B;y+=2) S[y][W-1]='^', S[y+1][W-1]='v', B--; W--; } for(y=0;y<H;y+=2) { for(x=0;x<W;x+=2) { if(A) { S[y][x]='<', S[y][x+1]='>', A--; if(A) S[y+1][x]='<', S[y+1][x+1]='>', A--; } else if(B) { S[y][x]='^', S[y+1][x]='v', B--; if(B) S[y][x+1]='^', S[y+1][x+1]='v', B--; } } } if(A==0 && B==0) output(); H=OH,W=OW,A=OA,B=OB; if(H%2 && W%2 && H>=3 && W>=3 && A>=2 && B>=2) { A-=2; B-=2; FOR(y,H) S[y]=string(W,'.'); S[H-3][W-3]=S[H-1][W-2]='<'; S[H-3][W-2]=S[H-1][W-1]='>'; S[H-2][W-3]=S[H-3][W-1]='^'; S[H-1][W-3]=S[H-2][W-1]='v'; for(y=0;y<H-3&&B;y+=2) S[y][W-1]='^',S[y+1][W-1]='v',B--; for(x=0;x<W-3&&A;x+=2) S[H-1][x]='<',S[H-1][x+1]='>',A--; for(y=0;y<H-1;y+=2) { for(x=0;x<W-1;x+=2) { if(S[y][x]!='.') continue; if(A) { S[y][x]='<', S[y][x+1]='>', A--; if(A) S[y+1][x]='<', S[y+1][x+1]='>', A--; } else if(B) { S[y][x]='^', S[y+1][x]='v', B--; if(B) S[y][x+1]='^', S[y+1][x+1]='v', B--; } } } if(A==0 && B==0) output(); } cout<<"NO"<<endl; } int main(int argc,char** argv){ string s;int i; if(argc==1) ios::sync_with_stdio(false), cin.tie(0); FOR(i,argc-1) s+=argv[i+1],s+='\n'; FOR(i,s.size()) ungetc(s[s.size()-1-i],stdin); cout.tie(0); solve(); return 0; }
[ "kmjp@users.noreply.github.com" ]
kmjp@users.noreply.github.com
529cc5f916cc090f6c4eeb5201a5e8c3b972e9ca
b63d8a7b366b9e9ed3108acbcf5c1b2ef14c2699
/05 - Contest - Stacks and Binary Search/04 - C impresses everyone.cpp
c9ca2f6d2793ece70c522e8038cfa2df4130a80e
[]
no_license
pedroccufc/programming-challenges
6da2db0c6d47fe702c4eb6a06198a07c0829b8be
6cc119c68f59d135434e2869efb79fe4e474cdf4
refs/heads/master
2021-02-12T21:16:01.617928
2020-08-28T03:10:22
2020-08-28T03:10:22
244,631,575
0
0
null
null
null
null
UTF-8
C++
false
false
592
cpp
#include <bits/stdc++.h> #define ALL(C) C.begin(), C.end() using namespace std; typedef long long ll; int main(){ // Número de voltas ll N; cin >> N; // Sequência de pedras adicionadas a cada turno std::vector<ll> A; A.resize(N+1); A[0] = 0; for (ll i = 1; i <= N; i++) { cin >> A[i]; A[i] += A[i-1]; } // Número de consultas ll Q, x; cin >> Q; for (ll i = 0; i < Q; i++) { cin >> x; int idx = A[N] - x + 1; idx = std::lower_bound(ALL(A), idx) - A.begin(); if (idx & 1) { cout << "A" << endl; } else { cout << "B" << endl; } } return 0; }
[ "pedroccufc@gmail.com" ]
pedroccufc@gmail.com
f8536e35e1ed91023b317ecb18f87dca640b8387
18b1b51b1fcc43c2fae3d62b90f6d8fc96c739d0
/VirtualAudioCable/JumpDesktopAudio/AdapterCommon.cpp
2f3bb9f07f292d27f9ec214243440d0d4e815704
[]
no_license
Blizzy01/TempStorage
8eed0c23e0786c9783d8b309fa01a9af635c3349
367c904a8bf213d4d3a4a67115116f836a3f9a53
refs/heads/master
2023-07-03T15:48:56.651397
2021-05-01T19:05:34
2021-05-01T19:05:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,619
cpp
#include "AdapterCommon.h" #include "RegistryHelper.h" #include "SubdeviceHelper.h" #include "MinipairDescriptorFactory.h" #include "MiniportWaveRT.h" LONG AdapterCommon::m_Instances = 0; AdapterCommon::~AdapterCommon() { PAGED_CODE(); DPF_ENTER(("[CAdapterCommon::~CAdapterCommon]")); if (m_pDeviceHelper) { ExFreePoolWithTag(m_pDeviceHelper, MINIADAPTER_POOLTAG); } InterlockedDecrement(&AdapterCommon::m_Instances); ASSERT(AdapterCommon::m_Instances == 0); } /* Creates a new AdapterCommon Arguments: Unknown - UnknownOuter - PoolType */ NTSTATUS AdapterCommon::Create ( _Out_ PUNKNOWN * Unknown, _In_ REFCLSID, _In_opt_ PUNKNOWN UnknownOuter, _When_((PoolType & NonPagedPoolMustSucceed) != 0, __drv_reportError("Must succeed pool allocations are forbidden. " "Allocation failures cause a system crash")) _In_ POOL_TYPE PoolType, _In_ PDEVICE_OBJECT DeviceObject, _In_ PIRP StartupIrp ) { PAGED_CODE(); DPF_ENTER(("[CAdapterCommon::Create]")); ASSERT(Unknown); ASSERT(StartupIrp); NTSTATUS ntStatus; // // This is a singleton, check before creating instance. // if (InterlockedCompareExchange(&AdapterCommon::m_Instances, 1, 0) != 0) { ntStatus = STATUS_DEVICE_BUSY; DPF(D_TERSE, ("NewAdapterCommon failed, adapter already created.")); goto Done; } // // Allocate an adapter object. // AdapterCommon* p = new(PoolType, MINIADAPTER_POOLTAG) AdapterCommon(UnknownOuter); if (p == NULL) { ntStatus = STATUS_INSUFFICIENT_RESOURCES; DPF(D_TERSE, ("NewAdapterCommon failed, 0x%x", ntStatus)); goto Done; } ntStatus = p->Init(StartupIrp, DeviceObject); IF_FAILED_ACTION_RETURN(ntStatus, DPF(D_TERSE, ("Error initializing Adapter, 0x%x", ntStatus))); // // Success. // *Unknown = PUNKNOWN((IAdapterCommon*)(p)); (*Unknown)->AddRef(); ntStatus = STATUS_SUCCESS; Done: return ntStatus; } // NewAdapterCommon /* Initialize the Adapter. */ NTSTATUS __stdcall AdapterCommon::Init(IRP* StartupIrp, PDEVICE_OBJECT DeviceObject) { PAGED_CODE(); DPF_ENTER(("[CAdapterCommon::Init]")); ASSERT(DeviceObject); NTSTATUS ntStatus = STATUS_SUCCESS; m_pDeviceObject = DeviceObject; m_pDeviceHelper = new(NonPagedPoolNx, MINIADAPTER_POOLTAG) SubdeviceHelper(this); if (!m_pDeviceHelper) { m_pDeviceHelper = NULL; ntStatus = STATUS_INSUFFICIENT_RESOURCES; } if (NT_SUCCESS(ntStatus)) { ntStatus = PcGetPhysicalDeviceObject(DeviceObject, &m_pPhysicalDeviceObject); if (!NT_SUCCESS(ntStatus)) DPF(D_TERSE, ("PcGetPhysicalDeviceObject failed, 0x%x", ntStatus)); } ntStatus = InstallVirtualCable(StartupIrp); IF_FAILED_ACTION_RETURN(ntStatus, DPF(D_TERSE, ("InstallVirtualCable failed, 0x%x", ntStatus))); if (!NT_SUCCESS(ntStatus)) { m_pDeviceObject = NULL; if (m_pDeviceHelper) ExFreePoolWithTag(m_pDeviceHelper, MINIADAPTER_POOLTAG); m_pPhysicalDeviceObject = NULL; } return ntStatus; } NTSTATUS AdapterCommon::InstallVirtualCable(IRP * irp) { NTSTATUS ntStatus = STATUS_SUCCESS; IUnknown* unknownMic; IUnknown* unknownSpeaker; ntStatus = InstallVirtualMic(irp, &unknownMic); IF_FAILED_ACTION_RETURN(ntStatus, DPF(D_TERSE, ("InstallVirtualMic failed, 0x%x", ntStatus))); ntStatus = InstallVirtualSpeaker(irp, &unknownSpeaker); IF_FAILED_ACTION_RETURN(ntStatus, DPF(D_TERSE, ("InstallVirtualSpeaker failed, 0x%x", ntStatus))); // Is there a purpuse for this code to exist ? // Not checking return value MiniportWaveRT* microphone; ntStatus = unknownMic->QueryInterface(IID_MiniportWaveRT, (PVOID*)&microphone); MiniportWaveRT* speaker; ntStatus = unknownSpeaker->QueryInterface(IID_MiniportWaveRT, (PVOID*)&speaker); microphone->SetPairedMiniport(speaker); return STATUS_SUCCESS; } NTSTATUS AdapterCommon::InstallVirtualMic(IRP* Irp, IUnknown** unknownMiniport) { PAGED_CODE(); NTSTATUS ntStatus = STATUS_NOT_IMPLEMENTED; ENDPOINT_MINIPAIR* pCaptureMiniport = NULL; ntStatus = MinipairDescriptorFactory::CreateMicrophone(&pCaptureMiniport); if (!NT_SUCCESS(ntStatus)) { return ntStatus; } // Missing status code check m_pDeviceHelper->InstallMinipair(Irp, pCaptureMiniport, NULL, NULL, NULL, NULL, unknownMiniport); return ntStatus; } NTSTATUS AdapterCommon::InstallVirtualSpeaker(IRP* Irp, IUnknown** unknownMiniport) { PAGED_CODE(); NTSTATUS ntStatus = STATUS_NOT_IMPLEMENTED; ENDPOINT_MINIPAIR* pRenderMiniport = NULL; ntStatus = MinipairDescriptorFactory::CreateSpeaker(&pRenderMiniport); if (!NT_SUCCESS(ntStatus)) { return ntStatus; } // Missing status code check m_pDeviceHelper->InstallMinipair(Irp, pRenderMiniport, NULL, NULL, NULL, NULL, unknownMiniport); return ntStatus; } STDMETHODIMP AdapterCommon::NonDelegatingQueryInterface ( _In_ REFIID Interface, _COM_Outptr_ PVOID * Object ) /*++ Routine Description: QueryInterface routine for AdapterCommon Arguments: Interface - Object - Return Value: NT status code. --*/ { PAGED_CODE(); ASSERT(Object); if (IsEqualGUIDAligned(Interface, IID_IUnknown)) { *Object = PVOID(PUNKNOWN((IAdapterCommon*)(this))); } else if (IsEqualGUIDAligned(Interface, IID_IAdapterCommon)) { *Object = PVOID((IAdapterCommon*)(this)); } else if (IsEqualGUIDAligned(Interface, IID_IAdapterPowerManagement)) { *Object = PVOID(PADAPTERPOWERMANAGEMENT(this)); } else { *Object = NULL; } if (*Object) { PUNKNOWN(*Object)->AddRef(); return STATUS_SUCCESS; } return STATUS_INVALID_PARAMETER; } // NonDelegatingQueryInterface PDEVICE_OBJECT __stdcall AdapterCommon::GetDeviceObject(void) { return m_pDeviceObject; } PDEVICE_OBJECT __stdcall AdapterCommon::GetPhysicalDeviceObject(void) { return m_pPhysicalDeviceObject; } #pragma code_seg() NTSTATUS __stdcall AdapterCommon::WriteEtwEvent(EPcMiniportEngineEvent miniportEventType, ULONGLONG ullData1, ULONGLONG ullData2, ULONGLONG ullData3, ULONGLONG ullData4) { NTSTATUS ntStatus = STATUS_SUCCESS; if (m_pPortClsEtwHelper) { ntStatus = m_pPortClsEtwHelper->MiniportWriteEtwEvent(miniportEventType, ullData1, ullData2, ullData3, ullData4); } return ntStatus; } #pragma code_seg("PAGE") void __stdcall AdapterCommon::SetEtwHelper(PPORTCLSETWHELPER _pPortClsEtwHelper) { PAGED_CODE(); SAFE_RELEASE(m_pPortClsEtwHelper); m_pPortClsEtwHelper = _pPortClsEtwHelper; if (m_pPortClsEtwHelper) { m_pPortClsEtwHelper->AddRef(); } } void __stdcall AdapterCommon::Cleanup() { PAGED_CODE(); DPF_ENTER(("[AdapterCommon::Cleanup]")); // Non consistent coding style if (m_pDeviceHelper) m_pDeviceHelper->Clean(); }
[ "Tudi@users.noreply.github.com" ]
Tudi@users.noreply.github.com
5570d1e1f25dcc0b32bbfb6783bfb775d2ce656a
9b06cdf4b01150b4c144599c5db5b7c82fb554b4
/libraries/AirConditioner/AirConditionerDisplay.cpp
d2509fdc44c30ad55b0399d4b6fbdc96d091c941
[]
no_license
RafaelSilva-RFS/Air-Conditioner-Remote
42282cb4688db1bf753361e8570357539e8a47d9
e908167e87f6865d4b83be5156a967dfc3054179
refs/heads/main
2023-04-03T15:33:16.915871
2021-04-21T03:20:03
2021-04-21T03:20:03
327,997,064
0
0
null
null
null
null
UTF-8
C++
false
false
7,459
cpp
#include "Arduino.h" #include "AirConditionerDisplay.h" AirConditionerDisplay::AirConditionerDisplay(){ }; void AirConditionerDisplay::Init(Adafruit_SSD1306 _display, AirConditionerEstateModel AirConditionerEstateDto){ display = _display; // Show initial display buffer contents on the screen -- the library initializes this with an Adafruit splash screen. display.display(); delay(2000); // Pause for 2 seconds // Clear the buffer display.clearDisplay(); DisplayUpdate(AirConditionerEstateDto); // DrawClock(10, 33); display.display(); }; void AirConditionerDisplay::DisplayUpdate(AirConditionerEstateModel AirConditionerEstateDto){ //On/Off if(AirConditionerEstateDto.OnOff != AirConditionerPreviousEstateDto.OnOff && AirConditionerEstateDto.OnOff == 0) { display.clearDisplay(); display.display(); AirConditionerPreviousEstateDto.OnOff = AirConditionerEstateDto.OnOff; return; } else if(AirConditionerEstateDto.OnOff != AirConditionerPreviousEstateDto.OnOff && AirConditionerEstateDto.OnOff == 1) { display.clearDisplay(); DrawDegrees(AirConditionerEstateDto.Degrees, AirConditionerEstateDto.DegreesMode); DrawTemperatureMode(AirConditionerEstateDto.DegreesMode); DrawCoolMode(AirConditionerEstateDto.CoolMode); DrawFanMode(AirConditionerEstateDto.FanMode); DrawSleepMode(AirConditionerEstateDto.SleepClock); AirConditionerPreviousEstateDto.OnOff = AirConditionerEstateDto.OnOff; AirConditionerPreviousEstateDto.FanMode = AirConditionerEstateDto.FanMode; AirConditionerPreviousEstateDto.Degrees = AirConditionerEstateDto.Degrees; AirConditionerPreviousEstateDto.CoolMode = AirConditionerEstateDto.CoolMode; AirConditionerPreviousEstateDto.SleepClock = AirConditionerEstateDto.SleepClock; AirConditionerPreviousEstateDto.DegreesMode = AirConditionerEstateDto.DegreesMode; return; }; // DrawDegrees if(AirConditionerEstateDto.Degrees != AirConditionerPreviousEstateDto.Degrees) { DrawDegrees(AirConditionerEstateDto.Degrees, AirConditionerEstateDto.DegreesMode); AirConditionerPreviousEstateDto.Degrees = AirConditionerEstateDto.Degrees; }; // DrawTemperatureMode if(AirConditionerEstateDto.DegreesMode != AirConditionerPreviousEstateDto.DegreesMode) { DrawTemperatureMode(AirConditionerEstateDto.DegreesMode); DrawDegrees(AirConditionerEstateDto.Degrees, AirConditionerEstateDto.DegreesMode); AirConditionerPreviousEstateDto.DegreesMode = AirConditionerEstateDto.DegreesMode; }; // DrawCoolMode if(AirConditionerEstateDto.CoolMode != AirConditionerPreviousEstateDto.CoolMode) { DrawCoolMode(AirConditionerEstateDto.CoolMode); AirConditionerPreviousEstateDto.CoolMode = AirConditionerEstateDto.CoolMode; }; // DrawFanMode if(AirConditionerEstateDto.FanMode != AirConditionerPreviousEstateDto.FanMode) { DrawFanMode(AirConditionerEstateDto.FanMode); AirConditionerPreviousEstateDto.FanMode = AirConditionerEstateDto.FanMode; }; // DrawSleepMode if(AirConditionerEstateDto.SleepClock != AirConditionerPreviousEstateDto.SleepClock) { DrawSleepMode(AirConditionerEstateDto.SleepClock); AirConditionerPreviousEstateDto.SleepClock = AirConditionerEstateDto.SleepClock; }; }; void AirConditionerDisplay::DrawCentreString(const String &buf, int x, int y) { display.setTextSize(3); display.setTextColor(SSD1306_WHITE); int16_t x1, y1; uint16_t w, h; display.getTextBounds(buf, x, y, &x1, &y1, &w, &h); //calc width of new string int16_t cursorX = (display.width() - w) / 2; int16_t cursorY = (display.height() - h) / 2; display.setCursor(cursorX, cursorY); display.print(buf); display.display(); }; void AirConditionerDisplay::DrawDegrees(int degreeIndex, int temperatureIndex){ CleanDegrees(); if(temperatureIndex == 0) { DrawCentreString(TemperatureCelsius[degreeIndex], 0, -38); }; if(temperatureIndex == 1) { DrawCentreString(TemperatureFahrenheit[degreeIndex], 0, -38); }; display.display(); }; void AirConditionerDisplay::CleanDegrees(){ display.fillRect (0, 13, 128, 21, SSD1306_BLACK); }; void AirConditionerDisplay::DrawFanMode(int fanModeIndex){ CleanFanMode(); switch(fanModeIndex) { case 0: display.drawBitmap(20, 47, fan3Icon, 16, 16, 1); break; case 1: display.drawBitmap(20, 47, fan2Icon, 16, 16, 1); break; case 2: display.drawBitmap(20, 47, fan1Icon, 16, 16, 1); break; case 3: display.drawBitmap(20, 47, autoIcon, 16, 16, 1); break; }; display.display(); }; void AirConditionerDisplay::CleanFanMode(){ display.fillRect (19, 48, 16, 16, SSD1306_BLACK); }; void AirConditionerDisplay::DrawCoolMode(int coolModeIndex){ CleanCoolMode(); switch(coolModeIndex) { case 0: display.drawBitmap(0, 48, autoIcon, 16, 16, 1); break; case 1: display.drawBitmap(0, 48, airConditionerIcon, 16, 16, 1); break; case 2: display.drawBitmap(0, 48, umidityIcon, 16, 16, 1); break; case 3: display.drawBitmap(0, 48, fan3Icon, 16, 16, 1); break; case 4: display.drawBitmap(0, 48, heaterIcon, 16, 16, 1); break; }; display.display(); }; void AirConditionerDisplay::CleanCoolMode(){ display.fillRect (0, 48, 16, 16, SSD1306_BLACK); }; void AirConditionerDisplay::DrawTemperatureMode(int temperatureIndex){ CleanTemperatureMode(); display.setTextSize(1); display.setTextColor(SSD1306_WHITE); display.setCursor(113, -2); display.write(9); display.setCursor(119, 0); if(temperatureIndex == 0) { display.print(F("C")); }; if(temperatureIndex == 1) { display.print(F("F")); }; display.display(); }; void AirConditionerDisplay::CleanTemperatureMode(){ display.fillRect (114, 0, 14, 7, SSD1306_BLACK); }; void AirConditionerDisplay::DrawSleepMode(int sleepModeIndex){ sleepHours = ""; sleepHours.concat(sleepModeIndex); sleepHours.concat("h"); CleanSleepMode(); if(sleepModeIndex > 0) { display.drawBitmap(40, 48, sleepOnIcon, 16, 16, 1); display.setCursor(60, 53); display.setTextSize(1); display.setTextColor(SSD1306_WHITE); display.print(sleepHours); } display.display(); }; void AirConditionerDisplay::CleanSleepMode(){ display.fillRect (38, 48, 40, 16, SSD1306_BLACK); }; void AirConditionerDisplay::DrawClock(int hour, int min){ CleanDrawClock(); clockHours = ""; clockHours.concat(hour); clockHours.concat(":"); if(min < 10 ) { clockHours.concat("0"); }; clockHours.concat(min); display.setTextSize(1); display.setTextColor(SSD1306_WHITE); display.setCursor(95, 53); display.print(clockHours); // Corrige falha na tela display.fillRect (0, 0, 10, 10, SSD1306_BLACK); display.display(); }; void AirConditionerDisplay::CleanDrawClock(){ display.fillRect (78, 48, 50, 16, SSD1306_BLACK); };
[ "rfs_designer@live.com" ]
rfs_designer@live.com
7ef72034505a16c4832a9507604d2354d451944d
e3317469bb30b0a211fd9bb918661c00359ef4a5
/MMCMonitorApp/mmcdisplaytablemodel.cpp
0a2258cca9f74d90ae7d8f9e0f8929465c4ef18e
[]
no_license
pipi95/MMCMonitor
132fe724a31f0c61e70053d44596ceea19125a57
76f2838c43909f9cf530a9bb284fb97e2fd20648
refs/heads/master
2020-03-28T22:36:26.218622
2018-09-18T08:25:49
2018-09-18T08:25:49
149,244,280
0
0
null
null
null
null
UTF-8
C++
false
false
716
cpp
#include "mmcdisplaytablemodel.h" MMCDisplayTableModel::MMCDisplayTableModel(QObject* parent) : QAbstractTableModel(parent) { } int MMCDisplayTableModel::rowCount(const QModelIndex& ) const { return numberOfContent; } int MMCDisplayTableModel::columnCount(const QModelIndex& ) const { return numberOfColumn; } QModelIndex MMCDisplayTableModel::parent(const QModelIndex& ) const { return QModelIndex(); } QVariant MMCDisplayTableModel::data(const QModelIndex& index, int role) const { switch (role) { case Qt::DisplayRole: return QVariant("Null data"); default: return QVariant("Null data"); } } void MMCDisplayTableModel::ParseFrame(const EquipFrame& fr) { }
[ "pipi95@163.com" ]
pipi95@163.com
101ae1e3d090d475b0a0cc594adf4268f4042226
62400f20b4d4aa8e51cd72805e258470e99c5dcf
/Network - Client/networkManager.cpp
53eebec271b7c769c7c56441f95fa442c3ee18e4
[]
no_license
Rhanjie/Network---TheGame
2860e1a5091695da1da8cec741c072b4c0dccfaf
6ad43a583455c17e4a1904d60104dd16cfba98f9
refs/heads/master
2016-08-07T11:52:24.346820
2015-06-03T20:11:06
2015-06-03T20:11:06
30,471,894
3
0
null
null
null
null
UTF-8
C++
false
false
865
cpp
#include "networkManager.hpp" bool rha::cNetworkManager::sendPacket(sf::TcpSocket* socket, sf::Packet* packet){ if(socket->send(*packet)==sf::Socket::Done) return true; else return false; } bool rha::cNetworkManager::sendRawPacket(sf::TcpSocket* socket, rha::typePacketsInClient typePacket){ sPacket<<typePacket; if(socket->send(sPacket)==sf::Socket::Done){sPacket.clear(); return true;} else{sPacket.clear(); return false;} } bool rha::cNetworkManager::receivePacket(sf::TcpSocket* socket){ if(socket->receive(this->dataPacket)==sf::Socket::Done){ if(this->dataPacket>>converter){ tLastPacketReceive=static_cast<rha::typePacketsInServer>(converter); return true; } else return false; }else{tLastPacketReceive=rha::typePacketsInServer::NORMAL_SERVER_NULL; return false; } }
[ "mdyla99@interia.pl" ]
mdyla99@interia.pl
696e578d27a59d9d2158070d155a8eb5f9cb2c6a
78f0044cab0c14205c7fe2a00067fe7aebe9eba3
/Communicational abilities/CyborgWorkspace/devel/include/speech_processing/Num.h
c96b8205ac54ee48a7b123e2d69eb22c7d4d02b7
[]
no_license
thentnucyborg/CyborgRobot_v1_archive
7ad8959b2e5f5cb5418699b9d93c2b41f962613c
fc1419d229f379063668684c51faaeb6cb6ba447
refs/heads/master
2021-01-16T05:14:51.804599
2020-02-25T11:51:39
2020-02-25T11:51:39
242,987,310
0
0
null
null
null
null
UTF-8
C++
false
false
6,458
h
/* Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, 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 Willow Garage, 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. * * Auto-generated by genmsg_cpp from file /home/viki/Desktop/speech_ws/src/speech_processing/msg/Num.msg * */ #ifndef SPEECH_PROCESSING_MESSAGE_NUM_H #define SPEECH_PROCESSING_MESSAGE_NUM_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> namespace speech_processing { template <class ContainerAllocator> struct Num_ { typedef Num_<ContainerAllocator> Type; Num_() : num(0) { } Num_(const ContainerAllocator& _alloc) : num(0) { } typedef int16_t _num_type; _num_type num; typedef boost::shared_ptr< ::speech_processing::Num_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::speech_processing::Num_<ContainerAllocator> const> ConstPtr; boost::shared_ptr<std::map<std::string, std::string> > __connection_header; }; // struct Num_ typedef ::speech_processing::Num_<std::allocator<void> > Num; typedef boost::shared_ptr< ::speech_processing::Num > NumPtr; typedef boost::shared_ptr< ::speech_processing::Num const> NumConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::speech_processing::Num_<ContainerAllocator> & v) { ros::message_operations::Printer< ::speech_processing::Num_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace speech_processing namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False} // {'speech_processing': ['/home/viki/Desktop/speech_ws/src/speech_processing/msg'], 'std_msgs': ['/opt/ros/hydro/share/std_msgs/cmake/../msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::speech_processing::Num_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsFixedSize< ::speech_processing::Num_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::speech_processing::Num_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::speech_processing::Num_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::speech_processing::Num_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::speech_processing::Num_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::speech_processing::Num_<ContainerAllocator> > { static const char* value() { return "79e2a05b252e69632375170571b25d3d"; } static const char* value(const ::speech_processing::Num_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x79e2a05b252e6963ULL; static const uint64_t static_value2 = 0x2375170571b25d3dULL; }; template<class ContainerAllocator> struct DataType< ::speech_processing::Num_<ContainerAllocator> > { static const char* value() { return "speech_processing/Num"; } static const char* value(const ::speech_processing::Num_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::speech_processing::Num_<ContainerAllocator> > { static const char* value() { return "int16 num\n\ "; } static const char* value(const ::speech_processing::Num_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::speech_processing::Num_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.num); } ROS_DECLARE_ALLINONE_SERIALIZER; }; // struct Num_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::speech_processing::Num_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::speech_processing::Num_<ContainerAllocator>& v) { s << indent << "num: "; Printer<int16_t>::stream(s, indent + " ", v.num); } }; } // namespace message_operations } // namespace ros #endif // SPEECH_PROCESSING_MESSAGE_NUM_H
[ "martinius.knudsen@ntnu.no" ]
martinius.knudsen@ntnu.no
2917a1ed363ad39cde34be61c1c8d54f9b173b51
488706ddcd860941510ddd5c8f35bbd065de9ca1
/visualtext3/cj/Ribbon/XTPRibbonControlTab.h
c737961ed39988fc6e0286cb38e8dc498f43a80b
[]
no_license
VisualText/legacy
8fabbf1da142dfac1a47f4759103671c84ee64fe
73d3dee26ab988e61507713ca37c4e9c0416aee5
refs/heads/main
2023-08-14T08:14:25.178165
2021-09-27T22:41:00
2021-09-27T22:41:00
411,052,445
0
0
null
2021-09-27T22:40:55
2021-09-27T21:48:09
C++
UTF-8
C++
false
false
12,521
h
// XTPRibbonControlTab.h: interface for the CXTPRibbonControlTab class. // // This file is a part of the XTREME RIBBON MFC class library. // (c)1998-2013 Codejock Software, All Rights Reserved. // // THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE // RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN // CONSENT OF CODEJOCK SOFTWARE. // // THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED // IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO // YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A // SINGLE COMPUTER. // // CONTACT INFORMATION: // support@codejock.com // http://www.codejock.com // ///////////////////////////////////////////////////////////////////////////// //{{AFX_CODEJOCK_PRIVATE #if !defined(__XTPRIBBONCONTROLTAB_H__) #define __XTPRIBBONCONTROLTAB_H__ //}}AFX_CODEJOCK_PRIVATE #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CXTPRibbonGroups; class CXTPRibbonBar; class CXTPRibbonGroup; class CXTPRibbonTab; //----------------------------------------------------------------------- // Summary: // Structure used as parameter for TCN_SELCHANGING and TCN_SELCHANGE messages when Ribbon tab is changed //----------------------------------------------------------------------- struct NMXTPTABCHANGE : public NMXTPCONTROL { CXTPRibbonTab* pTab; // Ribbon Tab to be selected }; //=========================================================================== // Summary: // CXTPRibbonControlTab is a CXTPTabManager derived class, It represents tabs of the ribbon bar //=========================================================================== class _XTP_EXT_CLASS CXTPRibbonControlTab : public CXTPControlPopup, public CXTPTabManager { DECLARE_XTP_CONTROL(CXTPRibbonControlTab) public: //----------------------------------------------------------------------- // Summary: // Constructs a CXTPRibbonControlTab object //----------------------------------------------------------------------- CXTPRibbonControlTab(); //----------------------------------------------------------------------- // Summary: // Destroys a CXTPRibbonControlTab object, handles cleanup and deallocation //----------------------------------------------------------------------- virtual ~CXTPRibbonControlTab(); public: //----------------------------------------------------------------------- // Summary: // Call this member to get a pointer to the tab paint manager. // The tab paint manager is used to customize the appearance of // CXTPTabManagerItem objects and the tab manager. I.e. Tab colors, // styles, etc... This member must be overridden in // derived classes. // Returns: // Pointer to CXTPTabPaintManager that contains the visual elements // of the tabs. //----------------------------------------------------------------------- virtual CXTPTabPaintManager* GetPaintManager() const; //----------------------------------------------------------------------- // Summary: // Retrieves parent CXTPRibbonBar object //----------------------------------------------------------------------- CXTPRibbonBar* GetRibbonBar() const; //----------------------------------------------------------------------- // Summary: // Cal this method to find tab by its identifier // Parameters: // nId - Identifier of tab to be found // Returns: // Pointer to CXTPRibbonTab object with specified identifier // See Also: GetTab //----------------------------------------------------------------------- CXTPRibbonTab* FindTab(int nId) const; //----------------------------------------------------------------------- // Summary: // Cal this method to get tab in specified position // Parameters: // nIndex - Index of tab to retrieve // Returns: // Pointer to CXTPRibbonTab object in specified position // See Also: FindTab //----------------------------------------------------------------------- CXTPRibbonTab* GetTab(int nIndex) const; //----------------------------------------------------------------------- // Summary: // Call this member to select a tab in the ribbon bar. // Parameters: // pItem - Points to a CXTPTabManagerItem object to be selected. //----------------------------------------------------------------------- void SetSelectedItem(CXTPTabManagerItem* pItem); protected: //----------------------------------------------------------------------- // Summary: // This method is called to update position of TabManager. //----------------------------------------------------------------------- void Reposition(); //------------------------------------------------------------------------- // Summary: // This virtual member is called to determine if control has focus and need // to draw focused rectangle around focused item // Returns: // TRUE if header has has focus //------------------------------------------------------------------------- virtual BOOL HeaderHasFocus() const; //----------------------------------------------------------------------- // Summary: // Call this member to set focus to the control. // Parameters: // bFocused - TRUE to set focus //----------------------------------------------------------------------- virtual void SetFocused(BOOL bFocused); //----------------------------------------------------------------------- // Summary: // Call this member to get the focused state of the control. // Returns: // TRUE if the control has focus; otherwise FALSE. //----------------------------------------------------------------------- virtual BOOL IsFocused() const; //---------------------------------------------------------------------- // Summary: // This method is called when the user activate control using its underline. //---------------------------------------------------------------------- void OnUnderlineActivate(); //---------------------------------------------------------------------- // Summary: // This method is called to check if control accept focus // See Also: SetFocused //---------------------------------------------------------------------- virtual BOOL IsFocusable() const; //---------------------------------------------------------------------- // Summary: // This method is called when the control becomes selected. // Parameters: // bSelected - TRUE if the control becomes selected. // Returns: // TRUE if successful; otherwise returns FALSE //---------------------------------------------------------------------- BOOL OnSetSelected(int bSelected); //---------------------------------------------------------------------- // Summary: // This method is called when a non-system key is pressed. // Parameters: // nChar - Specifies the virtual key code of the given key. // lParam - Specifies additional message-dependent information. // Returns: // TRUE if key handled, otherwise returns FALSE //---------------------------------------------------------------------- BOOL OnHookKeyDown (UINT nChar, LPARAM lParam); //---------------------------------------------------------------------- // Summary: // This method is called when an item(tab button) is clicked. // Parameters: // pItem - Item that was clicked. //---------------------------------------------------------------------- void OnItemClick(CXTPTabManagerItem* pItem); protected: //----------------------------------------------------------------------- // Summary: // This member is called when the icon of the ribbon tab needs to be // drawn. // Parameters: // pDC - Pointer to the destination device context. // pt - Specifies the location of the image. // pItem - CXTPTabManagerItem object to draw icon on. // bDraw - TRUE if the icon needs to be drawn, I.e. the icon size // changed. FALSE if the icon does not need to be // drawn or redrawn. // szIcon - Size of the tab icon. // Remarks: // For example, on mouseover. This member is overridden by its // descendants. This member must be overridden in // derived classes. // Returns: // TRUE if the icon was successfully drawn, FALSE if the icon // was not drawn. //----------------------------------------------------------------------- BOOL DrawIcon(CDC* pDC, CPoint pt, CXTPTabManagerItem* pItem, BOOL bDraw, CSize& szIcon) const; //----------------------------------------------------------------------- // Summary: // Initiates redrawing of the ribbon bar control. // Remarks: // Call this member function if you want to initialize redrawing // of the control. The control will be redrawn taking into account // its latest state. // Parameters: // lpRect - The rectangular area of the window that is invalid. // bAnimate - TRUE to animate changes in bounding rectangle. //----------------------------------------------------------------------- void RedrawControl(LPCRECT lpRect, BOOL bAnimate); //----------------------------------------------------------------------- // Summary: // Checks to see if the mouse is locked. // Remarks: // The mouse is locked when a CXTPCommandBarsPopup is currently visible. // Returns: // TRUE if locked; otherwise returns FALSE. //----------------------------------------------------------------------- BOOL IsMouseLocked() const; //---------------------------------------------------------------------- // Summary: // This method is called to draw the control. // Parameters: // pDC - Pointer to a valid device context. //---------------------------------------------------------------------- void Draw(CDC* pDC); //----------------------------------------------------------------------- // Summary: // Call this member function to Store/Load a properties collection // using the specified data object. // Parameters: // pPX - Source or destination CXTPPropExchange data object reference. // Remarks: // This member function is used to store or load properties collection // data to or form an storage. //----------------------------------------------------------------------- void DoPropExchange(CXTPPropExchange* pPX); //---------------------------------------------------------------------- // Summary: // This method is called to copy the control. // Parameters: // pControl - Points to a source CXTPControl object // bRecursive - TRUE to copy recursively. //---------------------------------------------------------------------- void Copy(CXTPControl* pControl, BOOL bRecursive = FALSE); //----------------------------------------------------------------------- // Summary: // Call this member to get the tracking state. // Returns: // TRUE if the ribbon is in the tracking mode. //----------------------------------------------------------------------- BOOL IsPopupBarTracking() const; protected: //{{AFX_CODEJOCK_PRIVATE void OnClick(BOOL bKeyboard = FALSE, CPoint pt = CPoint(0, 0)); void ShowPopupBar(BOOL bKeyboard); BOOL OnSetPopup(BOOL bPopup); void SetEnabled(BOOL bEnabled); CString GetItemTooltip(const CXTPTabManagerItem* pItem) const; virtual void AdjustExcludeRect(CRect& rc, BOOL bVertical); //}}AFX_CODEJOCK_PRIVATE protected: //{{AFX_CODEJOCK_PRIVATE virtual HRESULT GetAccessibleChildCount(long* pcountChildren); virtual HRESULT GetAccessibleChild(VARIANT varChild, IDispatch** ppdispChild); virtual HRESULT GetAccessibleName(VARIANT varChild, BSTR* pszName); virtual HRESULT GetAccessibleRole(VARIANT varChild, VARIANT* pvarRole); virtual HRESULT AccessibleLocation(long *pxLeft, long *pyTop, long *pcxWidth, long* pcyHeight, VARIANT varChild); virtual HRESULT AccessibleHitTest(long xLeft, long yTop, VARIANT* pvarChild); virtual HRESULT GetAccessibleState(VARIANT varChild, VARIANT* pvarState); virtual HRESULT GetAccessibleDefaultAction(VARIANT varChild, BSTR* pszDefaultAction); virtual HRESULT AccessibleDoDefaultAction(VARIANT varChild); virtual HRESULT AccessibleSelect(long flagsSelect, VARIANT varChild); //}}AFX_CODEJOCK_PRIVATE protected: BOOL m_bFocused; // TRUE if groups focused friend class CXTPRibbonBar; }; AFX_INLINE CXTPRibbonBar* CXTPRibbonControlTab::GetRibbonBar() const { return (CXTPRibbonBar*)m_pParent; } #endif // !defined(__XTPRIBBONCONTROLTAB_H__)
[ "david.dehilster@lexisnexisrisk.com" ]
david.dehilster@lexisnexisrisk.com
dfeb7707f6ec8c9f3eccef081b28c66dd02603e1
e6e6c81568e0f41831a85490895a7cf5c929d50e
/yukicoder/6/60.cpp
8813330a78dc4f28a8604b8d8fb7a6e5b797dfee
[]
no_license
mint6421/kyopro
69295cd06ff907cd6cc43887ce964809aa2534d9
f4ef43669352d84bd32e605a40f75faee5358f96
refs/heads/master
2021-07-02T04:57:13.566704
2020-10-23T06:51:20
2020-10-23T06:51:20
182,088,856
0
0
null
null
null
null
UTF-8
C++
false
false
1,304
cpp
#include<bits/stdc++.h> using namespace std; #define inf INT_MAX #define INF LLONG_MAX #define ll long long #define ull unsigned long long #define M (int)(1e9+7) #define P pair<int,int> #define PLL pair<ll,ll> #define FOR(i,m,n) for(int i=(int)m;i<(int)n;i++) #define RFOR(i,m,n) for(int i=(int)m;i>=(int)n;i--) #define rep(i,n) FOR(i,0,n) #define rrep(i,n) RFOR(i,n,0) #define all(a) a.begin(),a.end() #define IN(a,n) rep(i,n){ cin>>a[i]; } const int vx[4] = {0,1,0,-1}; const int vy[4] = {1,0,-1,0}; #define PI 3.14159265 #define F first #define S second #define PB push_back #define EB emplace_back #define int ll #define vi vector<int> int c[1100][1100]; signed main(){ cin.tie(0); ios::sync_with_stdio(false); int n,k; cin>>n>>k; vi x(n),y(n),hp(n); rep(i,n){ cin>>x[i]>>y[i]>>hp[i]; x[i]+=500; y[i]+=500; } rep(i,k){ int ax,ay,w,h,d; cin>>ax>>ay>>w>>h>>d; ax+=500; ay+=500; c[ay][ax]+=d; c[ay][min(1010LL,ax+w+1)]-=d; c[min(1010LL,ay+h+1)][ax]-=d; c[min(1010LL,ay+h+1)][min(1010LL,ax+w+1)]+=d; } rep(i,1000){ rep(j,1000){ c[i][j+1]+=c[i][j]; } } rep(j,1010){ rep(i,1010){ c[i+1][j]+=c[i][j]; } } int ans=0; rep(i,n){ ans+=max(0LL,hp[i]-c[y[i]][x[i]]); } cout<<ans<<endl; }
[ "distout.215@gmail.com" ]
distout.215@gmail.com
ceab6f16b33633b0a177ea173e1e68a15e230e3a
a54fe0243eece943c2609df64819e736bff85937
/src/auvsi16/misc/non-ros/auvsi_comm_protocol/main.cpp
4416f3626c19f5316cf5d6688d7dad571ef1533c
[]
no_license
krishnayoga/auvsi16
eb9b5827b4254abdd2e1ccfbff2a9333ac7857d4
d4b609eb334190840542a1aa20c9c9e1ee9e1383
refs/heads/master
2022-07-10T23:56:35.465918
2017-04-14T05:47:06
2017-04-14T05:47:06
88,235,120
0
0
null
null
null
null
UTF-8
C++
false
false
629
cpp
#include "include/auvsicommunication.hpp" #define MAX_BUFFER 3000 using namespace std; int main(int argc , char *argv[]) { string hostname = "127.0.0.1"; int port_number = 80; auvsiCommunication auvsi_protocol(hostname, port_number, "courseA", "rooster.php"); auvsi_protocol.setPayloadCommunication(heartbeat, "20111995", "bomb", -123.231234,412.21234); cout << auvsi_protocol.getPayload(); while (1) cout << auvsi_protocol.sendTCP(); return 0; } /* * PHP Test File - json_test.php <?php $request_body = file_get_contents('php://input'); var_dump(json_decode($request_body, true)); ?> */
[ "ida.bagus52@ui.ac.id" ]
ida.bagus52@ui.ac.id
969c0704a28aaf863e2be1c5ff80e418a63656e9
00bb26fc4fc1fe1942e30c1873d7f442e0ea08c8
/VNOI_1/B_THTIME/sol_dijkstra.cpp
d1034533f40131d3074698076bc8b10bd58cc7bc
[]
no_license
dntai/VNOI_contests
1230b4562e3aa32d61a6a4d9b28704792b430dc2
c9d3dae5586a4e0b49a052d92d4b67d629332f1d
refs/heads/master
2020-03-26T19:02:40.088628
2017-05-07T08:32:09
2017-05-07T08:32:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,882
cpp
// Author: happyboy99x #include<iostream> #include<cstring> #include<set> using namespace std; const int N = 1000, delta[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; char s[2][N][N+1]; int d[2][N][N], m, n; struct State { int map, x, y, d; State(const int &map = 0, const int &x = 0, const int &y = 0, const int &d = 0): map(map), x(x), y(y), d(d) {} bool operator < (const State &s) const { return d == s.d ? map == s.map ? x == s.x ? y < s.y : x < s.x : map < s.map : d < s.d; } bool valid() const { return x >= 0 && x < m && y >= 0 && y < n && s[map][x][y] != '#'; } }; char& map(const State &t) { return s[t.map][t.x][t.y]; } int& dist(const State &s) { return d[s.map][s.x][s.y]; } void enter() { cin >> m >> n; for(int map = 0; map < 2; ++map) for(int i = 0; i < m; ++i) cin >> s[map][i]; } void update(set<State> &s, const State &st) { if(st.valid() && dist(st) > st.d) { State temp (st); temp.d = dist(st); set<State>::iterator it = s.find(temp); if(it != s.end()) s.erase(it); s.insert(st); dist(st) = st.d; } } int solve() { // Dijkstra memset(d, 0x3f, sizeof d); set<State> heap; for(int i = 0; i < m; ++i) for(int j = 0; j < n; ++j) if(s[0][i][j] == 'S') { d[0][i][j] = 0; heap.insert(State(0, i, j, 0)); } while(!heap.empty()) { State s (*heap.begin()); heap.erase(heap.begin()); if(map(s) == 'T') return s.d; for(int k = 0; k < 4; ++k) update(heap, State(s.map, s.x + delta[k][0], s.y + delta[k][1], s.d)); update(heap, State(1 - s.map, s.x, s.y, s.d + 1)); } return -1; } int main() { ios::sync_with_stdio(false); enter(); cout << solve() << "\n"; return 0; }
[ "nguyentt@garena.com" ]
nguyentt@garena.com
a0cfbfa600259bf36fff0f59efedc5bbcae74e6c
230fb8845f39bef0f30f5d3541eff5dc0641de14
/Connect3/Export/windows/obj/include/haxe/ui/components/_Stepper/IncBehaviour.h
bb8807885c58b8342a98ef2005671a8408055107
[]
no_license
vhlk/AlgoritmoMinMax
76abd62a6e2859ed229e5831264b6d8af27e318d
40eded4948794ca48d50d16d2133a9ab21207768
refs/heads/main
2023-06-30T15:16:17.492478
2021-08-02T13:29:32
2021-08-02T13:29:32
390,493,745
1
0
null
null
null
null
UTF-8
C++
false
true
2,928
h
// Generated by Haxe 4.2.0 #ifndef INCLUDED_haxe_ui_components__Stepper_IncBehaviour #define INCLUDED_haxe_ui_components__Stepper_IncBehaviour #ifndef HXCPP_H #include <hxcpp.h> #endif #ifndef INCLUDED_haxe_ui_behaviours_Behaviour #include <haxe/ui/behaviours/Behaviour.h> #endif HX_DECLARE_CLASS3(haxe,ui,backend,ComponentBase) HX_DECLARE_CLASS3(haxe,ui,backend,ComponentImpl) HX_DECLARE_CLASS3(haxe,ui,behaviours,Behaviour) HX_DECLARE_CLASS4(haxe,ui,components,_Stepper,IncBehaviour) HX_DECLARE_CLASS3(haxe,ui,core,Component) HX_DECLARE_CLASS3(haxe,ui,core,ComponentBounds) HX_DECLARE_CLASS3(haxe,ui,core,ComponentCommon) HX_DECLARE_CLASS3(haxe,ui,core,ComponentContainer) HX_DECLARE_CLASS3(haxe,ui,core,ComponentEvents) HX_DECLARE_CLASS3(haxe,ui,core,ComponentLayout) HX_DECLARE_CLASS3(haxe,ui,core,ComponentValidation) HX_DECLARE_CLASS3(haxe,ui,core,IClonable) HX_DECLARE_CLASS3(haxe,ui,core,IComponentBase) HX_DECLARE_CLASS3(haxe,ui,util,VariantType) HX_DECLARE_CLASS3(haxe,ui,validation,IValidating) HX_DECLARE_CLASS2(openfl,display,DisplayObject) HX_DECLARE_CLASS2(openfl,display,DisplayObjectContainer) HX_DECLARE_CLASS2(openfl,display,IBitmapDrawable) HX_DECLARE_CLASS2(openfl,display,InteractiveObject) HX_DECLARE_CLASS2(openfl,display,Sprite) HX_DECLARE_CLASS2(openfl,events,EventDispatcher) HX_DECLARE_CLASS2(openfl,events,IEventDispatcher) namespace haxe{ namespace ui{ namespace components{ namespace _Stepper{ class HXCPP_CLASS_ATTRIBUTES IncBehaviour_obj : public ::haxe::ui::behaviours::Behaviour_obj { public: typedef ::haxe::ui::behaviours::Behaviour_obj super; typedef IncBehaviour_obj OBJ_; IncBehaviour_obj(); public: enum { _hx_ClassId = 0x79c185a9 }; void __construct( ::haxe::ui::core::Component component); inline void *operator new(size_t inSize, bool inContainer=true,const char *inName="haxe.ui.components._Stepper.IncBehaviour") { return ::hx::Object::operator new(inSize,inContainer,inName); } inline void *operator new(size_t inSize, int extra) { return ::hx::Object::operator new(inSize+extra,true,"haxe.ui.components._Stepper.IncBehaviour"); } static ::hx::ObjectPtr< IncBehaviour_obj > __new( ::haxe::ui::core::Component component); static ::hx::ObjectPtr< IncBehaviour_obj > __alloc(::hx::Ctx *_hx_ctx, ::haxe::ui::core::Component component); static void * _hx_vtable; static Dynamic __CreateEmpty(); static Dynamic __Create(::hx::DynamicArray inArgs); //~IncBehaviour_obj(); HX_DO_RTTI_ALL; ::hx::Val __Field(const ::String &inString, ::hx::PropertyAccess inCallProp); static void __register(); bool _hx_isInstanceOf(int inClassId); ::String __ToString() const { return HX_("IncBehaviour",9f,85,73,53); } ::haxe::ui::util::VariantType call( ::Dynamic param); }; } // end namespace haxe } // end namespace ui } // end namespace components } // end namespace _Stepper #endif /* INCLUDED_haxe_ui_components__Stepper_IncBehaviour */
[ "vhlk@cin.ufpe.br" ]
vhlk@cin.ufpe.br
fd088cb609508216727bb56bb0a30a0d31e079a7
23a5d39b3c9b171af32970fe0b0ad3e5c9ce9429
/cpp/removeDuplicatesFromSortedArray.cpp
4f2f1ee25db3ac008ea0d6a82791321a81683ba3
[]
no_license
kellytay143/leetcode
2e113b5268289f0be44e819cba3ffb22f8bb7aeb
0e7ebc4762256f38f60baef1a2bf54aa2f6d0430
refs/heads/master
2023-02-24T22:16:32.001010
2021-01-31T02:46:44
2021-01-31T02:46:44
291,169,100
0
0
null
null
null
null
UTF-8
C++
false
false
825
cpp
// Source: https://leetcode.com/problems/remove-duplicates-from-sorted-array/ // Author: Kelly Tay // Date: 12/20/2020 /** Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. **/ class Solution { public: int removeDuplicates(vector<int>& nums) { int length = 0; if(nums.empty()) { return length; } length++; for(int i = 1, j = 0; i < nums.size() && j < nums.size(); i++) { if(nums[i] != nums[j]) { length++; j++; nums[j] = nums[i]; } } return length; } };
[ "kellytay@Kellys-MacBook-Pro.local" ]
kellytay@Kellys-MacBook-Pro.local
4e884b332f457fee8a0b581ecf9d5b85d302f490
fa1445f3f23d2dcee4938ff73a543d9aae235799
/SDK/FN_PowerToastWidget_classes.hpp
78ff85edfd27e7b3419466ba183b3934a0423972
[]
no_license
chuhanpu/FNFUN
ac6d750037514bdfb3b1baa50830c9bce60ed85a
8326ae28b844f4d9ee38f3c64bb056e81106fdd3
refs/heads/master
2021-07-15T07:18:42.180136
2017-10-18T20:24:55
2017-10-18T20:24:55
107,524,245
0
0
null
null
null
null
UTF-8
C++
false
false
12,182
hpp
#pragma once // Fortnite SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // WidgetBlueprintGeneratedClass PowerToastWidget.PowerToastWidget_C // 0x0091 (0x02F1 - 0x0260) class UPowerToastWidget_C : public UFortPlayerTrackerBase { public: struct FPointerToUberGraphFrame UberGraphFrame; // 0x0260(0x0008) (CPF_Transient, CPF_DuplicateTransient) class UWidgetAnimation* LookAtMe; // 0x0268(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_BlueprintReadOnly, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_RepNotify, CPF_Interp, CPF_NonTransactional, CPF_EditorOnly, CPF_NoDestructor, CPF_AutoWeak, CPF_ContainsInstancedReference, CPF_AssetRegistrySearchable, CPF_SimpleDisplay, CPF_AdvancedDisplay, CPF_Protected, CPF_BlueprintCallable, CPF_BlueprintAuthorityOnly, CPF_TextExportTransient, CPF_NonPIEDuplicateTransient, CPF_ExposeOnSpawn, CPF_PersistentInstance, CPF_UObjectWrapper, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic, CPF_NativeAccessSpecifierProtected, CPF_NativeAccessSpecifierPrivate) class UWidgetAnimation* Outro; // 0x0270(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_BlueprintReadOnly, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_RepNotify, CPF_Interp, CPF_NonTransactional, CPF_EditorOnly, CPF_NoDestructor, CPF_AutoWeak, CPF_ContainsInstancedReference, CPF_AssetRegistrySearchable, CPF_SimpleDisplay, CPF_AdvancedDisplay, CPF_Protected, CPF_BlueprintCallable, CPF_BlueprintAuthorityOnly, CPF_TextExportTransient, CPF_NonPIEDuplicateTransient, CPF_ExposeOnSpawn, CPF_PersistentInstance, CPF_UObjectWrapper, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic, CPF_NativeAccessSpecifierProtected, CPF_NativeAccessSpecifierPrivate) class UWidgetAnimation* Intro; // 0x0278(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_BlueprintReadOnly, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_RepNotify, CPF_Interp, CPF_NonTransactional, CPF_EditorOnly, CPF_NoDestructor, CPF_AutoWeak, CPF_ContainsInstancedReference, CPF_AssetRegistrySearchable, CPF_SimpleDisplay, CPF_AdvancedDisplay, CPF_Protected, CPF_BlueprintCallable, CPF_BlueprintAuthorityOnly, CPF_TextExportTransient, CPF_NonPIEDuplicateTransient, CPF_ExposeOnSpawn, CPF_PersistentInstance, CPF_UObjectWrapper, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic, CPF_NativeAccessSpecifierProtected, CPF_NativeAccessSpecifierPrivate) class UCommonTextBlock* BoostedPower; // 0x0280(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_RepNotify, CPF_Interp, CPF_NonTransactional, CPF_EditorOnly, CPF_NoDestructor, CPF_AutoWeak, CPF_ContainsInstancedReference, CPF_AssetRegistrySearchable, CPF_SimpleDisplay, CPF_AdvancedDisplay, CPF_Protected, CPF_BlueprintCallable, CPF_BlueprintAuthorityOnly, CPF_TextExportTransient, CPF_NonPIEDuplicateTransient, CPF_ExposeOnSpawn, CPF_PersistentInstance, CPF_UObjectWrapper, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic, CPF_NativeAccessSpecifierProtected, CPF_NativeAccessSpecifierPrivate) class UCommonTextBlock* Description; // 0x0288(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_RepNotify, CPF_Interp, CPF_NonTransactional, CPF_EditorOnly, CPF_NoDestructor, CPF_AutoWeak, CPF_ContainsInstancedReference, CPF_AssetRegistrySearchable, CPF_SimpleDisplay, CPF_AdvancedDisplay, CPF_Protected, CPF_BlueprintCallable, CPF_BlueprintAuthorityOnly, CPF_TextExportTransient, CPF_NonPIEDuplicateTransient, CPF_ExposeOnSpawn, CPF_PersistentInstance, CPF_UObjectWrapper, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic, CPF_NativeAccessSpecifierProtected, CPF_NativeAccessSpecifierPrivate) class UImage* Image_3; // 0x0290(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_RepNotify, CPF_Interp, CPF_NonTransactional, CPF_EditorOnly, CPF_NoDestructor, CPF_AutoWeak, CPF_ContainsInstancedReference, CPF_AssetRegistrySearchable, CPF_SimpleDisplay, CPF_AdvancedDisplay, CPF_Protected, CPF_BlueprintCallable, CPF_BlueprintAuthorityOnly, CPF_TextExportTransient, CPF_NonPIEDuplicateTransient, CPF_ExposeOnSpawn, CPF_PersistentInstance, CPF_UObjectWrapper, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic, CPF_NativeAccessSpecifierProtected, CPF_NativeAccessSpecifierPrivate) class UImage* Image_Power; // 0x0298(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_RepNotify, CPF_Interp, CPF_NonTransactional, CPF_EditorOnly, CPF_NoDestructor, CPF_AutoWeak, CPF_ContainsInstancedReference, CPF_AssetRegistrySearchable, CPF_SimpleDisplay, CPF_AdvancedDisplay, CPF_Protected, CPF_BlueprintCallable, CPF_BlueprintAuthorityOnly, CPF_TextExportTransient, CPF_NonPIEDuplicateTransient, CPF_ExposeOnSpawn, CPF_PersistentInstance, CPF_UObjectWrapper, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic, CPF_NativeAccessSpecifierProtected, CPF_NativeAccessSpecifierPrivate) class UImage* LineSeparator; // 0x02A0(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_RepNotify, CPF_Interp, CPF_NonTransactional, CPF_EditorOnly, CPF_NoDestructor, CPF_AutoWeak, CPF_ContainsInstancedReference, CPF_AssetRegistrySearchable, CPF_SimpleDisplay, CPF_AdvancedDisplay, CPF_Protected, CPF_BlueprintCallable, CPF_BlueprintAuthorityOnly, CPF_TextExportTransient, CPF_NonPIEDuplicateTransient, CPF_ExposeOnSpawn, CPF_PersistentInstance, CPF_UObjectWrapper, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic, CPF_NativeAccessSpecifierProtected, CPF_NativeAccessSpecifierPrivate) class UPlayerBanner_C* PlayerBanner; // 0x02A8(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_RepNotify, CPF_Interp, CPF_NonTransactional, CPF_EditorOnly, CPF_NoDestructor, CPF_AutoWeak, CPF_ContainsInstancedReference, CPF_AssetRegistrySearchable, CPF_SimpleDisplay, CPF_AdvancedDisplay, CPF_Protected, CPF_BlueprintCallable, CPF_BlueprintAuthorityOnly, CPF_TextExportTransient, CPF_NonPIEDuplicateTransient, CPF_ExposeOnSpawn, CPF_PersistentInstance, CPF_UObjectWrapper, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic, CPF_NativeAccessSpecifierProtected, CPF_NativeAccessSpecifierPrivate) class UImage* PowerIconGlow; // 0x02B0(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_RepNotify, CPF_Interp, CPF_NonTransactional, CPF_EditorOnly, CPF_NoDestructor, CPF_AutoWeak, CPF_ContainsInstancedReference, CPF_AssetRegistrySearchable, CPF_SimpleDisplay, CPF_AdvancedDisplay, CPF_Protected, CPF_BlueprintCallable, CPF_BlueprintAuthorityOnly, CPF_TextExportTransient, CPF_NonPIEDuplicateTransient, CPF_ExposeOnSpawn, CPF_PersistentInstance, CPF_UObjectWrapper, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic, CPF_NativeAccessSpecifierProtected, CPF_NativeAccessSpecifierPrivate) class UCommonTextBlock* TeamMemberPower; // 0x02B8(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_RepNotify, CPF_Interp, CPF_NonTransactional, CPF_EditorOnly, CPF_NoDestructor, CPF_AutoWeak, CPF_ContainsInstancedReference, CPF_AssetRegistrySearchable, CPF_SimpleDisplay, CPF_AdvancedDisplay, CPF_Protected, CPF_BlueprintCallable, CPF_BlueprintAuthorityOnly, CPF_TextExportTransient, CPF_NonPIEDuplicateTransient, CPF_ExposeOnSpawn, CPF_PersistentInstance, CPF_UObjectWrapper, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic, CPF_NativeAccessSpecifierProtected, CPF_NativeAccessSpecifierPrivate) class UCommonTextBlock* Title; // 0x02C0(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_RepNotify, CPF_Interp, CPF_NonTransactional, CPF_EditorOnly, CPF_NoDestructor, CPF_AutoWeak, CPF_ContainsInstancedReference, CPF_AssetRegistrySearchable, CPF_SimpleDisplay, CPF_AdvancedDisplay, CPF_Protected, CPF_BlueprintCallable, CPF_BlueprintAuthorityOnly, CPF_TextExportTransient, CPF_NonPIEDuplicateTransient, CPF_ExposeOnSpawn, CPF_PersistentInstance, CPF_UObjectWrapper, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic, CPF_NativeAccessSpecifierProtected, CPF_NativeAccessSpecifierPrivate) class UFortUINotification* ToastNotification; // 0x02C8(0x0008) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData) float AnimationFinishedDelay; // 0x02D0(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData) unsigned char UnknownData00[0x4]; // 0x02D4(0x0004) MISSED OFFSET struct FScriptMulticastDelegate OnFinishedToast; // 0x02D8(0x0010) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_BlueprintAssignable) struct FTimerHandle AnimationDelayTimer; // 0x02E8(0x0008) (CPF_Edit, CPF_BlueprintVisible, CPF_DisableEditOnInstance) bool Show_Toast; // 0x02F0(0x0001) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData) static UClass* StaticClass() { static UClass* ptr = nullptr; if (!ptr) ptr = UObject::FindClass(0xa61c0095); return ptr; } void StartIntro(); void ShowText(const struct FText& Text, class UCommonTextBlock* TextBlock); void SetToast(class UFortUINotification* Toast); void HandleIntroFinished(); void HandleOutroFinished(); void HandleAnimationDelay(); void OnMouseEnter(struct FGeometry* MyGeometry, struct FPointerEvent* MouseEvent); void OnMouseLeave(struct FPointerEvent* MouseEvent); void BndEvt__OpenButton_K2Node_ComponentBoundEvent_5_CommonButtonClicked__DelegateSignature(class UCommonButton* Button); void OnPlayerInfoChanged(struct FFortTeamMemberInfo* NewInfo); void Construct(); void BndEvt__Intro_K2Node_ComponentBoundEvent_0_OnWidgetAnimationPlaybackStatusChanged__DelegateSignature(); void BndEvt__Outro_K2Node_ComponentBoundEvent_1_OnWidgetAnimationPlaybackStatusChanged__DelegateSignature(); void OnTeamMemberFinishedSynchronizing_Event_1(const struct FUniqueNetIdRepl& NewTeamMemberId); void ExecuteUbergraph_PowerToastWidget(int EntryPoint); void OnFinishedToast__DelegateSignature(); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "tj8@live.com.au" ]
tj8@live.com.au
9574425ae637bb6ebc4a6a2f6f6fd61b536388c9
52e1e9d04f59f391bc6710c0e09ea84ce88f6e0c
/atom.cpp
346bfe07795998c4c2183a03c418ebae85c40a0d
[]
no_license
vavachan/MONTE_CARLO_HARDSPHERE
3909fee4104bf2999f3159f26d88830b11508769
0d7188efcee6e25a7547379f977a8cfc58b6bd55
refs/heads/master
2020-06-12T09:34:18.047969
2017-05-24T04:26:31
2017-05-24T04:26:31
75,591,982
0
1
null
null
null
null
UTF-8
C++
false
false
659
cpp
#include "atom.hpp" #include<iostream> void atom::update_neighbour(int neigh) { neigh_list[index]=neigh; index++; } void atom::close_update_neighbour(int neigh) { close_neigh_list[close_index]=neigh; close_index++; } void atom::close_reset() { // neighbours=0; close_neighbours=0; ////////for(int i=0;i<180;i++) //////// neigh_list[i]=0; for(int i=0;i<50;i++) close_neigh_list[i]=0; // index=0; close_index=0; } void atom::reset() { neighbours=0; // close_neighbours=0; for(int i=0;i<180;i++) neigh_list[i]=0; ////////for(int i=0;i<50;i++) //////// close_neigh_list[i]=0; index=0; // close_index=0; }
[ "varghese.i.am@gmail.com" ]
varghese.i.am@gmail.com
b6c378f30012bc381709b779fe11cf79bf0a6f10
9a1fe44fa09ed0f2205d1bd5c86feddb73c48dc2
/renderarea.cpp
b8fa62f55a0824d81220d94e1c3aeaf952488669
[ "MIT" ]
permissive
vtpp2014/rrt-simulator
ac8efa63cd79d93bbeece2ba101ea7f0b8600118
fc90183802374fb12fe10f974eb757da14e645d3
refs/heads/master
2021-01-19T22:28:55.197026
2017-03-26T07:44:58
2017-03-26T07:44:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,010
cpp
#include "renderarea.h" #include <queue> #include <QTimer> RenderArea::RenderArea(QWidget *parent) : QWidget(parent) { setAttribute(Qt::WA_StaticContents); scribbling = false; rrt = new RRT; } /** * @brief Draw the world. * @param painter */ void RenderArea::drawField(QPainter &painter) { painter.save(); painter.setRenderHint(QPainter::Antialiasing); QRect field; field.setTopLeft(QPoint(this->x(), this->y())); field.setBottomRight(QPoint(this->width()-1, this->height()-1)); painter.setPen(Qt::black); painter.setBrush(QBrush(Qt::green)); painter.drawRect(field); painter.restore(); } /** * @brief Draw the start position of the bot. * @param painter */ void RenderArea::drawStartPos(QPainter &painter) { painter.save(); painter.setRenderHint(QPainter::Antialiasing); painter.setPen(Qt::black); painter.setBrush(QBrush(Qt::red)); painter.drawEllipse(this->x() + START_POS_X - BOT_RADIUS, this->y() + START_POS_Y - BOT_RADIUS, 2 * BOT_RADIUS, 2 * BOT_RADIUS); painter.restore(); } /** * @brief Draw the end point. * @param painter */ void RenderArea::drawEndPos(QPainter &painter) { painter.save(); painter.setRenderHint(QPainter::Antialiasing); painter.setPen(Qt::black); painter.setBrush(QBrush(Qt::blue)); painter.drawEllipse(END_POS_X - BOT_RADIUS, END_POS_Y - BOT_RADIUS, 2 * BOT_RADIUS, 2 * BOT_RADIUS); painter.restore(); } /** * @brief Draw all the rectangular obstacles. * @param painter */ void RenderArea::drawObstacles(QPainter &painter) { painter.save(); painter.setRenderHint(QPainter::Antialiasing); painter.setPen(Qt::black); painter.setBrush(QBrush(Qt::black)); pair<Vector2f, Vector2f> obstacle; for(int i = 0; i < (int)rrt->obstacles->obstacles.size(); i++) { obstacle = rrt->obstacles->obstacles[i]; QPoint topLeft(obstacle.first.x(), obstacle.first.y()); QPoint bottomRight(obstacle.second.x(), obstacle.second.y()); QRect rect(topLeft, bottomRight); painter.drawRect(rect); } painter.restore(); } /** * @brief Draw all the nodes generated in the RRT algorithm. * @param painter */ void RenderArea::drawNodes(QPainter &painter) { painter.save(); painter.setRenderHint(QPainter::Antialiasing); painter.setPen(Qt::black); painter.setBrush(QBrush(Qt::black)); Vector2f pos; for(int i = 0; i < (int)rrt->nodes.size(); i++) { for(int j = 0; j < (int)rrt->nodes[i]->children.size(); j++) { pos = rrt->nodes[i]->children[j]->position; painter.drawEllipse(pos.x()-1.5, pos.y()-1.5, 3, 3); } pos = rrt->nodes[i]->position; painter.drawEllipse(pos.x() - NODE_RADIUS, pos.y() - NODE_RADIUS, 2 * NODE_RADIUS, 2 * NODE_RADIUS); } painter.setPen(Qt::red); painter.setBrush(QBrush(Qt::red)); // if a path exists, draw it. for(int i = 0; i < (int)rrt->path.size() - 1; i++) { QPointF p1(rrt->path[i]->position.x(), rrt->path[i]->position.y()); QPointF p2(rrt->path[i+1]->position.x(), rrt->path[i+1]->position.y()); painter.drawLine(p1, p2); } painter.restore(); } void RenderArea::paintEvent(QPaintEvent *) { QPainter painter(this); drawField(painter); drawStartPos(painter); drawEndPos(painter); drawObstacles(painter); drawNodes(painter); emit painting(); } void RenderArea::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { lastMouseClickedPoint = event->pos(); scribbling = true; } } void RenderArea::mouseMoveEvent(QMouseEvent *event) { } void RenderArea::mouseReleaseEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton && scribbling) { QPoint curPoint = event->pos(); rrt->obstacles->addObstacle(Vector2f(lastMouseClickedPoint.x(), lastMouseClickedPoint.y()), Vector2f(curPoint.x(), curPoint.y())); update(); scribbling = false; } }
[ "ragnarok0211@gmail.com" ]
ragnarok0211@gmail.com
096a5401ee0339c9ab4e56c32affb0edac05fa72
5a4573bf0c3be68901f9d2a2a49e7a23c66a6629
/main.cpp
d5ba1334fb0071fbacfc59ae0adb65bab6fb435e
[]
no_license
braaahaaarararaga/GL_OPENGL_SKINMESH
34f55a98c6daad6c9b4e0f98e70af908c180987a
cad8c91d95318dd038de7a142d32b66056f6724e
refs/heads/master
2020-07-31T07:38:22.354357
2019-09-26T05:57:05
2019-09-26T05:57:05
210,532,697
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
5,104
cpp
#include "main.h" #include "manager.h" #include "renderer.h" #include "polygon.h" #include "camera.h" #include "field.h" #include "cube.h" #include "input.h" #include "light.h" #include "model.h" #include "modelAnimation.h" #include "resource.h" #include <memory> const char* CLASS_NAME = "OpenGALAppClass"; const char* WINDOW_NAME = "OpenGAY"; LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); HWND g_Window; HWND GetWindow() { return g_Window; } int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { WNDCLASSEX wcex = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0, 0, hInstance, NULL, LoadCursor(NULL, IDC_ARROW), (HBRUSH)(COLOR_WINDOW + 1), MAKEINTRESOURCE(IDR_MENU1), CLASS_NAME, NULL }; // ウィンドウクラスの登録 RegisterClassEx(&wcex); // ウィンドウの作成 g_Window = CreateWindowEx(0, CLASS_NAME, WINDOW_NAME, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, (SCREEN_WIDTH + GetSystemMetrics(SM_CXDLGFRAME) * 2), (SCREEN_HEIGHT + GetSystemMetrics(SM_CXDLGFRAME) * 2 + GetSystemMetrics(SM_CYCAPTION) + GetSystemMetrics(SM_CYMENU)), NULL, NULL, hInstance, NULL); // 初期化処理(ウィンドウを作成してから行う) Init(g_Window); // ウインドウの表示(初期化処理の後に行う) ShowWindow(g_Window, nCmdShow); UpdateWindow(g_Window); //フレームカウント初期化 DWORD dwExecLastTime; DWORD dwCurrentTime; timeBeginPeriod(1); dwExecLastTime = timeGetTime(); dwCurrentTime = 0; // メッセージループ MSG msg; while(1) { if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if(msg.message == WM_QUIT) {// PostQuitMessage()が呼ばれたらループ終了 break; } else { // メッセージの翻訳とディスパッチ TranslateMessage(&msg); DispatchMessage(&msg); } } else { dwCurrentTime = timeGetTime(); if((dwCurrentTime - dwExecLastTime) >= (1000 / 60)) { dwExecLastTime = dwCurrentTime; // 更新処理 Update(); // 描画処理 Draw(); } } } timeEndPeriod(1); // 分解能を戻す // ウィンドウクラスの登録を解除 UnregisterClass(CLASS_NAME, wcex.hInstance); // 終了処理 Uninit(); return (int)msg.wParam; } //============================================================================= // ウインドウプロシージャ //============================================================================= LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch(uMsg) { case WM_ACTIVATEAPP: Keyboard::ProcessMessage(uMsg, wParam, lParam); case WM_INPUT: case WM_MOUSEMOVE: case WM_LBUTTONDOWN: case WM_LBUTTONUP: case WM_RBUTTONDOWN: case WM_RBUTTONUP: case WM_MBUTTONDOWN: case WM_MBUTTONUP: case WM_MOUSEWHEEL: case WM_XBUTTONDOWN: case WM_XBUTTONUP: case WM_MOUSEHOVER: Mouse::ProcessMessage(uMsg, wParam, lParam); break; case WM_DESTROY: PostQuitMessage(0); break; case WM_KEYDOWN: switch (wParam) { case VK_ESCAPE: DestroyWindow(hWnd); break; } case WM_SYSKEYDOWN: case WM_KEYUP: case WM_SYSKEYUP: Keyboard::ProcessMessage(uMsg, wParam, lParam); break; case WM_COMMAND: { switch (LOWORD(wParam)) { case ID_BUTT_PUBE: MessageBoxA(g_Window, "DONT TOUCH PUBE!!", "CAPTION", MB_OK); break; case ID_BUTT_CLICK: MessageBoxA(g_Window, "pubeは恥骨の意味だよん〜", "CAPTION", MB_OK); break; case ID_BOX2_X1: { OPENFILENAME of; char fileName[MAX_PATH]; ZeroMemory(fileName, MAX_PATH); memset(&of, 0, sizeof(of)); of.lStructSize = sizeof(of); of.hwndOwner = g_Window; of.lpstrFilter = "FBXファイル(*.fbx)\0*.fbx\0"; of.lpstrTitle = "Open"; of.lpstrFile = fileName; of.nMaxFile = MAX_PATH; of.Flags = OFN_PATHMUSTEXIST; of.lpstrDefExt = "fbx"; if (GetOpenFileName(&of)) { LoadModel(fileName); } break; } default: break; } } default: break; } return DefWindowProc(hWnd, uMsg, wParam, lParam); } // Drag Drop // case : WM_CREATE: // { DragAcceptFiles(window, TRUE); break;} // .. case WM_DROPFILES: // { HDROP drop = (HDROP)wParam; // char fileName[MAX_PATH]; // DragQueryFileA(Drop, 0, fileName, MAX_PATH); ... break ;} std::unique_ptr<ModelAnimation> model; Camera3D* camera; void Init(HWND wnd) { CInput::Init(); InitRenderer(wnd); InitModel(); model = std::make_unique<ModelAnimation>("./asset/Model/mixamo/Walking2.fbx"); InitPolygon(); camera = new Camera3D(); } void Uninit() { UninitModel(); CInput::Uninit(); model.release(); UninitRenderer(); delete camera; } void Update() { UpdateModel(); model->Update(); camera->Update(); CInput::Update(); } void LoadModel(const char* filepath) { model.release(); model = std::make_unique<ModelAnimation>(filepath); } void Draw() { BeginRenderer(); camera->Draw(); SetLight(); //DrawCube(); DrawModel(); model->Draw(); DrawField(); DrawPolygon(); EndRenderer(); }
[ "ri.syouei.as@gmail.com" ]
ri.syouei.as@gmail.com
647a727c1b4e3df56f10a0b0d33642807e67c29c
5205378bf9fd382cbb070d9170610a8d5e4b0f7a
/src/HomeAssistant/Components/Weather.hpp
18ebe03d680fee03fe510e8544f57b6409fc7f4f
[ "MIT" ]
permissive
RobinSinghNanda/Home-assistant-display
65d02124f59bb078945271489152eeeba6aa7e41
6f59104012c0956b54d4b55e190aa89941c2c1af
refs/heads/main
2023-01-20T00:00:43.051506
2020-11-24T10:39:11
2020-11-24T10:39:11
306,589,564
2
0
null
null
null
null
UTF-8
C++
false
false
7,932
hpp
#ifndef __WEATHER_H__ #define __WEATHER_H__ #include "Entity.hpp" #include "RtcTime.hpp" namespace HomeAssistant { class WeatherForecast { public: typedef const char * Condition; WeatherForecast(); //condition static constexpr Condition CONDITION_CLEAR_NIGHT = "clear-night"; static constexpr Condition CONDITION_CLOUDY = "cloudy"; static constexpr Condition CONDITION_EXCEPTIONAL = "exceptional"; static constexpr Condition CONDITION_FOG = "fog"; static constexpr Condition CONDITION_HAIL = "hail"; static constexpr Condition CONDITION_LIGHTNING = "lightning"; static constexpr Condition CONDITION_LIGHTNING_RAINY = "lightning-rainy"; static constexpr Condition CONDITION_PARTLYCLOUDY = "partlycloudy"; static constexpr Condition CONDITION_POURING = "pouring"; static constexpr Condition CONDITION_RAINY = "rainy"; static constexpr Condition CONDITION_SNOWY = "snowy"; static constexpr Condition CONDITION_SNOWY_RAINY = "snowy-rainy"; static constexpr Condition CONDITION_SUNNY = "sunny"; static constexpr Condition CONDITION_WINDY = "windy"; static constexpr Condition CONDITION_WINDY_VARIANT = "windy-variant"; //Attributes static constexpr AttributeName ATTR_FORECAST_CONDITION = "condition"; static constexpr AttributeName ATTR_FORECAST_PRECIPITATION = "precipitation"; static constexpr AttributeName ATTR_FORECAST_PRECIPITATION_PROBABILITY = "precipitation_probability"; static constexpr AttributeName ATTR_FORECAST_TEMP = "temperature"; static constexpr AttributeName ATTR_FORECAST_TEMP_LOW = "templow"; static constexpr AttributeName ATTR_FORECAST_TIME = "datetime"; static constexpr AttributeName ATTR_FORECAST_WIND_BEARING = "wind_bearing"; static constexpr AttributeName ATTR_FORECAST_WIND_SPEED = "wind_speed"; //API inline const char * getCondition(); inline float getPrecipitation(); inline float getPrecipitationProbability(); inline float getTemperature(); inline float getTemplow(); inline uint32_t getDatetime(); inline float getWindBearing(); inline float getWindSpeed(); inline const char * getIcon(); inline bool isCondition(const char * condition); void updateAttributes(JsonObject attributesObject); protected: string icon = ""; string condition = ""; float precipitation = 0.0; float precipitationProbability = 0.0; float temperature = 0.0; float templow = 0.0; uint32_t datetime; float windBearing = 0.0; float windSpeed = 0.0; void setIcon(); }; class Weather : public Entity { public: Weather(const char * entity); virtual ~Weather(); static constexpr const char * ENTITY_DOMAIN = "weather"; //States static constexpr State STATE_CLEAR_NIGHT = "clear-night"; static constexpr State STATE_CLOUDY = "cloudy"; static constexpr State STATE_EXCEPTIONAL = "exceptional"; static constexpr State STATE_FOG = "fog"; static constexpr State STATE_HAIL = "hail"; static constexpr State STATE_LIGHTNING = "lightning"; static constexpr State STATE_LIGHTNING_RAINY = "lightning-rainy"; static constexpr State STATE_PARTLYCLOUDY = "partlycloudy"; static constexpr State STATE_POURING = "pouring"; static constexpr State STATE_RAINY = "rainy"; static constexpr State STATE_SNOWY = "snowy"; static constexpr State STATE_SNOWY_RAINY = "snowy-rainy"; static constexpr State STATE_SUNNY = "sunny"; static constexpr State STATE_WINDY = "windy"; static constexpr State STATE_WINDY_VARIANT = "windy-variant"; static constexpr AttributeName ATTR_FORECAST = "forecast"; static constexpr AttributeName ATTR_WEATHER_ATTRIBUTION = "attribution"; static constexpr AttributeName ATTR_WEATHER_HUMIDITY = "humidity"; static constexpr AttributeName ATTR_WEATHER_OZONE = "ozone"; static constexpr AttributeName ATTR_WEATHER_PRESSURE = "pressure"; static constexpr AttributeName ATTR_WEATHER_TEMPERATURE = "temperature"; static constexpr AttributeName ATTR_WEATHER_VISIBILITY = "visibility"; static constexpr AttributeName ATTR_WEATHER_WIND_BEARING = "wind_bearing"; static constexpr AttributeName ATTR_WEATHER_WIND_SPEED = "wind_speed"; // static Icon ICON_ATTR_HUMIDITY = ICON_WATER_PERCENT; // static Icon ICON_ATTR_WIND_BEARING = ICON_WEATHER_WINDY; // static Icon ICON_ATTR_WIND_SPEED = ICON_WEATHER_WINDY; // static Icon ICON_ATTR_PRESSURE = ICON_GAUGE; // static Icon ICON_ATTR_VISIBILITY = ICON_WEATHER_FOG; // static Icon ICON_ATTR_PRECIPITATION = ICON_WEATHER_RAINY; //API inline float getHumidity(); inline float getOzone(); inline float getPressure(); inline float getTemperature(); inline float getVisibility(); inline float getWindBearing(); inline float getWindSpeed(); inline uint8_t getNumForecasts(); const char * getAttributeIcon(const char * attribute); inline WeatherForecast * getForecast(uint8_t index); virtual void updateAttributes(JsonObject stateAttributesObject); protected: float humidity = 0; float ozone = 0; float pressure = 0; float temperature = 0; float visibility = 0; float windBearing = 0; float windSpeed = 0; uint8_t numForecasts = 0; std::vector<WeatherForecast*> forecasts; virtual void setIcon(); }; float Weather::getHumidity() { return humidity; } float Weather::getOzone() { return ozone; } float Weather::getPressure() { return pressure; } float Weather::getTemperature() { return temperature; } float Weather::getVisibility() { return visibility; } float Weather::getWindBearing() { return windBearing; } float Weather::getWindSpeed() { return windSpeed; } uint8_t Weather::getNumForecasts() { return numForecasts; } WeatherForecast * Weather::getForecast(uint8_t index) { if (index < numForecasts) { return forecasts[index]; } else { return nullptr; } } const char * WeatherForecast::getCondition() { return condition.c_str(); } float WeatherForecast::getPrecipitation() { return precipitation; } float WeatherForecast::getPrecipitationProbability() { return precipitationProbability; } float WeatherForecast::getTemperature() { return temperature; } float WeatherForecast::getTemplow() { return templow; } uint32_t WeatherForecast::getDatetime() { return datetime; } float WeatherForecast::getWindBearing() { return windBearing; } float WeatherForecast::getWindSpeed() { return windSpeed; } const char * WeatherForecast::getIcon() { return this->icon.c_str(); } bool WeatherForecast::isCondition(const char * condition) { return this->condition.compare(condition) == 0; } }; #endif // __WEATHER_H__
[ "nanda.robin.singh@gmail.com" ]
nanda.robin.singh@gmail.com
cf555346b9c3db24c46556d7672f84ecb6619f2c
5162ecef09ce3e8e2b1b83620cd93067ea026555
/applications/constVolumePSR/cv_param_sparse.cpp
aaa8c2a55bb3c6406d0216002a5808ad9f40b51d
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
LLNL/zero-rk
572c527deb53c7064179d40eebad53e48328c708
ffc09d1f8b9978eb22b2daf192648a20bd0fb125
refs/heads/master
2023-08-23T16:09:45.431124
2023-06-30T18:27:43
2023-06-30T18:28:21
194,750,365
29
19
null
null
null
null
UTF-8
C++
false
false
20,040
cpp
#include "cv_param_sparse.h" //n is length of perm_c which is allocated by calling function void read_perm_c_from_file(int n, int* perm_c) { int ncheck = 0; char line[1024]; FILE *infile; infile=fopen("perm_c.txt", "r"); //assumes perm_c has correct number of lines while (fgets(line, 1023, infile) != NULL && ncheck <= n) { perm_c[ncheck++] = atoi(line); } if(ncheck != n) { printf("ERROR: perm_c.txt not consistent with mechanism."); exit(-1); } return; } JsparseTermList * alloc_JsparseTermList(const int inpFD, const int inpFC) { JsparseTermList *w; w=(JsparseTermList *)malloc(sizeof(JsparseTermList)); if(w==NULL) { printf("ERROR: allocation 1 failed in alloc_JsparseTermList(...)\n"); return NULL; } w->nFwdDestroy=inpFD; w->nFwdCreate =inpFC; w->fwdDestroy=(JsparseIdx *)malloc(sizeof(JsparseIdx)*inpFD); if(w->fwdDestroy==NULL) { free(w); printf("ERROR: allocation 2 failed in alloc_JsparseTermList(...)\n"); return NULL; } w->fwdCreate=(JsparseIdx *)malloc(sizeof(JsparseIdx)*inpFC); if(w->fwdCreate==NULL) { free(w->fwdDestroy); free(w); printf("ERROR: allocation 3 failed in alloc_JsparseTermList(...)\n"); return NULL; } return w; } void free_JsparseTermList(JsparseTermList *w) { if(w != NULL) { free(w->fwdCreate); free(w->fwdDestroy); free(w); } } Jsparse * alloc_Jsparse(zerork::mechanism &mechInp, double tol, bool doILU, bool fakeUpdate, int threshType, double DiagPivotThresh, int permutationType) { int nSpc=mechInp.getNumSpecies(); int nStep=mechInp.getNumSteps(); int nReac,nProd; int j,k,m,rowIdx,colIdx,nzAddr; int nFD,nFC; int *isNonZero; // local dense matrix indicating the non-zero terms Jsparse *w; w=(Jsparse *)malloc(sizeof(Jsparse)); if(w==NULL) { printf("ERROR: allocation 1 failed in alloc_Jsparse(...)\n"); fflush(stdout); return NULL; } countJacobianTerms(mechInp,&nFD,&nFC); w->termList=alloc_JsparseTermList(nFD,nFC); if(w->termList==NULL) { free(w); printf("ERROR: allocation 2 failed in alloc_Jsparse(...)\n"); fflush(stdout); return NULL; } w->nSize=nSpc+2; //+1; // matrix size // allocate temporary arrays isNonZero = (int *)malloc(sizeof(int)*(w->nSize)*(w->nSize)); // allocate memory that is related to the matrix dimension w->mtxColSum = (int *)malloc(sizeof(int)*(w->nSize+1)); w->diagIdx = (int *)malloc(sizeof(int)*(w->nSize)); w->lastRowIdx = (int *)malloc(sizeof(int)*(w->nSize)); // initialize the dense nonzero flags for(j=0; j<nSpc; j++) // process the first nSpc columns { for(k=0; k<nSpc; k++) // process the first nSpc rows {isNonZero[j*(w->nSize)+k]=0;} isNonZero[j*(w->nSize)+j]=1; // mark the diagonal isNonZero[j*(w->nSize)+nSpc]=1; // mark the T row isNonZero[j*(w->nSize)+nSpc+1]=1;// mark the mass row? } for(k=0; k<(w->nSize); k++) // mark nSize rows in the temperature column {isNonZero[nSpc*(w->nSize)+k]=1;} for(k=0; k<(w->nSize); k++) // mark nSize rows in the mass column {isNonZero[(nSpc+1)*(w->nSize)+k]=1;} // re-parse the system filling in the Jacobian term data // Jacobian = d ydot(k)/ dy(j) nFD=nFC=0; for(j=0; j<nStep; j++) { nReac=mechInp.getOrderOfStep(j); nProd=mechInp.getNumProductsOfStep(j); for(k=0; k<nReac; k++) { colIdx=mechInp.getSpecIdxOfStepReactant(j,k); // species being perturbed // forward destruction for(m=0; m<nReac; m++) { rowIdx=mechInp.getSpecIdxOfStepReactant(j,m); // species being destroyed isNonZero[colIdx*(w->nSize)+rowIdx]=1; // mark location in dense w->termList->fwdDestroy[nFD].concIdx=colIdx; w->termList->fwdDestroy[nFD].rxnIdx=j; w->termList->fwdDestroy[nFD].sparseIdx=rowIdx; ++nFD; } // forward creation for(m=0; m<nProd; m++) { rowIdx=mechInp.getSpecIdxOfStepProduct(j,m); // species being created isNonZero[colIdx*(w->nSize)+rowIdx]=1; // mark location in dense w->termList->fwdCreate[nFC].concIdx=colIdx; w->termList->fwdCreate[nFC].rxnIdx=j; w->termList->fwdCreate[nFC].sparseIdx=rowIdx; ++nFC; } } } // check the jacobian term count if(nFD != w->termList->nFwdDestroy) { printf("ERROR: in alloc_Jterm_param()\n"); printf(" nFD = %d != %d = w->nFwdDestroy\n",nFD, w->termList->nFwdDestroy); exit(-1); } if(nFC != w->termList->nFwdCreate) { printf("ERROR: in alloc_Jterm_param()\n"); printf(" nFC = %d != %d = w->nFwdCreate\n",nFC, w->termList->nFwdCreate); exit(-1); } w->num_noninteger_jacobian_nonzeros = mechInp.getNonIntegerReactionNetwork()->GetNumJacobianNonzeros(); int* noninteger_row_id; int* noninteger_column_id; // non-integer reaction network if(w->num_noninteger_jacobian_nonzeros > 0) { noninteger_row_id = (int *)malloc(sizeof(int)*(w->num_noninteger_jacobian_nonzeros)); noninteger_column_id = (int *)malloc(sizeof(int)*(w->num_noninteger_jacobian_nonzeros)); w->noninteger_jacobian = (double *)malloc(sizeof(double)*(w->num_noninteger_jacobian_nonzeros)); w->noninteger_sparse_id = (int *)malloc(sizeof(int)*(w->num_noninteger_jacobian_nonzeros)); for(int j=0; j<w->num_noninteger_jacobian_nonzeros; ++j) { noninteger_row_id[j] = 0; noninteger_column_id[j] = 0; w->noninteger_jacobian[j] = 0.0; w->noninteger_sparse_id[j] = 0; } mechInp.getNonIntegerReactionNetwork()->GetJacobianPattern( noninteger_row_id,noninteger_column_id); for(int j=0; j<w->num_noninteger_jacobian_nonzeros; ++j) { int dense_id = noninteger_row_id[j]+noninteger_column_id[j]*w->nSize; isNonZero[dense_id]=1; // mark location in dense } } // end if(w->num_noninteger_jacobian_nonzeros > 0) // count the number of nonzero terms in the dense matrix w->nNonZero=1; // start the count at one so it can still serve as a flag w->mtxColSum[0]=0; for(j=0; j<(w->nSize); j++) // process column j { for(k=0; k<(w->nSize); k++) { if(isNonZero[j*(w->nSize)+k]==1) { isNonZero[j*(w->nSize)+k]=w->nNonZero; w->nNonZero++; } } // after counting column j store the running total in column j+1 // of the column sum w->mtxColSum[j+1]=w->nNonZero-1; } // now at each nonzero term, isNonZero is storing the (address+1) in the // actual compressed column storage data array w->nNonZero--; // decrement the count //printf("# number of nonzero terms = %d\n",w->nNonZero); fflush(stdout); // allocate matrix data w->mtxData=(double *)malloc(sizeof(double)*w->nNonZero); w->mtxRowIdx=(int *)malloc(sizeof(int)*w->nNonZero); for(j=0; j<w->nNonZero; j++) {w->mtxData[j]=0.0;} // initialize to zero for the print function // scan the the isNonZero array to determine the row indexes // and the special data addresses for(j=0; j<(w->nSize); j++) // process column j { for(k=0; k<(w->nSize); k++) // row k { nzAddr=isNonZero[j*(w->nSize)+k]; if(nzAddr>=1) {w->mtxRowIdx[nzAddr-1]=k;} } // record the diagonal address w->diagIdx[j] = isNonZero[j*(w->nSize)+j]-1; //w->lastRowIdx[j] = isNonZero[(j+1)*(w->nSize)-1]-1; w->lastRowIdx[j] = isNonZero[(j+1)*(w->nSize)-2]-1;//actually point to Temp row } // use the isNonZero array as a lookup to store the proper compressed // column data storage for(j=0; j<nFD; j++) { rowIdx=w->termList->fwdDestroy[j].sparseIdx; colIdx=w->termList->fwdDestroy[j].concIdx; nzAddr=isNonZero[colIdx*(w->nSize)+rowIdx]; if(nzAddr==0) { printf("ERROR: %d term in fwdDestroy points to a zero J term\n", j); printf(" at J(%d,%d)\n",rowIdx,colIdx); exit(-1); } w->termList->fwdDestroy[j].sparseIdx=nzAddr-1; // reset to sparse addr } for(j=0; j<nFC; j++) { rowIdx=w->termList->fwdCreate[j].sparseIdx; colIdx=w->termList->fwdCreate[j].concIdx; nzAddr=isNonZero[colIdx*(w->nSize)+rowIdx]; if(nzAddr==0) { printf("ERROR: %d term in fwdCreate points to a zero J term\n", j); printf(" at J(%d,%d)\n",rowIdx,colIdx); exit(-1); } w->termList->fwdCreate[j].sparseIdx=nzAddr-1; // reset to sparse addr } for(int j=0; j<w->num_noninteger_jacobian_nonzeros; ++j) { int dense_id = noninteger_row_id[j]+noninteger_column_id[j]*w->nSize; nzAddr=isNonZero[dense_id]; w->noninteger_sparse_id[j] = nzAddr-1; } if(w->num_noninteger_jacobian_nonzeros>0) { free(noninteger_row_id); free(noninteger_column_id); } // Now the JsparseTermList should contain a consistent set of indexes // for processing the Jacobian term by term. Note that each element // in the list is independent, so the lists of JsparseIdx can be sorted // to try to improve cache locality // sparse solver specific allocations // SuperLU w->isFirstFactor=1; // indicate to do the full factorization /* Set the default input options: options.Fact = DOFACT; options.Equil = YES; options.ColPerm = COLAMD; options.Trans = NOTRANS; options.IterRefine = NOREFINE; options.DiagPivotThresh = 1.0; options.SymmetricMode = NO; options.PivotGrowth = NO; options.ConditionNumber = NO; options.PrintStat = YES; */ set_default_options(&(w->optionSLU)); /* Set the default options for ILU options.Fact = DOFACT; options.Equil = YES; options.ColPerm = COLAMD; options.Trans = NOTRANS; options.IterRefine = NOREFINE; options.DiagPivotThresh = 0.1; //different from complete LU options.SymmetricMode = NO; options.PivotGrowth = NO; options.ConditionNumber = NO; options.PrintStat = YES; options.RowPerm = LargeDiag_MC64; options.ILU_DropTol = 1e-4; options.ILU_FillTol = 1e-2; options.ILU_FillFactor = 10.0; options.ILU_DropRule = DROP_BASIC | DROP_AREA; options.ILU_Norm = INF_NORM; options.ILU_MILU = SILU; */ ilu_set_default_options(&(w->optionSLU)); w->optionSLU.ILU_DropTol = 5e-4; w->optionSLU.ILU_FillTol = 1e-4; w->optionSLU.ILU_FillFactor = 2.0; w->optionSLU.DiagPivotThresh = DiagPivotThresh; w->optionSLU.ILU_DropRule = DROP_BASIC | DROP_AREA; w->optionSLU.ILU_MILU = SILU; //SMILU_{1,2,3}; // w->optionSLU.ColPerm = MMD_AT_PLUS_A; // best for iso-octane // w->optionSLU.ColPerm = COLAMD; // w->optionSLU.ColPerm = MMD_ATA; w->optionSLU.ColPerm = MY_PERMC; w->optionSLU.RowPerm = LargeDiag_MC64; w->optionSLU.Equil=YES; // w->optionSLU.SymmetricMode = YES; //Small DiagPivotThresh and MMD_AT_PLUS_A w->vecRHS=(double *)malloc(sizeof(double)*(w->nSize)); w->vecSoln=(double *)malloc(sizeof(double)*(w->nSize)); w->rowPermutation=(int *)malloc(sizeof(int)*(w->nSize)); w->colPermutation=(int *)malloc(sizeof(int)*(w->nSize)); w->colElimTree=(int *)malloc(sizeof(int)*(w->nSize)); w->reduceData=(double *)malloc(sizeof(double)*w->nNonZero); w->reduceRowIdx=(int *)malloc(sizeof(int)*w->nNonZero); w->reduceColSum=(int *)malloc(sizeof(int)*(w->nSize+1)); // create a compressed column matrix // SLU_NC == // SLU_D == data type double precision // SLU_GE == matrix structure general //dCreate_CompCol_Matrix(&(w->Mslu),w->nSize,w->nSize,w->nNonZero, // w->mtxData,w->mtxRowIdx,w->mtxColSum, // SLU_NC,SLU_D,SLU_GE); dCreate_CompCol_Matrix(&(w->Mslu), w->nSize, w->nSize, w->nNonZero, w->reduceData, w->reduceRowIdx, w->reduceColSum, SLU_NC,SLU_D,SLU_GE); w->Rvec=(double *)malloc(sizeof(double)*(w->nSize)); w->Cvec=(double *)malloc(sizeof(double)*(w->nSize)); dCreate_Dense_Matrix(&(w->Bslu),w->nSize,1,w->vecRHS,w->nSize, SLU_DN,SLU_D,SLU_GE); dCreate_Dense_Matrix(&(w->Xslu),w->nSize,1,w->vecSoln,w->nSize, SLU_DN,SLU_D,SLU_GE); StatInit(&(w->statSLU)); // initialize SuperLU statistics w->offDiagThreshold=tol; w->ILU = doILU; w->fakeUpdate = fakeUpdate; w->threshType = threshType; //Metis column permutation w->permutationType = permutationType; #ifdef CVIDT_USE_METIS METIS_SetDefaultOptions(w->metis_options); //Set to -1 for default w->metis_options[METIS_OPTION_NUMBERING] = 0; // C-numbering w->metis_options[METIS_OPTION_PFACTOR] = 0; // Default: 0 ["Good values often in the range of 60 to 200"] w->metis_options[METIS_OPTION_CCORDER] = 1; // Default: 0 w->metis_options[METIS_OPTION_COMPRESS] = 1; // Default: 1 w->metis_options[METIS_OPTION_NITER] = 10; // Default: 10 w->metis_options[METIS_OPTION_NSEPS] = 1; // Default: 1 w->metis_options[METIS_OPTION_RTYPE] = METIS_RTYPE_SEP1SIDED; // Default: ?? //METIS_RTYPE_FM FM-based cut refinnement. (SegFault) //METIS_RTYPE_GREEDY Greedy-based cut and volume refinement. (SegFault) //METIS_RTYPE_SEP2SIDED Two-sided node FM refinement. //METIS_RTYPE_SEP1SIDED One-sided node FM refinement. w->metis_options[METIS_OPTION_CTYPE] = METIS_CTYPE_RM; // Default: SHEM //METIS_CTYPE_RM Random matching. //METIS_CTYPE_SHEM Sorted heavy-edge matching. w->metis_options[METIS_OPTION_UFACTOR] = 1; // Default: 1 or 30 (ptype=rb or ptype=kway) w->metis_options[METIS_OPTION_SEED] = 0; // Default: ?? #endif if(w->permutationType < 1 || w->permutationType > 3) { printf("ERROR: Invalid permutationType: %d.",w->permutationType); exit(-1); } if(w->permutationType == 3) { read_perm_c_from_file(w->nSize,w->colPermutation); } free(isNonZero); return w; } void free_Jsparse(Jsparse *w) { if(w!=NULL) { StatFree(&(w->statSLU)); Destroy_SuperMatrix_Store(&(w->Bslu)); Destroy_SuperMatrix_Store(&(w->Xslu)); if(!w->isFirstFactor) { Destroy_SuperNode_Matrix(&(w->Lslu)); Destroy_CompCol_Matrix(&(w->Uslu)); } free(w->mtxData); free(w->mtxRowIdx); free(w->mtxColSum); free(w->diagIdx); free(w->lastRowIdx); free(w->reduceData); free(w->reduceRowIdx); free(w->reduceColSum); Destroy_SuperMatrix_Store(&(w->Mslu)); // SuperLU data free(w->vecSoln); free(w->vecRHS); free(w->Rvec); free(w->Cvec); free(w->rowPermutation); free(w->colPermutation); free(w->colElimTree); free_JsparseTermList(w->termList); if(w->num_noninteger_jacobian_nonzeros>0) { free(w->noninteger_sparse_id); free(w->noninteger_jacobian); } free(w); } } // void print_Jsparse(Jsparse *w) // { // int j,k,nElems; // int rowIdx; // double val; // printf("# Number of nonzero elements: %d\n",w->nNonZero); // for(j=0; j<w->nSize; j++) // { // nElems=w->mtxColSum[j+1]-w->mtxColSum[j]; // printf(" Col %d has %d nonzero elements\n",j,nElems); // for(k=0; k<nElems; k++) // { // val=w->mtxData[w->mtxColSum[j]+k]; // rowIdx=w->mtxRowIdx[w->mtxColSum[j]+k]; // printf(" J(%d,%d) = %14.6e\n",rowIdx,j,val); // } // printf("\n"); // //exit(-1); // } // printf("# Number of forward destruction terms: %d\n", // w->termList->nFwdDestroy); // printf("# Number of forward creation terms: %d\n", // w->termList->nFwdCreate); // printf("# Number of reverse destruction terms: %d\n", // w->termList->nRevDestroy); // printf("# Number of reverse creation terms: %d\n", // w->termList->nRevCreate); // printf("# Forward Destruction Terms:\n"); // printf("# i.e. both species are reactants in the same reaction\n"); // printf("#\n# numer denom\n"); // printf("# J term rxn ID spc ID spc ID sparse mtx ID\n"); // for(j=0; j<(w->termList->nFwdDestroy); j++) // { // printf("%6d %6d %6d %6d %6d\n",j, // w->termList->fwdDestroy[j].rxnIdx, // w->mtxRowIdx[w->termList->fwdDestroy[j].sparseIdx], // w->termList->fwdDestroy[j].concIdx, // w->termList->fwdDestroy[j].sparseIdx); // } // printf("\n\n"); // printf("# Forward Creation Terms:\n"); // printf("# i.e. numerator species is a product and the denominator\n"); // printf("# is a reactant in the same reaction\n"); // printf("#\n# numer denom\n"); // printf("# J term rxn ID spc ID spc ID\n"); // for(j=0; j<(w->termList->nFwdCreate); j++) // { // printf("%6d %6d %6d %6d %6d\n",j, // w->termList->fwdCreate[j].rxnIdx, // w->mtxRowIdx[w->termList->fwdCreate[j].sparseIdx], // w->termList->fwdCreate[j].concIdx, // w->termList->fwdCreate[j].sparseIdx); // } // printf("\n\n"); // printf("# Reverse Destruction Terms:\n"); // printf("# i.e. both species are products in the same reversible reaction\n"); // printf("#\n# numer denom\n"); // printf("# J term rxn ID spc ID spc ID sparse mtx ID\n"); // for(j=0; j<(w->termList->nRevDestroy); j++) // { // printf("%6d %6d %6d %6d %6d\n",j, // w->termList->revDestroy[j].rxnIdx, // w->mtxRowIdx[w->termList->revDestroy[j].sparseIdx], // w->termList->revDestroy[j].concIdx, // w->termList->revDestroy[j].sparseIdx); // } // printf("\n\n"); // printf("# Reverse Creation Terms:\n"); // printf("# i.e. numerator species is a reactant and the denominator\n"); // printf("# is a product in the same reversible reaction\n"); // printf("#\n# numer denom\n"); // printf("# J term rxn ID spc ID spc ID\n"); // for(j=0; j<(w->termList->nRevCreate); j++) // { // printf("%6d %6d %6d %6d %6d\n",j, // w->termList->revCreate[j].rxnIdx, // w->mtxRowIdx[w->termList->revCreate[j].sparseIdx], // w->termList->revCreate[j].concIdx, // w->termList->revCreate[j].sparseIdx); // } // } void countJacobianTerms(zerork::mechanism &mechInp, int *nFwdDestroy, int *nFwdCreate) { int j; int nStep=mechInp.getNumSteps(); double nuSumReac,nuSumProd; (*nFwdDestroy)=0; (*nFwdCreate)=0; for(j=0; j<nStep; j++) { nuSumReac=mechInp.getOrderOfStep(j); nuSumProd=mechInp.getNumProductsOfStep(j); (*nFwdDestroy)+=nuSumReac*nuSumReac; (*nFwdCreate)+=nuSumReac*nuSumProd; } } double getElement_Jsparse(Jsparse *w,const int rowIdx, const int colIdx) { int nElem=w->mtxColSum[colIdx+1]-w->mtxColSum[colIdx]; int j; int currentRow; for(j=0; j<nElem; j++) { currentRow=w->mtxRowIdx[w->mtxColSum[colIdx]+j]; if(rowIdx == currentRow) {return w->mtxData[w->mtxColSum[colIdx]+j];} else if(rowIdx < currentRow) {return 0.0;} } return 0.0; } void calcReaction_Jsparse(Jsparse *w, const double invPosConc[], const double fwdROP[]) { int j; int rxnId,concId,sparseId; // set the full sparse array for(j=0; j<w->nNonZero; j++) {w->mtxData[j]=0.0;} // process the forward destruction terms for(j=0; j<w->termList->nFwdDestroy; j++) { concId = w->termList->fwdDestroy[j].concIdx; rxnId = w->termList->fwdDestroy[j].rxnIdx; sparseId = w->termList->fwdDestroy[j].sparseIdx; //printf(" j = %d, concId = %d, rxnId = %d, sparseId = %d\n",j,concId,rxnId,sparseId); fflush(stdout); w->mtxData[sparseId]-=fwdROP[rxnId]*invPosConc[concId]; } // process the forward creation terms for(j=0; j<w->termList->nFwdCreate; j++) { concId = w->termList->fwdCreate[j].concIdx; rxnId = w->termList->fwdCreate[j].rxnIdx; sparseId = w->termList->fwdCreate[j].sparseIdx; w->mtxData[sparseId]+=fwdROP[rxnId]*invPosConc[concId]; } } void change_JsparseThresh(Jsparse *w, double newThresh) {w->offDiagThreshold=newThresh;}
[ "whitesides1@llnl.gov" ]
whitesides1@llnl.gov
305a655ef6f20996d484cf85f7d4c8a545a8f4bc
d01b79d885b2a5fd69b9514d35b0340bce5dd103
/poj/poj1008.cpp
7f1df1abc95b7e69d8fdeb30819fb67eda16c293
[]
no_license
lotay/online_judgement
0dd38afef7cb3450bd9927e8d7c20af5a72d8688
2c17e5745e3b4c339cc3f35741b691a11e571ede
refs/heads/master
2021-01-01T03:54:53.934783
2016-06-09T07:06:10
2016-06-09T07:06:10
58,803,721
0
0
null
null
null
null
UTF-8
C++
false
false
903
cpp
#include <stdio.h> #include <string.h> char HaabMonths[][10] = {"pop","no","zip","zotz","tzec","xul","yoxkin", "mol","chen","yax","zac","ceh","mac","kankin","muan","pax","koyab","cumhu","uayet"}; char TzolkinDate[][10] = {"imix","ik","akbal","kan","chicchan","cimi", "manik","lamat","muluk","ok","chuen","eb","ben","ix","mem","cib","caban","eznab","canac","ahau"}; int transfer1(int d, char *m, int y){ int mi = 0; for(;mi<19;mi++){ if(strcmp(HaabMonths[mi],m)==0){ break; } } return d+mi*20+y*365; } void transfer2(int date){ int y = date / 260; int l = date % 260; printf("%d %s %d\n",(l%13)+1,TzolkinDate[l%20],y); } int main(int argv,char **argc){ int d,y; char months[10]; int t =0; scanf("%d",&t); printf("%d\n",t); while(t-->0){ scanf("%d. %s %d",&d,months,&y); int date = transfer1(d,months,y); transfer2(date); // printf("%d %s %d\n",d,months,y); } return 0; }
[ "158481612@qq.com" ]
158481612@qq.com
82adaab37cdb95119a07a4c194628cf1ea18ff61
86a47af04be052b5b8c6d6f6c8c72d7290b8d6f3
/include/stats1d.h
d336aa692aa804d74fe0cf04fb0f40117e3cd8d0
[]
no_license
PeteBlackerThe3rd/gncTK
182c0eaa792a89a90a77d9aada3576caadb01117
a368e04718195e675d4bf5bc456c517ed49ec10f
refs/heads/master
2020-11-26T12:57:55.652878
2019-12-19T15:02:10
2019-12-19T15:02:10
229,077,713
2
0
null
null
null
null
UTF-8
C++
false
false
1,980
h
#ifndef GNCTK_STATS1D_H_ #define GNCTK_STATS1D_H_ /*-----------------------------------------------------------\\ || || || LIDAR fusion GNC project || || ---------------------------- || || || || Surrey Space Centre - STAR lab || || (c) Surrey University 2017 || || Pete dot Blacker at Gmail dot com || || || \\-----------------------------------------------------------// stats1d.h one dimensional statistical summary storage object --------------------------------------------------- This object stores the statistical summary of a set of one dimensional continuous values. Including the Naive mean, min, max, standard deviation, min_inlier, max_inlier and a histogram of densities. -------------------------------------------------------------*/ #include <string> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <cv_bridge/cv_bridge.h> namespace gncTK { class Stats1D; }; class gncTK::Stats1D { public: Stats1D(std::vector<double> values, int histogramBinCount = 20, float inlierThreshold = 3); // return a string list with basic stat header for CSV writing static std::vector<std::string> csvGetBasicHeaders(); // return a string list with basic stats for CSV writing std::vector<std::string> csvGetBasic(); // return a string list with all stats for CSV writing std::vector<std::string> csvGetAll(); // return a cv::Mat with the statistics and histogram displayed cv::Mat getStatsImage(); double mean; double min,max; double meanInlier, minInlier, maxInlier; double stdDev; unsigned int n; std::vector<double> histogramBins; std::vector<int> histogramTotals; }; #endif /* GNCTK_STATS_1D_H_ */
[ "P.Blacker@surrey.ac.uk" ]
P.Blacker@surrey.ac.uk
efe0d3c3d7f9250a3509d4dee4e1151fbf588100
e8c0bbb5be26f82f8956728d356d0d9b70e1a3b0
/RTreeGUI/RTreeScene.h
b372235c9a6522768c3b0bfd43fdae850dbc39db
[]
no_license
MarkVTech/BoostGeometryExperiment
82ab2290915f059822d6a05bc6b57b28262bf588
40d925e21e03e20954b8756fd976abda09cd4729
refs/heads/master
2023-04-07T04:26:31.567428
2023-03-23T19:25:25
2023-03-23T19:25:25
285,857,554
0
0
null
null
null
null
UTF-8
C++
false
false
856
h
#pragma once #include <QGraphicsScene> class QGraphicsRectItem; class RTreeScene : public QGraphicsScene { Q_OBJECT public: RTreeScene(QObject* parent=nullptr); void setMode(const QString& mode); // QGraphicsScene interface protected: void mousePressEvent(QGraphicsSceneMouseEvent *event) override; void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override; void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override; signals: void selectionAreaChanged(const QRectF& selectionRect); void mouseMove(double x, double y); private: QGraphicsRectItem *mSelectionRectItem = nullptr; QPointF mFirstPoint; QPointF mSecondPoint; QRectF mSelectionRect; QString mMode = "box"; };
[ "mwilson1962@gmail.com" ]
mwilson1962@gmail.com
7f24149ad883041c3da06c2f0f1681d040e70801
d04aaa5014ac6d8e53452b3169060fc4ef8e00f5
/cppDSmalik/ch4ex/absoluteValueEx.cpp
fbd986cbb43d4fb0eb629f4bbef8d6a6af1d697b
[]
no_license
StaringPanda/CPP-Practice
08082fb17343caffca2c16c7f9f2e7a46f9e471e
2dd7b169cd2930ab402a4843d98ea58f49ad1476
refs/heads/master
2020-07-01T04:55:59.699860
2019-08-16T15:19:26
2019-08-16T15:19:26
201,054,206
2
0
null
null
null
null
UTF-8
C++
false
false
1,615
cpp
/***************************************************************** // Example from Pg 210 shows how checking the comparison of // floating point numbers for equality may not behave as you // would expect. // // x = 1.0 and y = 0.999999~ so the if (x == y) is false, however // if you evaluate the equation in y wiht pen and paper you will // get 1.0 as a result. // // One way to check whether two floating point numbers are // equal is to check whether the absolute value of their // difference is less than a certain tolerance. // // The function fabs(), finds the absolute value of a floating // point integer. // // Not a good example of the fabs() function, gives correct // answer regardless of presence or absence of fabs() or // reversing the positions of x and y. *****************************************************************/ #include <iostream> #include <iomanip> #include <cmath> using namespace std; int main(){ double x = 1.0; double y = 3.0 / 7.0 + 2.0 / 7.0 + 2.0 / 7.0; cout << fixed << showpoint << setprecision(17); cout << "3.0 / 7.0 + 2.0 / 7.0 + 2.0 / 7.0 = " << 3.0 / 7.0 + 2.0 / 7.0 + 2.0 / 7.0 << endl; cout << "x = " << x << endl; cout << "y = " << y << endl; if (x == y){ cout << "x and y are the same." << endl; }else{ cout << "x and y are not the same." << endl; } if (fabs(y - x) < 0.000001){ cout << "x and y are the same within the tolerance 0.000001." << endl; }else{ cout << "x and y are not the same within the tolerance 0.000001." << endl; } return 0; }
[ "d00210089@student.dkit.ie" ]
d00210089@student.dkit.ie
eb1829662bd7248015e5b6b7ee9a9dd25951bcc0
fc0495b4d677a6e46be7bebebeaf8d9f77e211e3
/base/dsalgo_test/sort_test.cc
58ad978a5baab6fe0b645b7d46915be4dbdadac5
[]
no_license
caszhang/BackendDevelopmentEnvironment
6bb558352a11932ad0c547ed835d8ead62bef231
e6214e28022eaef08137edd20dcc7a7fe1b0a8d7
refs/heads/master
2021-09-20T21:32:39.017300
2018-08-15T14:58:39
2018-08-15T14:58:39
15,894,112
1
0
null
null
null
null
UTF-8
C++
false
false
3,343
cc
// Author: zhangguoqiang01 <80176975@qq.com> #include <stdlib.h> #include <time.h> #include "gtest/gtest.h" #include "dsalgo/sort.h" int32_t IntegerCompare(const void *param_one, const void *param_two) { int32_t *one = (int32_t*)param_one; int32_t *two = (int32_t*)param_two; if (*one > *two) { return 1; } else if (*one < *two) { return -1; } else { return 0; } } class SortTest:public testing::Test { protected: virtual void SetUp() { } virtual void TearDown() { } public: }; TEST_F(SortTest, FirstTest) { int32_t array[] = {2, 3, 4, 1, -5, 0, 7}; printf("before:\n"); for (uint32_t i = 0; i < sizeof(array) / sizeof(int32_t); i++) { printf("%d\n", array[i]); } //internal_sort::QSort((void*)array, sizeof(array) / sizeof(int32_t), sizeof(int32_t), IntegerCompare); //internal_sort::HeapSort((void*)array, sizeof(array) / sizeof(int32_t), sizeof(int32_t), IntegerCompare); //internal_sort::MergeSort((void*)array, sizeof(array) / sizeof(int32_t), sizeof(int32_t), IntegerCompare); internal_sort::EQSort((void*)array, sizeof(array) / sizeof(int32_t), sizeof(int32_t), IntegerCompare); printf("after:\n"); for (uint32_t i = 0; i < sizeof(array) / sizeof(int32_t); i++) { printf("%d\n", array[i]); } } TEST_F(SortTest, RandomTest) { int32_t array_size = 10; srand((unsigned)time(NULL)); int32_t *array = new int32_t[array_size]; printf("before:\n"); for (int32_t i = 0; i < array_size; ++i) { array[i] = rand() % 100; printf("%d\n", array[i]); } //internal_sort::QSort((void*)array, sizeof(array) / sizeof(int32_t), sizeof(int32_t), IntegerCompare); //internal_sort::HeapSort((void*)array, array_size, sizeof(int32_t), IntegerCompare); //internal_sort::MergeSort((void*)array, array_size, sizeof(int32_t), IntegerCompare); internal_sort::EQSort((void*)array, array_size, sizeof(int32_t), IntegerCompare); printf("after:\n"); for (uint32_t i = 0; i < array_size; i++) { printf("%d\n", array[i]); } delete[] array; } struct Node { int32_t value; std::string content; Node() { value = 0; content = ""; } }; int32_t StructCompare(const void *param_one, const void *param_two) { Node *one = (Node*)param_one; Node *two = (Node*)param_two; if (one->value > two->value) { return -1; } else if (one->value < two->value) { return 1; } else { return 0; } } TEST_F(SortTest, StructTest) { Node *array = new Node[8]; char buf[8]; printf("before:\n"); for (int i = 0; i < 8; i++) { array[i].value = (i * 3 + 4) % 8; snprintf(buf, 8, "%d", i); array[i].content = buf; printf("idx:%s, value:%d\n", array[i].content.c_str(), array[i].value); } //internal_sort::QSort((void*)array, 8, sizeof(Node), StructCompare); //internal_sort::HeapSort((void*)array, 8, sizeof(Node), StructCompare); //internal_sort::MergeSort((void*)array, 8, sizeof(Node), StructCompare); internal_sort::EQSort((void*)array, 8, sizeof(Node), StructCompare); printf("after:\n"); for (int i = 0; i < 8; i++) { printf("idx:%s, value:%d\n", array[i].content.c_str(), array[i].value); } delete[] array; }
[ "80176975@qq.com" ]
80176975@qq.com
9f2b3ff1443d3c979ee82318509b2fc89318bbcd
0ecf2d067e8fe6cdec12b79bfd68fe79ec222ffd
/media/cast/test/cast_benchmarks.cc
34309d2b353f639852841a771d56b02dff40d6bc
[ "BSD-3-Clause" ]
permissive
yachtcaptain23/browser-android-tabs
e5144cee9141890590d6d6faeb1bdc5d58a6cbf1
a016aade8f8333c822d00d62738a922671a52b85
refs/heads/master
2021-04-28T17:07:06.955483
2018-09-26T06:22:11
2018-09-26T06:22:11
122,005,560
0
0
NOASSERTION
2019-05-17T19:37:59
2018-02-19T01:00:10
null
UTF-8
C++
false
false
25,223
cc
// Copyright 2014 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. // // This program benchmarks the theoretical throughput of the cast library. // It runs using a fake clock, simulated network and fake codecs. This allows // tests to run much faster than real time. // To run the program, run: // $ ./out/Release/cast_benchmarks | tee benchmarkoutput.asc // This may take a while, when it is done, you can view the data with // meshlab by running: // $ meshlab benchmarkoutput.asc // After starting meshlab, turn on Render->Show Axis. The red axis will // represent bandwidth (in megabits) the blue axis will be packet drop // (in percent) and the green axis will be latency (in milliseconds). // // This program can also be used for profiling. On linux it has // built-in support for this. Simply set the environment variable // PROFILE_FILE before running it, like so: // $ export PROFILE_FILE=cast_benchmark.profile // Then after running the program, you can view the profile with: // $ pprof ./out/Release/cast_benchmarks $PROFILE_FILE --gv #include <math.h> #include <stddef.h> #include <stdint.h> #include <map> #include <memory> #include <utility> #include <vector> #include "base/at_exit.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" #include "base/debug/profiler.h" #include "base/memory/ptr_util.h" #include "base/memory/weak_ptr.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/test/simple_test_tick_clock.h" #include "base/threading/thread.h" #include "base/time/tick_clock.h" #include "media/base/audio_bus.h" #include "media/base/fake_single_thread_task_runner.h" #include "media/base/video_frame.h" #include "media/cast/cast_config.h" #include "media/cast/cast_environment.h" #include "media/cast/cast_receiver.h" #include "media/cast/cast_sender.h" #include "media/cast/logging/simple_event_subscriber.h" #include "media/cast/net/cast_transport.h" #include "media/cast/net/cast_transport_config.h" #include "media/cast/net/cast_transport_defines.h" #include "media/cast/net/cast_transport_impl.h" #include "media/cast/test/loopback_transport.h" #include "media/cast/test/skewed_single_thread_task_runner.h" #include "media/cast/test/skewed_tick_clock.h" #include "media/cast/test/utility/audio_utility.h" #include "media/cast/test/utility/default_config.h" #include "media/cast/test/utility/test_util.h" #include "media/cast/test/utility/udp_proxy.h" #include "media/cast/test/utility/video_utility.h" #include "testing/gtest/include/gtest/gtest.h" namespace media { namespace cast { namespace { static const int64_t kStartMillisecond = INT64_C(1245); static const int kTargetPlayoutDelayMs = 400; void ExpectVideoSuccess(OperationalStatus status) { EXPECT_EQ(STATUS_INITIALIZED, status); } void ExpectAudioSuccess(OperationalStatus status) { EXPECT_EQ(STATUS_INITIALIZED, status); } } // namespace // Wraps a CastTransport and records some statistics about // the data that goes through it. class CastTransportWrapper : public CastTransport { public: // Takes ownership of |transport|. void Init(CastTransport* transport, uint64_t* encoded_video_bytes, uint64_t* encoded_audio_bytes) { transport_.reset(transport); encoded_video_bytes_ = encoded_video_bytes; encoded_audio_bytes_ = encoded_audio_bytes; } void InitializeStream(const CastTransportRtpConfig& config, std::unique_ptr<RtcpObserver> rtcp_observer) final { if (config.rtp_payload_type <= RtpPayloadType::AUDIO_LAST) audio_ssrc_ = config.ssrc; else video_ssrc_ = config.ssrc; transport_->InitializeStream(config, std::move(rtcp_observer)); } void InsertFrame(uint32_t ssrc, const EncodedFrame& frame) final { if (ssrc == audio_ssrc_) { *encoded_audio_bytes_ += frame.data.size(); } else if (ssrc == video_ssrc_) { *encoded_video_bytes_ += frame.data.size(); } transport_->InsertFrame(ssrc, frame); } void SendSenderReport(uint32_t ssrc, base::TimeTicks current_time, RtpTimeTicks current_time_as_rtp_timestamp) final { transport_->SendSenderReport(ssrc, current_time, current_time_as_rtp_timestamp); } void CancelSendingFrames(uint32_t ssrc, const std::vector<FrameId>& frame_ids) final { transport_->CancelSendingFrames(ssrc, frame_ids); } void ResendFrameForKickstart(uint32_t ssrc, FrameId frame_id) final { transport_->ResendFrameForKickstart(ssrc, frame_id); } PacketReceiverCallback PacketReceiverForTesting() final { return transport_->PacketReceiverForTesting(); } void AddValidRtpReceiver(uint32_t rtp_sender_ssrc, uint32_t rtp_receiver_ssrc) final { return transport_->AddValidRtpReceiver(rtp_sender_ssrc, rtp_receiver_ssrc); } void InitializeRtpReceiverRtcpBuilder(uint32_t rtp_receiver_ssrc, const RtcpTimeData& time_data) final { transport_->InitializeRtpReceiverRtcpBuilder(rtp_receiver_ssrc, time_data); } void AddCastFeedback(const RtcpCastMessage& cast_message, base::TimeDelta target_delay) final { transport_->AddCastFeedback(cast_message, target_delay); } void AddRtcpEvents( const ReceiverRtcpEventSubscriber::RtcpEvents& rtcp_events) final { transport_->AddRtcpEvents(rtcp_events); } void AddRtpReceiverReport(const RtcpReportBlock& rtp_report_block) final { transport_->AddRtpReceiverReport(rtp_report_block); } void AddPli(const RtcpPliMessage& pli_message) final { transport_->AddPli(pli_message); } void SendRtcpFromRtpReceiver() final { transport_->SendRtcpFromRtpReceiver(); } void SetOptions(const base::DictionaryValue& options) final {} private: std::unique_ptr<CastTransport> transport_; uint32_t audio_ssrc_, video_ssrc_; uint64_t* encoded_video_bytes_; uint64_t* encoded_audio_bytes_; }; struct MeasuringPoint { MeasuringPoint(double bitrate_, double latency_, double percent_packet_drop_) : bitrate(bitrate_), latency(latency_), percent_packet_drop(percent_packet_drop_) {} bool operator<=(const MeasuringPoint& other) const { return bitrate >= other.bitrate && latency <= other.latency && percent_packet_drop <= other.percent_packet_drop; } bool operator>=(const MeasuringPoint& other) const { return bitrate <= other.bitrate && latency >= other.latency && percent_packet_drop >= other.percent_packet_drop; } std::string AsString() const { return base::StringPrintf( "%f Mbit/s %f ms %f %% ", bitrate, latency, percent_packet_drop); } double bitrate; double latency; double percent_packet_drop; }; class RunOneBenchmark { public: RunOneBenchmark() : start_time_(), task_runner_(new FakeSingleThreadTaskRunner(&testing_clock_)), testing_clock_sender_(&testing_clock_), task_runner_sender_( new test::SkewedSingleThreadTaskRunner(task_runner_)), testing_clock_receiver_(&testing_clock_), task_runner_receiver_( new test::SkewedSingleThreadTaskRunner(task_runner_)), cast_environment_sender_(new CastEnvironment(&testing_clock_sender_, task_runner_sender_, task_runner_sender_, task_runner_sender_)), cast_environment_receiver_(new CastEnvironment(&testing_clock_receiver_, task_runner_receiver_, task_runner_receiver_, task_runner_receiver_)), video_bytes_encoded_(0), audio_bytes_encoded_(0), frames_sent_(0) { testing_clock_.Advance( base::TimeDelta::FromMilliseconds(kStartMillisecond)); } void Configure(Codec video_codec, Codec audio_codec) { audio_sender_config_ = GetDefaultAudioSenderConfig(); audio_sender_config_.min_playout_delay = audio_sender_config_.max_playout_delay = base::TimeDelta::FromMilliseconds(kTargetPlayoutDelayMs); audio_sender_config_.codec = audio_codec; audio_receiver_config_ = GetDefaultAudioReceiverConfig(); audio_receiver_config_.rtp_max_delay_ms = audio_sender_config_.max_playout_delay.InMicroseconds(); audio_receiver_config_.codec = audio_codec; video_sender_config_ = GetDefaultVideoSenderConfig(); video_sender_config_.min_playout_delay = video_sender_config_.max_playout_delay = base::TimeDelta::FromMilliseconds(kTargetPlayoutDelayMs); video_sender_config_.max_bitrate = 4000000; video_sender_config_.min_bitrate = 4000000; video_sender_config_.start_bitrate = 4000000; video_sender_config_.codec = video_codec; video_receiver_config_ = GetDefaultVideoReceiverConfig(); video_receiver_config_.rtp_max_delay_ms = kTargetPlayoutDelayMs; video_receiver_config_.codec = video_codec; DCHECK_GT(video_sender_config_.max_frame_rate, 0); frame_duration_ = base::TimeDelta::FromSecondsD( 1.0 / video_sender_config_.max_frame_rate); } void SetSenderClockSkew(double skew, base::TimeDelta offset) { testing_clock_sender_.SetSkew(skew, offset); task_runner_sender_->SetSkew(1.0 / skew); } void SetReceiverClockSkew(double skew, base::TimeDelta offset) { testing_clock_receiver_.SetSkew(skew, offset); task_runner_receiver_->SetSkew(1.0 / skew); } void Create(const MeasuringPoint& p); void ReceivePacket(std::unique_ptr<Packet> packet) { cast_receiver_->ReceivePacket(std::move(packet)); } virtual ~RunOneBenchmark() { cast_sender_.reset(); cast_receiver_.reset(); task_runner_->RunTasks(); } base::TimeDelta VideoTimestamp(int frame_number) { return frame_number * base::TimeDelta::FromSecondsD( 1.0 / video_sender_config_.max_frame_rate); } void SendFakeVideoFrame() { // NB: Blackframe with timestamp cast_sender_->video_frame_input()->InsertRawVideoFrame( media::VideoFrame::CreateColorFrame(gfx::Size(2, 2), 0x00, 0x80, 0x80, VideoTimestamp(frames_sent_)), testing_clock_sender_.NowTicks()); frames_sent_++; } void RunTasks(base::TimeDelta duration) { task_runner_->Sleep(duration); } void BasicPlayerGotVideoFrame( const scoped_refptr<media::VideoFrame>& video_frame, const base::TimeTicks& render_time, bool continuous) { video_ticks_.push_back( std::make_pair(testing_clock_receiver_.NowTicks(), render_time)); cast_receiver_->RequestDecodedVideoFrame(base::Bind( &RunOneBenchmark::BasicPlayerGotVideoFrame, base::Unretained(this))); } void BasicPlayerGotAudioFrame(std::unique_ptr<AudioBus> audio_bus, const base::TimeTicks& playout_time, bool is_continuous) { audio_ticks_.push_back( std::make_pair(testing_clock_receiver_.NowTicks(), playout_time)); cast_receiver_->RequestDecodedAudioFrame(base::Bind( &RunOneBenchmark::BasicPlayerGotAudioFrame, base::Unretained(this))); } void StartBasicPlayer() { cast_receiver_->RequestDecodedVideoFrame(base::Bind( &RunOneBenchmark::BasicPlayerGotVideoFrame, base::Unretained(this))); cast_receiver_->RequestDecodedAudioFrame(base::Bind( &RunOneBenchmark::BasicPlayerGotAudioFrame, base::Unretained(this))); } std::unique_ptr<test::PacketPipe> CreateSimplePipe(const MeasuringPoint& p) { std::unique_ptr<test::PacketPipe> pipe = test::NewBuffer(65536, p.bitrate); pipe->AppendToPipe(test::NewRandomDrop(p.percent_packet_drop / 100.0)); pipe->AppendToPipe(test::NewConstantDelay(p.latency / 1000.0)); return pipe; } void Run(const MeasuringPoint& p) { available_bitrate_ = p.bitrate; Configure(CODEC_VIDEO_FAKE, CODEC_AUDIO_PCM16); Create(p); StartBasicPlayer(); for (int frame = 0; frame < 1000; frame++) { SendFakeVideoFrame(); RunTasks(frame_duration_); } RunTasks(100 * frame_duration_); // Empty the pipeline. VLOG(1) << "=============INPUTS============"; VLOG(1) << "Bitrate: " << p.bitrate << " mbit/s"; VLOG(1) << "Latency: " << p.latency << " ms"; VLOG(1) << "Packet drop drop: " << p.percent_packet_drop << "%"; VLOG(1) << "=============OUTPUTS============"; VLOG(1) << "Frames lost: " << frames_lost(); VLOG(1) << "Late frames: " << late_frames(); VLOG(1) << "Playout margin: " << frame_playout_buffer().AsString(); VLOG(1) << "Video bandwidth used: " << video_bandwidth() << " mbit/s (" << (video_bandwidth() * 100 / desired_video_bitrate()) << "%)"; VLOG(1) << "Good run: " << SimpleGood(); } // Metrics int frames_lost() const { return frames_sent_ - video_ticks_.size(); } int late_frames() const { int frames = 0; // Ignore the first two seconds of video or so. for (size_t i = 60; i < video_ticks_.size(); i++) { if (video_ticks_[i].first > video_ticks_[i].second) { frames++; } } return frames; } test::MeanAndError frame_playout_buffer() const { std::vector<double> values; for (size_t i = 0; i < video_ticks_.size(); i++) { values.push_back( (video_ticks_[i].second - video_ticks_[i].first).InMillisecondsF()); } return test::MeanAndError(values); } // Mbits per second double video_bandwidth() const { double seconds = (frame_duration_.InSecondsF() * frames_sent_); double megabits = video_bytes_encoded_ * 8 / 1000000.0; return megabits / seconds; } // Mbits per second double audio_bandwidth() const { double seconds = (frame_duration_.InSecondsF() * frames_sent_); double megabits = audio_bytes_encoded_ * 8 / 1000000.0; return megabits / seconds; } double desired_video_bitrate() { return std::min<double>(available_bitrate_, video_sender_config_.max_bitrate / 1000000.0); } bool SimpleGood() { return frames_lost() <= 1 && late_frames() <= 1 && video_bandwidth() > desired_video_bitrate() * 0.8 && video_bandwidth() < desired_video_bitrate() * 1.2; } private: FrameReceiverConfig audio_receiver_config_; FrameReceiverConfig video_receiver_config_; FrameSenderConfig audio_sender_config_; FrameSenderConfig video_sender_config_; base::TimeTicks start_time_; // These run in "test time" base::SimpleTestTickClock testing_clock_; scoped_refptr<FakeSingleThreadTaskRunner> task_runner_; // These run on the sender timeline. test::SkewedTickClock testing_clock_sender_; scoped_refptr<test::SkewedSingleThreadTaskRunner> task_runner_sender_; // These run on the receiver timeline. test::SkewedTickClock testing_clock_receiver_; scoped_refptr<test::SkewedSingleThreadTaskRunner> task_runner_receiver_; scoped_refptr<CastEnvironment> cast_environment_sender_; scoped_refptr<CastEnvironment> cast_environment_receiver_; LoopBackTransport* receiver_to_sender_; // Owned by CastTransportImpl. LoopBackTransport* sender_to_receiver_; // Owned by CastTransportImpl. CastTransportWrapper transport_sender_; std::unique_ptr<CastTransport> transport_receiver_; uint64_t video_bytes_encoded_; uint64_t audio_bytes_encoded_; std::unique_ptr<CastReceiver> cast_receiver_; std::unique_ptr<CastSender> cast_sender_; int frames_sent_; base::TimeDelta frame_duration_; double available_bitrate_; std::vector<std::pair<base::TimeTicks, base::TimeTicks> > audio_ticks_; std::vector<std::pair<base::TimeTicks, base::TimeTicks> > video_ticks_; }; namespace { class TransportClient : public CastTransport::Client { public: explicit TransportClient(RunOneBenchmark* run_one_benchmark) : run_one_benchmark_(run_one_benchmark) {} void OnStatusChanged(CastTransportStatus status) final { EXPECT_EQ(TRANSPORT_STREAM_INITIALIZED, status); }; void OnLoggingEventsReceived( std::unique_ptr<std::vector<FrameEvent>> frame_events, std::unique_ptr<std::vector<PacketEvent>> packet_events) final{}; void ProcessRtpPacket(std::unique_ptr<Packet> packet) final { if (run_one_benchmark_) run_one_benchmark_->ReceivePacket(std::move(packet)); }; private: RunOneBenchmark* const run_one_benchmark_; DISALLOW_COPY_AND_ASSIGN(TransportClient); }; } // namepspace void RunOneBenchmark::Create(const MeasuringPoint& p) { sender_to_receiver_ = new LoopBackTransport(cast_environment_sender_); transport_sender_.Init( new CastTransportImpl( &testing_clock_sender_, base::TimeDelta::FromSeconds(1), std::make_unique<TransportClient>(nullptr), base::WrapUnique(sender_to_receiver_), task_runner_sender_), &video_bytes_encoded_, &audio_bytes_encoded_); receiver_to_sender_ = new LoopBackTransport(cast_environment_receiver_); transport_receiver_.reset(new CastTransportImpl( &testing_clock_receiver_, base::TimeDelta::FromSeconds(1), std::make_unique<TransportClient>(this), base::WrapUnique(receiver_to_sender_), task_runner_receiver_)); cast_receiver_ = CastReceiver::Create(cast_environment_receiver_, audio_receiver_config_, video_receiver_config_, transport_receiver_.get()); cast_sender_ = CastSender::Create(cast_environment_sender_, &transport_sender_); cast_sender_->InitializeAudio(audio_sender_config_, base::Bind(&ExpectAudioSuccess)); cast_sender_->InitializeVideo(video_sender_config_, base::Bind(&ExpectVideoSuccess), CreateDefaultVideoEncodeAcceleratorCallback(), CreateDefaultVideoEncodeMemoryCallback()); receiver_to_sender_->Initialize(CreateSimplePipe(p), transport_sender_.PacketReceiverForTesting(), task_runner_, &testing_clock_); sender_to_receiver_->Initialize( CreateSimplePipe(p), transport_receiver_->PacketReceiverForTesting(), task_runner_, &testing_clock_); task_runner_->RunTasks(); } enum CacheResult { FOUND_TRUE, FOUND_FALSE, NOT_FOUND }; template <class T> class BenchmarkCache { public: CacheResult Lookup(const T& x) { base::AutoLock key(lock_); for (size_t i = 0; i < results_.size(); i++) { if (results_[i].second) { if (x <= results_[i].first) { VLOG(2) << "TRUE because: " << x.AsString() << " <= " << results_[i].first.AsString(); return FOUND_TRUE; } } else { if (x >= results_[i].first) { VLOG(2) << "FALSE because: " << x.AsString() << " >= " << results_[i].first.AsString(); return FOUND_FALSE; } } } return NOT_FOUND; } void Add(const T& x, bool result) { base::AutoLock key(lock_); VLOG(2) << "Cache Insert: " << x.AsString() << " = " << result; results_.push_back(std::make_pair(x, result)); } private: base::Lock lock_; std::vector<std::pair<T, bool> > results_; }; struct SearchVariable { SearchVariable() : base(0.0), grade(0.0) {} SearchVariable(double b, double g) : base(b), grade(g) {} SearchVariable blend(const SearchVariable& other, double factor) { CHECK_GE(factor, 0); CHECK_LE(factor, 1.0); return SearchVariable(base * (1 - factor) + other.base * factor, grade * (1 - factor) + other.grade * factor); } double value(double x) const { return base + grade * x; } double base; double grade; }; struct SearchVector { SearchVector blend(const SearchVector& other, double factor) { SearchVector ret; ret.bitrate = bitrate.blend(other.bitrate, factor); ret.latency = latency.blend(other.latency, factor); ret.packet_drop = packet_drop.blend(other.packet_drop, factor); return ret; } SearchVector average(const SearchVector& other) { return blend(other, 0.5); } MeasuringPoint GetMeasuringPoint(double v) const { return MeasuringPoint( bitrate.value(-v), latency.value(v), packet_drop.value(v)); } std::string AsString(double v) { return GetMeasuringPoint(v).AsString(); } SearchVariable bitrate; SearchVariable latency; SearchVariable packet_drop; }; class CastBenchmark { public: bool RunOnePoint(const SearchVector& v, double multiplier) { MeasuringPoint p = v.GetMeasuringPoint(multiplier); VLOG(1) << "RUN: v = " << multiplier << " p = " << p.AsString(); if (p.bitrate <= 0) { return false; } switch (cache_.Lookup(p)) { case FOUND_TRUE: return true; case FOUND_FALSE: return false; case NOT_FOUND: // Keep going break; } bool result = true; for (int tries = 0; tries < 3 && result; tries++) { RunOneBenchmark benchmark; benchmark.Run(p); result &= benchmark.SimpleGood(); } cache_.Add(p, result); return result; } void BinarySearch(SearchVector v, double accuracy) { double min = 0.0; double max = 1.0; while (RunOnePoint(v, max)) { min = max; max *= 2; } while (max - min > accuracy) { double avg = (min + max) / 2; if (RunOnePoint(v, avg)) { min = avg; } else { max = avg; } } // Print a data point to stdout. base::AutoLock key(lock_); MeasuringPoint p = v.GetMeasuringPoint(min); fprintf(stdout, "%f %f %f\n", p.bitrate, p.latency, p.percent_packet_drop); fflush(stdout); } void SpanningSearch(int max, int x, int y, int skip, SearchVector a, SearchVector b, SearchVector c, double accuracy, std::vector<std::unique_ptr<base::Thread>>* threads) { static int thread_num = 0; if (x > max) return; if (skip > max) { if (y > x) return; SearchVector ab = a.blend(b, static_cast<double>(x) / max); SearchVector ac = a.blend(c, static_cast<double>(x) / max); SearchVector v = ab.blend(ac, x == y ? 1.0 : static_cast<double>(y) / x); thread_num++; (*threads)[thread_num % threads->size()] ->message_loop() ->task_runner() ->PostTask(FROM_HERE, base::Bind(&CastBenchmark::BinarySearch, base::Unretained(this), v, accuracy)); } else { skip *= 2; SpanningSearch(max, x, y, skip, a, b, c, accuracy, threads); SpanningSearch(max, x + skip, y + skip, skip, a, b, c, accuracy, threads); SpanningSearch(max, x + skip, y, skip, a, b, c, accuracy, threads); SpanningSearch(max, x, y + skip, skip, a, b, c, accuracy, threads); } } void Run() { // Spanning search. std::vector<std::unique_ptr<base::Thread>> threads; for (int i = 0; i < 16; i++) { threads.push_back(std::make_unique<base::Thread>( base::StringPrintf("cast_bench_thread_%d", i))); threads[i]->Start(); } if (base::CommandLine::ForCurrentProcess()->HasSwitch("single-run")) { SearchVector a; a.bitrate.base = 100.0; a.bitrate.grade = 1.0; a.latency.grade = 1.0; a.packet_drop.grade = 1.0; threads[0]->message_loop()->task_runner()->PostTask( FROM_HERE, base::Bind(base::IgnoreResult(&CastBenchmark::RunOnePoint), base::Unretained(this), a, 1.0)); } else { SearchVector a, b, c; a.bitrate.base = b.bitrate.base = c.bitrate.base = 100.0; a.bitrate.grade = 1.0; b.latency.grade = 1.0; c.packet_drop.grade = 1.0; SpanningSearch(512, 0, 0, 1, a, b, c, 0.01, &threads); } for (size_t i = 0; i < threads.size(); i++) { threads[i]->Stop(); } } private: BenchmarkCache<MeasuringPoint> cache_; base::Lock lock_; }; } // namespace cast } // namespace media int main(int argc, char** argv) { base::AtExitManager at_exit; base::CommandLine::Init(argc, argv); media::cast::CastBenchmark benchmark; if (getenv("PROFILE_FILE")) { std::string profile_file(getenv("PROFILE_FILE")); base::debug::StartProfiling(profile_file); benchmark.Run(); base::debug::StopProfiling(); } else { benchmark.Run(); } }
[ "artem@brave.com" ]
artem@brave.com
6db1c42cf7db10853bb29d890fa54e997631436b
1ad05e00f49ebc3cb7d0516cc510a46f99e15cfe
/src/qt/sendcoinsentry.cpp
872a1e7918f6c8e93fa02a394120ccd9faff0b80
[ "MIT" ]
permissive
Stephanzf/finecoin
c9059c56aa25fc1e15b3774226427602a07f5dbe
395a85f5f585b86a5520469ad269e1ff5c4a8d24
refs/heads/master
2021-05-28T03:53:56.775939
2014-10-21T12:56:51
2014-10-21T12:56:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,193
cpp
#include "sendcoinsentry.h" #include "ui_sendcoinsentry.h" #include "guiutil.h" #include "bitcoinunits.h" #include "addressbookpage.h" #include "walletmodel.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include <QApplication> #include <QClipboard> SendCoinsEntry::SendCoinsEntry(QWidget *parent) : QFrame(parent), ui(new Ui::SendCoinsEntry), model(0) { ui->setupUi(this); #ifdef Q_WS_MAC ui->payToLayout->setSpacing(4); #endif #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book")); ui->payTo->setPlaceholderText(tr("Enter a FineCoin address (they start with an 'm')")); #endif setFocusPolicy(Qt::TabFocus); setFocusProxy(ui->payTo); GUIUtil::setupAddressWidget(ui->payTo, this); } SendCoinsEntry::~SendCoinsEntry() { delete ui; } void SendCoinsEntry::on_pasteButton_clicked() { // Paste text from clipboard into recipient field ui->payTo->setText(QApplication::clipboard()->text()); } void SendCoinsEntry::on_addressBookButton_clicked() { if(!model) return; AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if(dlg.exec()) { ui->payTo->setText(dlg.getReturnValue()); ui->payAmount->setFocus(); } } void SendCoinsEntry::on_payTo_textChanged(const QString &address) { if(!model) return; // Fill in label from address book, if address has an associated label QString associatedLabel = model->getAddressTableModel()->labelForAddress(address); if(!associatedLabel.isEmpty()) ui->addAsLabel->setText(associatedLabel); } void SendCoinsEntry::setModel(WalletModel *model) { this->model = model; if(model && model->getOptionsModel()) connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); clear(); } void SendCoinsEntry::setRemoveEnabled(bool enabled) { ui->deleteButton->setEnabled(enabled); } void SendCoinsEntry::clear() { ui->payTo->clear(); ui->addAsLabel->clear(); ui->payAmount->clear(); ui->payTo->setFocus(); // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void SendCoinsEntry::on_deleteButton_clicked() { emit removeEntry(this); } bool SendCoinsEntry::validate() { // Check input validity bool retval = true; if(!ui->payAmount->validate()) { retval = false; } else { if(ui->payAmount->value() <= 0) { // Cannot send 0 coins or less ui->payAmount->setValid(false); retval = false; } } if(!ui->payTo->hasAcceptableInput() || (model && !model->validateAddress(ui->payTo->text()))) { ui->payTo->setValid(false); retval = false; } return retval; } SendCoinsRecipient SendCoinsEntry::getValue() { SendCoinsRecipient rv; rv.address = ui->payTo->text(); rv.label = ui->addAsLabel->text(); rv.amount = ui->payAmount->value(); return rv; } QWidget *SendCoinsEntry::setupTabChain(QWidget *prev) { QWidget::setTabOrder(prev, ui->payTo); QWidget::setTabOrder(ui->payTo, ui->addressBookButton); QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton); QWidget::setTabOrder(ui->pasteButton, ui->deleteButton); QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel); return ui->payAmount->setupTabChain(ui->addAsLabel); } void SendCoinsEntry::setValue(const SendCoinsRecipient &value) { ui->payTo->setText(value.address); ui->addAsLabel->setText(value.label); ui->payAmount->setValue(value.amount); } bool SendCoinsEntry::isClear() { return ui->payTo->text().isEmpty(); } void SendCoinsEntry::setFocus() { ui->payTo->setFocus(); } void SendCoinsEntry::updateDisplayUnit() { if(model && model->getOptionsModel()) { // Update payAmount with the current unit ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); } }
[ "luke@debian.workgroup" ]
luke@debian.workgroup
07b026396beac58234cc1f2fb9e3793e9f1bee0e
06bed8ad5fd60e5bba6297e9870a264bfa91a71d
/libPr3/routemanager.cpp
5651c53c4eecb320f77f80e778caf7872db42422
[]
no_license
allenck/DecoderPro_app
43aeb9561fe3fe9753684f7d6d76146097d78e88
226c7f245aeb6951528d970f773776d50ae2c1dc
refs/heads/master
2023-05-12T07:36:18.153909
2023-05-10T21:17:40
2023-05-10T21:17:40
61,044,197
4
3
null
null
null
null
UTF-8
C++
false
false
97
cpp
#include "routemanager.h" RouteManager::RouteManager(QObject *parent) : Manager(parent) { }
[ "allenck@windstream.net" ]
allenck@windstream.net
c2d192249d11150b18000df2969d590c437110c1
95c5416ba31ad47ae4ade267476ba71052a253d5
/src/dji_sdk/src/modules/dji_sdk_node_time_sync.cpp
fa267ad0d26224c37294fb5c00bedbc271f099b6
[]
no_license
moyang602/bit_mbzirc
87dc435088e9a45d5ba35b773a5a0f8b411b0a8f
b74aabf4c0333c1097fd0044a8d8b10ed0200012
refs/heads/master
2020-08-28T23:35:02.428583
2020-01-19T08:18:16
2020-01-19T08:21:14
217,852,656
7
7
null
2019-10-27T12:59:55
2019-10-27T12:36:15
CMake
UTF-8
C++
false
false
2,510
cpp
/** @file dji_sdk_node_time_sync.cpp * @version 3.8.1 * @date May, 2019 * * @brief * Implementation of the time sync functions of DJISDKNode * * @copyright 2019 DJI. All rights reserved. * */ #include <dji_sdk/dji_sdk_node.h> void DJISDKNode::NMEACallback(Vehicle* vehiclePtr, RecvContainer recvFrame, UserData userData) { nmea_msgs::Sentence nmeaSentence; int length = recvFrame.recvInfo.len - OpenProtocol::PackageMin - 4; uint8_t rawBuf[length]; memcpy(rawBuf, recvFrame.recvData.raw_ack_array, length); nmeaSentence.header.frame_id = "NMEA"; nmeaSentence.header.stamp = ros::Time::now(); nmeaSentence.sentence = std::string((char*)rawBuf, length); DJISDKNode *p = (DJISDKNode *) userData; p->time_sync_nmea_publisher.publish(nmeaSentence); } void DJISDKNode::GPSUTCTimeCallback(Vehicle *vehiclePtr, RecvContainer recvFrame, UserData userData) { dji_sdk::GPSUTC GPSUTC; int length = recvFrame.recvInfo.len - OpenProtocol::PackageMin - 4; uint8_t rawBuf[length]; memcpy(rawBuf, recvFrame.recvData.raw_ack_array, length); GPSUTC.stamp = ros::Time::now(); GPSUTC.UTCTimeData = std::string((char*)rawBuf, length).c_str(); DJISDKNode *p = (DJISDKNode *) userData; p->time_sync_gps_utc_publisher.publish(GPSUTC); } void DJISDKNode::FCTimeInUTCCallback(Vehicle* vehiclePtr, RecvContainer recvFrame, UserData userData) { dji_sdk::FCTimeInUTC fcTimeInUtc; fcTimeInUtc.stamp = ros::Time::now(); fcTimeInUtc.fc_timestamp_us = recvFrame.recvData.fcTimeInUTC.fc_timestamp_us; fcTimeInUtc.fc_utc_hhmmss = recvFrame.recvData.fcTimeInUTC.utc_hhmmss; fcTimeInUtc.fc_utc_yymmdd = recvFrame.recvData.fcTimeInUTC.utc_yymmdd; DJISDKNode *p = (DJISDKNode *) userData; p->time_sync_fc_utc_publisher.publish(fcTimeInUtc); } void DJISDKNode::PPSSourceCallback(Vehicle* vehiclePtr, RecvContainer recvFrame, UserData userData) { std_msgs::String PPSSourceData; std::vector<std::string> stringVec = {"0", "INTERNAL_GPS", "EXTERNAL_GPS", "RTK"}; DJISDKNode *p = (DJISDKNode *) userData; if(recvFrame.recvData.ppsSourceType < stringVec.size()) { PPSSourceData.data = stringVec[recvFrame.recvData.ppsSourceType]; p->time_sync_pps_source_publisher.publish(PPSSourceData); } }
[ "test@bit.edu.cn" ]
test@bit.edu.cn
e640b2fdb233de1e7850910c1dda018485310220
24e53da2e930fb4876bf7d3f7edb61e7d845b4fc
/Label.h
be5dce4b3740b168a2c87789b97c34095d0160b3
[]
no_license
nickcuenca/GUI-Project
631bc5faaa052d6825f36cdf0968cac2504772c8
841feb6fb52b46068c29fcf31ced2d98a57d0264
refs/heads/master
2023-05-19T19:46:41.119431
2021-06-06T05:58:20
2021-06-06T05:58:20
363,311,849
0
0
null
null
null
null
UTF-8
C++
false
false
442
h
// // Created by Nicolas Cuenca on 4/9/2021. // #ifndef PROJECT_LABEL_H #define PROJECT_LABEL_H #include "SFML/Graphics.hpp" class Label : public sf::Drawable { private: sf::Text text; sf::Font font; std::string labelInstruction = "Enter your information:\n"; public: Label(); virtual void draw(sf::RenderTarget& window, sf::RenderStates states) const; //This function is to draw your text }; #endif //PROJECT_LABEL_H
[ "Nicolascuenca123@gmail.com" ]
Nicolascuenca123@gmail.com
1921ba49e41bb0929f12726524c8a1d59e071835
1008456f8b0a764978b4cbc993692b1e0526d3ce
/ActualProject/tryNumber2/GameEngine/Texture.h
81f5ff276939d61d51d21f15488979e741704d3b
[]
no_license
orleg01/openGl
903805ce296dcc703feb9234e378102fa1d8345d
fe8925a76cb5d63e7457e0f6e2d656e5038b51f0
refs/heads/master
2021-01-10T06:03:27.821080
2016-02-20T20:21:37
2016-02-20T20:21:37
51,646,905
0
0
null
null
null
null
UTF-8
C++
false
false
777
h
#ifndef __TEXTURE_H #define __TEXTURE_H #include <assimps\assimp\material.h> #include <glew\GL\glew.h> #include <glfw/GLFW/glfw3.h> #include <string> #include <fstream> #include <sstream> #include <iostream> #include <vector> #include <soil\SOIL.h> #include <glm\glm.hpp> //my Headers class Texture; using namespace std; class Texture { public: ~Texture(); static Texture* getTexture(string path , glm::vec2 textureWarpOption); static void setTexturesToShader(vector<Texture*> myTextures[] , GLuint shadId); void unBind(); void Bind(); static void deleteAllTextures(); private: static vector<Texture*> allTexture; string path; string nameOfTexture; GLuint textureId; glm::vec2 textureWarpOption; Texture(string path , glm::vec2 textureWarpOption); }; #endif
[ "orleg01@gmail.com" ]
orleg01@gmail.com
46469d59838bacca4953dce337d7d2ff2684c924
14eb67918b2ce484029115135ea5cf6f0454b0da
/Week4Fireworks2/src/burstParticle.cpp
c796cc46b9c2e505856f9436d3d7e19c89062e22
[]
no_license
Amiraanne/AmiraAnne_algo2012
eadf7fe6b20fadce5d4baec11952118b7d682514
2765f728f65117710b35d87c2caac0544613a231
refs/heads/master
2021-01-20T07:15:08.008913
2012-12-18T22:19:54
2012-12-18T22:19:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
706
cpp
/* * burstParticle.cpp * emptyExample * * Created by Amira Pettus on 10/28/12. */ #include "burstParticle.h" burstParticle::burstParticle() { setup(0, 0, 0, 0); damping = 0.01f; } void burstParticle::setup(float px, float py, float vx, float vy) { pos.set(px, py); vel.set(vx, vy); } void burstParticle::resetForce() { frc.set(0,0); } void burstParticle::addDampingForce() { //frc.x -= vel.x * damping; //frc.y -= vel.y * damping; } void burstParticle::update() { vel = vel + frc; pos.x += vel.x * cos(theta); pos.y += vel.y * sin(theta); } void burstParticle::draw() { ofPushMatrix(); ofTranslate(pos.x, pos.y); ofCircle(2, 0, 2); ofPopMatrix(); }
[ "renavatio.desonar@gmail.com" ]
renavatio.desonar@gmail.com
49aee9798e21ff9fe00112d3b89e8952cac40e68
9028d5e85e3321869e94c3accf24bf67e0e07ee0
/Tasks/task_20.cpp
e73c1eb837ff011bccd2553ad9289a937c975fcd
[]
no_license
pukala2/old_stuff
525dc8b3601df9141cbcfe215c2e9971e6fef3ed
2e45b8465b900b00c3781e716686c5df665f06d2
refs/heads/master
2020-03-24T08:11:37.674093
2018-07-27T14:50:55
2018-07-27T14:50:55
142,587,686
0
0
null
null
null
null
UTF-8
C++
false
false
209
cpp
#include <iostream> template <class T> void foo(T value) { static int counter; ++counter; std::cout << counter << std::endl; } int main() { foo(4); foo(5); foo(5.5); return 0; }
[ "przemyslaw.pukala@gmail.com" ]
przemyslaw.pukala@gmail.com
4f05f0916c3b570e0481b3463c275bee4b4fea74
d4386cdd1bf16a903b8e4dfc3484eb19eef80b5c
/VEXU2018-2019/VEX Code Snippits/Drive Backward.cpp
15f05d19dde2b82f6ee0c0350f935cb9c475c1ef
[]
no_license
TheRevilo2018/VEX-Robotics-SDSMT
1535b21b77ba35493ee7b9c1d22ae23ae173b150
b80a2ef00a2c4cf76301b81ce3ee3b3ec48db54f
refs/heads/master
2023-08-15T07:34:05.839114
2021-09-27T04:18:15
2021-09-27T04:18:15
109,911,898
1
0
null
2021-05-24T19:59:30
2017-11-08T01:30:23
C++
UTF-8
C++
false
false
1,850
cpp
#include "robot-config.h" /*+++++++++++++++++++++++++++++++++++++++++++++| Notes |++++++++++++++++++++++++++++++++++++++++++++++ Drive Backward This program instructs your robot to move backward at half power for three seconds. There is a two second pause at the beginning of the program. Robot Configuration: [Smart Port] [Name] [Type] [Description] [Reversed] Motor Port 1 LeftMotor V5 Smart Motor Left side motor false Motor Port 10 RightMotor V5 Smart Motor Right side motor true ----------------------------------------------------------------------------------------------------*/ int main() { //Wait 2 seconds or 2000 milliseconds before starting the program. vex::task::sleep(2000); //Print to the screen that the program has started. Brain.Screen.print("User Program has Started."); //Set the velocity of the left and right motor to 50% power. This command will not make the motor spin. LeftMotor.setVelocity(50, vex::velocityUnits::pct); RightMotor.setVelocity(50, vex::velocityUnits::pct); //Spin the right and left motor in the reverse direction. The motors will spin at 50% power because of the previous commands. LeftMotor.spin(vex::directionType::rev); RightMotor.spin(vex::directionType::rev); //Wait 3 second or 3000 milliseconds. vex::task::sleep(3000); //Stop both motors. LeftMotor.stop(); RightMotor.stop(); //Print to the brain's screen that the program has ended. Brain.Screen.newLine();//Move the cursor to a new line on the screen. Brain.Screen.print("User Program has Ended."); //Prevent main from exiting with an infinite loop. while(1) { vex::task::sleep(100);//Sleep the task for a short amount of time to prevent wasted resources. } }
[ "matthew.reff@mines.sdsmt.edu" ]
matthew.reff@mines.sdsmt.edu
5e7caef092d9a9394a8b626d5193ee4a326c1cab
a5cea5298c0bf3f88111b3eb9245905e11a10094
/test/indicator/FastNonDominatedRankTest.cpp
a11b10ff2a1752de513cf48cefd4b6afd84fe46a
[ "MIT" ]
permissive
blankjul/moo-cpp
a28feb2b37aadd91cdb84b6013f480ed0f1af9a0
df9c20e70f17b8aa4041f8442dd7d6ae9a3de093
refs/heads/master
2022-07-30T05:32:55.477615
2015-07-01T20:35:26
2015-07-01T20:35:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
711
cpp
#include "IndicatorTest.h" #include "indicator/NonDominatedRank.h" #include "indicator/FastNonDominatedRank.h" #include <unordered_map> class FastNonDominatedRankTest : public IndicatorTest { public: moo::Population<moo::Identity> population {100}; }; TEST_F(FastNonDominatedRankTest, RankOrderTestCorrect) { auto m = moo::NonDominatedRank::calculate(population); auto mfast = moo::FastNonDominatedRank::calculate(population); EXPECT_EQ(m, mfast); } TEST_F(FastNonDominatedRankTest, RankOrderTestCorrectOnlySomeIndividuals) { auto m = moo::NonDominatedRank::calculate_(population,20); auto mfast = moo::FastNonDominatedRank::calculate_(population,20); EXPECT_EQ(m, mfast); }
[ "jules89@arcor.de" ]
jules89@arcor.de
83182affc4ade104e1e7f782f19a3899e92da01f
fd1ebd6643638503b3de0d61886295e0000a50f2
/Arduino/libraries/USBHost/src/adk.cpp
3d5602d312bfce31b96cd2f3981c5b788895e534
[ "Apache-2.0", "LGPL-2.1-or-later" ]
permissive
zwartepoester/sheldon
20683aabe70a9d49fa17c78c83f8bca17a0e0252
7001551b65cd5b595a0a93e58528198d3d1e5553
refs/heads/master
2020-03-27T06:31:10.055745
2018-08-25T16:52:55
2018-08-25T16:52:55
146,112,676
0
0
Apache-2.0
2018-08-25T16:45:46
2018-08-25T16:45:46
null
UTF-8
C++
false
false
10,233
cpp
/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. This software may be distributed and modified under the terms of the GNU General Public License version 2 (GPL2) as published by the Free Software Foundation and appearing in the file GPL2.TXT included in the packaging of this file. Please note that GPL2 Section 2[b] requires that all works based on this software must also be made publicly available under the terms of the GPL2 ("Copyleft"). Contact information ------------------- Circuits At Home, LTD Web : http://www.circuitsathome.com e-mail : support@circuitsathome.com */ /* Google ADK interface */ #include "adk.h" const uint32_t ADK::epDataInIndex = 1; const uint32_t ADK::epDataOutIndex = 2; /** * \brief ADK class constructor. */ ADK::ADK(USBHost *p, const char* pmanufacturer, const char* pmodel, const char* pdescription, const char* pversion, const char* puri, const char* pserial) : manufacturer(pmanufacturer), model(pmodel), description(pdescription), version(pversion), uri(puri), serial(pserial), pUsb(p), bAddress(0), bNumEP(1), ready(false) { // Initialize endpoint data structures for (uint32_t i = 0; i < ADK_MAX_ENDPOINTS; ++i) { epInfo[i].deviceEpNum = 0; epInfo[i].hostPipeNum = 0; epInfo[i].maxPktSize = (i) ? 0 : 8; epInfo[i].epAttribs = 0; epInfo[i].bmNakPower = (i) ? USB_NAK_NOWAIT : USB_NAK_MAX_POWER; } // Register in USB subsystem if (pUsb) { pUsb->RegisterDeviceClass(this); } } /** * \brief Initialize connection to an Android Phone. * * \param parent USB device address of the Parent device. * \param port USB device base address. * \param lowspeed USB device speed. * * \return 0 on success, error code otherwise. */ uint32_t ADK::Init(uint32_t parent, uint32_t port, uint32_t lowspeed) { uint8_t buf[sizeof(USB_DEVICE_DESCRIPTOR)]; uint32_t rcode = 0; UsbDevice *p = NULL; EpInfo *oldep_ptr = NULL; uint32_t adkproto = -1; uint32_t num_of_conf = 0; // Get memory address of USB device address pool AddressPool &addrPool = pUsb->GetAddressPool(); TRACE_USBHOST(printf("ADK::Init\r\n");) // Check if address has already been assigned to an instance if (bAddress) { return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE; } // Get pointer to pseudo device with address 0 assigned p = addrPool.GetUsbDevicePtr(0); if (!p) { return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; } if (!p->epinfo) { return USB_ERROR_EPINFO_IS_NULL; } // Save old pointer to EP_RECORD of address 0 oldep_ptr = p->epinfo; // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence p->epinfo = epInfo; p->lowspeed = lowspeed; // Get device descriptor rcode = pUsb->getDevDescr(0, 0, sizeof(USB_DEVICE_DESCRIPTOR), (uint8_t*)buf); // Restore p->epinfo p->epinfo = oldep_ptr; if (rcode) { goto FailGetDevDescr; } // Allocate new address according to device class bAddress = addrPool.AllocAddress(parent, false, port); // Extract Max Packet Size from device descriptor epInfo[0].maxPktSize = (uint8_t)((USB_DEVICE_DESCRIPTOR*)buf)->bMaxPacketSize0; // Assign new address to the device rcode = pUsb->setAddr(0, 0, bAddress); if (rcode) { p->lowspeed = false; addrPool.FreeAddress(bAddress); bAddress = 0; TRACE_USBHOST(printf("ADK::Init : setAddr failed with rcode %lu\r\n", rcode);) return rcode; } TRACE_USBHOST(printf("ADK::Init : device address is now %lu\r\n", bAddress);) p->lowspeed = false; //get pointer to assigned address record p = addrPool.GetUsbDevicePtr(bAddress); if (!p) { return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; } p->lowspeed = lowspeed; // Assign epInfo to epinfo pointer - only EP0 is known rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); if (rcode) { goto FailSetDevTblEntry; } // Check if ADK device is already in accessory mode; if yes, configure and exit if (((USB_DEVICE_DESCRIPTOR*)buf)->idVendor == ADK_VID && (((USB_DEVICE_DESCRIPTOR*)buf)->idProduct == ADK_PID || ((USB_DEVICE_DESCRIPTOR*)buf)->idProduct == ADB_PID)) { TRACE_USBHOST(printf("ADK::Init : Accessory mode device detected\r\n");) /* Go through configurations, find first bulk-IN, bulk-OUT EP, fill epInfo and quit */ num_of_conf = ((USB_DEVICE_DESCRIPTOR*)buf)->bNumConfigurations; TRACE_USBHOST(printf("ADK::Init : number of configuration is %lu\r\n", num_of_conf);) for (uint32_t i = 0; i < num_of_conf; ++i) { ConfigDescParser<0, 0, 0, 0> confDescrParser(this); delay(1); rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser); #if defined(XOOM) //Added by Jaylen Scott Vanorden if (rcode) { TRACE_USBHOST(printf("ADK::Init : Got 1st bad code for config: %lu\r\n", rcode);) // Try once more rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser); } #endif if (rcode) { goto FailGetConfDescr; } if (bNumEP > 2) { break; } } if (bNumEP == 3) { // Assign epInfo to epinfo pointer - this time all 3 endpoins rcode = pUsb->setEpInfoEntry(bAddress, 3, epInfo); if (rcode) { goto FailSetDevTblEntry; } } // Set Configuration Value rcode = pUsb->setConf(bAddress, 0, bConfNum); if (rcode) { goto FailSetConf; } TRACE_USBHOST(printf("ADK::Init : ADK device configured successfully\r\n");) ready = true; return 0; } // Probe device - get accessory protocol revision delay(1); rcode = getProto((uint8_t*)&adkproto); #if defined(XOOM) // Added by Jaylen Scott Vanorden if (rcode) { TRACE_USBHOST(printf("ADK::Init : Got 1st bad code for config: %lu\r\n", rcode);) // Try once more rcode = getProto((uint8_t*)&adkproto ); } #endif if (rcode) { goto FailGetProto; } TRACE_USBHOST(printf("ADK::Init : DK protocol rev. %lu", adkproto);) // Send ID strings sendStr(ACCESSORY_STRING_MANUFACTURER, manufacturer); sendStr(ACCESSORY_STRING_MODEL, model); sendStr(ACCESSORY_STRING_DESCRIPTION, description); sendStr(ACCESSORY_STRING_VERSION, version); sendStr(ACCESSORY_STRING_URI, uri); sendStr(ACCESSORY_STRING_SERIAL, serial); // Switch to accessory mode // The Android phone will reset rcode = switchAcc(); if (rcode) { goto FailSwAcc; } rcode = -1; goto SwAttempt; // Switch to accessory mode // Diagnostic messages FailGetDevDescr: TRACE_USBHOST(printf("ADK::Init getDevDescr : ");) goto Fail; FailSetDevTblEntry: TRACE_USBHOST(printf("ADK::Init setDevTblEn : ");) goto Fail; FailGetProto: TRACE_USBHOST(printf("ADK::Init getProto : ");) goto Fail; FailSwAcc: TRACE_USBHOST(printf("ADK::Init swAcc : ");) goto Fail; SwAttempt: TRACE_USBHOST(printf("ADK::Init Accessory mode switch attempt : ");) goto Fail; FailGetConfDescr: TRACE_USBHOST(printf("ADK::Init getConf : ");) goto Fail; FailSetConf: TRACE_USBHOST(printf("ADK::Init setConf : ");) goto Fail; Fail: TRACE_USBHOST(printf("error code: %lu\r\n", rcode);) Release(); return rcode; } /** * \brief Extract bulk-IN and bulk-OUT endpoint information from configuration * descriptor. * * \param conf Configuration number. * \param iface Interface number. * \param alt Alternate setting. * \param proto Protocol version used. * \param pep Pointer to endpoint descriptor. */ void ADK::EndpointXtract(uint32_t conf, uint32_t iface, uint32_t alt, uint32_t proto, const USB_ENDPOINT_DESCRIPTOR *pep) { if (bNumEP == 3) { return; } bConfNum = conf; uint32_t index = 0; uint32_t pipe = 0; if ((pep->bmAttributes & 0x02) == 2) { index = ((pep->bEndpointAddress & 0x80) == 0x80) ? epDataInIndex : epDataOutIndex; } // Fill in the endpoint info structure epInfo[index].deviceEpNum = pep->bEndpointAddress & 0x0F; epInfo[index].maxPktSize = pep->wMaxPacketSize; TRACE_USBHOST(printf("ADK::EndpointXtract : Found new endpoint\r\n");) TRACE_USBHOST(printf("ADK::EndpointXtract : deviceEpNum: %lu\r\n", epInfo[index].deviceEpNum);) TRACE_USBHOST(printf("ADK::EndpointXtract : maxPktSize: %lu\r\n", epInfo[index].maxPktSize);) TRACE_USBHOST(printf("ADK::EndpointXtract : index: %lu\r\n", index);) if (index == epDataInIndex) pipe = UHD_Pipe_Alloc(bAddress, epInfo[index].deviceEpNum, UOTGHS_HSTPIPCFG_PTYPE_BLK, UOTGHS_HSTPIPCFG_PTOKEN_IN, epInfo[index].maxPktSize, 0, UOTGHS_HSTPIPCFG_PBK_1_BANK); else if (index == epDataOutIndex) pipe = UHD_Pipe_Alloc(bAddress, epInfo[index].deviceEpNum, UOTGHS_HSTPIPCFG_PTYPE_BLK, UOTGHS_HSTPIPCFG_PTOKEN_OUT, epInfo[index].maxPktSize, 0, UOTGHS_HSTPIPCFG_PBK_1_BANK); // Ensure pipe allocation is okay if (pipe == 0) { TRACE_USBHOST(printf("ADK::EndpointXtract : Pipe allocation failure\r\n");) // Enumeration failed, so user should not perform write/read since isConnected will return false return; } epInfo[index].hostPipeNum = pipe; bNumEP++; } /** * \brief Release USB allocated resources (pipes and address). * * \note Release call is made from USBHost.task() on disconnection events. * \note Release call is made from Init() on enumeration failure. * * \return Always 0. */ uint32_t ADK::Release() { // Free allocated host pipes UHD_Pipe_Free(epInfo[epDataInIndex].hostPipeNum); UHD_Pipe_Free(epInfo[epDataOutIndex].hostPipeNum); // Free allocated USB address pUsb->GetAddressPool().FreeAddress(bAddress); // Must have to be reset to 1 bNumEP = 1; bAddress = 0; ready = false; return 0; } /** * \brief Read from ADK. * * \param nreadbytes Return value containing the number of read bytes. * \param datalen Buffer length. * \param dataptr Buffer to store the incoming data. * * \return 0 on success, error code otherwise. */ uint32_t ADK::read(uint32_t *nreadbytes, uint32_t datalen, uint8_t *dataptr) { *nreadbytes = datalen; return pUsb->inTransfer(bAddress, epInfo[epDataInIndex].deviceEpNum, nreadbytes, dataptr); } /** * \brief Write to ADK. * * \param datalen Amount of data to send. This parameter shall not exceed * dataptr length. * \param dataptr Buffer containing the data to be sent. * * \return 0 on success, error code otherwise. */ uint32_t ADK::write(uint32_t datalen, uint8_t *dataptr) { return pUsb->outTransfer(bAddress, epInfo[epDataOutIndex].deviceEpNum, datalen, dataptr); }
[ "dave.shinsel@gmail.com" ]
dave.shinsel@gmail.com
b3287ec6ed77eba8adf03e5dc0f8e450572829ef
7da51e1fb66879a668718f9c08a7e95f11341190
/sources/openGL/camera.cpp
c67faf7009793a3977759fef5daeba16a4c05c46
[]
no_license
fafancier/light-field-remote-vision
ab26960789decdc9ca219f96aca0ab1ac9f6946d
fd8b7befc06274e05cac36bcd7bbf7d93d6270f9
refs/heads/master
2021-09-02T02:26:44.673557
2017-12-29T18:36:48
2017-12-29T18:36:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,484
cpp
#include "camera.h" // Permet d'éviter la ré-écriture du namespace glm:: using namespace glm; // Constructeurs et Destructeur Camera::Camera() : m_phi(0.0), m_theta(0.0), m_orientation(), m_axeVertical(0, 0, 1), m_deplacementLateral(), m_position(), m_pointCible(), m_sensibilite(0.0), m_vitesse(0.0) { } Camera::Camera(glm::vec3 position, glm::vec3 pointCible, glm::vec3 axeVertical, float sensibilite, float vitesse) : m_phi(0.0), m_theta(0.0), m_orientation(), m_axeVertical(axeVertical), m_deplacementLateral(), m_position(position), m_pointCible(pointCible), m_sensibilite(sensibilite), m_vitesse(vitesse) { // Actualisation du point ciblé setPointcible(); } Camera::~Camera() { } // Méthodes void Camera::orienter(int xRel, int yRel) { // Récupération des angles m_phi += xRel * m_sensibilite; m_theta += -yRel * m_sensibilite; // Limitation de l'angle phi if(m_phi > 89.0) m_phi = 89.0; else if(m_phi < -89.0) m_phi = -89.0; // Conversion des angles en radian float phiRadian = m_phi * M_PI / 180; float thetaRadian = m_theta * M_PI / 180; // Si l'axe vertical est l'axe X if(m_axeVertical.x == 1.0) { // Calcul des coordonnées sphériques m_orientation.x = sin(phiRadian); m_orientation.y = cos(phiRadian) * cos(thetaRadian); m_orientation.z = cos(phiRadian) * sin(thetaRadian); } // Si c'est l'axe Y else if(m_axeVertical.y == 1.0) { // Calcul des coordonnées sphériques m_orientation.x = cos(phiRadian) * sin(thetaRadian); m_orientation.y = sin(phiRadian); m_orientation.z = cos(phiRadian) * cos(thetaRadian); } // Sinon c'est l'axe Z else { // Calcul des coordonnées sphériques m_orientation.x = cos(phiRadian) * cos(thetaRadian); m_orientation.y = cos(phiRadian) * sin(thetaRadian); m_orientation.z = sin(phiRadian); } // Calcul de la normale m_deplacementLateral = cross(m_axeVertical, m_orientation); m_deplacementLateral = normalize(m_deplacementLateral); // Calcul du point ciblé pour OpenGL m_pointCible = m_position + m_orientation; } void Camera::deplacer(Input const &input) { // Gestion de l'orientation if(input.moveMouse()) { orienter(input.getXRel(), input.getYRel()); } // Avancée de la caméra if(input.getKey(SDL_SCANCODE_UP)) { m_position = m_position + m_orientation * m_vitesse; m_pointCible = m_position + m_orientation; } // Recul de la caméra if(input.getKey(SDL_SCANCODE_DOWN)) { m_position = m_position - m_orientation * m_vitesse; m_pointCible = m_position + m_orientation; } // Déplacement vers la gauche if(input.getKey(SDL_SCANCODE_LEFT)) { m_position = m_position + m_deplacementLateral * m_vitesse; m_pointCible = m_position + m_orientation; } // Déplacement vers la droite if(input.getKey(SDL_SCANCODE_RIGHT)) { m_position = m_position - m_deplacementLateral * m_vitesse; m_pointCible = m_position + m_orientation; } } void Camera::lookAt(glm::mat4 &modelview) { // Actualisation de la vue dans la matrice modelview = glm::lookAt(m_position, m_pointCible, m_axeVertical); } // Getters et Setters void Camera::setPointcible() { // Calcul du vecteur orientation m_orientation = m_pointCible - m_position; m_orientation = normalize(m_orientation); // Si l'axe vertical est l'axe X if(m_axeVertical.x == 1.0) { // Calcul des angles m_phi = asin(m_orientation.x); m_theta = acos(m_orientation.y / cos(m_phi)); if(m_orientation.y < 0) m_theta *= -1; } // Si c'est l'axe Y else if(m_axeVertical.y == 1.0) { // Calcul des angles m_phi = asin(m_orientation.y); m_theta = acos(m_orientation.z / cos(m_phi)); if(m_orientation.z < 0) m_theta *= -1; } // Sinon c'est l'axe Z else { // Calcul des angles m_phi = asin(m_orientation.x); m_theta = acos(m_orientation.z / cos(m_phi)); if(m_orientation.z < 0) m_theta *= -1; } // Conversion en degrés m_phi = m_phi * 180 / M_PI; m_theta = m_theta * 180 / M_PI; } void Camera::setPosition(glm::vec3 position) { // Mise à jour de la position m_position = position; // Actualisation du point ciblé m_pointCible = m_position + m_orientation; } float Camera::getSensibilite() const { return m_vitesse; } float Camera::getVitesse() const { return m_vitesse; } void Camera::setSensibilite(float sensibilite) { m_sensibilite = sensibilite; } void Camera::setVitesse(float vitesse) { m_vitesse = vitesse; }
[ "gregoire.nieto@inria.fr" ]
gregoire.nieto@inria.fr
54b0a06093fd6f6a5f78507f2238bb2a8540612d
f1f230510bfc867c43f8563f33d3a756dd162b45
/lib/GFX_Library_for_Arduino/src/display/Arduino_ILI9341.cpp
09b5c29b5ed2af4e166133d00f3e0d185f6fa303
[]
no_license
Tinyu-Zhao/roundDisplay
60bae3b54416ae1cf5a600882b98bbd17bdc3dd0
84ced7b6cffbf624d86c97cea30776baf2362d37
refs/heads/master
2023-08-23T18:03:59.864231
2021-09-16T13:01:47
2021-09-16T13:01:47
399,998,448
0
0
null
null
null
null
UTF-8
C++
false
false
3,630
cpp
/* * start rewrite from: * https://github.com/adafruit/Adafruit-GFX-Library.git * https://github.com/adafruit/Adafruit_ILI9341.git */ #include "Arduino_ILI9341.h" Arduino_ILI9341::Arduino_ILI9341(Arduino_DataBus *bus, int8_t rst, uint8_t r) : Arduino_TFT(bus, rst, r, false, ILI9341_TFTWIDTH, ILI9341_TFTHEIGHT, 0, 0, 0, 0) { } void Arduino_ILI9341::begin(int32_t speed) { Arduino_TFT::begin(speed); } // Companion code to the above tables. Reads and issues // a series of LCD commands stored in PROGMEM byte array. void Arduino_ILI9341::tftInit() { if (_rst < 0) { _bus->sendCommand(ILI9341_SWRESET); // 1: Software reset delay(ILI9341_RST_DELAY); } spi_operation_t ili9341_init_operations[] = { {BEGIN_WRITE, 0}, {WRITE_COMMAND_8, ILI9341_PWCTR1}, // Power control VRH[5:0] {WRITE_DATA_8, 0x23}, {WRITE_COMMAND_8, ILI9341_PWCTR2}, // Power control SAP[2:0];BT[3:0] {WRITE_DATA_8, 0x10}, {WRITE_COMMAND_8, ILI9341_VMCTR1}, // VCM control {WRITE_DATA_8, 0x3e}, {WRITE_DATA_8, 0x28}, {WRITE_COMMAND_8, ILI9341_VMCTR2}, // VCM control2 {WRITE_DATA_8, 0x86}, {WRITE_COMMAND_8, ILI9341_VSCRSADD}, // Vertical scroll zero {WRITE_DATA_8, 0x00}, {WRITE_COMMAND_8, ILI9341_PIXFMT}, {WRITE_DATA_8, 0x55}, {WRITE_COMMAND_8, ILI9341_FRMCTR1}, {WRITE_DATA_8, 0x00}, {WRITE_DATA_8, 0x18}, {WRITE_COMMAND_8, ILI9341_DFUNCTR}, // Display Function Control {WRITE_DATA_8, 0x08}, {WRITE_DATA_8, 0x82}, {WRITE_DATA_8, 0x27}, {WRITE_COMMAND_8, ILI9341_SLPOUT}, // Exit Sleep {END_WRITE, 0}, {DELAY, ILI9341_SLPOUT_DELAY}, {BEGIN_WRITE, 0}, {WRITE_COMMAND_8, ILI9341_DISPON}, // Display on {END_WRITE, 0}, }; _bus->batchOperation(ili9341_init_operations, sizeof(ili9341_init_operations) / sizeof(ili9341_init_operations[0])); } void Arduino_ILI9341::writeAddrWindow(uint16_t x, uint16_t y, uint16_t w, uint16_t h) { if ((x != _currentX) || (w != _currentW)) { _bus->writeC8D16D16(ILI9341_CASET, x + _xStart, x + w - 1 + _xStart); _currentX = x; _currentW = w; } if ((y != _currentY) || (h != _currentH)) { _bus->writeC8D16D16(ILI9341_PASET, y + _yStart, y + h - 1 + _yStart); _currentY = y; _currentH = h; } _bus->writeCommand(ILI9341_RAMWR); // write to RAM } /**************************************************************************/ /*! @brief Set origin of (0,0) and orientation of TFT display @param m The index for rotation, from 0-3 inclusive */ /**************************************************************************/ void Arduino_ILI9341::setRotation(uint8_t r) { Arduino_TFT::setRotation(r); switch (_rotation) { case 0: r = (ILI9341_MADCTL_MX | ILI9341_MADCTL_BGR); break; case 1: r = (ILI9341_MADCTL_MV | ILI9341_MADCTL_BGR); break; case 2: r = (ILI9341_MADCTL_MY | ILI9341_MADCTL_BGR); break; case 3: r = (ILI9341_MADCTL_MX | ILI9341_MADCTL_MY | ILI9341_MADCTL_MV | ILI9341_MADCTL_BGR); break; } _bus->beginWrite(); _bus->writeC8D8(ILI9341_MADCTL, r); _bus->endWrite(); } void Arduino_ILI9341::invertDisplay(bool i) { _bus->sendCommand(i ? ILI9341_INVON : ILI9341_INVOFF); } void Arduino_ILI9341::displayOn(void) { _bus->sendCommand(ILI9341_SLPOUT); delay(ILI9341_SLPOUT_DELAY); } void Arduino_ILI9341::displayOff(void) { _bus->sendCommand(ILI9341_SLPIN); delay(ILI9341_SLPIN_DELAY); }
[ "Tinyu.Zhao@gmail.com" ]
Tinyu.Zhao@gmail.com
d4899bb86e24dafe7b95252961c7ba0b3068cb0b
08cde2396e1c6e2fc3de721570948a72cd9fa632
/Subdivision/_3DStructure.h
206f9f2f5c1ca747dd8e0d15d2e2b45df3bbb0d6
[]
no_license
Gchenyu/3D_modeling
65b59e39f17707d7fe721ca0f37dcdc94c95114c
1f051a4d78542bac0864b9f406a8c7477613b005
refs/heads/master
2020-05-30T05:30:07.761781
2019-05-31T09:43:11
2019-05-31T09:43:11
189,561,996
0
1
null
null
null
null
GB18030
C++
false
false
2,043
h
#pragma once #ifndef _3DStructure_H_ #define _3DStructure_H_ /**************************总依赖*********************************/ //_3DStructure.h的依赖 #include <cmath> #include <assert.h> #include<iostream> //Display.h的依赖 #include <GL/glut.h> #include<GL/glu.h> #include <stdio.h> #include <windows.h> //MeshStructure.h的依赖 #include<fstream> #include<string> #include<vector> #include<algorithm> /****************************************************************/ using namespace std; /**************************三维向量结构定义*********************************/ class _3DStructure{ public: float x, y, z; _3DStructure(float _x = 0.0, float _y = 0.0, float _z = 0.0) :x(_x), y(_y), z(_z) {} float Length() { return sqrt(x * x + y * y + z * z); } void display() { cout << "x=" << x << " y=" << y << " z=" << z << "\n"; } }; /********************************向量基础运算,运算符符重载****************************************/ _3DStructure operator+(const _3DStructure& v1, const _3DStructure& v2) { return _3DStructure(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z); } _3DStructure operator-(const _3DStructure& v1, const _3DStructure& v2) { return _3DStructure(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z); } _3DStructure operator-(const _3DStructure& v) { return _3DStructure(-v.x, -v.y, -v.z); } _3DStructure operator*(const _3DStructure& v, float l) { return _3DStructure(v.x*l, v.y*l, v.z*l); } _3DStructure operator*(float l, const _3DStructure & v) { return _3DStructure(v.x*l, v.y*l, v.z*l); } _3DStructure operator/(const _3DStructure& v, float l) { return _3DStructure(v.x / l, v.y / l, v.z / l); } //点乘 float operator^(const _3DStructure& v1, const _3DStructure& v2) { return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z; } //叉乘 _3DStructure operator*(const _3DStructure& v1, const _3DStructure& v2) { return _3DStructure(v1.y*v2.z - v1.z*v2.y, v1.z*v2.x - v1.x*v2.z, v1.x*v2.y - v1.y*v2.x); } #endif
[ "41496394+Gchenyu@users.noreply.github.com" ]
41496394+Gchenyu@users.noreply.github.com
e09b12f37fb2e476acc9582eb74e525f6831f328
15a5465e10831bbad713827d08eec2f34dd272c3
/source/Objeto.cpp
b986dd7f9374b2fcd28c4bccc21ae27205133b54
[ "MIT" ]
permissive
JoaoPedroAssis/Jankenpo
7e1b5d67580795df46d1ee30edc6612bbfd2fc41
86e35dbb7d48c3015abe4efcebd3009aa482d0e1
refs/heads/master
2020-04-11T16:10:51.053933
2018-12-15T21:42:24
2018-12-15T21:42:24
161,914,055
0
0
null
null
null
null
UTF-8
C++
false
false
957
cpp
// Copyright 2018 João Pedro Assis #include "../include/Objeto.h" Objeto::Objeto(int X, int Y) { srcRect = new SDL_Rect; destRect = new SDL_Rect; pos_X = X; pos_Y = Y; srcRect->x = 0; srcRect->y = 0; } int Objeto::get_x() { return pos_X; } int Objeto::get_y() { return pos_Y; } void Objeto::set_x(int X) { pos_X = destRect->x = X; } void Objeto::set_y(int Y) { pos_Y = destRect->y = Y; } void Objeto::render(SDL_Renderer* r) { SDL_RenderCopy(r, this->textura, srcRect, destRect); } void Objeto::mudaTextura(SDL_Texture* textura) { this->textura = textura; } void Objeto::setSrcRect(int x, int y, int w, int h) { srcRect->x = x; srcRect->y = y; srcRect->w = w; srcRect->h = h; } void Objeto::setDestRect(int x, int y, int w, int h) { destRect->x = x; destRect->y = y; destRect->w = w; destRect->h = h; } Objeto::~Objeto() { delete srcRect; delete destRect; }
[ "joapedroassisdossantos@gmail.com" ]
joapedroassisdossantos@gmail.com
a9f9b37592c25a0e26443e7861fe6dd560eec9e2
d7dcdff7a24b8600066626c77cf0eebdc0b45f1f
/src/SpeechStuff.cpp
a62c45adafc3f5256a3a35aceb5b1c2af8d94db7
[ "MIT" ]
permissive
rethesda/playerTextToSpeechSSE
ff709af82fe2401f95403865b473cb348853b93a
3e546882f15a545ab14f400748746ed8956ca788
refs/heads/master
2023-08-04T12:21:59.753233
2021-09-14T21:30:52
2021-09-14T21:30:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,098
cpp
// // Created by peter on 7/27/21. // std::vector<ISpObjectToken*> gVoices; ISpVoice* gVoice = nullptr; // Default settings - should match those in Papyrus bool gModEnabled = true; uint32_t gPlayerVoiceID = 0; uint32_t gPlayerVoiceVolume = 50; int32_t gPlayerVoiceRateAdjust = 0; /************************* ** Player speech state ** **************************/ enum PlayerSpeechState { TOPIC_NOT_SELECTED = 0, TOPIC_SELECTED = 1, TOPIC_SPOKEN = 2 }; struct PlayerSpeech { PlayerSpeechState state; bool isNPCSpeechDelayed; uint32_t option; }; PlayerSpeech* gPlayerSpeech = nullptr; void initializePlayerSpeech() { if (gPlayerSpeech == nullptr) { gPlayerSpeech = new PlayerSpeech(); gPlayerSpeech->state = TOPIC_NOT_SELECTED; gPlayerSpeech->isNPCSpeechDelayed = false; } } /*************************************************** ** Event handling for when TTS finished speaking ** ****************************************************/ void TopicSpokenEventDelegateFn() { //uint32_t setTopic = 0x006740E0; //uint32_t sayTopicResponse = 0x006741B0; if (gPlayerSpeech->state == TOPIC_SELECTED) { gPlayerSpeech->state = TOPIC_SPOKEN; gPlayerSpeech->isNPCSpeechDelayed = false; // Here's the fun part: once TTS stopped speaking, we have to set the topic again, // then speak it. It's already done on the first click event, but we're ignoring it // with our onDialogueSayHook to allow TTS to speak. //RE::MenuTopicManager* mtm = RE::MenuTopicManager::GetSingleton(); //thisCall<void>(mtm, setTopic, gPlayerSpeech->option); //thisCall<void>(mtm, sayTopicResponse, 0, 0); } } void executeVoiceNotifyThread() { CSpEvent evt; HANDLE voiceNotifyHandle = gVoice->GetNotifyEventHandle(); do { WaitForSingleObject(voiceNotifyHandle, INFINITE); while (gVoice != nullptr && evt.GetFrom(gVoice) == S_OK) { if (evt.eEventId == SPEI_END_INPUT_STREAM) { SKSE::GetTaskInterface()->AddTask(TopicSpokenEventDelegateFn); } } } while (gVoice != nullptr); } /******************************************** ** Initializing voices and setting up TTS ** *********************************************/ std::vector<ISpObjectToken*> getVoices() { std::vector<ISpObjectToken*> voiceObjects; ULONG voiceCount = 0; ISpObjectToken* voiceObject; IEnumSpObjectTokens* enumVoiceObjects; SpEnumTokens(SPCAT_VOICES, nullptr, nullptr, &enumVoiceObjects); enumVoiceObjects->GetCount(&voiceCount); HRESULT hr = S_OK; ULONG i = 0; while (SUCCEEDED(hr) && i < voiceCount) { hr = enumVoiceObjects->Item(i, &voiceObject); voiceObjects.push_back(voiceObject); i++; } enumVoiceObjects->Release(); return voiceObjects; } ULONG getVoicesCount() { ULONG voiceCount = 0; IEnumSpObjectTokens* enumVoiceObjects; SpEnumTokens(SPCAT_VOICES, nullptr, nullptr, &enumVoiceObjects); enumVoiceObjects->GetCount(&voiceCount); enumVoiceObjects->Release(); return voiceCount; } void initializeVoices() { if (gVoice == nullptr) { gVoices = getVoices(); if (FAILED(CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED))) { //_MESSAGE("Problem: CoInitializeEx failed"); logger::error<>("Problem: CoCreateInstance failed"); } else if (FAILED(CoCreateInstance(CLSID_SpVoice, nullptr, CLSCTX_ALL, IID_ISpVoice, (void **)&gVoice))) { //_MESSAGE("Problem: CoCreateInstance failed"); logger::error<>("Problem: CoCreateInstance failed"); } CoUninitialize(); ULONGLONG eventTypes = SPFEI(SPEI_END_INPUT_STREAM); if (FAILED(gVoice->SetInterest(eventTypes, eventTypes))) { //_MESSAGE("Problem: SetInterest failed"); logger::error<>("Problem: SetInterest failed"); } CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)executeVoiceNotifyThread, nullptr, NULL, nullptr); } } void speak(const char* message) { auto masterVolumeSetting = RE::TESForm::LookupByID<RE::BGSSoundCategory>(0x000EB803)->GetCategoryVolume(); auto voiceVolumeSetting = RE::TESForm::LookupByID<RE::BGSSoundCategory>(0x000876BD)->GetCategoryVolume(); initializeVoices(); std::wstringstream messageStream; messageStream << message; // Volume is set every time because master / voice volume might have changed gVoice->SetVolume((u_short)round((float)gPlayerVoiceVolume * static_cast<float>(masterVolumeSetting) * (voiceVolumeSetting))); gVoice->Speak(messageStream.str().c_str(), SPF_ASYNC | SPF_IS_NOT_XML | SPF_PURGEBEFORESPEAK, nullptr); } void stopSpeaking() { gVoice->Speak(L"", SPF_ASYNC | SPF_IS_NOT_XML | SPF_PURGEBEFORESPEAK, nullptr); } /********************* ** ON TOPIC SETTER ** **********************/ //x86 //BYTE* gOnTopicSetter = (BYTE*)0x00674113; //x64 //uintptr_t gOnTopicSetter = 0x014056F910; uintptr_t gOnTopicSetter; uintptr_t gOnTopicSetterResume; uintptr_t* gOnTopicSetterResumePtr = &gOnTopicSetterResume; struct ObjectWithMessage { const char* message; }; struct ObjectWithObjectWithMessage { ObjectWithMessage* object; }; void onTopicSetterHook(RE::MenuTopicManager* object, uint32_t option) { if (!gModEnabled) { return; } initializePlayerSpeech(); if (gPlayerSpeech->state == TOPIC_NOT_SELECTED || gPlayerSpeech->state == TOPIC_SPOKEN) { gPlayerSpeech->state = TOPIC_SELECTED; gPlayerSpeech->isNPCSpeechDelayed = false; gPlayerSpeech->option = option; speak(object->lastSelectedDialogue->topicText.c_str()); } } //__declspec(naked) void onTopicSetterHooked() { // __asm { // push edx // mov edx, [esp+0xC] // The selected option is an argument to the function, and is still on the stack there // pushad // push edx // push esi // `esi` register here contains a pointer to an object, containing // // a pointer to another object with a pointer to the string of a chosen topic // // (I didn't bother to figure out what this object is) // call onTopicSetterHook // popad // pop edx // jmp[gOnTopicSetterResume] // } //} struct onTopicSetterHookedPatch : Xbyak::CodeGenerator { explicit onTopicSetterHookedPatch(uintptr_t SetterHook,uintptr_t ResumePtr) { mov(rbx, ptr [rsp+0x98]); //mov(edx,ptr [esp+0xC]); //pushad(); //push(edx); //push(esi); push(rcx); mov(rcx, rsi); push(rax); mov(rax, SetterHook); call(rax); pop(rax); pop(rcx); //popad(); //pop(edx); mov(r15, ResumePtr); mov(r15, ptr[r15]); jmp(r15); } }; /*********************** ** DIALOGUE SAY HOOK ** ************************/ uintptr_t gOnDialogueSay; uintptr_t gOnDialogueSayResume; uintptr_t gOnDialogueSaySkip; uintptr_t* gOnDialogueSayResumePtr = &gOnDialogueSayResume; bool shouldDelayNPCSpeech() { if (!gModEnabled) { return false; } initializePlayerSpeech(); // This is for when the user wants to skip the convo by (usually vigorously) clicking if (gPlayerSpeech->state == TOPIC_SELECTED && gPlayerSpeech->isNPCSpeechDelayed) { gPlayerSpeech->state = TOPIC_NOT_SELECTED; gPlayerSpeech->isNPCSpeechDelayed = false; stopSpeaking(); } else if (gPlayerSpeech->state == TOPIC_SELECTED) { gPlayerSpeech->isNPCSpeechDelayed = true; return true; } return false; } struct onDialogueSayHookedPatch : Xbyak::CodeGenerator { explicit onDialogueSayHookedPatch(uintptr_t DelayTest,uintptr_t ResumePtr,uintptr_t SaySkip) { Xbyak::Label DELAY_NPC_SPEECH; //pushad(); mov(ptr [rsp+0x20], ecx); mov(rcx, rbx); push(rcx); mov(rcx,DelayTest); call(rcx); pop(rcx); test(al,al); jnz(DELAY_NPC_SPEECH); //popad(); mov(rax, ResumePtr); mov(rax, ptr[rax]); jmp(rax); L(DELAY_NPC_SPEECH); mov(r8, SaySkip); jmp(r8); //popad(); } }; //__declspec(naked) void onDialogueSayHooked() { // __asm { // pushad // call shouldDelayNPCSpeech // test al, al // jnz DELAY_NPC_SPEECH // If we should delay NPC speech, go to some code after // popad // jmp[gOnDialogueSayResume] // // DELAY_NPC_SPEECH: // popad // jmp[gOnDialogueSaySkip] // } //} /********************************************** ** Registered functions and their delegates ** **********************************************/ void SetVoiceFn() { initializeVoices(); gVoice->SetVoice(gVoices[gPlayerVoiceID]); } void SetRateAdjustFn() { initializeVoices(); gVoice->SetRate(gPlayerVoiceRateAdjust); } std::string getAvailableTTSVoices(RE::StaticFunctionTag*) { std::vector<ISpObjectToken*> voices = getVoices(); // We can't just use `gVoices` because it's on another thread std::vector<std::string> vmVoiceList; WCHAR* szDesc{}; const char* szDescString; size_t size = voices.size(); vmVoiceList.resize(size); for (size_t i = 0; i < size; i++) { SpGetDescription(voices[i], &szDesc); _bstr_t szDescCommon(szDesc); szDescString = szDescCommon; vmVoiceList[i] = std::string(szDescString); voices[i]->Release(); } voices.clear(); auto joinedParts = boost::algorithm::join(vmVoiceList, "::"); return joinedParts; } uint32_t setModEnabled(RE::StaticFunctionTag*, bool modEnabled) { gModEnabled = modEnabled; return 1; // Pretty sure it'll be successful } int32_t setTTSPlayerVoiceID(RE::StaticFunctionTag*, int32_t id) { int32_t isSuccessful = 1; if (static_cast<uint32_t>(id) >= getVoicesCount()) { id = 0; isSuccessful = 0; } gPlayerVoiceID = id; SKSE::GetTaskInterface()->AddTask(SetVoiceFn); return isSuccessful; } int32_t setTTSPlayerVoiceVolume(RE::StaticFunctionTag*, int32_t volume) { int32_t isSuccessful = 1; if (volume > 100 || volume < 0) { volume = 50; isSuccessful = 0; } gPlayerVoiceVolume = volume; return isSuccessful; } int32_t setTTSPlayerVoiceRateAdjust(RE::StaticFunctionTag*, int32_t rateAdjust) { int32_t isSuccessful = 1; if (rateAdjust < -10 || rateAdjust > 10) { rateAdjust = 0; isSuccessful = 0; } gPlayerVoiceRateAdjust = rateAdjust; SKSE::GetTaskInterface()->AddTask(SetRateAdjustFn); return isSuccessful; } bool registerFuncs(RE::BSScript::Internal::VirtualMachine* a_registry) { a_registry->RegisterFunction("GetAvailableTTSVoices", "TTS_Voiced_Player_Dialogue_MCM_Script", getAvailableTTSVoices); a_registry->RegisterFunction("SetTTSModEnabled", "TTS_Voiced_Player_Dialogue_MCM_Script", setModEnabled); a_registry->RegisterFunction("SetTTSPlayerVoiceID", "TTS_Voiced_Player_Dialogue_MCM_Script", setTTSPlayerVoiceID); a_registry->RegisterFunction("SetTTSPlayerVoiceVolume", "TTS_Voiced_Player_Dialogue_MCM_Script", setTTSPlayerVoiceVolume); a_registry->RegisterFunction("SetTTSPlayerVoiceRateAdjust", "TTS_Voiced_Player_Dialogue_MCM_Script", setTTSPlayerVoiceRateAdjust); return true; } /******************** ** Initialization ** *********************/ bool InnerPluginLoad() { //x86 //BYTE* gOnDialogueSaySkip = (BYTE*)0x006D39C4; //x64 //uintptr_t gOnDialogueSaySkip = 0x01405E83D8; //file offset 0x005E77D8 //RVA seems to be 0x5E83D8 gOnDialogueSaySkip = REL::Offset(0x5E83D1).address(); //x86 //BYTE* gOnDialogueSay = (BYTE*)0x006D397E; //comparison https://i.imgur.com/i2exbOy.png //X64 //uintptr_t gOnDialogueSay = 0x01405E837F; gOnDialogueSay = REL::Offset(0x5E83C5).address(); gOnDialogueSayResume = REL::Offset(0x5E83C9).address(); //x86 //BYTE* gOnTopicSetter = (BYTE*)0x00674113; //x64 //uintptr_t gOnTopicSetter = 0x014056F910; //comparison https://i.imgur.com/4ZAN0aU.png //file offset 0x0056ED10 //RVA seems to be 0x56F910 gOnTopicSetter = REL::Offset(0x56F910).address(); gOnTopicSetterResume = REL::Offset(0x56F918).address(); // These set up injection points to the game: auto& trampoline = SKSE::GetTrampoline(); onTopicSetterHookedPatch Tsh{ reinterpret_cast<uintptr_t>(onTopicSetterHook), reinterpret_cast<uintptr_t>(gOnTopicSetterResumePtr) }; onDialogueSayHookedPatch Dsh{ reinterpret_cast<uintptr_t>(shouldDelayNPCSpeech), reinterpret_cast<uintptr_t>(gOnDialogueSayResumePtr), gOnDialogueSaySkip }; const auto onTopicSetterHooked = trampoline.allocate(Tsh); const auto onDialogueSayHooked = trampoline.allocate(Dsh); // 1. When the topic is clicked, we'd like to remember the selected // option (so that we can trigger same option choice later) and actually speak the TTS message //gOnTopicSetterResume = detourWithTrampoline(gOnTopicSetter, (BYTE*)onTopicSetterHooked, 5); REL::safe_fill(gOnTopicSetter, 0x90, 8); trampoline.write_branch<5>(gOnTopicSetter,onTopicSetterHooked); // 2. When the NPC is about to speak, we'd like prevent them initially, but still allow other dialogue events. // We also check there, well, if user clicks during a convo to try to skip it, we'll also stop the TTS speaking. //gOnDialogueSayResume = detourWithTrampoline(gOnDialogueSay, (BYTE*)onDialogueSayHooked, 6); //REL::safe_fill(gOnDialogueSay, 0x90, 7); //trampoline.write_branch<5>(gOnDialogueSay,onDialogueSayHooked); //if (!g_papyrusInterface) { // _MESSAGE("Problem: g_papyrusInterface is false"); // return false; // } auto papyrus = SKSE::GetPapyrusInterface(); if (!papyrus->Register(registerFuncs)) { return false; } //g_taskInterface = static_cast<SKSETaskInterface*>(skse->QueryInterface(kInterface_Task)); //if (!g_taskInterface) { // _MESSAGE("Problem: task registration failed"); // return false; // } logger::info<>("TTS Voiced Player Dialogue loaded"); return true; }
[ "peterpan0413@live.com" ]
peterpan0413@live.com
b614a3816b71b2872a3b16eaaa5a932ad1a597b9
f68c1a09ade5d969f3973246747466e4a540ff74
/src/prod/src/Management/DnsService/include/INetIoManager.h
e8405887b0c630b30ec42f667dabdfbf74caf268
[ "MIT" ]
permissive
GitTorre/service-fabric
ab38752d4cc7c8f2ee03553372c0f3e05911ff67
88da19dc5ea8edfe1c9abebe25a5c5079995db63
refs/heads/master
2021-04-09T10:57:45.678751
2018-08-20T19:17:28
2018-08-20T19:17:28
125,401,516
0
0
MIT
2018-03-15T17:13:53
2018-03-15T17:13:52
null
UTF-8
C++
false
false
3,576
h
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #pragma once #include "IDnsTracer.h" namespace DNS { #if defined(PLATFORM_UNIX) #define WSA_IO_PENDING (ERROR_IO_PENDING) #define WSA_OPERATION_ABORTED (WSAEINTR) #endif typedef KDelegate<void(__in NTSTATUS)> UdpListenerCallback; typedef KDelegate<void(__in NTSTATUS, __in KBuffer&, __in ULONG)> UdpReadOpCompletedCallback; typedef KDelegate<void(__in NTSTATUS, __in ULONG)> UdpWriteOpCompletedCallback; interface ISocketAddress { K_SHARED_INTERFACE(ISocketAddress); public: virtual PVOID Address() = 0; virtual socklen_t Size() const = 0; virtual socklen_t* SizePtr() = 0; }; void CreateSocketAddress( __out ISocketAddress::SPtr& spAddress, __in KAllocator& allocator ); void CreateSocketAddress( __out ISocketAddress::SPtr& spAddress, __in KAllocator& allocator, __in ULONG address, __in USHORT port ); interface IUdpListener { K_SHARED_INTERFACE(IUdpListener); public: virtual bool StartListener( __in_opt KAsyncContextBase* const parent, __inout USHORT& port, __in UdpListenerCallback completionCallback ) = 0; virtual bool CloseAsync( ) = 0; virtual void ReadAsync( __out KBuffer& buffer, __out ISocketAddress& addressFrom, __in UdpReadOpCompletedCallback readCallback, __in ULONG timeoutInMs ) = 0; virtual void WriteAsync( __in KBuffer& buffer, __in ULONG numberOfBytesToWrite, __in ISocketAddress& addressTo, __in UdpWriteOpCompletedCallback writeCallback ) = 0; }; interface IUdpAsyncOp { K_SHARED_INTERFACE(IUdpAsyncOp); public: virtual void IOCP_Completion( __in ULONG status, __in ULONG bytesTransferred ) = 0; virtual KBuffer::SPtr GetBuffer() = 0; virtual ULONG GetBufferDataLength() = 0; virtual ISocketAddress::SPtr GetAddress() = 0; }; interface INetIoManager { K_SHARED_INTERFACE(INetIoManager); public: virtual void StartManager( __in_opt KAsyncContextBase* const parent ) = 0; virtual void CloseAsync() = 0; virtual void CreateUdpListener( __out IUdpListener::SPtr& spListener ) = 0; #if defined(PLATFORM_UNIX) virtual bool RegisterSocket( __in SOCKET socket ) = 0; virtual void UnregisterSocket( __in SOCKET socket ) = 0; virtual int ReadAsync( __in SOCKET socket, __in IUdpAsyncOp& overlapOp, __out ULONG& bytesRead ) = 0; virtual int WriteAsync( __in SOCKET socket, __in KBuffer& buffer, __in ULONG count, __in ISocketAddress& address, __in IUdpAsyncOp& overlapOp, __out ULONG& bytesWritten ) = 0; #endif }; void CreateNetIoManager( __out INetIoManager::SPtr& spManager, __in KAllocator& allocator, __in const IDnsTracer::SPtr& spTracer, __in ULONG numberOfConcurrentQueries ); }
[ "noreply-sfteam@microsoft.com" ]
noreply-sfteam@microsoft.com
d7698fc8fbf51d7438c44271fb1e909fe1fe2b54
1e229c70a50309e6082abe7266eb53d6021d6433
/include/shiokaze/array/macarray_extrapolator3.h
0a27c75198b95d3f854720a0162da74d988d67e6
[]
no_license
ryichando/shiokaze
e3d8a688c25a5aabb4eac6576bcc4510436d181d
62e25b38882a1676c4a84181aa8eedaf716a0d0e
refs/heads/master
2022-06-21T04:10:44.898687
2022-06-13T11:04:55
2022-06-13T11:04:55
149,598,476
57
5
null
null
null
null
UTF-8
C++
false
false
2,076
h
/* ** macarray_extrapolator3.h ** ** This is part of Shiokaze, a research-oriented fluid solver for computer graphics. ** Created by Ryoichi Ando <rand@nii.ac.jp> on Feb 14, 2018. ** ** 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. */ // #ifndef SHKZ_MACARRAY_EXTRAPOLATOR3_H #define SHKZ_MACARRAY_EXTRAPOLATOR3_H // #include "array_extrapolator3.h" // SHKZ_BEGIN_NAMESPACE // /** @file */ /// \~english @brief Namespace that implements MAC array extrapolation. /// \~japanese @brief MAC グリッドの外挿を実装する名前空間。 namespace macarray_extrapolator3 { /** \~english @brief Extrapolate MAC array. @param[in] array Grid to extrapolate. @param[in] width Extrapolation count. \~japanese @brief MAC グリッドを外挿する。 @param[in] array 外挿を行うグリッド。 @param[in] width 外挿する回数。 */ template<class T> void extrapolate ( macarray3<T> &array, int width ) { for( int dim : DIMS3 ) { array_extrapolator3::extrapolate<T>(array[dim],width); } }; }; // SHKZ_END_NAMESPACE // #endif //
[ "rand@nii.ac.jp" ]
rand@nii.ac.jp
68108298350fd665dffb7fab6b7c6e9a8460bfc0
97e02ecd270f47176ef8b6c5b89cfa9dd335d2a1
/华东师范大学oj/3161. 位运算.cpp
36d341b96c8f435e82fd6e5ec7d2a56f766af15a
[]
no_license
TechAoba/OJ-code
61f06ce7a94cadd501457853da2f3c4932bb226e
7e91b734bae170c4a7415984d4760740f677a26f
refs/heads/main
2023-07-08T23:49:10.258066
2021-08-17T11:47:26
2021-08-17T11:47:26
300,805,551
0
0
null
null
null
null
UTF-8
C++
false
false
426
cpp
#include<iostream> #include<cstdio> #include<cstring> using namespace std; unsigned int a; int p, len, st, en, A[32]; inline bool in(int a) { if(a>=st && a<=en) return 1; return 0; } int main() { cin>>a>>p>>len; st = p-len+1, en=p; unsigned int ans=0, quan=1, i; for(i=0;i<32;i++) { if(a&1) A[i] = 1; if(in(i)) A[i] = 1-A[i]; if(A[i]) ans += quan; quan *= 2; a >>= 1; } printf("%u\n", ans); return 0; }
[ "Techaoba@163.com" ]
Techaoba@163.com
b7ad2199f6495064c887bbcb320d0dd2c879c8e3
1d7bea41cf1982b6d5909385cb7ef19e0a7b5aaa
/code/pixel_parser.cpp
0333035a41cfb8bae1877972d2a869ffccf3f2ed
[ "MIT" ]
permissive
DonutLaser/laser-pixel
d7be88656c0f851b1a37b9ef14e05d34019ced8d
3f7762c8a748b50fe218b9763972d46795047738
refs/heads/master
2020-04-18T19:42:28.568008
2019-02-24T14:08:18
2019-02-24T14:08:18
167,718,727
0
0
null
null
null
null
UTF-8
C++
false
false
2,743
cpp
#include "pixel_parser.h" #include "../third_party/gui_string_buffer.h" #include "../third_party/gui_utility.h" #define SYMBOL_LEFT_BRACKET '[' #define SYMBOL_RIGHT_BRACKET ']' #define SYMBOL_FRAME_END '-' static bool is_whitespace (char c) { return c == '\n' || c == '\t' || c == '\r' || c == ' '; } static void skip_whitespace (char** text) { while (is_whitespace (**text)) ++(*text); } static token get_next_token (char** text) { skip_whitespace (text); bool is_color_value = false; unsigned count = 0; token result = { }; result.type = TT_COUNT; char* value_start = *text; while (!is_whitespace (**text)) { if (**text == SYMBOL_LEFT_BRACKET || **text == SYMBOL_RIGHT_BRACKET) result.type = TT_COLOR; else if (**text == SYMBOL_FRAME_END) result.type = TT_FRAME_END; ++count; ++(*text); } str_copy (value_start, result.value, 0, count); result.value[count] = '\0'; return result; } static int parse_number (char* value) { return utility_is_integer (value) ? utility_string_to_int (value) : 0; } static void parse_color (char* value, int* color, unsigned* amount) { unsigned count = 0; char* value_start = value; while (*value != '\0') { if (*value == SYMBOL_LEFT_BRACKET) { char color_value[MAX_TOKEN_LENGTH]; str_copy (value_start, color_value, 0, count); color_value[count] = '\0'; *color = parse_number (color_value); count = 0; ++value; value_start = value; continue; } else if (*value == SYMBOL_RIGHT_BRACKET) { char amount_value[MAX_TOKEN_LENGTH]; str_copy (value_start, amount_value, 0, count); amount_value[count] = '\0'; *amount = (unsigned)parse_number (amount_value); } ++count; ++value; } } ppp parse_ppp (char* text) { ppp result = { }; unsigned start_x = 0; unsigned start_y = 0; unsigned frame = 0; token t = { }; do { t = get_next_token (&text); unsigned amount = 0; int color = -1; if (t.type == TT_COUNT) result.frame_count = (unsigned)parse_number (t.value); else if (t.type == TT_COLOR) { if (amount == 0) { color = -1; amount = 0; parse_color (t.value, &color, &amount); } for (unsigned y = start_y; y < GRID_TILE_COUNT_Y; ++y) { for (unsigned x = start_x; x < GRID_TILE_COUNT_X; ++x) { result.frames[frame].grid[y][x] = color; --amount; if (amount == 0) { if (x < GRID_TILE_COUNT_X - 1) { start_x = x + 1; start_y = y; } else { start_x = 0; start_y = y + 1; } break; } } if (amount == 0) break; else start_x = 0; } } else if (t.type == TT_FRAME_END) { ++frame; start_x = 0; start_y = 0; } } while (frame != result.frame_count); return result; }
[ "vidmantas.luneckas@gmail.com" ]
vidmantas.luneckas@gmail.com
9d6686a69eec2779c31a476217e8f0bbc3558446
a71e120698165b95c6c3f4cdb9b8ec1e5e118170
/Validation/VstQuaeroUtils/src/Refine.cc
2c0841102de90517e7740c98aed9323585c9fbee
[]
no_license
peiffer/usercode
173d69b64e2a4f7082c9009f84336aa7c45f32c5
7558c340d4cda8ec5a5b00aabcf94d5b3591e178
refs/heads/master
2021-01-14T14:27:32.667867
2016-09-06T13:59:05
2016-09-06T13:59:05
57,212,842
0
0
null
2016-04-27T12:47:54
2016-04-27T12:47:54
null
UTF-8
C++
false
false
65,595
cc
/******************************************* Implements Refine, a class that "refines" a sample of events, cutting away events outside the boundaries we are able to analyze. ********************************************/ #include "Validation/VstQuaeroUtils/interface/Refine.hh" #include <string> #include <cfloat> using namespace std; /* Constructor. Arguments include which collider (tev1, tev2, lep2, hera, or lhc) and which experiment (aleph, l3, cdf, d0, h1, or cms) Refine should assume. int _level specifies the level of refinement, with higher levels implementing more refinement. HintSpec is passed in as an argument if this refinement restricts itself to a subsample in which a hint (of new physics) is observed. */ Refine::Refine(string _collider, string _experiment, string partitionRuleName, int _level, HintSpec _hintSpec): collider(_collider), experiment(_experiment), partitionRule((partitionRuleName=="" ? _collider+"-Vista" : partitionRuleName)), level(_level), hintSpec(_hintSpec) { // Ensure _collider and _experiment are understood assert( ((collider=="tev1")&& ((experiment=="d0"))) || ((collider=="tev2")&& ((experiment=="cdf")||(experiment=="d0"))) || ((collider=="lhc")&& ((experiment=="cms")||(experiment=="atlas"))) || ((collider=="lep2")&& ((experiment=="aleph")||(experiment=="l3"))) || ((collider=="hera")&& ((experiment=="h1"))) ); minWt = 0; return; } bool Refine::satisfiesCriteriaQ(QuaeroEvent& e) { vector<QuaeroRecoObject> o = e.getObjects(); double wt = e.getWeight(); bool debug = false; // if((e.getEventType()=="sig")&&(wt>10)) wt = 10; double zvtx = e.getZVtx(); double sumPt = 0; for(size_t i=0; i<o.size(); i++) sumPt += o[i].getFourVector().perp(); sumPt += e.getPmiss().perp(); string fs = partitionRule.getFinalState(e).getTextString(); bool ans = true; /************************************************* LEP II **************************************************/ if((collider=="lep2")&& ((experiment=="l3")||(experiment=="aleph"))) { if(experiment=="aleph") { for(size_t i=0; i<o.size(); i++) if((o[i].getObjectTypeSansSign()=="e")|| (o[i].getObjectTypeSansSign()=="mu")|| (o[i].getObjectTypeSansSign()=="tau")|| (o[i].getObjectTypeSansSign()=="ph")) for(size_t j=0; j<o.size(); j++) if(o[j].getObjectType()=="ph") if(i!=j) if((Math::deltaphi(o[i].getFourVector().phi(),o[j].getFourVector().phi())<3./180*M_PI)&& (fabs(o[i].getFourVector().theta()-o[j].getFourVector().theta())<3./180*M_PI)) { o[i] = QuaeroRecoObject(o[i].getObjectType(), o[i].getFourVector()+o[j].getFourVector()); o.erase(o.begin()+j); break; } } // Cluster at a larger scale int k1=0,k2=0; while((k1>=0)&&(k2>=0)) { k1=k2=-1; double y_cut = 0.01; double yij_min = y_cut; for(size_t i=0; i<o.size(); i++) if((o[i].getObjectType()=="j") || (o[i].getObjectType()=="b") || (o[i].getObjectTypeSansSign()=="tau")) for(size_t j=i+1; j<o.size(); j++) if((o[j].getObjectType()=="j") || (o[j].getObjectType()=="b") || (o[i].getObjectTypeSansSign()=="tau")) { double yij = pow((o[i].getFourVector()+o[j].getFourVector()).m()/e.getRootS(),2.); if(yij < yij_min) { yij_min = yij; k1=i; k2=j; } } if((k1>=0)&&(k2>=0)) { o[k1] = QuaeroRecoObject("j",o[k1].getFourVector()+o[k2].getFourVector()); o.erase(o.begin()+k2); } } // e = QuaeroEvent(e.getEventType(), e.getRunNumber(), e.getWeight(), o, e.getRootS(), e.getZVtx()); e.setObjects(o); fs = partitionRule.getFinalState(e).getTextString(); bool nothingInterestingInEvent = ((e.numberOfObjects(25,0.7)==0) || (fs=="1pmiss") || ((e.numberOfObjects(25,0.7)==1)&&(e.numberOfObjects("uncl",25,0.7)==1)) ); bool eventContainsFarForwardObject = false; for(size_t i=0; i<o.size(); i++) if((fabs(cos(o[i].getFourVector().theta()))>0.9)&& (o[i].getFourVector().e()>10)) eventContainsFarForwardObject = true; if(experiment=="l3") { // In events with two like-sign electrons, make them opposite sign if( (e.numberOfObjects("e+")==2) ) for(size_t i=0; i<o.size(); i++) if(o[i].getObjectType()=="e+") { o[i].chargeConjugate(); break; } if( (e.numberOfObjects("e-")==2) ) for(size_t i=0; i<o.size(); i++) if(o[i].getObjectType()=="e-") { o[i].chargeConjugate(); break; } /* // Massage electron energy of Monte Carlo if(e.getEventType()!="data") { for(size_t i=0; i<o.size(); i++) if((o[i].getObjectTypeSansSign()=="e")&&(o[i].getFourVector().e()>20)) { double E = o[i].getFourVector().e(); double q = ( E - (E>20)*1.0*(E -20)/((e.getRootS()-10)-20) - (E>e.getRootS()-10)*(E-(e.getRootS()-10))*3.5/10 - (E>e.getRootS())*(E-e.getRootS())/2 ) / o[i].getFourVector().e(); o[i] = QuaeroRecoObject(o[i].getObjectType(),o[i].getFourVector()*q); } } for(int i=0; i<o.size(); i++) { if((o[i].getObjectTypeSansSign()=="e")&& (fabs(cos(o[i].getFourVector().theta()))>0.65)) o[i].changeComponentType("ph"); } e.setObjects(o); if((e.numberOfObjects("e+")==1)&& (e.numberOfObjects("ph")==1)) for(size_t i=0; i<o.size(); i++) if(o[i].getObjectType()=="ph") o[i].changeComponentType("e-"); if((e.numberOfObjects("e-")==1)&& (e.numberOfObjects("ph")==1)) for(size_t i=0; i<o.size(); i++) if(o[i].getObjectType()=="ph") o[i].changeComponentType("e+"); if((e.numberOfObjects("e")==0)&& (e.numberOfObjects("ph")==2)) for(size_t i=0; i<o.size(); i++) if((o[i].getObjectType()=="ph")&& (fabs(cos(o[i].getFourVector().theta()))>0.65)) o[i].changeComponentType( ((cos(o[i].getFourVector().theta())>0) ? "e-" : "e+") ); e.setObjects(o); */ bool poorlyMeasuredBackToBack = false; if((o.size()==2) && (Math::deltaphi(o[0].getFourVector().phi(),o[1].getFourVector().phi())>3.0) && (e.getPmiss().perp()>10) ) poorlyMeasuredBackToBack = true; /* if(e.numberOfObjects("e")==1) { int j=-1; for(size_t i=0; i<o.size(); i++) if(o[i].getObjectType()=="ph") if((j<0)||(o[j].getFourVector().perp()<o[i].getFourVector().perp())) j=i; if(j>=0) { if(e.numberOfObjects("e+")==1) o[j].changeComponentType("e-"); else o[j].changeComponentType("e+"); } } // The simulation does not appear to do a good job of reproducing the tracking efficiency // for electrons with |cos(theta)| > 0.6. We are removing events with an electron and with a // photon reconstructed with |cos(theta)| > 0.6. if( (e.numberOfObjects("e")==1) && (e.numberOfObjects("ph")>=1) && (fabs(cos(e.getThisObject("ph",1)->getFourVector().theta()))>0.6) ) ans = false; */ // Adjust energies if((e.getEventType()!="data")&&(level>=5)) { for(size_t i=0; i<o.size(); i++) if(o[i].getObjectType()=="j") o[i] = QuaeroRecoObject("j",o[i].getFourVector()*Math::gasdev(1,0.01)); else if(o[i].getObjectTypeSansSign()=="mu") o[i] = QuaeroRecoObject(o[i].getObjectType(),o[i].getFourVector()*Math::gasdev(1,0.05)); else if((o[i].getObjectTypeSansSign()=="e") || (o[i].getObjectType()=="ph")) o[i] = QuaeroRecoObject(o[i].getObjectType(),o[i].getFourVector()*0.99); } // Slightly smear azimuthal angle of Monte Carlo events if((e.getEventType()!="data")&&(level>=5)) for(size_t i=0; i<o.size(); i++) { CLHEP::HepLorentzVector p = o[i].getFourVector(); double pt = p.perp(); double phi = p.phi()+Math::gasdev(0,0.005); p = CLHEP::HepLorentzVector(p.e(), CLHEP::Hep3Vector(pt*cos(phi),pt*sin(phi),p.pz())); o[i] = QuaeroRecoObject(o[i].getObjectType(),p); } e.setObjects(o); fs = partitionRule.getFinalState(e).getTextString(); bool lowEnergySingleObjectEvent = false; int i1=-1; for(size_t i=0; i<o.size(); i++) if(o[i].getFourVector().e()>10) if(i1<0) i1=i; else i1=99; if((i1>=0)&&(i1!=99)) if((o[i1].getFourVector().e()<75)|| (o[i1].getFourVector().e() > (e.getRootS()/2-10))|| (fabs(cos(o[i1].getFourVector().theta()))>0.5)) lowEnergySingleObjectEvent = true; bool forwardDoubleObjectEvent = false; i1=-1; int i2=-1; for(size_t i=0; i<o.size(); i++) if(o[i].getFourVector().e()>10) if(i1<0) i1=i; else if(i2<0) i2=i; else i1=99; if((i1>=0)&&(i2>=0)&&(i1!=99)) if((fabs(cos(o[i1].getFourVector().theta()))>0.5)|| (fabs(cos(o[i2].getFourVector().theta()))>0.5)) forwardDoubleObjectEvent = true; /* // Remove events with poorly measured electron, producing collinear missing energy if((fs=="1e+1e-1pmiss")) { double dphi = Math::deltaphi( e.getThisObject("e+")->getFourVector().phi(), e.getThisObject("e+")->getFourVector().phi() ); if(dphi>3.0) ans = false; } */ /* We see additional events in the data in the final states 1j and 1j1pmiss. From scanning events, we note that these appear to be due to events with a cosmic ray muon that brems in the hadronic calorimeter, screwing up the reconstruction of the event. The hypothesis that this excess is due to new physics is discarded by the fact that no such excess is seen in the Aleph data, where we have been able to do a more thorough job of removing cosmic ray events. We therefore remove the 1j and 1j1pmiss final states. */ /* bool disallowedFinalState = false; if( (fs=="1e+1pmiss") || (fs=="1e-1pmiss") || (fs=="1j") || (fs=="1j1pmiss") ) disallowedFinalState = true; if((fs=="1e+1j")||(fs=="1e-1j")) { for(size_t i=0; i<o.size(); i++) if(o[i].getObjectType()=="j") { if(fs=="1e+1j") o[i].changeComponentType("e-"); if(fs=="1e-1j") o[i].changeComponentType("e+"); break; } fs = "1e+1e-"; } if( (fs=="1e+1j1pmiss") || (fs=="1e-1j1pmiss") || (fs=="1j1ph1pmiss") || (fs=="1j1ph1pmiss") ) { double dphi = Math::deltaphi( e.getThisObject("j")->getFourVector().phi(), e.getPmiss().phi() ); if((dphi<0.1)||(dphi>M_PI-0.1)) ans = false; } */ double pmissPolar = fabs(cos(e.getPmiss().theta())); bool missingEnergyPointingIntoSpacCal = ((e.getPmiss().e()>15)&&(pmissPolar>0.7)&&(pmissPolar<0.75)); bool missingEnergyPointingDownBeamPipe = ((e.getPmiss().e()>15)&&(pmissPolar>0.9)); bool hasObjectFarForward = false; for(size_t i=0; i<o.size(); i++) if((fabs(cos(o[i].getFourVector().theta()))>0.9)&& (o[i].getFourVector().e()>10)) hasObjectFarForward = true; bool photonPmissEvent = false; if((fs=="1ph1pmiss")|| (fs=="2ph1pmiss")|| (fs=="3ph1pmiss")|| (fs=="4ph1pmiss")) photonPmissEvent = true; bool photonOnlyEvent = false; if((fs=="1ph")|| (fs=="2ph")|| (fs=="3ph")|| (fs=="4ph")) photonOnlyEvent = true; if( nothingInterestingInEvent || missingEnergyPointingIntoSpacCal || missingEnergyPointingDownBeamPipe || lowEnergySingleObjectEvent || forwardDoubleObjectEvent || hasObjectFarForward //photonPmissEvent || //photonOnlyEvent || //poorlyMeasuredBackToBack || //disallowedFinalState ) ans = false; } if(experiment=="aleph") { bool cosmicEvent = false; if((e.numberOfObjects("mu+",10)==1)&& (e.numberOfObjects("mu-",10)==1)) { CLHEP::HepLorentzVector mu1 = e.getThisObject("mu+",1)->getFourVector(); CLHEP::HepLorentzVector mu2 = e.getThisObject("mu-",1)->getFourVector(); // double m = (mu1+mu2).m(); if( (Math::deltaphi(mu1.phi(),mu2.phi())>3.13) ) cosmicEvent = true; } bool screwedUpReconstructionOfBremEvent = false; if((e.numberOfObjects("e+",10)==1)&& (e.numberOfObjects("e-",10)==1)&& (e.numberOfObjects("ph",10)==1)) { CLHEP::HepLorentzVector e1 = e.getThisObject("e+",1)->getFourVector(); CLHEP::HepLorentzVector e2 = e.getThisObject("e-",1)->getFourVector(); if( (Math::deltaphi(e1.phi(),e2.phi())>3.0) ) screwedUpReconstructionOfBremEvent = true; } bool conversion = false; if( (fs=="2e+") || (fs=="2e-") || (fs=="2mu+") || (fs=="2mu-") ) conversion = true; for(int i=0; i<e.numberOfObjects("e+",10); i++) for(int j=0; j<e.numberOfObjects("e-",10); j++) if( (e.getThisObject("e+",i+1)->getFourVector()+ e.getThisObject("e-",j+1)->getFourVector()).m() < 5 ) conversion = true; bool photonPmissEvent = false; if((fs=="1ph")|| // contributions from cosmic rays that we do not model ((fs=="2ph")&& // One of two different issues: ((fabs(e.getRootS()-183)<1) || // (1) Kyle and I never ran over the multiph-183 file ((e.getThisObject("ph",1)!=NULL)&& // (2) cosmic rays again (e.getThisObject("ph",2)!=NULL)&& (Math::deltaphi(e.getThisObject("ph",1)->getFourVector().phi(), e.getThisObject("ph",2)->getFourVector().phi()) < 1)) ))|| (fs=="1ph1pmiss")|| (fs=="2ph1pmiss")|| (fs=="3ph1pmiss")|| (fs=="4ph1pmiss")) photonPmissEvent = true; bool mistakenOneProngTau = false; if( (o.size()==2)&& ( (o[0].getObjectTypeSansSign()=="tau") || (o[1].getObjectTypeSansSign()=="tau") ) && ( (o[0].getObjectTypeSansSign()=="e") || (o[0].getObjectTypeSansSign()=="mu") || (o[0].getObjectTypeSansSign()=="tau") ) && ( (o[1].getObjectTypeSansSign()=="e") || (o[1].getObjectTypeSansSign()=="mu") || (o[1].getObjectTypeSansSign()=="tau") ) && ( Math::deltaphi(o[0].getFourVector().phi(),o[1].getFourVector().phi()) > 3.13 ) ) mistakenOneProngTau = true; if((fs=="1e+1j")||(fs=="1e-1j")) { for(size_t i=0; i<o.size(); i++) if(o[i].getObjectType()=="j") { if(fs=="1e+1j") o[i].changeComponentType("e-"); if(fs=="1e-1j") o[i].changeComponentType("e+"); break; } fs = "1e+1e-"; } if( nothingInterestingInEvent || eventContainsFarForwardObject || cosmicEvent || screwedUpReconstructionOfBremEvent || conversion || mistakenOneProngTau || ((level>=5) && (photonPmissEvent)) ) ans = false; } } /************************************************* HERA **************************************************/ if((collider=="hera")&& ((experiment=="h1")||(experiment=="zeus"))) { double maxEta = 2.44; // = -log(tan(10./180*M_PI/2)); double oPtMin = ((level<=1) ? 15 : 20); if(e.getEventType()=="sig") { // All e's are e+'s in the H1 General Search for(size_t i=0; i<o.size(); i++) if(o[i].getObjectType()=="e-") o[i].chargeConjugate(); // Merge any jets with deltaR < 1.0 for(size_t i=0; i<o.size(); i++) for(size_t j=i+1; j<o.size(); j++) if((o[i].getObjectType()=="j")&& (o[j].getObjectTypeSansSign()=="j")&& (Math::deltaR(o[i].getFourVector().phi(), Math::theta2eta(o[i].getFourVector().theta()), o[j].getFourVector().phi(), Math::theta2eta(o[j].getFourVector().theta())) < 1.0)) { o[i] = QuaeroRecoObject("j",o[i].getFourVector()+o[j].getFourVector()); o.erase(o.begin()+j); j--; } // Any object with 10 < theta < 140 degrees is converted to unclustered energy for(size_t i=0; i<o.size(); i++) if((o[i].getFourVector().theta()*180./M_PI < 10)|| (o[i].getFourVector().theta()*180./M_PI > 140)) o[i].changeComponentType("uncl"); e.setObjects(o); fs = partitionRule.getFinalState(e).getTextString(); // Remove events with E - pz > 75 GeV, following the H1 General Search double energy=0, pz=0; for(size_t i=0; i<o.size(); i++) { energy += o[i].getFourVector().e(); pz += fabs(o[i].getFourVector().pz()); } if(energy-pz>75) // see email from Caron to Knuteson on 2/21/2005 ans = false; if((e.getEventType()=="sig")&& (level==11)) { // KILL.qbg -- see investigateKills_summary.txt wt *= 0.99; // KILL.noz -- see investigateKills_summary.txt if((o.size()==2)&& ((o[0].getObjectType()=="ph")|| (o[1].getObjectType()=="ph"))) wt *= 0.99; // electrons are sometimes killed int z = e.numberOfObjects("e",oPtMin); if(z>=1) { if(e.numberOfObjects("j",oPtMin)==0) wt *= pow(0.80,1.*z); if(e.numberOfObjects("j",oPtMin)==1) wt *= pow(1729./2400*1.1,1.*z); if(e.numberOfObjects("j",oPtMin)==2) wt *= pow(616./947,1.*z); if(e.numberOfObjects("j",oPtMin)==3) wt *= pow(0.55,1.*z); if(e.numberOfObjects("j",oPtMin)==4) wt *= pow(0.54,1.*z); if(e.getThisObject("e+",1)!=0) { double eta = Math::theta2eta(e.getThisObject("e+",1)->getFourVector().theta()); wt *= (1-min(3.,max(-1.,eta-0.8))*0.10); if(eta>1) wt *= .5; } } // photons are sometimes killed if(e.numberOfObjects("ph",oPtMin)>=1) { if(e.numberOfObjects("j",oPtMin)==0) wt *= 0.80; if(e.numberOfObjects("j",oPtMin)==1) wt *= 16./36; if(e.numberOfObjects("j",oPtMin)>=2) wt *= 0.25; if(e.getThisObject("ph",1)!=0) wt *= (1-min(3.,max(-1.,(Math::theta2eta(e.getThisObject("ph",1)->getFourVector().theta())-1.2)))*0.20); } // muons are sometimes killed if(e.numberOfObjects("mu",oPtMin)>=1) { if(e.getThisObject("mu+",1)!=0) { double eta = Math::theta2eta(e.getThisObject("mu+",1)->getFourVector().theta()); if(eta>1) wt *= 0.5; } } } for(size_t i=0; i<o.size(); i++) if(o[i].getObjectType()=="kill") { if((o[i].getFourVector().perp()>20)&& (o[i].getFourVector().theta()*180./M_PI > 10)&& (o[i].getFourVector().theta()*180./M_PI < 140)) ans = false; else o[i].changeComponentType("uncl"); } if(e.getEventType()!="data") { // Remove events containing a photon within deltaR < 1.0 of a jet for(size_t i=0; i<o.size(); i++) for(size_t j=0; j<o.size(); j++) if((o[i].getObjectType()=="j")&& (o[j].getObjectType()=="ph")&& (Math::deltaR(o[i].getFourVector().phi(), Math::theta2eta(o[i].getFourVector().theta()), o[j].getFourVector().phi(), Math::theta2eta(o[j].getFourVector().theta())) < 1.0)) ans = false; // Remove events containing an electron within deltaR < 1.0 of a jet for(size_t i=0; i<o.size(); i++) for(size_t j=0; j<o.size(); j++) if((o[i].getObjectType()=="j")&& (o[j].getObjectTypeSansSign()=="e")&& (Math::deltaR(o[i].getFourVector().phi(), Math::theta2eta(o[i].getFourVector().theta()), o[j].getFourVector().phi(), Math::theta2eta(o[j].getFourVector().theta())) < 1.0)) ans = false; } } // Remove the 1mu+1pmiss final state // There is a large discrepancy here, hypothesized to result from a low-pT track // being misreconstructed to high-pT // Also remove other final states with only one object if( ( ( e.numberOfObjects("e",oPtMin)+ e.numberOfObjects("mu",oPtMin)+ e.numberOfObjects("ph",oPtMin)+ e.numberOfObjects("j",oPtMin,maxEta) ) < 2 ) ) ans = false; } /************************************************* Tevatron I **************************************************/ if((collider=="tev1")&& (experiment=="d0")) { for(size_t i=0; i<o.size(); i++) if((o[i].getObjectType()=="e-")|| (o[i].getObjectType()=="mu-")) // all leptons are positive at D0 Run I o[i].chargeConjugate(); for(size_t i=0; i<o.size(); i++) if(o[i].getObjectType()=="j") for(size_t j=i+1; j<o.size(); j++) if(o[j].getObjectType()=="j") if(Math::deltaR(o[i].getFourVector().phi(), Math::theta2eta(o[i].getFourVector().theta()), o[j].getFourVector().phi(), Math::theta2eta(o[j].getFourVector().theta()))<0.7) { o[i] = QuaeroRecoObject("j",o[i].getFourVector()+o[j].getFourVector()); o.erase(o.begin()+j); j--; } e.setObjects(o); fs = partitionRule.getFinalState(e).getTextString(); bool allowedFinalState = false; if( (fs=="1e+2j1pmiss")|| (fs=="1e+3j1pmiss")|| (fs=="1e+4j1pmiss")|| (fs=="1e+5j1pmiss")|| (fs=="1e+6j1pmiss")|| (fs=="2e+2j")|| (fs=="2e+3j")|| (fs=="2e+4j")|| (fs=="1e+1mu+")|| (fs=="1e+1j1mu+")|| (fs=="1e+2j1mu+")|| (fs=="1e+3j1mu+")|| (fs=="1e+1mu+1pmiss")|| (fs=="1e+1j1mu+1pmiss")|| (fs=="1e+2j1mu+1pmiss")|| (fs=="1e+3j1mu+1pmiss") ) allowedFinalState = true; bool allowedTopology = false; CLHEP::HepLorentzVector jetSum; for(size_t i=0; i<o.size(); i++) if(o[i].getObjectType()=="j") jetSum = jetSum + o[i].getFourVector(); if((e.numberOfObjects("e+",20)>=1)&& (e.getPmiss().perp()>30)&& (e.numberOfObjects("j",20)>=2)&& ((e.getThisObject("e+",1)->getFourVector()+e.getPmiss()).m()>30)&& ((e.getThisObject("e+",1)->getFourVector()+e.getPmiss()).perp()>45)&& (jetSum.perp()>45)&& (Math::deltaphi(e.getThisObject("j",1)->getFourVector().phi(),e.getPmiss().phi())>0.25)&& (Math::deltaphi(e.getThisObject("j",2)->getFourVector().phi(),e.getPmiss().phi())>0.25)) allowedTopology = true; // cuts_1e0mu0tau0ph2j0b1met if((e.numberOfObjects("e+",15)>=1)&& (e.numberOfObjects("mu+",15)>=1)) allowedTopology = true; // cuts_1e1mu0tau0ph0j0b0met if((e.numberOfObjects("e+",20)>=2)&& (e.numberOfObjects("j",20)>=2)) allowedTopology = true; if(e.getEventType()=="sig") { // These numbers come from Quaero_d0/particleIDefficiencies.txt if(e.numberOfObjects("e+")>=2) // 2e0mu0tau0ph2j0b0met wt *= 0.70; if((e.numberOfObjects("e+")==1)&& (e.numberOfObjects("mu+")==0)) // 1e0mu0tau0ph2j0b1met wt *= 0.61; if((e.numberOfObjects("e+")==1)&& (e.numberOfObjects("mu+")==1)) // 1e1mu0tau0ph0j0b0met wt *= 0.30; } if( (!allowedFinalState)|| (!allowedTopology) ) ans = false; } /************************************************* Tevatron II **************************************************/ if((collider=="tev2")&& ((experiment=="d0"))) { string eventType = e.getEventType(); if( (eventType.find("data_1pc")!=string::npos)|| (eventType.find("dataset_1pc")!=string::npos)|| (eventType.find("data_10pc")!=string::npos)|| (eventType.find("dataset_10pc")!=string::npos)|| (eventType.find("hipt-data")!=string::npos) ) eventType = "data"; e.reType(eventType); string rn = e.getRunNumber(); // Remove duplicate objects vector<string> orderedObjects; orderedObjects.push_back("e"); orderedObjects.push_back("mu"); orderedObjects.push_back("tau"); orderedObjects.push_back("ph"); orderedObjects.push_back("b"); orderedObjects.push_back("j"); for(size_t i=0; i<o.size(); i++) { vector<string>::iterator k=find(orderedObjects.begin(),orderedObjects.end(),o[i].getObjectTypeSansSign()); if(k!=orderedObjects.end()) for(size_t j=0; j<o.size(); j++) if((i!=j)&&(find(k+1,orderedObjects.end(),o[j].getObjectTypeSansSign())!=orderedObjects.end())) if(Math::deltaR(o[i].getFourVector().phi(), Math::theta2eta(o[i].getFourVector().theta()), o[j].getFourVector().phi(), Math::theta2eta(o[j].getFourVector().theta())) < 0.4) { o[j] = QuaeroRecoObject("uncl",o[j].getFourVector()); } } // Remove electrons in the ICD for(size_t i=0; i<o.size(); i++) if((o[i].getObjectTypeSansSign()=="e")) { double e_eta = Math::theta2eta(o[i].getFourVector().theta()); if((abs(e_eta)>1.1)&& (abs(e_eta)<1.5)) o[i] = QuaeroRecoObject("uncl",o[i].getFourVector()); } e.setObjects(o); fs = partitionRule.getFinalState(e).getTextString(); bool disallowedFinalState = false; if(level>=5) { if((fs=="1e+")||(fs=="1e-")|| (fs=="1mu+")||(fs=="1mu-")|| (fs=="1tau+")||(fs=="1tau-")|| (fs=="1ph")||(fs=="1ph1pmiss")|| (fs=="1j1pmiss_sumPt0-400")||(fs=="1j1pmiss_sumPt400+")|| (fs=="1j_sumPt0-400")||(fs=="1j_sumPt400+") ) disallowedFinalState = true; // cut out "runt" final states } if(level>=7) { if(eventType!="data") for(size_t i=0; i<o.size(); i++) if(o[i].getObjectTypeSansSign()=="e") if(drand48()<0.01) o[i] = QuaeroRecoObject(((string)"e")+((o[i].getSign()=="+") ? "-" : "+"),o[i].getFourVector()); } double ptThreshold0 = 10, ptThreshold01 = 15, ptThreshold1 = 20, ptThreshold12 = 25, ptThreshold2 = 35, ptThreshold3 = 50; if(level>=6) { ptThreshold0 = 17; ptThreshold01 = 20; ptThreshold1 = 25; ptThreshold12 = 30; ptThreshold2 = 40; ptThreshold3 = 60; } bool passesSingleCentralElectronTrigger = (e.numberOfObjects("e",ptThreshold1,1.0)>=1); bool passesSinglePlugElectronTrigger = (e.numberOfObjects("e",25,2.5)>=1); /* bool passesPrescaledSinglePlugElectronTrigger = ((e.numberOfObjects("e",ptThreshold12,2.5)- e.numberOfObjects("e",ptThreshold12,1.0)>=1)&& ((eventType!="data")|| ((rn.length()>1)&&(rn.substr(rn.length()-1)=="0"))) ); */ bool passesDiEmObjectTrigger = ( ( (e.numberOfObjects("e",ptThreshold1,2.5)+ e.numberOfObjects("ph",ptThreshold1,2.5)) >=2 ) && ( (e.numberOfObjects("e",ptThreshold1+5,2.5)+ e.numberOfObjects("ph",ptThreshold1+5,2.5)) >=1 ) ); /* bool passesPrescaledSingleCentralElectronTrigger = ( (e.numberOfObjects("e",ptThreshold01,1.0)>=1) && ((eventType!="data")|| ((rn.length()>1)&&(rn.substr(rn.length()-1)=="0"))) ); bool passesPrescaledSingleCentralMuonTrigger = ( (e.numberOfObjects("mu",ptThreshold01,1.0)>=1) && ((eventType!="data")|| ((rn.length()>1)&&(rn.substr(rn.length()-1)=="0"))) ); bool passesPrescaledSingleCentralPhotonTrigger = ( (e.numberOfObjects("ph",ptThreshold2,1.0)>=1) && ((eventType!="data")|| ((rn.length()>1)&&(rn.substr(rn.length()-2)=="00"))) ); */ int cem8 = e.numberOfObjects("e",ptThreshold0,1.0); int cem20 = e.numberOfObjects("e",ptThreshold01,1.0); int pem8 = e.numberOfObjects("e",ptThreshold1,2.5)-e.numberOfObjects("e",ptThreshold1,1.0); int muo8 = e.numberOfObjects("mu",ptThreshold0,1.0); int muo20 = e.numberOfObjects("mu",ptThreshold01,1.0); int trk8 = e.numberOfObjects("tau",ptThreshold0,1.0); bool passesDileptonTrigger = ( (cem8>=2) || (muo8>=2) || ((muo8>=1)&&(e.numberOfObjects("mu",ptThreshold0,2.5)>=2)) || (cem8 && pem8) || (cem8 && muo8) || (cem20 && trk8) || (pem8 && muo8) || (muo20 && trk8) ); bool passesSingleMuonTrigger = false; for(size_t i=0; i<o.size(); i++) if((o[i].getObjectTypeSansSign()=="mu")&& (o[i].getFourVector().perp()>ptThreshold1)&& (fabs(Math::theta2eta(o[i].getFourVector().theta()))<2.5)&& (Math::deltaphi(o[i].getFourVector().phi(),-M_PI/2)>0.5)) passesSingleMuonTrigger = true; // bool passesDiTauTrigger = // ( (e.numberOfObjects("tau",ptThreshold0,1.0)>=2) ); bool passesSinglePhotonTrigger = (e.numberOfObjects("ph", (level<=5 ? 55 : 60), 1.0)>=1); bool passesDiPhotonTrigger = (e.numberOfObjects("ph", ptThreshold1, 2.5)>=2); bool passesPhotonLeptonTrigger = ( ( (e.numberOfObjects("ph", ptThreshold1, 2.5)>=1) && (e.numberOfObjects("e",ptThreshold0,1.0)+ e.numberOfObjects("mu",ptThreshold0,1.0) // +e.numberOfObjects("tau",ptThreshold1,1.0) )>=1) ); // bool passesPhotonBTrigger = ( (e.numberOfObjects("ph", ptThreshold2, 1.0)>=1) && // (e.numberOfObjects("b", ptThreshold0, 1.0)>=1) ); bool passesCentralLeptonBTrigger = ( ( (e.numberOfObjects("e", ptThreshold1, 1.0)+ e.numberOfObjects("mu", ptThreshold1, 1.0)) >= 1 ) && (e.numberOfObjects("b", ptThreshold0, 1.0)>=1) ); // bool passesPlugElectronBTrigger = ( (e.numberOfObjects("e", ptThreshold1, 2.5)>=1) && // (e.numberOfObjects("b", ptThreshold1, 1.0)>=1) ); bool passesPlugElectronCentralTauTrigger = ( (e.numberOfObjects("e", ptThreshold2, 2.5)>=1) && (e.numberOfObjects("tau", ptThreshold0, 1.0)>=1) ); bool passesSingleJetTrigger = ((e.numberOfObjects("j", (level<=5 ? 150 : 200),1.0)+ e.numberOfObjects("b", (level<=5 ? 150 : 200),1.0)) >=1); bool passesSinglePlugPhotonTrigger = (e.numberOfObjects("ph", (level<=5 ? 250 : 300),2.5) >= 1 ); // bool passesPlugPhotonBTrigger = ( (e.numberOfObjects("ph", ptThreshold2, 2.5) >= 1) && // ( (e.numberOfObjects("b",ptThreshold0,1.0)>=1) ) ); bool passesCentralPhotonTauTrigger = ( (e.numberOfObjects("ph", ptThreshold2, 1.0)>=1) && (e.numberOfObjects("tau",ptThreshold2, 1.0)>=1) ); bool passesPlugPhotonTauTrigger = ( (e.numberOfObjects("ph", ptThreshold2, 2.5) >= 1) && (e.numberOfObjects("tau",ptThreshold2,1.0)>=1) ); bool passesPhoton_diTau_Trigger = ( (e.numberOfObjects("ph",ptThreshold2,2.5) >= 1) && (e.numberOfObjects("tau",ptThreshold0,1.0)>=2) ); bool passesPhoton_diB_Trigger = ( (e.numberOfObjects("ph",ptThreshold2,1.0) >= 1) && (e.numberOfObjects("b",ptThreshold1,1.0)>=2) ); bool passesPhoton_tauB_Trigger = ( (e.numberOfObjects("ph",ptThreshold2,2.5) >= 1) && (e.numberOfObjects("b",ptThreshold1,1.0)>=1) && (e.numberOfObjects("tau",ptThreshold1,1.0)>=1) ); bool passesPrescaledJet25Trigger = ((e.numberOfObjects("j",40,1.0)+ e.numberOfObjects("b",40,1.0) >= 1)&& (e.getEventType()!="data")&& // labeled as "jet25" instead (e.getEventType()!="sig")&& ((eventType!="jet25")||(rn.substr(rn.length()-1)=="0"))); // take only every tenth event from jet25 bool passesPrescaledJet25TauTrigger = ((e.numberOfObjects("j",40,1.0)+ e.numberOfObjects("b",40,1.0) >= 1)&& (e.numberOfObjects("tau",ptThreshold0,1.0)>=1)&& (e.getEventType()!="data")&& // labeled as "jet25" instead (e.getEventType()!="sig")); bool passesPrescaledJet25jetBTrigger = ((e.numberOfObjects("j",ptThreshold3,1.0)>=1)&& (e.numberOfObjects("b",ptThreshold1,1.0)>=1)&& (e.getEventType()!="data")&& // labeled as "jet25" instead (e.getEventType()!="sig")); bool passesPrescaledJet25BTrigger = ((e.numberOfObjects("b",ptThreshold3,1.0)>=1)&& (e.getEventType()!="data")&& // labeled as "jet25" instead (e.getEventType()!="sig")); bool passesTrigger = ( passesSingleCentralElectronTrigger || passesSinglePlugElectronTrigger || passesDiEmObjectTrigger || passesSingleMuonTrigger || passesDileptonTrigger || // passesDiTauTrigger || passesSinglePhotonTrigger || passesSinglePlugPhotonTrigger || passesDiPhotonTrigger || passesPhotonLeptonTrigger || // passesPhotonBTrigger || passesCentralLeptonBTrigger || // passesPlugElectronBTrigger || passesPlugElectronCentralTauTrigger || passesSingleJetTrigger || passesPrescaledJet25Trigger || passesPrescaledJet25TauTrigger || passesPrescaledJet25jetBTrigger || passesPrescaledJet25BTrigger || /* passesPrescaledSingleCentralElectronTrigger || passesPrescaledSingleCentralMuonTrigger || passesPrescaledSinglePlugElectronTrigger || passesPrescaledSingleCentralPhotonTrigger || */ // passesPlugPhotonBTrigger || passesCentralPhotonTauTrigger || passesPlugPhotonTauTrigger || passesPhoton_diTau_Trigger || passesPhoton_diB_Trigger || passesPhoton_tauB_Trigger ); if((e.getEventType()=="sig")&& (!passesTrigger)&& (e.numberOfObjects("j",40,1.0)+e.numberOfObjects("b",40,1.0) >= 1)) { if(level>=10) wt *= 0.00012; // jet25 prescale passesTrigger = true; } if(level>=5) if((!passesTrigger)|| (disallowedFinalState)) ans = false; } if((collider=="tev2")&& ((experiment=="cdf"))) { string eventType = e.getEventType(); if( (zvtx==0) && ( ( (eventType.length()>=6) && (eventType.substr(0,6)=="cosmic") ) || (eventType=="sig") ) ) { while((zvtx==0)||(fabs(zvtx)>60)) zvtx = Math::gasdev(0,30.); // units are cm for(size_t i=0; i<o.size(); i++) { double newObjectEta = QuaeroRecoObject::getEventEta("cdf", o[i].getObjectType(), Math::theta2eta(o[i].getFourVector().theta()), zvtx); double newObjectPt = o[i].getFourVector().e()*fabs(sin(Math::eta2theta(newObjectEta))); o[i] = QuaeroRecoObject(o[i].getObjectType(), QuaeroRecoObject::setLorentzVectorMPtEtaPhi(o[i].getFourVector().m(), newObjectPt, newObjectEta, o[i].getFourVector().phi())); } e.setObjects(o); } else { if((e.getZVtx()==0)|| (fabs(e.getZVtx())>60)) return(false); // does not contain a legal ZVertex } //remove Nj_sumPt400+ events where j2 has pT < 75, because they are regular QCD events that coincide with a cosmic. So, j2 is prompt (and so is j3,j4 etc), j1 is cosmic, and typically j2 pT < 75 GeV. if(e.sumPt()>=400 && e.numberOfObjects("j") >= 2 && e.numberOfObjects("b")==0 && e.numberOfObjects("e")==0 && e.numberOfObjects("mu")==0 && e.numberOfObjects("tau")==0 && e.numberOfObjects("ph")==0 ) { if(e.getThisObject("j",2)->getFourVector().perp() < 75) return(false); } // Remove suspected cosmic rays bool failsCosmicCut = false; // Note events that have a kill object bool killed = false; for(size_t i=0; i<o.size(); i++) if(o[i].getObjectType()=="kill") killed = true; // Remove b's and tau's from the plug if((eventType=="data")|| (eventType=="jet20")|| (eventType=="sig")) for(size_t i=0; i<o.size(); i++) if(((o[i].getObjectTypeSansSign()=="b")|| (o[i].getObjectTypeSansSign()=="tau"))&& //(fabs(QuaeroRecoObject::getDetectorEta("cdf", o[i].getObjectTypeSansSign(), Math::theta2eta(o[i].getFourVector().theta()), e.getZVtx()))>1.0) (fabs(Math::theta2eta(o[i].getFourVector().theta()))>1.0) ) o[i] = QuaeroRecoObject("j",o[i].getFourVector()); // Remove taus with |eta|<0.1 // These taus tend to be misreconstructed electrons in our Monte Carlo samples /* for(size_t i=0; i<o.size(); i++) if((o[i].getObjectTypeSansSign()=="tau")&& (fabs(QuaeroRecoObject::getDetectorEta("cdf", o[i].getObjectTypeSansSign(), Math::theta2eta(o[i].getFourVector().theta()), e.getZVtx()))<0.1)) o[i] = QuaeroRecoObject("j",o[i].getFourVector()); */ // If this is a mrenna or mad sample, then it was reconstructed with gen5, with different tau id. // The p(e->tau) rate should be doubled in the Z->ee samples, where one e fakes a tau. // This modification is motivated by a Vista 1e+1tau-[12]j:mass(e+,tau-) discrepancy. if(((eventType.length()>=11)&& (eventType.substr(0,11)=="mrenna_e+e-")) || ((eventType.length()>=8)&& (eventType.substr(0,8)=="mad_e+e-"))) { string electronCharge=""; for(size_t i=0; i<o.size(); i++) if(o[i].getObjectTypeSansSign()=="e") if(electronCharge=="") electronCharge = o[i].getSign(); else electronCharge="moreThanOneElectron"; if(electronCharge.length()==1) for(size_t i=0; i<o.size(); i++) if((o[i].getObjectTypeSansSign()=="tau")&& (fabs(Math::theta2eta(o[i].getFourVector().theta()))<1.0)&& (o[i].getFourVector().perp()>partitionRule.getPmin())) if(o[i].getSign()!=electronCharge) // the tau and electron have opposite charge, hence the tau could have come from the other electron wt *= 2; } // Check if event has an electron and another EM object within deltaR < 0.2 for(size_t i=0; i<o.size(); i++) if(o[i].getObjectTypeSansSign()=="e") for(size_t j=i+1; j<o.size(); j++) if((o[j].getObjectTypeSansSign()=="e")|| (o[j].getObjectTypeSansSign()=="ph")) if(Math::deltaR(o[i].getFourVector().phi(), Math::theta2eta(o[i].getFourVector().theta()), o[j].getFourVector().phi(), Math::theta2eta(o[j].getFourVector().theta())) < 0.2) { o[j] = QuaeroRecoObject("uncl",o[j].getFourVector()); } if(level>5) { // An electron with 1.1<|detEta|<1.2 has dubious charge string chargeOfWellDeterminedLepton = ""; int iOfDubiousChargeElectron = -1; for(size_t i=0; i<o.size(); i++) { if((o[i].getObjectTypeSansSign()=="mu") // ||(o[i].getObjectTypeSansSign()=="tau") ) chargeOfWellDeterminedLepton += o[i].getSign(); else if(o[i].getObjectTypeSansSign()=="e") { double detEta = QuaeroRecoObject::getDetectorEta("cdf", "e", o[i].getFourVector().pseudoRapidity(), zvtx); if((fabs(detEta)>1.1)&&(fabs(detEta)<1.2)) iOfDubiousChargeElectron=i; else chargeOfWellDeterminedLepton += o[i].getSign(); } } if((iOfDubiousChargeElectron>=0)&& (chargeOfWellDeterminedLepton==o[iOfDubiousChargeElectron].getSign())) o[iOfDubiousChargeElectron].chargeConjugate(); // Fix sign of plug electrons string centralElectronIfPresent = ""; for(size_t i=0; i<o.size(); i++) if((o[i].getObjectTypeSansSign()=="e")&& (fabs(Math::theta2eta(o[i].getFourVector().theta()))<0.9)) centralElectronIfPresent = o[i].getObjectType(); for(size_t i=0; i<o.size(); i++) if((o[i].getObjectTypeSansSign()=="e")&& (fabs(Math::theta2eta(o[i].getFourVector().theta()))>0.9)) if(centralElectronIfPresent==o[i].getObjectType()) o[i].chargeConjugate(); // Two plug electrons with the same sign should have opposite sign string plugElectronIfPresent = ""; // double pTofHighestPtPlugElectron = 0; for(size_t i=0; i<o.size(); i++) if((o[i].getObjectTypeSansSign()=="e")&& (fabs(Math::theta2eta(o[i].getFourVector().theta()))>0.9)) for(size_t j=i+1; j<o.size(); j++) if((o[j].getObjectTypeSansSign()=="e")&& (fabs(Math::theta2eta(o[j].getFourVector().theta()))>0.9)&& (o[i].getObjectType()==o[j].getObjectType())) if(o[i].getFourVector().perp()<o[j].getFourVector().perp()) o[i].chargeConjugate(); else o[j].chargeConjugate(); // Check if event has lepton with deltaR < 0.75 from nearest jet for(size_t i=0; i<o.size(); i++) if((o[i].getObjectTypeSansSign()=="e")|| (o[i].getObjectTypeSansSign()=="tau")|| (o[i].getObjectTypeSansSign()=="mu")) for(size_t j=0; j<o.size(); j++) if(j!=i) if(((o[j].getObjectTypeSansSign()=="j") ||(o[j].getObjectTypeSansSign()=="b") ||(o[j].getObjectTypeSansSign()=="tau") )&& (o[j].getFourVector().perp()>partitionRule.getPmin())&& (fabs(Math::theta2eta(o[j].getFourVector().theta()))<2.5)) if(Math::deltaR(o[i].getFourVector().phi(), Math::theta2eta(o[i].getFourVector().theta()), o[j].getFourVector().phi(), Math::theta2eta(o[j].getFourVector().theta())) < 0.75) return(false); // contains lepton too close to a jet // Correct for triggerEfficiencies between CMUP and CMX if((eventType!="data")&& (eventType!="jet20")) { string locationOfSingleTriggerMuon = ""; for(size_t i=0; i<o.size(); i++) if((o[i].getObjectTypeSansSign()=="e")|| (o[i].getObjectTypeSansSign()=="tau")|| (o[i].getObjectTypeSansSign()=="ph")|| ((o[i].getObjectTypeSansSign()=="mu")&& (locationOfSingleTriggerMuon!=""))) { locationOfSingleTriggerMuon="thereIsAnotherTriggerObject"; break; } else if(o[i].getObjectTypeSansSign()=="mu") if(fabs(Math::theta2eta(o[i].getFourVector().theta()))<0.6) locationOfSingleTriggerMuon=="CMUP"; else locationOfSingleTriggerMuon=="CMX"; if(locationOfSingleTriggerMuon=="CMUP") wt *= 0.98; // CMUP trigger efficiency is 2% less than "average" muon efficiency if(locationOfSingleTriggerMuon=="CMX") wt *= 1.02; // CMX trigger efficiency is 2% higher than "average" muon efficiency } // Impose Bayesian interpretation on muon momentum for(size_t i=0; i<o.size(); i++) if((o[i].getObjectTypeSansSign()=="mu")) { double phat = o[i].getFourVector().perp(); double p = phat; double sigma = 0.002; if(p<200) sigma=(phat-60)/140*0.002; // this (and the next line, the if statement) is hack in order to not run into trouble at trigger thresholds if(sigma>0.001) p = (-1/phat + sqrt(1/(phat*phat) + 8 * (sigma*sigma)))/(4*(sigma*sigma)); o[i] = QuaeroRecoObject(o[i].getObjectType(),o[i].getFourVector() * (p/phat) ); } } // Any object with (|eta| > 2.5) || (pT < 15) is converted to unclustered energy // Option: change to pT < 10 GeV for investigating low-pT leptons if(!((hintSpec.collider=="tev2")&& (hintSpec.experiment=="cdf")&& (hintSpec.finalState=="lowPtDileptons"))) for(size_t i=0; i<o.size(); i++) if( (fabs(Math::theta2eta(o[i].getFourVector().theta()))>2.5) || (o[i].getFourVector().perp()<15) ) o[i] = QuaeroRecoObject("uncl",o[i].getFourVector()); CLHEP::HepLorentzVector uncl = CLHEP::HepLorentzVector(0,0,0,0); for(size_t i=o.size()-1; ; i--) { if(o[i].getObjectType()=="uncl") { uncl = uncl + o[i].getFourVector(); o.erase(o.begin()+i); } if( i==0 ) break; } if(uncl.perp()>0) o.push_back(QuaeroRecoObject("uncl",uncl)); double highJetPtThreshold = 200; // units are GeV bool usingChargedTrackJets = false; if(usingChargedTrackJets) highJetPtThreshold = 100; // units are GeV if(level>=5) { if((level>=10)&& ((eventType=="sig")|| (usingChargedTrackJets))) { // Cluster events passing SingleJetTrigger to a significantly higher scale (say 50 GeV) double kTscale = 15; bool lowPtJets = false; bool highPtJets = false; if((e.numberOfObjects("j",highJetPtThreshold,1.0)+ e.numberOfObjects("b",highJetPtThreshold,1.0) >= 1)|| (usingChargedTrackJets)) { kTscale = 50; highPtJets = true; } else if(e.numberOfObjects("e",25,1)+ e.numberOfObjects("mu",25,1)+ e.numberOfObjects("ph",25,2.5)==0) lowPtJets = true; if(highPtJets) { int k1=0,k2=0; double minDeltaRjj = 0; while(minDeltaRjj<0.7) { k1=k2=-1; minDeltaRjj=0.7; for(size_t i=0; i<o.size(); i++) if((o[i].getObjectType()=="j") || (o[i].getObjectType()=="b")) for(size_t j=i+1; j<o.size(); j++) if((o[j].getObjectType()=="j") || (o[j].getObjectType()=="b")) { double deltaRjj = Math::deltaR(o[i].getFourVector().phi(), Math::theta2eta(o[i].getFourVector().theta()), o[j].getFourVector().phi(), Math::theta2eta(o[j].getFourVector().theta())); if(deltaRjj < minDeltaRjj) { minDeltaRjj = deltaRjj; k1=i; k2=j; } } if((k1>=0)&&(k2>=0)) { o[k1] = QuaeroRecoObject("j",o[k1].getFourVector()+o[k2].getFourVector()); o.erase(o.begin()+k2); } } } int k1=0,k2=0; while((k1>=0)&&(k2>=0)) { k1=k2=-1; int nj=0; for(size_t i=0; i<o.size(); i++) if(o[i].getObjectType()=="j") nj++; // Find the highest pt jet bool noIndex = true; size_t highestPtJet = 0; double highestJetPt = 0; for(size_t i=0; i<o.size(); i++) if((o[i].getObjectType()=="j")|| (o[i].getObjectType()=="b")) if(o[i].getFourVector().perp()>highestJetPt) { highestJetPt = o[i].getFourVector().perp(); highestPtJet = i; noIndex = false; } double m_cut = (((nj>4)&&(!lowPtJets)) ? FLT_MAX : kTscale); double mij_min = m_cut; for(size_t i=0; i<o.size(); i++) if( noIndex || i!=highestPtJet) if((o[i].getObjectType()=="j") || (o[i].getObjectType()=="b") || (o[i].getObjectTypeSansSign()=="tau")) for(size_t j=i+1; j<o.size(); j++) if( noIndex || j!=highestPtJet) if((o[j].getObjectType()=="j") || (o[j].getObjectType()=="b") || (o[i].getObjectTypeSansSign()=="tau")) { double mij = (o[i].getFourVector()+o[j].getFourVector()).m(); if(mij < mij_min) { mij_min = mij; k1=i; k2=j; } } if((k1>=0)&&(k2>=0)) { o[k1] = QuaeroRecoObject("j",o[k1].getFourVector()+o[k2].getFourVector()); o.erase(o.begin()+k2); } } } } // Flag events that contain a plug objects that has been counted twice: as both a photon and an electron // This is a reconstruction screw-up { int iph = -1; for(size_t i=0; i<o.size(); i++) if(o[i].getObjectType()=="ph") if(iph==-1) iph = i; else iph = -2; if(iph>=0) { CLHEP::HepLorentzVector ph = o[iph].getFourVector(); bool killThePhoton = false; for(size_t i=0; i<o.size(); i++) if(o[i].getObjectTypeSansSign()=="e") { CLHEP::HepLorentzVector ele = o[i].getFourVector(); if(((fabs(Math::theta2eta(ele.theta()))>1)|| (fabs(Math::theta2eta(ph.theta()))>1))&& (Math::deltaR(ele.phi(),ele.theta(), ph.phi(),ph.theta())<1.8)&& ((fabs(ele.e()-ph.e())<5)|| ((fabs(ele.e()-ph.e())<10)&& (fabs(max(fabs(Math::theta2eta(ele.theta())), fabs(Math::theta2eta(ph.theta())))-1.2)<0.1)))) killThePhoton = true; } if(killThePhoton) { //o.erase(o.begin()+iph); o[iph] = QuaeroRecoObject("uncl",o[iph].getFourVector()); } } } e.setObjects(o); e.reVertex(zvtx); fs = partitionRule.getFinalState(e).getTextString(); string rn = e.getRunNumber(); string::size_type pos = rn.find (".",0); // find the dot string runNumberString = rn.substr(0,pos); // keep only the run number string. // int runNumber = atoi(runNumberString.c_str()); if(level>=5) { bool disallowedFinalState = false; if((fs=="1j_sumPt0-400")|| (fs=="1j1pmiss_sumPt0-400")|| (fs=="1b_sumPt0-400")|| (fs=="1b1pmiss_sumPt0-400")|| (fs=="1b_sumPt400+")) disallowedFinalState = true; // cut out low-pt 1j and 1j1pmiss final states if((fs=="1e+")||(fs=="1e-")|| (fs=="1mu+")||(fs=="1mu-")) disallowedFinalState = true; // cut out 1e and 1mu final states if((fs=="1tau+")||(fs=="1tau-")|| (fs=="1pmiss1tau+")||(fs=="1pmiss1tau-")) disallowedFinalState = true; // cut out 1tau final states if((fs=="1ph")) disallowedFinalState = true; // cut out 1ph final state if((fs=="1pmiss")) disallowedFinalState = true; // cut out 1pmiss final state if(disallowedFinalState) return(false); /* The CDF silicon detector was not as efficient at identifying bottom quarks early in Run II. The jet20 trigger had a lower prescale early in Run II. The sumPt0-400 final states with identified bottom quarks thus need to have reduced SM prediction. */ if((e.getEventType()!="data")&& (e.getEventType()!="jet20")&& ((fs=="1b1j_sumPt0-400")|| (fs=="1b2j_sumPt0-400")|| (fs=="1b3j_sumPt0-400")|| (fs=="1b4j_sumPt0-400")|| // In early runs we did not have as good b-tagging *nor* as good phoenix electron id, // so we take a hit for this in the first ~150 pb^-1 ((e.numberOfObjects("e",15,2.5)- e.numberOfObjects("e",15,1.0)>=1)&& (e.numberOfObjects("b",15,1.0)>=1)) )) wt *= 0.98; } bool jet20DuplicateEvent = false; if(e.getEventType()=="jet20") { if(rn=="179056.3633137") jet20DuplicateEvent = true; } double ptThreshold0 = 10, ptThreshold01 = 15, ptThreshold1 = 20, ptThreshold12 = 25, ptThreshold2 = 35, ptThreshold3 = 50, ptThreshold4 = 75; if(level>=6) { ptThreshold0 = 17; ptThreshold01 = 20; ptThreshold1 = 25; ptThreshold12 = 30; ptThreshold2 = 40; ptThreshold3 = 60; ptThreshold4 = 90; } bool passesTrigger = false; if((e.numberOfObjects("e")>=1)) { if( ( (e.numberOfObjects("e",ptThreshold1,1.0)>=1) // &&((eventType!="data")||((rn.length()>1)&&(rn.substr(rn.length()-1)=="0"))) ) || // passesSingleCentralElectron25Trigger (e.numberOfObjects("e",ptThreshold2,1.0)>=1) || // passesSingleCentralElectron40Trigger ( (e.numberOfObjects("e",ptThreshold1,1.0)>=1) && (e.getPmiss().perp()>ptThreshold0) && (e.numberOfObjects("j",ptThreshold0,2.5)+ e.numberOfObjects("b",ptThreshold0,1.0)>=2) ) || // passesSingleCentralElectronWjetsTrigger ( (e.numberOfObjects("e",ptThreshold2,2.5)>=1) // passesSinglePlugElectron40Trigger // && ((eventType!="data")||((rn.length()>1)&&(rn.substr(rn.length()-1)=="0"))) ) || (e.numberOfObjects("e",ptThreshold3,2.5)>=1) || // passesSinglePlugElectron60Trigger ( (e.numberOfObjects("e",ptThreshold2,2.5)>=1) && (e.getPmiss().perp()>ptThreshold0) && (e.numberOfObjects("j",ptThreshold0,2.5)+ e.numberOfObjects("b",ptThreshold0,1.0)>=2) ) || // passesSinglePlugElectronWjetsTrigger /* ((e.numberOfObjects("e",ptThreshold12,2.5)- e.numberOfObjects("e",ptThreshold12,1.0)>=1)&& ((eventType!="data")|| ((rn.length()>1)&&(rn.substr(rn.length()-1)=="0"))) ) || // passesDoublyPrescaledSinglePlugElectronTrigger */ ( ( (e.numberOfObjects("e",ptThreshold1,2.5)+ e.numberOfObjects("ph",ptThreshold1,2.5)) >=2 ) && ( e.numberOfObjects("e",ptThreshold1,2.5) >= 1 ) ) || // passesDiEmObjectTrigger with electron ( (e.numberOfObjects("e",ptThreshold01,1.0)>=1) && ((eventType!="data")||((rn.length()>2)&&(rn.substr(rn.length()-2)=="00"))) ) || // passesDoublyPrescaledSingleCentralElectron20Trigger ( (e.numberOfObjects("ph", ptThreshold1, 2.5)>=1) && (e.numberOfObjects("e",ptThreshold1,1.0)>=1) ) || // passesCentralElectronPlusPhotonTrigger ( (e.numberOfObjects("e", ptThreshold1, 1.0)>=1) && (e.numberOfObjects("b", ptThreshold0, 1.0)>=1) ) || // passesCentralElectronBTrigger /* ( (e.numberOfObjects("e", ptThreshold1, 2.5)>=1) && (e.numberOfObjects("b", ptThreshold1, 1.0)>=1) ) || // passesPlugElectronBTrigger */ ( (e.numberOfObjects("e", ptThreshold2, 2.5)>=1) && (e.numberOfObjects("tau", ptThreshold0, 1.0)>=1) ) // passesPlugElectronCentralTauTrigger ) passesTrigger = true; } if((!passesTrigger)&&(e.numberOfObjects("mu")>=1)) { if( (e.numberOfObjects("mu",ptThreshold2,1.0)>=1) || // passesSingleCentralMuon40Trigger ( (e.numberOfObjects("mu",ptThreshold1,1.0)>=1) // && ((eventType!="data")||((rn.length()>1)&&(rn.substr(rn.length()-1)=="0"))) ) || // passesSingleCentralMuon25Trigger ( (e.numberOfObjects("mu",ptThreshold01,1.0)>=1) && ((eventType!="data")||((rn.length()>2)&&(rn.substr(rn.length()-2)=="00"))) ) || // passesDoublyPrescaledSingleCentralMuon20Trigger ( (e.numberOfObjects("mu",ptThreshold1,1.0)>=1) && (e.getPmiss().perp()>ptThreshold0) && (e.numberOfObjects("j",ptThreshold0,2.5)+ e.numberOfObjects("b",ptThreshold0,1.0)>=2) ) || // passesSingleCentralMuonWjetsTrigger ( (e.numberOfObjects("ph", ptThreshold1, 2.5)>=1) && (e.numberOfObjects("mu",ptThreshold0,1.0)>=1) ) || // passesMuonPhotonTrigger ( (e.numberOfObjects("mu", ptThreshold1, 1.0)>=1) && (e.numberOfObjects("b", ptThreshold0, 1.0)>=1) ) // passesCentralMuonBTrigger ) passesTrigger = true; } if((!passesTrigger)&&(e.numberOfObjects("tau")>=1)) { if(e.numberOfObjects("tau",ptThreshold1,1.0)>=2) // passesDiTauTrigger { int numberOfTausInCentralDetector=0; for(size_t j=0; j<o.size(); j++) if((o[j].getObjectTypeSansSign()=="tau")&& (fabs(QuaeroRecoObject::getDetectorEta("cdf", "tau", Math::theta2eta(o[j].getFourVector().theta()), e.getZVtx()))<1)) numberOfTausInCentralDetector++; if(numberOfTausInCentralDetector>=2) // need to have two taus with |detEta|<1, in addition to |eta|<1. passesTrigger=true; } if( ( (e.numberOfObjects("ph", ptThreshold2, 1.0)>=1) && (e.numberOfObjects("tau",ptThreshold2, 1.0)>=1) ) || // passesCentralPhotonTauTrigger ( (e.numberOfObjects("ph", ptThreshold2, 2.5) >= 1) && (e.numberOfObjects("tau",ptThreshold2,1.0)>=1) ) || // passesPlugPhotonTauTrigger ( (e.numberOfObjects("ph",ptThreshold2,2.5) >= 1) && (e.numberOfObjects("tau",ptThreshold0,1.0)>=2) ) || // passesPhoton_diTau_Trigger ( (e.numberOfObjects("ph",ptThreshold2,2.5) >= 1) && (e.numberOfObjects("b",ptThreshold1,1.0)>=1) && (e.numberOfObjects("tau",ptThreshold1,1.0)>=1) ) // passesTauPhotonBTrigger ) passesTrigger = true; } if((!passesTrigger)&&(e.numberOfObjects("ph", ptThreshold1)>=1)) { if( //( (e.numberOfObjects("ph",ptThreshold1,1.0)>=1) && // ((eventType!="data")|| // passesPrescaledSingleCentralPhotonTrigger // ((rn.length()>1)&&(rn.substr(rn.length()-2)=="00"))) ) || // We use this trigger to allow us to get a good handle of j->ph fakes between 25 and 60 GeV (e.numberOfObjects("ph",(level<=5 ? 55 : 60),1.0)>=1) || // passesSinglePhotonTrigger ( (e.numberOfObjects("ph", ptThreshold1, 2.5)>=2) && (e.numberOfObjects("ph", ptThreshold1, 1.0)>=1) ) || // passesDiPhotonTrigger /* ( (e.numberOfObjects("ph", ptThreshold2, 1.0)>=1) && (e.numberOfObjects("b", ptThreshold0, 1.0)>=1) ) || // passesPhotonBTrigger */ (e.numberOfObjects("ph", (level<=5 ? 250 : 300),2.5) >= 1 ) || // passesSinglePlugPhotonTrigger /* ( (e.numberOfObjects("ph", ptThreshold2, 2.5) >= 1) && (e.numberOfObjects("b",ptThreshold0,1.0)>=1) ) || // passesPlugPhotonBTrigger */ ( (e.numberOfObjects("ph",ptThreshold2,1.0) >= 1) && (e.numberOfObjects("b",ptThreshold1,1.0)>=2) ) // passesPhoton_diB_Trigger ) passesTrigger = true; } if((!passesTrigger)&&(e.numberOfObjects("b", ptThreshold2, 1.0)>=2)) { if( /* ( (e.numberOfObjects("b", ptThreshold4, 1.0)>=2) ) || // passesDiBjetTrigger */ ( (e.numberOfObjects("b", ptThreshold3, 1.0)>=3) && (e.numberOfObjects("b", ptThreshold4, 1.0)>=1) ) // passesTriBjetTrigger ) passesTrigger = true; } if((!passesTrigger)) { if( ((e.numberOfObjects("j", (level<=5 ? 150 : highJetPtThreshold),1.0)+ e.numberOfObjects("b", (level<=5 ? 150 : highJetPtThreshold),1.0))>=1) || // passesSingleJetTrigger ((e.numberOfObjects("j",40,1.0)+e.numberOfObjects("b",40,1.0) >= 1)&& (eventType!="data")&& // labeled as "jet20" instead (eventType!="sig")&& ((eventType!="jet20")||(rn.substr(rn.length()-1)=="0")) // take only every tenth event from jet20 ) || // passesPrescaledJet20Trigger ((e.numberOfObjects("j",40,1.0)+e.numberOfObjects("b",40,1.0) >= 1)&& (e.numberOfObjects("tau",ptThreshold0,1.0)>=1)&& (eventType!="data")&& // labeled as "jet20" instead (eventType!="sig")) || // passesPrescaledJet20TauTrigger ((e.numberOfObjects("j",ptThreshold3,1.0)>=1)&& (e.numberOfObjects("b",ptThreshold1,1.0)>=1)&& (eventType!="data")&& // labeled as "jet20" instead (eventType!="sig")) || // passesPrescaledJet20jetBTrigger ((e.numberOfObjects("b",ptThreshold3,1.0)>=1)&& (eventType!="data")&& // labeled as "jet20" instead (eventType!="sig")) // passesPrescaledJet20BTrigger ) passesTrigger = true; } if(!passesTrigger) { int cem8 = e.numberOfObjects("e",ptThreshold0,1.0); int cem20 = e.numberOfObjects("e",ptThreshold01,1.0); int pem8 = e.numberOfObjects("e",ptThreshold1,2.5)-e.numberOfObjects("e",ptThreshold1,1.0); int muo8 = e.numberOfObjects("mu",ptThreshold0,1.0); int muo20 = e.numberOfObjects("mu",ptThreshold01,1.0); int trk8 = e.numberOfObjects("tau",ptThreshold0,1.0); bool passesDileptonTrigger = ( // (cem8>=2) || (muo8>=2) || ((muo8>=1)&&(e.numberOfObjects("mu",ptThreshold0,2.5)>=2)) || // (cem8 && pem8) || (cem8 && muo8) || (cem20 && trk8) || (pem8 && muo8) || (muo20 && trk8) || ((hintSpec.collider=="tev2")&& (hintSpec.experiment=="cdf")&& (hintSpec.finalState=="lowPtDileptons")&& (((e.numberOfObjects("mu",4,0.6)>=1)&& (e.numberOfObjects("mu",4,1.0)>=2))|| (e.numberOfObjects("e",4,1.0)>=2))) ); if(passesDileptonTrigger) passesTrigger = true; } if((eventType=="sig")&& (!passesTrigger)&& (e.numberOfObjects("j",40,1.0)+e.numberOfObjects("b",40,1.0) >= 1)) { if(level>=10) wt *= 0.00012; // jet20 prescale passesTrigger = true; } // Cosmic processes cannot produce b jets bool thisIsAnUnintendedUseOfThisGeneratedProcess = false; if( ( ( (eventType.length()>=6) && (eventType.substr(0,6)=="cosmic") ) ) ) for(size_t i=0; i<o.size(); i++) if(o[i].getObjectType()=="b") thisIsAnUnintendedUseOfThisGeneratedProcess = true; if( ( (eventType=="mrenna_e+e-")|| (eventType=="mrenna_e+e-j")|| (eventType=="mad_e+e-") ) && (fs=="1b1e+") ) thisIsAnUnintendedUseOfThisGeneratedProcess = true; // Our reconstruction can reconstruct a mrenna_e+e- Monte Carlo event as containing an electron and a jet. // Our misReconstruction can than call that jet a tau by applying p(j->tau). // In the data, this does not happen. // This contribution to our background estimate in the 1e1tauX final states must therefore be removed. if( ( (eventType=="mrenna_e+e-")|| (eventType=="mrenna_e+e-j")|| (eventType=="mad_e+e-") ) && ((fs=="1e+1tau+") || (fs=="1e+1tau-")) ) thisIsAnUnintendedUseOfThisGeneratedProcess = true; // Pythia W->lnu should not fake 1l1pmiss1tau+. // This should be handled by MadEvent W->lnu (+1 or more reconstructed jets) if( ( (eventType=="sewkad")|| // Pythia W->enu (eventType=="wewk7m")|| // Pythia W->munu (eventType=="wexo0m")|| (eventType=="we0s8m") ) && ( ( (fs.find("1e")!=string::npos) || (fs.find("1mu")!=string::npos) ) && (fs.find("1tau")!=string::npos) ) ) thisIsAnUnintendedUseOfThisGeneratedProcess = true; // zx0sd[em] should not be used for m(ll)>20 GeV if( (eventType=="zx0sde") && // Pythia Z->ee, m>10 GeV ( (e.numberOfObjects("e+")==0) || (e.numberOfObjects("e-")==0) || ( (e.getThisObject("e+")->getFourVector()+e.getThisObject("e-")->getFourVector()).m() > 20) // units are GeV ) ) thisIsAnUnintendedUseOfThisGeneratedProcess = true; if( (eventType=="zx0sdm") && // Pythia Z->mumu, m>10 GeV ( (e.numberOfObjects("mu+")==0) || (e.numberOfObjects("mu-")==0) || ( (e.getThisObject("mu+")->getFourVector()+e.getThisObject("mu-")->getFourVector()).m() > 20) // units are GeV ) ) thisIsAnUnintendedUseOfThisGeneratedProcess = true; if(level>=5) if( (!passesTrigger) || failsCosmicCut || thisIsAnUnintendedUseOfThisGeneratedProcess || jet20DuplicateEvent || killed ) { ans = false; if (debug) cout << " Refined out because " << "[(!passesTrigger)||failsCosmicCut||thisIsAnUnintendedUseOfThisGeneratedProcess||jet20DuplicateEvent||killed]=[" << (!passesTrigger) <<"||"<< failsCosmicCut <<"||"<< thisIsAnUnintendedUseOfThisGeneratedProcess <<"||"<< jet20DuplicateEvent <<"||"<< killed << "]" << endl; } } /************************************************* Cleanup **************************************************/ e.reWeight(wt); e.setObjects(o); e.reVertex(zvtx); /************************************************* Hint **************************************************/ if(hintSpec.active==true) { if(collider!=hintSpec.collider) ans = false; if(experiment!=hintSpec.experiment) ans = false; if(fs!=hintSpec.finalState) { if(((hintSpec.finalState=="1bb1w")|| (hintSpec.finalState=="1bb1w+")|| (hintSpec.finalState=="1bb1w-"))&& ((fs=="1b1e+1j1pmiss")|| (fs=="1b1j1mu+1pmiss") )) ; // okay if((fs.length()>hintSpec.finalState.length())&& (hintSpec.finalState==fs.substr(0,hintSpec.finalState.length()))&& (fs.substr(hintSpec.finalState.length(),6)=="_sumPt")) ; // okay else ans = false; // not okay } if(e.sumPt()<hintSpec.sumPtCut) ans = false; } return(ans); } void Refine::setMinWt(double _minWt) { assert(_minWt>=0); minWt = _minWt; return; } bool Refine::passesMinWt(QuaeroEvent& e, double& runningWeight) { bool passesSpecialCriteria = false; if((collider=="tev2")&& (experiment=="cdf")) passesSpecialCriteria = passesSpecialSleuthCriteriaQ(e); double minWt1 = minWt; if(passesSpecialCriteria) minWt1 = minWt/10; if(e.getWeight()>=minWt1) return(true); else { runningWeight += e.getWeight(); if(((int)(runningWeight/minWt1)) > ((int)((runningWeight-e.getWeight())/minWt1))) { runningWeight -= minWt1; e.reWeight(minWt1); return(true); } } return(false); } bool Refine::passesSpecialSleuthCriteriaQ(const QuaeroEvent& e) { bool passesSpecialCriteria = false; if((e.numberOfObjects("e",15,2.5)+ e.numberOfObjects("mu",15,2.5) >= 1) && (e.numberOfObjects("j",15,2.5)+ e.numberOfObjects("b",15,2.5) >=4 )) passesSpecialCriteria = true; // top lepton + jets if((e.numberOfObjects("e",15,2.5)+ e.numberOfObjects("mu",15,2.5) >= 2) && (e.numberOfObjects("j",15,2.5)+ e.numberOfObjects("b",15,2.5) >=2 )) passesSpecialCriteria = true; // top dilepton if((e.numberOfObjects("e",15,2.5) >= 1) && (e.numberOfObjects("mu",15,2.5) >= 1)) passesSpecialCriteria = true; // 1e1muX if((e.numberOfObjects("e",20,2.5) >= 1) && (e.numberOfObjects("tau",20,2.5) >= 1)) passesSpecialCriteria = true; // 1e1tauX if((e.numberOfObjects("tau",15,2.5) >= 1)&& (e.numberOfObjects("j",17,2.5) >= 2)&& (e.sumPt()>400)) passesSpecialCriteria = true; // 1jj1tau if((e.numberOfObjects("tau",15,2.5) >= 1)&& (e.sumPt()>400)) passesSpecialCriteria = true; // 1pmiss1tau if((e.numberOfObjects("e",15,2.5)+ e.numberOfObjects("mu",15,2.5)>=1)&& (e.numberOfObjects("ph",15,2.5)>=1)&& (e.numberOfObjects("j",15,2.5)>=3)&& (e.getPmiss().perp()>12) && (e.sumPt() > 200)) passesSpecialCriteria = true; // 1e+2jj1ph1pmiss if((e.numberOfObjects("e",15,2.5)+ e.numberOfObjects("mu",15,2.5)>=2)&& (e.numberOfObjects("b",15,1.0)>=1)&& (e.numberOfObjects("j",15,2.5)>=1)&& (e.getPmiss().perp()>12) && (e.sumPt() > 200)) passesSpecialCriteria = true; // 1e+1e-1bb1pmiss if((e.numberOfObjects("b",200,2.5)>=1)&& (e.getPmiss().perp()>50) && (e.sumPt() > 700)) passesSpecialCriteria = true; // 1bb1pmiss if((e.numberOfObjects("j",15,2.5)>=4)&& (e.getPmiss().perp()>50) && (e.sumPt() > 800)) passesSpecialCriteria = true; // 1bb1pmiss if((e.numberOfObjects("e",15,2.5)+ e.numberOfObjects("mu",15,2.5)>=1)&& (e.numberOfObjects("ph",15,2.5)>=2)&& (e.getPmiss().perp()>12)) passesSpecialCriteria = true; // 1e+2ph1pmiss if(e.numberOfObjects("e+",15,2.5)+ e.numberOfObjects("mu+",15,2.5)>=2) passesSpecialCriteria = true; // 2e+X if((e.numberOfObjects("e",15,2.5)+ e.numberOfObjects("mu",15,2.5)>=3)) passesSpecialCriteria = true; // trilepton return(passesSpecialCriteria); }
[ "mrenna@fnal.gov" ]
mrenna@fnal.gov
15d8625ced8955c8ce1a2f2bad71fb77f4c9eec0
bcecb8afcad65531b2544cc910e8647bbaa4d0f3
/OpenGLTemplate/HeightMapTerrain.cpp
cd376dbf274997b6096eb8a9ee7d183a7f0c9a43
[ "Apache-2.0" ]
permissive
ferenc-schultesz/3DRacerGame
924913f3619f2a7297bc668ecb6151fb5e2d41cb
34784f0dbdbade13fe4f6b00f5d1327aabaa1ef2
refs/heads/master
2020-04-12T03:44:36.693446
2018-12-18T11:13:50
2018-12-18T11:13:50
162,275,996
0
0
null
null
null
null
UTF-8
C++
false
false
6,008
cpp
#include "HeightMapTerrain.h" #pragma comment(lib, "lib/FreeImage.lib") CHeightMapTerrain::CHeightMapTerrain() { m_dib = NULL; } CHeightMapTerrain::~CHeightMapTerrain() { delete [] m_heightMap; } // Convert a point from image (pixel) coordinates to world coordinates glm::vec3 CHeightMapTerrain::ImageToWorldCoordinates(glm::vec3 p) { // Normalize the image point so that it in the range [-1, 1] in x and [-1, 1] in z p.x = 2.0f * (p.x / m_width) - 1.0f; p.z = 2.0f * (p.z / m_height) - 1.0f; // Now scale the point so that the terrain has the right size in x and z p.x *= m_terrainSizeX / 2.0f; p.z *= m_terrainSizeZ / 2.0f; // Now translate the point based on the origin passed into the function p += m_origin; return p; } // Convert a point from world coordinates to image (pixel) coordinates glm::vec3 CHeightMapTerrain::WorldToImageCoordinates(glm::vec3 p) { p -= m_origin; // Normalize the image point so that it in the range [-1, 1] in x and [-1, 1] in z p.x *= 2.0f / m_terrainSizeX; p.z *= 2.0f / m_terrainSizeZ; // Now transform the point so that it is in the range [0, 1] in x and [0, 1] in z p.x = (p.x + 1.0f) * (m_width / 2.0f); p.z = (p.z + 1.0f) * (m_height / 2.0f); return p; } bool CHeightMapTerrain::GetImageBytes(char *terrainFilename, BYTE **bDataPointer, unsigned int &width, unsigned int &height) { FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; fif = FreeImage_GetFileType(terrainFilename, 0); // Check the file signature and deduce its format if(fif == FIF_UNKNOWN) // If still unknown, try to guess the file format from the file extension fif = FreeImage_GetFIFFromFilename(terrainFilename); if(fif == FIF_UNKNOWN) // If still unknown, return failure return false; if(FreeImage_FIFSupportsReading(fif)) // Check if the plugin has reading capabilities and load the file m_dib = FreeImage_Load(fif, terrainFilename); if(!m_dib) { char message[1024]; sprintf_s(message, "Cannot load image\n%s\n", terrainFilename); MessageBox(NULL, message, "Error", MB_ICONERROR); return false; } *bDataPointer = FreeImage_GetBits(m_dib); // Retrieve the image data width = FreeImage_GetWidth(m_dib); height = FreeImage_GetHeight(m_dib); // If somehow one of these failed (they shouldn't), return failure if(bDataPointer == NULL || width == 0 || height == 0) return false; return true; } // This function generates a heightmap terrain based on a bitmap bool CHeightMapTerrain::Create(char *terrainFilename, char *textureFilename, glm::vec3 origin, float terrainSizeX, float terrainSizeZ, float terrainHeightScale) { BYTE *bDataPointer; unsigned int width, height; if (GetImageBytes(terrainFilename, &bDataPointer, width, height) == false) return false; m_width = width; m_height = height; m_origin = origin; m_terrainSizeX = terrainSizeX; m_terrainSizeZ = terrainSizeZ; // Allocate memory and initialize to store the image m_heightMap = new float[m_width * m_height]; if (m_heightMap == NULL) return false; // Clear the heightmap memset(m_heightMap, 0, m_width * m_height * sizeof(float)); // Form mesh std::vector<CVertex> vertices; std::vector<unsigned int> triangles; float halfSizeX = m_width / 2.0f; float halfSizeY = m_height / 2.0f; int X = 1; int Z = m_width; int triangleId = 0; for (int z = 0; z < m_height; z++) { for (int x = 0; x < m_width; x++) { int index = x + z * m_width; // Retreive the colour from the terrain image, and set the normalized height in the range [0, 1] float grayScale = (bDataPointer[index*3] + bDataPointer[index*3+1] + bDataPointer[index*3+2]) / 3.0f; float height = (grayScale - 128.0f) / 128.0f; // Make a point based on this pixel position. Then, transform so that the mesh has the correct size and origin // This transforms a point in image coordinates to world coordinates glm::vec3 pImage = glm::vec3((float) x, height, (float) z); glm::vec3 pWorld = ImageToWorldCoordinates(pImage); // Scale the terrain and store for later pWorld.y *= terrainHeightScale; m_heightMap[index] = pWorld.y; // Store the point in a vector CVertex v = CVertex(pWorld, glm::vec2(0.0, 0.0), glm::vec3(0.0, 0.0, 0.0)); vertices.push_back(v); } } FreeImage_Unload(m_dib); // Form triangles from successive rows of the image for (int z = 0; z < m_height-1; z++) { for (int x = 0; x < m_width-1; x++) { int index = x + z * m_width; triangles.push_back(index); triangles.push_back(index+X+Z); triangles.push_back(index+X); triangles.push_back(index); triangles.push_back(index+Z); triangles.push_back(index+X+Z); } } // Create a face vertex mesh m_mesh.CreateFromTriangleList(vertices, triangles); // Load a texture for texture mapping the mesh m_texture0.Load(textureFilename, true); m_texture1.Load("resources\\textures\\dirtpile01.jpg", true); return true; } // For a point p in world coordinates, return the height of the terrain float CHeightMapTerrain::ReturnGroundHeight(glm::vec3 p) { // Undo the transformation going from image coordinates to world coordinates glm::vec3 pImage = WorldToImageCoordinates(p); // Bilinear interpolation. int xl = (int) floor(pImage.x); int zl = (int) floor (pImage.z); // Check if the position is in the region of the heightmap if (xl < 0 || xl >= m_width - 1 || zl < 0 || zl >= m_height -1) return 0.0f; // Get the indices of four pixels around the current point int indexll = xl + zl * m_width; int indexlr = (xl+1) + zl * m_width; int indexul = xl + (zl+1) * m_width; int indexur = (xl+1) + (zl+1) * m_width; // Interpolation amounts in x and z float dx = pImage.x - xl; float dz = pImage.z - zl; // Interpolate -- first in x and and then in z float a = (1-dx) * m_heightMap[indexll] + dx * m_heightMap[indexlr]; float b = (1-dx) * m_heightMap[indexul] + dx * m_heightMap[indexur]; float c = (1-dz) * a + dz * b; return c; } void CHeightMapTerrain::Render() { m_texture0.Bind(0); m_texture1.Bind(1); m_mesh.Render(); }
[ "ferenc.schultesz@gmail.com" ]
ferenc.schultesz@gmail.com
4ae435cfd7434b8bb62f2477560b8974f32a083b
b43817bfaa62b9dc26b3b312b117c89021116586
/src/SARibbonBar/SARibbonGalleryItem.cpp
d43d720ef3130e30ce31b7862400f92b889363f9
[ "MIT" ]
permissive
PrimUV/SARibbon
75f701f60d5915b68da9b90221333941f09b93fe
2609a96c8a8e56600af663aaaf57e3c736bbf246
refs/heads/master
2023-06-25T22:57:30.153197
2021-07-21T15:08:18
2021-07-21T15:08:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,236
cpp
#include "SARibbonGalleryItem.h" #include "SARibbonGalleryGroup.h" SARibbonGalleryItem::SARibbonGalleryItem() : m_flsgs(Qt::ItemIsEnabled|Qt::ItemIsSelectable) , m_action(nullptr) { } SARibbonGalleryItem::SARibbonGalleryItem(const QIcon& icon) : m_flsgs(Qt::ItemIsEnabled|Qt::ItemIsSelectable) , m_action(nullptr) { setIcon(icon); } SARibbonGalleryItem::SARibbonGalleryItem(QAction *act) : m_flsgs(Qt::ItemIsEnabled|Qt::ItemIsSelectable) { setAction(act); } SARibbonGalleryItem::~SARibbonGalleryItem() { } void SARibbonGalleryItem::setData(int role, const QVariant& data) { m_datas[role] = data; } QVariant SARibbonGalleryItem::data(int role) const { if (m_action) { switch (role) { case Qt::DisplayRole: return (m_action->text()); case Qt::ToolTipRole: return (m_action->toolTip()); case Qt::DecorationRole: return (m_action->icon()); default: break; } } return (m_datas.value(role)); } void SARibbonGalleryItem::setText(const QString& text) { setData(Qt::DisplayRole, text); } QString SARibbonGalleryItem::text() const { if (m_action) { return (m_action->text()); } return (data(Qt::DisplayRole).toString()); } void SARibbonGalleryItem::setToolTip(const QString& text) { setData(Qt::ToolTipRole, text); } QString SARibbonGalleryItem::toolTip() const { if (m_action) { return (m_action->toolTip()); } return (data(Qt::ToolTipRole).toString()); } void SARibbonGalleryItem::setIcon(const QIcon& ico) { setData(Qt::DecorationRole, ico); } QIcon SARibbonGalleryItem::icon() const { if (m_action) { return (m_action->icon()); } return (qvariant_cast<QIcon>(data(Qt::DecorationRole))); } bool SARibbonGalleryItem::isSelectable() const { return (m_flsgs & Qt::ItemIsSelectable); } void SARibbonGalleryItem::setSelectable(bool isSelectable) { if (isSelectable) { m_flsgs |= Qt::ItemIsSelectable; }else { m_flsgs = (m_flsgs & (~Qt::ItemIsSelectable)); } } bool SARibbonGalleryItem::isEnable() const { if (m_action) { return (m_action->isEnabled()); } return (m_flsgs & Qt::ItemIsEnabled); } void SARibbonGalleryItem::setEnable(bool isEnable) { if (m_action) { m_action->setEnabled(isEnable); } if (isEnable) { m_flsgs |= Qt::ItemIsEnabled; }else { m_flsgs = (m_flsgs & (~Qt::ItemIsEnabled)); } } void SARibbonGalleryItem::setFlags(Qt::ItemFlags flag) { m_flsgs = flag; if (m_action) { m_action->setEnabled(flag & Qt::ItemIsEnabled); } } Qt::ItemFlags SARibbonGalleryItem::flags() const { return (m_flsgs); } void SARibbonGalleryItem::setAction(QAction *act) { m_action = act; if (act->isEnabled()) { m_flsgs |= Qt::ItemIsEnabled; }else { m_flsgs = (m_flsgs & (~Qt::ItemIsEnabled)); } } QAction *SARibbonGalleryItem::action() { return (m_action); }
[ "czy.t@163.com" ]
czy.t@163.com
3f3db046f18c3d6c860f4c708e4280011c5228cd
63bd5d5d6597b0057e4401a7235b4065b7f8bbb2
/hash_code.cpp
764d80f46e3435a83f30d7116f0791d63f9fda64
[]
no_license
laksh-ayy/hash_code
22cb720818ed173827ad7033d21c4eb83b2fce7e
e34f420f8faa439abc5d2814b7f7a60cfb88e2b3
refs/heads/master
2021-01-08T07:52:37.939594
2020-02-20T19:28:55
2020-02-20T19:28:55
241,962,268
0
0
null
null
null
null
UTF-8
C++
false
false
533
cpp
#include<iostream> using namespace std; int main(){ int totalbooks, totallibraries, deadline; cin>>totalbooks>>totallibraries>>deadline; int score[totalbooks]; for(int i=0; i<totalbooks; i++){ cin>>score[i]; } int sign[totallibraries], books[totallibraries], scan[totallibraries], listofbooks[totallibraries][]; for(int i =0; i<totallibraries; i++){ cin>>books[i]>>sign[i]>>scan[i]; for(int j=0; j<books[i]; j++){ cin>>listofbooks[i][j]; } } return 0; }
[ "36309535+laksh-ayy@users.noreply.github.com" ]
36309535+laksh-ayy@users.noreply.github.com
265d300c1526a7c6281e2ab694c45e6ada079797
ece5f0f44b4f91d09af81d74c232852919488cf8
/2021/CAMP_1/Function_Recursion/Sport.cpp
67f6973f4a5d5f9f7ace25878b71a90ba4b5ea09
[]
no_license
Phatteronyyz/POSN
57020f27065fe106d49be8b6f89248da0ccd21e9
3c6fa467377d367104476208801993697a15bd4d
refs/heads/main
2023-04-30T03:42:57.386892
2021-05-16T13:23:57
2021-05-16T13:23:57
351,687,620
2
0
null
null
null
null
UTF-8
C++
false
false
432
cpp
#include<bits/stdc++.h> using namespace std; int k,w,l,a[10000000]; void sport(int w,int l,int st){ if(w==k||l==k){ for(int i=0;i<st;i++){ if(a[i]==1) printf("W "); else printf("L "); } printf("\n"); return ; } a[st]=1; sport(w+1,l,st+1); a[st]=2; sport(w,l+1,st+1); } int main() { scanf("%d %d %d",&k,&w,&l); sport(w,l,0); return 0; }
[ "pattarawat123.k@gmail.com" ]
pattarawat123.k@gmail.com
bc3b1e461882f9c56ad1f42bb5467f1a556ce1a6
83a32a0e5c512ae18ccc02d8a08e83aceddd64b7
/p106/p106/p106.cpp
c55b942faa9079c492953600343fb892a899961f
[]
no_license
daelong/C
de2f50f6f1c3a589dcc0b02b14a9232555574bee
6e843a7f9978b00eb5dd9696847119bd48847086
refs/heads/master
2020-05-02T03:18:12.245668
2019-03-26T06:14:22
2019-03-26T06:14:22
177,725,032
0
0
null
null
null
null
UHC
C++
false
false
199
cpp
#include <stdio.h> int main(void) { double rad; double area; printf("원의 반지름 입력: "); scanf("%f", &rad); area = rad*rad*3.1415; printf("원의 넓이: %f \n", area); return 0; }
[ "dleogus0569@naver.com" ]
dleogus0569@naver.com
e89bba1ce9a2f93314039f0769522c2fa87c4aae
d85fe3cb534847e61a62dc358ad4e0ad938f00fc
/head4.h
17ffad96ec61f0af45bda7b4552742ff323c8a93
[]
no_license
utkarshsimha/partitions-generator
ba2ae8a21424ed6e12984665a3cd178c079a1eaf
b98d71423a366bbda0fe0fef760b01a42d75823f
refs/heads/master
2020-05-29T13:09:07.193893
2014-10-23T07:49:21
2014-10-23T07:49:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
603
h
#include<iostream> //#include<set> //#include<ctime> //#include<vector> //#include<stdlib.h> //#include<iomanip> //#include<climits> //#include<memory> using namespace std; class List; int num; int dim; int * p[100000]; int res[100]; int * possible[100000]; long double sum[100]; int *a; int *d; //vector<int*> possibleNodes; void addpart(int, int, int, shared_ptr<List>); bool ispossible(int**, int *, int); bool checkPartition(int**, int *, int); bool compare(int *, int *); int *copyNode(int *); int *node(int); void printPartition(int **, int ); void printNode(int *); void nplus(int **, int, int);
[ "utkarshsimha@gmail.com" ]
utkarshsimha@gmail.com
67231726f0ca7fbed954f90b8d0b77be4dba0dcd
6c77fbfaffc6203e709db11cfb92c27c8fcc3169
/Plugins/GOAPer/Source/GOAPer/Private/FSM/DoActionState.cpp
e2e0bba0fddcb52f091b75e3f75cc79b46e4561d
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
cthulhurlyeh/GOAPer
d02b375c95ca3bc52a8ded8a7f6c10ce003ebb15
9d6323357e391db2a481ee91bc027d5402f63727
refs/heads/master
2021-01-21T06:24:06.414993
2017-02-24T08:22:40
2017-02-24T08:23:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
980
cpp
#include "GOAPer.h" #include "DoActionState.h" #include "IdleState.h" #include "GOAPAction.h" #include "GOAPAIController.h" DoActionState::DoActionState() { eState = EGOAPFSMState::DoAction; } DoActionState::~DoActionState() { } TSharedPtr<GOAPFSMState> DoActionState::Tick(AGOAPAIController& controller, float DeltaTime) { // Check if the preconditions are still valid, we need to invalidate the plan if (!controller.CurrentAction->ArePreconditionsSatisfied(&controller)) { controller.CurrentAction = nullptr; controller.ActionQueue.Empty(); return MakeShareable(new IdleState()); } // Otherwise, crack on with it if (controller.CurrentAction->Execute(&controller, DeltaTime)) { // And clear the action controller.CurrentAction = nullptr; // Then return to idle return MakeShareable(new IdleState()); } return nullptr; } void DoActionState::Enter(AGOAPAIController& controller) { } FString DoActionState::ToString() { return TEXT("DoAction"); }
[ "chrisashworth@appzeit.com" ]
chrisashworth@appzeit.com
8b7f432a60cf6086720803d94d1a0d21c0eadbb3
752a01cd9a431bfe1abe4ebb03fd8619e4efdad1
/BlueLight.ino
98a7e7e1f3a8b3623b9bbd2218a7841d383b07ed
[]
no_license
smargonz/arduino-bluetooth
6dd2d1efb0c8ec6297f13753c60241128d8aa6e2
428a0ac45540213d364abe3d7ed5f21605e3847f
refs/heads/master
2021-01-18T17:17:25.767270
2012-06-19T00:20:21
2012-06-19T00:20:21
4,687,805
1
0
null
null
null
null
UTF-8
C++
false
false
1,115
ino
//=============================// // BLUELIGHT v1 // // Arduino+Android+BT // // // // Authors: // // dpeter (GH: sarenji) // // smargonz // //=============================// #include <Servo.h> #define LED 3 #define servoPin 4 #define SERVO_DELAY 1500 Servo myservo; void setup() { Serial.begin(9600); pinMode(LED, OUTPUT); } void loop() { if ( Serial.available() ) { Serial.println("BT Data received: "); char c = Serial.read(); switch( c ) { case( 'L' ): Serial.print( "ON" ); digitalWrite( LED, HIGH ); myservo.attach(servoPin); myservo.write(-180); delay(SERVO_DELAY); myservo.detach(); break; case( 'D' ): Serial.print( "OFF" ); digitalWrite( LED, LOW ); myservo.attach(servoPin); myservo.write(180); delay(SERVO_DELAY); myservo.detach(); break; default: //Serial.print( "..." ); break; } } }
[ "smar.gonz@gmail.com" ]
smar.gonz@gmail.com
5d4cebc7a63f975477af920a4319ba41facf16fb
89a8387418064c0523a8fffb5535086f2a2882e9
/lhop_v1/src/utils/zlib_compress.h
3229019397630c8cbb39d21c351860507ff4cf58
[]
no_license
pacman-project/LHOP
5704cdd8577537fb3135c18404d1e3c5a77c7caa
9a82fddc5befaade28ba1cdfc8567092cd318cad
refs/heads/master
2021-03-30T17:51:01.994612
2014-05-20T22:53:11
2014-05-20T22:53:11
11,122,668
0
0
null
null
null
null
UTF-8
C++
false
false
2,901
h
#ifndef _ZLIB_COMPRESS_H_ #define _ZLIB_COMPRESS_H_ #include <string> #include <iostream> #if defined WIN32 | defined WIN64 #include <typeinfo.h> #else #include <typeinfo> #endif #include <zlib.h> using namespace std; // zlib (de)compression class /////////////////////////////////////////////////////////////////////////////// class zlib_compress { private: static const int CHUNK = 512*1024; // 512 KB (bigger chunk better compression) // buffer for compression char* buffer_in; char* buffer_out; // current position of empty data on buffer_in (starts with 0) if using for write_to_buf_and_compress // else current possition of data to be read in buffer_out if using read_to_buf_and_decompress int buffer_pos; // zlib compression level int compression_level; z_stream zlib_stream; istream* in; ostream* out; // compresses chunk from buffer_in and writes it to this->out stream void compress_chunk(int flush_flag); // reades chunk data from this->in stream to buffer_in and // returns decompressed in buffer_out void decompress_chunk(int flush_flag); public: /** * This method must be called before any (de)compression begins * It will call inflateInit or deflateInit and prepare all necessary buffers. * Same function is used for compression and decompression. * Set argument decompress = true for decompression otherwise compression is used (default). */ void begin_compression(bool decompress = false); /** * Writes data of 'size' to intermediate buffer (buffer_in) and * when buffer is full it compresses it to buffer_out and writes whole buffer to underlying stream. */ void write_to_buf_and_compress(const char* ptr, streamsize size); /** * Reads data from underlying stream to intermedeiate buffer (buffer_out) and * decompresses its to buffer_in. Data of size 'size' is then copied from buffer_in to ptr. */ void read_to_buf_and_decompress(const char* ptr, streamsize size); /** * Method must be called on end of (de)compression so it will deallocate memory * and make call to inflateEnd or deflateEnd. * Same function is used for compression and decompression. * Set argument decompress = true for decompression otherwise compression is used (default). */ void end_compression(bool decompress = false); public: zlib_compress(int zlib_compression_level = Z_NO_COMPRESSION); virtual ~zlib_compress(); // MUST set input stream from where data will be read to intermediate buffer void set_istream(istream* pin) { this->in = pin; } // MUST set output stream from where data will be writen from compressed data buffer void set_ostream(ostream* pout) { this->out = pout; } // gets level of compression (uses default z_lib constants for compression level) int get_compression_level() { return this->compression_level; } }; #endif
[ "meteozay@gmail.com" ]
meteozay@gmail.com
132440c415d84d2b2f94c65ebd11f3d26199d67d
309975d60e30260f2e02d11e71eaaf6e08b93659
/Modules/TArc/Sources/TArc/WindowSubSystem/Private/QtEvents.h
16fa6e815f32236a7a660dcb2d817cd6ed46d6e0
[]
permissive
BlitzModder/dava.engine
e83b038a9d24b37c00b095e83ffdfd8cd497823c
0c7a16e627fc0d12309250d6e5e207333b35361e
refs/heads/development
2023-03-15T12:30:32.342501
2018-02-19T11:09:02
2018-02-19T11:09:02
122,161,150
4
3
BSD-3-Clause
2018-02-20T06:00:07
2018-02-20T06:00:07
null
UTF-8
C++
false
false
601
h
#pragma once #include "TArc/WindowSubSystem/QtTArcEvents.h" #include <QEvent> namespace DAVA { class QtOverlayWidgetVisibilityChange : public QEvent { public: QtOverlayWidgetVisibilityChange(bool isVisible_); bool IsVisible() const; private: bool isVisible = false; }; inline QtOverlayWidgetVisibilityChange::QtOverlayWidgetVisibilityChange(bool isVisible_) : QEvent(static_cast<QEvent::Type>(EventsTable::OverlayWidgetVisibilityChange)) , isVisible(isVisible_) { } inline bool QtOverlayWidgetVisibilityChange::IsVisible() const { return isVisible; } } // namespace DAVA
[ "m_molokovskih@wargaming.net" ]
m_molokovskih@wargaming.net
bd19e3906f479fe0023edc16d434810526e5c753
ccc4de8d95eeba1eac0151ebca3f234ff6801f50
/InimigoHorneetle.cpp
f26175872e6f7de30e38864e55339c1c99a5a8ce
[]
no_license
luiz734/Jogo-VS
9b9962693f0e07de21db42bc240665f69be9f053
f43feca6a5db0e2044eeea7eda976a6f89d6e2a9
refs/heads/master
2020-07-18T00:55:56.468807
2019-09-03T17:42:42
2019-09-03T17:42:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,020
cpp
#include "InimigoHorneetle.h" using namespace Personagens; InimigoHorneetle::InimigoHorneetle(int posX, int posY) { setTamX(100*2); setTamY(100*2); setPosX(posX*48); setPosY(posY*48); setGravidade(3.0); setInercia(5.0); setForcaPulo(30.0); setVelMax(25.0); setMaxPulo(1); valor = 5000; vidas = 15; sprite.setOrigin(73, 126); setTextura("files/Horneetle.png", 2, 0, 0, 150, 150, false); } InimigoHorneetle::~InimigoHorneetle() { } void InimigoHorneetle::andar() { int aux = getContAnimacao()%851; if(aux == 100) setAceleracaoX(2*direcao); else if(aux == 170) direcao *= -1; else if(aux == 270) setAceleracaoX(2*direcao); else if(aux == 340) direcao *= -1; else if(aux == 440) setVelocidadeX(25*direcao); else if(aux == 490) direcao *= -1; else if(aux == 540) { setVelocidadeX(25*direcao); setVelocidadeY(-55); } else if(aux == 590) direcao *= -1; else if(aux == 690) setAceleracaoX(4*direcao); else if(aux == 730) direcao *= -1; else if(aux == 750) setAceleracaoX(4*direcao); else if(aux == 790) direcao *= -1; else if(aux == 810) setAceleracaoX(4*direcao); else if(aux == 850) direcao *= -1; } void InimigoHorneetle::movimentar() { andar(); calcMovimentar(); setPosicaoEnt(); animar(); } void InimigoHorneetle::animar() { sprite.setScale(2*direcao, 2); if(getVelocidadeX() == 0) { animacao.top = 0; if(getContAnimacao()%6 == 0) { animacao.left = 150*(getContAnimacao()%30/6); } } else { animacao.top = 150; if(getContAnimacao()%4 == 0) { animacao.left = 150*(getContAnimacao()%28/4); } } setContAnimacao(getContAnimacao() + 1); sprite.setTextureRect(animacao); }
[ "mateusmat@hotmail.com" ]
mateusmat@hotmail.com
6fdb8ca60ec5a023eae2dc18454c03e55c84b904
0345f0058ba2294fa29a886194df79d4f0c9c894
/p7/IndentStream.h
8ef70cce8b69a8e39f862f713767d7c26f7cd72f
[]
no_license
atomek88/cpp-metaprogramming
0d90e28a4590c6ff0bc7b150d2296db36df832a8
8bd149ad0fd12510bfd9b0a234a963b24072c464
refs/heads/master
2020-04-14T14:14:32.346915
2019-01-09T18:06:29
2019-01-09T18:06:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,202
h
#ifndef INDENT_STREAM_H # define INDENT_STREAM_H // Created by Tomasz Michalik on 5/12/18. #include <streambuf> #include <iostream> #include <fstream> using std::ostream; using std::streambuf; namespace cspp51044 { using std::ostream; using std::streambuf; using std::cout; using std::cin; using std::endl; class IndentStreamBuf : public streambuf { public: IndentStreamBuf(ostream &stream) : wrappedStream(stream), isLineStart(true), myIndent(0) {} virtual int overflow(int outputVal) override { if(outputVal == '\n') { isLineStart = true; } else if(isLineStart) { for(size_t i = 0; i < myIndent; i++) { wrappedStream << ' '; } isLineStart = false; } wrappedStream << static_cast<char>(outputVal); return outputVal; } protected: ostream &wrappedStream; bool isLineStart; public: size_t myIndent; }; class IndentStream : public ostream { public: IndentStream(ostream &wrappedStream) : ostream(new IndentStreamBuf(wrappedStream)) { } ~IndentStream() { delete this->rdbuf(); } }; ostream &indent(ostream &ostr); ostream &unindent(ostream &ostr); } #endif
[ "michalik@cs.uchicago.edu" ]
michalik@cs.uchicago.edu
c533fd7a56cb4c429ae534a92c1146048d748a3e
2dc10608952230c5ab29bd226cc9ead57c5b8705
/red-ball-core/src/main/c++/red_ball/core/actions/Sequence.hpp
fefa9850747968f7c0ccfcbc30be0f2cfea46ce4
[]
no_license
mikosz/red-ball
a6fadf915dab59ede658a0cacfcff1f00b7dca87
e5ac6a993a153242f00473089176b1806b97668c
refs/heads/master
2020-05-04T22:27:56.529294
2013-02-13T23:01:48
2013-02-13T23:01:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
514
hpp
#ifndef RED_BALL_CORE_ACTIONS_SEQUENCE_HPP_ #define RED_BALL_CORE_ACTIONS_SEQUENCE_HPP_ #include <queue> #include "Action.hpp" namespace red_ball { namespace core { namespace actions { class Sequence : public Action { public: bool act(utils::Timer::Seconds* timeLeft); void enqueue(ActionPtr action); private: typedef std::queue<ActionPtr> Actions; Actions actions_; }; } // namespace actions } // namespace core } // namespace red_ball #endif /* RED_BALL_CORE_ACTIONS_SEQUENCE_HPP_ */
[ "mikoszrrr@gmail.com" ]
mikoszrrr@gmail.com
fdb1884bd23778e9d98291159518eaa13605f5cb
64ce9d40c49d9008ef660c2f9d1671be140a5005
/d04/ex04/MiningBarge.cpp
60eb635bc1c862a47c5ed5672414d28934520ed4
[]
no_license
fmallaba/cpp
33b4ac79a9800ab1e1c7fc24dd258b86b1468f69
79674e3b6e09b5b83952a71ff3d0590dd6d72108
refs/heads/master
2021-04-09T14:40:29.060979
2018-04-09T17:04:24
2018-04-09T17:04:24
125,549,843
0
0
null
null
null
null
UTF-8
C++
false
false
464
cpp
#include "MiningBarge.hpp" MiningBarge::MiningBarge(void) { this->_count = 0; return; } MiningBarge::~MiningBarge(void) { for (int i = 0; i < this->_count; ++i) { delete this->_lasers[i]; } } void MiningBarge::equip(IMiningLaser* laser) { if (this->_count < 4) { this->_lasers[this->_count] = laser; this->_count++; } } void MiningBarge::mine(IAsteroid* ast) const { for (int i = 0; i < this->_count; ++i) { this->_lasers[i]->mine(ast); } }
[ "bomcrimea@gmail.com" ]
bomcrimea@gmail.com
59b29cbaa39e48ab4825436ae71dd3fef0976d9a
63ea75c1cd144db8434e7b84ab5b3d1baa986ac7
/run/tutorials/multiphase/interDyMFoam/ras/sloshingTank2D3DoF/system/controlDict
33e425ab6d1d660c2d95a64cc219235d6c1f6b3a
[]
no_license
houkensjtu/interFOAM
86a3f88891db4d47eb6ac033515b51bf2a63e069
8040064d075718d4259a207a30c216974bf8a8af
refs/heads/master
2016-09-06T15:02:08.625024
2013-03-11T12:40:10
2013-03-11T12:40:10
8,702,790
1
1
null
null
null
null
UTF-8
C++
false
false
2,042
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 2.1.x | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "system"; object controlDict; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // application interDyMFoam; startFrom startTime; startTime 0; stopAt endTime; endTime 40; deltaT 0.01; writeControl adjustableRunTime; writeInterval 0.05; purgeWrite 0; writeFormat ascii; writePrecision 6; writeCompression compressed; timeFormat general; timePrecision 6; runTimeModifiable yes; adjustTimeStep yes; maxCo 0.5; maxAlphaCo 0.5; maxDeltaT 1; functions { probes { type probes; functionObjectLibs ("libsampling.so"); outputControl outputTime; probeLocations ( ( 0 9.95 19.77 ) ( 0 -9.95 19.77 ) ); fields ( p ); } wallPressure { type surfaces; functionObjectLibs ("libsampling.so"); outputControl outputTime; surfaceFormat raw; fields ( p ); surfaces ( walls { type patch; patches (walls); triangulate false; } ); } } // ************************************************************************* //
[ "houkensjtu@gmail.com" ]
houkensjtu@gmail.com
bc65982fc861b8e95636485e230a6774bc0210cb
d61aa7d638e3fe949e940f01f293b004017753a3
/poj/Archives/2112/7059093_WA.cpp
9eb7ad2d639fdee0f54eb79c6fd58046622b7768
[]
no_license
dementrock/acm
e50468504f20aa0831eb8609e1b65160c5fddb3d
a539707ca3c0b78e4160fdf2acad1b0125fa8211
refs/heads/master
2016-09-06T01:18:36.769494
2012-11-06T01:21:41
2012-11-06T01:21:41
2,811,681
0
0
null
null
null
null
UTF-8
C++
false
false
2,350
cpp
#include<stdio.h> #include<stdlib.h> #include<string.h> int v[300][300],map[300][300],f[300][300],s,t,oo=99999999; int list[300],layer[300],que[300]; int path[300],judge,minf=oo; bool found=false,vis[300]; int counter[300]; int n,k,c,m; inline int max(int a, int b){return a>b?a:b;} void init() { scanf("%d%d%d",&k,&c,&m); n=k+c; for(int i=1;i<=n;++i) for(int j=1;j<=n;++j) scanf("%d",&map[i][j]); memset(f,0x77,sizeof(f)); } void spfa(int s) { memset(que,0,sizeof(que)); memset(vis,false,sizeof(vis)); int closed=0,open=1,now; que[1]=s,vis[s]=true,f[s][s]=0; while(closed<open) { closed=closed%n+1; now=que[closed]; for(int i=1;i<=n;++i) if(map[now][i]&&map[now][i]+f[s][now]<f[s][i]) { f[s][i]=map[now][i]+f[s][now]; if(!vis[i]) { open=open%n+1; que[open]=i; vis[i]=true; } } vis[now]=false; } } void aug(int now) { int i,tmp=minf,minl=t-1; if(now==t) { found=true; judge+=minf; return; } for(i=s;i<=t;++i) { if(v[now][i]>0) { if(layer[now]==layer[i]+1) { if(v[now][i]<minf) minf=v[now][i]; aug(i); if(layer[s]>=t) return; if(found) break; minf=tmp; } if(layer[i]<minl) minl=layer[i]; } } if(!found) { --counter[layer[now]]; if(counter[layer[now]]==0) layer[s]=t; layer[now]=minl+1; ++counter[layer[now]]; } else { v[now][i]-=minf; v[i][now]+=minf; } } bool sap(int cut) { memset(v,0,sizeof(v)); memset(list,0,sizeof(list)); memset(layer,0,sizeof(layer)); memset(path,0,sizeof(path)); memset(counter,0,sizeof(counter)); for(int i=1;i<=k;++i) v[s][i]=m; for(int i=1;i<=k;++i) for(int j=k+1;j<=k+c;++j) if(f[i][j]<=cut) v[i][j]=1; for(int i=k+1;i<=k+c;++i) v[i][t]=1; judge=0; counter[0]=t+1; while(layer[s]<t) { minf=oo; found=false; aug(s); } return judge==c; } void work() { int maxl=oo; s=0,t=n+1; for(int i=1;i<=k;++i) spfa(i); // for(int i=1;i<=n;++i) for(int j=1;j<=n;++j) if(f[i][j]<1000000) maxl=max(maxl,f[i][j]); int left=0,right=maxl,ans,mid; while(left<right-1) { mid=left+right>>1; if(sap(mid)) right=mid; else left=mid; } while(sap(right)) { ans=right; --right; } printf("%d\n",ans); } int main() { init(); work(); return 0; }
[ "dementrock@gmail.com" ]
dementrock@gmail.com
4f4e7b6f84b171048b507578d38981ead14bd5dd
c14500adc5ce57e216123138e8ab55c3e9310953
/Geo/MVertexRTree.h
eec986c5561a85aa2c5f0b4abf742d6fe7722b93
[ "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.0-or-later", "LicenseRef-scancode-generic-exception", "GPL-1.0-or-later", "LicenseRef-scancode-proprietary-license", "GPL-2.0-only", "GPL-2.0-or-later", "LicenseRef-scancode-other-copyleft", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ResonanceGroup/GMSH304
8c8937ed3839c9c85ab31c7dd2a37568478dc08e
a07a210131ee7db8c0ea5e22386270ceab44a816
refs/heads/master
2020-03-14T23:58:48.751856
2018-05-02T13:51:09
2018-05-02T13:51:09
131,857,142
0
1
MIT
2018-05-02T13:51:10
2018-05-02T13:47:05
null
UTF-8
C++
false
false
2,081
h
// Gmsh - Copyright (C) 1997-2017 C. Geuzaine, J.-F. Remacle // // See the LICENSE.txt file for license information. Please report all // bugs and problems to the public mailing list <gmsh@onelab.info>. #ifndef _MVERTEX_RTREE_ #define _MVERTEX_RTREE_ #include <vector> #include "GmshMessage.h" #include "MVertex.h" #include "rtree.h" // Stores MVertex pointers in an R-Tree so we can query unique vertices by their // coordinates, up to a prescribed tolerance. class MVertexRTree{ private: RTree<MVertex*, double, 3, double> *_rtree; double _tol; static bool rtree_callback(MVertex *v, void *ctx) { MVertex **out = static_cast<MVertex**>(ctx); *out = v; return false; // we're done searching } public: MVertexRTree(double tolerance = 1.e-8) { _rtree = new RTree<MVertex*, double, 3, double>(); _tol = tolerance; } ~MVertexRTree() { _rtree->RemoveAll(); delete _rtree; } MVertex *insert(MVertex *v, bool warnIfExists=false) { MVertex *out; double _min[3] = {v->x() - _tol, v->y() - _tol, v->z() - _tol}; double _max[3] = {v->x() + _tol, v->y() + _tol, v->z() + _tol}; if(!_rtree->Search(_min, _max, rtree_callback, &out)){ _rtree->Insert(_min, _max, v); return 0; } else{ if(warnIfExists) Msg::Warning("Vertex %d (%.16g, %.16g, %.16g) already exists in the " "mesh with tolerance %g", v->getNum(), v->x(), v->y(), v->z(), _tol); return out; } } int insert(std::vector<MVertex*> &v, bool warnIfExists=false) { int num = 0; for(unsigned int i = 0; i < v.size(); i++) num += (insert(v[i], warnIfExists) ? 1 : 0); return num; // number of vertices not inserted } MVertex *find(double x, double y, double z) { MVertex *out; double _min[3] = {x - _tol, y - _tol, z - _tol}; double _max[3] = {x + _tol, y + _tol, z + _tol}; if(_rtree->Search(_min, _max, rtree_callback, &out)) return out; return 0; } unsigned int size() { return _rtree->Count(); } }; #endif
[ "=phillipmobley2@gmail.com" ]
=phillipmobley2@gmail.com
566958ccff26914941edf68f656dfe65f9b4a9c3
5ef9a73d2a3c4fb36d54dd0f60e141e2d44f10d6
/samples/Projects/Shooter - Test/Source/Shooter/Test/IsolatedComponent0694.h
de5002410227a19e20713ca295cb04d48dfb3d09
[]
no_license
djbhsys/UE4
1d822fcc96b7bb14d96d6d0ee53c82d27d8d6347
5eb798e6084a5436c476170d65ffb218bf0bba33
refs/heads/master
2023-07-18T04:44:20.430929
2021-08-22T12:43:10
2021-08-22T12:43:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
575
h
#pragma once #include "Components/ActorComponent.h" #include "IsolatedComponent0694.generated.h" UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) ) class UIsolatedComponent0694 : public UActorComponent { GENERATED_BODY() public: UIsolatedComponent0694(); protected: virtual void BeginPlay() override; virtual void Gurke(); public: virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override; protected: UPROPERTY(EditAnywhere, Category = General) float MovementRadius; };
[ "the.prompt@gmail.com" ]
the.prompt@gmail.com
8b6259d02782e6ba9586c63c8b7291d02ec1f049
af67e87d94680a68b597edf29da4e16a61a09108
/source/ShareUtils.cpp
23e8aed902c332cae8321f8d321f60236bf69c95
[]
no_license
refaqtor/BeShare
0080b21eeff0fa3c81cf48b505a557d3f5cfc00a
58031882f15a724e8c946ed80bc0d10541b8f645
refs/heads/master
2020-12-02T00:36:56.031179
2018-09-29T21:57:07
2018-10-01T06:01:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,253
cpp
#include <stdio.h> #include <app/Message.h> #include "ShareUtils.h" #include "util/StringTokenizer.h" namespace beshare { void GetByteSizeString(int64 v, char * buf) { // special hack to give file sizes in kilobytes, etc. for readability if (v > (1024LL*1024LL*1024LL*1024LL)) sprintf(buf, "%.2fTB", ((double)v)/(1024LL*1024LL*1024LL*1024LL)); else if (v > (1024LL*1024LL*1024LL)) sprintf(buf, "%.2fGB", ((double)v)/(1024LL*1024LL*1024LL)); else if (v > (1024LL*1024LL)) sprintf(buf, "%.2fMB", ((double)v)/(1024LL*1024LL)); else if (v > (1024LL*10LL)) sprintf(buf, "%LiKB", v/1024LL); else sprintf(buf, "%Li bytes", v); } void GetTimeString(time_t when, char * buf) { struct tm * now = localtime(&when); sprintf(buf, "%02i/%02i/%04i %02i:%02i:%02i", now->tm_mon+1, now->tm_mday, now->tm_year+1900, now->tm_hour, now->tm_min, now->tm_sec); } status_t SaveColorToMessage(const char * fn, const rgb_color & col, BMessage & msg) { return msg.AddInt32(fn, (((uint32)col.red)<<24) | (((uint32)col.green)<<16) | (((uint32)col.blue)<<8) | (((uint32)col.alpha)<<0)); } // Restores the given color from the given BMessage with the given field name. status_t RestoreColorFromMessage(const char * fn, rgb_color & retCol, const BMessage & msg, uint32 which) { uint32 val; if (msg.FindInt32(fn, which, (int32*)&val) == B_NO_ERROR) { retCol.red = (val >> 24); retCol.green = (val >> 16); retCol.blue = (val >> 8); retCol.alpha = (val >> 0); return B_NO_ERROR; } else return B_ERROR; } String SubstituteLabelledURLs(const String & shortName) { String ret; const char * url = NULL; // if non-NULL, we've found a URL const char * space = NULL; // if non-NULL, we've found the space after the URL too const char * left = NULL; // if non-NULL, we've found the left bracket for the label bool lastWasSpace = true; // If true, the last char we looked at was a space for (const char * sn = shortName(); *sn != '\0'; sn++) { char c = *sn; bool isSpace = ((c == ' ')||(c == '\t')); if (url) { if (space) { if (left) { if (c == ']') { // We've completed the sequence... so now dump just the label part, // plus any spaces that preceded the left bracket. String temp = (left+1); ret += temp.Substring(0, sn-(left+1)); url = space = left = NULL; } } else if (isSpace == false) { if (c == '[') left = sn; else { // Oops, guess there is no label, so dump out what we got String temp = url; ret += temp.Substring(0, 1+sn-url); url = space = NULL; } } } else if (isSpace) space = sn; } else { if ((lastWasSpace)&&(IsLink(sn))) url = sn; else ret += c; } lastWasSpace = isSpace; } if (url) ret += url; // dump any leftovers return ret; } bool IsLink(const char * str) { return ((strncmp(str, "file://", 7) == 0) || (strncmp(str, "http://", 7) == 0) || (strncmp(str, "https://", 8) == 0) || (strncmp(str, "mailto:", 7) == 0) || (strncmp(str, "ftp://", 6) == 0) || (strncmp(str, "audio://", 8) == 0) || (strncmp(str, "beshare:", 8) == 0) || (strncmp(str, "priv:", 5) == 0) || (strncmp(str, "share:", 6) == 0)); } }; // end namespace beshare
[ "modeenf@116878ba-14ce-4675-8531-4544a6312073" ]
modeenf@116878ba-14ce-4675-8531-4544a6312073