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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e50d9cfad9edb01379fd99896c4ffe3c308c3357
|
600df3590cce1fe49b9a96e9ca5b5242884a2a70
|
/chrome/browser/extensions/process_manager_browsertest.cc
|
4027593333f320b8a3dd916c17fc1d5fd848e795
|
[
"BSD-3-Clause"
] |
permissive
|
metux/chromium-suckless
|
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
|
72a05af97787001756bae2511b7985e61498c965
|
refs/heads/orig
| 2022-12-04T23:53:58.681218
| 2017-04-30T10:59:06
| 2017-04-30T23:35:58
| 89,884,931
| 5
| 3
|
BSD-3-Clause
| 2022-11-23T20:52:53
| 2017-05-01T00:09:08
| null |
UTF-8
|
C++
| false
| false
| 53,111
|
cc
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stddef.h>
#include <memory>
#include <utility>
#include "base/callback.h"
#include "base/macros.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/test/histogram_tester.h"
#include "chrome/browser/extensions/browser_action_test_util.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/test_extension_dir.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/extensions/extension_process_policy.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/guest_view/browser/test_guest_view_manager.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/browser_side_navigation_policy.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_utils.h"
#include "extensions/browser/app_window/app_window.h"
#include "extensions/browser/app_window/app_window_registry.h"
#include "extensions/browser/process_manager.h"
#include "extensions/common/permissions/permissions_data.h"
#include "extensions/common/value_builder.h"
#include "extensions/test/background_page_watcher.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
namespace extensions {
namespace {
void AddFrameToSet(std::set<content::RenderFrameHost*>* frames,
content::RenderFrameHost* rfh) {
if (rfh->IsRenderFrameLive())
frames->insert(rfh);
}
GURL CreateBlobURL(content::RenderFrameHost* frame,
const std::string& content) {
std::string blob_url_string;
EXPECT_TRUE(ExecuteScriptAndExtractString(
frame,
"var blob = new Blob(['<html><body>" + content + "</body></html>'],\n"
" {type: 'text/html'});\n"
"domAutomationController.send(URL.createObjectURL(blob));\n",
&blob_url_string));
GURL blob_url(blob_url_string);
EXPECT_TRUE(blob_url.is_valid());
EXPECT_TRUE(blob_url.SchemeIsBlob());
return blob_url;
}
GURL CreateFileSystemURL(content::RenderFrameHost* frame,
const std::string& content) {
std::string filesystem_url_string;
EXPECT_TRUE(ExecuteScriptAndExtractString(
frame,
"var blob = new Blob(['<html><body>" + content + "</body></html>'],\n"
" {type: 'text/html'});\n"
"window.webkitRequestFileSystem(TEMPORARY, blob.size, fs => {\n"
" fs.root.getFile('foo.html', {create: true}, file => {\n"
" file.createWriter(writer => {\n"
" writer.write(blob);\n"
" writer.onwriteend = () => {\n"
" domAutomationController.send(file.toURL());\n"
" }\n"
" });\n"
" });\n"
"});\n",
&filesystem_url_string));
GURL filesystem_url(filesystem_url_string);
EXPECT_TRUE(filesystem_url.is_valid());
EXPECT_TRUE(filesystem_url.SchemeIsFileSystem());
return filesystem_url;
}
std::string GetTextContent(content::RenderFrameHost* frame) {
std::string result;
EXPECT_TRUE(ExecuteScriptAndExtractString(
frame, "domAutomationController.send(document.body.innerText)", &result));
return result;
}
// Helper to send a postMessage from |sender| to |opener| via window.opener,
// wait for a reply, and verify the response. Defines its own message event
// handlers.
void VerifyPostMessageToOpener(content::RenderFrameHost* sender,
content::RenderFrameHost* opener) {
EXPECT_TRUE(
ExecuteScript(opener,
"window.addEventListener('message', function(event) {\n"
" event.source.postMessage(event.data, '*');\n"
"});"));
EXPECT_TRUE(
ExecuteScript(sender,
"window.addEventListener('message', function(event) {\n"
" window.domAutomationController.send(event.data);\n"
"});"));
std::string result;
EXPECT_TRUE(ExecuteScriptAndExtractString(
sender, "opener.postMessage('foo', '*');", &result));
EXPECT_EQ("foo", result);
}
} // namespace
// Takes a snapshot of all frames upon construction. When Wait() is called, a
// MessageLoop is created and Quit when all previously recorded frames are
// either present in the tab, or deleted. If a navigation happens between the
// construction and the Wait() call, then this logic ensures that all obsolete
// RenderFrameHosts have been destructed when Wait() returns.
// See also the comment at ProcessManagerBrowserTest::NavigateToURL.
class NavigationCompletedObserver : public content::WebContentsObserver {
public:
explicit NavigationCompletedObserver(content::WebContents* web_contents)
: content::WebContentsObserver(web_contents),
message_loop_runner_(new content::MessageLoopRunner) {
web_contents->ForEachFrame(
base::Bind(&AddFrameToSet, base::Unretained(&frames_)));
}
void Wait() {
if (!AreAllFramesInTab())
message_loop_runner_->Run();
}
void RenderFrameDeleted(content::RenderFrameHost* rfh) override {
if (frames_.erase(rfh) != 0 && message_loop_runner_->loop_running() &&
AreAllFramesInTab())
message_loop_runner_->Quit();
}
private:
// Check whether all frames that were recorded at the construction of this
// class are still part of the tab.
bool AreAllFramesInTab() {
std::set<content::RenderFrameHost*> current_frames;
web_contents()->ForEachFrame(
base::Bind(&AddFrameToSet, base::Unretained(¤t_frames)));
for (content::RenderFrameHost* frame : frames_) {
if (current_frames.find(frame) == current_frames.end())
return false;
}
return true;
}
std::set<content::RenderFrameHost*> frames_;
scoped_refptr<content::MessageLoopRunner> message_loop_runner_;
DISALLOW_COPY_AND_ASSIGN(NavigationCompletedObserver);
};
// Exists as a browser test because ExtensionHosts are hard to create without
// a real browser.
class ProcessManagerBrowserTest : public ExtensionBrowserTest {
public:
// Create an extension with web-accessible frames and an optional background
// page.
const Extension* CreateExtension(const std::string& name,
bool has_background_process) {
std::unique_ptr<TestExtensionDir> dir(new TestExtensionDir());
DictionaryBuilder manifest;
manifest.Set("name", name)
.Set("version", "1")
.Set("manifest_version", 2)
// To allow ExecuteScript* to work.
.Set("content_security_policy",
"script-src 'self' 'unsafe-eval'; object-src 'self'")
.Set("sandbox",
DictionaryBuilder()
.Set("pages", ListBuilder().Append("sandboxed.html").Build())
.Build())
.Set("web_accessible_resources", ListBuilder().Append("*").Build());
if (has_background_process) {
manifest.Set("background",
DictionaryBuilder().Set("page", "bg.html").Build());
dir->WriteFile(FILE_PATH_LITERAL("bg.html"),
"<iframe id='bgframe' src='empty.html'></iframe>");
}
dir->WriteFile(FILE_PATH_LITERAL("blank_iframe.html"),
"<iframe id='frame0' src='about:blank'></iframe>");
dir->WriteFile(FILE_PATH_LITERAL("srcdoc_iframe.html"),
"<iframe id='frame0' srcdoc='Hello world'></iframe>");
dir->WriteFile(FILE_PATH_LITERAL("two_iframes.html"),
"<iframe id='frame1' src='empty.html'></iframe>"
"<iframe id='frame2' src='empty.html'></iframe>");
dir->WriteFile(FILE_PATH_LITERAL("sandboxed.html"), "Some sandboxed page");
dir->WriteFile(FILE_PATH_LITERAL("empty.html"), "");
dir->WriteManifest(manifest.ToJSON());
const Extension* extension = LoadExtension(dir->UnpackedPath());
EXPECT_TRUE(extension);
temp_dirs_.push_back(std::move(dir));
return extension;
}
// ui_test_utils::NavigateToURL sometimes returns too early: It returns as
// soon as the StopLoading notification has been triggered. This does not
// imply that RenderFrameDeleted was called, so the test may continue too
// early and fail when ProcessManager::GetAllFrames() returns too many frames
// (namely frames that are in the process of being deleted). To work around
// this problem, we also wait until all previous frames have been deleted.
void NavigateToURL(const GURL& url) {
NavigationCompletedObserver observer(
browser()->tab_strip_model()->GetActiveWebContents());
ui_test_utils::NavigateToURL(browser(), url);
// Wait until the last RenderFrameHosts are deleted. This wait doesn't take
// long.
observer.Wait();
}
size_t IfExtensionsIsolated(size_t if_enabled, size_t if_disabled) {
return content::AreAllSitesIsolatedForTesting() ||
IsIsolateExtensionsEnabled()
? if_enabled
: if_disabled;
}
content::WebContents* OpenPopup(content::RenderFrameHost* opener,
const GURL& url) {
content::WindowedNotificationObserver popup_observer(
chrome::NOTIFICATION_TAB_ADDED,
content::NotificationService::AllSources());
EXPECT_TRUE(ExecuteScript(
opener, "window.popup = window.open('" + url.spec() + "')"));
popup_observer.Wait();
content::WebContents* popup =
browser()->tab_strip_model()->GetActiveWebContents();
WaitForLoadStop(popup);
EXPECT_EQ(url, popup->GetMainFrame()->GetLastCommittedURL());
return popup;
}
private:
std::vector<std::unique_ptr<TestExtensionDir>> temp_dirs_;
};
// Test that basic extension loading creates the appropriate ExtensionHosts
// and background pages.
IN_PROC_BROWSER_TEST_F(ProcessManagerBrowserTest,
ExtensionHostCreation) {
ProcessManager* pm = ProcessManager::Get(profile());
// We start with no background hosts.
ASSERT_EQ(0u, pm->background_hosts().size());
ASSERT_EQ(0u, pm->GetAllFrames().size());
// Load an extension with a background page.
scoped_refptr<const Extension> extension =
LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("none"));
ASSERT_TRUE(extension.get());
// Process manager gains a background host.
EXPECT_EQ(1u, pm->background_hosts().size());
EXPECT_EQ(1u, pm->GetAllFrames().size());
EXPECT_TRUE(pm->GetBackgroundHostForExtension(extension->id()));
EXPECT_TRUE(pm->GetSiteInstanceForURL(extension->url()));
EXPECT_EQ(1u, pm->GetRenderFrameHostsForExtension(extension->id()).size());
EXPECT_FALSE(pm->IsBackgroundHostClosing(extension->id()));
EXPECT_EQ(0, pm->GetLazyKeepaliveCount(extension.get()));
// Unload the extension.
UnloadExtension(extension->id());
// Background host disappears.
EXPECT_EQ(0u, pm->background_hosts().size());
EXPECT_EQ(0u, pm->GetAllFrames().size());
EXPECT_FALSE(pm->GetBackgroundHostForExtension(extension->id()));
EXPECT_TRUE(pm->GetSiteInstanceForURL(extension->url()));
EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension->id()).size());
EXPECT_FALSE(pm->IsBackgroundHostClosing(extension->id()));
EXPECT_EQ(0, pm->GetLazyKeepaliveCount(extension.get()));
}
// Test that loading an extension with a browser action does not create a
// background page and that clicking on the action creates the appropriate
// ExtensionHost.
// Disabled due to flake, see http://crbug.com/315242
IN_PROC_BROWSER_TEST_F(ProcessManagerBrowserTest,
DISABLED_PopupHostCreation) {
ProcessManager* pm = ProcessManager::Get(profile());
// Load an extension with the ability to open a popup but no background
// page.
scoped_refptr<const Extension> popup =
LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("popup"));
ASSERT_TRUE(popup.get());
// No background host was added.
EXPECT_EQ(0u, pm->background_hosts().size());
EXPECT_EQ(0u, pm->GetAllFrames().size());
EXPECT_FALSE(pm->GetBackgroundHostForExtension(popup->id()));
EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(popup->id()).size());
EXPECT_TRUE(pm->GetSiteInstanceForURL(popup->url()));
EXPECT_FALSE(pm->IsBackgroundHostClosing(popup->id()));
EXPECT_EQ(0, pm->GetLazyKeepaliveCount(popup.get()));
// Simulate clicking on the action to open a popup.
BrowserActionTestUtil test_util(browser());
content::WindowedNotificationObserver frame_observer(
content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
content::NotificationService::AllSources());
// Open popup in the first extension.
test_util.Press(0);
frame_observer.Wait();
ASSERT_TRUE(test_util.HasPopup());
// We now have a view, but still no background hosts.
EXPECT_EQ(0u, pm->background_hosts().size());
EXPECT_EQ(1u, pm->GetAllFrames().size());
EXPECT_FALSE(pm->GetBackgroundHostForExtension(popup->id()));
EXPECT_EQ(1u, pm->GetRenderFrameHostsForExtension(popup->id()).size());
EXPECT_TRUE(pm->GetSiteInstanceForURL(popup->url()));
EXPECT_FALSE(pm->IsBackgroundHostClosing(popup->id()));
EXPECT_EQ(0, pm->GetLazyKeepaliveCount(popup.get()));
}
// Content loaded from http://hlogonemlfkgpejgnedahbkiabcdhnnn should not
// interact with an installed extension with that ID. Regression test
// for bug 357382.
IN_PROC_BROWSER_TEST_F(ProcessManagerBrowserTest, HttpHostMatchingExtensionId) {
ProcessManager* pm = ProcessManager::Get(profile());
// We start with no background hosts.
ASSERT_EQ(0u, pm->background_hosts().size());
ASSERT_EQ(0u, pm->GetAllFrames().size());
// Load an extension with a background page.
scoped_refptr<const Extension> extension =
LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("none"));
// Set up a test server running at http://[extension-id]
ASSERT_TRUE(extension.get());
const std::string& aliased_host = extension->id();
host_resolver()->AddRule(aliased_host, "127.0.0.1");
ASSERT_TRUE(embedded_test_server()->Start());
GURL url =
embedded_test_server()->GetURL("/extensions/test_file_with_body.html");
GURL::Replacements replace_host;
replace_host.SetHostStr(aliased_host);
url = url.ReplaceComponents(replace_host);
// Load a page from the test host in a new tab.
ui_test_utils::NavigateToURLWithDisposition(
browser(), url, WindowOpenDisposition::NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
// Sanity check that there's no bleeding between the extension and the tab.
content::WebContents* tab_web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
EXPECT_EQ(url, tab_web_contents->GetVisibleURL());
EXPECT_FALSE(pm->GetExtensionForWebContents(tab_web_contents))
<< "Non-extension content must not have an associated extension";
ASSERT_EQ(1u, pm->GetRenderFrameHostsForExtension(extension->id()).size());
content::WebContents* extension_web_contents =
content::WebContents::FromRenderFrameHost(
*pm->GetRenderFrameHostsForExtension(extension->id()).begin());
EXPECT_TRUE(extension_web_contents->GetSiteInstance() !=
tab_web_contents->GetSiteInstance());
EXPECT_TRUE(pm->GetSiteInstanceForURL(extension->url()) !=
tab_web_contents->GetSiteInstance());
EXPECT_TRUE(pm->GetBackgroundHostForExtension(extension->id()));
}
IN_PROC_BROWSER_TEST_F(ProcessManagerBrowserTest, NoBackgroundPage) {
ASSERT_TRUE(embedded_test_server()->Start());
ProcessManager* pm = ProcessManager::Get(profile());
const Extension* extension =
LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("messaging")
.AppendASCII("connect_nobackground"));
ASSERT_TRUE(extension);
// The extension has no background page.
EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension->id()).size());
// Start in a non-extension process, then navigate to an extension process.
NavigateToURL(embedded_test_server()->GetURL("/empty.html"));
EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension->id()).size());
const GURL extension_url = extension->url().Resolve("manifest.json");
NavigateToURL(extension_url);
EXPECT_EQ(1u, pm->GetRenderFrameHostsForExtension(extension->id()).size());
NavigateToURL(GURL("about:blank"));
EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension->id()).size());
ui_test_utils::NavigateToURLWithDisposition(
browser(), extension_url, WindowOpenDisposition::NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
EXPECT_EQ(1u, pm->GetRenderFrameHostsForExtension(extension->id()).size());
}
// Tests whether frames are correctly classified. Non-extension frames should
// never appear in the list. Top-level extension frames should always appear.
// Child extension frames should only appear if it is hosted in an extension
// process (i.e. if the top-level frame is an extension page, or if OOP frames
// are enabled for extensions).
IN_PROC_BROWSER_TEST_F(ProcessManagerBrowserTest, FrameClassification) {
const Extension* extension1 = CreateExtension("Extension 1", false);
const Extension* extension2 = CreateExtension("Extension 2", true);
embedded_test_server()->ServeFilesFromDirectory(extension1->path());
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kExt1TwoFramesUrl(extension1->url().Resolve("two_iframes.html"));
const GURL kExt1EmptyUrl(extension1->url().Resolve("empty.html"));
const GURL kExt2TwoFramesUrl(extension2->url().Resolve("two_iframes.html"));
const GURL kExt2EmptyUrl(extension2->url().Resolve("empty.html"));
ProcessManager* pm = ProcessManager::Get(profile());
// 1 background page + 1 frame in background page from Extension 2.
BackgroundPageWatcher(pm, extension2).WaitForOpen();
EXPECT_EQ(2u, pm->GetAllFrames().size());
EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension1->id()).size());
EXPECT_EQ(2u, pm->GetRenderFrameHostsForExtension(extension2->id()).size());
ExecuteScriptInBackgroundPageNoWait(extension2->id(),
"setTimeout(window.close, 0)");
BackgroundPageWatcher(pm, extension2).WaitForClose();
EXPECT_EQ(0u, pm->GetAllFrames().size());
EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension2->id()).size());
NavigateToURL(embedded_test_server()->GetURL("/two_iframes.html"));
EXPECT_EQ(0u, pm->GetAllFrames().size());
content::WebContents* tab =
browser()->tab_strip_model()->GetActiveWebContents();
// Tests extension frames in non-extension page.
EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame1", kExt1EmptyUrl));
EXPECT_EQ(IfExtensionsIsolated(1, 0),
pm->GetRenderFrameHostsForExtension(extension1->id()).size());
EXPECT_EQ(IfExtensionsIsolated(1, 0), pm->GetAllFrames().size());
EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame2", kExt2EmptyUrl));
EXPECT_EQ(IfExtensionsIsolated(1, 0),
pm->GetRenderFrameHostsForExtension(extension2->id()).size());
EXPECT_EQ(IfExtensionsIsolated(2, 0), pm->GetAllFrames().size());
// Tests non-extension page in extension frame.
NavigateToURL(kExt1TwoFramesUrl);
// 1 top-level + 2 child frames from Extension 1.
EXPECT_EQ(3u, pm->GetAllFrames().size());
EXPECT_EQ(3u, pm->GetRenderFrameHostsForExtension(extension1->id()).size());
EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension2->id()).size());
EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame1",
embedded_test_server()
->GetURL("/empty.html")));
// 1 top-level + 1 child frame from Extension 1.
EXPECT_EQ(2u, pm->GetRenderFrameHostsForExtension(extension1->id()).size());
EXPECT_EQ(2u, pm->GetAllFrames().size());
EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame1", kExt1EmptyUrl));
// 1 top-level + 2 child frames from Extension 1.
EXPECT_EQ(3u, pm->GetAllFrames().size());
EXPECT_EQ(3u, pm->GetRenderFrameHostsForExtension(extension1->id()).size());
// Load a frame from another extension.
EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame1", kExt2EmptyUrl));
// 1 top-level + 1 child frame from Extension 1,
// 1 child frame from Extension 2.
EXPECT_EQ(IfExtensionsIsolated(3, 2), pm->GetAllFrames().size());
EXPECT_EQ(2u, pm->GetRenderFrameHostsForExtension(extension1->id()).size());
EXPECT_EQ(IfExtensionsIsolated(1, 0),
pm->GetRenderFrameHostsForExtension(extension2->id()).size());
// Destroy all existing frames by navigating to another extension.
NavigateToURL(extension2->url().Resolve("empty.html"));
EXPECT_EQ(1u, pm->GetAllFrames().size());
EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension1->id()).size());
EXPECT_EQ(1u, pm->GetRenderFrameHostsForExtension(extension2->id()).size());
// Test about:blank and about:srcdoc child frames.
NavigateToURL(extension2->url().Resolve("srcdoc_iframe.html"));
// 1 top-level frame + 1 child frame from Extension 2.
EXPECT_EQ(2u, pm->GetAllFrames().size());
EXPECT_EQ(2u, pm->GetRenderFrameHostsForExtension(extension2->id()).size());
NavigateToURL(extension2->url().Resolve("blank_iframe.html"));
// 1 top-level frame + 1 child frame from Extension 2.
EXPECT_EQ(2u, pm->GetAllFrames().size());
EXPECT_EQ(2u, pm->GetRenderFrameHostsForExtension(extension2->id()).size());
// Sandboxed frames are not viewed as extension frames.
EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame0",
extension2->url()
.Resolve("sandboxed.html")));
// 1 top-level frame from Extension 2.
EXPECT_EQ(1u, pm->GetAllFrames().size());
EXPECT_EQ(1u, pm->GetRenderFrameHostsForExtension(extension2->id()).size());
NavigateToURL(extension2->url().Resolve("sandboxed.html"));
EXPECT_EQ(0u, pm->GetAllFrames().size());
EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension2->id()).size());
// Test nested frames (same extension).
NavigateToURL(kExt2TwoFramesUrl);
// 1 top-level + 2 child frames from Extension 2.
EXPECT_EQ(3u, pm->GetAllFrames().size());
EXPECT_EQ(3u, pm->GetRenderFrameHostsForExtension(extension2->id()).size());
EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame1", kExt2TwoFramesUrl));
// 1 top-level + 2 child frames from Extension 1,
// 2 child frames in frame1 from Extension 2.
EXPECT_EQ(5u, pm->GetAllFrames().size());
EXPECT_EQ(5u, pm->GetRenderFrameHostsForExtension(extension2->id()).size());
// The extension frame from the other extension should not be classified as an
// extension (unless out-of-process frames are enabled).
EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame1", kExt1EmptyUrl));
// 1 top-level + 1 child frames from Extension 2,
// 1 child frame from Extension 1.
EXPECT_EQ(IfExtensionsIsolated(3, 2), pm->GetAllFrames().size());
EXPECT_EQ(IfExtensionsIsolated(1, 0),
pm->GetRenderFrameHostsForExtension(extension1->id()).size());
EXPECT_EQ(2u, pm->GetRenderFrameHostsForExtension(extension2->id()).size());
EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame2", kExt1TwoFramesUrl));
// 1 top-level + 1 child frames from Extension 2,
// 1 child frame + 2 child frames in frame2 from Extension 1.
EXPECT_EQ(IfExtensionsIsolated(5, 1), pm->GetAllFrames().size());
EXPECT_EQ(IfExtensionsIsolated(4, 0),
pm->GetRenderFrameHostsForExtension(extension1->id()).size());
EXPECT_EQ(1u, pm->GetRenderFrameHostsForExtension(extension2->id()).size());
// Crash tab where the top-level frame is an extension frame.
content::CrashTab(tab);
EXPECT_EQ(0u, pm->GetAllFrames().size());
EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension1->id()).size());
EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension2->id()).size());
// Now load an extension page and a non-extension page...
ui_test_utils::NavigateToURLWithDisposition(
browser(), kExt1EmptyUrl, WindowOpenDisposition::NEW_BACKGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
NavigateToURL(embedded_test_server()->GetURL("/two_iframes.html"));
EXPECT_EQ(1u, pm->GetAllFrames().size());
// ... load an extension frame in the non-extension process
EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame1", kExt1EmptyUrl));
EXPECT_EQ(IfExtensionsIsolated(2, 1),
pm->GetRenderFrameHostsForExtension(extension1->id()).size());
// ... and take down the tab. The extension process is not part of the tab,
// so it should be kept alive (minus the frames that died).
content::CrashTab(tab);
EXPECT_EQ(1u, pm->GetAllFrames().size());
EXPECT_EQ(1u, pm->GetRenderFrameHostsForExtension(extension1->id()).size());
}
// Verify correct keepalive count behavior on network request events.
// Regression test for http://crbug.com/535716.
IN_PROC_BROWSER_TEST_F(ProcessManagerBrowserTest, KeepaliveOnNetworkRequest) {
// Load an extension with a lazy background page.
scoped_refptr<const Extension> extension =
LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("lazy_background_page")
.AppendASCII("broadcast_event"));
ASSERT_TRUE(extension.get());
ProcessManager* pm = ProcessManager::Get(profile());
ProcessManager::FrameSet frames =
pm->GetRenderFrameHostsForExtension(extension->id());
ASSERT_EQ(1u, frames.size());
// Keepalive count at this point is unpredictable as there may be an
// outstanding event dispatch. We use the current keepalive count as a
// reliable baseline for future expectations.
int baseline_keepalive = pm->GetLazyKeepaliveCount(extension.get());
// Simulate some network events. This test assumes no other network requests
// are pending, i.e., that there are no conflicts with the fake request IDs
// we're using. This should be a safe assumption because LoadExtension should
// wait for loads to complete, and we don't run the message loop otherwise.
content::RenderFrameHost* frame_host = *frames.begin();
pm->OnNetworkRequestStarted(frame_host, 1);
EXPECT_EQ(baseline_keepalive + 1, pm->GetLazyKeepaliveCount(extension.get()));
pm->OnNetworkRequestDone(frame_host, 1);
EXPECT_EQ(baseline_keepalive, pm->GetLazyKeepaliveCount(extension.get()));
// Simulate only a request completion for this ID and ensure it doesn't result
// in keepalive decrement.
pm->OnNetworkRequestDone(frame_host, 2);
EXPECT_EQ(baseline_keepalive, pm->GetLazyKeepaliveCount(extension.get()));
}
IN_PROC_BROWSER_TEST_F(ProcessManagerBrowserTest, ExtensionProcessReuse) {
const size_t kNumExtensions = 3;
content::RenderProcessHost::SetMaxRendererProcessCount(kNumExtensions - 1);
ProcessManager* pm = ProcessManager::Get(profile());
std::set<int> processes;
std::set<const Extension*> installed_extensions;
// Create 3 extensions, which is more than the process limit.
for (int i = 1; i <= static_cast<int>(kNumExtensions); ++i) {
const Extension* extension =
CreateExtension(base::StringPrintf("Extension %d", i), true);
installed_extensions.insert(extension);
ExtensionHost* extension_host =
pm->GetBackgroundHostForExtension(extension->id());
EXPECT_EQ(extension->url(),
extension_host->host_contents()->GetSiteInstance()->GetSiteURL());
processes.insert(extension_host->render_process_host()->GetID());
}
EXPECT_EQ(kNumExtensions, installed_extensions.size());
if (content::AreAllSitesIsolatedForTesting()) {
EXPECT_EQ(kNumExtensions, processes.size()) << "Extension process reuse is "
"expected to be disabled in "
"--site-per-process.";
} else {
EXPECT_LT(processes.size(), kNumExtensions)
<< "Expected extension process reuse, but none happened.";
}
// Interact with each extension background page by setting and reading back
// the cookie. This would fail for one of the two extensions in a shared
// process, if that process is locked to a single origin. This is a regression
// test for http://crbug.com/600441.
for (const Extension* extension : installed_extensions) {
content::DOMMessageQueue queue;
ExecuteScriptInBackgroundPageNoWait(
extension->id(),
"document.cookie = 'extension_cookie';"
"window.domAutomationController.send(document.cookie);");
std::string message;
ASSERT_TRUE(queue.WaitForMessage(&message));
EXPECT_EQ(message, "\"extension_cookie\"");
}
}
// Test that navigations to blob: and filesystem: URLs with extension origins
// are disallowed when initiated from non-extension processes. See
// https://crbug.com/645028 and https://crbug.com/644426.
IN_PROC_BROWSER_TEST_F(ProcessManagerBrowserTest,
NestedURLNavigationsToExtensionBlocked) {
// Disabling web security is necessary to test the browser enforcement;
// without it, the loads in this test would be blocked by
// SecurityOrigin::canDisplay() as invalid local resource loads.
PrefService* prefs = browser()->profile()->GetPrefs();
prefs->SetBoolean(prefs::kWebKitWebSecurityEnabled, false);
// Create a simple extension without a background page.
const Extension* extension = CreateExtension("Extension", false);
embedded_test_server()->ServeFilesFromDirectory(extension->path());
ASSERT_TRUE(embedded_test_server()->Start());
// Navigate main tab to a web page with two web iframes. There should be no
// extension frames yet.
NavigateToURL(embedded_test_server()->GetURL("/two_iframes.html"));
ProcessManager* pm = ProcessManager::Get(profile());
EXPECT_EQ(0u, pm->GetAllFrames().size());
EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension->id()).size());
content::WebContents* tab =
browser()->tab_strip_model()->GetActiveWebContents();
// Navigate first subframe to an extension URL. With --isolate-extensions,
// this will go into a new extension process.
const GURL extension_url(extension->url().Resolve("empty.html"));
EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame1", extension_url));
EXPECT_EQ(IfExtensionsIsolated(1, 0),
pm->GetRenderFrameHostsForExtension(extension->id()).size());
EXPECT_EQ(IfExtensionsIsolated(1, 0), pm->GetAllFrames().size());
content::RenderFrameHost* main_frame = tab->GetMainFrame();
content::RenderFrameHost* extension_frame = ChildFrameAt(main_frame, 0);
// Validate that permissions have been granted for the extension scheme
// to the process of the extension iframe.
content::ChildProcessSecurityPolicy* policy =
content::ChildProcessSecurityPolicy::GetInstance();
EXPECT_TRUE(policy->CanRequestURL(
extension_frame->GetProcess()->GetID(),
GURL("blob:chrome-extension://some-extension-id/some-guid")));
EXPECT_TRUE(policy->CanRequestURL(
main_frame->GetProcess()->GetID(),
GURL("blob:chrome-extension://some-extension-id/some-guid")));
EXPECT_TRUE(policy->CanRequestURL(
extension_frame->GetProcess()->GetID(),
GURL("filesystem:chrome-extension://some-extension-id/some-path")));
EXPECT_TRUE(policy->CanRequestURL(
main_frame->GetProcess()->GetID(),
GURL("filesystem:chrome-extension://some-extension-id/some-path")));
EXPECT_TRUE(policy->CanRequestURL(
extension_frame->GetProcess()->GetID(),
GURL("chrome-extension://some-extension-id/resource.html")));
EXPECT_TRUE(policy->CanRequestURL(
main_frame->GetProcess()->GetID(),
GURL("chrome-extension://some-extension-id/resource.html")));
if (IsIsolateExtensionsEnabled()) {
EXPECT_TRUE(policy->CanCommitURL(
extension_frame->GetProcess()->GetID(),
GURL("blob:chrome-extension://some-extension-id/some-guid")));
EXPECT_FALSE(policy->CanCommitURL(
main_frame->GetProcess()->GetID(),
GURL("blob:chrome-extension://some-extension-id/some-guid")));
EXPECT_TRUE(policy->CanCommitURL(
extension_frame->GetProcess()->GetID(),
GURL("chrome-extension://some-extension-id/resource.html")));
EXPECT_FALSE(policy->CanCommitURL(
main_frame->GetProcess()->GetID(),
GURL("chrome-extension://some-extension-id/resource.html")));
EXPECT_TRUE(policy->CanCommitURL(
extension_frame->GetProcess()->GetID(),
GURL("filesystem:chrome-extension://some-extension-id/some-path")));
EXPECT_FALSE(policy->CanCommitURL(
main_frame->GetProcess()->GetID(),
GURL("filesystem:chrome-extension://some-extension-id/some-path")));
}
// Open a new about:blank popup from main frame. This should stay in the web
// process.
content::WebContents* popup =
OpenPopup(main_frame, GURL(url::kAboutBlankURL));
EXPECT_NE(popup, tab);
ASSERT_EQ(2, browser()->tab_strip_model()->count());
EXPECT_EQ(IfExtensionsIsolated(1, 0),
pm->GetRenderFrameHostsForExtension(extension->id()).size());
EXPECT_EQ(IfExtensionsIsolated(1, 0), pm->GetAllFrames().size());
// Create valid blob and filesystem URLs in the extension's origin.
url::Origin extension_origin(extension_frame->GetLastCommittedOrigin());
GURL blob_url(CreateBlobURL(extension_frame, "foo"));
EXPECT_EQ(extension_origin, url::Origin(blob_url));
GURL filesystem_url(CreateFileSystemURL(extension_frame, "foo"));
EXPECT_EQ(extension_origin, url::Origin(filesystem_url));
// Navigate the popup to each nested URL with extension origin.
GURL nested_urls[] = {blob_url, filesystem_url};
for (size_t i = 0; i < arraysize(nested_urls); i++) {
content::TestNavigationObserver observer(popup);
EXPECT_TRUE(ExecuteScript(
popup, "location.href = '" + nested_urls[i].spec() + "';"));
observer.Wait();
// This is a top-level navigation that should be blocked since it
// originates from a non-extension process. Ensure that the error page
// doesn't commit an extension URL or origin.
EXPECT_NE(nested_urls[i], popup->GetLastCommittedURL());
EXPECT_FALSE(extension_origin.IsSameOriginWith(
popup->GetMainFrame()->GetLastCommittedOrigin()));
EXPECT_NE("foo", GetTextContent(popup->GetMainFrame()));
EXPECT_EQ(IfExtensionsIsolated(1, 0),
pm->GetRenderFrameHostsForExtension(extension->id()).size());
EXPECT_EQ(IfExtensionsIsolated(1, 0), pm->GetAllFrames().size());
}
// Navigate second subframe to each nested URL from the main frame (i.e.,
// from non-extension process). This should be blocked in
// --isolate-extensions, but allowed without --isolate-extensions due to
// unblessed extension frames.
//
// TODO(alexmos): This is also temporarily allowed under PlzNavigate, because
// currently this particular blocking happens in
// ChromeContentBrowserClientExtensionsPart::ShouldAllowOpenURL, which isn't
// triggered below under PlzNavigate (since there'll be no transfer). Once
// the blob/filesystem URL checks in ExtensionNavigationThrottle are updated
// to apply to all frames and not just main frames, the PlzNavigate exception
// below can be removed. See https://crbug.com/661324.
for (size_t i = 0; i < arraysize(nested_urls); i++) {
EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame2", nested_urls[i]));
content::RenderFrameHost* second_frame = ChildFrameAt(main_frame, 1);
if (IsIsolateExtensionsEnabled() &&
!content::IsBrowserSideNavigationEnabled()) {
EXPECT_NE(nested_urls[i], second_frame->GetLastCommittedURL());
EXPECT_FALSE(extension_origin.IsSameOriginWith(
second_frame->GetLastCommittedOrigin()));
EXPECT_NE("foo", GetTextContent(second_frame));
EXPECT_EQ(IfExtensionsIsolated(1, 0),
pm->GetRenderFrameHostsForExtension(extension->id()).size());
EXPECT_EQ(IfExtensionsIsolated(1, 0), pm->GetAllFrames().size());
} else {
EXPECT_EQ(nested_urls[i], second_frame->GetLastCommittedURL());
EXPECT_EQ(extension_origin, second_frame->GetLastCommittedOrigin());
EXPECT_EQ("foo", GetTextContent(second_frame));
EXPECT_EQ(IfExtensionsIsolated(2, 0),
pm->GetRenderFrameHostsForExtension(extension->id()).size());
EXPECT_EQ(IfExtensionsIsolated(2, 0), pm->GetAllFrames().size());
}
EXPECT_TRUE(
content::NavigateIframeToURL(tab, "frame2", GURL(url::kAboutBlankURL)));
}
}
// Test that navigations to blob: and filesystem: URLs with extension origins
// are allowed when initiated from extension processes. See
// https://crbug.com/645028 and https://crbug.com/644426.
IN_PROC_BROWSER_TEST_F(ProcessManagerBrowserTest,
NestedURLNavigationsToExtensionAllowed) {
// Create a simple extension without a background page.
const Extension* extension = CreateExtension("Extension", false);
embedded_test_server()->ServeFilesFromDirectory(extension->path());
ASSERT_TRUE(embedded_test_server()->Start());
// Navigate main tab to an extension URL with a blank subframe.
const GURL extension_url(extension->url().Resolve("blank_iframe.html"));
NavigateToURL(extension_url);
ProcessManager* pm = ProcessManager::Get(profile());
EXPECT_EQ(2u, pm->GetAllFrames().size());
EXPECT_EQ(2u, pm->GetRenderFrameHostsForExtension(extension->id()).size());
content::WebContents* tab =
browser()->tab_strip_model()->GetActiveWebContents();
content::RenderFrameHost* main_frame = tab->GetMainFrame();
// Create blob and filesystem URLs in the extension's origin.
url::Origin extension_origin(main_frame->GetLastCommittedOrigin());
GURL blob_url(CreateBlobURL(main_frame, "foo"));
EXPECT_EQ(extension_origin, url::Origin(blob_url));
GURL filesystem_url(CreateFileSystemURL(main_frame, "foo"));
EXPECT_EQ(extension_origin, url::Origin(filesystem_url));
// From the main frame, navigate its subframe to each nested URL. This
// should be allowed and should stay in the extension process.
GURL nested_urls[] = {blob_url, filesystem_url};
for (size_t i = 0; i < arraysize(nested_urls); i++) {
EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame0", nested_urls[i]));
content::RenderFrameHost* child = ChildFrameAt(main_frame, 0);
EXPECT_EQ(nested_urls[i], child->GetLastCommittedURL());
EXPECT_EQ(extension_origin, child->GetLastCommittedOrigin());
EXPECT_EQ("foo", GetTextContent(child));
EXPECT_EQ(2u, pm->GetRenderFrameHostsForExtension(extension->id()).size());
EXPECT_EQ(2u, pm->GetAllFrames().size());
}
// From the main frame, create a blank popup and navigate it to each nested
// URL. This should also be allowed, since the navigation originated from an
// extension process.
for (size_t i = 0; i < arraysize(nested_urls); i++) {
content::WebContents* popup =
OpenPopup(main_frame, GURL(url::kAboutBlankURL));
EXPECT_NE(popup, tab);
content::TestNavigationObserver observer(popup);
EXPECT_TRUE(ExecuteScript(
popup, "location.href = '" + nested_urls[i].spec() + "';"));
observer.Wait();
EXPECT_EQ(nested_urls[i], popup->GetLastCommittedURL());
EXPECT_EQ(extension_origin,
popup->GetMainFrame()->GetLastCommittedOrigin());
EXPECT_EQ("foo", GetTextContent(popup->GetMainFrame()));
EXPECT_EQ(3 + i,
pm->GetRenderFrameHostsForExtension(extension->id()).size());
EXPECT_EQ(3 + i, pm->GetAllFrames().size());
}
}
// Test that navigations to blob: and filesystem: URLs with extension origins
// are disallowed in an unprivileged, non-guest web process when the extension
// origin corresponds to a Chrome app with the "webview" permission. See
// https://crbug.com/656752. These requests should still be allowed inside
// actual <webview> guest processes created by a Chrome app; this is checked in
// WebViewTest.Shim_TestBlobURL.
IN_PROC_BROWSER_TEST_F(ProcessManagerBrowserTest,
NestedURLNavigationsToAppBlocked) {
// TODO(alexmos): Re-enable this test for PlzNavigate after tightening
// nested URL blocking for apps with the "webview" permission in
// ExtensionNavigationThrottle and removing the corresponding check from
// ChromeExtensionsNetworkDelegate. The latter is incompatible with
// PlzNavigate.
if (content::IsBrowserSideNavigationEnabled())
return;
// Disabling web security is necessary to test the browser enforcement;
// without it, the loads in this test would be blocked by
// SecurityOrigin::canDisplay() as invalid local resource loads.
PrefService* prefs = browser()->profile()->GetPrefs();
prefs->SetBoolean(prefs::kWebKitWebSecurityEnabled, false);
// Load a simple app that has the "webview" permission. The app will also
// open a <webview> when it's loaded.
ASSERT_TRUE(embedded_test_server()->Start());
base::FilePath dir;
PathService::Get(chrome::DIR_TEST_DATA, &dir);
dir = dir.AppendASCII("extensions")
.AppendASCII("platform_apps")
.AppendASCII("web_view")
.AppendASCII("simple");
const Extension* app = LoadAndLaunchApp(dir);
EXPECT_TRUE(app->permissions_data()->HasAPIPermission(
extensions::APIPermission::kWebView));
auto app_windows = AppWindowRegistry::Get(browser()->profile())
->GetAppWindowsForApp(app->id());
EXPECT_EQ(1u, app_windows.size());
content::WebContents* app_tab = (*app_windows.begin())->web_contents();
content::RenderFrameHost* app_rfh = app_tab->GetMainFrame();
url::Origin app_origin(app_rfh->GetLastCommittedOrigin());
EXPECT_EQ(url::Origin(app->url()), app_rfh->GetLastCommittedOrigin());
// Wait for the app's guest WebContents to load.
guest_view::TestGuestViewManager* guest_manager =
static_cast<guest_view::TestGuestViewManager*>(
guest_view::TestGuestViewManager::FromBrowserContext(
browser()->profile()));
content::WebContents* guest = guest_manager->WaitForSingleGuestCreated();
// There should be two extension frames in ProcessManager: the app's main
// page and the background page.
ProcessManager* pm = ProcessManager::Get(profile());
EXPECT_EQ(2u, pm->GetAllFrames().size());
EXPECT_EQ(2u, pm->GetRenderFrameHostsForExtension(app->id()).size());
// Create valid blob and filesystem URLs in the app's origin.
GURL blob_url(CreateBlobURL(app_rfh, "foo"));
EXPECT_EQ(app_origin, url::Origin(blob_url));
GURL filesystem_url(CreateFileSystemURL(app_rfh, "foo"));
EXPECT_EQ(app_origin, url::Origin(filesystem_url));
// Create a new tab, unrelated to the app, and navigate it to a web URL.
chrome::NewTab(browser());
content::WebContents* web_tab =
browser()->tab_strip_model()->GetActiveWebContents();
GURL web_url(embedded_test_server()->GetURL("/title1.html"));
ui_test_utils::NavigateToURL(browser(), web_url);
EXPECT_NE(web_tab, app_tab);
EXPECT_NE(web_tab->GetMainFrame()->GetProcess(), app_rfh->GetProcess());
// The web process shouldn't have permission to request URLs in the app's
// origin, but the guest process should.
content::ChildProcessSecurityPolicy* policy =
content::ChildProcessSecurityPolicy::GetInstance();
EXPECT_FALSE(policy->HasSpecificPermissionForOrigin(
web_tab->GetRenderProcessHost()->GetID(), app_origin));
EXPECT_TRUE(policy->HasSpecificPermissionForOrigin(
guest->GetRenderProcessHost()->GetID(), app_origin));
// Try navigating the web tab to each nested URL with the app's origin. This
// should be blocked.
GURL nested_urls[] = {blob_url, filesystem_url};
for (size_t i = 0; i < arraysize(nested_urls); i++) {
content::TestNavigationObserver observer(web_tab);
EXPECT_TRUE(ExecuteScript(
web_tab, "location.href = '" + nested_urls[i].spec() + "';"));
observer.Wait();
EXPECT_NE(nested_urls[i], web_tab->GetLastCommittedURL());
EXPECT_FALSE(app_origin.IsSameOriginWith(
web_tab->GetMainFrame()->GetLastCommittedOrigin()));
EXPECT_NE("foo", GetTextContent(web_tab->GetMainFrame()));
EXPECT_NE(web_tab->GetMainFrame()->GetProcess(), app_rfh->GetProcess());
EXPECT_EQ(2u, pm->GetAllFrames().size());
EXPECT_EQ(2u, pm->GetRenderFrameHostsForExtension(app->id()).size());
}
}
// Test that a web frame can't navigate a proxy for an extension frame to a
// blob/filesystem extension URL. See https://crbug.com/656752.
IN_PROC_BROWSER_TEST_F(ProcessManagerBrowserTest,
NestedURLNavigationsViaProxyBlocked) {
base::HistogramTester uma;
// Create a simple extension without a background page.
const Extension* extension = CreateExtension("Extension", false);
embedded_test_server()->ServeFilesFromDirectory(extension->path());
ASSERT_TRUE(embedded_test_server()->Start());
// Navigate main tab to an empty web page. There should be no extension
// frames yet.
NavigateToURL(embedded_test_server()->GetURL("/empty.html"));
ProcessManager* pm = ProcessManager::Get(profile());
EXPECT_EQ(0u, pm->GetAllFrames().size());
EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension->id()).size());
content::WebContents* tab =
browser()->tab_strip_model()->GetActiveWebContents();
content::RenderFrameHost* main_frame = tab->GetMainFrame();
// Open a new about:blank popup from main frame. This should stay in the web
// process.
content::WebContents* popup =
OpenPopup(main_frame, GURL(url::kAboutBlankURL));
EXPECT_NE(popup, tab);
ASSERT_EQ(2, browser()->tab_strip_model()->count());
EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension->id()).size());
EXPECT_EQ(0u, pm->GetAllFrames().size());
// Navigate popup to an extension page.
const GURL extension_url(extension->url().Resolve("empty.html"));
content::TestNavigationObserver observer(popup);
EXPECT_TRUE(
ExecuteScript(popup, "location.href = '" + extension_url.spec() + "';"));
observer.Wait();
EXPECT_EQ(1u, pm->GetAllFrames().size());
EXPECT_EQ(1u, pm->GetRenderFrameHostsForExtension(extension->id()).size());
content::RenderFrameHost* extension_frame = popup->GetMainFrame();
// Create valid blob and filesystem URLs in the extension's origin.
url::Origin extension_origin(extension_frame->GetLastCommittedOrigin());
GURL blob_url(CreateBlobURL(extension_frame, "foo"));
EXPECT_EQ(extension_origin, url::Origin(blob_url));
GURL filesystem_url(CreateFileSystemURL(extension_frame, "foo"));
EXPECT_EQ(extension_origin, url::Origin(filesystem_url));
// Have the web page navigate the popup to each nested URL with extension
// origin via the window reference it obtained earlier from window.open.
GURL nested_urls[] = {blob_url, filesystem_url};
for (size_t i = 0; i < arraysize(nested_urls); i++) {
EXPECT_TRUE(ExecuteScript(
tab, "window.popup.location.href = '" + nested_urls[i].spec() + "';"));
WaitForLoadStop(popup);
// This is a top-level navigation that should be blocked since it
// originates from a non-extension process. Ensure that the popup stays at
// the original page and doesn't navigate to the nested URL.
EXPECT_NE(nested_urls[i], popup->GetLastCommittedURL());
EXPECT_NE("foo", GetTextContent(popup->GetMainFrame()));
EXPECT_EQ(1u, pm->GetRenderFrameHostsForExtension(extension->id()).size());
EXPECT_EQ(1u, pm->GetAllFrames().size());
}
// Verify that the blocking was recorded correctly in UMA.
uma.ExpectTotalCount("Extensions.ShouldAllowOpenURL.Failure", 2);
uma.ExpectBucketCount("Extensions.ShouldAllowOpenURL.Failure",
0 /* FAILURE_FILE_SYSTEM_URL */, 1);
uma.ExpectBucketCount("Extensions.ShouldAllowOpenURL.Failure",
1 /* FAILURE_BLOB_URL */, 1);
}
// Verify that a web popup created via window.open from an extension page can
// communicate with the extension page via window.opener. See
// https://crbug.com/590068.
IN_PROC_BROWSER_TEST_F(ProcessManagerBrowserTest,
WebPopupFromExtensionMainFrameHasValidOpener) {
// Create a simple extension without a background page.
const Extension* extension = CreateExtension("Extension", false);
embedded_test_server()->ServeFilesFromDirectory(extension->path());
ASSERT_TRUE(embedded_test_server()->Start());
// Navigate main tab to an extension page.
NavigateToURL(extension->GetResourceURL("empty.html"));
ProcessManager* pm = ProcessManager::Get(profile());
EXPECT_EQ(1u, pm->GetAllFrames().size());
EXPECT_EQ(1u, pm->GetRenderFrameHostsForExtension(extension->id()).size());
content::WebContents* tab =
browser()->tab_strip_model()->GetActiveWebContents();
content::RenderFrameHost* main_frame = tab->GetMainFrame();
// Open a new web popup from the extension tab. The popup should go into a
// new process.
GURL popup_url(embedded_test_server()->GetURL("/empty.html"));
content::WebContents* popup = OpenPopup(main_frame, popup_url);
EXPECT_NE(popup, tab);
ASSERT_EQ(2, browser()->tab_strip_model()->count());
EXPECT_EQ(1u, pm->GetRenderFrameHostsForExtension(extension->id()).size());
EXPECT_EQ(1u, pm->GetAllFrames().size());
EXPECT_NE(popup->GetRenderProcessHost(), main_frame->GetProcess());
// Ensure the popup's window.opener is defined.
bool is_opener_defined = false;
EXPECT_TRUE(ExecuteScriptAndExtractBool(
popup, "window.domAutomationController.send(!!window.opener)",
&is_opener_defined));
EXPECT_TRUE(is_opener_defined);
// Verify that postMessage to window.opener works.
VerifyPostMessageToOpener(popup->GetMainFrame(), main_frame);
}
// Verify that a web popup created via window.open from an extension subframe
// can communicate with the extension page via window.opener. Similar to the
// test above, but for subframes. See https://crbug.com/590068.
IN_PROC_BROWSER_TEST_F(ProcessManagerBrowserTest,
WebPopupFromExtensionSubframeHasValidOpener) {
// This test only makes sense if OOPIFs are enabled for extension subframes.
if (!IsIsolateExtensionsEnabled())
return;
// Create a simple extension without a background page.
const Extension* extension = CreateExtension("Extension", false);
embedded_test_server()->ServeFilesFromDirectory(extension->path());
ASSERT_TRUE(embedded_test_server()->Start());
// Navigate main tab to a web page with a blank iframe. There should be no
// extension frames yet.
NavigateToURL(embedded_test_server()->GetURL("/blank_iframe.html"));
ProcessManager* pm = ProcessManager::Get(profile());
EXPECT_EQ(0u, pm->GetAllFrames().size());
EXPECT_EQ(0u, pm->GetRenderFrameHostsForExtension(extension->id()).size());
content::WebContents* tab =
browser()->tab_strip_model()->GetActiveWebContents();
// Navigate first subframe to an extension URL.
const GURL extension_url(extension->GetResourceURL("empty.html"));
EXPECT_TRUE(content::NavigateIframeToURL(tab, "frame0", extension_url));
EXPECT_EQ(1u, pm->GetRenderFrameHostsForExtension(extension->id()).size());
EXPECT_EQ(1u, pm->GetAllFrames().size());
content::RenderFrameHost* main_frame = tab->GetMainFrame();
content::RenderFrameHost* extension_frame = ChildFrameAt(main_frame, 0);
// Open a new web popup from extension frame. The popup should go into main
// frame's web process.
GURL popup_url(embedded_test_server()->GetURL("/empty.html"));
content::WebContents* popup = OpenPopup(extension_frame, popup_url);
EXPECT_NE(popup, tab);
ASSERT_EQ(2, browser()->tab_strip_model()->count());
EXPECT_EQ(1u, pm->GetRenderFrameHostsForExtension(extension->id()).size());
EXPECT_EQ(1u, pm->GetAllFrames().size());
EXPECT_NE(popup->GetRenderProcessHost(), extension_frame->GetProcess());
EXPECT_EQ(popup->GetRenderProcessHost(), main_frame->GetProcess());
// Ensure the popup's window.opener is defined.
bool is_opener_defined = false;
EXPECT_TRUE(ExecuteScriptAndExtractBool(
popup, "window.domAutomationController.send(!!window.opener)",
&is_opener_defined));
EXPECT_TRUE(is_opener_defined);
// Verify that postMessage to window.opener works.
VerifyPostMessageToOpener(popup->GetMainFrame(), extension_frame);
}
} // namespace extensions
|
[
"enrico.weigelt@gr13.net"
] |
enrico.weigelt@gr13.net
|
900a9cb40c67529ad6db9a98a38689f2a92d6a18
|
c54a0897be1c62def168009ed931acc2ab178872
|
/ouzel/audio/openal/OALAudioDevice.hpp
|
2c73475439327a2751c7ff3f272078da14e84a34
|
[
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
yeeway/ouzel
|
af73005af643a1b8b19ee90775d26bf062c38dff
|
ad469531ad5c5d424e140aae31a1084098f36b56
|
refs/heads/master
| 2020-09-03T15:46:14.215978
| 2019-11-03T22:56:52
| 2019-11-03T22:56:52
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,157
|
hpp
|
// Copyright 2015-2019 Elviss Strazdins. All rights reserved.
#ifndef OUZEL_AUDIO_AUDIODEVICEAL_HPP
#define OUZEL_AUDIO_AUDIODEVICEAL_HPP
#include "core/Setup.h"
#if OUZEL_COMPILE_OPENAL
#include <atomic>
#include <thread>
#if defined(__APPLE__)
# include <OpenAl/al.h>
# include <OpenAl/alc.h>
#else
# include <AL/al.h>
# include <AL/alc.h>
#endif
#include "audio/AudioDevice.hpp"
#include "utils/Thread.hpp"
namespace ouzel
{
namespace audio
{
namespace openal
{
class AudioDevice final: public audio::AudioDevice
{
public:
AudioDevice(uint32_t initBufferSize,
uint32_t initSampleRate,
uint16_t initChannels,
const std::function<void(uint32_t frames,
uint16_t channels,
uint32_t sampleRate,
std::vector<float>& samples)>& initDataGetter);
~AudioDevice();
void start() final;
void stop() final;
void process();
inline auto getDevice() const noexcept { return device; }
inline auto getContext() const noexcept { return context; }
private:
void run();
ALCdevice* device = nullptr;
ALCcontext* context = nullptr;
ALenum format40 = 0;
ALenum format51 = 0;
ALenum format61 = 0;
ALenum format71 = 0;
ALuint sourceId = 0;
ALenum format = 0;
uint32_t nextBuffer = 0;
ALuint bufferIds[2] = {0, 0};
uint32_t sampleSize = 0;
std::vector<uint8_t> data;
#if !defined(__EMSCRIPTEN__)
std::atomic_bool running{false};
Thread audioThread;
#endif
};
} // namespace openal
} // namespace audio
} // namespace ouzel
#endif
#endif // OUZEL_AUDIO_AUDIODEVICEAL_HPP
|
[
"elviss@elviss.lv"
] |
elviss@elviss.lv
|
b7fc7bea72bfb0f94f28ccb853e7ddd8a7345818
|
c60fe551e358a9c7b3340c9bc8551817f5c6732e
|
/src/calculate.hpp
|
8a0ebe91d8480df15addbc6eaa50f546f5aac1ce
|
[] |
no_license
|
callumacrae/cpp-calculator
|
45b9cd3e70d3a3d01cc518e75e41a26d477d4b29
|
8b80db9895e31906b9e9ba43b7f84bd1cb2854dc
|
refs/heads/main
| 2023-06-04T06:10:34.752871
| 2021-06-29T18:06:01
| 2021-06-29T18:06:01
| 377,284,658
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 154
|
hpp
|
//
// calculate.hpp
// calculator
//
// Created by Callum Macrae on 15/06/2021.
//
#pragma once
float calculate(const std::string_view &mathString);
|
[
"callum@macr.ae"
] |
callum@macr.ae
|
d81591d29dce1bc6281bcb4828e3df2c238eaa31
|
3ded37602d6d303e61bff401b2682f5c2b52928c
|
/toy/0503/Classes/Model/MiniGameManager.h
|
4e20e6c102df74b97976b50ff848db9697b3cbbc
|
[] |
no_license
|
CristinaBaby/Demo_CC
|
8ce532dcf016f21b442d8b05173a7d20c03d337e
|
6f6a7ff132e93271b8952b8da6884c3634f5cb59
|
refs/heads/master
| 2021-05-02T14:58:52.900119
| 2018-02-09T11:48:02
| 2018-02-09T11:48:02
| 120,727,659
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,500
|
h
|
//
// MiniGameManager.h
// BedtimeStory
//
// Created by maxiang on 8/31/15.
//
//
#ifndef __BedtimeStory__MiniGameManager__
#define __BedtimeStory__MiniGameManager__
#include "cocos2d.h"
#include "AppConfigs.h"
class BaseGameData
{
public:
BaseGameData() :
index(-1),
resPath(""),
logo("")
{};
public:
int index;
std::string resPath;
std::string logo;
};
#pragma mark- Spot Game Data
class SpotGameData : public BaseGameData
{
public:
SpotGameData() :
tmxFileName(""),
textureFileName(""),
textureFilePlist("")
{};
public:
std::string tmxFileName;
std::string textureFileName;
std::string textureFilePlist;
};
#pragma mark- Jigsaw Game Data
class JigsawConfig
{
public:
JigsawConfig():
rows(0),
columns(0),
totalWidth(0.0),
totalHeight(0.0)
{};
struct JigsawTileInfo
{
float offsetx;
float offsety;
float width;
float height;
std::string tilePath;
};
public:
int rows;
int columns;
float totalWidth;
float totalHeight;
void init(const std::string& csvfile);
std::vector<JigsawTileInfo> jigsawTilesVector;
};
class JigsawGameData : public BaseGameData
{
public:
JigsawGameData() :
textureFileName(""),
config(nullptr)
{};
~JigsawGameData()
{
if (config != nullptr)
{
delete config;
}
};
public:
JigsawConfig *config;
std::string textureFileName;
};
#pragma mark- ColorBook Game Data
class ColorBookGameData : public BaseGameData
{
public:
ColorBookGameData() :
pictureFileName(""),
maskFileName("")
{};
public:
std::string pictureFileName;
std::string maskFileName;
};
struct Pen
{
std::string penLogo;
GLuint R;
GLuint G;
GLuint B;
GLuint A;
int index;
};
struct Pattern
{
std::string patternLogo;
std::string pattern;
int index;
};
enum class PensType
{
PensType_None = 0,
PensType_Pen1,
PensType_Pen2,
PensType_Pattern,
};
#pragma mark- Record Game Data
class RecordGameData : public BaseGameData //this data struct used to show logo
{
public:
RecordGameData():
leftStoryImageFile(""),
rightStoryImageFile("")
{};
~RecordGameData()
{
};
public:
std::string leftStoryImageFile;
std::string rightStoryImageFile;
};
struct RecordInfo //this data struct used to store record info
{
int index;
int recordTime;
bool isSelected;
std::string recordFilePath;
std::string recordDate;
};
#pragma mark- Game Manager
enum class GameType
{
None = 0,
Spot,
Jigsaw,
ColorBook,
Story,
Record
};
class MiniGameManager
{
public:
static MiniGameManager* getInstance();
MiniGameManager();
~MiniGameManager();
void initSpotData();
void initJigsawData();
//for color book game
void initColorBookData();
void setupPens(const std::string& path);
void setupPatterns(const std::string& path);
std::vector<Pen> *getPens(){return &_pensVector;};
std::vector<Pattern> *getPatterns(){return &_patternsVector;};
CC_SYNTHESIZE(PensType, _currentPensType, CurrentPensType);
//for record data
void initRecordData();
void saveRecordInfo();
void addRecordInfo(const int storyIndex, RecordInfo *info);
void deleteRecordInfo(const int storyIndex, RecordInfo *info);
std::vector<RecordInfo*>* getRecordInfoVector(const int storyIndex);
void destroySpotGameData();
void destroyJigsawGameData();
void destroyColorBookGameData();
void destroyRecordDataVector();
CC_SYNTHESIZE_READONLY_PASS_BY_REF(std::vector<SpotGameData*>, _spotDataVector, SpotDataVector);
CC_SYNTHESIZE_READONLY_PASS_BY_REF(std::vector<JigsawGameData*>, _jigsawDataVector, JigsawDataVector);
CC_SYNTHESIZE_READONLY_PASS_BY_REF(std::vector<ColorBookGameData*>, _colorBookDataVector, ColorBookDataVector);
CC_SYNTHESIZE_READONLY_PASS_BY_REF(std::vector<RecordGameData*>, _recordDataVector, RecordDataVector);
protected:
std::vector<Pen> _pensVector;
std::vector<Pattern> _patternsVector;
//key->story index, value->RecordInfo sturct, used to store records
std::unordered_map<std::string, std::vector<RecordInfo*>> _recordInfoMap;
cocos2d::ValueVector _recordInfoV;
};
#endif /* defined(__BedtimeStory__MiniGameManager__) */
|
[
"wuguiling@smalltreemedia.com"
] |
wuguiling@smalltreemedia.com
|
2d53f683632423017ea7687ed56bdb094113e327
|
906429cb55aa76ef0b44f03ac84a1265fb311d54
|
/Lab2_ACM_2020/2.AvgExcludeMinAndMax/ConsoleApplication2/ConsoleApplication2.cpp
|
b7cdd3e1d52892243e90500995cf43861dd203a6
|
[] |
no_license
|
Ranazh/Shakieva_ACM_Labs
|
02bf314337506b6b8d95ffe97780b2e4e798ab50
|
2bb23b500f7ef415738044790ae0bac79695198f
|
refs/heads/main
| 2022-12-31T13:21:08.663315
| 2020-10-19T21:18:48
| 2020-10-19T21:18:48
| 305,397,163
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,015
|
cpp
|
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class Solution1 {
public:
double average(vector<int>& salary) {
int size = salary.size();
int mx = salary[0];
int mn = salary[0];
double sum = salary[0];
for (int i = 1; i < size; i++) {
sum += salary[i];
mx = max(mx, salary[i]);
mn = min(mn, salary[i]);
}
return (sum - mn - mx) / (size - 2);
}
};
class Solution2 {
public:
double average(vector<int>& salary) {
int size = salary.size();
sort(salary.begin(), salary.end());
double sum = salary[1];
for (int i = 2; i < size - 1; i++) {
sum += salary[i];
}
return sum / (size - 2);
}
};
int main()
{
Solution1 *obj1 = new Solution1();
Solution2 *obj2 = new Solution2();
vector<int> v;
int num;
cout << "Enter Numbers" << '\n';
while (cin >> num)
{
v.push_back(num);
}
cout << "The first solution: " << obj1->average(v) << endl;
cout << "The second solution: " << obj2->average(v) << endl;
return 0;
}
|
[
"62495507+Ranazh@users.noreply.github.com"
] |
62495507+Ranazh@users.noreply.github.com
|
63dad212574f3af5756aa197847489d271350ca0
|
ce6fc44470dcb5fca78cdd3349a7be70d75f2e3a
|
/AtCoder/Beginner 134/E.cpp
|
92279d0207e0a3f476b32c278259073843f69a42
|
[] |
no_license
|
cormackikkert/competitive-programming
|
f3fa287fcb74248ba218ecd763f8f6df31d57424
|
3a1200b8ff9b6941c422371961a127d7be8f2e00
|
refs/heads/master
| 2022-12-17T02:02:40.892608
| 2020-09-20T11:47:15
| 2020-09-20T11:47:15
| 266,775,265
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,473
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
#define F0R(i,a) FOR(i,0,a)
#define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i)
#define R0F(i,a) ROF(i,0,a)
using ll = long long;
ll INF = LLONG_MAX;
using vc = vector<char>;
using vi = vector<int>;
using pii = pair<int, int>;
vector<pii> tree;
void modify(int i, pii v) {
i += tree.size()/2;
tree[i] = v;
for (i /= 2; i >= 1; i /= 2) tree[i] = min(tree[2*i], tree[2*i+1]);
}
pii query(int a, int b) {
a += tree.size() / 2; b += tree.size() / 2;
pii s = {1e9+1,1e9+1};
while (a <= b) {
if (a % 2 == 1) s = min(s, tree[a++]);
if (b % 2 == 0) s = min(s, tree[b--]);
a /= 2; b /= 2;
}
return s;
}
int main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int N; cin >> N;
tree.resize(2*N);
F0R(i, N) {
int val; cin >> val;
modify(i, pii {val, i});
}
int operations = 0;
while (true) {
pii res = query(0, N-1);
if (res.first == 1e9+1) break;
++operations;
int pos = res.second + 1;
while (pos && res.first < 1e9+1) {
if (query(pos, pos).first <= res.first) {++pos; continue;}
modify(pos, pii {1e9+1, 1e9+1});
res = query(res.second + 1, N-1);
}
if (res.first < 1e9+1) modify(res.second, pii {1e9+1, 1e9+1});
}
cout << operations << endl;
}
|
[
"u6427001@anu.edu.au"
] |
u6427001@anu.edu.au
|
70f2bb9e9c151ef3f2bae749ee42a374000bd92b
|
981925c2d9a19f66e2c57f599439576be7ed98fb
|
/myCirclellist/myCirclellist/源.cpp
|
1f0cd685e3a2f25afbe72ecaa60e0ba9c5cac733
|
[] |
no_license
|
ssexuejinwei/create-datastructure-by-myself
|
eafd529bca892e1c1713e4a8ca7701cb6536ca7b
|
d635c2585f8b39b630ac247e7a8a6fc2a9dc3ea9
|
refs/heads/master
| 2020-03-23T04:26:49.240019
| 2018-07-16T04:56:40
| 2018-07-16T04:56:40
| 141,083,959
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 580
|
cpp
|
#include"CirList.h"
#include<iostream>
int main() {
using namespace std;
Cirlist<int> list;
int x;
int n, s, m, k;
cin >> n >> s >> m >> k;
LinkNode<int>* p;
for (int i = 0; i < n; i++)
list.Insert(i + 1, i + 1);
p = list.locate(s);
while (n > k) {
for (int i = 1; i < m; i++) {
if (p == list.getRear()) {
p = list.getHead()->link;
continue;
}
p = p->link;
}
LinkNode<int>* next;
if (p == list.getRear()) {
next = list.getHead()->link;
}
else
next = p->link;
list.Remove(x, p);
p = next;
cout << x << " ";
n--;
}
return 0;
}
|
[
"839315380@qq.com"
] |
839315380@qq.com
|
fb5de8f03fa785d8ffb7c80a659bcb80a5c86210
|
b526330604e6cc42b4604dee855ba3291f2df454
|
/CodeLib/Brute Force/POJ 1077 Eight.cpp
|
e6e7d15d221528f688d54b33da640277fe769650
|
[] |
no_license
|
KamikazeChan/Contest
|
039166160140b1eb424cbcc2e2765e6f04d3cafc
|
dcacfee07e7c7c201205b73dc1d92281e6824c63
|
refs/heads/master
| 2021-01-24T23:11:44.978319
| 2014-12-15T10:38:15
| 2014-12-15T10:38:32
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 3,550
|
cpp
|
/*
** POJ 1077 Eight
** Created by Rayn @@ 2014/05/22
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <bitset>
#include <algorithm>
using namespace std;
const int MAX = 400000;
int nGoalStatus;
bitset<387420498> Flag;
char szRes[MAX], szMove[MAX];
char Dir[] = "udrl";
int Pre[MAX], Queue[MAX];
int Head, Tail;
int NineToTen(char *s) //九进制字符串转化为十进制数字
{
int res = 0;
for(int i=0; s[i]; ++i)
{
res = res * 9 + s[i] - '0';
}
//printf("%d\n", res);
return res;
}
int TenToNine(int n, char *s) //十进制数字转化为九进制字符串
{
int ZeroPos, nBase = 1;
while (nBase <= n)
nBase *= 9;
nBase /= 9;
int j = 0;
do {
s[j] = n/nBase + '0';
if (s[j] == '0')
ZeroPos = j;
j++;
n %= nBase;
nBase /= 9;
} while(nBase >= 1);
s[j] = '\0';
if(j < 9)
{
for(int i = j+1; i > 0; --i)
{
s[i] = s[i-1];
}
s[0] = '0';
return 0;
}
return ZeroPos;
}
int NewStatus(int nStatus, char cMove)
{
char tmp[20];
int ZeroPos = TenToNine(nStatus, tmp); //返回空格的位置
switch(cMove)
{
case 'u':
if (ZeroPos - 3 < 0) return -1; //空格在第一行
else {
tmp[ZeroPos] = tmp[ZeroPos-3];
tmp[ZeroPos-3] = '0';
}
break;
case 'd':
if (ZeroPos + 3 > 8) return -1; //空格在第三行
else {
tmp[ZeroPos] = tmp[ZeroPos+3];
tmp[ZeroPos+3] = '0';
}
break;
case 'l':
if (ZeroPos % 3 == 0) return -1; //空格在第一列
else {
tmp[ZeroPos] = tmp[ZeroPos-1];
tmp[ZeroPos-1] = '0';
}
break;
case 'r':
if (ZeroPos % 3 == 2) return -1; //空格在第三列
else {
tmp[ZeroPos] = tmp[ZeroPos+1];
tmp[ZeroPos+1] = '0';
}
break;
}
return NineToTen(tmp);
}
bool BFS(int nStatus)
{
int nNewStatus;
Head = Tail = 0;
Queue[Head] = nStatus;
Tail++;
while (Head < Tail)
{
nStatus = Queue[Head];
if(nStatus == nGoalStatus)
return true;
for(int i=0; i<4; ++i)
{
nNewStatus = NewStatus(nStatus, Dir[i]);
if(nNewStatus == -1)
continue;
if(Flag[nNewStatus])
continue;
Flag.set(nNewStatus, true);
Queue[Tail] = nNewStatus;
Pre[Tail] = Head;
szMove[Tail] = Dir[i];
Tail++;
}
Head++;
}
return false;
}
int main()
{
nGoalStatus = NineToTen("123456780");
Flag.reset();
char Line1[50], Line2[20];
cin.getline(Line1, 40);
int i, j;
for(i=0, j=0; Line1[i]; ++i)
{
if(Line1[i] != ' ')
{
if(Line1[i] == 'x')
Line2[j++] = '0';
else
Line2[j++] = Line1[i];
}
}
Line2[j] = '\0';
if( BFS(NineToTen(Line2)) )
{
int nMove = 0;
int nPos = Head;
do {
szRes[nMove++] = szMove[nPos];
nPos = Pre[nPos];
} while(nPos);
for(int i = nMove-1; i >= 0; --i)
{
cout << szRes[i];
}
}
else
{
cout << "unsolvable" << endl;
}
return 0;
}
|
[
"rayn1027@outlook.com"
] |
rayn1027@outlook.com
|
d1e448d44043d2b807c7a0e94bb239e93fad851f
|
a5db05a373f489d05a7f2b8e06d2805ee711de17
|
/android/hardware/aw/marlin/Include/Bento4/Core/Ap4Movie.h
|
99e7232a41818ffda71779be992c1abff19b6b14
|
[] |
no_license
|
BPI-SINOVOIP/BPI-H3-New-Android
|
7c0cdd50a23e62a204d4818954357868b4925945
|
5cbaa7ad4f73f615dcc4fbed07b52ae240743504
|
refs/heads/master
| 2023-02-25T15:43:36.633336
| 2018-07-18T10:56:14
| 2018-07-18T10:56:14
| 69,656,896
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,849
|
h
|
/*****************************************************************
|
| AP4 - Movie
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
|
| This file is part of Bento4/AP4 (MP4 Atom Processing Library).
|
| Unless you have obtained Bento4 under a difference license,
| this version of Bento4 is Bento4|GPL.
| Bento4|GPL is free software; you can redistribute it and/or modify
| it under the terms of the GNU General Public License as published by
| the Free Software Foundation; either version 2, or (at your option)
| any later version.
|
| Bento4|GPL is distributed in the hope that it will be useful,
| but WITHOUT ANY WARRANTY; without even the implied warranty of
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
| GNU General Public License for more details.
|
| You should have received a copy of the GNU General Public License
| along with Bento4|GPL; see the file COPYING. If not, write to the
| Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
| 02111-1307, USA.
|
****************************************************************/
#ifndef _AP4_MOVIE_H_
#define _AP4_MOVIE_H_
/*----------------------------------------------------------------------
| includes
+---------------------------------------------------------------------*/
#include "Ap4Types.h"
#include "Ap4MoovAtom.h"
#include "Ap4MvhdAtom.h"
#include "Ap4Track.h"
#include "Ap4List.h"
/*----------------------------------------------------------------------
| class references
+---------------------------------------------------------------------*/
class AP4_ByteStream;
class AP4_AtomInspector;
class AP4_MetaData;
/*----------------------------------------------------------------------
| AP4_Movie
+---------------------------------------------------------------------*/
class AP4_Movie {
public:
// methods
AP4_Movie(AP4_UI32 time_scale = 0);
AP4_Movie(AP4_MoovAtom* moov, AP4_ByteStream& sample_stream, bool transfer_moov_ownership = true);
virtual ~AP4_Movie();
AP4_Result Inspect(AP4_AtomInspector& inspector);
AP4_MoovAtom* GetMoovAtom() { return m_MoovAtom;}
AP4_MvhdAtom* GetMvhdAtom() { return m_MvhdAtom;}
AP4_List<AP4_Track>& GetTracks() { return m_Tracks; }
AP4_Track* GetTrack(AP4_UI32 track_id);
AP4_Track* GetTrack(AP4_Track::Type type, AP4_Ordinal index = 0);
AP4_Result AddTrack(AP4_Track* track);
AP4_UI32 GetTimeScale();
AP4_UI64 GetDuration();
AP4_UI32 GetDurationMs();
bool HasFragments();
private:
// members
AP4_MoovAtom* m_MoovAtom;
bool m_MoovAtomIsOwned;
AP4_MvhdAtom* m_MvhdAtom;
AP4_List<AP4_Track> m_Tracks;
};
#endif // _AP4_MOVIE_H_
|
[
"justin@justin-ThinkPad-T420.(none)"
] |
justin@justin-ThinkPad-T420.(none)
|
1eb35009b4afee6258adf665a23a54d9b3ab2332
|
92b6aaade5a3f323d7f8e7d02fb9fec09f4c2f50
|
/CP-Codes/cf_476b.cpp
|
d94b1bef0d24b081f28f9d0001ae983fba89de1e
|
[] |
no_license
|
suraj1611/Competitive_Programming
|
846dee00396e2f2b6d13e2ea8aaed444a34062af
|
82bd88081ac067ad4170553afedc6c479bb53753
|
refs/heads/master
| 2020-04-22T17:27:18.116585
| 2019-12-16T19:42:29
| 2019-12-16T19:42:29
| 170,541,477
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,522
|
cpp
|
/* Code by : Suraj (@suraj1611) */
#include<bits/stdc++.h>
#include <string>
using namespace std;
#define ll long long
#define rep(i,n) for(int i=0; i<n; i++)
#define rep1(i,n) for(int i=1;i<=n;i++)
#define mx INT_MAX
#define mn INT_MIN
#define md 1000000007
#define pb push_back
#define mp make_pair
#define maxsize 1100005
#define lb cout<<endl;
#define endl "\n"
#define F first
#define S second
#define label cout<<"hello!"<<endl
#define IOS ios_base::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL);
double fact[20];
ll power(ll x, ll y)
{
ll m=md;
ll ans=1;
while (y > 0)
{
if (y & 1)
ans = (ans * x) % m;
x = (x * x) % m;
y >>= 1;
}
return ans;
}
void fac()
{
fact[0]=1;
fact[1]=1;
for(ll i=2;i<15;i++)
{
fact[i]=i*fact[i-1];
}
}
int main()
{
IOS
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
string s1,s2;
fac();
cin>>s1>>s2;
ll a=0,b=0,a1=0,b1=0,q=0;
double ans=0;
rep(i,s1.length())
{
if(s1[i]=='+')
a++;
else
b++;
}
rep(i,s2.length())
{
if(s2[i]=='+')
a1++;
else if(s2[i]=='-')
b1++;
else
q++;
}
//cout<<q<<" "<<a1<<" "<<b1<<endl;
if(a1>a or b1>b)
ans=0;
else if(q==0)
ans=1;
else
{
ans = (1/(pow(2,q)))*(fact[q]/(fact[a-a1]*fact[b-b1]));
}
cout<<setprecision(12)<<fixed;
cout<<ans<<endl;
#ifndef ONLINE_JUDGE
cout<<"\nTime Elapsed : " << 1.0*clock() / CLOCKS_PER_SEC << " s\n";
#endif
return 0;
}
|
[
"surajsk1611@gmail.com"
] |
surajsk1611@gmail.com
|
92a073d897ff44193293ec8a1e41764417254267
|
a9ef859bd36defcc2bcc88ee2d3925e678e670f8
|
/codeforces/1294/B.cpp
|
1eb89c8876d5cbb127131da9695fd6cbb8420a6d
|
[] |
no_license
|
thun-cp/Problem-Solving
|
6655c5452849c1a576cb54cc5b8c135148d2a8e1
|
663c5bdb5b51695ded2a3c8c6b0f334f7c97e8f3
|
refs/heads/master
| 2023-02-22T01:30:10.604479
| 2021-01-04T19:38:40
| 2021-01-04T19:38:40
| 323,599,063
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,808
|
cpp
|
// #pragma comment(linker, "/stack:200000000")
// #pragma GCC optimize("Ofast")
// #pragma GCC target("avx,avx2,fma")
// #pragma GCC optimization("unroll-loops")
#include "bits/stdc++.h"
#define pb push_back
#define mp make_pair
#define mt make_tuple
#define endl '\n'
#define F first
#define S second
#define IO ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define cf ll testcases;cin>>testcases;while(testcases--)
#define prn(x) if(x) cout<<"YES"<<endl; else cout<<"NO"<<endl;
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
#define minel(x) (*min_element(all(x)))
#define maxel(x) (*max_element(all(x)))
#define cou dbg=1;cout
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<ll,ll> pi;
typedef vector<ll> vi;
typedef vector<ld> vd;
typedef vector<pi> vp;
ll dbg=0;
template<typename A, typename B> ostream& operator<<(ostream &cout, pair<A, B> const &p);
template<typename A> ostream& operator<<(ostream &cout, vector<A> const &v);
template<typename A, typename B> istream& operator>>(istream& cin, pair<A, B> &p);
template<typename A> istream& operator>>(istream& cin, vector<A> &v);
int dx[] = {-1, -1, -1, 0, 0, 1, 1, 1};
int dy[] = {-1, 0, 1, -1, 1, -1, 0, 1};
ll t=0;
void solve(){
ll n;
cin>>n;
vp arr(n);
cin>>arr;
sort(all(arr));
// for(auto i:arr){
// cout<<i<<endl;
// }
for(ll i=0;i<n;i++){
for(ll j=i+1;j<n;j++){
if((arr[i].F>arr[j].F&&arr[i].S<=arr[j].S)||(arr[i].F<=arr[j].F&&arr[i].S>arr[j].S)){
cout<<"NO"<<endl;
return;
}
}
}
cout<<"YES"<<endl;
string ans;
ll x=0,y=0;
for(auto i:arr){
for(ll j=x;j<i.F;j++) ans+='R';
for(ll j=y;j<i.S;j++) ans+='U';
x=i.F,y=i.S;
}
cout<<ans<<endl;
}
int main(){
IO;
cf
solve();
return 0;
}
template<typename A, typename B> ostream& operator<<(ostream &cout, pair<A, B> const &p) {
if(dbg){dbg=0;
return cout << "(" << p.F << ", " << p.S << ")";
}else{
return cout<<p.F<<' '<<p.S;
}
}
template<typename A> ostream& operator<<(ostream &cout, vector<A> const &v) {
if(dbg){dbg=0;
cout << "["; for(ll i = 0; i < v.size(); i++) {if (i) cout << ", "; cout << v[i];} return cout << "]";
}else{
for(ll i=0;i<v.size()-1;i++) cout<<v[i]<<' ';
return cout<<v[v.size()-1];
}
}
template<typename A, typename B> istream& operator>>(istream& cin, pair<A, B> &p) {
cin >> p.first;
return cin >> p.second;
}
template<typename A> istream& operator>>(istream& cin, vector<A> &v) {
for(ll i=0;i<v.size()-1;i++) cin>>v[i];
return cin >> v[v.size()-1];
}
|
[
"tmodpe@gmail.com"
] |
tmodpe@gmail.com
|
c05247070a7d6efdb85211d709a7bdaa7b5322ed
|
4b055f9c18ad613f10c0e281873b800f3ff515ff
|
/Minigin/Renderer.cpp
|
bbf67f609ae66d97ae9e10e8016be455e0dd1735
|
[] |
no_license
|
minoarno/MidestinyEngine
|
982508e7ac0197fc49649c1bec362ad5ba113469
|
68e88f2f3dc537cf4add9fe474004681a90e8a84
|
refs/heads/main
| 2023-07-16T06:31:24.398267
| 2021-08-23T04:40:14
| 2021-08-23T04:40:14
| 337,725,203
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,959
|
cpp
|
#include "MiniginPCH.h"
#include "Renderer.h"
#include <SDL.h>
#include "SceneManager.h"
#include "Texture2D.h"
bool dae::Renderer::m_ShowDemo = true;
void dae::Renderer::Init(SDL_Window * window)
{
m_Window = window;
m_Renderer = SDL_CreateRenderer(window, GetOpenGLDriverIndex(), SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (m_Renderer == nullptr)
{
throw std::runtime_error(std::string("SDL_CreateRenderer Error: ") + SDL_GetError());
}
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGui_ImplSDL2_InitForOpenGL(window, SDL_GL_GetCurrentContext());
ImGui_ImplOpenGL2_Init();
}
int dae::Renderer::GetOpenGLDriverIndex()
{
auto openglIndex = -1;
const int driverCount = SDL_GetNumRenderDrivers();
for (int i = 0; i < driverCount; i++)
{
SDL_RendererInfo info;
if (!SDL_GetRenderDriverInfo(i, &info))
{
if (!strcmp(info.name, "opengl"))
{
openglIndex = i;
}
}
}
return openglIndex;
}
void dae::Renderer::Render() const
{
SDL_RenderClear(m_Renderer);
SceneManager::GetInstance().Render();
ImGui_ImplOpenGL2_NewFrame();
ImGui_ImplSDL2_NewFrame(m_Window);
ImGui::NewFrame();
if (m_ShowDemo)
{
ImGui::ShowDemoWindow(&m_ShowDemo);
}
ImGui::Render();
ImGui_ImplOpenGL2_RenderDrawData(ImGui::GetDrawData());
SDL_RenderPresent(m_Renderer);
}
void dae::Renderer::Destroy()
{
ImGui_ImplOpenGL2_Shutdown();
ImGui_ImplSDL2_Shutdown();
ImGui::DestroyContext();
if (m_Renderer != nullptr)
{
SDL_DestroyRenderer(m_Renderer);
m_Renderer = nullptr;
}
}
void dae::Renderer::RenderTexture(const Texture2D* pTexture, const float x, const float y) const
{
SDL_Rect dst{};
dst.x = static_cast<int>(x);
dst.y = static_cast<int>(y);
SDL_QueryTexture(pTexture->GetSDLTexture(), nullptr, nullptr, &dst.w, &dst.h);
SDL_RenderCopy(GetSDLRenderer(), pTexture->GetSDLTexture(), nullptr, &dst);
}
void dae::Renderer::RenderTexture(const Texture2D* pTexture, const float x, const float y, const float width, const float height) const
{
SDL_Rect dst{};
dst.x = static_cast<int>(x);
dst.y = static_cast<int>(y);
dst.w = static_cast<int>(width);
dst.h = static_cast<int>(height);
SDL_RenderCopy(GetSDLRenderer(), pTexture->GetSDLTexture(), nullptr, &dst);
}
void dae::Renderer::RenderTexture(const Texture2D* pTexture, SDL_Rect srcRect,const float x, const float y, const float width, const float height) const
{
SDL_Rect dst{};
dst.x = static_cast<int>(x);
dst.y = static_cast<int>(y);
dst.w = static_cast<int>(width);
dst.h = static_cast<int>(height);
SDL_RenderCopy(GetSDLRenderer(), pTexture->GetSDLTexture(), &srcRect, &dst);
}
void dae::Renderer::RenderTexture(const Texture2D* pTexture, SDL_Rect srcRect, const float x, const float y) const
{
SDL_Rect dst{};
dst.x = static_cast<int>(x);
dst.y = static_cast<int>(y);
SDL_QueryTexture(pTexture->GetSDLTexture(), nullptr, nullptr, &dst.w, &dst.h);
SDL_RenderCopy(GetSDLRenderer(), pTexture->GetSDLTexture(), &srcRect, &dst);
}
|
[
"minoarno@users.noreply.github.com"
] |
minoarno@users.noreply.github.com
|
dcf579f490db38b49bd90c24f58bfa07bf5dc9f5
|
7e79799ffb2b32666ed6bce1c3223f4d4e39c7db
|
/03_C_plusplus/096_Remove_Element/01_Remove_Element.cpp
|
89c136e94e49d8941290bdebf8610f18a58e9274
|
[] |
no_license
|
daegukdo/TIL
|
c24fef4b0c694dd5db0a48cc041960b9cb8ede34
|
f3ad8d802e0bf55896d97d5d70fd08a1f7736a79
|
refs/heads/master
| 2022-05-10T12:26:53.270934
| 2022-05-05T13:30:24
| 2022-05-05T13:30:24
| 200,057,564
| 0
| 3
| null | null | null | null |
UHC
|
C++
| false
| false
| 2,259
|
cpp
|
/*
@ LeetCode
Remove Element
Given an array nums and a value val, remove all instances of that value in-place and return 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.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example 1:
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
It doesn't matter what you leave beyond the returned length.
Example 2:
Given nums = [0,1,2,2,3,0,4,2], val = 2,
Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
Note that the order of those five elements can be arbitrary.
It doesn't matter what values are set beyond the returned length.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
// nums is passed in by reference. (i.e., without making a copy)
int len = removeElement(nums, val);
// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
ref : https://leetcode.com/explore/learn/card/array-and-string/205/array-two-pointer-technique/1151/
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
// index 저장소 정의
vector<int> removeIndexVct;
// 오름차순 정렬
sort(nums.begin(), nums.end());
// 찾아서 삭제
for(int i = 0; i < nums.size(); i++){
if(nums[i] == val){
removeIndexVct.push_back(i);
}
}
for(int i = removeIndexVct.size() - 1; i > -1; i--){
nums.erase(nums.begin() + removeIndexVct[i]);
}
return nums.size();
}
};
int main() {
int numsArr[4] = {3,2,2,3};
vector<int> nums(numsArr, *(&numsArr + 1));
int val = 3;
Solution s;
int r = s.removeElement(nums, val);
return 0;
}
|
[
"eornrsayclub@gmail.com"
] |
eornrsayclub@gmail.com
|
7635f0b820925c78502746b914a9d79081d1655a
|
26ee37a92336ac6268b6d23f965d1b54d5594a7b
|
/src/consistency/traditional_ssp_consistency.cc
|
18a5488af0b656f9fa57bcb03b6484a53d75e523
|
[] |
no_license
|
CaryLorrk/woops
|
9494082f9a90926a63299462075e83e49d9688b9
|
66d10b9f93f275f2d2e4aaa71acfa09a3cefa862
|
refs/heads/master
| 2020-05-23T18:30:05.316492
| 2018-09-18T04:08:45
| 2018-09-18T04:08:45
| 95,071,315
| 0
| 1
| null | 2017-10-13T05:09:41
| 2017-06-22T03:36:56
|
C++
|
UTF-8
|
C++
| false
| false
| 1,609
|
cc
|
#include "traditional_ssp_consistency.h"
#include "lib.h"
namespace woops
{
TraditionalSSPConsistency::TraditionalSSPConsistency(Iteration staleness): SSPConsistency(staleness) {}
void TraditionalSSPConsistency::BeforeClock(Iteration iteration) {
auto&& tables = Lib::Client().GetTables();
for (auto&& kv: tables) {
Tableid id = kv.first;
auto&& table = *kv.second;
Iteration min;
{
std::lock_guard<std::mutex> lock(table.mu);
min = std::min_element(
table.iterations.begin(), table.iterations.end(),
[](ClientTable::Iterations::value_type& l,
ClientTable::Iterations::value_type& r) -> bool {
return l.second < r.second;
})->second;
}
if (min < iteration - staleness_) {
// push to server
auto&& partitions = Lib::Placement().GetPartitions(id);
std::map<Hostid, Bytes> server_to_bytes;
{
std::lock_guard<std::mutex> lock(table.mu);
server_to_bytes = table.transmit_buffer->Encode(partitions);
}
for (auto&& kv: partitions) {
auto&& server = kv.first;
auto&& bytes = server_to_bytes[server];
Lib::Comm().ClientPush(server, id, iteration, std::move(bytes));
}
// pull from server
for (auto&& kv: partitions) {
Lib::Comm().ClientPull(kv.first, id, iteration);
}
}
}
}
} /* woops */
|
[
"carylorrk@gmail.com"
] |
carylorrk@gmail.com
|
268cb90fe62680f45851e8bc3359d815e22dd90e
|
00692ba81551905b594279fc37ee8e3ca3a4f8eb
|
/List.cpp
|
235115b0fad04a08e1ac76a2c1ed46d9d45554fe
|
[] |
no_license
|
zhan81776075/Cplusplus-Primer
|
a52bd0ea62bedf248cc9b72e5915e01930b97460
|
9b4103138c94728a4f9ec541a05ae6835fcf5a41
|
refs/heads/master
| 2020-05-17T09:16:13.259039
| 2019-06-15T14:16:30
| 2019-06-15T14:16:30
| 183,628,642
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,692
|
cpp
|
#include<iostream>
#include<list>
#include <utility> // std::move std::swap
#include <vector> // std::vector
#include <string> // std::string
int main()
{
/*list::assign
std::list<int> first;
std::list<int> second;
//void assign (size_type n, const value_type& val);
first.assign(7, 100);
//void assign(InputIterator first, InputIterator last);
second.assign(first.begin(), first.end());
//assigning from array
int myints[] = { 1776,7,3 };
first.assign(myints, myints + 3);
std::cout << "Size of first: " << int(first.size()) << '\n';
std::cout << "Size of second: " << int(second.size()) << '\n';
return 0;
*/
/*list::back
std::list<int> mylist;
mylist.push_back(10);
while (mylist.back() != 0)
{
mylist.push_back(mylist.back() - 1);
}
std::cout << "mylist contains:";
for (std::list<int>::iterator it = mylist.begin(); it != mylist.end(); ++it) {
std::cout << ' ' << *it;
}
std::cout << '\n';
return 0;
*/
/*list::begin
int myints[] = { 75,23,65,42,13 };
std::list<int> mylist(myints, myints + 5);
std::cout << "mylist contains:";
for (std::list<int>::iterator it = mylist.begin(); it != mylist.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
*/
/* std::move
std::string foo = "foo-string";
std::string bar = "bar-string";
std::vector<std::string> myvector;
myvector.push_back(foo); // copies
myvector.push_back(std::move(bar)); // moves
std::cout << "myvector contains:";
for (std::string& x : myvector) std::cout << ' ' << x;
std::cout << '\n';
std::cout <<"foo_value:"<< foo << std::endl;
std::cout <<"bar_value:"<< bar << std::endl;
return 0;
*/
}
|
[
"416810161@qq.com"
] |
416810161@qq.com
|
fe1e4d7b7dbc225bb7231a7cc2942dba348f76f2
|
5be91d95c7c0e3ecd2f6da2cd1f73018f444e0d1
|
/ProjetoPOO/Virus.cpp
|
ff6720161016b4d1a2e02323012ef59f9adb77bc
|
[
"MIT"
] |
permissive
|
DiogoTojal7/ProjetoPOO-
|
8d336ad5ef642efb87376cf15f1e4ab2a4822564
|
5990806a191cbf6f02c7a6b9119ba8c7bd38226b
|
refs/heads/main
| 2023-01-20T19:13:35.422856
| 2020-11-20T18:32:13
| 2020-11-20T18:32:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 111
|
cpp
|
#include "Virus.h"
#include "Pessoa.h"
Virus::Virus(string c1)
{
//ctor
}
Virus::~Virus()
{
//dtor
}
|
[
"63270037+DiogoTojal@users.noreply.github.com"
] |
63270037+DiogoTojal@users.noreply.github.com
|
8a29594b18a3bfd282cf2f54d6f903ed3dfc9d31
|
6d3a70abecb8d5f706673ba7068bcd2b941fc84d
|
/Libraries/Dicom/dcm_value_ul.cpp
|
092320c3804318edf9f29b470ceecdd69521ba0d
|
[] |
no_license
|
MarcoTestDVTk/TestDVTk
|
352ab93c0d1ed154985fbad83ed6982029da66d1
|
c9202041090d6f68f5cdfd23db904592440fb365
|
refs/heads/master
| 2021-01-09T20:30:38.405636
| 2016-06-15T08:52:41
| 2016-06-15T08:52:41
| 61,128,764
| 0
| 1
| null | null | null | null |
WINDOWS-1252
|
C++
| false
| false
| 2,399
|
cpp
|
// ------------------------------------------------------
// DVTk - The Healthcare Validation Toolkit (www.dvtk.org)
// Copyright © 2009 DVTk
// ------------------------------------------------------
// This file is part of DVTk.
//
// DVTk is free software; you can redistribute it and/or modify it under the terms of the GNU
// Lesser General Public License as published by the Free Software Foundation; either version 3.0
// of the License, or (at your option) any later version.
//
// DVTk is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
// General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License along with this
// library; if not, see <http://www.gnu.org/licenses/>
//*****************************************************************************
// EXTERNAL DECLARATIONS
//*****************************************************************************
#include "dcm_value_ul.h"
//>>===========================================================================
DCM_VALUE_UL_CLASS::DCM_VALUE_UL_CLASS()
// DESCRIPTION : Constructor.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
// constructor activities
identifierM = "";
}
//>>===========================================================================
DCM_VALUE_UL_CLASS::~DCM_VALUE_UL_CLASS()
// DESCRIPTION : Destructor.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
// destructor activities
}
//>>===========================================================================
bool DCM_VALUE_UL_CLASS::operator = (DCM_VALUE_UL_CLASS& source)
// DESCRIPTION : Equal operator.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
// copy all members
identifierM = source.identifierM;
UINT32 value;
source.Get(value);
Set(value);
return true;
}
|
[
"marco.kemper@dvtk.org"
] |
marco.kemper@dvtk.org
|
bc949847e11d14bab314ca201cacacfc9d95eaee
|
696e35ccdf167c3f6b1a7f5458406d3bb81987c9
|
/media/gpu/command_buffer_helper.h
|
13744e53e8f60d4e35fd712b720d5639bcef30d6
|
[
"BSD-3-Clause"
] |
permissive
|
mgh3326/iridium-browser
|
064e91a5e37f4e8501ea971483bd1c76297261c3
|
e7de6a434d2659f02e94917be364a904a442d2d0
|
refs/heads/master
| 2023-03-30T16:18:27.391772
| 2019-04-24T02:14:32
| 2019-04-24T02:14:32
| 183,128,065
| 0
| 0
|
BSD-3-Clause
| 2019-11-30T06:06:02
| 2019-04-24T02:04:51
| null |
UTF-8
|
C++
| false
| false
| 5,104
|
h
|
// Copyright 2018 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.
#ifndef MEDIA_GPU_COMMAND_BUFFER_HELPER_H_
#define MEDIA_GPU_COMMAND_BUFFER_HELPER_H_
#include "base/callback_forward.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_refptr.h"
#include "gpu/command_buffer/common/mailbox.h"
#include "gpu/command_buffer/common/sync_token.h"
#include "media/gpu/media_gpu_export.h"
#include "ui/gl/gl_bindings.h"
namespace gpu {
class CommandBufferStub;
} // namespace gpu
namespace gl {
class GLContext;
class GLImage;
} // namespace gl
namespace media {
// TODO(sandersd): CommandBufferHelper does not inherently need to be ref
// counted, but some clients want that (VdaVideoDecoder and PictureBufferManager
// both hold a ref to the same CommandBufferHelper). Consider making an owned
// variant.
class MEDIA_GPU_EXPORT CommandBufferHelper
: public base::RefCountedThreadSafe<CommandBufferHelper> {
public:
REQUIRE_ADOPTION_FOR_REFCOUNTED_TYPE();
using WillDestroyStubCB = base::OnceCallback<void(bool have_context)>;
// TODO(sandersd): Consider adding an Initialize(stub) method so that
// CommandBufferHelpers can be created before a stub is available.
static scoped_refptr<CommandBufferHelper> Create(
gpu::CommandBufferStub* stub);
// Gets the associated GLContext.
//
// Used by DXVAVDA to test for D3D11 support, and by V4L2VDA to create
// EGLImages. New clients should use more specialized accessors instead.
virtual gl::GLContext* GetGLContext() = 0;
// Checks whether the stub has been destroyed.
virtual bool HasStub() = 0;
// Makes the GL context current.
virtual bool MakeContextCurrent() = 0;
// Creates a texture and returns its |service_id|.
//
// See glTexImage2D() for argument definitions.
//
// The texture will be configured as a video frame: linear filtering, clamp to
// edge. If |target| is GL_TEXTURE_2D, storage will be allocated but not
// initialized.
//
// It is up to the caller to initialize the texture before providing it to the
// renderer, else the results are undefined.
//
// The context must be current.
//
// TODO(sandersd): Is really necessary to allocate storage? GpuVideoDecoder
// does this, but it's not clear that any clients require it.
virtual GLuint CreateTexture(GLenum target,
GLenum internal_format,
GLsizei width,
GLsizei height,
GLenum format,
GLenum type) = 0;
// Destroys a texture.
//
// The context must be current.
virtual void DestroyTexture(GLuint service_id) = 0;
// Sets the cleared flag on level 0 of the texture.
virtual void SetCleared(GLuint service_id) = 0;
// Binds level 0 of the texture to an image.
//
// If the sampler binding already exists, set |client_managed| to true.
// Otherwise set it to false, and BindTexImage()/CopyTexImage() will be called
// when the texture is used.
virtual bool BindImage(GLuint service_id,
gl::GLImage* image,
bool client_managed) = 0;
// Creates a mailbox for a texture.
//
// TODO(sandersd): Specify the behavior when the stub has been destroyed. The
// current implementation returns an empty (zero) mailbox. One solution would
// be to add a HasStub() method, and not define behavior when it is false.
virtual gpu::Mailbox CreateMailbox(GLuint service_id) = 0;
// Produce a texture into a mailbox. The context does not have to be current.
// However, this will fail if the stub has been destroyed.
virtual void ProduceTexture(const gpu::Mailbox& mailbox,
GLuint service_id) = 0;
// Waits for a SyncToken, then runs |done_cb|.
//
// |done_cb| may be destructed without running if the stub is destroyed.
//
// TODO(sandersd): Currently it is possible to lose the stub while
// PictureBufferManager is waiting for all picture buffers, which results in a
// decoding softlock. Notification of wait failure (or just context/stub lost)
// is probably necessary.
virtual void WaitForSyncToken(gpu::SyncToken sync_token,
base::OnceClosure done_cb) = 0;
// Set the callback to be called when our stub is destroyed. This callback
// may not change the current context.
virtual void SetWillDestroyStubCB(WillDestroyStubCB will_destroy_stub_cb) = 0;
protected:
CommandBufferHelper() = default;
// TODO(sandersd): Deleting remaining textures upon destruction requires
// making the context current, which may be undesireable. Consider adding an
// explicit DestroyWithContext() API.
virtual ~CommandBufferHelper() = default;
private:
friend class base::RefCountedThreadSafe<CommandBufferHelper>;
DISALLOW_COPY_AND_ASSIGN(CommandBufferHelper);
};
} // namespace media
#endif // MEDIA_GPU_COMMAND_BUFFER_HELPER_H_
|
[
"commit-bot@chromium.org"
] |
commit-bot@chromium.org
|
d848543165c911d67f18f6fc3dd2334212dc102b
|
ca0f494b45522eab05d0342f25b1f0907ce1d720
|
/sources/services/sysmgr/srv/src/NetRpc.cpp
|
b7e345feb207fa06a82510d93df6159d639466a5
|
[] |
no_license
|
hackboxguy/brbox
|
9f79f21097685464c9c9a429603e586e034f8cae
|
ba3850807067b7f623ead5f65dad9c0bf0b3ec2d
|
refs/heads/master
| 2023-07-21T15:38:07.666015
| 2023-07-10T11:51:00
| 2023-07-10T11:51:00
| 32,072,062
| 26
| 9
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 13,846
|
cpp
|
#include "NetRpc.h"
#include "ADSysInfo.hpp"
//#include "SysmgrJsonDef.h"
/* ------------------------------------------------------------------------- */
NetRpc:: NetRpc(std::string rpcName,int myIndex,bool emu,bool log,SYSMGR_CMN_DATA_CACHE *pData):ADJsonRpcMgrConsumer(rpcName,myIndex,emu,log)
{
pDataCache=pData;
}
/* ------------------------------------------------------------------------- */
NetRpc::~ NetRpc()
{
}
/* ------------------------------------------------------------------------- */
int NetRpc::MapJsonToBinary(JsonDataCommObj* pReq,int index)
{
//printf("NetRpc::MapJsonToBinary called\n");
EJSON_SYSMGR_RPC_TYPES command =(EJSON_SYSMGR_RPC_TYPES)index;
switch(command)
{
case EJSON_SYSMGR_RPC_GET_MAC_ADDR :return json_to_bin_get_mac_addr(pReq);
case EJSON_SYSMGR_RPC_SET_MAC_ADDR :return json_to_bin_set_mac_addr(pReq);
case EJSON_SYSMGR_RPC_GET_ETH_COUNT:return json_to_bin_get_eth_count(pReq);
case EJSON_SYSMGR_RPC_GET_ETH_NAME :return json_to_bin_get_eth_name(pReq);
case EJSON_SYSMGR_RPC_GET_IP_ADDR :return json_to_bin_get_ip_addr(pReq);
case EJSON_SYSMGR_RPC_SET_IP_ADDR :return json_to_bin_set_ip_addr(pReq);
case EJSON_SYSMGR_RPC_GET_NETMASK :return json_to_bin_get_netmask(pReq);
case EJSON_SYSMGR_RPC_SET_NETMASK :return json_to_bin_set_netmask(pReq);
}
return -1;//0;
}
/* ------------------------------------------------------------------------- */
int NetRpc::MapBinaryToJson(JsonDataCommObj* pReq,int index)
{
//printf("NetRpc::MapBinaryToJson called\n");
EJSON_SYSMGR_RPC_TYPES command =(EJSON_SYSMGR_RPC_TYPES)index;
switch(command)
{
case EJSON_SYSMGR_RPC_GET_MAC_ADDR :return bin_to_json_get_mac_addr(pReq);
case EJSON_SYSMGR_RPC_SET_MAC_ADDR :return bin_to_json_set_mac_addr(pReq);
case EJSON_SYSMGR_RPC_GET_ETH_COUNT:return bin_to_json_get_eth_count(pReq);
case EJSON_SYSMGR_RPC_GET_ETH_NAME :return bin_to_json_get_eth_name(pReq);
case EJSON_SYSMGR_RPC_GET_IP_ADDR :return bin_to_json_get_ip_addr(pReq);
case EJSON_SYSMGR_RPC_SET_IP_ADDR :return bin_to_json_set_ip_addr(pReq);
case EJSON_SYSMGR_RPC_GET_NETMASK :return bin_to_json_get_netmask(pReq);
case EJSON_SYSMGR_RPC_SET_NETMASK :return bin_to_json_set_netmask(pReq);
}
return -1;
}
/* ------------------------------------------------------------------------- */
int NetRpc::ProcessWork(JsonDataCommObj* pReq,int index,ADJsonRpcMgrProducer* pObj)
{
//printf("NetRpc::ProcessWork called\n");
EJSON_SYSMGR_RPC_TYPES command =(EJSON_SYSMGR_RPC_TYPES)index;
switch(command)
{
case EJSON_SYSMGR_RPC_GET_MAC_ADDR :return process_get_mac_addr(pReq);
case EJSON_SYSMGR_RPC_SET_MAC_ADDR :return process_set_mac_addr(pReq);
case EJSON_SYSMGR_RPC_GET_ETH_COUNT:return process_get_eth_count(pReq);
case EJSON_SYSMGR_RPC_GET_ETH_NAME :return process_get_eth_name(pReq);
case EJSON_SYSMGR_RPC_GET_IP_ADDR :return process_get_ip_addr(pReq);
case EJSON_SYSMGR_RPC_SET_IP_ADDR :return process_set_ip_addr(pReq);
case EJSON_SYSMGR_RPC_GET_NETMASK :return process_get_netmask(pReq);
case EJSON_SYSMGR_RPC_SET_NETMASK :return process_set_netmask(pReq);
}
return 0;
}
/* ------------------------------------------------------------------------- */
RPC_SRV_RESULT NetRpc::ProcessWorkAsync(int index,unsigned char* pWorkData)
{
RPC_SRV_RESULT ret_val=RPC_SRV_RESULT_FAIL;
return ret_val;
}
/* ------------------------------------------------------------------------- */
int NetRpc::json_to_bin_get_mac_addr(JsonDataCommObj* pReq)
{
SYSMGR_MAC_ADDR_PACKET* pPanelCmdObj=NULL;
PREPARE_JSON_REQUEST(RPC_SRV_REQ,SYSMGR_MAC_ADDR_PACKET,RPC_SRV_ACT_READ,EJSON_SYSMGR_RPC_GET_MAC_ADDR);
//after assigning pointer to pPanelReq->dataRef, modify cmd-req-obj with correct client arguments
//JSON_STRING_TO_ENUM(SYSMGR_RPC_MAC_ADDR_ARG_IFACE,SYSMGR_RPC_MAC_ADDR_ARG_IFACE_TABL,EJSON_SYSMGR_IFACE_TYPE,EJSON_SYSMGR_IFACE_TYPE_UNKNOWN,pPanelCmdObj->eth_type);
JSON_STRING_TO_STRING(SYSMGR_RPC_IP_ADDR_ARG_IFACE,pPanelCmdObj->eth_name);//changed from fixed enum list to string
return 0;
}
int NetRpc::bin_to_json_get_mac_addr(JsonDataCommObj* pReq)
{
PREPARE_JSON_RESP_STRING(RPC_SRV_REQ,SYSMGR_MAC_ADDR_PACKET,SYSMGR_RPC_MAC_ADDR_ARG,mac_addr);
return 0;
}
int NetRpc::process_get_mac_addr(JsonDataCommObj* pReq)
{
ADSysInfo SysInfo;//lib-class for reading cpu-info and system-info
char ip[512];char netmask[512];
RPC_SRV_REQ *pPanelReq=NULL;
pPanelReq=(RPC_SRV_REQ *)pReq->pDataObj;
SYSMGR_MAC_ADDR_PACKET* pPacket;
pPacket=(SYSMGR_MAC_ADDR_PACKET*)pPanelReq->dataRef;
const char *table[] = SYSMGR_RPC_MAC_ADDR_ARG_IFACE_TABL;
//if network is connected,then read details from SysInfo
//if(SysInfo.read_network_info((char*)table[pPacket->eth_type],pPacket->mac_addr,ip,netmask)==0)
if(SysInfo.read_network_info(pPacket->eth_name,pPacket->mac_addr,ip,netmask)==0)
pPanelReq->result=RPC_SRV_RESULT_SUCCESS;
else
{
//if network is not connected, use ifconfig method
//if(SysInfo.read_network_info_ifconfig((char*)table[pPacket->eth_type],pPacket->mac_addr,ip,netmask)==0)
if(SysInfo.read_network_info_ifconfig(pPacket->eth_name,pPacket->mac_addr,ip,netmask)==0)
pPanelReq->result=RPC_SRV_RESULT_SUCCESS;
else
pPanelReq->result=RPC_SRV_RESULT_FAIL;
}
return 0;
}
/* ------------------------------------------------------------------------- */
int NetRpc::json_to_bin_set_mac_addr(JsonDataCommObj* pReq)
{
SYSMGR_MAC_ADDR_PACKET* pPanelCmdObj=NULL;
PREPARE_JSON_REQUEST(RPC_SRV_REQ,SYSMGR_MAC_ADDR_PACKET,RPC_SRV_ACT_WRITE,EJSON_SYSMGR_RPC_SET_MAC_ADDR);
//after assigning pointer to pPanelReq->dataRef, modify cmd-req-obj with correct client arguments
JSON_STRING_TO_ENUM(SYSMGR_RPC_MAC_ADDR_ARG_IFACE,SYSMGR_RPC_MAC_ADDR_ARG_IFACE_TABL,EJSON_SYSMGR_IFACE_TYPE,EJSON_SYSMGR_IFACE_TYPE_UNKNOWN,pPanelCmdObj->eth_type);
return 0;
}
int NetRpc::bin_to_json_set_mac_addr(JsonDataCommObj* pReq)
{
PREPARE_JSON_RESP(RPC_SRV_REQ,SYSMGR_MAC_ADDR_PACKET);
return 0;
}
int NetRpc::process_set_mac_addr(JsonDataCommObj* pReq)
{
//TODO:dont supprt mac writing yet
RPC_SRV_REQ *pPanelReq=NULL;
pPanelReq=(RPC_SRV_REQ *)pReq->pDataObj;
pPanelReq->result=RPC_SRV_RESULT_FEATURE_UNSUPPORTED;
return 0;
}
/* ------------------------------------------------------------------------- */
int NetRpc::json_to_bin_get_eth_count(JsonDataCommObj* pReq)
{
SYSMGR_ETH_COUNT_PACKET* pPanelCmdObj=NULL;
PREPARE_JSON_REQUEST(RPC_SRV_REQ,SYSMGR_ETH_COUNT_PACKET,RPC_SRV_ACT_READ,EJSON_SYSMGR_RPC_GET_ETH_COUNT);
return 0;
}
int NetRpc::bin_to_json_get_eth_count(JsonDataCommObj* pReq)
{
PREPARE_JSON_RESP_INT(RPC_SRV_REQ,SYSMGR_MAC_ADDR_PACKET,SYSMGR_RPC_ETH_COUNT_ARG,EthCountIndx);
return 0;
}
int NetRpc::process_get_eth_count(JsonDataCommObj* pReq)
{
RPC_SRV_REQ *pPanelReq=NULL;
pPanelReq=(RPC_SRV_REQ *)pReq->pDataObj;
SYSMGR_ETH_COUNT_PACKET* pPacket;
pPacket=(SYSMGR_ETH_COUNT_PACKET*)pPanelReq->dataRef;
pPacket->EthCountIndx=0;
ADSysInfo SysInfo;
pPanelReq->result=SysInfo.get_total_eth_count(pPacket->EthCountIndx);
return 0;
}
/* ------------------------------------------------------------------------- */
int NetRpc::json_to_bin_get_eth_name(JsonDataCommObj* pReq)
{
SYSMGR_ETH_NAME_PACKET* pPanelCmdObj=NULL;
PREPARE_JSON_REQUEST(RPC_SRV_REQ,SYSMGR_ETH_NAME_PACKET,RPC_SRV_ACT_READ,EJSON_SYSMGR_RPC_GET_ETH_NAME);
JSON_STRING_TO_INT(SYSMGR_RPC_ETH_NAME_ARG_INDEX,pPanelCmdObj->EthCountIndx);
return 0;
}
int NetRpc::bin_to_json_get_eth_name(JsonDataCommObj* pReq)
{
PREPARE_JSON_RESP_STRING(RPC_SRV_REQ,SYSMGR_ETH_NAME_PACKET,SYSMGR_RPC_ETH_NAME_ARG,eth_name);
return 0;
}
int NetRpc::process_get_eth_name(JsonDataCommObj* pReq)
{
RPC_SRV_REQ *pPanelReq=NULL;
pPanelReq=(RPC_SRV_REQ *)pReq->pDataObj;
SYSMGR_ETH_COUNT_PACKET* pPacket;
pPacket=(SYSMGR_ETH_COUNT_PACKET*)pPanelReq->dataRef;
//pPacket->EthCountIndx=0;
//TODO:
ADSysInfo SysInfo;int tmpCount;
pPanelReq->result=SysInfo.get_total_eth_count(tmpCount);
if(pPanelReq->result!=RPC_SRV_RESULT_SUCCESS)
return 0;
if(tmpCount==0)
{
pPanelReq->result=RPC_SRV_RESULT_FAIL;//no eth interfaces are available
return 0;
}
//zero based index must be passed by the client
if(pPacket->EthCountIndx > (tmpCount-1) )
{
pPanelReq->result=RPC_SRV_RESULT_ARG_ERROR;
return 0;
}
pPanelReq->result=SysInfo.get_nth_eth_name(pPacket->EthCountIndx+1,pPacket->eth_name);
return 0;
}
/* ------------------------------------------------------------------------- */
int NetRpc::json_to_bin_get_ip_addr(JsonDataCommObj* pReq)
{
SYSMGR_NET_INFO_PACKET* pPanelCmdObj=NULL;
PREPARE_JSON_REQUEST(RPC_SRV_REQ,SYSMGR_NET_INFO_PACKET,RPC_SRV_ACT_READ,EJSON_SYSMGR_RPC_GET_IP_ADDR);
//after assigning pointer to pPanelReq->dataRef, modify cmd-req-obj with correct client arguments
//JSON_STRING_TO_ENUM(SYSMGR_RPC_IP_ADDR_ARG_IFACE,SYSMGR_RPC_IP_ADDR_ARG_IFACE_TABL,EJSON_SYSMGR_IFACE_TYPE,EJSON_SYSMGR_IFACE_TYPE_UNKNOWN,pPanelCmdObj->eth_type);
JSON_STRING_TO_STRING(SYSMGR_RPC_IP_ADDR_ARG_IFACE,pPanelCmdObj->eth_name);//changed from fixed enum list to string
return 0;
}
int NetRpc::bin_to_json_get_ip_addr(JsonDataCommObj* pReq)
{
PREPARE_JSON_RESP_STRING(RPC_SRV_REQ,SYSMGR_NET_INFO_PACKET,SYSMGR_RPC_IP_ADDR_ARG,addr);
return 0;
}
int NetRpc::process_get_ip_addr(JsonDataCommObj* pReq)
{
ADSysInfo SysInfo;//lib-class for reading cpu-info and system-info
char netmask[512];char mac[512];
RPC_SRV_REQ *pPanelReq=NULL;
pPanelReq=(RPC_SRV_REQ *)pReq->pDataObj;
SYSMGR_NET_INFO_PACKET* pPacket;
pPacket=(SYSMGR_NET_INFO_PACKET*)pPanelReq->dataRef;
const char *table[] = SYSMGR_RPC_MAC_ADDR_ARG_IFACE_TABL;
//if network is connected,then read details from SysInfo
//if(SysInfo.read_network_info((char*)table[pPacket->eth_type],mac,pPacket->addr,netmask)==0)
if(SysInfo.read_network_info(pPacket->eth_name,mac,pPacket->addr,netmask)==0)
pPanelReq->result=RPC_SRV_RESULT_SUCCESS;
else
{
//if network is not connected, use ifconfig method
//if(SysInfo.read_network_info_ifconfig((char*)table[pPacket->eth_type],mac,pPacket->addr,netmask)==0)
if(SysInfo.read_network_info_ifconfig(pPacket->eth_name,mac,pPacket->addr,netmask)==0)
pPanelReq->result=RPC_SRV_RESULT_SUCCESS;
else
pPanelReq->result=RPC_SRV_RESULT_FAIL;
}
return 0;
}
int NetRpc::json_to_bin_set_ip_addr(JsonDataCommObj* pReq)
{
SYSMGR_NET_INFO_PACKET* pPanelCmdObj=NULL;
PREPARE_JSON_REQUEST(RPC_SRV_REQ,SYSMGR_NET_INFO_PACKET,RPC_SRV_ACT_WRITE,EJSON_SYSMGR_RPC_SET_IP_ADDR);
//after assigning pointer to pPanelReq->dataRef, modify cmd-req-obj with correct client arguments
JSON_STRING_TO_ENUM(SYSMGR_RPC_IP_ADDR_ARG_IFACE,SYSMGR_RPC_IP_ADDR_ARG_IFACE_TABL,EJSON_SYSMGR_IFACE_TYPE,EJSON_SYSMGR_IFACE_TYPE_UNKNOWN,pPanelCmdObj->eth_type);
return 0;
}
int NetRpc::bin_to_json_set_ip_addr(JsonDataCommObj* pReq)
{
PREPARE_JSON_RESP(RPC_SRV_REQ,SYSMGR_NET_INFO_PACKET);
return 0;
}
int NetRpc::process_set_ip_addr(JsonDataCommObj* pReq)
{
//TODO:dont supprt mac writing yet
RPC_SRV_REQ *pPanelReq=NULL;
pPanelReq=(RPC_SRV_REQ *)pReq->pDataObj;
pPanelReq->result=RPC_SRV_RESULT_FEATURE_UNSUPPORTED;
return 0;
}
/* ------------------------------------------------------------------------- */
int NetRpc::json_to_bin_get_netmask(JsonDataCommObj* pReq)
{
SYSMGR_NET_INFO_PACKET* pPanelCmdObj=NULL;
PREPARE_JSON_REQUEST(RPC_SRV_REQ,SYSMGR_NET_INFO_PACKET,RPC_SRV_ACT_READ,EJSON_SYSMGR_RPC_GET_NETMASK);
//after assigning pointer to pPanelReq->dataRef, modify cmd-req-obj with correct client arguments
//JSON_STRING_TO_ENUM(SYSMGR_RPC_NETMASK_ARG_IFACE,SYSMGR_RPC_NETMASK_ARG_IFACE_TABL,EJSON_SYSMGR_IFACE_TYPE,EJSON_SYSMGR_IFACE_TYPE_UNKNOWN,pPanelCmdObj->eth_type);
JSON_STRING_TO_STRING(SYSMGR_RPC_IP_ADDR_ARG_IFACE,pPanelCmdObj->eth_name);//changed from fixed enum list to string
return 0;
}
int NetRpc::bin_to_json_get_netmask(JsonDataCommObj* pReq)
{
PREPARE_JSON_RESP_STRING(RPC_SRV_REQ,SYSMGR_NET_INFO_PACKET,SYSMGR_RPC_NETMASK_ARG,addr);
return 0;
}
int NetRpc::process_get_netmask(JsonDataCommObj* pReq)
{
ADSysInfo SysInfo;//lib-class for reading cpu-info and system-info
char ip[512];char mac[512];
RPC_SRV_REQ *pPanelReq=NULL;
pPanelReq=(RPC_SRV_REQ *)pReq->pDataObj;
SYSMGR_NET_INFO_PACKET* pPacket;
pPacket=(SYSMGR_NET_INFO_PACKET*)pPanelReq->dataRef;
const char *table[] = SYSMGR_RPC_MAC_ADDR_ARG_IFACE_TABL;
//if network is connected,then read details from SysInfo
//if(SysInfo.read_network_info((char*)table[pPacket->eth_type],mac,ip,pPacket->addr)==0)
if(SysInfo.read_network_info(pPacket->eth_name,mac,ip,pPacket->addr)==0)
pPanelReq->result=RPC_SRV_RESULT_SUCCESS;
else
{
//if network is not connected, use ifconfig method
//if(SysInfo.read_network_info_ifconfig((char*)table[pPacket->eth_type],mac,ip,pPacket->addr)==0)
if(SysInfo.read_network_info_ifconfig(pPacket->eth_name,mac,ip,pPacket->addr)==0)
pPanelReq->result=RPC_SRV_RESULT_SUCCESS;
else
pPanelReq->result=RPC_SRV_RESULT_FAIL;
}
return 0;
}
int NetRpc::json_to_bin_set_netmask(JsonDataCommObj* pReq)
{
SYSMGR_NET_INFO_PACKET* pPanelCmdObj=NULL;
PREPARE_JSON_REQUEST(RPC_SRV_REQ,SYSMGR_NET_INFO_PACKET,RPC_SRV_ACT_WRITE,EJSON_SYSMGR_RPC_SET_NETMASK);
//after assigning pointer to pPanelReq->dataRef, modify cmd-req-obj with correct client arguments
JSON_STRING_TO_ENUM(SYSMGR_RPC_NETMASK_ARG_IFACE,SYSMGR_RPC_NETMASK_ARG_IFACE_TABL,EJSON_SYSMGR_IFACE_TYPE,EJSON_SYSMGR_IFACE_TYPE_UNKNOWN,pPanelCmdObj->eth_type);
return 0;
}
int NetRpc::bin_to_json_set_netmask(JsonDataCommObj* pReq)
{
PREPARE_JSON_RESP(RPC_SRV_REQ,SYSMGR_NET_INFO_PACKET);
return 0;
}
int NetRpc::process_set_netmask(JsonDataCommObj* pReq)
{
//TODO:dont supprt mac writing yet
RPC_SRV_REQ *pPanelReq=NULL;
pPanelReq=(RPC_SRV_REQ *)pReq->pDataObj;
pPanelReq->result=RPC_SRV_RESULT_FEATURE_UNSUPPORTED;
return 0;
}
/* ------------------------------------------------------------------------- */
|
[
"albert.david@gmail.com"
] |
albert.david@gmail.com
|
7a5b27cc8aeefb3b49e1f3dfee406d6eacd3be5d
|
b4826dd67114c5282b769fc9d658c9c55617a96d
|
/DataStructuresLearningSoftware/DataStructuresLearningSoftware/LinkedList1.h
|
8e8862c2bea61d946a490efe5f799bfe565ad7be
|
[] |
no_license
|
Kethavath9199/Data-Structures-Software-Learning
|
c7d5ed7efaab9baf0ee014311c7727ccbbea0208
|
990512de73234a9f7c348bdca4b38f529ff72a3f
|
refs/heads/master
| 2022-11-26T21:11:32.731210
| 2020-08-06T15:17:04
| 2020-08-06T15:17:04
| 285,603,091
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 24,123
|
h
|
#pragma once
#include "LinkedList_Introduction.h"
#include "LinkedList_Insertion.h"
#include "LinkedList_Deletion.h"
#include "LinkedList_Traversal.h"
#include "Quiz.h"
#include "DiscussionForum.h"
namespace DataStructuresLearningSoftware {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
/// <summary>
/// Summary for LinkedList1
/// </summary>
public ref class LinkedList1 : public System::Windows::Forms::Form
{
public:
LinkedList1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
/// <summary>
/// Clean up any resources being used.
/// </summary>
~LinkedList1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Panel^ panel1;
protected:
private: System::Windows::Forms::Panel^ panel2;
private: System::Windows::Forms::Panel^ MainPanel;
private: System::Windows::Forms::Button^ btnTraversal;
private: System::Windows::Forms::Button^ btnDeletion;
private: System::Windows::Forms::Button^ btnInsertion;
private: System::Windows::Forms::Button^ btnIntroduction;
private: System::Windows::Forms::Button^ btnQuiz;
private: System::Windows::Forms::Button^ btnHome;
private: System::Windows::Forms::Button^ btnNext;
private: System::Windows::Forms::Button^ btnBack;
private: System::Windows::Forms::Label^ lblWelcome;
private: System::Windows::Forms::Button^ button1;
private:
/// <summary>
/// Required designer variable.
/// </summary>
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent(void)
{
System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(LinkedList1::typeid));
this->panel1 = (gcnew System::Windows::Forms::Panel());
this->btnQuiz = (gcnew System::Windows::Forms::Button());
this->btnTraversal = (gcnew System::Windows::Forms::Button());
this->btnDeletion = (gcnew System::Windows::Forms::Button());
this->btnInsertion = (gcnew System::Windows::Forms::Button());
this->btnIntroduction = (gcnew System::Windows::Forms::Button());
this->panel2 = (gcnew System::Windows::Forms::Panel());
this->button1 = (gcnew System::Windows::Forms::Button());
this->lblWelcome = (gcnew System::Windows::Forms::Label());
this->btnHome = (gcnew System::Windows::Forms::Button());
this->btnNext = (gcnew System::Windows::Forms::Button());
this->btnBack = (gcnew System::Windows::Forms::Button());
this->MainPanel = (gcnew System::Windows::Forms::Panel());
this->panel1->SuspendLayout();
this->panel2->SuspendLayout();
this->SuspendLayout();
//
// panel1
//
this->panel1->BackColor = System::Drawing::Color::AliceBlue;
this->panel1->Controls->Add(this->btnQuiz);
this->panel1->Controls->Add(this->btnTraversal);
this->panel1->Controls->Add(this->btnDeletion);
this->panel1->Controls->Add(this->btnInsertion);
this->panel1->Controls->Add(this->btnIntroduction);
this->panel1->Location = System::Drawing::Point(0, 0);
this->panel1->Name = L"panel1";
this->panel1->Size = System::Drawing::Size(175, 720);
this->panel1->TabIndex = 0;
//
// btnQuiz
//
this->btnQuiz->Cursor = System::Windows::Forms::Cursors::Hand;
this->btnQuiz->FlatAppearance->BorderSize = 0;
this->btnQuiz->FlatStyle = System::Windows::Forms::FlatStyle::Popup;
this->btnQuiz->Font = (gcnew System::Drawing::Font(L"Comic Sans MS", 11.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->btnQuiz->Location = System::Drawing::Point(0, 210);
this->btnQuiz->Name = L"btnQuiz";
this->btnQuiz->Size = System::Drawing::Size(175, 40);
this->btnQuiz->TabIndex = 4;
this->btnQuiz->Text = L"Quiz Time";
this->btnQuiz->UseVisualStyleBackColor = true;
this->btnQuiz->Click += gcnew System::EventHandler(this, &LinkedList1::btnQuiz_Click);
//
// btnTraversal
//
this->btnTraversal->Cursor = System::Windows::Forms::Cursors::Hand;
this->btnTraversal->FlatAppearance->BorderSize = 0;
this->btnTraversal->FlatStyle = System::Windows::Forms::FlatStyle::Popup;
this->btnTraversal->Font = (gcnew System::Drawing::Font(L"Comic Sans MS", 11.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->btnTraversal->Location = System::Drawing::Point(0, 170);
this->btnTraversal->Name = L"btnTraversal";
this->btnTraversal->Size = System::Drawing::Size(175, 40);
this->btnTraversal->TabIndex = 3;
this->btnTraversal->Text = L"Traversal";
this->btnTraversal->UseVisualStyleBackColor = true;
this->btnTraversal->Click += gcnew System::EventHandler(this, &LinkedList1::btnTraversal_Click);
//
// btnDeletion
//
this->btnDeletion->Cursor = System::Windows::Forms::Cursors::Hand;
this->btnDeletion->FlatAppearance->BorderSize = 0;
this->btnDeletion->FlatStyle = System::Windows::Forms::FlatStyle::Popup;
this->btnDeletion->Font = (gcnew System::Drawing::Font(L"Comic Sans MS", 11.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->btnDeletion->Location = System::Drawing::Point(0, 130);
this->btnDeletion->Name = L"btnDeletion";
this->btnDeletion->Size = System::Drawing::Size(175, 40);
this->btnDeletion->TabIndex = 2;
this->btnDeletion->Text = L"Deletion";
this->btnDeletion->UseVisualStyleBackColor = true;
this->btnDeletion->Click += gcnew System::EventHandler(this, &LinkedList1::btnDeletion_Click);
//
// btnInsertion
//
this->btnInsertion->Cursor = System::Windows::Forms::Cursors::Hand;
this->btnInsertion->FlatAppearance->BorderSize = 0;
this->btnInsertion->FlatStyle = System::Windows::Forms::FlatStyle::Popup;
this->btnInsertion->Font = (gcnew System::Drawing::Font(L"Comic Sans MS", 11.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->btnInsertion->Location = System::Drawing::Point(0, 90);
this->btnInsertion->Name = L"btnInsertion";
this->btnInsertion->Size = System::Drawing::Size(175, 40);
this->btnInsertion->TabIndex = 1;
this->btnInsertion->Text = L"Insertion";
this->btnInsertion->UseVisualStyleBackColor = true;
this->btnInsertion->Click += gcnew System::EventHandler(this, &LinkedList1::btnInsertion_Click);
//
// btnIntroduction
//
this->btnIntroduction->Cursor = System::Windows::Forms::Cursors::Hand;
this->btnIntroduction->FlatAppearance->BorderSize = 0;
this->btnIntroduction->FlatStyle = System::Windows::Forms::FlatStyle::Popup;
this->btnIntroduction->Font = (gcnew System::Drawing::Font(L"Comic Sans MS", 11.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->btnIntroduction->Location = System::Drawing::Point(0, 50);
this->btnIntroduction->Name = L"btnIntroduction";
this->btnIntroduction->Size = System::Drawing::Size(175, 40);
this->btnIntroduction->TabIndex = 0;
this->btnIntroduction->Text = L"Introduction";
this->btnIntroduction->UseVisualStyleBackColor = true;
this->btnIntroduction->Click += gcnew System::EventHandler(this, &LinkedList1::btnIntroduction_Click);
//
// panel2
//
this->panel2->BackColor = System::Drawing::Color::AliceBlue;
this->panel2->Controls->Add(this->button1);
this->panel2->Controls->Add(this->lblWelcome);
this->panel2->Controls->Add(this->btnHome);
this->panel2->Controls->Add(this->btnNext);
this->panel2->Controls->Add(this->btnBack);
this->panel2->Location = System::Drawing::Point(175, 0);
this->panel2->Name = L"panel2";
this->panel2->Size = System::Drawing::Size(1105, 50);
this->panel2->TabIndex = 1;
//
// button1
//
this->button1->BackColor = System::Drawing::Color::CornflowerBlue;
this->button1->FlatAppearance->BorderSize = 0;
this->button1->FlatStyle = System::Windows::Forms::FlatStyle::Popup;
this->button1->Font = (gcnew System::Drawing::Font(L"Comic Sans MS", 11.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->button1->Location = System::Drawing::Point(50, 10);
this->button1->Name = L"button1";
this->button1->Size = System::Drawing::Size(150, 30);
this->button1->TabIndex = 0;
this->button1->Text = L"Discussion Forum";
this->button1->UseVisualStyleBackColor = false;
this->button1->Click += gcnew System::EventHandler(this, &LinkedList1::button1_Click);
//
// lblWelcome
//
this->lblWelcome->Font = (gcnew System::Drawing::Font(L"Comic Sans MS", 11.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->lblWelcome->ForeColor = System::Drawing::Color::Firebrick;
this->lblWelcome->Location = System::Drawing::Point(206, 15);
this->lblWelcome->Name = L"lblWelcome";
this->lblWelcome->Size = System::Drawing::Size(749, 20);
this->lblWelcome->TabIndex = 4;
this->lblWelcome->Text = L"label1";
this->lblWelcome->TextAlign = System::Drawing::ContentAlignment::MiddleRight;
//
// btnHome
//
this->btnHome->Cursor = System::Windows::Forms::Cursors::Hand;
this->btnHome->FlatAppearance->BorderSize = 0;
this->btnHome->FlatStyle = System::Windows::Forms::FlatStyle::Popup;
this->btnHome->Image = (cli::safe_cast<System::Drawing::Image^ >(resources->GetObject(L"btnHome.Image")));
this->btnHome->Location = System::Drawing::Point(1055, 0);
this->btnHome->Name = L"btnHome";
this->btnHome->Size = System::Drawing::Size(50, 50);
this->btnHome->TabIndex = 2;
this->btnHome->UseVisualStyleBackColor = true;
this->btnHome->Click += gcnew System::EventHandler(this, &LinkedList1::btnHome_Click);
//
// btnNext
//
this->btnNext->Cursor = System::Windows::Forms::Cursors::Hand;
this->btnNext->FlatAppearance->BorderSize = 0;
this->btnNext->FlatStyle = System::Windows::Forms::FlatStyle::Popup;
this->btnNext->Image = (cli::safe_cast<System::Drawing::Image^ >(resources->GetObject(L"btnNext.Image")));
this->btnNext->Location = System::Drawing::Point(1005, 0);
this->btnNext->Name = L"btnNext";
this->btnNext->Size = System::Drawing::Size(50, 50);
this->btnNext->TabIndex = 1;
this->btnNext->UseVisualStyleBackColor = true;
this->btnNext->Click += gcnew System::EventHandler(this, &LinkedList1::btnNext_Click);
//
// btnBack
//
this->btnBack->Cursor = System::Windows::Forms::Cursors::Hand;
this->btnBack->FlatAppearance->BorderSize = 0;
this->btnBack->FlatStyle = System::Windows::Forms::FlatStyle::Popup;
this->btnBack->Image = (cli::safe_cast<System::Drawing::Image^ >(resources->GetObject(L"btnBack.Image")));
this->btnBack->Location = System::Drawing::Point(0, 0);
this->btnBack->Name = L"btnBack";
this->btnBack->Size = System::Drawing::Size(50, 50);
this->btnBack->TabIndex = 0;
this->btnBack->UseVisualStyleBackColor = true;
this->btnBack->Click += gcnew System::EventHandler(this, &LinkedList1::btnBack_Click);
//
// MainPanel
//
this->MainPanel->AutoScroll = true;
this->MainPanel->Location = System::Drawing::Point(175, 50);
this->MainPanel->Name = L"MainPanel";
this->MainPanel->Size = System::Drawing::Size(1105, 670);
this->MainPanel->TabIndex = 2;
//
// LinkedList1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->BackColor = System::Drawing::SystemColors::Control;
this->ClientSize = System::Drawing::Size(1280, 720);
this->Controls->Add(this->MainPanel);
this->Controls->Add(this->panel2);
this->Controls->Add(this->panel1);
this->FormBorderStyle = System::Windows::Forms::FormBorderStyle::None;
this->Name = L"LinkedList1";
this->StartPosition = System::Windows::Forms::FormStartPosition::CenterScreen;
this->Text = L"LinkedList1";
this->Load += gcnew System::EventHandler(this, &LinkedList1::LinkedList1_Load);
this->panel1->ResumeLayout(false);
this->panel2->ResumeLayout(false);
this->ResumeLayout(false);
}
#pragma endregion
public: String ^username;
int moduleId;
String ^fullname;
int modulesCompleted;
private: System::Void btnIntroduction_Click(System::Object^ sender, System::EventArgs^ e) {
OleDb::OleDbConnection ^ DB_Connection = gcnew OleDb::OleDbConnection();
DB_Connection->ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+IO::Path::GetDirectoryName(Application::StartupPath)+"\\Database.accdb";
DB_Connection->Open();
String ^readString = "SELECT * FROM Users WHERE UserName='"+username+"'";
OleDbCommand ^ cmd = gcnew OleDbCommand(readString, DB_Connection);
OleDbDataReader ^ reader = cmd->ExecuteReader();
if(reader->Read()){
modulesCompleted = reader->GetInt32(10);
}
DB_Connection->Close();
if(modulesCompleted < 0){ // 0 is module ID of Introduction
MessageBox::Show("Complete the previous module to unlock this module");
}
else{
moduleId = 0;
display();
}
}
private: System::Void btnInsertion_Click(System::Object^ sender, System::EventArgs^ e) {
OleDb::OleDbConnection ^ DB_Connection = gcnew OleDb::OleDbConnection();
DB_Connection->ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+IO::Path::GetDirectoryName(Application::StartupPath)+"\\Database.accdb";
DB_Connection->Open();
String ^readString = "SELECT * FROM Users WHERE UserName='"+username+"'";
OleDbCommand ^ cmd = gcnew OleDbCommand(readString, DB_Connection);
OleDbDataReader ^ reader = cmd->ExecuteReader();
if(reader->Read()){
modulesCompleted = reader->GetInt32(10);
}
DB_Connection->Close();
if(modulesCompleted < 1){ // 1 is module ID of Insertion
MessageBox::Show("Complete the previous module to unlock this module");
}
else{
moduleId = 1;
display();
}
}
private: System::Void btnDeletion_Click(System::Object^ sender, System::EventArgs^ e) {
OleDb::OleDbConnection ^ DB_Connection = gcnew OleDb::OleDbConnection();
DB_Connection->ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+IO::Path::GetDirectoryName(Application::StartupPath)+"\\Database.accdb";
DB_Connection->Open();
String ^readString = "SELECT * FROM Users WHERE UserName='"+username+"'";
OleDbCommand ^ cmd = gcnew OleDbCommand(readString, DB_Connection);
OleDbDataReader ^ reader = cmd->ExecuteReader();
if(reader->Read()){
modulesCompleted = reader->GetInt32(10);
}
DB_Connection->Close();
if(modulesCompleted < 2){ // 2 is module ID of Deletion
MessageBox::Show("Complete the previous module to unlock this module");
}
else{
moduleId = 2;
display();
}
}
private: System::Void btnTraversal_Click(System::Object^ sender, System::EventArgs^ e) {
OleDb::OleDbConnection ^ DB_Connection = gcnew OleDb::OleDbConnection();
DB_Connection->ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+IO::Path::GetDirectoryName(Application::StartupPath)+"\\Database.accdb";
DB_Connection->Open();
String ^readString = "SELECT * FROM Users WHERE UserName='"+username+"'";
OleDbCommand ^ cmd = gcnew OleDbCommand(readString, DB_Connection);
OleDbDataReader ^ reader = cmd->ExecuteReader();
if(reader->Read()){
modulesCompleted = reader->GetInt32(10);
}
DB_Connection->Close();
if(modulesCompleted < 3){ // 3 is module ID of Traversal
MessageBox::Show("Complete the previous module to unlock this module");
}
else{
moduleId = 3;
display();
}
}
private: System::Void btnQuiz_Click(System::Object^ sender, System::EventArgs^ e) {
OleDb::OleDbConnection ^ DB_Connection = gcnew OleDb::OleDbConnection();
DB_Connection->ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+IO::Path::GetDirectoryName(Application::StartupPath)+"\\Database.accdb";
DB_Connection->Open();
String ^readString = "SELECT * FROM Users WHERE UserName='"+username+"'";
OleDbCommand ^ cmd = gcnew OleDbCommand(readString, DB_Connection);
OleDbDataReader ^ reader = cmd->ExecuteReader();
if(reader->Read()){
modulesCompleted = reader->GetInt32(10);
}
DB_Connection->Close();
if(modulesCompleted < 3){ // 4 is module ID of Quiz
MessageBox::Show("Complete the previous module to unlock this module");
}
else{
moduleId = 4;
display();
}
}
private: System::Void LinkedList1_Load(System::Object^ sender, System::EventArgs^ e) {
moduleId = 0;
OleDb::OleDbConnection ^ DB_Connection = gcnew OleDb::OleDbConnection();
DB_Connection->ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+IO::Path::GetDirectoryName(Application::StartupPath)+"\\Database.accdb";
DB_Connection->Open();
String ^readString = "SELECT * FROM Users WHERE UserName='"+username+"'";
OleDbCommand ^ cmd = gcnew OleDbCommand(readString, DB_Connection);
OleDbDataReader ^ reader = cmd->ExecuteReader();
if(reader->Read()){
fullname = reader->GetString(2);
modulesCompleted = reader->GetInt32(10);
}
DB_Connection->Close();
lblWelcome->Text = "Welcome, "+fullname;
display();
}
public: void display(){
if(modulesCompleted == 0){
btnIntroduction->BackColor = Color::IndianRed;
btnInsertion->BackColor = Color::IndianRed;
btnDeletion->BackColor = Color::IndianRed;
btnTraversal->BackColor = Color::IndianRed;
btnQuiz->BackColor = Color::IndianRed;
}
else if(modulesCompleted == 1){
btnIntroduction->BackColor = Color::MediumSeaGreen;
btnInsertion->BackColor = Color::IndianRed;
btnDeletion->BackColor = Color::IndianRed;
btnTraversal->BackColor = Color::IndianRed;
btnQuiz->BackColor = Color::IndianRed;
}
else if(modulesCompleted == 2){
btnIntroduction->BackColor = Color::MediumSeaGreen;
btnInsertion->BackColor = Color::MediumSeaGreen;
btnDeletion->BackColor = Color::IndianRed;
btnTraversal->BackColor = Color::IndianRed;
btnQuiz->BackColor = Color::IndianRed;
}
else if(modulesCompleted == 3){
btnIntroduction->BackColor = Color::MediumSeaGreen;
btnInsertion->BackColor = Color::MediumSeaGreen;
btnDeletion->BackColor = Color::MediumSeaGreen;
btnTraversal->BackColor = Color::IndianRed;
btnQuiz->BackColor = Color::IndianRed;
}
else if(modulesCompleted == 4){
btnIntroduction->BackColor = Color::MediumSeaGreen;
btnInsertion->BackColor = Color::MediumSeaGreen;
btnDeletion->BackColor = Color::MediumSeaGreen;
btnTraversal->BackColor = Color::MediumSeaGreen;
btnQuiz->BackColor = Color::IndianRed;
}
else if(modulesCompleted == 5){
btnIntroduction->BackColor = Color::MediumSeaGreen;
btnInsertion->BackColor = Color::MediumSeaGreen;
btnDeletion->BackColor = Color::MediumSeaGreen;
btnTraversal->BackColor = Color::MediumSeaGreen;
btnQuiz->BackColor = Color::MediumSeaGreen;
}
if(moduleId == 0){
btnIntroduction->BackColor = Color::CornflowerBlue;
btnBack->Hide();
btnNext->Show();
MainPanel->Controls->Clear();
LinkedList_Introduction ^newUserControl = gcnew LinkedList_Introduction();
newUserControl->username = username;
MainPanel->Controls->Add(newUserControl);
}
else if(moduleId == 1){
btnInsertion->BackColor = Color::CornflowerBlue;
btnBack->Show();
btnNext->Show();
MainPanel->Controls->Clear();
LinkedList_Insertion ^newUserControl = gcnew LinkedList_Insertion();
newUserControl->username = username;
MainPanel->Controls->Add(newUserControl);
}
else if(moduleId == 2){
btnDeletion->BackColor = Color::CornflowerBlue;
btnBack->Show();
btnNext->Show();
MainPanel->Controls->Clear();
LinkedList_Deletion ^newUserControl = gcnew LinkedList_Deletion();
newUserControl->username = username;
MainPanel->Controls->Add(newUserControl);
}
else if(moduleId == 3){
btnTraversal->BackColor = Color::CornflowerBlue;
btnBack->Show();
btnNext->Show();
MainPanel->Controls->Clear();
LinkedList_Traversal ^newUserControl = gcnew LinkedList_Traversal();
newUserControl->username = username;
MainPanel->Controls->Add(newUserControl);
}
else if(moduleId == 4){
btnQuiz->BackColor = Color::CornflowerBlue;
btnNext->Hide();
btnBack->Show();
MainPanel->Controls->Clear();
Quiz ^newUserControl = gcnew Quiz();
newUserControl->username = username;
newUserControl->ds_id = 1;
MainPanel->Controls->Add(newUserControl);
}
}
private: System::Void btnBack_Click(System::Object^ sender, System::EventArgs^ e) {
OleDb::OleDbConnection ^ DB_Connection = gcnew OleDb::OleDbConnection();
DB_Connection->ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+IO::Path::GetDirectoryName(Application::StartupPath)+"\\Database.accdb";
DB_Connection->Open();
String ^readString = "SELECT * FROM Users WHERE UserName='"+username+"'";
OleDbCommand ^ cmd = gcnew OleDbCommand(readString, DB_Connection);
OleDbDataReader ^ reader = cmd->ExecuteReader();
if(reader->Read()){
modulesCompleted = reader->GetInt32(10);
}
DB_Connection->Close();
if(moduleId-1 > modulesCompleted){
MessageBox::Show("Complete the previous module to unlock this module");
}
else{
moduleId--;
display();
}
}
private: System::Void btnNext_Click(System::Object^ sender, System::EventArgs^ e) {
OleDb::OleDbConnection ^ DB_Connection = gcnew OleDb::OleDbConnection();
DB_Connection->ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+IO::Path::GetDirectoryName(Application::StartupPath)+"\\Database.accdb";
DB_Connection->Open();
String ^readString = "SELECT * FROM Users WHERE UserName='"+username+"'";
OleDbCommand ^ cmd = gcnew OleDbCommand(readString, DB_Connection);
OleDbDataReader ^ reader = cmd->ExecuteReader();
if(reader->Read()){
modulesCompleted = reader->GetInt32(10);
}
DB_Connection->Close();
if(moduleId+1 > modulesCompleted){
MessageBox::Show("Complete the previous module to unlock this module");
}
else{
moduleId++;
display();
}
}
private: System::Void btnHome_Click(System::Object^ sender, System::EventArgs^ e) {
OleDb::OleDbConnection ^ DB_Connection = gcnew OleDb::OleDbConnection();
DB_Connection->ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+IO::Path::GetDirectoryName(Application::StartupPath)+"\\Database.accdb";
DB_Connection->Open();
String ^readString = "SELECT * FROM Users WHERE UserName='"+username+"'";
OleDbCommand ^ cmd = gcnew OleDbCommand(readString, DB_Connection);
OleDbDataReader ^ reader = cmd->ExecuteReader();
if(reader->Read()){
modulesCompleted = reader->GetInt32(10);
}
this->Close();
}
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
MainPanel->Controls->Clear();
DiscussionForum ^ discuss = gcnew DiscussionForum;
discuss->username=username;
discuss->module="Linked List";
MainPanel->Controls->Add(discuss);
}
};
}
|
[
"kethavathnaveen@192.168.1.5"
] |
kethavathnaveen@192.168.1.5
|
32a996f23bb99a5d1b454fb92cfa81929c3b20cb
|
2b089f87cb277c5f40eb0b89ca593fd6cd96b725
|
/Graph/bridge_2.cpp
|
c776d6da84a129d60314860261a5b3e0443f7efe
|
[] |
no_license
|
ryuat/algorithm
|
f78d0ab8758bb40a24be4508cf8054d75336ad7c
|
2b8dc909a96cb6cbacc46b421ccde92ae40eeacc
|
refs/heads/master
| 2021-07-02T18:46:31.083472
| 2019-02-22T05:43:55
| 2019-02-22T05:43:55
| 134,426,459
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,686
|
cpp
|
/*
다리 만들기 2번째 방법
*/
#include <iostream>
#include <utility>
#include <queue>
int a[100][100]; // (1:육지 2:바다)
int g[100][100]; // 그룹
int d[100][100]; // 거리
int dx[] = {0, 0, -1, 1};
int dy[] = {-1, 1, 0, 0};
using namespace std;
int main(){
int n;
scanf("%d", &n);
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
scanf("%d", &a[i][j]);
g[i][j] = 0; // 그룹 초기화
d[i][j] = -1; // 거리 초기화
}
}
// 육지의 그룹 번호 저장
int grp = 0; //그룹번호
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(a[i][j] == 1 && g[i][j] == 0){ // 육지이고 탐색하지 않았다면
queue<pair<int,int>> q;
q.push(make_pair(i,j));
g[i][j] = ++grp; // 다음 그룹
while(!q.empty()){
int x = q.front().first;
int y = q.front().second;
//printf("%dx%d node 호출\n", x,y);
q.pop();
for(int k=0;k<4;k++){
int nx = x+dx[k];
int ny = y+dy[k];
if(0<=nx && nx < n && 0 <= ny && ny < n){ // 인덱스 존재
if(a[nx][ny] == 1 && g[nx][ny]==0){ // 육지이면서 방문 안했다면
q.push(make_pair(nx,ny));
g[nx][ny] = grp; // 현재 grp
}
}
}
}
}
}
}
// dist 계산 + 그룹 채우기
// start node
queue<pair<int,int>> q;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(a[i][j] == 1 && d[i][j] == -1){ // 육지 노드 & 방문 x 를 모두 start로,
q.push(make_pair(i,j)); // start 노드들 = 육지
d[i][j] = 0;
}
}
}
while(!q.empty()){
int x = q.front().first;
int y = q.front().second;
q.pop();
for(int k=0;k<4;k++){
int nx = x+dx[k];
int ny = y+dy[k];
if(0<=nx && nx < n && 0 <= ny && ny < n){
if(d[nx][ny] == -1){ // 방문 x
d[nx][ny] = d[x][y]+1;
g[nx][ny] = g[x][y];
q.push(make_pair(nx,ny));
}
}
}
}
int ans = n*20*n; // 임의의 큰 수
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
for(int k=0;k<4;k++){ // 인접노드
int nx = i + dx[k];
int ny = j + dy[k];
if(0<=nx && nx < n && 0 <= ny && ny < n){
if(g[nx][ny] != g[i][j]){ //인접노드의 그룹이 다를 경우
if(ans > d[i][j] + d[nx][ny]){ // 인접노드 거리의 합을 구하고
//printf("%dx%d - %dx%d\n",i,j ,nx,ny);
ans = d[i][j] + d[nx][ny]; // 최소값 저장
}
}
}
}
}
}
/*
printf("그룹\n");
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
printf("%2d", g[i][j]);
}
printf("\n");
}
printf("거리\n");
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
printf("%2d", d[i][j]);
}
printf("\n");
}*/
printf("%d\n", ans);
return 0;
}
/*
1. 그룹 저장
2. dist 계산 + 바다 그룹 채우기
3. 서로 다른 그룹이 인접한 바다 중 최소 dist
*/
|
[
"jungohryu@gmail.com"
] |
jungohryu@gmail.com
|
ee7c17de38bfae05742667e6de587c9006096b3f
|
a82facec4d7111825c59c67a859825074823e6f7
|
/IGC/VectorCompiler/lib/Utils/GenX/Printf.cpp
|
4a9981337f5708584d19238c73ebf9cea20f1f24
|
[
"MIT"
] |
permissive
|
mfkiwl/intel-graphics-compiler-dp4a
|
f6f85313f1f62ffc86786fc7d3239d5366a015d1
|
9d3ddd2a85278b225930dac964427a0395c39c58
|
refs/heads/master
| 2023-04-02T17:24:52.035704
| 2021-05-21T02:17:42
| 2021-05-21T04:03:30
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,791
|
cpp
|
/*========================== begin_copyright_notice ============================
Copyright (C) 2021 Intel Corporation
SPDX-License-Identifier: MIT
============================= end_copyright_notice ===========================*/
#include "vc/Utils/GenX/Printf.h"
#include <llvm/GenXIntrinsics/GenXIntrinsics.h>
#include <llvm/ADT/Optional.h>
#include <llvm/ADT/STLExtras.h>
#include <llvm/ADT/StringRef.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/GlobalVariable.h>
#include <llvm/IR/Operator.h>
#include <llvm/IR/Value.h>
#include <llvm/Support/Casting.h>
#include <algorithm>
#include <iterator>
#include <regex>
#include <string>
#include "Probe/Assertion.h"
using namespace llvm;
using namespace vc;
// extracts underlying c-string from provided constant
static StringRef extractCStr(const Constant &CStrConst) {
if (isa<ConstantDataArray>(CStrConst))
return cast<ConstantDataArray>(CStrConst).getAsCString();
IGC_ASSERT(isa<ConstantAggregateZero>(CStrConst));
return "";
}
Optional<StringRef> vc::getConstStringFromOperandOptional(const Value &Op) {
IGC_ASSERT_MESSAGE(Op.getType()->isPointerTy(),
"wrong argument: pointer was expected");
IGC_ASSERT_MESSAGE(Op.getType()->getPointerElementType()->isIntegerTy(8),
"wrong argument: i8* value was expected");
if (!isa<GEPOperator>(Op))
return {};
auto *StrConst = cast<GEPOperator>(Op).getPointerOperand();
if (!isa<GlobalVariable>(StrConst))
return {};
return extractCStr(*cast<GlobalVariable>(StrConst)->getInitializer());
}
StringRef vc::getConstStringFromOperand(const Value &Op) {
auto FmtStr = getConstStringFromOperandOptional(Op);
IGC_ASSERT_MESSAGE(FmtStr.hasValue(),
"couldn't reach constexpr string through pointer operand");
return FmtStr.getValue();
}
using SRefMatch = std::match_results<StringRef::iterator>;
using SRefRegExIterator = std::regex_iterator<StringRef::iterator>;
// Given that \p ArgDesc describes integer conversion with signedness equal to
// \p IsSigned, defines which particular integer type is provided.
static PrintfArgInfo parseIntLengthModifier(StringRef ArgDesc, bool IsSigned) {
std::string Suffix{1u, ArgDesc.back()};
if (ArgDesc.endswith("hh" + Suffix))
return {PrintfArgInfo::Char, IsSigned};
if (ArgDesc.endswith("h" + Suffix))
return {PrintfArgInfo::Short, IsSigned};
if (ArgDesc.endswith("ll" + Suffix))
// TOTHINK: maybe we need a separate type ID for long long.
return {PrintfArgInfo::Long, IsSigned};
if (ArgDesc.endswith("l" + Suffix))
return {PrintfArgInfo::Long, IsSigned};
return {PrintfArgInfo::Int, IsSigned};
}
static StringRef toStringRef(SRefMatch Match) {
IGC_ASSERT_MESSAGE(!Match.empty(),
"wrong argument: matched string is expected");
return {Match[0].first, static_cast<std::size_t>(Match[0].length())};
}
// \p ArgDescMatch is a format string conversion specifier matched by a regex
// (some string that starts with % and ends with d,i,f,...).
static PrintfArgInfo parseArgDesc(SRefMatch ArgDescMatch) {
StringRef ArgDesc = toStringRef(ArgDescMatch);
if (ArgDesc.endswith("c"))
// FIXME: support %lc
return {PrintfArgInfo::Int, /* IsSigned */ true};
if (ArgDesc.endswith("s"))
// FIXME: support %ls
return {PrintfArgInfo::String, /* IsSigned */ false};
if (ArgDesc.endswith("d") || ArgDesc.endswith("i"))
return parseIntLengthModifier(ArgDesc, /* IsSigned */ true);
if (ArgDesc.endswith("o") || ArgDesc.endswith("u") ||
ArgDesc.endswith_lower("x"))
return parseIntLengthModifier(ArgDesc, /* IsSigned */ false);
if (ArgDesc.endswith_lower("f") || ArgDesc.endswith_lower("e") ||
ArgDesc.endswith_lower("a") || ArgDesc.endswith_lower("g"))
return {PrintfArgInfo::Double, /* IsSigned */ true};
IGC_ASSERT_MESSAGE(ArgDesc.endswith("p"), "unexpected conversion specifier");
return {PrintfArgInfo::Pointer, /* IsSigned */ false};
}
PrintfArgInfoSeq vc::parseFormatString(StringRef FmtStr) {
PrintfArgInfoSeq Args;
std::regex ArgDescRegEx{"%(?:%|.*?[csdioxXufFeEaAgGp])"};
auto &&ArgDescs = make_filter_range(
make_range(SRefRegExIterator{FmtStr.begin(), FmtStr.end(), ArgDescRegEx},
SRefRegExIterator{}),
[](SRefMatch ArgDesc) { return toStringRef(ArgDesc) != "%%"; });
transform(ArgDescs, std::back_inserter(Args),
[](SRefMatch ArgDesc) { return parseArgDesc(ArgDesc); });
return Args;
}
bool vc::isPrintFormatIndex(const User &Usr) {
return GenXIntrinsic::getGenXIntrinsicID(&Usr) ==
GenXIntrinsic::genx_print_format_index;
}
static bool isLegalPrintFormatIndexGEPImpl(const User &GEP) {
IGC_ASSERT_MESSAGE(
isa<GEPOperator>(GEP),
"wrong argument: gep instruction or gep constexpr are expected");
if (GEP.user_empty())
return false;
return std::all_of(GEP.user_begin(), GEP.user_end(),
[](const User *Usr) { return isPrintFormatIndex(*Usr); });
}
bool vc::isLegalPrintFormatIndexGEP(const GetElementPtrInst &GEP) {
return isLegalPrintFormatIndexGEPImpl(GEP);
}
bool vc::isLegalPrintFormatIndexGEP(const Value &V) {
if (isa<GetElementPtrInst>(V))
return isLegalPrintFormatIndexGEPImpl(cast<User>(V));
if (isa<ConstantExpr>(V) &&
cast<ConstantExpr>(V).getOpcode() == Instruction::GetElementPtr)
return isLegalPrintFormatIndexGEPImpl(cast<User>(V));
return false;
}
bool vc::isPrintFormatIndexGEP(const GEPOperator &GEP) {
return std::any_of(GEP.user_begin(), GEP.user_end(),
[](const User *Usr) { return isPrintFormatIndex(*Usr); });
}
bool vc::isPrintFormatIndexGEP(const User &Usr) {
if (!isa<GEPOperator>(Usr))
return false;
return isPrintFormatIndexGEP(cast<GEPOperator>(Usr));
}
|
[
"sys_igcbot@intel.com"
] |
sys_igcbot@intel.com
|
f3824b4bac7b5187c5b567a08ac775f2bc9b0271
|
286a310a00923d5e2cec35d9630aedb34dafcdb9
|
/swagger/sdrangel/code/qt5/client/SWGBladeRF2InputReport.cpp
|
5f3e7d89eb985f9fc54af21f59ed1bf7f715a35b
|
[] |
no_license
|
agrawalharshit/sdrangel
|
a98b6565db7484324786898d59ca9c6f1bb6f19b
|
13eae0d8fe6119397177871b8c66ab073255a9d7
|
refs/heads/master
| 2020-04-14T22:10:24.515807
| 2019-01-01T17:57:41
| 2019-01-01T17:57:41
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,153
|
cpp
|
/**
* SDRangel
* This is the web REST/JSON API of SDRangel SDR software. SDRangel is an Open Source Qt5/OpenGL 3.0+ (4.3+ in Windows) GUI and server Software Defined Radio and signal analyzer in software. It supports Airspy, BladeRF, HackRF, LimeSDR, PlutoSDR, RTL-SDR, SDRplay RSP1 and FunCube --- Limitations and specifcities: * In SDRangel GUI the first Rx device set cannot be deleted. Conversely the server starts with no device sets and its number of device sets can be reduced to zero by as many calls as necessary to /sdrangel/deviceset with DELETE method. * Preset import and export from/to file is a server only feature. * Device set focus is a GUI only feature. * The following channels are not implemented (status 501 is returned): ATV and DATV demodulators, Channel Analyzer NG, LoRa demodulator * The device settings and report structures contains only the sub-structure corresponding to the device type. The DeviceSettings and DeviceReport structures documented here shows all of them but only one will be or should be present at a time * The channel settings and report structures contains only the sub-structure corresponding to the channel type. The ChannelSettings and ChannelReport structures documented here shows all of them but only one will be or should be present at a time ---
*
* OpenAPI spec version: 4.3.0
* Contact: f4exb06@gmail.com
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
#include "SWGBladeRF2InputReport.h"
#include "SWGHelpers.h"
#include <QJsonDocument>
#include <QJsonArray>
#include <QObject>
#include <QDebug>
namespace SWGSDRangel {
SWGBladeRF2InputReport::SWGBladeRF2InputReport(QString* json) {
init();
this->fromJson(*json);
}
SWGBladeRF2InputReport::SWGBladeRF2InputReport() {
frequency_range = nullptr;
m_frequency_range_isSet = false;
sample_rate_range = nullptr;
m_sample_rate_range_isSet = false;
bandwidth_range = nullptr;
m_bandwidth_range_isSet = false;
global_gain_range = nullptr;
m_global_gain_range_isSet = false;
gain_modes = nullptr;
m_gain_modes_isSet = false;
}
SWGBladeRF2InputReport::~SWGBladeRF2InputReport() {
this->cleanup();
}
void
SWGBladeRF2InputReport::init() {
frequency_range = new SWGFrequencyRange();
m_frequency_range_isSet = false;
sample_rate_range = new SWGRange();
m_sample_rate_range_isSet = false;
bandwidth_range = new SWGRange();
m_bandwidth_range_isSet = false;
global_gain_range = new SWGRange();
m_global_gain_range_isSet = false;
gain_modes = new QList<SWGNamedEnum*>();
m_gain_modes_isSet = false;
}
void
SWGBladeRF2InputReport::cleanup() {
if(frequency_range != nullptr) {
delete frequency_range;
}
if(sample_rate_range != nullptr) {
delete sample_rate_range;
}
if(bandwidth_range != nullptr) {
delete bandwidth_range;
}
if(global_gain_range != nullptr) {
delete global_gain_range;
}
if(gain_modes != nullptr) {
auto arr = gain_modes;
for(auto o: *arr) {
delete o;
}
delete gain_modes;
}
}
SWGBladeRF2InputReport*
SWGBladeRF2InputReport::fromJson(QString &json) {
QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject);
return this;
}
void
SWGBladeRF2InputReport::fromJsonObject(QJsonObject &pJson) {
::SWGSDRangel::setValue(&frequency_range, pJson["frequencyRange"], "SWGFrequencyRange", "SWGFrequencyRange");
::SWGSDRangel::setValue(&sample_rate_range, pJson["sampleRateRange"], "SWGRange", "SWGRange");
::SWGSDRangel::setValue(&bandwidth_range, pJson["bandwidthRange"], "SWGRange", "SWGRange");
::SWGSDRangel::setValue(&global_gain_range, pJson["globalGainRange"], "SWGRange", "SWGRange");
::SWGSDRangel::setValue(&gain_modes, pJson["gainModes"], "QList", "SWGNamedEnum");
}
QString
SWGBladeRF2InputReport::asJson ()
{
QJsonObject* obj = this->asJsonObject();
QJsonDocument doc(*obj);
QByteArray bytes = doc.toJson();
delete obj;
return QString(bytes);
}
QJsonObject*
SWGBladeRF2InputReport::asJsonObject() {
QJsonObject* obj = new QJsonObject();
if((frequency_range != nullptr) && (frequency_range->isSet())){
toJsonValue(QString("frequencyRange"), frequency_range, obj, QString("SWGFrequencyRange"));
}
if((sample_rate_range != nullptr) && (sample_rate_range->isSet())){
toJsonValue(QString("sampleRateRange"), sample_rate_range, obj, QString("SWGRange"));
}
if((bandwidth_range != nullptr) && (bandwidth_range->isSet())){
toJsonValue(QString("bandwidthRange"), bandwidth_range, obj, QString("SWGRange"));
}
if((global_gain_range != nullptr) && (global_gain_range->isSet())){
toJsonValue(QString("globalGainRange"), global_gain_range, obj, QString("SWGRange"));
}
if(gain_modes->size() > 0){
toJsonArray((QList<void*>*)gain_modes, obj, "gainModes", "SWGNamedEnum");
}
return obj;
}
SWGFrequencyRange*
SWGBladeRF2InputReport::getFrequencyRange() {
return frequency_range;
}
void
SWGBladeRF2InputReport::setFrequencyRange(SWGFrequencyRange* frequency_range) {
this->frequency_range = frequency_range;
this->m_frequency_range_isSet = true;
}
SWGRange*
SWGBladeRF2InputReport::getSampleRateRange() {
return sample_rate_range;
}
void
SWGBladeRF2InputReport::setSampleRateRange(SWGRange* sample_rate_range) {
this->sample_rate_range = sample_rate_range;
this->m_sample_rate_range_isSet = true;
}
SWGRange*
SWGBladeRF2InputReport::getBandwidthRange() {
return bandwidth_range;
}
void
SWGBladeRF2InputReport::setBandwidthRange(SWGRange* bandwidth_range) {
this->bandwidth_range = bandwidth_range;
this->m_bandwidth_range_isSet = true;
}
SWGRange*
SWGBladeRF2InputReport::getGlobalGainRange() {
return global_gain_range;
}
void
SWGBladeRF2InputReport::setGlobalGainRange(SWGRange* global_gain_range) {
this->global_gain_range = global_gain_range;
this->m_global_gain_range_isSet = true;
}
QList<SWGNamedEnum*>*
SWGBladeRF2InputReport::getGainModes() {
return gain_modes;
}
void
SWGBladeRF2InputReport::setGainModes(QList<SWGNamedEnum*>* gain_modes) {
this->gain_modes = gain_modes;
this->m_gain_modes_isSet = true;
}
bool
SWGBladeRF2InputReport::isSet(){
bool isObjectUpdated = false;
do{
if(frequency_range != nullptr && frequency_range->isSet()){ isObjectUpdated = true; break;}
if(sample_rate_range != nullptr && sample_rate_range->isSet()){ isObjectUpdated = true; break;}
if(bandwidth_range != nullptr && bandwidth_range->isSet()){ isObjectUpdated = true; break;}
if(global_gain_range != nullptr && global_gain_range->isSet()){ isObjectUpdated = true; break;}
if(gain_modes->size() > 0){ isObjectUpdated = true; break;}
}while(false);
return isObjectUpdated;
}
}
|
[
"f4exb06@gmail.com"
] |
f4exb06@gmail.com
|
b4771a67b824c59573db7b52440bca76c5b0b212
|
6ced41da926682548df646099662e79d7a6022c5
|
/aws-cpp-sdk-drs/source/model/DeleteJobResult.cpp
|
60c099c98cc79b83f6be170ce28bb65fce0eb780
|
[
"Apache-2.0",
"MIT",
"JSON"
] |
permissive
|
irods/aws-sdk-cpp
|
139104843de529f615defa4f6b8e20bc95a6be05
|
2c7fb1a048c96713a28b730e1f48096bd231e932
|
refs/heads/main
| 2023-07-25T12:12:04.363757
| 2022-08-26T15:33:31
| 2022-08-26T15:33:31
| 141,315,346
| 0
| 1
|
Apache-2.0
| 2022-08-26T17:45:09
| 2018-07-17T16:24:06
|
C++
|
UTF-8
|
C++
| false
| false
| 787
|
cpp
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/drs/model/DeleteJobResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::drs::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
DeleteJobResult::DeleteJobResult()
{
}
DeleteJobResult::DeleteJobResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
DeleteJobResult& DeleteJobResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
AWS_UNREFERENCED_PARAM(result);
return *this;
}
|
[
"aws-sdk-cpp-automation@github.com"
] |
aws-sdk-cpp-automation@github.com
|
3a7ef778fda72ff154a433928e69d9ef8cd0402e
|
3ff1fe3888e34cd3576d91319bf0f08ca955940f
|
/iss/src/v20230517/model/ListRecordBackupPlanDevicesResponse.cpp
|
6d46a2f38f705174039b0c0c7a1be1bb2606e58b
|
[
"Apache-2.0"
] |
permissive
|
TencentCloud/tencentcloud-sdk-cpp
|
9f5df8220eaaf72f7eaee07b2ede94f89313651f
|
42a76b812b81d1b52ec6a217fafc8faa135e06ca
|
refs/heads/master
| 2023-08-30T03:22:45.269556
| 2023-08-30T00:45:39
| 2023-08-30T00:45:39
| 188,991,963
| 55
| 37
|
Apache-2.0
| 2023-08-17T03:13:20
| 2019-05-28T08:56:08
|
C++
|
UTF-8
|
C++
| false
| false
| 4,149
|
cpp
|
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/iss/v20230517/model/ListRecordBackupPlanDevicesResponse.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Iss::V20230517::Model;
using namespace std;
ListRecordBackupPlanDevicesResponse::ListRecordBackupPlanDevicesResponse() :
m_dataHasBeenSet(false)
{
}
CoreInternalOutcome ListRecordBackupPlanDevicesResponse::Deserialize(const string &payload)
{
rapidjson::Document d;
d.Parse(payload.c_str());
if (d.HasParseError() || !d.IsObject())
{
return CoreInternalOutcome(Core::Error("response not json format"));
}
if (!d.HasMember("Response") || !d["Response"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `Response` is null or not object"));
}
rapidjson::Value &rsp = d["Response"];
if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.RequestId` is null or not string"));
}
string requestId(rsp["RequestId"].GetString());
SetRequestId(requestId);
if (rsp.HasMember("Error"))
{
if (!rsp["Error"].IsObject() ||
!rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() ||
!rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.Error` format error").SetRequestId(requestId));
}
string errorCode(rsp["Error"]["Code"].GetString());
string errorMsg(rsp["Error"]["Message"].GetString());
return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId));
}
if (rsp.HasMember("Data") && !rsp["Data"].IsNull())
{
if (!rsp["Data"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `Data` is not object type").SetRequestId(requestId));
}
CoreInternalOutcome outcome = m_data.Deserialize(rsp["Data"]);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_dataHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
string ListRecordBackupPlanDevicesResponse::ToJsonString() const
{
rapidjson::Document value;
value.SetObject();
rapidjson::Document::AllocatorType& allocator = value.GetAllocator();
if (m_dataHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Data";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
m_data.ToJsonObject(value[key.c_str()], allocator);
}
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RequestId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
value.Accept(writer);
return buffer.GetString();
}
ListRecordBackupPlanDevicesData ListRecordBackupPlanDevicesResponse::GetData() const
{
return m_data;
}
bool ListRecordBackupPlanDevicesResponse::DataHasBeenSet() const
{
return m_dataHasBeenSet;
}
|
[
"tencentcloudapi@tencent.com"
] |
tencentcloudapi@tencent.com
|
74fab5f8cb799a4218a67b6a2de342d93740dd2a
|
dd80a584130ef1a0333429ba76c1cee0eb40df73
|
/ndk/sources/cxx-stl/llvm-libc++/libcxx/include/__debug
|
0d631bf043861e545592bab8ec955585b5071ef1
|
[
"MIT",
"NCSA"
] |
permissive
|
karunmatharu/Android-4.4-Pay-by-Data
|
466f4e169ede13c5835424c78e8c30ce58f885c1
|
fcb778e92d4aad525ef7a995660580f948d40bc9
|
refs/heads/master
| 2021-03-24T13:33:01.721868
| 2017-02-18T17:48:49
| 2017-02-18T17:48:49
| 81,847,777
| 0
| 2
|
MIT
| 2020-03-09T00:02:12
| 2017-02-13T16:47:00
| null |
UTF-8
|
C++
| false
| false
| 5,259
|
// -*- C++ -*-
//===--------------------------- __debug ----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef _LIBCPP_DEBUG_H
#define _LIBCPP_DEBUG_H
#if _LIBCPP_DEBUG_LEVEL >= 1
# include <cstdlib>
# include <cstdio>
# include <cstddef>
# ifndef _LIBCPP_ASSERT
# define _LIBCPP_ASSERT(x, m) ((x) ? (void)0 : (_VSTD::printf("%s\n", m), _VSTD::abort()))
# endif
#endif
#if _LIBCPP_DEBUG_LEVEL >= 2
_LIBCPP_BEGIN_NAMESPACE_STD
struct _LIBCPP_TYPE_VIS __c_node;
struct _LIBCPP_TYPE_VIS __i_node
{
void* __i_;
__i_node* __next_;
__c_node* __c_;
__i_node(const __i_node&) = delete;
__i_node& operator=(const __i_node&) = delete;
_LIBCPP_INLINE_VISIBILITY
__i_node(void* __i, __i_node* __next, __c_node* __c)
: __i_(__i), __next_(__next), __c_(__c) {}
~__i_node();
};
struct _LIBCPP_TYPE_VIS __c_node
{
void* __c_;
__c_node* __next_;
__i_node** beg_;
__i_node** end_;
__i_node** cap_;
__c_node(const __c_node&) = delete;
__c_node& operator=(const __c_node&) = delete;
_LIBCPP_INLINE_VISIBILITY
__c_node(void* __c, __c_node* __next)
: __c_(__c), __next_(__next), beg_(nullptr), end_(nullptr), cap_(nullptr) {}
virtual ~__c_node();
virtual bool __dereferenceable(const void*) const = 0;
virtual bool __decrementable(const void*) const = 0;
virtual bool __addable(const void*, ptrdiff_t) const = 0;
virtual bool __subscriptable(const void*, ptrdiff_t) const = 0;
void __add(__i_node* __i);
_LIBCPP_HIDDEN void __remove(__i_node* __i);
};
template <class _Cont>
struct _C_node
: public __c_node
{
_C_node(void* __c, __c_node* __n)
: __c_node(__c, __n) {}
virtual bool __dereferenceable(const void*) const;
virtual bool __decrementable(const void*) const;
virtual bool __addable(const void*, ptrdiff_t) const;
virtual bool __subscriptable(const void*, ptrdiff_t) const;
};
template <class _Cont>
bool
_C_node<_Cont>::__dereferenceable(const void* __i) const
{
typedef typename _Cont::const_iterator iterator;
const iterator* __j = static_cast<const iterator*>(__i);
_Cont* _Cp = static_cast<_Cont*>(__c_);
return _Cp->__dereferenceable(__j);
}
template <class _Cont>
bool
_C_node<_Cont>::__decrementable(const void* __i) const
{
typedef typename _Cont::const_iterator iterator;
const iterator* __j = static_cast<const iterator*>(__i);
_Cont* _Cp = static_cast<_Cont*>(__c_);
return _Cp->__decrementable(__j);
}
template <class _Cont>
bool
_C_node<_Cont>::__addable(const void* __i, ptrdiff_t __n) const
{
typedef typename _Cont::const_iterator iterator;
const iterator* __j = static_cast<const iterator*>(__i);
_Cont* _Cp = static_cast<_Cont*>(__c_);
return _Cp->__addable(__j, __n);
}
template <class _Cont>
bool
_C_node<_Cont>::__subscriptable(const void* __i, ptrdiff_t __n) const
{
typedef typename _Cont::const_iterator iterator;
const iterator* __j = static_cast<const iterator*>(__i);
_Cont* _Cp = static_cast<_Cont*>(__c_);
return _Cp->__subscriptable(__j, __n);
}
class _LIBCPP_TYPE_VIS __libcpp_db
{
__c_node** __cbeg_;
__c_node** __cend_;
size_t __csz_;
__i_node** __ibeg_;
__i_node** __iend_;
size_t __isz_;
__libcpp_db();
public:
__libcpp_db(const __libcpp_db&) = delete;
__libcpp_db& operator=(const __libcpp_db&) = delete;
~__libcpp_db();
class __db_c_iterator;
class __db_c_const_iterator;
class __db_i_iterator;
class __db_i_const_iterator;
__db_c_const_iterator __c_end() const;
__db_i_const_iterator __i_end() const;
template <class _Cont>
_LIBCPP_INLINE_VISIBILITY
void __insert_c(_Cont* __c)
{
__c_node* __n = __insert_c(static_cast<void*>(__c));
::new(__n) _C_node<_Cont>(__n->__c_, __n->__next_);
}
void __insert_i(void* __i);
__c_node* __insert_c(void* __c);
void __erase_c(void* __c);
void __insert_ic(void* __i, const void* __c);
void __iterator_copy(void* __i, const void* __i0);
void __erase_i(void* __i);
void* __find_c_from_i(void* __i) const;
void __invalidate_all(void* __c);
__c_node* __find_c_and_lock(void* __c) const;
__c_node* __find_c(void* __c) const;
void unlock() const;
void swap(void* __c1, void* __c2);
bool __dereferenceable(const void* __i) const;
bool __decrementable(const void* __i) const;
bool __addable(const void* __i, ptrdiff_t __n) const;
bool __subscriptable(const void* __i, ptrdiff_t __n) const;
bool __comparable(const void* __i, const void* __j) const;
private:
_LIBCPP_HIDDEN
__i_node* __insert_iterator(void* __i);
_LIBCPP_HIDDEN
__i_node* __find_iterator(const void* __i) const;
friend _LIBCPP_FUNC_VIS __libcpp_db* __get_db();
};
_LIBCPP_FUNC_VIS __libcpp_db* __get_db();
_LIBCPP_FUNC_VIS const __libcpp_db* __get_const_db();
_LIBCPP_END_NAMESPACE_STD
#endif
#endif // _LIBCPP_DEBUG_H
|
[
"karun.matharu@gmail.com"
] |
karun.matharu@gmail.com
|
|
8273697452a4cd52b5d38eb345d7ba3879e280b6
|
45014139581f1211a43b6415a6ee32d442c29fc0
|
/src/content/renderer/render_thread_impl.h
|
e13f73a1ef631d9e482e2e878bd5c79c8b7f0790
|
[
"BSD-3-Clause"
] |
permissive
|
webosose/chromium91
|
a31b847e64391c3de98ca5b6dac3ac247d393e78
|
b28e2ae83ee2e4907a36a49a4c0f054aa386dbfa
|
refs/heads/master
| 2022-12-12T09:32:30.580155
| 2022-09-01T09:02:15
| 2022-09-18T23:58:11
| 460,692,960
| 1
| 5
| null | 2022-10-05T07:19:39
| 2022-02-18T03:16:04
| null |
UTF-8
|
C++
| false
| false
| 24,434
|
h
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_RENDERER_RENDER_THREAD_IMPL_H_
#define CONTENT_RENDERER_RENDER_THREAD_IMPL_H_
#include <stddef.h>
#include <stdint.h>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/cancelable_callback.h"
#include "base/clang_profiling_buildflags.h"
#include "base/containers/unique_ptr_adapters.h"
#include "base/macros.h"
#include "base/memory/discardable_memory_allocator.h"
#include "base/memory/memory_pressure_listener.h"
#include "base/memory/ref_counted.h"
#include "base/metrics/user_metrics_action.h"
#include "base/observer_list.h"
#include "base/optional.h"
#include "base/time/time.h"
#include "base/types/pass_key.h"
#include "build/build_config.h"
#include "cc/mojom/render_frame_metadata.mojom.h"
#include "content/child/child_thread_impl.h"
#include "content/common/agent_scheduling_group.mojom.h"
#include "content/common/content_export.h"
#include "content/common/frame.mojom.h"
#include "content/common/render_message_filter.mojom.h"
#include "content/common/renderer.mojom.h"
#include "content/common/renderer_host.mojom.h"
#include "content/public/renderer/render_thread.h"
#include "content/renderer/compositor/compositor_dependencies.h"
#include "content/renderer/discardable_memory_utils.h"
#include "gpu/ipc/client/gpu_channel_host.h"
#include "ipc/ipc_sync_channel.h"
#include "media/media_buildflags.h"
#include "mojo/public/cpp/bindings/associated_receiver.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "mojo/public/cpp/bindings/pending_associated_receiver.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "net/base/network_change_notifier.h"
#include "net/nqe/effective_connection_type.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
#include "services/viz/public/mojom/compositing/compositing_mode_watcher.mojom.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
#include "third_party/blink/public/common/user_agent/user_agent_metadata.h"
#include "third_party/blink/public/platform/scheduler/web_rail_mode_observer.h"
#include "third_party/blink/public/platform/scheduler/web_thread_scheduler.h"
#include "third_party/blink/public/platform/url_loader_throttle_provider.h"
#include "third_party/blink/public/platform/web_connection_type.h"
#include "third_party/blink/public/web/web_memory_statistics.h"
#include "ui/gfx/native_widget_types.h"
///@name USE_NEVA_APPRUNTIME
///@{
#include "third_party/blink/public/platform/web_scoped_page_pauser.h"
///@}
#if defined(USE_NEVA_MEDIA) || defined(USE_NEVA_SUSPEND_MEDIA_CAPTURE)
// Mix-in for neva
#include "content/renderer/neva/render_thread_impl.h"
#endif
class SkBitmap;
namespace blink {
class WebResourceRequestSenderDelegate;
class WebVideoCaptureImplManager;
}
namespace base {
class SingleThreadTaskRunner;
class Thread;
}
namespace cc {
class TaskGraphRunner;
}
namespace gfx {
class RenderingPipeline;
}
namespace gpu {
class GpuChannelHost;
}
namespace media {
class DecoderFactory;
class GpuVideoAcceleratorFactories;
}
namespace mojo {
class BinderMap;
}
namespace viz {
class ContextProviderCommandBuffer;
class Gpu;
class RasterContextProvider;
} // namespace viz
namespace content {
class AgentSchedulingGroup;
class CategorizedWorkerPool;
class GpuVideoAcceleratorFactoriesImpl;
class MediaInterfaceFactory;
class RenderFrameImpl;
class RenderThreadObserver;
class RendererBlinkPlatformImpl;
class VariationsRenderThreadObserver;
#if defined(OS_ANDROID)
class StreamTextureFactory;
#endif
// The RenderThreadImpl class represents the main thread, where RenderView
// instances live. The RenderThread supports an API that is used by its
// consumer to talk indirectly to the RenderViews and supporting objects.
// Likewise, it provides an API for the RenderViews to talk back to the main
// process (i.e., their corresponding WebContentsImpl).
//
// Most of the communication occurs in the form of IPC messages. They are
// routed to the RenderThread according to the routing IDs of the messages.
// The routing IDs correspond to RenderView instances.
class CONTENT_EXPORT RenderThreadImpl
: public RenderThread,
public ChildThreadImpl,
public mojom::Renderer,
#if defined(USE_NEVA_MEDIA) || defined(USE_NEVA_SUSPEND_MEDIA_CAPTURE)
public neva::RenderThreadImpl<RenderThreadImpl>,
#endif
public viz::mojom::CompositingModeWatcher,
public CompositorDependencies {
public:
static RenderThreadImpl* current();
static mojom::RenderMessageFilter* current_render_message_filter();
static RendererBlinkPlatformImpl* current_blink_platform_impl();
static void SetRenderMessageFilterForTesting(
mojom::RenderMessageFilter* render_message_filter);
static void SetRendererBlinkPlatformImplForTesting(
RendererBlinkPlatformImpl* blink_platform_impl);
// Returns the task runner for the main thread where the RenderThread lives.
static scoped_refptr<base::SingleThreadTaskRunner>
DeprecatedGetMainTaskRunner();
RenderThreadImpl(
base::RepeatingClosure quit_closure,
std::unique_ptr<blink::scheduler::WebThreadScheduler> scheduler);
RenderThreadImpl(
const InProcessChildThreadParams& params,
int32_t client_id,
std::unique_ptr<blink::scheduler::WebThreadScheduler> scheduler);
~RenderThreadImpl() override;
void Shutdown() override;
bool ShouldBeDestroyed() override;
// When initializing WebKit, ensure that any schemes needed for the content
// module are registered properly. Static to allow sharing with tests.
static void RegisterSchemes();
// RenderThread implementation:
IPC::SyncChannel* GetChannel() override;
std::string GetLocale() override;
IPC::SyncMessageFilter* GetSyncMessageFilter() override;
void AddRoute(int32_t routing_id, IPC::Listener* listener) override;
void AttachTaskRunnerToRoute(
int32_t routing_id,
scoped_refptr<base::SingleThreadTaskRunner> task_runner) override;
void RemoveRoute(int32_t routing_id) override;
int GenerateRoutingID() override;
bool GenerateFrameRoutingID(
int32_t& routing_id,
blink::LocalFrameToken& frame_token,
base::UnguessableToken& devtools_frame_token) override;
void AddFilter(IPC::MessageFilter* filter) override;
void RemoveFilter(IPC::MessageFilter* filter) override;
void AddObserver(RenderThreadObserver* observer) override;
void RemoveObserver(RenderThreadObserver* observer) override;
void SetResourceRequestSenderDelegate(
blink::WebResourceRequestSenderDelegate* delegate) override;
blink::WebResourceRequestSenderDelegate* GetResourceRequestSenderDelegate() {
return resource_request_sender_delegate_;
}
void RegisterExtension(std::unique_ptr<v8::Extension> extension) override;
int PostTaskToAllWebWorkers(base::RepeatingClosure closure) override;
base::WaitableEvent* GetShutdownEvent() override;
int32_t GetClientId() override;
void SetRendererProcessType(
blink::scheduler::WebRendererProcessType type) override;
blink::WebString GetUserAgent() override;
const blink::UserAgentMetadata& GetUserAgentMetadata() override;
bool IsUseZoomForDSF() override;
// IPC::Listener implementation via ChildThreadImpl:
void OnAssociatedInterfaceRequest(
const std::string& name,
mojo::ScopedInterfaceEndpointHandle handle) override;
// ChildThread implementation via ChildThreadImpl:
scoped_refptr<base::SingleThreadTaskRunner> GetIOTaskRunner() override;
// CompositorDependencies implementation.
bool IsUseZoomForDSFEnabled() override;
blink::scheduler::WebThreadScheduler* GetWebMainThreadScheduler() override;
cc::TaskGraphRunner* GetTaskGraphRunner() override;
std::unique_ptr<cc::UkmRecorderFactory> CreateUkmRecorderFactory() override;
gfx::RenderingPipeline* GetMainThreadPipeline() override;
gfx::RenderingPipeline* GetCompositorThreadPipeline() override;
bool IsLcdTextEnabled();
bool IsElasticOverscrollEnabled();
bool IsScrollAnimatorEnabled();
// TODO(crbug.com/1111231): The `enable_scroll_animator` flag is currently
// being passed as part of `CreateViewParams`, despite it looking like a
// global setting. It should probably be moved to some `mojom::Renderer` API
// and this method should be removed.
void SetScrollAnimatorEnabled(bool enable_scroll_animator,
base::PassKey<AgentSchedulingGroup>);
bool IsThreadedAnimationEnabled();
// viz::mojom::CompositingModeWatcher implementation.
void CompositingModeFallbackToSoftware() override;
// Whether gpu compositing is being used or is disabled for software
// compositing. Clients of the compositor should give resources that match
// the appropriate mode.
bool IsGpuCompositingDisabled() { return is_gpu_compositing_disabled_; }
// Synchronously establish a channel to the GPU plugin if not previously
// established or if it has been lost (for example if the GPU plugin crashed).
// If there is a pending asynchronous request, it will be completed by the
// time this routine returns.
scoped_refptr<gpu::GpuChannelHost> EstablishGpuChannelSync();
gpu::GpuMemoryBufferManager* GetGpuMemoryBufferManager();
blink::AssociatedInterfaceRegistry* GetAssociatedInterfaceRegistry();
base::DiscardableMemoryAllocator* GetDiscardableMemoryAllocatorForTest()
const {
return discardable_memory_allocator_.get();
}
RendererBlinkPlatformImpl* blink_platform_impl() const {
DCHECK(blink_platform_impl_);
return blink_platform_impl_.get();
}
// Returns the task runner on the compositor thread.
//
// Will be null if threaded compositing has not been enabled.
scoped_refptr<base::SingleThreadTaskRunner> compositor_task_runner() const {
return compositor_task_runner_;
}
const std::vector<std::string> cors_exempt_header_list() const {
return cors_exempt_header_list_;
}
blink::URLLoaderThrottleProvider* url_loader_throttle_provider() const {
return url_loader_throttle_provider_.get();
}
#if defined(OS_ANDROID)
scoped_refptr<StreamTextureFactory> GetStreamTexureFactory();
bool EnableStreamTextureCopy();
#endif
blink::WebVideoCaptureImplManager* video_capture_impl_manager() const {
return vc_manager_.get();
}
mojom::RenderMessageFilter* render_message_filter();
// Get the GPU channel. Returns NULL if the channel is not established or
// has been lost.
gpu::GpuChannelHost* GetGpuChannel();
// Returns a SingleThreadTaskRunner instance corresponding to the message loop
// of the thread on which media operations should be run. Must be called
// on the renderer's main thread.
scoped_refptr<base::SingleThreadTaskRunner> GetMediaThreadTaskRunner();
// A TaskRunner instance that runs tasks on the raster worker pool.
base::TaskRunner* GetWorkerTaskRunner();
// Creates a ContextProvider if yet created, and returns it to be used for
// video frame compositing. The ContextProvider given as an argument is
// one that has been lost, and is a hint to the RenderThreadImpl to clear
// it's |video_frame_compositor_context_provider_| if it matches.
scoped_refptr<viz::RasterContextProvider>
GetVideoFrameCompositorContextProvider(
scoped_refptr<viz::RasterContextProvider>);
// Returns a worker context provider that will be bound on the compositor
// thread.
scoped_refptr<viz::RasterContextProvider>
SharedCompositorWorkerContextProvider(bool try_gpu_rasterization);
media::GpuVideoAcceleratorFactories* GetGpuFactories();
media::DecoderFactory* GetMediaDecoderFactory();
scoped_refptr<viz::ContextProviderCommandBuffer>
SharedMainThreadContextProvider();
// For producing custom V8 histograms. Custom histograms are produced if all
// RenderViews share the same host, and the host is in the pre-specified set
// of hosts we want to produce custom diagrams for. The name for a custom
// diagram is the name of the corresponding generic diagram plus a
// host-specific suffix.
class CONTENT_EXPORT HistogramCustomizer {
public:
HistogramCustomizer();
~HistogramCustomizer();
// Called when a top frame of a RenderView navigates. This function updates
// RenderThreadImpl's information about whether all RenderViews are
// displaying a page from the same host. |host| is the host where a
// RenderView navigated, and |view_count| is the number of RenderViews in
// this process.
void RenderViewNavigatedToHost(const std::string& host, size_t view_count);
// Used for customizing some histograms if all RenderViews share the same
// host. Returns the current custom histogram name to use for
// |histogram_name|, or |histogram_name| if it shouldn't be customized.
std::string ConvertToCustomHistogramName(const char* histogram_name) const;
private:
FRIEND_TEST_ALL_PREFIXES(RenderThreadImplUnittest,
IdentifyAlexaTop10NonGoogleSite);
friend class RenderThreadImplUnittest;
// Converts a host name to a suffix for histograms
std::string HostToCustomHistogramSuffix(const std::string& host);
// Helper function to identify a certain set of top pages
bool IsAlexaTop10NonGoogleSite(const std::string& host);
// Used for updating the information on which is the common host which all
// RenderView's share (if any). If there is no common host, this function is
// called with an empty string.
void SetCommonHost(const std::string& host);
// The current common host of the RenderViews; empty string if there is no
// common host.
std::string common_host_;
// The corresponding suffix.
std::string common_host_histogram_suffix_;
// Set of histograms for which we want to produce a custom histogram if
// possible.
std::set<std::string> custom_histograms_;
DISALLOW_COPY_AND_ASSIGN(HistogramCustomizer);
};
HistogramCustomizer* histogram_customizer() {
return &histogram_customizer_;
}
void RegisterPendingFrameCreate(
int routing_id,
mojo::PendingReceiver<mojom::Frame> frame);
mojom::RendererHost* GetRendererHost();
struct RendererMemoryMetrics {
size_t partition_alloc_kb;
size_t blink_gc_kb;
size_t malloc_mb;
size_t discardable_kb;
size_t v8_main_thread_isolate_mb;
size_t total_allocated_mb;
size_t non_discardable_total_allocated_mb;
size_t total_allocated_per_render_view_mb;
};
bool GetRendererMemoryMetrics(RendererMemoryMetrics* memory_metrics) const;
void RecordMetricsForBackgroundedRendererPurge();
// Sets the current pipeline rendering color space.
void SetRenderingColorSpace(const gfx::ColorSpace& color_space);
gfx::ColorSpace GetRenderingColorSpace();
scoped_refptr<base::SingleThreadTaskRunner>
CreateVideoFrameCompositorTaskRunner();
// In the case of kOnDemand, we wont be using the task_runner created in
// CreateVideoFrameCompositorTaskRunner.
// TODO(https://crbug/901513): Remove once kOnDemand is removed.
void SetVideoFrameCompositorTaskRunner(
scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
video_frame_compositor_task_runner_ = task_runner;
}
private:
friend class RenderThreadImplBrowserTest;
friend class AgentSchedulingGroup;
void OnProcessFinalRelease() override;
// IPC::Listener
void OnChannelError() override;
// ChildThread
bool OnControlMessageReceived(const IPC::Message& msg) override;
void RecordAction(const base::UserMetricsAction& action) override;
void RecordComputedAction(const std::string& action) override;
bool IsMainThread();
void Init();
void InitializeCompositorThread();
void InitializeWebKit(mojo::BinderMap* binders);
void OnTransferBitmap(const SkBitmap& bitmap, int resource_id);
void OnGetAccessibilityTree();
// mojom::Renderer:
void CreateAgentSchedulingGroup(
mojo::PendingReceiver<IPC::mojom::ChannelBootstrap> bootstrap,
mojo::PendingRemote<blink::mojom::BrowserInterfaceBroker> broker_remote)
override;
void CreateAssociatedAgentSchedulingGroup(
mojo::PendingAssociatedReceiver<mojom::AgentSchedulingGroup>
agent_scheduling_group,
mojo::PendingRemote<blink::mojom::BrowserInterfaceBroker> broker_remote)
override;
void OnNetworkConnectionChanged(
net::NetworkChangeNotifier::ConnectionType type,
double max_bandwidth_mbps) override;
void OnNetworkQualityChanged(net::EffectiveConnectionType type,
base::TimeDelta http_rtt,
base::TimeDelta transport_rtt,
double bandwidth_kbps) override;
void SetWebKitSharedTimersSuspended(bool suspend) override;
void SetUserAgent(const std::string& user_agent) override;
void SetUserAgentMetadata(const blink::UserAgentMetadata& metadata) override;
void SetCorsExemptHeaderList(const std::vector<std::string>& list) override;
void UpdateScrollbarTheme(
mojom::UpdateScrollbarThemeParamsPtr params) override;
void OnSystemColorsChanged(int32_t aqua_color_variant,
const std::string& highlight_text_color,
const std::string& highlight_color) override;
void UpdateSystemColorInfo(
mojom::UpdateSystemColorInfoParamsPtr params) override;
void PurgePluginListCache(bool reload_pages) override;
void SetProcessState(mojom::RenderProcessBackgroundState background_state,
mojom::RenderProcessVisibleState visible_state) override;
void SetSchedulerKeepActive(bool keep_active) override;
///@name USE_NEVA_APPRUNTIME
///@{
void ProcessResume() override;
void ProcessSuspend() override;
void OnSystemMemoryPressureLevelChanged(
base::MemoryPressureListener::MemoryPressureLevel level) override;
///@}
void SetIsLockedToSite() override;
#if BUILDFLAG(CLANG_PROFILING_INSIDE_SANDBOX)
void WriteClangProfilingProfile(
WriteClangProfilingProfileCallback callback) override;
#endif
void SetIsCrossOriginIsolated(bool value) override;
void OnMemoryPressure(
base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level);
bool RendererIsHidden() const;
void OnRendererHidden();
void OnRendererVisible();
bool RendererIsBackgrounded() const;
void OnRendererBackgrounded();
void OnRendererForegrounded();
void RecordMemoryUsageAfterBackgrounded(const char* suffix,
int foregrounded_count);
void OnRecordMetricsForBackgroundedRendererPurgeTimerExpired(
const char* suffix,
int foregrounded_count_when_purged);
void ReleaseFreeMemory();
void OnSyncMemoryPressure(
base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level);
void OnRendererInterfaceReceiver(
mojo::PendingAssociatedReceiver<mojom::Renderer> receiver);
scoped_refptr<discardable_memory::ClientDiscardableSharedMemoryManager>
discardable_memory_allocator_;
// These objects live solely on the render thread.
std::unique_ptr<blink::scheduler::WebThreadScheduler> main_thread_scheduler_;
std::unique_ptr<RendererBlinkPlatformImpl> blink_platform_impl_;
std::unique_ptr<blink::URLLoaderThrottleProvider>
url_loader_throttle_provider_;
std::vector<std::string> cors_exempt_header_list_;
// Used on the render thread.
std::unique_ptr<blink::WebVideoCaptureImplManager> vc_manager_;
// Used to keep track of the renderer's backgrounded and visibility state.
// Updated via an IPC from the browser process. If nullopt, the browser
// process has yet to send an update and the state is unknown.
base::Optional<mojom::RenderProcessBackgroundState> background_state_;
base::Optional<mojom::RenderProcessVisibleState> visible_state_;
blink::WebString user_agent_;
blink::UserAgentMetadata user_agent_metadata_;
// Sticky once true, indicates that compositing is done without Gpu, so
// resources given to the compositor or to the viz service should be
// software-based.
bool is_gpu_compositing_disabled_ = false;
// Utility class to provide GPU functionalities to media.
// TODO(dcastagna): This should be just one scoped_ptr once
// http://crbug.com/580386 is fixed.
// NOTE(dcastagna): At worst this accumulates a few bytes per context lost.
std::vector<std::unique_ptr<GpuVideoAcceleratorFactoriesImpl>> gpu_factories_;
// Utility classes to allow WebRTC to create video decoders.
std::unique_ptr<MediaInterfaceFactory> media_interface_factory_;
std::unique_ptr<media::DecoderFactory> media_decoder_factory_;
// Thread for running multimedia operations (e.g., video decoding).
std::unique_ptr<base::Thread> media_thread_;
std::unique_ptr<gfx::RenderingPipeline> main_thread_pipeline_;
std::unique_ptr<gfx::RenderingPipeline> compositor_thread_pipeline_;
// Will point to appropriate task runner after initialization,
// regardless of whether |compositor_thread_| is overriden.
scoped_refptr<base::SingleThreadTaskRunner> compositor_task_runner_;
// Task to run the VideoFrameCompositor on.
scoped_refptr<base::SingleThreadTaskRunner>
video_frame_compositor_task_runner_;
// Pool of workers used for raster operations (e.g., tile rasterization).
scoped_refptr<CategorizedWorkerPool> categorized_worker_pool_;
#if defined(OS_ANDROID)
scoped_refptr<StreamTextureFactory> stream_texture_factory_;
#endif
scoped_refptr<viz::ContextProviderCommandBuffer> shared_main_thread_contexts_;
base::ObserverList<RenderThreadObserver>::Unchecked observers_;
scoped_refptr<viz::RasterContextProvider>
video_frame_compositor_context_provider_;
scoped_refptr<viz::RasterContextProvider> shared_worker_context_provider_;
HistogramCustomizer histogram_customizer_;
std::unique_ptr<base::MemoryPressureListener> memory_pressure_listener_;
std::unique_ptr<viz::Gpu> gpu_;
std::unique_ptr<VariationsRenderThreadObserver> variations_observer_;
// Compositor settings.
int gpu_rasterization_msaa_sample_count_;
bool is_lcd_text_enabled_;
bool is_zero_copy_enabled_;
bool is_gpu_memory_buffer_compositor_resources_enabled_;
bool is_partial_raster_enabled_;
bool is_elastic_overscroll_enabled_;
bool is_zoom_for_dsf_enabled_;
bool is_threaded_animation_enabled_;
bool is_scroll_animator_enabled_;
// Target rendering ColorSpace.
gfx::ColorSpace rendering_color_space_;
// Used when AddRoute() is called and the RenderFrameImpl hasn't been created
// yet.
std::map<int, mojo::PendingReceiver<mojom::Frame>> pending_frames_;
mojo::AssociatedRemote<mojom::RendererHost> renderer_host_;
blink::AssociatedInterfaceRegistry associated_interfaces_;
mojo::AssociatedReceiver<mojom::Renderer> renderer_receiver_{this};
mojo::AssociatedRemote<mojom::RenderMessageFilter> render_message_filter_;
std::set<std::unique_ptr<AgentSchedulingGroup>, base::UniquePtrComparator>
agent_scheduling_groups_;
RendererMemoryMetrics purge_and_suspend_memory_metrics_;
int process_foregrounded_count_;
int32_t client_id_;
#if defined(USE_NEVA_MEDIA)
template <typename original_t>
friend class neva::RenderThreadImpl;
#endif
#if defined(USE_NEVA_APPRUNTIME)
unsigned suspension_count_ = 0;
#endif
// A mojo connection to the CompositingModeReporter service.
mojo::Remote<viz::mojom::CompositingModeReporter> compositing_mode_reporter_;
// The class is a CompositingModeWatcher, which is bound to mojo through
// this member.
mojo::Receiver<viz::mojom::CompositingModeWatcher>
compositing_mode_watcher_receiver_{this};
///@name USE_NEVA_APPRUNTIME
///@{
std::unique_ptr<blink::WebScopedPagePauser> page_pauser_;
///@}
// Delegate is expected to live as long as requests may be sent.
blink::WebResourceRequestSenderDelegate* resource_request_sender_delegate_ =
nullptr;
base::WeakPtrFactory<RenderThreadImpl> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(RenderThreadImpl);
};
} // namespace content
#endif // CONTENT_RENDERER_RENDER_THREAD_IMPL_H_
|
[
"youngsoo.choi@lge.com"
] |
youngsoo.choi@lge.com
|
250e5032beba9460f90c3cc33ec46827b7f3e3de
|
154c3822e32c3fc707e775531d3973834345d270
|
/114_ejercicio.cpp
|
b59e0627b9701b1b01e40ef04761e007357a84d1
|
[] |
no_license
|
MEng-Alejandro-Nieto/Learning-cpp
|
f2da6a4f46eb1f86d472d8a1469bd885eb99287c
|
3d17d451cb534afdf9ea79e2fcb8e5495dc8a6d7
|
refs/heads/master
| 2020-07-30T13:08:22.122242
| 2019-12-05T23:20:48
| 2019-12-05T23:20:48
| 210,244,804
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 867
|
cpp
|
/*
Comprobar si un numero es par o impar, y senalar la posicion de memoria
donde se esta guardando el numero con punteros.
*/
#include <iostream>
using std::cin; using std::cout; using std::endl;
///////////////////////////////////////////////////////////////////
int n{0},*dir_n=&n;
///////////////////////////////////////////////////////////////////
void pregunta();
void par(int);
///////////////////////////////////////////////////////////////////
int main(){
pregunta();
par(n);
return 0;
}
///////////////////////////////////////////////////////////////////
void pregunta(){
cout<<"Ingrese un numero para comprobar si es par: "; cin>>n;
}
void par(int n){
if(*dir_n%2==0){
cout<<"El numero "<<*&n<< " es par y esta ubicado en "<<&n;
}
else{
cout<<"El numero "<<*&n<< " es impar y esta ubicado en "<<&n;
}
}
|
[
"alejandrolive932@hotmail.com"
] |
alejandrolive932@hotmail.com
|
0af9d676ad79790b86e906672ea473f80ec9a7af
|
2e26bbbbe3801eccf026fdb44fa16497c51de5fd
|
/bank.h
|
c450f1df3f77f324144666771185a46671a03a86
|
[] |
no_license
|
Mordequess/a6
|
aad3b3e28c81d56f723eda692573260193b13aeb
|
0bc869505fb9b30584d817f584063b9f446ce65e
|
refs/heads/master
| 2021-01-10T15:49:35.695324
| 2015-12-07T02:09:30
| 2015-12-07T02:09:30
| 47,424,905
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 446
|
h
|
#ifndef BANK_H
#define BANK_H
#include <vector>
_Monitor Bank {
uCondition insufficientFunds; // waiting on deposits
unsigned int waiters; // number of people waiting
std::vector<unsigned int> studentAccounts; // the student accounts
public:
Bank( unsigned int numStudents );
void deposit( unsigned int id, unsigned int amount );
void withdraw( unsigned int id, unsigned int amount );
};
#endif
|
[
"t.babaran@gmail.com"
] |
t.babaran@gmail.com
|
694c62cad032361e5bc6d8f3ca915112cc8794a4
|
1fdbb7e551cf8b52b43359cf406bedd969b5f59f
|
/source/driversdk/driverupdate/MainTask.cpp
|
e16935b052868f2c5aa2acc8bc62981af02f2147
|
[] |
no_license
|
trigrass2/eview-server
|
1292958416ebe772ff4ce0b1f1639c65ca13ce92
|
a5e452016a730af79a1d402a3d918403eb6073aa
|
refs/heads/master
| 2023-06-17T09:38:25.004889
| 2021-07-15T09:45:56
| 2021-07-15T09:45:56
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 3,135
|
cpp
|
/**************************************************************
* Filename: RecvThread.cpp
* Copyright: Shanghai Peak InfoTech Co., Ltd.
*
* Description: 接收消息线程.
*
* @author: liuqifeng
* @version 04/13/2009 liuqifeng Initial Version
**************************************************************/
// RecvThread.cpp: implementation of the CRecvThread class.
//
//////////////////////////////////////////////////////////////////////
#include <ace/INET_Addr.h>
#include <ace/Log_Msg.h>
#include "ClientSockHandler.h"
#include "ace/Select_Reactor.h"
#include "ace/OS_NS_strings.h"
#include "MainTask.h"
#include "SystemConfig.h"
#include "common/pklog.h"
#include "SystemConfig.h"
#include "ace/SOCK_Connector.h"
extern CPKLog PKLog;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
//ACE_DLL g_dllforwardaccessor;
//PFN_ReadAllTagsInfo g_pfnReadAllTagsInfo = NULL;
//PFN_ReadAllTagsData g_pfnReadAllTagsData = NULL;
//PFN_ReleaseAllTagsInfo g_pfnReleaseAllTagsInfo = NULL;
#define DLLNAME_FORWARDACCESSOR "forwardaccessor"
CMainTask::CMainTask():m_cycleReader(this)
{
ACE_Select_Reactor *pSelectReactor = new ACE_Select_Reactor();
m_pReactor = new ACE_Reactor(pSelectReactor, 1);
reactor(m_pReactor);
}
CMainTask::~CMainTask()
{
if (m_pReactor != NULL)
{
delete m_pReactor;
m_pReactor = NULL;
}
}
//线程服务
int CMainTask::svc()
{
//long nErr = g_dllforwardaccessor.open(DLLNAME_FORWARDACCESSOR);
//if (nErr == 0)
//{
// PKLog.LogMessage(PK_LOGLEVEL_NOTICE, " load Module %s 成功", DLLNAME_FORWARDACCESSOR);
//}
//else
// PKLog.LogMessage(PK_LOGLEVEL_ERROR, " load Module %s 失败", DLLNAME_FORWARDACCESSOR);
//// 导入初始化函数
//g_pfnReadAllTagsInfo = (PFN_ReadAllTagsInfo)g_dllforwardaccessor.symbol("ReadAllTagsInfo");
//if(g_pfnReadAllTagsInfo == NULL)
//{
// PKLog.LogMessage(PK_LOGLEVEL_ERROR, " 从%s 获取导出函数%s失败",g_dllforwardaccessor.dll_name_, "ReadAllTagsInfo");
//}
//g_pfnReadAllTagsData = (PFN_ReadAllTagsData)g_dllforwardaccessor.symbol("ReadAllTagsData");
//if(g_pfnReadAllTagsData == NULL)
//{
// PKLog.LogMessage(PK_LOGLEVEL_ERROR, " 从%s 获取导出函数%s失败",g_dllforwardaccessor.dll_name_, "ReadAllTagsData");
//}
//g_pfnReleaseAllTagsInfo = (PFN_ReleaseAllTagsInfo)g_dllforwardaccessor.symbol("ReleaseAllTagsInfo");
//if(g_pfnReleaseAllTagsInfo == NULL)
//{
// PKLog.LogMessage(PK_LOGLEVEL_ERROR, " 从%s 获取导出函数%s失败",g_dllforwardaccessor.dll_name_, "ReleaseAllTagsInfo");
//}
this->reactor()->owner(ACE_OS::thr_self ());
m_cycleReader.m_nPollRate = SYSTEM_CONFIG->m_nCycleMS;
m_cycleReader.StartTimer();
this->reactor()->reset_reactor_event_loop();
this->reactor()->run_reactor_event_loop();
m_cycleReader.StopTimer();
return 0;
}
void CMainTask::Stop()
{
// 发出关闭响应起得请求
this->reactor()->end_reactor_event_loop();
// 等待响应器关闭后退出
this->wait();
}
int CMainTask::Start()
{
return this->activate();
}
|
[
"746257224@qq.com"
] |
746257224@qq.com
|
07f865db53e262c036668795ee294b1f38f15157
|
03d01d133062e1ee483b685b834a76a7bfff6cd4
|
/src/ofApp.h
|
904a6251f333097b4be8af32d8536c2cea5a0679
|
[] |
no_license
|
AgnesChavez/XTrees_2020
|
0a99c22836d29dabd466919756e522f4d4413543
|
3722b643aabf9e2d62f5967e4edab0c868565e4c
|
refs/heads/master
| 2023-05-15T08:05:52.785686
| 2021-06-02T19:10:03
| 2021-06-02T19:10:03
| 296,460,159
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,445
|
h
|
#pragma once
#include "ofMain.h"
//#include "ofxControlPanel.h"
#include "TreesManager.h"
#include "InteractiveAudio.h"
//#include "ofxApp.h"
#include "XTreeButton.h"
#include "AlphaRect.h"
#include "TwitterLayer.h"
#include "LeavesLayer.h"
#include "LinesLayer.h"
#include "TwitterStream.h"
class ofApp :
//public ofxApp{
public ofBaseApp{
public:
ofApp();
~ofApp();
void setup();
void update();
void draw();
void exit();
void mousePressed(ofMouseEventArgs& args);
void mouseMoved(ofMouseEventArgs& args);
void mouseDragged(ofMouseEventArgs& args);
void keyPressed(ofKeyEventArgs& args);
void keyReleased(int key);
void windowResized(int w, int h);
#if USE_PDLIB
void audioReceived(float * input, int bufferSize, int nChannels);
void audioRequested(float * output, int bufferSize, int nChannels);
#endif
vector<ofNode> nodes;
// AlphaRect m_fadeRectangle;
ofSoundPlayer soundtrack;
// FlowersLayer* m_flowersLayer;
ofImage background;
bool use_background;
int backgroundOpacity;
void setFromWindowSize();
private:
void start();
void stop();
void goClicked(bool& do_);
void resetClicked(bool& do_);
// void controlChanged(guiCallbackData & data);
void updateSimulationState();
enum GuiState {
STATE_SETUP,
STATE_GUI,
STATE_SIMULATION
};
enum TimelineStates {
TIME_GROWING, // starts growing trees
TIME_LEAVES, // stop trees, start leaves
TIME_LINES_TRANS, // wait some more time after leaves have fallen
TIME_LINES, // starts the lines
TIME_LEAVESFALLING_TRANS, // stops for N seconds with all the leaves in place
TIME_LEAVESFALLING, // leaves fall,
TIME_LINES_FAST, // when no leaves are anymore present, accelerate lines
TIME_STOP_LINES, // stop
TIME_REGENERATE, // regenerate
TIME_GROWING_TRANS, // wait some time before restarting
};
GuiState m_state;
std::shared_ptr<TreesManager> m_treesLayer = nullptr;
std::shared_ptr<TwitterLayer> m_twitterLayer = nullptr;
std::shared_ptr<LinesLayer> m_linesLayer = nullptr;
std::shared_ptr<LeavesLayer> m_leavesLayer = nullptr;
std::unique_ptr<XTreeButton> m_goBtn = nullptr;
std::unique_ptr<XTreeButton> m_resetBtn = nullptr;
ofColor m_layerObfuscationColor;
// simpleFileLister m_backgroundsLister;
// simpleFileLister m_soundtracksLister;
bool m_internetOk;
int m_backgroundFadeTime;
int m_back1, m_back2;
float m_maxThreads;
bool m_screenshot;
TimelineStates m_simulationState;
unsigned int m_simulationTimer;
unsigned int m_numberOfIterations;
bool m_clearFBO;
string toString(GuiState s) {
switch(s){
case STATE_SETUP : return "STATE_SETUP";
case STATE_GUI : return "STATE_GUI";
case STATE_SIMULATION : return "STATE_SIMULATION";
}
return "";
}
string toString(TimelineStates s) {
switch(s)
{
case TIME_GROWING: return "TIME_GROWING";
case TIME_LEAVES: return "TIME_LEAVES";
case TIME_LINES_TRANS: return "TIME_LINES_TRANS";
case TIME_LINES: return "TIME_LINES";
case TIME_LEAVESFALLING_TRANS: return "TIME_LEAVESFALLING_TRANS";
case TIME_LEAVESFALLING: return "TIME_LEAVESFALLING";
case TIME_LINES_FAST: return "TIME_LINES_FAST";
case TIME_STOP_LINES: return "TIME_STOP_LINES";
case TIME_REGENERATE: return "TIME_REGENERATE";
case TIME_GROWING_TRANS: return "TIME_GROWING_TRANS";
}
return "";
}
bool bDrawStatesInfo = false;
bool bDebug = false;
bool bDrawGui = false;
};
|
[
"macdonald.roy@gmail.com"
] |
macdonald.roy@gmail.com
|
5fe58ea5c94898f78cec3ab075f98b3946bd3d09
|
7a2425190626dd2e75dd6cbca9fe47727afbad42
|
/cxxrt-source/testsuite/cxxrt.conformance/loc-22-1-1-1-2.exp
|
6e7811bbb191abfa7c380b7b675f544801d11e31
|
[] |
no_license
|
dietmarkuehl/kuhllib
|
fadd4073c9b09992479e92112ef34c367cb90fad
|
482ddc2b910870398a9a2bcaa0a77a145e081f78
|
refs/heads/main
| 2023-08-31T22:13:02.079530
| 2023-08-21T22:14:14
| 2023-08-21T22:14:14
| 3,148,966
| 71
| 7
| null | 2023-08-21T22:14:15
| 2012-01-10T21:49:09
|
C++
|
UTF-8
|
C++
| false
| false
| 2,304
|
exp
|
#!/usr/local/bin/expect
# -*-C++-*- loc-22-1-1-1-2.exp -- C++ is actually a lie but it helps
# --------------------------------------------------------------------------
# Copyright (c) 2002 Dietmar Kuehl
# 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.
# --------------------------------------------------------------------------
# Author: Dietmar Kuehl <http://www.dietmar-kuehl.de/>
# Title: Class locale::facet
# Version: $Id: loc-22-1-1-1-2.exp,v 1.1.1.1 2002/06/05 01:02:57 dietmar_kuehl Exp $
# --------------------------------------------------------------------------
inline_compile {
#include <iostream>
#include <locale>
#include <cstdlib>
#if !defined(_CXXRT_STD_NAME)
# define STD std::
#else
# define STD _CXXRT_STD_NAME::
#endif
class facet: public STD locale::facet
{
public:
static STD locale::id id;
facet(): STD locale::facet(), refs(0) {}
explicit facet(STD size_t r): STD locale::facet(r), refs(r) {}
~facet() { STD cout << "dtor: " << static_cast<int>(refs) << "\n"; }
private:
STD size_t refs;
};
STD locale::id facet::id;
int main(int, char *[])
{
STD locale l;
STD locale l1(l, new facet);
STD locale l2(l, new facet(1));
return 0;
}
}
simple_test "locale::facet refcount" "" {
dtor: 0
}
|
[
"dietmar.kuehl@me.com"
] |
dietmar.kuehl@me.com
|
d33bfa4018a480130c2d6f65c12a4c968874e7ee
|
9c875e2e2a425a62ee0ffb148e701342c142a029
|
/src/Saurobyte/AudioStream.hpp
|
8a10bfebf72696ed124bf8a1847071851aa433ce
|
[
"MIT"
] |
permissive
|
Symphonym/Saurobyte
|
4b80e587517d8108a7ac4d60f17ec7518a693c48
|
c4bc5afd4ac4353ed6cd9a201454fd14aa3aced2
|
refs/heads/master
| 2016-08-05T13:26:18.701701
| 2014-07-13T00:46:06
| 2014-07-13T00:46:06
| 17,995,418
| 19
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,919
|
hpp
|
/*
The MIT License (MIT)
Copyright (c) 2014 by Jakob Larsson
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 SAUROBYTE_AUDIOSTREAM_HPP
#define SAUROBYTE_AUDIOSTREAM_HPP
#include <Saurobyte/AudioSource.hpp>
#include <array>
#include <thread>
namespace Saurobyte
{
class AudioStream : public AudioSource
{
public:
explicit AudioStream(AudioSource::AudioFilePtr audioPtr, std::uint32_t newSource);
~AudioStream();
virtual void play();
virtual void pause();
virtual void stop();
virtual void setLooping(bool looping);
virtual void setOffset(Time offset);
virtual Time getOffset() const;
virtual bool isLooping() const;
private:
bool m_loop;
bool m_requestStop;
Time m_playingOffset;
std::thread m_thread;
// Array of OpenAL buffer handles
std::array<AudioSource::BufferWrapper, 3> m_buffers;
void processStream();
void prepareStreaming();
};
};
#endif
|
[
"symphonymdev@gmail.com"
] |
symphonymdev@gmail.com
|
3142093627ae4033a8b5ff12d61960a38bac28ed
|
26dbe4913ffb77fad2eafb6ba466233e956ef68e
|
/debugformat/debugformat-example.cpp
|
faa0b58f92568a4925f7f58555a1557a89a5c209
|
[] |
no_license
|
retdec-build/retdec-build-system-tests
|
c1fd970b2237c5e3369d35cde46f4c234c4f0dd9
|
dc5882c340d7640e207e63e43723e3304257506b
|
refs/heads/master
| 2023-01-20T18:07:58.232114
| 2020-07-21T09:55:37
| 2020-07-21T09:55:37
| 467,175,156
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 157
|
cpp
|
#include <iostream>
#include <retdec/debugformat/debugformat.h>
int main(int argc, char* argv[])
{
retdec::debugformat::DebugFormat debug;
return 0;
}
|
[
"peter.matula@avast.com"
] |
peter.matula@avast.com
|
453d8030070ac2115102ea4e30bdd990c79f9063
|
1e5c93564f82e6b069504a38c7048c1e9e1e47a6
|
/2017.1/algorithms-review/t235.cpp
|
0e82403c82d77c8a9e29c1b4f5158cb1b47da69b
|
[
"MIT"
] |
permissive
|
Forec/learn
|
d3a28209b73f4ffa9026dd232b4914f2e19f7b8d
|
38ef91d1310f82713e7a04c45c7e99e3929df813
|
refs/heads/master
| 2021-01-17T02:33:31.201367
| 2017-10-18T15:44:17
| 2017-10-18T15:44:17
| 39,928,290
| 4
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,496
|
cpp
|
#include <iostream>
#include <unordered_map>
#include <vector>
#include <unordered_set>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution1 {
private:
unordered_set<TreeNode*> vis;
unordered_map<TreeNode*, TreeNode*> par;
TreeNode *pn, *qn;
TreeNode *res;
TreeNode * find(TreeNode *u){
return par[u] == u ? u : find(par[u]);
}
void init(TreeNode * root){
if (root == NULL)
return;
par[root] = root;
init(root->left);
init(root->right);
}
void tarjan(TreeNode * root){
if (root == NULL)
return;
vis.insert(root);
if (root == pn || root == qn){
if (root == pn && vis.count(qn) >= 1)
res = find(qn);
if (root == qn && vis.count(pn) >= 1)
res = find(pn);
}
if (root->left != NULL && vis.count(root->left) == 0){
tarjan(root->left);
par[root->left] = root;
}
if (root->right != NULL && vis.count(root->right) == 0){
tarjan(root->right);
par[root->right] = root;
}
}
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
res = NULL;
pn = p; qn = q;
vis.clear();
par.clear();
init(root);
tarjan(root);
return res;
}
};
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
while ((root->val - p->val) * (root->val - q->val) > 0) {
root = p->val > root->val ? root->right : root->left;
}
return root;
}
};
int main(){
TreeNode * n6 = new TreeNode(6);
TreeNode * n2 = new TreeNode(2);
TreeNode * n8 = new TreeNode(8);
TreeNode * n0 = new TreeNode(0);
TreeNode * n4 = new TreeNode(4);
TreeNode * n7 = new TreeNode(7);
TreeNode * n9 = new TreeNode(9);
TreeNode * n3 = new TreeNode(3);
TreeNode * n5 = new TreeNode(5);
n6->left = n2; n6->right = n8;
n2->left = n0; n2->right = n4;
n4->left = n3; n4->right = n5;
n8->left = n7; n8->right = n9;
Solution sol;
TreeNode * ans1 = sol.lowestCommonAncestor(n6, n2, n8);
cout << (ans1 != NULL && 6 == ans1->val) << endl;
TreeNode * ans2 = sol.lowestCommonAncestor(n6, n2, n4);
cout << (ans2 != NULL && 2 == ans2->val) << endl;
TreeNode * ans3 = sol.lowestCommonAncestor(n6, n0, n5);
cout << (ans3 != NULL && 2 == ans3->val) << endl;
return 0;
}
|
[
"forec@bupt.edu.cn"
] |
forec@bupt.edu.cn
|
9e48c2d5e1dd5377ade75545a1450f5d49a47873
|
0e1693c18bb5897e2242549b2512d34555a0a266
|
/Libraries/Prim.cpp
|
e189788adc2ea9ff796b9f20d05d0fb773bca2b1
|
[] |
no_license
|
AngelFA04/algoritmos
|
b3c9cef7b37fb500f05cc463677a99564cefe847
|
bbc16d8e492872d6d3cd2f6f0586d3ee9e5590d3
|
refs/heads/master
| 2022-12-02T02:27:06.874755
| 2020-08-19T15:49:21
| 2020-08-19T15:49:21
| 287,777,577
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,567
|
cpp
|
#include <iostream>
#include <limits.h>
#include "Prim.h"
using namespace std;
Prim::Prim(int numeroNodos, int **matrizAdj){
this->numeroNodos = numeroNodos;
this->matrizAdj = matrizAdj;
arbol = new int[numeroNodos];
visitados = new bool[numeroNodos];
}
void Prim::inicializarValores(){
for(int i = 0; i < numeroNodos; i++){
arbol[i] = -1;
visitados[i] = false;
}
arbol[0] = 0;
visitados[0] = true;
}
bool Prim::noVisiteTodos(){
for(int i = 0; i < numeroNodos; i++){
if(!visitados[i]){
return true;
}
}
return false;
}
void Prim::imprimirSolucion(){
cout << "[ ";
for(int i = 0; i < numeroNodos - 1; i++){
cout << arbol[i] << ", ";
}
cout << arbol[numeroNodos - 1] << " ]" << endl;
}
void Prim::calcularAEM(){
inicializarValores();
while(noVisiteTodos()){
int minPeso = INT_MAX;
int minIndex;
int padre;
for(int i = 0; i < numeroNodos; i++){
if(arbol[i] != -1){
for(int j = 0; j < numeroNodos; j++){
if(visitados[j] || matrizAdj[i][j] == 0) continue;
if(matrizAdj[i][j] < minPeso){
minPeso = matrizAdj[i][j];
minIndex = j;
padre = i;
}
}
}
}
arbol[minIndex] = padre + 1;
visitados[minIndex] = true;
}
imprimirSolucion();
}
|
[
"cyberangel1000@gmail.com"
] |
cyberangel1000@gmail.com
|
dd5a3f7f5f30d778882add63e5e6f5456d399c77
|
681dd06d092fb9af9639fdc2d9be897ffc260645
|
/Source/JCVoronoiPlugin/Private/JCVValueGenerator.cpp
|
83ee3f966e32942e4d7e89a0594724aa79286207
|
[
"MIT"
] |
permissive
|
mengdada/JCVoronoiPlugin
|
5934675540a9307cbfc3f6613e231e9a00dd4839
|
25b309759160d52f44604f013e4551c6e597fa19
|
refs/heads/master
| 2020-05-15T23:07:18.883778
| 2019-04-03T22:15:20
| 2019-04-03T22:15:20
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 15,001
|
cpp
|
////////////////////////////////////////////////////////////////////////////////
//
// MIT License
//
// Copyright (c) 2018-2019 Nuraga Wiswakarma
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
////////////////////////////////////////////////////////////////////////////////
//
#include "JCVValueGenerator.h"
#include "JCVDiagramAccessor.h"
int32 FJCVValueGenerator::MarkFeature(FJCVDiagramMap& Map, TQueue<FJCVCell*>& cellQ, TSet<FJCVCell*>& ExclusionSet, FJCVCell& c, int32 i, const FJCVCellTraits& cond)
{
int32 count = 0;
cellQ.Enqueue(&c);
ExclusionSet.Emplace(&c);
while (! cellQ.IsEmpty())
{
FJCVCell* cell;
cellQ.Dequeue(cell);
FJCVEdge* g = cell->GetEdge();
check(g);
if (cond.HasValidFeature(*cell))
{
cell->SetType(cond.FeatureType, i);
++count;
}
else
continue;
do
{
FJCVCell* n = Map.GetCellNeighbour(g);
if (! n) continue;
if (ExclusionSet.Contains(n)) continue;
if (cond.HasValidFeature(*n))
{
ExclusionSet.Emplace(n);
cellQ.Enqueue(n);
}
}
while ((g = g->next) != nullptr);
}
return count;
}
void FJCVValueGenerator::AddRadialFill0(FJCVDiagramMap& Map, FRandomStream& Rand, FJCVCell& OriginCell, const FJCVRadialFill& FillParams)
{
check(Map.IsValidIndex(OriginCell.GetIndex()));
float BaseValue = FillParams.Value;
const float Radius = FillParams.Radius;
const float Sharpness = FillParams.Sharpness;
const bool bRadial = FillParams.bRadialDegrade;
const bool bFilterBorder = FillParams.bFilterBorder;
const bool bUseSharpness = Sharpness > KINDA_SMALL_NUMBER;
TQueue<FJCVCell*> cellQ;
TSet<FJCVCell*> ExclusionSet;
OriginCell.Value = FMath::Min(OriginCell.Value+BaseValue, 1.f);
ExclusionSet.Reserve(Map.Num());
ExclusionSet.Emplace(&OriginCell);
cellQ.Enqueue(&OriginCell);
while (! cellQ.IsEmpty() && BaseValue > .01f)
{
FJCVCell* cell;
cellQ.Dequeue(cell);
if (bRadial)
{
BaseValue = cell->Value;
}
BaseValue *= Radius;
FJCVEdge* g = cell->GetEdge();
check(g);
do
{
FJCVCell* n = Map.GetCellNeighbour(g);
// Skip invalid or already visited cells
if (! n || ExclusionSet.Contains(n))
{
continue;
}
ExclusionSet.Emplace(n);
cellQ.Enqueue(n);
// Zero border cell values if required
if (bFilterBorder && n->IsBorder())
{
n->Value = 0.f;
continue;
}
// Calculate new cell value
float SharpnessModifier = 1.f;
if (bUseSharpness)
{
SharpnessModifier = Rand.GetFraction() * Sharpness + 1.1f - Sharpness;
}
float CellValue = n->Value + BaseValue * SharpnessModifier;
CellValue = FMath::Min(CellValue, 1.f);
if (n->Value < CellValue)
{
n->Value = CellValue;
}
}
while ((g = g->next) != nullptr);
}
}
void FJCVValueGenerator::AddRadialFill(FJCVDiagramMap& Map, FRandomStream& Rand, FJCVCell& OriginCell, const FJCVRadialFill& FillParams)
{
if (FillParams.Radius < KINDA_SMALL_NUMBER)
{
return;
}
check(Map.IsValidIndex(OriginCell.GetIndex()));
const FVector2D OriginPosition = OriginCell.ToVector2D();
const float Radius = FillParams.Radius;
const float RadiusSq = Radius * Radius;
const float InvRadius = 1.f / Radius;
const bool bFilterBorder = FillParams.bFilterBorder;
const UCurveFloat* ValueCurve = FillParams.ValueCurve;
float BaseValue = FillParams.Value;
// Cell queue and visited cell set
TQueue<FJCVCell*> cellQ;
TSet<FJCVCell*> cellS;
// Assign base value to origin cell
OriginCell.Value = BaseValue;
cellS.Reserve(Map.Num());
cellS.Emplace(&OriginCell);
cellQ.Enqueue(&OriginCell);
while (! cellQ.IsEmpty())
{
FJCVCell* cell;
cellQ.Dequeue(cell);
FJCVEdge* g = cell->GetEdge();
check(g);
do
{
FJCVCell* n = Map.GetCellNeighbour(g);
// Skip invalid or already visited cells
if (! n || cellS.Contains(n))
{
continue;
}
cellS.Emplace(n);
float DistToOriginSq = (n->ToVector2D()-OriginPosition).SizeSquared();
// Skip cells outside of radius
if (DistToOriginSq > RadiusSq)
{
continue;
}
cellQ.Enqueue(n);
// Set border cell value to zero if filter is set
if (bFilterBorder && n->IsBorder())
{
n->Value = 0.f;
continue;
}
// Calculate new cell value
float ValueRatio = (1.f - FMath::Sqrt(DistToOriginSq) * InvRadius);
if (ValueCurve)
{
ValueRatio = ValueCurve->GetFloatValue(ValueRatio);
}
n->Value = BaseValue * ValueRatio;
}
while ((g = g->next) != nullptr);
}
}
void FJCVValueGenerator::MarkFeatures(FJCVDiagramMap& Map, const FJCVCellTraits& Cond, FJCVCellSet& ExclusionSet)
{
if (Map.IsEmpty())
{
return;
}
TQueue<FJCVCell*> cellQ;
const int32 cellN = Map.Num();
int32 f = 0;
int32 n;
do
{
FJCVCell* c = nullptr;
n = 0;
// Find single unmarked cell
for (int32 i=0; i<cellN; ++i)
if (Cond.HasUndefinedType(Map.GetCell(i)))
c = &Map.GetCell(i);
if (c)
n = MarkFeature(Map, cellQ, ExclusionSet, *c, f++, Cond);
}
// Loop until there is no undefined cell left or no conversion made
while (n > 0);
}
void FJCVValueGenerator::MarkFeatures(FJCVDiagramMap& Map, const FJCVSite& Seed, const FJCVCellTraits& Cond, int32 FeatureIndex, FJCVCellSet& ExclusionSet)
{
if (Map.IsEmpty())
{
return;
}
const FJCVSite* s = &Seed;
FJCVCell* c = Map.GetCell(s);
if (c)
{
TQueue<FJCVCell*> cellQ;
MarkFeature(Map, cellQ, ExclusionSet, *c, FeatureIndex, Cond);
}
}
float FJCVValueGenerator::GetClosestDistanceFromCellSq(
FJCVDiagramMap& Map,
const FJCVCell& OriginCell,
uint8 FeatureType,
int32 FeatureIndex,
bool bAgainstAnyType
)
{
check(Map.HasFeatureType(FeatureType));
check(Map.IsValidCell(&OriginCell));
const FVector2D Origin = OriginCell.ToVector2D();
float DistanceToFeatureSq = BIG_NUMBER;
TFunctionRef<void(FJCVCell& Cell)> CellCallback(
[&](FJCVCell& Cell)
{
const FVector2D CellPoint = Cell.ToVector2D();
const float CellDistSq = (CellPoint-Origin).SizeSquared();
if (CellDistSq < DistanceToFeatureSq)
{
DistanceToFeatureSq = CellDistSq;
}
} );
if (bAgainstAnyType)
{
Map.VisitCells(CellCallback, &OriginCell);
}
else
{
Map.VisitFeatureCells(CellCallback, FeatureType, FeatureIndex);
}
return DistanceToFeatureSq;
}
float FJCVValueGenerator::GetFurthestDistanceFromCellSq(
FJCVDiagramMap& Map,
const FJCVCell& OriginCell,
uint8 FeatureType,
int32 FeatureIndex,
bool bAgainstAnyType
)
{
check(Map.HasFeatureType(FeatureType));
check(Map.IsValidCell(&OriginCell));
const FVector2D Origin = OriginCell.ToVector2D();
float DistanceToFeatureSq = TNumericLimits<float>::Min();
TFunctionRef<void(FJCVCell& Cell)> CellCallback(
[&](FJCVCell& Cell)
{
const FVector2D CellPoint = Cell.ToVector2D();
const float CellDistSq = (CellPoint-Origin).SizeSquared();
if (CellDistSq > DistanceToFeatureSq)
{
DistanceToFeatureSq = CellDistSq;
}
} );
if (bAgainstAnyType)
{
Map.VisitCells(CellCallback, &OriginCell);
}
else
{
Map.VisitFeatureCells(CellCallback, FeatureType, FeatureIndex);
}
return DistanceToFeatureSq;
}
void FJCVValueGenerator::MapNormalizedDistanceFromCell(
FJCVDiagramMap& Map,
const FJCVCell& OriginCell,
uint8 FeatureType,
int32 FeatureIndex,
bool bAgainstAnyType
)
{
check(Map.HasFeatureType(FeatureType));
check(Map.IsValidCell(&OriginCell));
const FVector2D Origin = OriginCell.ToVector2D();
const float FurthestDistanceFromCell = GetFurthestDistanceFromCell(Map, OriginCell, FeatureType, FeatureIndex, bAgainstAnyType);
const float InvDistanceFromCell = 1.f / FMath::Max(FurthestDistanceFromCell, KINDA_SMALL_NUMBER);
TFunctionRef<void(FJCVCell&)> CellCallback(
[&](FJCVCell& Cell)
{
const FVector2D CellPoint = Cell.ToVector2D();
const float CellDist = (CellPoint-Origin).Size();
Cell.SetValue(CellDist * InvDistanceFromCell);
} );
if (bAgainstAnyType)
{
Map.VisitCells(CellCallback, &OriginCell);
}
else
{
Map.VisitFeatureCells(CellCallback, FeatureType, FeatureIndex);
}
}
void UJCVValueUtilityLibrary::SetCellValues(UJCVDiagramAccessor* Accessor, float Value)
{
if (! IsValid(Accessor))
{
UE_LOG(LogJCV,Error, TEXT("UJCVValueUtilityLibrary::AddRadialFillAtPosition() ABORTED, INVALID ACCESSOR"));
return;
}
if (! Accessor->HasValidMap())
{
UE_LOG(LogJCV,Error, TEXT("UJCVValueUtilityLibrary::AddRadialFillAtPosition() ABORTED, INVALID ACCESOR MAP"));
return;
}
FJCVDiagramMap& Map(Accessor->GetMap());
const int32 CellCount = Map.Num();
for (int32 i=0; i<CellCount; ++i)
{
Map.GetCell(i).SetValue(Value);
}
}
void UJCVValueUtilityLibrary::AddRadialFillAtPosition(UJCVDiagramAccessor* Accessor, int32 Seed, const FVector2D& Position, FJCVRadialFill FillParams)
{
if (! IsValid(Accessor))
{
UE_LOG(LogJCV,Error, TEXT("UJCVValueUtilityLibrary::AddRadialFillAtPosition() ABORTED, INVALID ACCESSOR"));
return;
}
if (! Accessor->HasValidMap())
{
UE_LOG(LogJCV,Error, TEXT("UJCVValueUtilityLibrary::AddRadialFillAtPosition() ABORTED, INVALID ACCESOR MAP"));
return;
}
FJCVDiagramMap& Map(Accessor->GetMap());
FJCVCell* OriginCell = Map.GetCell(Map->Find(Position));
if (OriginCell)
{
FJCVValueGenerator::AddRadialFill(Map, Seed, *OriginCell, FillParams);
}
}
void UJCVValueUtilityLibrary::AddRadialFillAtCell(UJCVDiagramAccessor* Accessor, int32 Seed, FJCVCellRef OriginCellRef, FJCVRadialFill FillParams)
{
if (! IsValid(Accessor))
{
UE_LOG(LogJCV,Error, TEXT("UJCVValueUtilityLibrary::AddRadialFillAtCell() ABORTED, INVALID ACCESSOR"));
return;
}
if (! Accessor->HasValidMap())
{
UE_LOG(LogJCV,Error, TEXT("UJCVValueUtilityLibrary::AddRadialFillAtCell() ABORTED, INVALID ACCESOR MAP"));
return;
}
if (! Accessor->IsValidCell(OriginCellRef))
{
UE_LOG(LogJCV,Error, TEXT("UJCVValueUtilityLibrary::AddRadialFillAtCell() ABORTED, INVALID ORIGIN CELL"));
return;
}
FJCVDiagramMap& Map(Accessor->GetMap());
FJCVCell& OriginCell(Map.GetCell(OriginCellRef.Data->GetIndex()));
FJCVValueGenerator::AddRadialFill(Map, Seed, OriginCell, FillParams);
}
void UJCVValueUtilityLibrary::AddRadialFillByIndex(UJCVDiagramAccessor* Accessor, int32 Seed, int32 CellIndex, FJCVRadialFill FillParams)
{
if (! IsValid(Accessor))
{
UE_LOG(LogJCV,Error, TEXT("UJCVValueUtilityLibrary::AddRadialFillByIndex() ABORTED, INVALID ACCESSOR"));
return;
}
if (! Accessor->HasValidMap())
{
UE_LOG(LogJCV,Error, TEXT("UJCVValueUtilityLibrary::AddRadialFillByIndex() ABORTED, INVALID ACCESOR MAP"));
return;
}
FJCVDiagramMap& Map(Accessor->GetMap());
if (Map.IsValidIndex(CellIndex))
{
FJCVCell& OriginCell(Map.GetCell(CellIndex));
FJCVValueGenerator::AddRadialFill(Map, Seed, OriginCell, FillParams);
}
}
void UJCVValueUtilityLibrary::AddRadialFillNum(UJCVDiagramAccessor* Accessor, int32 Seed, int32 PointCount, FJCVRadialFill FillParams, float Padding, float ValueThreshold, int32 MaxPlacementTest)
{
if (! IsValid(Accessor))
{
UE_LOG(LogJCV,Error, TEXT("UJCVValueUtilityLibrary::AddRadialFillNum() ABORTED, INVALID ACCESSOR"));
return;
}
if (! Accessor->HasValidMap())
{
UE_LOG(LogJCV,Error, TEXT("UJCVValueUtilityLibrary::AddRadialFillNum() ABORTED, INVALID ACCESOR MAP"));
return;
}
if (PointCount < 1)
{
return;
}
FJCVDiagramMap& Map(Accessor->GetMap());
FRandomStream Rand(Seed);
const float tMin = FMath::Clamp(ValueThreshold, 0.f, 1.f);
const float tMax = 1.f-tMin;
const int32 CellCount = Map.Num();
Padding = FMath::Clamp(Padding, 0.f, 1.f);
FBox2D Bounds(Accessor->GetBounds());
FBox2D BoundsExpand(Bounds.Min*Padding, Bounds.Max*(1.f-Padding));
for (int32 it=0; it<PointCount; ++it)
{
for (int32 i=0; i<MaxPlacementTest; ++i)
{
int32 CellIdx = Rand.RandHelper(CellCount);
FJCVCell& OriginCell(Map.GetCell(CellIdx));
if (OriginCell.Value < tMin && BoundsExpand.IsInside(OriginCell.ToVector2D()))
{
FillParams.Value *= tMax*Rand.GetFraction();
FillParams.Value += tMin;
FJCVValueGenerator::AddRadialFill(Map, Rand, OriginCell, FillParams);
break;
}
}
}
}
|
[
"kubis.padangpasir@gmail.com"
] |
kubis.padangpasir@gmail.com
|
c36c9d7e02d6cc3785e5dcb5c7146f18d9599bdc
|
7e72fd8bd7faf8a311439b43fa7574c16daafc92
|
/src/Graph.hpp
|
2d80f6089dbb5b2d6438d5cc32a446d7fa171d5f
|
[] |
no_license
|
stryitg/csp_lab1
|
20d8973c1fa422efecefc76a4f39627a756eeb6f
|
7d75ee5146a60e3026fd07c870d45540564ff907
|
refs/heads/master
| 2023-02-07T07:52:34.326155
| 2020-12-19T17:24:41
| 2020-12-19T17:24:41
| 305,174,489
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 90
|
hpp
|
#pragma once
#include <vector>
using AdjacmentMatrix = std::vector<std::vector<double>>;
|
[
"stryitg@gmail.com"
] |
stryitg@gmail.com
|
26f3cabdbf00c6736e2e8b401a5599c6e2390cfb
|
cefd6c17774b5c94240d57adccef57d9bba4a2e9
|
/WebKit/Source/WebCore/platform/graphics/ca/win/CACFLayerTreeHost.cpp
|
5e5411a49d6620f22bfb1f32486953b769aa88c9
|
[
"BSL-1.0",
"BSD-2-Clause",
"LGPL-2.0-only",
"LGPL-2.1-only"
] |
permissive
|
adzhou/oragle
|
9c054c25b24ff0a65cb9639bafd02aac2bcdce8b
|
5442d418b87d0da161429ffa5cb83777e9b38e4d
|
refs/heads/master
| 2022-11-01T05:04:59.368831
| 2014-03-12T15:50:08
| 2014-03-12T15:50:08
| 17,238,063
| 0
| 1
|
BSL-1.0
| 2022-10-18T04:23:53
| 2014-02-27T05:39:44
|
C++
|
UTF-8
|
C++
| false
| false
| 10,237
|
cpp
|
/*
* Copyright (C) 2009, 2013 Apple 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:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "CACFLayerTreeHost.h"
#include "CACFLayerTreeHostClient.h"
#include "DefWndProcWindowClass.h"
#include "LayerChangesFlusher.h"
#include "LegacyCACFLayerTreeHost.h"
#include "PlatformCALayerWin.h"
#include "WKCACFViewLayerTreeHost.h"
#include "WebCoreInstanceHandle.h"
#include <limits.h>
#include <QuartzCore/CABase.h>
#include <wtf/CurrentTime.h>
#include <wtf/StdLibExtras.h>
#include <wtf/win/GDIObject.h>
#ifdef DEBUG_ALL
#pragma comment(lib, "QuartzCore_debug")
#else
#pragma comment(lib, "QuartzCore")
#endif
inline static CGRect winRectToCGRect(RECT rc)
{
return CGRectMake(rc.left, rc.top, (rc.right - rc.left), (rc.bottom - rc.top));
}
inline static CGRect winRectToCGRect(RECT rc, RECT relativeToRect)
{
return CGRectMake(rc.left, (relativeToRect.bottom-rc.bottom), (rc.right - rc.left), (rc.bottom - rc.top));
}
namespace WebCore {
bool CACFLayerTreeHost::acceleratedCompositingAvailable()
{
static bool available;
static bool tested;
if (tested)
return available;
tested = true;
// Initialize available to true since this function will be called from a
// propagation within createRenderer(). We want to be able to return true
// when that happens so that the test can continue.
available = true;
HMODULE library = LoadLibrary(TEXT("d3d9.dll"));
if (!library) {
available = false;
return available;
}
FreeLibrary(library);
#ifdef DEBUG_ALL
library = LoadLibrary(TEXT("QuartzCore_debug.dll"));
#else
library = LoadLibrary(TEXT("QuartzCore.dll"));
#endif
if (!library) {
available = false;
return available;
}
FreeLibrary(library);
// Make a dummy HWND.
HWND testWindow = ::CreateWindow(defWndProcWindowClassName(), L"CoreAnimationTesterWindow", WS_POPUP, -500, -500, 20, 20, 0, 0, 0, 0);
if (!testWindow) {
available = false;
return available;
}
RefPtr<CACFLayerTreeHost> host = CACFLayerTreeHost::create();
host->setWindow(testWindow);
available = host->createRenderer();
host->setWindow(0);
::DestroyWindow(testWindow);
return available;
}
PassRefPtr<CACFLayerTreeHost> CACFLayerTreeHost::create()
{
if (!acceleratedCompositingAvailable())
return 0;
RefPtr<CACFLayerTreeHost> host = WKCACFViewLayerTreeHost::create();
if (!host)
host = LegacyCACFLayerTreeHost::create();
host->initialize();
return host.release();
}
CACFLayerTreeHost::CACFLayerTreeHost()
: m_client(0)
, m_rootLayer(PlatformCALayerWin::create(PlatformCALayer::LayerTypeRootLayer, 0))
, m_window(0)
, m_shouldFlushPendingGraphicsLayerChanges(false)
, m_isFlushingLayerChanges(false)
#if !ASSERT_DISABLED
, m_state(WindowNotSet)
#endif
{
}
void CACFLayerTreeHost::initialize()
{
// Point the CACFContext to this
initializeContext(this, m_rootLayer.get());
// Under the root layer, we have a clipping layer to clip the content,
// that contains a scroll layer that we use for scrolling the content.
// The root layer is the size of the client area of the window.
// The clipping layer is the size of the WebView client area (window less the scrollbars).
// The scroll layer is the size of the root child layer.
// Resizing the window will change the bounds of the rootLayer and the clip layer and will not
// cause any repositioning.
// Scrolling will affect only the position of the scroll layer without affecting the bounds.
m_rootLayer->setName("CACFLayerTreeHost rootLayer");
m_rootLayer->setAnchorPoint(FloatPoint3D(0, 0, 0));
m_rootLayer->setGeometryFlipped(true);
#ifndef NDEBUG
CGColorRef debugColor = CGColorCreateGenericRGB(1, 0, 0, 0.8);
m_rootLayer->setBackgroundColor(debugColor);
CGColorRelease(debugColor);
#endif
}
CACFLayerTreeHost::~CACFLayerTreeHost()
{
ASSERT_WITH_MESSAGE(m_state != WindowSet, "Must call setWindow(0) before destroying CACFLayerTreeHost");
}
void CACFLayerTreeHost::setWindow(HWND window)
{
if (window == m_window)
return;
#if !ASSERT_DISABLED
switch (m_state) {
case WindowNotSet:
ASSERT_ARG(window, window);
ASSERT(!m_window);
m_state = WindowSet;
break;
case WindowSet:
ASSERT_ARG(window, !window);
ASSERT(m_window);
m_state = WindowCleared;
break;
case WindowCleared:
ASSERT_NOT_REACHED();
break;
}
#endif
if (m_window)
destroyRenderer();
m_window = window;
}
PlatformCALayer* CACFLayerTreeHost::rootLayer() const
{
return m_rootLayer.get();
}
void CACFLayerTreeHost::addPendingAnimatedLayer(PassRefPtr<PlatformCALayer> layer)
{
m_pendingAnimatedLayers.add(layer);
}
void CACFLayerTreeHost::setRootChildLayer(PlatformCALayer* layer)
{
m_rootLayer->removeAllSublayers();
m_rootChildLayer = layer;
if (m_rootChildLayer)
m_rootLayer->appendSublayer(m_rootChildLayer.get());
}
void CACFLayerTreeHost::layerTreeDidChange()
{
if (m_isFlushingLayerChanges) {
// The layer tree is changing as a result of flushing GraphicsLayer changes to their
// underlying PlatformCALayers. We'll flush those changes to the context as part of that
// process, so there's no need to schedule another flush here.
return;
}
// The layer tree is changing as a result of someone modifying a PlatformCALayer that doesn't
// have a corresponding GraphicsLayer. Schedule a flush since we won't schedule one through the
// normal GraphicsLayer mechanisms.
LayerChangesFlusher::shared().flushPendingLayerChangesSoon(this);
}
void CACFLayerTreeHost::destroyRenderer()
{
m_rootLayer = 0;
m_rootChildLayer = 0;
LayerChangesFlusher::shared().cancelPendingFlush(this);
}
static void getDirtyRects(HWND window, Vector<CGRect>& outRects)
{
ASSERT_ARG(outRects, outRects.isEmpty());
RECT clientRect;
if (!GetClientRect(window, &clientRect))
return;
auto region = adoptGDIObject(::CreateRectRgn(0, 0, 0, 0));
int regionType = GetUpdateRgn(window, region.get(), false);
if (regionType != COMPLEXREGION) {
RECT dirtyRect;
if (GetUpdateRect(window, &dirtyRect, false))
outRects.append(winRectToCGRect(dirtyRect, clientRect));
return;
}
DWORD dataSize = ::GetRegionData(region.get(), 0, 0);
auto regionDataBuffer = std::make_unique<unsigned char[]>(dataSize);
RGNDATA* regionData = reinterpret_cast<RGNDATA*>(regionDataBuffer.get());
if (!::GetRegionData(region.get(), dataSize, regionData))
return;
outRects.resize(regionData->rdh.nCount);
RECT* rect = reinterpret_cast<RECT*>(regionData->Buffer);
for (size_t i = 0; i < outRects.size(); ++i, ++rect)
outRects[i] = winRectToCGRect(*rect, clientRect);
}
void CACFLayerTreeHost::paint()
{
Vector<CGRect> dirtyRects;
getDirtyRects(m_window, dirtyRects);
render(dirtyRects);
}
void CACFLayerTreeHost::flushPendingGraphicsLayerChangesSoon()
{
m_shouldFlushPendingGraphicsLayerChanges = true;
LayerChangesFlusher::shared().flushPendingLayerChangesSoon(this);
}
void CACFLayerTreeHost::setShouldInvertColors(bool)
{
}
void CACFLayerTreeHost::flushPendingLayerChangesNow()
{
// Calling out to the client could cause our last reference to go away.
RefPtr<CACFLayerTreeHost> protector(this);
m_isFlushingLayerChanges = true;
// Flush changes stored up in GraphicsLayers to their underlying PlatformCALayers, if
// requested.
if (m_client && m_shouldFlushPendingGraphicsLayerChanges) {
m_shouldFlushPendingGraphicsLayerChanges = false;
m_client->flushPendingGraphicsLayerChanges();
}
// Flush changes stored up in PlatformCALayers to the context so they will be rendered.
flushContext();
m_isFlushingLayerChanges = false;
}
void CACFLayerTreeHost::contextDidChange()
{
// All pending animations will have been started with the flush. Fire the animationStarted calls.
notifyAnimationsStarted();
}
void CACFLayerTreeHost::notifyAnimationsStarted()
{
// Send currentTime to the pending animations. This function is called by CACF in a callback
// which occurs after the drawInContext calls. So currentTime is very close to the time
// the animations actually start
double currentTime = monotonicallyIncreasingTime();
HashSet<RefPtr<PlatformCALayer> >::iterator end = m_pendingAnimatedLayers.end();
for (HashSet<RefPtr<PlatformCALayer> >::iterator it = m_pendingAnimatedLayers.begin(); it != end; ++it)
(*it)->animationStarted(currentTime);
m_pendingAnimatedLayers.clear();
}
CGRect CACFLayerTreeHost::bounds() const
{
RECT clientRect;
GetClientRect(m_window, &clientRect);
return winRectToCGRect(clientRect);
}
}
|
[
"adzhou@hp.com"
] |
adzhou@hp.com
|
013e5d9fcf18c0d83a43c6e0b9c0e65ed2e0ea1f
|
9e6844d984c81fcd002c81452b5648585b90abaa
|
/tests/test.cpp
|
a5560119ab97c0066169990afc3d87d4bf7e9579
|
[] |
no_license
|
siriusbetta/cpp_connector
|
5cc0edd8388dc74af9b48e4f7086ca1d54f9521d
|
ea13cfd9993b2d087ed443472af5c5355db760a1
|
refs/heads/master
| 2021-07-03T18:04:44.967981
| 2017-09-26T14:33:33
| 2017-09-26T14:33:33
| 104,113,909
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 375
|
cpp
|
#define CATCH_CONFIG_MAIN
#include <../include/Catch/include/catch.hpp>
unsigned int Factorial( unsigned int number)
{
return number <= 1 ? number : Factorial(number - 1) * number;
}
TEST_CASE( "Factorial are computed", "[factorial]")
{
REQUIRE( Factorial(1) == 1 );
REQUIRE( Factorial(2) == 2 );
REQUIRE( Factorial(3) == 6 );
REQUIRE( Factorial(10) == 3628800);
}
|
[
"conan85@inbox.ru"
] |
conan85@inbox.ru
|
513eede9c8b5ce0e2cb0c3edec392634932be424
|
4a6e20a36f5b6b7fa34fdb2c465969e3425d67c0
|
/VulkanProject/Utilities.h
|
c0f12445ccfee201ee77de1edc8dc2f3880e0224
|
[] |
no_license
|
axsaucedo/VulkanWrapper
|
0aec4b4839357bb3667f8dddb05f3c9a19cdddd1
|
42a244db8fef3fdf99ea7a5b80a5420881194bff
|
refs/heads/master
| 2022-11-23T18:43:14.420896
| 2020-07-28T08:16:34
| 2020-07-28T08:16:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 11,747
|
h
|
#pragma once
#include <fstream>
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
const int MAX_FRAME_DRAWS = 2;
const int MAX_OBJECTS = 20;
const std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
struct Vertex
{
glm::vec3 pos; // Vertex position (x, y, z)
glm::vec3 col; // Vertex colour (r, g, b)
glm::vec2 tex; // Texture coords (u, v)
};
// Indices (locations) of queue families (if they exist at all)
struct QueueFamilyIndices {
int graphicsFamily = -1; // Location of Graphics Queue Family
int presentationFamily = -1; // Location of presentation queue family
// Check if queue families are valid
bool isValid() {
return graphicsFamily >= 0 && presentationFamily >= 0;
}
};
struct SwapchainDetails {
VkSurfaceCapabilitiesKHR surfaceCapabilities; // Surface properties, e.g. image size/extent
std::vector<VkSurfaceFormatKHR> formats; // Surface image formats e.g. RGBA and size of each color
std::vector<VkPresentModeKHR> presentationModes; // How images should be presented to screen
};
struct SwapchainImage {
VkImage image;
VkImageView imageView;
};
static std::vector<char> readFile(const std::string& filename) {
// OPen stream from given file
// std::ios::binary telsl stream to read file as binary
// std::ios::ate tells stream to start reading from end of file
std::ifstream file(filename, std::ios::binary | std::ios::ate);
// Check if file stream successfully opened
if (!file.is_open()) {
throw std::runtime_error("Failed to open a file!");
}
// Get current read position and use to resize file buffer
size_t fileSize = (size_t)file.tellg();
std::vector<char> fileBuffer(fileSize);
// Move read position (seek to) the start of the file
file.seekg(0);
// Read the file data into the buffer (stream "filesize" in total)
file.read(fileBuffer.data(), fileSize);
// Close stream
file.close();
return fileBuffer;
}
static uint32_t findMemoryTypeIndex(VkPhysicalDevice physicalDevice, uint32_t allowedTypes, VkMemoryPropertyFlags properties)
{
// Get properties of physical device memory
VkPhysicalDeviceMemoryProperties memoryProperties;
vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memoryProperties);
for (uint32_t i = 0; i < memoryProperties.memoryTypeCount; i++) {
// Currently we are checking if we are aligned to the current allowed type
// ie 1 would be 0001 and if i is 2, then we'd see the 1 shifted into 0100
// This means that we would be comparing the specific allowed type with the current one
if ((allowedTypes & (1 << i)) // Index of memory type must match corresponding bit in allowed types
&& (memoryProperties.memoryTypes[i].propertyFlags & properties) == properties) // Desired property flags are exactly the same as properties flag
{
// This memory type is valid so return its index
return i;
}
}
throw std::runtime_error("No memory type index found");
}
static void createBuffer(
VkPhysicalDevice physicalDevice,
VkDevice device,
VkDeviceSize bufferSize,
VkBufferUsageFlags bufferUsage,
VkMemoryPropertyFlags bufferProperties,
VkBuffer* buffer,
VkDeviceMemory* bufferMemory) {
// -- Create Vertex buffer
// Information to create a buffer (doesn't include assigning memory)
VkBufferCreateInfo bufferInfo = {};
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferInfo.size = bufferSize; // Size of buffer (size of 1 vertex * number of vertices)
bufferInfo.usage = bufferUsage; // Multiple types of buffers possible
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; // Similar to sawp chain images, can share vertex buffers
VkResult result = vkCreateBuffer(device, &bufferInfo, nullptr, buffer);
if (result != VK_SUCCESS) {
throw std::runtime_error("Failed to create a vertex buffer");
}
// Get buffer memory requirements
VkMemoryRequirements memRequirements;
vkGetBufferMemoryRequirements(device, *buffer, &memRequirements);
// Allocate memory to buffer
VkMemoryAllocateInfo memoryAllocInfo = {};
memoryAllocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
memoryAllocInfo.allocationSize = memRequirements.size;
memoryAllocInfo.memoryTypeIndex = findMemoryTypeIndex(physicalDevice, memRequirements.memoryTypeBits, // Index of memory type on physical device that has required bit flags
bufferProperties); // VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT: CPU can interact with memory. VK_MEMORY_PROERTY_HOST_COHERENT_BIT: allows placement of data straight into buffer after mapping (otherwise would have to specify manually)
// Allocate memory to vkDeviceMemory
result = vkAllocateMemory(device, &memoryAllocInfo, nullptr, bufferMemory);
if (result != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate vertext buffer memory");
}
// Bind the buffer into the memory to given vertex buffer
vkBindBufferMemory(device, *buffer, *bufferMemory, 0);
}
static VkCommandBuffer beginCommandBuffer(VkDevice device, VkCommandPool commandPool) {
// Command buffer to hold trasnfer commands
VkCommandBuffer commandBuffer;
// Command buffer details
VkCommandBufferAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = commandPool;
allocInfo.commandBufferCount = 1;
// Allocate command buffer from pool
vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
// Info to begin the command buffer recod
VkCommandBufferBeginInfo beginInfo = {};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; // We're only use the comand buffer once, so set i for one time submt
// Begin recording transfer commands
vkBeginCommandBuffer(commandBuffer, &beginInfo);
return commandBuffer;
}
static void endAndSubmitCommandBuffer(VkDevice device, VkCommandPool commandPool, VkQueue queue, VkCommandBuffer commandBuffer) {
// End commands
vkEndCommandBuffer(commandBuffer);
// Queue submission information
VkSubmitInfo submitInfo = {};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
// Submit transfer command
// Because we don't have many meshes we can have a simple wait for queue to be done (instead of setting the fences/semaphores)
vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(queue);
// Free temporary command buffer back to pool
vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
}
static void copyBuffer(
VkDevice device,
VkQueue transferQueue,
VkCommandPool transferCommandPool,
VkBuffer srcBuffer,
VkBuffer dstBuffer,
VkDeviceSize bufferSize)
{
// Create buffer
VkCommandBuffer transferCommandBuffer = beginCommandBuffer(device, transferCommandPool);
// Region of data to copy from and to
VkBufferCopy bufferCopyRegion = {};
bufferCopyRegion.srcOffset = 0; // Copy everything from the start of the first buffer
bufferCopyRegion.dstOffset = 0; // Copy everything to the start of the second buffer
bufferCopyRegion.size = bufferSize;
// Command to copy src buffer to dst buffer
vkCmdCopyBuffer(transferCommandBuffer, srcBuffer, dstBuffer, 1, &bufferCopyRegion);
// End and submit buffer to dst buffer
endAndSubmitCommandBuffer(device, transferCommandPool, transferQueue, transferCommandBuffer);
}
static void copyImageBuffer(VkDevice device, VkQueue transferQueue, VkCommandPool transferCommandPool,
VkBuffer srcBuffer, VkImage dstImage, uint32_t width, uint32_t height) {
// Create buffer
VkCommandBuffer transferCommandBuffer = beginCommandBuffer(device, transferCommandPool);
VkBufferImageCopy imageRegion = {};
imageRegion.bufferOffset = 0; // Offset into data
imageRegion.bufferRowLength = 0; // Row length of data to calculate data spacing
imageRegion.bufferImageHeight = 0; // Image height to calculate data spacing
imageRegion.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; // Which aspect of image to copy
imageRegion.imageSubresource.mipLevel = 0; // Mipmap level to copy
imageRegion.imageSubresource.baseArrayLayer = 0; // Starting array layer if there is array
imageRegion.imageSubresource.layerCount = 1; // Number of layers to start copy starting at baseArrayLayer
imageRegion.imageOffset = { 0, 0, 0 }; // Offset into image as opposed to raw data in bufferOffset
imageRegion.imageExtent = { width, height, 1 };
// Copy buffer to given image
vkCmdCopyBufferToImage(transferCommandBuffer, srcBuffer, dstImage,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &imageRegion);
// End and submit buffer to dst buffer
endAndSubmitCommandBuffer(device, transferCommandPool, transferQueue, transferCommandBuffer);
}
static void transitionImageLayout(VkDevice device, VkQueue queue,
VkCommandPool commandPool, VkImage image, VkImageLayout oldLayout, VkImageLayout newLayout) {
// Create buffer
VkCommandBuffer commandBuffer = beginCommandBuffer(device, commandPool);
VkImageMemoryBarrier imageMemoryBarrier = {};
imageMemoryBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
imageMemoryBarrier.oldLayout = oldLayout; // Layout to transition from
imageMemoryBarrier.newLayout = newLayout; // Layout to transition to
imageMemoryBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; // Queue family to trans
imageMemoryBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
imageMemoryBarrier.image = image;
imageMemoryBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; // ASpect of image being altered
imageMemoryBarrier.subresourceRange.baseMipLevel = 0; // Firsst mip level to start alteations on
imageMemoryBarrier.subresourceRange.levelCount = 1; // Number of mip levels to start from base
imageMemoryBarrier.subresourceRange.baseArrayLayer = 0; // First layer to start alterations on
imageMemoryBarrier.subresourceRange.layerCount = 1; // Number of layers to alter starting from baseArrayLayer
VkPipelineStageFlags srcStage;
VkPipelineStageFlags dstStage;
// If transitioning from new image to image ready to receive data do the following if statement
if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
imageMemoryBarrier.srcAccessMask = 0; // Memory stage transition must happen after this stage (currently set to 0 meaning it doens't matter)
imageMemoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; // THis is the access mask that we want to ensure the transition happens before
srcStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
dstStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
}
// If transitioning from transfer detination to shader readable
else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
imageMemoryBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
imageMemoryBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
srcStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
dstStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
}
vkCmdPipelineBarrier(
commandBuffer,
srcStage, dstStage, // pipeline stages (match to src and dst access masks just above)
0, // Dependency flags
0, nullptr, // Memory barrier count + data
0, nullptr, // Buffer memory barrier count + data
1, &imageMemoryBarrier // Image memory barrier count + data
);
// End and submit buffer to dst buffer
endAndSubmitCommandBuffer(device, commandPool, queue, commandBuffer);
}
|
[
"axsauze@gmail.com"
] |
axsauze@gmail.com
|
4139dcc5944bb511e85e4d5887d1305b0588320f
|
51318bac6c32d5d298e277bad94511bcf3de42cf
|
/message.cpp
|
48be0a2767d3b162eb4227e69fc0d8ffd1607fd3
|
[] |
no_license
|
xxmicloxx/GSPlayerQT
|
8d66a5ac6ce6a597aa6347faf4b3692d60bd8030
|
83e5f6ed0ef7f1d66e5503a6e9b94602d842996e
|
refs/heads/master
| 2021-01-17T05:30:07.205693
| 2014-01-01T21:05:35
| 2014-01-01T21:05:35
| 4,930,092
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,204
|
cpp
|
#include "message.h"
#include "ui_message.h"
#include <QTimer>
Message::Message(QWidget *parent) :
QWidget(parent),
ui(new Ui::Message)
{
ui->setupUi(this);
opacity = new QGraphicsOpacityEffect(this);
opacity->setOpacity(0.0);
this->setGraphicsEffect(opacity);
blendIn = new QPropertyAnimation(opacity, "opacity");
blendOut = new QPropertyAnimation(opacity, "opacity");
moveUp = new QPropertyAnimation(this, "geometry");
moveUp->setDuration(1000);
blendIn->setDuration(500);
blendOut->setDuration(500);
blendIn->setStartValue(0.0);
blendOut->setStartValue(0.75);
blendIn->setEndValue(0.75);
blendOut->setEndValue(0.0);
this->setAttribute(Qt::WA_TransparentForMouseEvents);
connect(blendIn, SIGNAL(finished()), this, SLOT(blendedIn()));
}
Message::~Message()
{
delete ui;
delete blendIn;
delete blendOut;
delete moveUp;
}
void Message::blendedIn() {
QTimer* timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), blendOut, SLOT(start()));
timer->setSingleShot(true);
timer->start(1500);
}
void Message::setText(std::string text) {
ui->lblMessage->setText(QString::fromStdString(text));
}
|
[
"xxmicloxx@googlemail.com"
] |
xxmicloxx@googlemail.com
|
372cda4d3001bc77956d7874d8c9b11ca960ecc4
|
82886772b5b5a201979112790fe38b93755f810b
|
/src/Grid.cpp
|
918f1c06a83e19e9e4a3a18e9dd540ced8b1baa5
|
[] |
no_license
|
wnguatem/Simple3DViewer
|
49fbcd8d2d1f749a06ea1db6c926b2863e9d72c1
|
87b2ff8fa357bc11272c50c9f9ccdeceb157b996
|
refs/heads/master
| 2021-01-18T22:33:33.447227
| 2016-02-04T16:54:38
| 2016-02-04T16:54:38
| 32,938,923
| 5
| 1
| null | 2016-06-01T17:50:14
| 2015-03-26T16:27:54
|
C++
|
UTF-8
|
C++
| false
| false
| 4,351
|
cpp
|
#include "Grid.h"
#include "Game.h"
#include "GameException.h"
#include "Camera.h"
#include "ColorHelper.h"
#include "VectorHelper.h"
#include "Utility.h"
#include "VertexDeclarations.h"
using namespace glm;
namespace Library
{
//RTTI_DEFINITIONS(Grid)
const GLuint Grid::DefaultSize = 50;
const GLuint Grid::DefaultScale = 500;
const vec4 Grid::DefaultColor = vec4(0.961f, 0.871f, 0.702f, 1.0f);
Grid::Grid(Game& game, Camera& camera)
: DrawableGameComponent(game), mVertexArrayObject(0), mVertexBuffer(0),
mPosition(Vector3Helper::Zero), mSize(DefaultSize), mScale(DefaultScale), mColor(DefaultColor),
mWorldMatrix(), mVertexCount(0), mContentFolder(game.getGameContentFolder())
{
mCamera = &camera;
}
Grid::Grid(Game& game, Camera& camera, GLuint size, GLuint scale, const vec4& color)
: DrawableGameComponent(game), mVertexArrayObject(0), mVertexBuffer(0),
mPosition(Vector3Helper::Zero), mSize(size), mScale(scale), mColor(color), mWorldMatrix(), mContentFolder(game.getGameContentFolder())
{
mCamera = &camera;
}
Grid::~Grid()
{
glDeleteBuffers(1, &mVertexBuffer);
glDeleteVertexArrays(1, &mVertexArrayObject);
}
const vec3& Grid::Position() const
{
return mPosition;
}
const vec4& Grid::Color() const
{
return mColor;
}
const GLuint Grid::Size() const
{
return mSize;
}
const GLuint Grid::Scale() const
{
return mScale;
}
void Grid::SetPosition(const vec3& position)
{
mPosition = position;
mWorldMatrix = translate(mat4(), mPosition);
}
void Grid::SetPosition(float x, float y, float z)
{
mPosition = vec3(x, y, z);
mWorldMatrix = translate(mat4(), mPosition);
}
void Grid::SetColor(const vec4& color)
{
mColor = color;
InitializeGrid();
}
void Grid::SetSize(GLuint size)
{
mSize = size;
InitializeGrid();
}
void Grid::SetScale(GLuint scale)
{
mScale = scale;
InitializeGrid();
}
void Grid::Initialize()
{
//SetCurrentDirectory(Utility::ExecutableDirectory().c_str());
// Build the shader program
std::vector<ShaderDefinition> shaders;
shaders.push_back(ShaderDefinition(GL_VERTEX_SHADER, mContentFolder + "/BasicEffect.vert"));
shaders.push_back(ShaderDefinition(GL_FRAGMENT_SHADER, mContentFolder + "/BasicEffect.frag"));
mShaderProgram.BuildProgram(shaders);
InitializeGrid();
// Create the vertex array object
glGenVertexArrays(1, &mVertexArrayObject);
mShaderProgram.Initialize(mVertexArrayObject);
glBindVertexArray(0);
}
void Grid::Draw(const GameTime& gameTime)
{
glBindVertexArray(mVertexArrayObject);
glBindBuffer(GL_ARRAY_BUFFER, mVertexBuffer);
mShaderProgram.Use();
mat4 wvp = mCamera->ViewProjectionMatrix() * mWorldMatrix;
mShaderProgram.WorldViewProjection() << wvp;
glLineWidth(4);
glDrawArrays(GL_LINES, 0, mVertexCount);
glBindVertexArray(0);
}
void Grid::InitializeGrid()
{
mVertexCount = (mSize + 1) * 4;
//std::unique_ptr<VertexPositionColor> vertexData(new VertexPositionColor[mVertexCount]);
//VertexPositionColor* vertices = vertexData.get();
//VertexPositionColor rrr[mVertexCount];
//VertexPositionColor *vertices = new VertexPositionColor();
//std::vector<VertexPositionColor> vertices(mVertexCount);
std::vector<VertexPositionColor> vertices(mVertexCount);
float adjustedScale = mScale * 0.1f;
float maxPosition = mSize * adjustedScale / 2;
for (unsigned int i = 0, j = 0; i < mSize + 1; i++, j = 4 * i)
{
float position = maxPosition - (i * adjustedScale);
// Vertical line
vertices[j] = VertexPositionColor(vec4(position, 0.0f, maxPosition, 1.0f), mColor);
vertices[j + 1] = VertexPositionColor(vec4(position, 0.0f, -maxPosition, 1.0f), mColor);
// Horizontal line
vertices[j + 2] = VertexPositionColor(vec4(maxPosition, 0.0f, position, 1.0f), mColor);
vertices[j + 3] = VertexPositionColor(vec4(-maxPosition, 0.0f, position, 1.0f), mColor);
}
glDeleteBuffers(1, &mVertexBuffer);
mShaderProgram.CreateVertexBuffer(reinterpret_cast<VertexPositionColor*> (vertices.data()), mVertexCount, mVertexBuffer);
// mShaderProgram.CreateVertexBuffer(vertices, mVertexCount, mVertexBuffer);
// glDeleteBuffers(1, &mVertexBuffer);s
//delete vertices;
}
}
|
[
"william.nguatem@googlemail.com"
] |
william.nguatem@googlemail.com
|
c0ba5e02dbe26de3c9ba7dd4817d85064b84f00f
|
06bf3efc9b3b8f5968509e279ec0dd5285f19537
|
/test/utilities/testUtils.hpp
|
b57f2f54778971f5f4e5686033f37afcd5cdfece
|
[
"BSD-3-Clause"
] |
permissive
|
jiridanek/Strongtalk
|
0a87c0eb5281702df6d8c3a927403dc2a7402f72
|
ee19957341abe4b2113378394806b18ed329bc07
|
refs/heads/master
| 2021-05-30T14:09:38.537071
| 2016-01-10T10:34:47
| 2016-01-10T10:34:47
| 42,392,327
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 157
|
hpp
|
#define as_large_integer(value) \
byteArrayPrimitives::largeIntegerFromSmallInteger(as_smiOop(value), klassOop(Universe::find_global("LargeInteger")))
|
[
"steve@vimes.worldonline.co.uk"
] |
steve@vimes.worldonline.co.uk
|
6e1dd40574260400141e45f94645e47eb64b3d86
|
d1f3fd80b11190ac54f0dbcb5366c05e855d2d61
|
/ameba_tools_macosx/tools/macosx/src/postbuild_img2_arduino_macosx.cpp
|
8a5a7dd8fa2f2e6725e583dbd2b081e5545f78c1
|
[] |
no_license
|
DistyDevice/Arduino
|
14c5f1dfd03d096ad29f6f221776d00eca845c18
|
cf5a864ee9011da6c294bebbf38167b2ded6dc50
|
refs/heads/master
| 2022-04-06T06:38:53.801243
| 2020-03-03T03:42:24
| 2020-03-03T03:42:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,092
|
cpp
|
/*
Compile command:
g++ -o postbuild_img2_arduino_macosx tools/macosx/src/postbuild_img2_arduino_macosx.cpp
*/
#include <iostream>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <unistd.h>
#include <vector>
using namespace std;
int main(int argc, char *argv[]) {
int ret = 0;
stringstream cmdss;
string cmd, line, msg;
vector<string> lines;
vector<string>::iterator iter;
string path_tool;
string path_arm_none_eabi_gcc;
string path_symbol_black_list;
string bksym;
ifstream fin;
bool has_sdram = false;
string sram_start_st = "", sram_end_st = "", sdram_start_st = "", sdram_end_st = "";
unsigned int sram_start = 0, sram_end = 0, sdram_start = 0, sdram_end = 0;
size_t pos;
// 0. change work folder
chdir(argv[1]);
// 1. copy elf application.axf to current folder
cmdss.clear();
cmdss << "cp " << argv[2] << " ./";
getline(cmdss, cmd);
cout << cmd << endl;
system(cmd.c_str());
// 2. remove previous files
cmd = "rm -f application.map";
cout << cmd << endl;
system(cmd.c_str());
cmd = "rm -f application.asm";
cout << cmd << endl;
system(cmd.c_str());
cmd = "rm -f *.bin";
cout << cmd << endl;
system(cmd.c_str());
// 3. generate information files
path_arm_none_eabi_gcc.assign(argv[3]);
cmdss.clear();
cmdss << path_arm_none_eabi_gcc << "arm-none-eabi-nm --numeric-sort application.axf > application.map";
getline(cmdss, cmd);
cout << cmd << endl;
system(cmd.c_str());
fin.open("application.map");
while( getline(fin, line) ) {
lines.push_back(line);
}
fin.close();
cmdss.clear();
cmdss << path_arm_none_eabi_gcc << "arm-none-eabi-objdump -d application.axf > application.asm";
getline(cmdss, cmd);
cout << cmd << endl;
system(cmd.c_str());
// 3.1 check if any forbidden symbols
path_symbol_black_list.assign(argv[4]);
fin.open(path_symbol_black_list.c_str(), ifstream::in);
cout << path_symbol_black_list << endl;
ret = 0;
if (fin) {
while ( !fin.eof() && ret == 0) {
fin >> bksym;
getline(fin, msg);
// check if this symbole appears in the map file
for (iter = lines.begin(); iter != lines.end(); ++iter) {
if ( (iter->find(bksym)) != string::npos ) {
cerr << endl << "ERROR: " << msg << endl << endl;
ret = -1;
break;
}
}
}
}
fin.close();
if (ret != 0) {
return -1;
}
// 4. grep sram and sdram information
for (iter = lines.begin(); iter != lines.end(); ++iter) {
line = *iter;
pos = line.find("__ram_image2_text_start__");
if ( pos != string::npos ) {
sram_start_st = line.substr(0, pos-3);
sram_start = strtol(sram_start_st.c_str(), NULL, 16);
}
pos = line.find("__ram_image2_text_end__");
if ( pos != string::npos ) {
sram_end_st = line.substr(0, pos-3);
sram_end = strtol(sram_end_st.c_str(), NULL, 16);
}
pos = line.find("__sdram_data_start__");
if ( pos != string::npos ) {
sdram_start_st = line.substr(0, pos-3);
sdram_start = strtol(sdram_start_st.c_str(), NULL, 16);
}
pos = line.find("__sdram_data_end__");
if ( pos != string::npos ) {
sdram_end_st = line.substr(0, pos-3);
sdram_end = strtol(sdram_end_st.c_str(), NULL, 16);
}
}
if (sdram_start > 0 && sdram_end > 0) {
has_sdram = true;
}
cout << "sram " << sram_start_st << " ~ " << sram_end_st << endl;
if (has_sdram) {
cout << "sdram " << sdram_start_st << " ~ " << sdram_end_st << endl;
}
// 5. generate image 2 and image 3
cmdss.clear();
cmdss << path_arm_none_eabi_gcc << "arm-none-eabi-objcopy -j .image2.start.table -j .ram_image2.text -j .ram.data -Obinary ./application.axf ./ram_2.bin";
getline(cmdss, cmd);
cout << cmd << endl;
system(cmd.c_str());
if (has_sdram) {
cmdss.clear();
cmdss << path_arm_none_eabi_gcc << "arm-none-eabi-objcopy -j .image3 -j .sdr_data -Obinary ./application.axf ./sdram.bin";
getline(cmdss, cmd);
cout << cmd << endl;
system(cmd.c_str());
}
// 6. fulfill header
cmdss.clear();
cmdss << "./tools/macosx/pick " << sram_start << " " << sram_end << " ram_2.bin ram_2.p.bin body+reset_offset+sig";
getline(cmdss, cmd);
cout << cmd << endl;
system(cmd.c_str());
cmdss.clear();
cmdss << "./tools/macosx/pick " << sram_start << " " << sram_end << " ram_2.bin ram_2.ns.bin body+reset_offset";
getline(cmdss, cmd);
cout << cmd << endl;
system(cmd.c_str());
if (has_sdram) {
cmdss.clear();
cmdss << "./tools/macosx/pick " << sdram_start << " " << sdram_end << " sdram.bin ram_3.p.bin body+reset_offset";
getline(cmdss, cmd);
cout << cmd << endl;
system(cmd.c_str());
}
// 7. prepare image 1
cmd = "cp bsp/image/ram_1.p.bin ./";
cout << cmd << endl;
system(cmd.c_str());
cmd = "./tools/macosx/padding 44k 0xFF ram_1.p.bin";
cout << cmd << endl;
system(cmd.c_str());
// 8. generate ram_all.bin
if (has_sdram) {
cmd = "cat ram_1.p.bin ram_2.p.bin ram_3.p.bin > ram_all.bin";
cout << cmd << endl;
system(cmd.c_str());
cmd = "cat ram_2.ns.bin ram_3.p.bin > ota.bin";
cout << cmd << endl;
system(cmd.c_str());
} else {
cmd = "cat ram_1.p.bin ram_2.p.bin > ram_all.bin";
cout << cmd << endl;
system(cmd.c_str());
cmd = "cat ram_2.ns.bin > ota.bin";
cout << cmd << endl;
system(cmd.c_str());
}
// 9. add checksum
cmd = "./tools/macosx/checksum ota.bin";
cout << cmd << endl;
system(cmd.c_str());
return 0;
}
|
[
"william_lai@realtek.com"
] |
william_lai@realtek.com
|
bb8402d568064b70e1536b152e54c902578f2699
|
d7c94f4a713aaf0fbb3dbb9b56c9f6945e0479c1
|
/URI Online Judge/uri2309.cpp
|
e78d5b4d834b7ec294a5f7027494c2e143a8f265
|
[] |
no_license
|
fonte-nele/Competitive-Programming
|
2dabb4aab6ce2e6dc552885464fefdd485f9218c
|
faf0c6077ae0115f121968f7b70f4d68f9ce922b
|
refs/heads/master
| 2021-06-28T09:24:07.708562
| 2020-12-27T14:45:15
| 2020-12-27T14:45:15
| 193,268,717
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 870
|
cpp
|
#include <cstdio>
int getValue(int n)
{
switch (n)
{
case 4: return 0;
case 5: return 1;
case 6: return 2;
case 7: return 3;
case 12: return 4;
case 11: return 5;
case 13: return 6;
case 1: return 7;
case 2: return 8;
case 3: return 9;
}
}
bool wins(int a, int b)
{
return getValue(a) >= getValue(b);
}
int main()
{
int n;
scanf("%d", &n);
int a = 0;
int b = 0;
while (n--)
{
int _a = 0;
int _b = 0;
int p, q, r;
int x, y, z;
scanf("%d %d %d %d %d %d", &p, &q, &r, &x, &y, &z);
if (wins(p, x)) _a++; else _b++;
if (wins(q, y)) _a++; else _b++;
if (wins(r, z)) _a++; else _b++;
if (_a > _b) a++;
else b++;
}
printf("%d %d\n", a, b);
return 0;
}
|
[
"felipephontinelly@hotmail.com"
] |
felipephontinelly@hotmail.com
|
bc1fd59320df8de2825bb16f58c4b2428e93270d
|
5e6637b14fa372049196b4fdbea0bd03ef6180cb
|
/oj题目/其他人/李春阳/P1058(S9789).cpp
|
22593aa107f91cdb768df60558a128a8085ee91f
|
[] |
no_license
|
dangfugui/note-C
|
de1d9ad34b7ad5e804f41093a6fade408ac56ef5
|
0cfce2b3f06749312ef22e965bf29f6ed1783f0a
|
refs/heads/master
| 2020-06-23T13:41:00.370822
| 2016-09-10T14:24:26
| 2016-09-10T14:24:26
| 67,228,867
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 606
|
cpp
|
#include"iostream"
using namespace std;
#include"cstring"
int main ()
{
int a,b;
cin>>a>>b;
string x[10002];
string y[1002];
for(int i=0;i<a;i++)
{
cin>>x[i];
}
for(int j=0;j<b;j++)
{
cin>>y[j];
}
for(int k=0;k<b;k++)
{
int q=0;
for(int l=0;l<a;l++)
{
if(y[k]==x[l])
{
cout<<"YES"<<endl;
break;
}
else
q++;
if(q==a)
cout<<"NO"<<endl;
}
}
return 0;
}
|
[
"dangfugui@163.com"
] |
dangfugui@163.com
|
4e3f4b20ee8c0cda628457b83582e40577e02ee7
|
2962f164cecb440ecd905ab9f3cc569c03a01ad5
|
/RtspPlayer/assemblies/sunell/include/MultiTripWireAbility.h
|
107116e9f0e55f2c5bdb42e2db36d19be682d7f6
|
[] |
no_license
|
paxan222/hello-world
|
5ef9bd04a5c4337c1403a04973e2c0c11665bb26
|
c55c60e0f72a04e1e2560dc19c2a6bbd7e8b430f
|
refs/heads/master
| 2020-12-11T21:09:30.200433
| 2017-05-04T08:39:53
| 2017-05-04T08:39:53
| 55,044,669
| 0
| 1
| null | null | null | null |
GB18030
|
C++
| false
| false
| 28,790
|
h
|
#ifndef _MULTITRIPWIREABILITY_H_
#define _MULTITRIPWIREABILITY_H_
#include "SNPlatOS.h"
#include "DomainConst.h"
#include <string>
/**********************************************************************/
//此处用于控制文件编译字节对齐,拷贝时两行注释间内容需一起拷贝,
//结束处的“#ifdef PRAGMA_PACK”部分也要一起拷贝,否则pragma pack入栈出栈不匹配
#if(PRAGMA_PACK_DEFINE != 10000)
# error Not included "SNPlatOS.h".
#endif
#ifdef PRAGMA_PACK
#ifdef WIN32
#pragma pack(push, PRAGMA_PACK_CHAR)
#endif
#ifndef WIN32
#ifndef _PACKED_1_
#define _PACKED_1_ __attribute__((packed, aligned(PRAGMA_PACK_CHAR))) // for gcc
#endif
#else
#ifndef _PACKED_1_
#define _PACKED_1_
#endif
#endif
#else
#ifndef _PACKED_1_
#define _PACKED_1_
#endif
#endif
/**********************************************************************/
class SN_DLL_API MultiTripWireAbility
{
public:
MultiTripWireAbility();
~MultiTripWireAbility();
MultiTripWireAbility& operator=(const MultiTripWireAbility& p_objMultiTripWireAbility);
/***********************************************************************
* 概述:设置提供双绊线(MultiTripWire)功能的智能库的ID
* 输入:
* p_nLibId :智能库ID
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 输入的智能库ID需要跟能力列表的库ID匹配,不然将视为非法的ID,
* 功能无法正常启用。
************************************************************************/
void setLibId(const int p_nLibId);
/***********************************************************************
* 概述:获取提供双绊线(MultiTripWire)功能的智能库的ID
* 输入:
* 无
* 输出:
* 无
* 返回值:
* const int : 当前提供该功能的智能库ID
* 功能正文:
* 返回的库ID是当前设备提供该智能分析功能的库ID
************************************************************************/
const int getLibId() const;
/***********************************************************************
* 概述:设置分析区域能力是否支持
* 输入:
* p_bRegionEnable :是否支持该项能力
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 输入为true : 支持该项能力;
* 输入为false : 不支持该项能力。
************************************************************************/
void setRegionEnable(const bool p_bRegionEnable);
/***********************************************************************
* 概述:获取分析区域能力是否支持
* 输入:
* 无
* 输出:
* 无
* 返回值:
* bool : 如果启用,返回true;
* 如果不启用,返回false。
* 功能正文:
* 无
************************************************************************/
const bool getRegionEnable() const;
/***********************************************************************
* 概述:设置支持的分析区域个数
* 输入:
* p_nEdgeNum :分析区域个数
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setEdgeNum(const int p_nEdgeNum);
/***********************************************************************
* 概述:获取支持的分析区域个数
* 输入:
* 无
* 输出:
* 无
* 返回值:
* int : 支持的分析区域个数
* 功能正文:
* 无
************************************************************************/
const int getEdgeNum() const;
/***********************************************************************
* 概述:设置最多支持的分析区域个数
* 输入:
* p_nMaxRegionNum :最多支持的分析区域个数
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setMaxRegionNum(const int p_nMaxRegionNum);
/***********************************************************************
* 概述:获取最多支持的分析区域个数
* 输入:
* 无
* 输出:
* 无
* 返回值:
* int : 最多支持的分析区域个数
* 功能正文:
* 无
************************************************************************/
const int getMaxRegionNum() const;
/***********************************************************************
* 概述:设置是否获取详细信息的能力是否支持
* 输入:
* p_bDetailGetEnable :是否支持该能力
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 输入true,支持;
* 输入false,不支持。
************************************************************************/
void setDetailGetEnable(const bool p_bDetailGetEnable);
/***********************************************************************
* 概述:获取是否获取详细信息的能力的是否支持
* 输入:
* 无
* 输出:
* 无
* 返回值:
* bool : 如果支持,返回true;
* 如果不支持,返回false。
* 功能正文:
* 无
************************************************************************/
const bool getDetailGetEnable() const;
/***********************************************************************
* 概述:设置双绊线(MultiTripWire)能力是否支持
* 输入:
* p_bEnable :是否支持该项能力
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 输入为true : 支持该项能力;
* 输入为false : 不支持该项能力。
************************************************************************/
void setEnable(const bool p_bEnable);
/***********************************************************************
* 概述:获取双绊线(MultiTripWire)能力是否支持
* 输入:
* 无
* 输出:
* 无
* 返回值:
* bool : 如果支持,返回true;
* 如果不支持,返回false。
* 功能正文:
* 无
************************************************************************/
const bool getEnable() const;
/***********************************************************************
* 概述:设置是否支持目标最大尺寸
* 输入:
* p_bMaxTargetSizeEnable :是否支持
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setMaxTargetSizeEnable(const bool p_bMaxTargetSizeEnable);
/***********************************************************************
* 概述:获取是否支持目标最大尺寸
* 输入:
* 无
* 输出:
* 无
* 返回值:
* bool :返回true,支持;
* 返回false,不支持。
* 功能正文:
* 无
************************************************************************/
const bool getMaxTargetSizeEnable() const;
/***********************************************************************
* 概述:设置目标最大尺寸的最大值
* 输入:
* p_nMaxTargetSizeMax :目标最大尺寸的最大值
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setMaxTargetSizeMax(const int p_nMaxTargetSizeMax);
/***********************************************************************
* 概述:获取目标最大尺寸的最大值
* 输入:
* 无
* 输出:
* 无
* 返回值:
* int :目标最大尺寸的最大值
* 功能正文:
* 无
************************************************************************/
const int getMaxTargetSizeMax() const;
/***********************************************************************
* 概述:设置目标最大尺寸的最小值
* 输入:
* p_nMaxTargetSizeMin :目标最大尺寸的最小值
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setMaxTargetSizeMin(const int p_nMaxTargetSizeMin);
/***********************************************************************
* 概述:获取目标最大尺寸的最小值
* 输入:
* 无
* 输出:
* 无
* 返回值:
* int :目标最大尺寸的最小值
* 功能正文:
* 无
************************************************************************/
const int getMaxTargetSizeMin() const;
/***********************************************************************
* 概述:设置目标最大尺寸的单位
* 输入:
* p_pMaxTargetSizeUnit :目标最大尺寸的单位
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
bool setMaxTargetSizeUnit(const char* p_pMaxTargetSizeUnit);
/***********************************************************************
* 概述:获取目标最大尺寸的单位
* 输入:
* 无
* 输出:
* 无
* 返回值:
* string :目标最大尺寸的单位
* 功能正文:
* 无
************************************************************************/
const char* getMaxTargetSizeUnit() const;
/***********************************************************************
* 概述:设置是否支持目标最小尺寸
* 输入:
* p_bMinTargetSizeEnable :是否支持
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setMinTargetSizeEnable(const bool p_bMinTargetSizeEnable);
/***********************************************************************
* 概述:获取是否支持目标最小尺寸
* 输入:
* 无
* 输出:
* 无
* 返回值:
* bool :返回true,支持;
* 返回false,不支持。
* 功能正文:
* 无
************************************************************************/
const bool getMinTargetSizeEnable() const;
/***********************************************************************
* 概述:设置目标最小尺寸的最大值
* 输入:
* p_nMinTargetSizeMax :目标最小尺寸的最大值
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setMinTargetSizeMax(const int p_nMinTargetSizeMax);
/***********************************************************************
* 概述:获取目标最小尺寸的最大值
* 输入:
* 无
* 输出:
* 无
* 返回值:
* int :目标最小尺寸的最大值
* 功能正文:
* 无
************************************************************************/
const int getMinTargetSizeMax() const;
/***********************************************************************
* 概述:设置目标最小尺寸的最小值
* 输入:
* p_nMinTargetSizeMin :目标最小尺寸的最小值
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setMinTargetSizeMin(const int p_nMinTargetSizeMin);
/***********************************************************************
* 概述:获取目标最小尺寸的最小值
* 输入:
* 无
* 输出:
* 无
* 返回值:
* int :目标最小尺寸的最小值
* 功能正文:
* 无
************************************************************************/
const int getMinTargetSizeMin() const;
/***********************************************************************
* 概述:设置目标最小尺寸的单位
* 输入:
* p_pMinTargetSizeUnit :目标最小尺寸的单位
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
bool setMinTargetSizeUnit(const char* p_pMinTargetSizeUnit);
/***********************************************************************
* 概述:获取目标最小尺寸的单位
* 输入:
* 无
* 输出:
* 无
* 返回值:
* string :目标最小尺寸的单位
* 功能正文:
* 无
************************************************************************/
const char* getMinTargetSizeUnit() const;
/***********************************************************************
* 概述:设置是否限定目标大小的能力的支持与否
* 输入:
* p_bTargetSizeConstrainEnable :是否支持该功能
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setTargetSizeConstrainEnable(const bool p_bTargetSizeConstrainEnable);
/***********************************************************************
* 概述:获取是否限定目标大小的能力的支持与否
* 输入:
* 无
* 输出:
* 无
* 返回值:
* bool : 支持,返回true;
* 不支持,返回false。
* 功能正文:
* 无
************************************************************************/
const bool getTargetSizeConstrainEnable() const;
/***********************************************************************
* 概述:设置限定目标大小的最大值
* 输入:
* p_nTargetSizeConstrainMin :限定目标大小的最大值
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setTargetSizeConstrainMax(const int p_nTargetSizeConstrainMax);
/***********************************************************************
* 概述:获取限定目标大小的最大值
* 输入:
* 无
* 输出:
* 无
* 返回值:
* int : 限定目标大小的最大值
* 功能正文:
* 无
************************************************************************/
const int getTargetSizeConstrainMax() const;
/***********************************************************************
* 概述:设置限定目标大小的最小值
* 输入:
* p_nTargetSizeConstrainMin :限定目标大小的最小值
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setTargetSizeConstrainMin(const int p_nTargetSizeConstrainMin);
/***********************************************************************
* 概述:获取限定目标大小的最小值
* 输入:
* 无
* 输出:
* 无
* 返回值:
* int : 限定目标大小的最小值
* 功能正文:
* 无
************************************************************************/
const int getTargetSizeConstrainMin() const;
/***********************************************************************
* 概述:设置限定目标大小的单位
* 输入:
* p_nTargetSizeConstrainMin :限定目标大小的单位
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
bool setTargetSizeConstrainUnit(const char* p_pTargetSizeConstrainUnit);
/***********************************************************************
* 概述:获取限定目标大小的单位
* 输入:
* 无
* 输出:
* 无
* 返回值:
* string :限定目标大小的单位
* 功能正文:
* 无
************************************************************************/
const char* getTargetSizeConstrainUnit() const;
/***********************************************************************
* 概述:设置限定目标类型的能力的支持与否
* 输入:
* p_bTargetTypeConstrainEnable :是否支持该能力
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 目标类型指人、车等。
* 如果支持,表示只侦测设置的类型(如人、车等)
************************************************************************/
void setTargetTypeConstrainEnable(const bool p_bTargetTypeConstrainEnable);
/***********************************************************************
* 概述:获取是否支持限定目标类型
* 输入:
* 无
* 输出:
* 无
* 返回值:
* bool : 如果支持,返回true;
* 如果不支持,返回false。
* 功能正文:
* 目标类型指人、车等。
************************************************************************/
const bool getTargetTypeConstrainEnable() const;
/***********************************************************************
* 概述:设置目标类型的最大尺寸
* 输入:
* p_nTargetTypeConstrainMin :目标类型的最大尺寸
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 目标类型指人、车等。
************************************************************************/
void setTargetTypeConstrainMax(const int p_nTargetTypeConstrainMax);
/***********************************************************************
* 概述:获取目标类型的最大尺寸
* 输入:
* 无
* 输出:
* 无
* 返回值:
* int : 目标类型的最大尺寸
* 功能正文:
* 目标类型指人、车等。
************************************************************************/
const int getTargetTypeConstrainMax() const;
/***********************************************************************
* 概述:设置目标类型的最小尺寸
* 输入:
* p_nTargetTypeConstrainMin :目标类型的最小尺寸
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 目标类型指人、车等。
************************************************************************/
void setTargetTypeConstrainMin(const int p_nTargetTypeConstrainMin);
/***********************************************************************
* 概述:获取目标类型的最小尺寸
* 输入:
* 无
* 输出:
* 无
* 返回值:
* int : 目标类型的最小尺寸
* 功能正文:
* 目标类型指人、车等。
************************************************************************/
const int getTargetTypeConstrainMin() const;
/***********************************************************************
* 概述:设置目标类型尺寸的单位
* 输入:
* p_pTargetTypeConstrainUnit :目标类型尺寸的单位
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 目标类型指人、车等。
************************************************************************/
bool setTargetTypeConstrainUnit(const char* p_pTargetTypeConstrainUnit);
/***********************************************************************
* 概述:设置目标类型尺寸的单位
* 输入:
* 无
* 输出:
* 无
* 返回值:
* string : 目标类型尺寸的单位
* 功能正文:
* 目标类型指人、车等。
************************************************************************/
const char* getTargetTypeConstrainUnit() const;
/***********************************************************************
* 概述:设置限定类型能力的支持与否
* 输入:
* p_bTargetTypeEnable :是否支持限定类型能力
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 支持限定类型,表示支持限定人、车等类型的能力。
************************************************************************/
void setTargetTypeEnable(const bool p_bTargetTypeEnable);
/***********************************************************************
* 概述:获取限定类型能力的支持与否
* 输入:
* 无
* 输出:
* 无
* 返回值:
* bool : 返回true,支持该能力;
* 返回false,不支持。
* 功能正文:
* 支持限定类型,表示支持限定人、车等类型的能力。
************************************************************************/
const bool getTargetTypeEnable() const;
/***********************************************************************
* 概述:设置限定类型的尺寸的最大值
* 输入:
* p_nTargetTypeMax :限定类型的尺寸的最大值
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 支持限定类型,表示支持限定人、车等类型的能力。
************************************************************************/
void setTargetTypeMax(const int p_nTargetTypeMax);
/***********************************************************************
* 概述:获取限定类型的尺寸的最大值
* 输入:
* 无
* 输出:
* 无
* 返回值:
* int : 限定类型的尺寸的最大值
* 功能正文:
* 支持限定类型,表示支持限定人、车等类型的能力。
************************************************************************/
const int getTargetTypeMax() const;
/***********************************************************************
* 概述:设置限定类型的尺寸的最小值
* 输入:
* p_nTargetTypeMin :限定类型的尺寸的最小值
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 支持限定类型,表示支持限定人、车等类型的能力。
************************************************************************/
void setTargetTypeMin(const int p_nTargetTypeMin);
/***********************************************************************
* 概述:获取限定类型的尺寸的最小值
* 输入:
* 无
* 输出:
* 无
* 返回值:
* int : 限定类型的尺寸的最小值
* 功能正文:
* 支持限定类型,表示支持限定人、车等类型的能力。
************************************************************************/
const int getTargetTypeMin() const;
/***********************************************************************
* 概述:设置限定类型的尺寸的单位
* 输入:
* p_pTargetTypeUnit :限定类型的尺寸的单位
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 支持限定类型,表示支持限定人、车等类型的能力。
************************************************************************/
bool setTargetTypeUnit(const char* p_pTargetTypeUnit);
/***********************************************************************
* 概述:获取限定类型的尺寸的单位
* 输入:
* 无
* 输出:
* 无
* 返回值:
* string : 限定类型的尺寸的单位
* 功能正文:
* 支持限定类型,表示支持限定人、车等类型的能力。
************************************************************************/
const char* getTargetTypeUnit() const;
/***********************************************************************
* 概述:设置是否支持双绊线的时间间隔的功能
* 输入:
* p_bTimeIntervalEnable :是否支持该项功能。
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setTimeIntervalEnable(const bool p_bTimeIntervalEnable);
/***********************************************************************
* 概述:获取是否支持双绊线的时间间隔的功能
* 输入:
* 无
* 输出:
* 无
* 返回值:
* bool : 返回true,支持;
* 返回false,不支持。
* 功能正文:
* 无
************************************************************************/
const bool getTimeIntervalEnable() const;
/***********************************************************************
* 概述:设置双绊线的时间间隔的最小值
* 输入:
* p_nTimeIntervalMin :双绊线的时间间隔的最小值。
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setTimeIntervalMin(const int p_nTimeIntervalMin);
/***********************************************************************
* 概述:获取双绊线的时间间隔的最小值
* 输入:
* 无
* 输出:
* 无
* 返回值:
* int : 双绊线的时间间隔的最小值
* 功能正文:
* 无
************************************************************************/
const int getTimeIntervalMin() const;
/***********************************************************************
* 概述:设置双绊线的时间间隔的最大值
* 输入:
* p_nTimeIntervalMin :双绊线的时间间隔的最大值。
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setTimeIntervalMax(const int p_nTimeIntervalMax);
/***********************************************************************
* 概述:获取双绊线的时间间隔的最大值
* 输入:
* 无
* 输出:
* 无
* 返回值:
* int : 双绊线的时间间隔的最大值
* 功能正文:
* 无
************************************************************************/
const int getTimeIntervalMax() const;
/***********************************************************************
* 概述:设置双绊线的时间间隔的单位
* 输入:
* p_pTimeIntervalUnit :双绊线的时间间隔的单位。
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
bool setTimeIntervalUnit(const char* p_pTimeIntervalUnit);
/***********************************************************************
* 概述:获取双绊线的时间间隔的单位
* 输入:
* 无
* 输出:
* 无
* 返回值:
* string : 双绊线的时间间隔的单位
* 功能正文:
* 无
************************************************************************/
const char* getTimeIntervalUnit() const;
/***********************************************************************
* 概述:设置是否支持双绊线的触发方向设置的功能
* 输入:
* p_bTimeIntervalEnable :是否支持该项功能。
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setTriggerDirectionEnable(const bool p_bTriggerDirectionEnable);
/***********************************************************************
* 概述:获取是否支持双绊线的触发方向设置的功能
* 输入:
* 无
* 输出:
* 无
* 返回值:
* bool : 返回true,支持;
* 返回false,不支持。
* 功能正文:
* 无
************************************************************************/
const bool getTriggerDirectionEnable() const;
private:
int m_nLibId;
bool m_bRegionEnable;
int m_nEdgeNum;
int m_nMaxRegionNum;
bool m_bDetailGetEnable;
bool m_bEnable;
bool m_bMaxTargetSizeEnable;
int m_nMaxTargetSizeMax;
int m_nMaxTargetSizeMin;
bool m_bMinTargetSizeEnable;
int m_nMinTargetSizeMax;
int m_nMinTargetSizeMin;
bool m_bTargetSizeConstrainEnable;
int m_nTargetSizeConstrainMax;
int m_nTargetSizeConstrainMin;
bool m_bTargetTypeConstrainEnable;
int m_nTargetTypeConstrainMax;
int m_nTargetTypeConstrainMin;
bool m_bTargetTypeEnable;
int m_nTargetTypeMax;
int m_nTargetTypeMin;
bool m_bTimeIntervalEnable;
int m_nTimeIntervalMin;
int m_nTimeIntervalMax;
bool m_bTriggerDirectionEnable;
char m_pMaxTargetSizeUnit[CONST_INTELLIGENCE_ANALYSE_UNIT_LEN + 1];
char m_pMinTargetSizeUnit[CONST_INTELLIGENCE_ANALYSE_UNIT_LEN + 1];
char m_pTargetSizeConstrainUnit[CONST_INTELLIGENCE_ANALYSE_UNIT_LEN + 1];
char m_pTargetTypeConstrainUnit[CONST_INTELLIGENCE_ANALYSE_UNIT_LEN + 1];
char m_pTargetTypeUnit[CONST_INTELLIGENCE_ANALYSE_UNIT_LEN + 1];
char m_pTimeIntervalUnit[CONST_INTELLIGENCE_ANALYSE_UNIT_LEN + 1];
}_PACKED_1_;
/**********************************************************************/
#ifdef PRAGMA_PACK
#ifdef WIN32
#pragma pack(pop)
#endif
#endif
/**********************************************************************/
#endif //_MULTITRIPWIREABILITY_H_
|
[
"paxan222@yandex.ru"
] |
paxan222@yandex.ru
|
5c5cd8e873b497912a17077f1049a73930ace82a
|
898c4e7e2c2e4024f7376da729fec0c9aa694e02
|
/C_Algorithm/chapter01/Q18.cpp
|
25d52a990dbf25cb8ddb6510d2ee876c6fd319b8
|
[] |
no_license
|
blue-monkey0/C
|
f847088563947ff305ce01736d85a385b8f1903f
|
8b859b26c0d5f7d68cc01eec18d17579fa4521a9
|
refs/heads/main
| 2023-02-23T16:27:01.242229
| 2021-01-29T00:29:16
| 2021-01-29T00:29:16
| null | 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 402
|
cpp
|
#include <stdio.h>
void nrpira(int n) {
int i, j;
for (i = 1; i <= n; i++) {
for (j = 1; j <= i - 1; j++)
putchar(' ');
for (j = 1; j <= (n - i) * 2 + 1; j++)
printf("%d", i % 10);
putchar('\n');
}
}
int main(void) {
int n;
puts("n단의 숫자 피라미드를 출력하겠습니다.");
do {
printf("몇 단? : "); scanf_s("%d", &n);
} while (n <= 0);
nrpira(n);
return 0;
}
|
[
"geon0599@cu.ac.kr"
] |
geon0599@cu.ac.kr
|
20357a8d46bbc68fc3857cc400c07cb69f883b62
|
fbc4da93b078c320b064f413ee3721a3f24277af
|
/OfficeVol2/OptionDlgModule.cpp
|
72d42a5839251625842b4bb60ddea540ce5a9b5c
|
[] |
no_license
|
wyrover/LazyVol
|
f97f696d12f7f2053a18a81c130afc9f8eee303c
|
925df4b1eb1a2405d570a0b59ec58aeb3c1d3c60
|
refs/heads/master
| 2021-01-20T08:00:16.257356
| 2013-04-24T06:59:35
| 2013-04-24T06:59:35
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 14,927
|
cpp
|
#include "MainHead.h"
#include "OfficeVolModule.h"
#include "OptionDlgModule.h"
OptionDlgModule::OptionDlgModule(HWND parent_hwnd):mParentHwnd(parent_hwnd)
{
}
OptionDlgModule::~OptionDlgModule(void)
{
}
LPCTSTR OptionDlgModule::GetWindowClassName() const
{
return _T("ScanMainForm");
};
void OptionDlgModule::OnFinalMessage(HWND /*hWnd*/)
{
delete this;
};
void OptionDlgModule::Init()
{
CKeyEditUI* tmpEdit = static_cast<CKeyEditUI*>(m_pm.FindControl(_T("OFF_VOLUP")));
assert(tmpEdit);
std::string configStr;
OfficeVolModule::GetInstance()->GetConfigStr("OFF_VOLUP", configStr);
tmpEdit->SetKey(configStr.c_str());
tmpEdit->SetText(configStr.c_str());
mKeyEditVec.push_back(tmpEdit);
tmpEdit = static_cast<CKeyEditUI*>(m_pm.FindControl(_T("OFF_VOLDOWN")));
assert(tmpEdit);
OfficeVolModule::GetInstance()->GetConfigStr("OFF_VOLDOWN", configStr);
tmpEdit->SetKey(configStr.c_str());
tmpEdit->SetText(configStr.c_str());
mKeyEditVec.push_back(tmpEdit);
tmpEdit = static_cast<CKeyEditUI*>(m_pm.FindControl(_T("OFF_VOLON")));
assert(tmpEdit);
OfficeVolModule::GetInstance()->GetConfigStr("OFF_VOLON", configStr);
tmpEdit->SetKey(configStr.c_str());
tmpEdit->SetText(configStr.c_str());
mKeyEditVec.push_back(tmpEdit);
tmpEdit = static_cast<CKeyEditUI*>(m_pm.FindControl(_T("OFF_VOLOFF")));
assert(tmpEdit);
OfficeVolModule::GetInstance()->GetConfigStr("OFF_VOLOFF", configStr);
tmpEdit->SetKey(configStr.c_str());
tmpEdit->SetText(configStr.c_str());
mKeyEditVec.push_back(tmpEdit);
tmpEdit = static_cast<CKeyEditUI*>(m_pm.FindControl(_T("OFF_VOLSELECT_MASTER")));
assert(tmpEdit);
OfficeVolModule::GetInstance()->GetConfigStr("OFF_VOLSELECT_MASTER", configStr);
tmpEdit->SetKey(configStr.c_str());
tmpEdit->SetText(configStr.c_str());
mKeyEditVec.push_back(tmpEdit);
tmpEdit = static_cast<CKeyEditUI*>(m_pm.FindControl(_T("OFF_VOLSELECT_WAVE")));
assert(tmpEdit);
OfficeVolModule::GetInstance()->GetConfigStr("OFF_VOLSELECT_WAVE", configStr);
tmpEdit->SetKey(configStr.c_str());
tmpEdit->SetText(configStr.c_str());
mKeyEditVec.push_back(tmpEdit);
tmpEdit = static_cast<CKeyEditUI*>(m_pm.FindControl(_T("OFF_VOLSELECT_MIC")));
assert(tmpEdit);
OfficeVolModule::GetInstance()->GetConfigStr("OFF_VOLSELECT_MIC", configStr);
tmpEdit->SetKey(configStr.c_str());
tmpEdit->SetText(configStr.c_str());
mKeyEditVec.push_back(tmpEdit);
tmpEdit = static_cast<CKeyEditUI*>(m_pm.FindControl(_T("OFF_OPTION")));
assert(tmpEdit);
OfficeVolModule::GetInstance()->GetConfigStr("OFF_OPTION", configStr);
tmpEdit->SetKey(configStr.c_str());
tmpEdit->SetText(configStr.c_str());
mKeyEditVec.push_back(tmpEdit);
tmpEdit = static_cast<CKeyEditUI*>(m_pm.FindControl(_T("OFF_QUIT")));
assert(tmpEdit);
OfficeVolModule::GetInstance()->GetConfigStr("OFF_QUIT", configStr);
tmpEdit->SetKey(configStr.c_str());
tmpEdit->SetText(configStr.c_str());
mKeyEditVec.push_back(tmpEdit);
mWinStartOpt = static_cast<COptionUI*>(m_pm.FindControl(_T("OFF_WINSTART")));
assert(mWinStartOpt);
OfficeVolModule::GetInstance()->GetConfigStr("OFF_WINSTART", configStr);
if(configStr == "ON")
{
mWinStartOpt->Selected(true);
}
else
{
mWinStartOpt->Selected(false);
}
}
void OptionDlgModule::Notify(TNotifyUI& msg)
{
if(msg.sType == _T("click"))
{
if( msg.pSender->GetName() == _T("cancelbtn") ||
msg.pSender->GetName() == _T("exitbtn"))
{
Close();
return;
}
if( msg.pSender->GetName() == _T("okBtn") )
{
UpdateConfig();
Close();
return;
}
if( msg.pSender->GetName() == _T("applyBtn") )
{
UpdateConfig();
return;
}
}
else if (_tcsicmp(msg.sType, _T("selectchanged")) == 0)
{
CTabLayoutUI* pTabControl = static_cast<CTabLayoutUI*>(m_pm.FindControl(kMainTabCtrl));
CTabLayoutUI* pGTabControl = static_cast<CTabLayoutUI*>(m_pm.FindControl(kGeneralTableCtrl));
if (_tcsicmp(msg.pSender->GetName(), kTabGeneral) == 0)
{
if (pTabControl && pTabControl->GetCurSel() != 0)
{
pTabControl->SelectItem(0);
}
}
else if (_tcsicmp(msg.pSender->GetName(), kTabAbout) == 0)
{
if (pTabControl && pTabControl->GetCurSel() != 1)
{
pTabControl->SelectItem(1);
}
}
else if (_tcsicmp(msg.pSender->GetName(), kGTabKeyboard) == 0)
{
if (pGTabControl && pGTabControl->GetCurSel() != 0)
{
pGTabControl->SelectItem(0);
}
}
else if (_tcsicmp(msg.pSender->GetName(), kGTabCommon) == 0)
{
if (pGTabControl && pGTabControl->GetCurSel() != 1)
{
pGTabControl->SelectItem(1);
}
}
}
}
LRESULT OptionDlgModule::OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
//LONG styleValue = ::GetWindowLong(*this, GWL_STYLE);
//styleValue &= ~WS_CAPTION;
//::SetWindowLong(*this, GWL_STYLE, styleValue | WS_CLIPSIBLINGS | WS_CLIPCHILDREN);
m_pm.Init(m_hWnd);
//m_pm.SetTransparent(100);
CDialogBuilder builder;
CControlUI* pRoot = builder.Create(_T("OpSkin.xml"), (UINT)0, this, &m_pm);
ASSERT(pRoot && "Failed to parse XML");
m_pm.AttachDialog(pRoot);
m_pm.AddNotifier(this);
Init();
return 0;
}
LRESULT OptionDlgModule::OnClose(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
bHandled = FALSE;
return 0;
}
LRESULT OptionDlgModule::OnDestroy(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
if(mParentHwnd)
::PostMessage(mParentHwnd, MSG_DISMISS_OPTION, wParam, lParam);
bHandled = FALSE;
return 0;
}
LRESULT OptionDlgModule::OnNcActivate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
if( ::IsIconic(*this) ) bHandled = FALSE;
return (wParam == 0) ? TRUE : FALSE;
}
LRESULT OptionDlgModule::OnNcCalcSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
return 0;
}
LRESULT OptionDlgModule::OnNcPaint(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
return 0;
}
LRESULT OptionDlgModule::OnNcHitTest(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
#if 1
POINT pt; pt.x = GET_X_LPARAM(lParam); pt.y = GET_Y_LPARAM(lParam);
::ScreenToClient(*this, &pt);
RECT rcClient;
::GetClientRect(*this, &rcClient);
if( !::IsZoomed(*this) ) {
RECT rcSizeBox = m_pm.GetSizeBox();
if( pt.y < rcClient.top + rcSizeBox.top ) {
if( pt.x < rcClient.left + rcSizeBox.left ) return HTTOPLEFT;
if( pt.x > rcClient.right - rcSizeBox.right ) return HTTOPRIGHT;
return HTTOP;
}
else if( pt.y > rcClient.bottom - rcSizeBox.bottom ) {
if( pt.x < rcClient.left + rcSizeBox.left ) return HTBOTTOMLEFT;
if( pt.x > rcClient.right - rcSizeBox.right ) return HTBOTTOMRIGHT;
return HTBOTTOM;
}
if( pt.x < rcClient.left + rcSizeBox.left ) return HTLEFT;
if( pt.x > rcClient.right - rcSizeBox.right ) return HTRIGHT;
}
RECT rcCaption = m_pm.GetCaptionRect();
if( pt.x >= rcClient.left + rcCaption.left && pt.x < rcClient.right - rcCaption.right \
&& pt.y >= rcCaption.top && pt.y < rcCaption.bottom ) {
CControlUI* pControl = static_cast<CControlUI*>(m_pm.FindControl(pt));
if( pControl && _tcscmp(pControl->GetClass(), _T("ButtonUI")) != 0 &&
_tcscmp(pControl->GetClass(), _T("OptionUI")) != 0 &&
_tcscmp(pControl->GetClass(), _T("TextUI")) != 0 )
return HTCAPTION;
}
#endif
return HTCLIENT;
}
LRESULT OptionDlgModule::OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
SIZE szRoundCorner = m_pm.GetRoundCorner();
if( !::IsIconic(*this) && (szRoundCorner.cx != 0 || szRoundCorner.cy != 0) ) {
CDuiRect rcWnd;
::GetWindowRect(*this, &rcWnd);
rcWnd.Offset(-rcWnd.left, -rcWnd.top);
rcWnd.right++; rcWnd.bottom++;
RECT rc = { rcWnd.left, rcWnd.top + szRoundCorner.cx, rcWnd.right, rcWnd.bottom };
HRGN hRgn1 = ::CreateRectRgnIndirect( &rc );
HRGN hRgn2 = ::CreateRoundRectRgn(rcWnd.left, rcWnd.top, rcWnd.right, rcWnd.bottom - szRoundCorner.cx, szRoundCorner.cx, szRoundCorner.cy);
::CombineRgn( hRgn1, hRgn1, hRgn2, RGN_OR );
::SetWindowRgn(*this, hRgn1, TRUE);
::DeleteObject(hRgn1);
::DeleteObject(hRgn2);
}
bHandled = FALSE;
return 0;
}
LRESULT OptionDlgModule::OnMove(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
RECT rcWnd = { 0 };
::GetWindowRect(m_hWnd, &rcWnd );
::SetWindowPos(m_hWnd, HWND_TOPMOST, rcWnd.left, rcWnd.top, rcWnd.right -rcWnd.left,
rcWnd.bottom -rcWnd.top, SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER);
bHandled = FALSE;
return 0;
}
LRESULT OptionDlgModule::OnGetMinMaxInfo(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
#if 0
MONITORINFO oMonitor = {};
oMonitor.cbSize = sizeof(oMonitor);
::GetMonitorInfo(::MonitorFromWindow(*this, MONITOR_DEFAULTTOPRIMARY), &oMonitor);
CDuiRect rcWork = oMonitor.rcWork;
rcWork.Offset(-oMonitor.rcMonitor.left, -oMonitor.rcMonitor.top);
LPMINMAXINFO lpMMI = (LPMINMAXINFO) lParam;
lpMMI->ptMaxPosition.x = rcWork.left;
lpMMI->ptMaxPosition.y = rcWork.top;
lpMMI->ptMaxSize.x = rcWork.right;
lpMMI->ptMaxSize.y = rcWork.bottom;
bHandled = FALSE;
#endif
return 0;
}
LRESULT OptionDlgModule::OnSysCommand(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
#if 0
// 有时会在收到WM_NCDESTROY后收到wParam为SC_CLOSE的WM_SYSCOMMAND
if( wParam == SC_CLOSE ) {
::PostQuitMessage(0L);
bHandled = TRUE;
return 0;
}
BOOL bZoomed = ::IsZoomed(*this);
LRESULT lRes = CWindowWnd::HandleMessage(uMsg, wParam, lParam);
if( ::IsZoomed(*this) != bZoomed ) {
if( !bZoomed ) {
CControlUI* pControl = static_cast<CControlUI*>(m_pm.FindControl(_T("maxbtn")));
if( pControl ) pControl->SetVisible(false);
pControl = static_cast<CControlUI*>(m_pm.FindControl(_T("restorebtn")));
if( pControl ) pControl->SetVisible(true);
}
else {
CControlUI* pControl = static_cast<CControlUI*>(m_pm.FindControl(_T("maxbtn")));
if( pControl ) pControl->SetVisible(true);
pControl = static_cast<CControlUI*>(m_pm.FindControl(_T("restorebtn")));
if( pControl ) pControl->SetVisible(false);
}
}
return lRes;
#endif
return 0;
}
LRESULT OptionDlgModule::HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
LRESULT lRes = 0;
BOOL bHandled = TRUE;
switch( uMsg ) {
case WM_MOVE:
Off_DegMsg("sdfsdfddddddddd");
break;
case WM_CREATE: lRes = OnCreate(uMsg, wParam, lParam, bHandled); break;
case WM_CLOSE: lRes = OnClose(uMsg, wParam, lParam, bHandled); break;
case WM_DESTROY: lRes = OnDestroy(uMsg, wParam, lParam, bHandled); break;
//case WM_NCACTIVATE: lRes = OnNcActivate(uMsg, wParam, lParam, bHandled); break;
//case WM_NCCALCSIZE: lRes = OnNcCalcSize(uMsg, wParam, lParam, bHandled); break;
//case WM_NCPAINT: lRes = OnNcPaint(uMsg, wParam, lParam, bHandled); break;
//case WM_NCHITTEST: lRes = OnNcHitTest(uMsg, wParam, lParam, bHandled); break;
case WM_SIZE: lRes = OnSize(uMsg, wParam, lParam, bHandled); break;
//case WM_MOVE: lRes = OnMove(uMsg, wParam, lParam, bHandled); break;
//case WM_GETMINMAXINFO: lRes = OnGetMinMaxInfo(uMsg, wParam, lParam, bHandled); break;
case WM_SYSCOMMAND: lRes = OnSysCommand(uMsg, wParam, lParam, bHandled); break;
default:
bHandled = FALSE;
}
if( bHandled ) return lRes;
if( m_pm.MessageHandler(uMsg, wParam, lParam, lRes) ) return lRes;
return CWindowWnd::HandleMessage(uMsg, wParam, lParam);
}
CControlUI* OptionDlgModule::CreateControl(LPCTSTR pstrClass)
{
std::string strname(pstrClass);
if(strname == "KEdit")
return new CKeyEditUI;
return NULL;
}
LRESULT OptionDlgModule::UpdateConfig()
{
std::vector<CKeyEditUI*>::iterator iter;
LRESULT ret = 0;
std::string old_config;
for(iter=mKeyEditVec.begin(); iter != mKeyEditVec.end(); ++iter)
{
CKeyEditUI* tmpCtrl = *iter;
assert(tmpCtrl);
ret = OfficeVolModule::GetInstance()->GetConfigStr((LPCTSTR)tmpCtrl->GetName(), old_config);
if(ret)
{
char str[1024] = {0};
_snprintf(str, 1024, "获取配置错误 %s", (LPCTSTR)tmpCtrl->GetName());
Off_Msg(str);
}
if(old_config != tmpCtrl->GetKey())
{
ret = OfficeVolModule::GetInstance()->SetConfigStr(OFF_KEY_UPDATE,
(LPCTSTR)tmpCtrl->GetName(),
tmpCtrl->GetKey());
if(ret)
{
char str[1024] = {0};
_snprintf(str, 1024, "配置错误 %s:%s", (LPCTSTR)tmpCtrl->GetName(),
tmpCtrl->GetKey().c_str());
Off_Msg(str);
}
}
}
ret = OfficeVolModule::GetInstance()->GetConfigStr((LPCTSTR)mWinStartOpt->GetName(), old_config);
if(ret)
{
char str[1024] = {0};
_snprintf(str, 1024, "获取配置错误 %s", (LPCTSTR)mWinStartOpt->GetName());
Off_Msg(str);
ReadConfig();
return OFF_ERROR;
}
if(old_config == "OFF" && mWinStartOpt->IsSelected())
{
ret = OfficeVolModule::GetInstance()->SetConfigStr(OFF_WIN_START,
(LPCTSTR)mWinStartOpt->GetName(),
"ON");
if(ret)
{
char str[1024] = {0};
_snprintf(str, 1024, "配置错误 %s:%s", (LPCTSTR)mWinStartOpt->GetName(),
"ON");
Off_Msg(str);
}
}
else if(old_config == "ON" && !mWinStartOpt->IsSelected())
{
ret = OfficeVolModule::GetInstance()->SetConfigStr(OFF_WIN_START,
(LPCTSTR)mWinStartOpt->GetName(),
"OFF");
if(ret)
{
char str[1024] = {0};
_snprintf(str, 1024, "配置错误 %s:%s", (LPCTSTR)mWinStartOpt->GetName(),
"OFF");
Off_Msg(str);
}
}
ReadConfig();
return 0;
}
LRESULT OptionDlgModule::ReadConfig()
{
std::vector<CKeyEditUI*>::iterator iter;
LRESULT ret = 0;
std::string configStr;
for(iter=mKeyEditVec.begin(); iter != mKeyEditVec.end(); ++iter)
{
CKeyEditUI* tmpCtrl = *iter;
assert(tmpCtrl);
ret = OfficeVolModule::GetInstance()->GetConfigStr((LPCTSTR)tmpCtrl->GetName(), configStr);
if(ret)
{
char str[1024] = {0};
_snprintf(str, 1024, "获取配置错误 %s", (LPCTSTR)tmpCtrl->GetName());
Off_Msg(str);
}
tmpCtrl->SetKey(configStr.c_str());
tmpCtrl->SetText(configStr.c_str());
}
return 0;
}
|
[
"guolisen@163.com"
] |
guolisen@163.com
|
8023c3c92b9261ac91719046e7ff43d1c456bd8c
|
ea401c3e792a50364fe11f7cea0f35f99e8f4bde
|
/hackathon/hanchuan/sscope/FlyCapture2/src/FlyCapture2GUI/Format7DrawingArea.cpp
|
96b0a471f48323af694a71c83e972ababdde511d
|
[
"MIT"
] |
permissive
|
Vaa3D/vaa3d_tools
|
edb696aa3b9b59acaf83d6d27c6ae0a14bf75fe9
|
e6974d5223ae70474efaa85e1253f5df1814fae8
|
refs/heads/master
| 2023-08-03T06:12:01.013752
| 2023-08-02T07:26:01
| 2023-08-02T07:26:01
| 50,527,925
| 107
| 86
|
MIT
| 2023-05-22T23:43:48
| 2016-01-27T18:19:17
|
C++
|
WINDOWS-1252
|
C++
| false
| false
| 18,920
|
cpp
|
//=============================================================================
// Copyright © 2008 Point Grey Research, Inc. All Rights Reserved.
//
// This software is the confidential and proprietary information of Point
// Grey Research, Inc. ("Confidential Information"). You shall not
// disclose such Confidential Information and shall use it only in
// accordance with the terms of the license agreement you entered into
// with PGR.
//
// PGR MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
// SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE, OR NON-INFRINGEMENT. PGR SHALL NOT BE LIABLE FOR ANY DAMAGES
// SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
// THIS SOFTWARE OR ITS DERIVATIVES.
//=============================================================================
//=============================================================================
// $Id: Format7DrawingArea.cpp,v 1.27 2010/08/05 22:16:18 soowei Exp $
//=============================================================================
#include "Precompiled.h"
#include "Format7DrawingArea.h"
#include <vector>
namespace FlyCapture2
{
Format7DrawingArea::Format7DrawingArea( BaseObjectType* cobject, const Glib::RefPtr<Gnome::Glade::Xml>& /*refGlade*/ )
: Gtk::DrawingArea(cobject),
m_moveCursor( Gdk::FLEUR )
{
Gdk::EventMask mask =
Gdk::BUTTON_PRESS_MASK |
Gdk::BUTTON_RELEASE_MASK |
Gdk::BUTTON1_MOTION_MASK |
Gdk::POINTER_MOTION_MASK;
set_events( mask );
m_leftMBHeld = false;
m_rightMBHeld = false;
m_left = 0;
m_top = 0;
m_width = 0;
m_height = 0;
m_lastFiredLeft = 0;
m_lastFiredTop = 0;
m_lastFiredWidth = 0;
m_lastFiredHeight = 0;
m_maxWidth = 0;
m_maxHeight = 0;
m_offsetHStepSize = 0;
m_offsetVStepSize = 0;
m_imageHStepSize = 0;
m_imageVStepSize = 0;
m_startX = 0;
m_startY = 0;
m_offsetX = 0;
m_offsetY = 0;
m_currX = 0;
m_currY = 0;
m_imageSizeChanged = false;
}
Format7DrawingArea::~Format7DrawingArea()
{
}
sigc::signal<void, unsigned int, unsigned int, unsigned int, unsigned int> Format7DrawingArea::signal_image_size_changed()
{
return m_signal_image_size_changed;
}
bool Format7DrawingArea::on_expose_event( GdkEventExpose* event )
{
Glib::RefPtr<Gdk::Window> window = get_window();
if( window == NULL)
{
return true;
}
Cairo::RefPtr<Cairo::Context> refCairo = window->create_cairo_context();
// clip to the area indicated by the expose event so that we only redraw
// the portion of the window that needs to be redrawn
refCairo->rectangle(
event->area.x,
event->area.y,
event->area.width,
event->area.height);
refCairo->clip();
// Get width / height of widget
int width;
int height;
window->get_size( width, height );
// Figure out which scale to use (horizontal or vertical)
const float horzScale = m_maxWidth / (float)width;
const float vertScale = m_maxHeight / (float)height;
m_previewScale = (horzScale < vertScale) ? vertScale : horzScale;
Gtk::AspectFrame* pFrame = (Gtk::AspectFrame*)get_parent();
float fRatio = m_maxWidth / (float)m_maxHeight;
if ( fRatio != pFrame->property_ratio())
{
pFrame->set( 0.0, 0.0, fRatio, false );
}
unsigned int scaledLeft = static_cast<unsigned int>(ToScaled( m_left ));
unsigned int scaledTop = static_cast<unsigned int>(ToScaled( m_top ));
unsigned int scaledWidth = static_cast<unsigned int>(ToScaled( m_width ));
unsigned int scaledHeight = static_cast<unsigned int>(ToScaled( m_height ));
// Fill the background with the PGR color
FillBackground(
refCairo,
event->area.x,
event->area.y,
event->area.width,
event->area.height);
// Draw the data on top of the filled background
DrawRectangle( refCairo, scaledLeft, scaledTop, scaledWidth, scaledHeight );
DrawDashedLines( refCairo, scaledLeft, scaledTop, scaledWidth, scaledHeight );
DrawImageDimensionsText( refCairo, m_left, m_top, m_width, m_height );
DrawCurrentCursorPositionText( refCairo, m_currX, m_currY );
if ( m_imageSizeChanged == true )
{
if ( m_left != m_lastFiredLeft ||
m_top != m_lastFiredTop ||
m_width != m_lastFiredWidth ||
m_height != m_lastFiredHeight )
{
m_signal_image_size_changed( m_left, m_top, m_width, m_height );
m_lastFiredLeft = m_left;
m_lastFiredTop = m_top;
m_lastFiredWidth = m_width;
m_lastFiredHeight = m_height;
}
m_imageSizeChanged = false;
}
return true;
}
void Format7DrawingArea::FillBackground(
Cairo::RefPtr<Cairo::Context> refCairo,
unsigned int left, unsigned int top, unsigned int width, unsigned int height )
{
refCairo->save();
refCairo->rectangle(
left,
top,
width,
height );
const double divisor = 255.0;
const double red = 157.0 / divisor;
const double green = 184.0 / divisor;
const double blue = 210.0 / divisor;
refCairo->set_source_rgb( red, green, blue );
refCairo->fill();
refCairo->restore();
}
void Format7DrawingArea::DrawRectangle(
Cairo::RefPtr<Cairo::Context> refCairo,
unsigned int left, unsigned int top, unsigned int width, unsigned int height )
{
refCairo->save();
// Set draw color
refCairo->set_source_rgb(1.0, 0.0, 0.0);
// Set line width
refCairo->set_line_width(1.0);
// Draw the image rectangle
refCairo->rectangle(
left,
top,
width,
height );
refCairo->stroke();
refCairo->restore();
}
void Format7DrawingArea::DrawDashedLines(
Cairo::RefPtr<Cairo::Context> refCairo,
unsigned int left, unsigned int top, unsigned int width, unsigned int height )
{
refCairo->save();
// Get width / height of widget
int windowWidth;
int windowHeight;
get_window()->get_size( windowWidth, windowHeight );
// Set the dash parameters
std::vector<double> dash_vector(2);
dash_vector[0] = 4.0;
dash_vector[1] = 2.0;
refCairo->set_dash( dash_vector, 0.0 );
// Set draw color
refCairo->set_source_rgb(0.0, 0.0, 0.0);
// Set line width
refCairo->set_line_width(1.0);
refCairo->move_to( left, top );
refCairo->line_to( left, 0 );
refCairo->move_to( left, top );
refCairo->line_to( 0, top );
refCairo->move_to( left + width, top + height );
refCairo->line_to( left + width, windowHeight );
refCairo->move_to( left + width, top + height );
refCairo->line_to( windowWidth, top + height );
refCairo->stroke();
refCairo->restore();
}
void Format7DrawingArea::DrawImageDimensionsText(
Cairo::RefPtr<Cairo::Context> refCairo,
unsigned int left, unsigned int top, unsigned int width, unsigned int height )
{
refCairo->save();
// Set the font parameters
refCairo->select_font_face(
"monospace",
Cairo::FONT_SLANT_NORMAL,
Cairo::FONT_WEIGHT_BOLD );
refCairo->set_font_size( 10 );
// Set draw color to black
refCairo->set_source_rgb(0.0, 0.0, 0.0);
// Get width / height of widget
int widgetWidth = 0;
int widgetHeight = 0;
get_window()->get_size( widgetWidth, widgetHeight );
// Create text for image offset
char imageOffsets[128];
sprintf(
imageOffsets,
"Start: (%d,%d) End: (%d,%d)",
left,
top,
left + width,
top + height );
Cairo::TextExtents offsetExtents;
refCairo->get_text_extents(imageOffsets, offsetExtents);
// Draw the offset text
refCairo->move_to(
(widgetWidth/2) - (offsetExtents.width/2),
(widgetHeight/2) - offsetExtents.height - (offsetExtents.height/2));
refCairo->show_text( imageOffsets );
// Create text for image dimensions
char imageDimensions[128];
sprintf(
imageDimensions,
"Dimensions: %d x %d",
width,
height);
Cairo::TextExtents dimensionsExtents;
refCairo->get_text_extents(imageDimensions, dimensionsExtents);
// Draw the dimensions text
refCairo->move_to(
(widgetWidth/2) - (dimensionsExtents.width/2),
(widgetHeight/2) + dimensionsExtents.height + (dimensionsExtents.height/2));
refCairo->show_text( imageDimensions );
refCairo->restore();
}
void Format7DrawingArea::DrawCurrentCursorPositionText(
Cairo::RefPtr<Cairo::Context> refCairo,
unsigned int currX, unsigned int currY )
{
refCairo->save();
// Set the font parameters
refCairo->select_font_face(
"monospace",
Cairo::FONT_SLANT_NORMAL,
Cairo::FONT_WEIGHT_BOLD );
refCairo->set_font_size( 10 );
// Set draw color to black
refCairo->set_source_rgb(0.0, 0.0, 0.0);
// Print current cursor position
char cursorPosition[128];
sprintf(
cursorPosition,
"Cursor: (%d, %d)",
currX,
currY );
// Get width / height of widget
int width;
int height;
get_window()->get_size( width, height );
Cairo::TextExtents textExtents;
refCairo->get_text_extents( cursorPosition, textExtents );
refCairo->move_to( (width / 2) - (textExtents.width / 2), (height * 0.9) - (textExtents.height / 2) );
refCairo->show_text( cursorPosition );
refCairo->restore();
}
bool Format7DrawingArea::on_button_press_event( GdkEventButton* event )
{
gdouble startX = event->x;
gdouble startY = event->y;
ClipPoint( &startX, &startY );
unsigned int startXOrig = ToOriginal( (float)startX );
unsigned int startYOrig = ToOriginal( (float)startY );
switch ( event->button )
{
case 1:
// Store the start point
m_startX = startXOrig;
m_startY = startYOrig;
m_leftMBHeld = true;
break;
case 3:
get_window()->set_cursor( m_moveCursor );
// Store the difference between the start point and the left/top
m_offsetX = m_left - startXOrig;
m_offsetY = m_top - startYOrig;
m_rightMBHeld = true;
break;
}
return true;
}
bool Format7DrawingArea::on_button_release_event( GdkEventButton* event )
{
gdouble endX = event->x;
gdouble endY = event->y;
ClipPoint( &endX, &endY );
const unsigned int endXOrig = ToOriginal( (float)endX );
const unsigned int endYOrig = ToOriginal( (float)endY );
switch ( event->button )
{
case 1:
m_left = std::min(m_startX, endXOrig);
m_top = std::min(m_startY, endYOrig);
m_width = std::max(m_startX, endXOrig) - m_left;
m_height = std::max(m_startY, endYOrig) - m_top;
ClampAllValues();
m_imageSizeChanged = true;
m_leftMBHeld = false;
break;
case 3:
get_window()->set_cursor();
m_rightMBHeld = false;
break;
}
queue_draw();
return true;
}
bool Format7DrawingArea::on_motion_notify_event( GdkEventMotion* event )
{
gdouble currX = event->x;
gdouble currY = event->y;
// This may actually be negative if the mouse is dragged to the
// left or top of the image, so ints should be used instead of
// unsigned ints to prevent overflow
int currXOrig = 0;
int currYOrig = 0;
if ( m_leftMBHeld == true )
{
ClipPoint( &currX, &currY );
currXOrig = ToOriginal( static_cast<float>(currX) );
currYOrig = ToOriginal( static_cast<float>(currY) );
if ( currXOrig <= static_cast<int>(m_startX) )
{
m_left = currXOrig;
m_width = m_startX - m_left;
}
else
{
m_left = m_startX;
m_width = currXOrig - m_left;
}
if ( currYOrig <= static_cast<int>(m_startY) )
{
m_top = currYOrig;
m_height = m_startY - m_top;
}
else
{
m_top = m_startY;
m_height = currYOrig - m_top;
}
ClampAllValues();
m_imageSizeChanged = true;
}
else if ( m_rightMBHeld == true )
{
currXOrig = ToOriginal( static_cast<float>(currX) );
currYOrig = ToOriginal( static_cast<float>(currY) );
// Perform some initial calculations to make sure that the
// left and top values are not overflowing
if ( currXOrig + m_offsetX < 0 )
{
m_left = 0;
}
else
{
m_left = currXOrig + m_offsetX;
}
if ( currYOrig + m_offsetY < 0 )
{
m_top = 0;
}
else
{
m_top = currYOrig + m_offsetY;
}
ClampAllValues();
// Ensure we are still within the boundaries
if ( m_left + m_width > m_maxWidth )
{
m_left = m_maxWidth - m_width;
}
else if ( m_left + m_width < m_width )
{
m_left = 0;
}
if ( m_top + m_height > m_maxHeight )
{
m_top = m_maxHeight - m_height;
}
else if ( m_top + m_height < m_height )
{
m_top = 0;
}
m_imageSizeChanged = true;
}
else
{
ClipPoint( &currX, &currY );
currXOrig = ToOriginal( static_cast<float>(currX) );
currYOrig = ToOriginal( static_cast<float>(currY) );
}
// Store the current cursor coordinates
m_currX = currXOrig;
m_currY = currYOrig;
queue_draw();
return true;
}
void Format7DrawingArea::UpdateSettings( Format7Info* pFmt7Info, Format7ImageSettings* pImageSettings )
{
// Maximum resolution
m_maxWidth = pFmt7Info->maxWidth;
m_maxHeight = pFmt7Info->maxHeight;
// Step sizes
m_offsetHStepSize = pFmt7Info->offsetHStepSize;
m_offsetVStepSize = pFmt7Info->offsetVStepSize;
m_imageHStepSize = pFmt7Info->imageHStepSize;
m_imageVStepSize = pFmt7Info->imageVStepSize;
m_left = pImageSettings->offsetX;
m_top = pImageSettings->offsetY;
m_width = pImageSettings->width;
m_height = pImageSettings->height;
queue_draw();
}
void Format7DrawingArea::UpdateSettings( GigEImageSettingsInfo* pImageInfo, GigEImageSettings* pImageSettings )
{
// Maximum resolution
m_maxWidth = pImageInfo->maxWidth;
m_maxHeight = pImageInfo->maxHeight;
// Step sizes
m_offsetHStepSize = pImageInfo->offsetHStepSize;
m_offsetVStepSize = pImageInfo->offsetVStepSize;
m_imageHStepSize = pImageInfo->imageHStepSize;
m_imageVStepSize = pImageInfo->imageVStepSize;
m_left = pImageSettings->offsetX;
m_top = pImageSettings->offsetY;
m_width = pImageSettings->width;
m_height = pImageSettings->height;
queue_draw();
}
unsigned int Format7DrawingArea::ClampValue( unsigned int inputVal, unsigned int stepSize )
{
if ( inputVal % stepSize != 0 )
{
return inputVal - (inputVal % stepSize);
}
else
{
return inputVal;
}
}
void Format7DrawingArea::ClampAllValues()
{
m_left = ClampValue( m_left, m_offsetHStepSize );
m_top = ClampValue( m_top, m_offsetVStepSize );
m_width = ClampValue( m_width, m_imageHStepSize );
m_height = ClampValue( m_height, m_imageVStepSize );
}
void Format7DrawingArea::ClipPoint( gdouble* x, gdouble* y )
{
// Get window size
int width;
int height;
get_window()->get_size( width, height );
if ( *x < 0 )
{
*x = 0;
}
else if ( *x > width )
{
*x = width;
}
if ( *y < 0 )
{
*y = 0;
}
else if ( *y > height )
{
*y = height;
}
}
float Format7DrawingArea::ToScaled( int original )
{
return original / m_previewScale;
}
int Format7DrawingArea::ToOriginal( float scaled )
{
return static_cast<int>(scaled * m_previewScale);
}
}
|
[
"hanchuan.peng@gmail.com"
] |
hanchuan.peng@gmail.com
|
a8a67ec51302ad45b4f4eb4106a419e95b7cb259
|
220529721e151c6cc088ebecf4d3c19fd4716df3
|
/AtCoder/abc157/C.cpp
|
7f0a5afc11a610f215b9c0373fcd6b498f835b68
|
[
"MIT"
] |
permissive
|
jahid-coder/competitive-programming
|
baa2311796e3ffad3ded4789e43f4f37b95673ef
|
e7878de2445019c916404238180959dc9308ed4a
|
refs/heads/master
| 2023-08-26T10:13:57.816451
| 2021-10-18T04:26:32
| 2021-10-18T04:26:32
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,307
|
cpp
|
/****************************************************
* Template for coding contests *
* Author : Sanjeev Sharma *
* Email : thedevelopersanjeev@gmail.com *
*****************************************************/
#pragma GCC optimize ("O3")
#pragma GCC optimize("Ofast")
#pragma GCC optimize ("unroll-loops")
#pragma GCC optimize("no-stack-protector,fast-math")
#pragma GCC target ("sse4")
#pragma comment(linker, "/stack:200000000")
#include <bits/stdc++.h>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
#define deb(x) cout << #x << " is " << x << "\n";
using namespace std;
using namespace __gnu_pbds;
const double PI = 2 * acos(0.0);
const long long INF = 1e18L + 5;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n, m, s, c;
cin >> n >> m;
vector<int> num(n, -1);
while (m--) {
cin >> s >> c;
if (num[--s] != -1 && num[s] != c || n > 1 && !s && !c) {
cout << -1 << '\n';
return 0;
}
num[s] = c;
}
for (int i = 0; i < n; ++i)
cout << (num[i] == -1 ? (n > 1 && !i) : num[i]);
cout << '\n';
return 0;
}
|
[
"thedevelopersanjeev@gmail.com"
] |
thedevelopersanjeev@gmail.com
|
61b9d2a7d8ec3cc44a705922c59a4a5e05adfe49
|
050b2e7566af61eba7983e2a38a32c34c48b07bb
|
/balancer/service/center/src/handle/server/SyncServiceRsp.cc
|
ee65a35499c3935512e916a4dba2418003760d5a
|
[] |
no_license
|
coolulu/balancer
|
2e4084f57ad57c9613e5bc96f3d550d84360d9be
|
2d214dcefb149ba60622b035e280b2ee7a2958bb
|
refs/heads/master
| 2021-06-26T20:43:30.713616
| 2019-02-13T13:49:20
| 2019-02-13T13:49:20
| 132,157,585
| 1
| 0
| null | 2018-07-22T02:40:28
| 2018-05-04T15:28:11
|
C++
|
UTF-8
|
C++
| false
| false
| 1,214
|
cc
|
#include "SyncServiceRsp.h"
#include "log/Log.h"
SyncServiceRsp::SyncServiceRsp(Proc& proc,
const muduo::net::TcpConnectionPtr& conn,
PacketPtr& packet_ptr,
muduo::Timestamp time)
: _proc(proc),
_conn(conn),
_packet_ptr(packet_ptr),
_time(time)
{
}
SyncServiceRsp::~SyncServiceRsp()
{
}
void SyncServiceRsp::handle(const center::CenterMsg& msg)
{
const center::SyncServiceReq& req = msg.sync_service_req();
B_LOG_INFO << "conf_update_time=" << req.conf_update_time();
std::string conf_json;
unsigned long long update_time = _proc._sc.get_config_derivative().update_time;
if(update_time != req.conf_update_time())
{
conf_json = _proc._sc.map_to_json();
B_LOG_INFO << "update update_time=" << update_time
<< ", conf_json=" << conf_json;
}
else
{
B_LOG_INFO << "not update conf_json";
}
PacketPtr packet_ptr_rsp(new Packet(_packet_ptr->_from_service_id, 0, _packet_ptr->_app_id, _packet_ptr->_app_version, _packet_ptr->_conn_seq_id, _packet_ptr->_msg_seq_id));
CenterStack::SyncServiceRsp(packet_ptr_rsp->_body,
common::SUCCESS,
"",
update_time,
conf_json);
_proc._tcp_server.send_msg(_conn, packet_ptr_rsp);
}
|
[
"757533566@qq.com"
] |
757533566@qq.com
|
cb1eb0501767f445c5a99cafa187d820ac86107c
|
9be246df43e02fba30ee2595c8cec14ac2b355d1
|
/public/inetgraph.h
|
50a5fd4c00f793ee08e615c4e9724d9d2e46509d
|
[] |
no_license
|
Clepoy3/LeakNet
|
6bf4c5d5535b3824a350f32352f457d8be87d609
|
8866efcb9b0bf9290b80f7263e2ce2074302640a
|
refs/heads/master
| 2020-05-30T04:53:22.193725
| 2019-04-12T16:06:26
| 2019-04-12T16:06:26
| 189,544,338
| 18
| 5
| null | 2019-05-31T06:59:39
| 2019-05-31T06:59:39
| null |
UTF-8
|
C++
| false
| false
| 1,602
|
h
|
//======== (C) Copyright 1999, 2000 Valve, L.L.C. All rights reserved. ========
//
// The copyright to the contents herein is the property of Valve, L.L.C.
// The contents may be used and/or copied only with the written permission of
// Valve, L.L.C., or in accordance with the terms and conditions stipulated in
// the agreement/contract under which the contents have been supplied.
//
// Purpose:
//
// $Workfile: $
// $Date: $
//
//-----------------------------------------------------------------------------
// $Log: $
//
// $NoKeywords: $
//=============================================================================
#if !defined( INETGRAPH_H )
#define INETGRAPH_H
#ifdef _WIN32
#pragma once
#endif
class INetGraph
{
public:
virtual int GetOutgoingSequence( void ) = 0;
virtual int GetIncomingSequence( void ) = 0;
virtual int GetUpdateWindowSize( void ) = 0;
virtual int GetUpdateWindowMask( void ) = 0;
virtual bool IsFrameValid( int frame_number ) = 0;
virtual float GetFrameReceivedTime( int frame_number ) = 0;
virtual float GetFrameLatency( int frame_number ) = 0;
virtual int GetFrameBytes( int frame_number, const char *fieldName ) = 0;
virtual void GetAverageDataFlow( float *incoming, float *outgoing ) = 0;
virtual float GetCommandInterpolationAmount( int command_number ) = 0;
virtual bool GetCommandSent( int command_number ) = 0;
virtual int GetCommandSize( int command_number ) = 0;
};
extern INetGraph *netgraph;
#define VNETGRAPH_INTERFACE_VERSION "VNETGRAPH001"
#endif // INETGRAPH_H
|
[
"uavxp29@gmail.com"
] |
uavxp29@gmail.com
|
6f75536e6246c3b93555f011b8d775dc85e1a6ca
|
4fc1e78d401305cb8bf91e58566e29d526a58cfe
|
/Josephus/JosephusUsingLinkedList.cpp
|
1f119929251190dfeaaa8d69d162777101ab9344
|
[] |
no_license
|
peterloos/Cpp_Josephus
|
ab2224a8cdca11d2796119e7e2e82e764498a25a
|
e8f7769ae380d995d05fa136bb32ce0c21c62179
|
refs/heads/master
| 2021-01-20T19:42:29.669315
| 2016-06-14T19:44:30
| 2016-06-14T19:44:30
| 61,150,987
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,519
|
cpp
|
#include <iostream>
using namespace std;
#include "Soldier.h"
#include "Josephus.h"
namespace SolutionUsingLinkedList
{
// c'tor(s), d'tor
Josephus::Josephus()
: m_count(41), m_alive(41), m_lastEliminated(0)
{
m_passby = Josephus::DefaultPassBy;
CreateLinkedList();
}
Josephus::Josephus(int count)
: m_count(count), m_alive(count), m_lastEliminated(0)
{
m_passby = Josephus::DefaultPassBy;
CreateLinkedList();
}
Josephus::~Josephus()
{
Soldier* soldier = m_root;
// delete each single element
do
{
// store current node pointer
Soldier* current = soldier;
// advance to next node
soldier = soldier -> m_next;
// delete 'current' node pointer
delete current;
}
while (soldier != m_root);
}
// public interface
bool Josephus::EliminateNextSoldier()
{
// more than one soldier?
if (m_alive == 1)
return false;
// locate next soldier
for (int i = 0; i < m_passby - 1; i ++)
m_current = m_current -> m_next;
// remove soldier from list
Soldier* node = m_current -> m_next;
m_current -> m_next = node -> m_next;
// take care, if root object is removed
if (m_root == node)
m_root = m_root -> m_next;
m_lastEliminated = node -> m_number;
delete node;
m_alive --;
return true;
}
void Josephus::EliminateAll()
{
while (EliminateNextSoldier())
;
}
// private helper methods
void Josephus::CreateLinkedList()
{
// create first soldier
m_root = new Soldier(1);
m_current = m_root;
for (int i = 1; i < m_count; i ++)
{
Soldier* s = new Soldier(i + 1);
// link previous Soldier with current one
m_current -> m_next = s;
m_current = s;
}
// link last soldier with first one
m_current -> m_next = m_root;
}
// output
ostream& operator<< (ostream& os, const Josephus& j)
{
os << '[';
Soldier* tmp = j.m_root;
do
{
os << *tmp;
if (tmp -> m_next != j.m_root)
os << ',';
tmp = tmp -> m_next;
}
while (tmp != j.m_root);
os << ']';
return os;
}
}
|
[
"peter.loos@gmx.de"
] |
peter.loos@gmx.de
|
7652f2ba92279e36fdf58beeedadbfc28dee8181
|
b77326e5dd7afd7ca08019958c924aee6bcba550
|
/iBeacon/iBeacon.ino
|
00c23bf876b72c7bebfb50fef22f0d468d862d4a
|
[] |
no_license
|
tmatz/bean-experiments
|
950bfe218510214f609140e78cc8640316899993
|
5171b2294ff643d2ed2038b1c49ae348793d8db7
|
refs/heads/master
| 2021-01-17T15:46:56.502055
| 2016-10-10T08:09:40
| 2016-10-10T08:09:40
| 69,889,562
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 212
|
ino
|
void setup() {
Bean.enableConfigSave(false);
Bean.setAdvertisingInterval(1000);
Bean.setBeaconParameters(0xDEAD, 0xBEEF, 0xCAFE);
Bean.setBeaconEnable(true);
}
void loop() {
Bean.sleep(0xFFFFFFFF);
}
|
[
"t.matsuda.1000@gmail.com"
] |
t.matsuda.1000@gmail.com
|
898dcd49d9c180ed6870b8798b7d8230765e71e9
|
42e6482f57a8d3506987621607b5e9d2719c903e
|
/bo2k/scr/commandloop.cpp
|
059fd317b2eaa3f6a8e3293e9bd28fdce003df58
|
[] |
no_license
|
baiyfcu/BO2K
|
216ce061bea7cd2f5ad01e2eed3fb703adc5a3b4
|
c9df1bf1def0005640ccd879d1a7c720ac237bf2
|
refs/heads/master
| 2020-03-21T19:29:52.886208
| 2018-03-01T16:48:53
| 2018-03-01T16:48:53
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,965
|
cpp
|
/* Back Orifice 2000 - Remote Administration Suite
Copyright (C) 1999, Cult Of The Dead Cow
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
The author of this program may be contacted at dildog@l0pht.com. */
#include<windows.h>
#include<auth.h>
#include<iohandler.h>
#include<encryption.h>
#include<bocomreg.h>
#include<commnet.h>
#include<commandloop.h>
#include<config.h>
// ---------------- Global variables ----------------
CIOHandler *g_pIOHandler;
CEncryptionHandler *g_pEncryptionHandler;
CAuthHandler *g_pAuthHandler;
CAuthSocket *g_pCommSock[MAX_COMMAND_SOCKETS];
CAuthSocket *g_pConnSock[MAX_COMMAND_CONNECTIONS];
int g_nCommCount, g_nConnCount;
#ifdef NDEBUG
char g_szStartupOptions[]= "<**CFG**>Startup\0"
"S[8]:Init Cmd Net Type=TCPIO\0\0\0\0"
"S[48]:Init Cmd Bind Str=\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"S[8]:Init Cmd Encryption=XOR\0\0\0\0\0\0"
"S[8]:Init Cmd Auth=NULLAUTH\0"
"N[0,5000000]:Idle Timeout (ms)=60000\0\0";
#else
char g_szStartupOptions[]= "<**CFG**>Startup\0"
"S[8]:Init Cmd Net Type=TCPIO\0\0\0\0"
"S[48]:Init Cmd Bind Str=54320\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"S[8]:Init Cmd Encryption=XOR\0\0\0\0\0\0"
"S[8]:Init Cmd Auth=NULLAUTH\0"
"N[0,5000000]:Idle Timeout (ms)=60000\0\0";
#endif
BOOL g_bBO2KFinished; // Set this to -TRUE- when you want to exit BO2K
// ---------------- Function implementations --------------------
BOOL StartupCommandHandlers(void)
{
char svParam[256];
// Initialize primary command socket
g_nCommCount=0;
g_nConnCount=0;
svParam[0]='\0';
// Don't even start up unless user has configured a port to talk on.
// This keeps the 31337 phenomena from happening.
char *bindstr=GetCfgStr(g_szStartupOptions,"Init Cmd Bind Str");
if(bindstr==NULL) return FALSE;
if(bindstr[0]=='\0') {
return FALSE;
}
CAuthSocket *cas;
do {
cas=ListenAuthSocket(NULL,0,NULL,
bindstr,
GetCfgStr(g_szStartupOptions,"Init Cmd Net Type"),
GetCfgStr(g_szStartupOptions,"Init Cmd Encryption"),
GetCfgStr(g_szStartupOptions,"Init Cmd Auth"));
if(cas!=NULL && cas!=(CAuthSocket *)0xFFFFFFFF) {
g_pCommSock[g_nCommCount]=cas;
g_nCommCount++;
return TRUE;
}
Sleep(100);
} while(cas!=NULL && cas!=(CAuthSocket *)0xFFFFFFFF);
return FALSE;
}
void ShutdownCommandHandlers(void)
{
int i;
// Close all connections
for(i=0;i<g_nConnCount;i++) {
g_pConnSock[i]->Close();
delete g_pConnSock[i];
}
// Terminate all bound sockets
for(i=0;i<g_nCommCount;i++) {
g_pCommSock[i]->Close();
delete g_pCommSock[i];
}
}
void CommandHandlerLoop(void)
{
BYTE *buffer;
int buflen,ret,i,j;
DWORD dwLastTime,dwTimeout;
BOOL bIdle;
// Start the command handlers
if(StartupCommandHandlers()==FALSE) return;
// Lower Thread Priority
SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_NORMAL);
// Command handler loop
g_bBO2KFinished=FALSE;
dwLastTime=GetTickCount();
dwTimeout=GetCfgNum(g_szStartupOptions,"Idle Timeout (ms)");
bIdle=FALSE;
while(!g_bBO2KFinished) {
if(dwTimeout!=0) {
if(!bIdle && ((GetTickCount()-dwLastTime)>dwTimeout)) {
SetPriorityClass(GetCurrentProcess(),IDLE_PRIORITY_CLASS);
SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_IDLE);
bIdle=TRUE;
}
}
// Sift through bound sockets looking for connections
for(i=0; i<g_nCommCount; i++) {
CAuthSocket *cas;
cas=g_pCommSock[i]->Accept();
if(cas!=NULL) {
if(g_nConnCount<MAX_COMMAND_CONNECTIONS) {
dwLastTime=GetTickCount();
if(bIdle) {
SetPriorityClass(GetCurrentProcess(),NORMAL_PRIORITY_CLASS);
SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_NORMAL);
bIdle=FALSE;
}
g_pConnSock[g_nConnCount]=cas;
g_nConnCount++;
} else {
cas->Close();
delete cas;
}
}
}
// Sift through active connections pulling commands
// and removing dead connections
for(i=(g_nConnCount-1);i>=0;i--) {
ret=g_pConnSock[i]->Recv(&buffer,&buflen);
if(ret<0) {
// Must be dead. Kill.
g_pConnSock[i]->Close();
delete g_pConnSock[i];
for(j=i;j<(g_nConnCount-1);j++) {
g_pConnSock[j]=g_pConnSock[j+1];
}
g_pConnSock[j]=NULL;
g_nConnCount--;
}
else if(ret==0) {
// Nothing here, move along
}
else {
dwLastTime=GetTickCount();
if(bIdle) {
SetPriorityClass(GetCurrentProcess(),NORMAL_PRIORITY_CLASS);
SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_LOWEST);
bIdle=FALSE;
}
// Command received
int cmdlen,command,comid,nArg1;
char *svArg2,*svArg3;
BreakDownCommand(buffer, &cmdlen, &command, &comid, &nArg1, &svArg2, &svArg3);
if(cmdlen==buflen) {
DispatchCommand(command, g_pConnSock[i],comid,nArg1,svArg2,svArg3);
}
// Free command memory
g_pConnSock[i]->Free(buffer);
}
}
Sleep(20);
}
// Terminate command handlers
ShutdownCommandHandlers();
}
|
[
"jeremyngalloway@gmail.com"
] |
jeremyngalloway@gmail.com
|
9c10235056bb6e516ead4ea4784b251664b39ca4
|
19ad5c2df2a3950cc5dbe837df2e7be2e1d21081
|
/Warehouse.cpp
|
fac34f11842a7fcd77247e70fe8e97e8d87f5a34
|
[] |
no_license
|
frederik1904/kattis
|
8cd593367b6e4f74c0c3530d643f9c75d6757863
|
a6846c5d7176e904b2e43d7f515c18f5abe7786c
|
refs/heads/master
| 2021-07-15T04:09:44.442471
| 2021-07-03T18:08:04
| 2021-07-03T18:08:04
| 195,087,312
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,635
|
cpp
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct nameValue {
int amount = 0;
string name;
} ;
bool compareName(const nameValue &a, const nameValue &b) {
if (a.amount == b.amount) {
int minLen = a.name.length() < b.name.length() ?
a.name.length() : b.name.length();
for (int i = 0; i < minLen; i++) {
if (a.name.at(i) != b.name.at(i)) {
return a.name.at(i) < b.name.at(i);
}
}
return a.name.length() < b.name.length();
} else {
return a.amount > b.amount;
}
}
int main(int argc, char *argv[]) {
int testCases, products, value;
string str;
cin >> testCases;
for (int j = 0; j < testCases; j++) {
vector<nameValue> names;
cin >> products;
for (int k = 0; k < products; k++) {
cin >> str >> value;
bool found = false;
for (int i = 0; i < names.size(); i++) {
if (names.at(i).name.compare(str) == 0) {
names.at(i).amount += value;
found = true;
break;
}
}
if (!found) {
nameValue n;
n.name = str;
n.amount = value;
names.push_back(n);
}
}
sort(names.begin(), names.end(), compareName);
cout << names.size() << endl;
for (int i = 0; i < names.size(); i++) {
cout << names.at(i).name << " " << names.at(i).amount << endl;
}
}
}
|
[
"Frederik1904@gmail.com"
] |
Frederik1904@gmail.com
|
ce78da355c11b0593d68e2259e3862ddc5809de6
|
5b70406792ce4203c6895a13948e282fb909d1d9
|
/SaveTheGoozesSolution/SaveTheGoozesLib/SaveTheGoozesLib.cpp
|
64d0eeb4a47dc13efc629e90fa997db624da6425
|
[] |
no_license
|
Rivaus/Save-The-Goozes-Game
|
918f673c863f0495bab732cea0d3b76409a70de6
|
faaf4098fb728f46daa3b80fd0fbc120ef64eead
|
refs/heads/master
| 2020-05-30T12:14:31.010619
| 2019-07-02T21:54:27
| 2019-07-02T21:54:27
| 189,728,024
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 836
|
cpp
|
// SaveTheGoozesLib.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include <iostream>
int main()
{
std::cout << "Hello World!\n";
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
|
[
"quentin.tran25@orange.fr"
] |
quentin.tran25@orange.fr
|
dc3c3dbaaa7ce3efd8d3e50bca316d84ccbd7a33
|
3047545349bf224a182b2c33bf1f110aef1ce9b6
|
/Transims60/GridData/Write_Summary.cpp
|
9eed25f328727f3dde90b319e5bf9567f94864f1
|
[] |
no_license
|
qingswu/Transim
|
585afe71d9666557cff53f6683cf54348294954c
|
f182d1639a4db612dd7b43a379a3fa344c2de9ea
|
refs/heads/master
| 2021-01-10T21:04:50.576267
| 2015-04-08T19:07:28
| 2015-04-08T19:07:28
| 35,232,171
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,573
|
cpp
|
//*********************************************************
// Write_Summary.cpp - Write the New Summary File
//*********************************************************
#include "GridData.hpp"
//---------------------------------------------------------
// Write_Summary
//---------------------------------------------------------
void GridData::Write_Summary ()
{
int i, j, count;
Summary_Itr sum_itr;
Range_Array_Itr range_itr;
Dbls_Itr dbls_itr;
Dbl_Itr data_itr;
count = 0;
Show_Message (2, String ("Writing %s -- Record") % summary_file.File_Type ());
Set_Progress ();
for (sum_itr = summary_array.begin (); sum_itr != summary_array.end (); sum_itr++) {
Show_Progress ();
summary_file.Put_Field (0, sum_itr->group);
summary_file.Put_Field (1, sum_itr->field_name);
dbls_itr = sum_itr->data_array.begin ();
for (i=0, range_itr = sum_itr->select_values.begin (); range_itr != sum_itr->select_values.end (); range_itr++, dbls_itr++, i++) {
summary_file.Put_Field (2, range_itr->Low ());
summary_file.Put_Field (3, range_itr->High ());
summary_file.Put_Field (4, sum_itr->grid_counts [i]);
for (j=data_offset, data_itr = dbls_itr->begin (); data_itr != dbls_itr->end (); data_itr++, j++) {
summary_file.Put_Field (j, *data_itr);
}
if (!summary_file.Write ()) {
Error (String ("Writing %s") % summary_file.File_Type ());
}
count++;
}
}
End_Progress ();
summary_file.Close ();
Print (1);
Write (1, "Number of Summary Records Written = ") << count;
}
|
[
"davidroden@7728d46c-9721-0410-b1ea-f014b4b56054"
] |
davidroden@7728d46c-9721-0410-b1ea-f014b4b56054
|
dc877522d25d314a1da9c17db8cffa56a5988df4
|
77ee3feb0f82773760bffd9c287910c5865d5a80
|
/src/GM/TexCUBE.cpp
|
b94bbfc9e85ad5b2fee558ae22eb8dd07b5f894f
|
[] |
no_license
|
cecilietlandersen/OpenGL
|
2fa8caf7dbfeb868c6098e4e88979da7b5ad8002
|
0223782c7241a36af3c9ee0ed6a05ef39b9a5a4d
|
refs/heads/master
| 2021-01-15T22:02:27.021912
| 2012-10-31T12:52:02
| 2012-10-31T12:52:02
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,911
|
cpp
|
#include "TexCUBE.h"
using namespace GM;
TexCUBE::TexCUBE(const TexCUBEParams &tex_params)
: faces_set(6)
{
#ifdef GL_TEXTURE_CUBE_MAP_SEAMLESS
glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
#endif
glGenTextures(1, &handle);
bind();
for(unsigned int i = 0; i < tex_params.params.size(); i++)
{
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X+i,
0, tex_params.params[i].internal_format, tex_params.params[i].w, tex_params.params[i].h,
0, tex_params.params[i].format, tex_params.params[i].type, tex_params.params[i].data);
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
}
TexCUBE::TexCUBE()
: faces_set(0)
{
#ifdef GL_TEXTURE_CUBE_MAP_SEAMLESS
glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
#endif
glGenTextures(1, &handle);
bind();
}
TexCUBE::~TexCUBE()
{
glDeleteTextures(1, &handle);
}
void TexCUBE::setFace(unsigned int side, const T2DTexParams ¶m)
{
glTexImage2D(side,
0, param.internal_format, param.w, param.h,
0, param.format, param.type, param.data);
faces_set++;
}
void TexCUBE::finished()
{
if(faces_set != 6)
return;
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
}
void TexCUBE::bind()
{
glBindTexture(GL_TEXTURE_CUBE_MAP, handle);
}
void TexCUBE::unbind()
{
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
}
|
[
"ann_ht3@hotmail.com"
] |
ann_ht3@hotmail.com
|
3b4e8279d5c5b7ae1ff1af1c32edca63a35d3869
|
c6062b3748f6f4aa8c088a181109cebfa4d99bf3
|
/Bots/BotAIController.h
|
b58a1394e7b71589f27d5f0687aec5ee353b9440
|
[] |
no_license
|
qipa/UE4-RPG-Demo
|
c543c16e0813c29c0d7cb8151dbb88abdd4941ed
|
b0cc148bea228ffcc8c7d368e721a4e1a5239498
|
refs/heads/master
| 2021-05-29T21:08:37.036409
| 2015-11-08T08:41:44
| 2015-11-08T08:41:44
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 427
|
h
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "AIController.h"
#include "BotAIController.generated.h"
class UBehaviorTreeComponent;
class UBlackboardComponent;
UCLASS()
class RPGDEMO_API ABotAIController : public AAIController
{
GENERATED_BODY()
public:
bool GetRandomPointInRadius(UNavigationSystem* navSys, FVector origin, float radius, FVector& location);
};
|
[
"infamousjeezy@gmail.com"
] |
infamousjeezy@gmail.com
|
855909cedafd1b6249f8324f15b5ab4856ed4df8
|
27d32027fc88567ae7fce89cef561747acbe25ad
|
/hackerrank/Algorithms/Implementation/Angry Professor.cpp
|
663e2c418cf77f2a62a2c2ad6fd898baedfdd700
|
[] |
no_license
|
jayantsurana/competitiveCoding
|
ff12aa9ef1cc59701609a400856c9b4f5ee416c6
|
e4d5ba5132f9f5a4dad4a2f87a831b845ed364de
|
refs/heads/master
| 2021-07-20T16:31:18.661792
| 2020-04-25T12:38:25
| 2020-04-25T12:38:25
| 144,750,103
| 0
| 0
| null | 2019-02-19T12:18:19
| 2018-08-14T17:11:07
|
C++
|
UTF-8
|
C++
| false
| false
| 1,920
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
vector<string> split_string(string);
// Complete the angryProfessor function below.
string angryProfessor(int k, vector<int> a) {
int earlyontime=0;
string s;
for(int i=0; i<a.size(); i++){
if(a[i]<=0)
earlyontime++;
}
if(k<=earlyontime)
s="NO";
else
s="YES";
return s;
}//By Jayant Surana.
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
int t;
cin >> t;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
for (int t_itr = 0; t_itr < t; t_itr++) {
string nk_temp;
getline(cin, nk_temp);
vector<string> nk = split_string(nk_temp);
int n = stoi(nk[0]);
int k = stoi(nk[1]);
string a_temp_temp;
getline(cin, a_temp_temp);
vector<string> a_temp = split_string(a_temp_temp);
vector<int> a(n);
for (int i = 0; i < n; i++) {
int a_item = stoi(a_temp[i]);
a[i] = a_item;
}
string result = angryProfessor(k, a);
fout << result << "\n";
}
fout.close();
return 0;
}
vector<string> split_string(string input_string) {
string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) {
return x == y and x == ' ';
});
input_string.erase(new_end, input_string.end());
while (input_string[input_string.length() - 1] == ' ') {
input_string.pop_back();
}
vector<string> splits;
char delimiter = ' ';
size_t i = 0;
size_t pos = input_string.find(delimiter);
while (pos != string::npos) {
splits.push_back(input_string.substr(i, pos - i));
i = pos + 1;
pos = input_string.find(delimiter, i);
}
splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));
return splits;
}
|
[
"jayantplb@gmail.com"
] |
jayantplb@gmail.com
|
3283b34a9cffd4258704a7e96dc41ae88fec5108
|
c444b63016a742bccc9515f5fc2d38f9a3c3c760
|
/Reco.h
|
31dd0e09ccda36ebf93c407e7b4f24f52fbd983e
|
[] |
no_license
|
vbashkirov/DataFormat-v44
|
d38a4eeaa10924fc04b5285141813f3b0bbca8de
|
b583107f04b63aee64273fbee2c60fd0f5877184
|
refs/heads/master
| 2021-01-22T12:57:01.595679
| 2015-02-24T21:23:26
| 2015-02-24T21:23:26
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 36,413
|
h
|
// Andriy Zatserklyaniy, April 17, 2014: production release
#ifndef Reco_h
#define Reco_h
#include "DataFormat.h"
#include "Track.h"
#include "Sensor.h"
#include "Geometry.h"
#include <iostream>
#include <vector>
#include <map>
#include <list>
using std::cout; using std::endl;
ClassImp(Hit2D);
ClassImp(SensorHit);
ClassImp(CRay2D);
//ClassImp(CRay);
ClassImp(Track2D);
//ClassImp(Track);
ClassImp(SuperTrack2D);
ClassImp(SuperTrack);
class Reco {
public:
Bool_t debug_;
Float_t deltaT_;
const Geometry* geometry_;
PCTSensors* pCTSensors_;
const BeamSpot* beamSpotIn_;
const BeamSpot* beamSpotOut_;
const PCTEvent* pCTEvent_;
Int_t event_;
std::list<const Track2D*> tin_;
std::list<const Track2D*> tout_;
std::list<const Track2D*> vin_;
std::list<const Track2D*> vout_;
std::list<const SuperTrack2D*> vSuperTracks_;
std::list<const SuperTrack2D*> tSuperTracks_;
std::list<const SuperTrack*> superTracks_;
static TClonesArray* poolTrack2D_; //->
static TClonesArray* poolSuperTrack2D_; //->
static TClonesArray* poolSuperTrack_; //->
// additional info
Int_t nhitv_[4];
Int_t nhitt_[4];
std::list<const SensorHit*> firstHitv_;
std::list<const SensorHit*> firstHitt_;
public:
Reco(const Geometry* geometry, PCTSensors* pCTSensors, const BeamSpot* beamSpotIn, const BeamSpot* beamSpotOut, const PCTEvent* pCTEvent, Int_t event, bool debug=kFALSE): debug_(debug)
, geometry_(geometry), pCTSensors_(pCTSensors), beamSpotIn_(beamSpotIn), beamSpotOut_(beamSpotOut), pCTEvent_(pCTEvent)
, event_(event)
{
//cout<< "Reco::Reco" <<endl;
deltaT_ = pCTEvent_->deltaT;
//cout<< "Reco::Reco: create pool" <<endl;
//Sensor::CreateHitPool();
Sensor::ClearPool();
if (!poolTrack2D_) poolTrack2D_ = new TClonesArray("Track2D", 1024);
if (!poolSuperTrack2D_) poolSuperTrack2D_ = new TClonesArray("SuperTrack2D", 128);
if (!poolSuperTrack_) poolSuperTrack_ = new TClonesArray("SuperTrack", 16);
//cout<< "Sensor::poolSensorHit_->GetLast()+1 = " << Sensor::poolSensorHit_->GetLast()+1 <<endl;
//cout<< "poolTrack2D_->GetLast()+1 = " << poolTrack2D_->GetLast()+1 <<endl;
//cout<< "poolSuperTrack2D_->GetLast()+1 = " << poolSuperTrack2D_->GetLast()+1 <<endl;
//cout<< "poolSuperTrack_->GetLast()+1 = " << poolSuperTrack_->GetLast()+1 <<endl;
//----------- pCTSensors_ = new PCTSensors();
pCTSensors_->clear();
for (int ilayer=0; ilayer<4; ++ilayer) {
nhitv_[ilayer] = 0;
nhitt_[ilayer] = 0;
}
// get hits for this event
for (int iFPGA=0; iFPGA<12; ++iFPGA)
{
const TrackerFPGA& trackerFPGA = pCTEvent_->trackerFPGA[iFPGA];
for (unsigned int ichip=0; ichip<trackerFPGA.numChips; ++ichip)
{
TrackerChip* trackerChip = (TrackerChip*) trackerFPGA.chips->At(ichip);
for (int icluster=0; icluster<trackerChip->numClust; ++icluster) {
if (debug_) {
Int_t strip = 64*trackerChip->address + (63-trackerChip->nfirst[icluster]);
cout<< event_ << "\t iFPGA = " << std::setw(2) << iFPGA
<< " trackerChip->address = " << std::setw(2) << (unsigned) trackerChip->address
<< " nstrips[" << icluster << "] = " << (unsigned) trackerChip->nstrips[icluster]
<< " nfirst[" << icluster << "] = " << (unsigned) trackerChip->nfirst[icluster]
<< " strip = " << strip <<endl;
// printf("%-8d iFPGA = %2d trackerChip->address = %2d nstrips[%d] = %d nfirst[%d] = %d strip = %d\n",
// event,iFPGA,(unsigned) trackerChip->address,icluster,(unsigned) trackerChip->nstrips[icluster],icluster,(unsigned) trackerChip->nfirst[icluster],strip);
}
pCTSensors_->AddCluster(iFPGA, trackerChip->address, trackerChip->nfirst[icluster], trackerChip->nstrips[icluster]);
}
}
}
pCTSensors_->GetHits();
const SensorHit* first_v = 0;
Int_t n_v_hits = 0;
for (unsigned ilayer=0; ilayer<4; ++ilayer) {
n_v_hits += pCTSensors_->v_hits[ilayer].size();
nhitv_[ilayer] += pCTSensors_->v_hits[ilayer].size();
if (!first_v && pCTSensors_->v_hits[ilayer].size() > 0) {
first_v = pCTSensors_->v_hits[ilayer].front();
firstHitv_.push_back(first_v);
}
}
const SensorHit* first_t = 0;
Int_t n_t_hits = 0;
for (unsigned ilayer=0; ilayer<4; ++ilayer) {
n_t_hits += pCTSensors_->t_hits[ilayer].size();
nhitt_[ilayer] = pCTSensors_->t_hits[ilayer].size();
if (!first_t && pCTSensors_->t_hits[ilayer].size() > 0) {
first_t = pCTSensors_->t_hits[ilayer].front();
firstHitt_.push_back(first_t);
}
}
if (debug_) cout<< "n_v_hits = " << n_v_hits << " n_t_hits = " << n_t_hits <<endl;
}
~Reco() {
//cout<< "Reco::~Reco" <<endl;
//for (std::list<const Track2D*>::const_iterator it=tin_.begin(); it!=tin_.end(); ++it) delete *it;
//for (std::list<const Track2D*>::const_iterator it=tout_.begin(); it!=tout_.end(); ++it) delete *it;
//for (std::list<const Track2D*>::const_iterator it=vin_.begin(); it!=vin_.end(); ++it) delete *it;
//for (std::list<const Track2D*>::const_iterator it=vout_.begin(); it!=vout_.end(); ++it) delete *it;
if (poolTrack2D_) poolTrack2D_->Clear();
if (poolTrack2D_) poolSuperTrack2D_->Clear();
if (poolTrack2D_) poolSuperTrack_->Clear();
//for (std::list<const SuperTrack2D*>::const_iterator it=vSuperTracks_.begin(); it!=vSuperTracks_.end(); ++it) delete *it;
//for (std::list<const SuperTrack2D*>::const_iterator it=tSuperTracks_.begin(); it!=tSuperTracks_.end(); ++it) delete *it;
//for (std::list<const SuperTrack*>::const_iterator it=superTracks_.begin(); it!=superTracks_.end(); ++it) delete *it;
//------------ delete pCTSensors_;
}
void Tracking()
{
// sanity checks
if (pCTSensors_->t_hits[0].size() + pCTSensors_->t_hits[1].size() == 0) return;
if (pCTSensors_->t_hits[2].size() + pCTSensors_->t_hits[3].size() == 0) return;
if (pCTSensors_->v_hits[0].size() + pCTSensors_->v_hits[1].size() == 0) return;
if (pCTSensors_->v_hits[2].size() + pCTSensors_->v_hits[3].size() == 0) return;
if (false
|| pCTSensors_->t_hits[0].size() > 3
|| pCTSensors_->t_hits[1].size() > 3
|| pCTSensors_->t_hits[2].size() > 3
|| pCTSensors_->t_hits[3].size() > 3
|| pCTSensors_->v_hits[0].size() > 3
|| pCTSensors_->v_hits[1].size() > 3
|| pCTSensors_->v_hits[2].size() > 3
|| pCTSensors_->v_hits[3].size() > 3
) return;
GenerateTracks2D();
if (tin_.size() && tout_.size() && vin_.size() && vout_.size()) GenerateSuperTracks2D();
if (vSuperTracks_.size() && tSuperTracks_.size()) GenerateSuperTracks();
if (superTracks_.size() > 0) {
Corrections();
return; // seems to be fine event
}
// try to recover gap hits
Int_t n_t_hits[4]; // initial number of the hits before adding of the gap hits
for (int ilayer=0; ilayer<4; ++ilayer) n_t_hits[ilayer] = pCTSensors_->t_hits[ilayer].size();
Int_t n_v_hits[4]; // initial number of the hits before adding of the gap hits
for (int ilayer=0; ilayer<4; ++ilayer) n_v_hits[ilayer] = pCTSensors_->v_hits[ilayer].size();
// input telescope
RecoverHits(0, beamSpotIn_);
// output telescope
RecoverHits(2, beamSpotOut_);
// redo the track reconstruction
GenerateTracks2D();
if (!tin_.size() || !tout_.size() || !vin_.size() || !vout_.size()) return;
if (tin_.size() && tout_.size() && vin_.size() && vout_.size()) GenerateSuperTracks2D();
if (vSuperTracks_.size() && tSuperTracks_.size()) GenerateSuperTracks();
if (debug_) cout<< "Reco::Tracking: superTracks_.size() = " << superTracks_.size() <<endl;
if (superTracks_.size() > 0) Corrections();
}
void Corrections()
{
if (debug_) cout<< "Reco::Corrections: superTracks_.size() = " << superTracks_.size() <<endl;
if (superTracks_.size() == 0) return;
//-- Double_t tilt = 2.94e-3; // radians
Double_t tilt = 2.50e-3; // radians // after Robert's corrections
for (std::list<const SuperTrack*>::iterator it=superTracks_.begin(); it!=superTracks_.end(); ++it) {
const SuperTrack* superTrack = *it;
Track2D* otrack_t = const_cast<Track2D*>(superTrack->tTrack_->otrack2D_);
Track2D* otrack_v = const_cast<Track2D*>(superTrack->vTrack_->otrack2D_);
Double_t v0 = otrack_v->x_;
Double_t t0 = otrack_t->x_;
//--AZ-- otrack_t->x_ -= v0*tilt - 0.030;
//--AZ-- otrack_v->x_ += (t0 - 150.)*tilt - 0.15;
otrack_t->x_ -= (v0 - 12.)*tilt;
otrack_v->x_ += t0*tilt;
// otrack_t->x_ -= (v0 - 10.)*tilt;
// otrack_v->x_ += (t0 - 170.)*tilt;
}
}
void RecoverHits(Int_t layerToStart, const BeamSpot* beamSpot)
{
Int_t n_t_hits[4]; // initial number of the hits before adding of the gap hits
for (int ilayer=0; ilayer<4; ++ilayer) n_t_hits[ilayer] = pCTSensors_->t_hits[ilayer].size();
Int_t n_v_hits[4]; // initial number of the hits before adding of the gap hits
for (int ilayer=0; ilayer<4; ++ilayer) n_v_hits[ilayer] = pCTSensors_->v_hits[ilayer].size();
SensorHit vertexHit_t(0, 0, 0, beamSpot->u_, beamSpot->t_); // vertex hit for recovery of the t-hits
SensorHit vertexHit_v(0, 0, 0, beamSpot->u_, beamSpot->v_); // vertex hit for recovery of the v-hits
Int_t layer1 = layerToStart;
Int_t layer2 = layer1 + 1;
//-- Double_t distance_max = 1. + 5.*beamSpot->r_*(geometry_->ut_[1]-geometry_->ut_[0])/(geometry_->ut_[0] - beamSpot->u_);
Double_t distance_max = 1. + 5.*beamSpot->r_*(geometry_->ut_[layer2]-geometry_->ut_[layer1])/(geometry_->ut_[layer1] - beamSpot->u_);
for (int ilayer=layerToStart; ilayer<=layerToStart+1; ++ilayer)
{
for (int ihit=0; ihit<n_t_hits[ilayer]; ++ihit) // loop over "real" t-hits
{
const SensorHit* hit = pCTSensors_->t_hits[ilayer][ihit];
Track2D vertex_track(&vertexHit_t, hit);
Int_t layerTo = (ilayer == layerToStart)? layerToStart+1: layerToStart;
Double_t pos = vertex_track.at(geometry_->ut_[layerTo]); // position of the t-hit. Will be used for both t- and v-recovery
// look at t-gaps for t-hits recovery
for (int igap=0; igap<3; ++igap)
{
//------------- if (TMath::Abs(pos - pCTSensors_->gap_.tgap_[layerTo][igap]) < distance_max)
if (TMath::Abs(pos - pCTSensors_->gap_.tgap_[layerTo][igap]) < pCTSensors_->gap_.width_)
{
// create a gap hit
//-----------------
// Double_t sigma_vertex = beamSpot->r_*(geometry_->ut_[layer2] - geometry_->ut_[layer1])/(geometry_->ut_[layerTo]-beamSpot->u_);
// Double_t sigma_gap = 1./TMath::Sqrt(12.);
// Double_t w_vertex = 1./(sigma_vertex*sigma_vertex);
// Double_t w_gap = 1./(sigma_gap*sigma_gap);
// Double_t pos_mean = (w_vertex*pos + w_gap*pCTSensors_->gap_.tgap_[layerTo][igap]) / (w_vertex + w_gap);
Double_t pos_mean = pCTSensors_->gap_.tgap_[layerTo][igap];
//-----------------
Int_t nstrips_gap = pCTSensors_->gap_.width_/geometry_->pitch_;
Int_t sensorId = -(20 + layerTo);
//-- SensorHit* gapHit = new ((*Sensor::poolSensorHit_)[Sensor::poolSensorHit_->GetLast()+1])
//-- SensorHit(sensorId, 0, nstrips_gap, geometry_->ut_[layerTo], pCTSensors_->gap_.tgap_[layerTo][igap]);
SensorHit* gapHit = new ((*Sensor::poolSensorHit_)[Sensor::poolSensorHit_->GetLast()+1])
SensorHit(sensorId, 0, nstrips_gap, geometry_->ut_[layerTo], pos_mean);
// add it to the common place
pCTSensors_->t_hits[layerTo].push_back(gapHit);
if (debug_) cout<< " added t hit " << *gapHit <<endl;
}
}
// look at v-gaps for v-hits recovery
for (int igap=0; igap<3; ++igap)
{
//------------ if (TMath::Abs(pos - pCTSensors_->gap_.vgap_[layerTo][igap]) < distance_max)
if (TMath::Abs(pos - pCTSensors_->gap_.vgap_[layerTo][igap]) < pCTSensors_->gap_.width_)
{
// create a gap hit for V
Int_t nstrips_gap = pCTSensors_->gap_.width_/geometry_->pitch_;
// project all v-hits
for (int ihit_v=0; ihit_v<n_v_hits[ilayer]; ++ihit_v)
{
const SensorHit* hit_v = pCTSensors_->v_hits[ilayer][ihit]; // current v-hit
Track2D vertex_track_v(&vertexHit_v, hit_v); // vertex track for fcurrent v-hit
Int_t sensorId = -(10 + layerTo);
SensorHit* gapHit = new ((*Sensor::poolSensorHit_)[Sensor::poolSensorHit_->GetLast()+1])
SensorHit(sensorId, 0, nstrips_gap, geometry_->uv_[layerTo], vertex_track_v.at(geometry_->uv_[layerTo])); // create v-hit at projection of v vertex track
// add it to the common place
pCTSensors_->v_hits[layerTo].push_back(gapHit);
if (debug_) cout<< " added v hit " << *gapHit <<endl;
}
}
}
}
}
}
void GenerateTracks2D()
{
tin_.clear();
tout_.clear();
vin_.clear();
vout_.clear();
// T-sensors
for (unsigned ihit1=0; ihit1<pCTSensors_->t_hits[0].size(); ++ihit1) {
const SensorHit* hit1 = pCTSensors_->t_hits[0][ihit1];
if (debug_) cout<< "hit1: " << *hit1 <<endl;
for (unsigned ihit2=0; ihit2<pCTSensors_->t_hits[1].size(); ++ihit2) {
const SensorHit* hit2 = pCTSensors_->t_hits[1][ihit2];
if (debug_) cout<< "hit2: " << *hit2 <<endl;
if (hit1->sensorId_ < 0 && hit2->sensorId_ < 0) continue; // at least one of the hits should be "real"
Track2D* cRay2d = new ((*poolTrack2D_)[poolTrack2D_->GetLast()+1]) Track2D(hit1, hit2);
tin_.push_back(cRay2d);
}
}
for (unsigned ihit1=0; ihit1<pCTSensors_->t_hits[2].size(); ++ihit1) {
const SensorHit* hit1 = pCTSensors_->t_hits[2][ihit1];
if (debug_) cout<< "hit1: " << *hit1 <<endl;
for (unsigned ihit2=0; ihit2<pCTSensors_->t_hits[3].size(); ++ihit2) {
const SensorHit* hit2 = pCTSensors_->t_hits[3][ihit2];
if (debug_) cout<< "hit2: " << *hit2 <<endl;
if (hit1->sensorId_ < 0 && hit2->sensorId_ < 0) continue; // at least one of the hits should be "real"
Track2D* cRay2d = new ((*poolTrack2D_)[poolTrack2D_->GetLast()+1]) Track2D(hit1, hit2);
tout_.push_back(cRay2d);
}
}
if (debug_) {
cout<< "tin_" <<endl;
for (std::list<const Track2D*>::const_iterator it=tin_.begin(); it!=tin_.end(); ++it) {
cout<< "it->x_ = " << (*it)->x_ <<endl;
}
}
if (debug_) {
cout<< "tout_" <<endl;
for (std::list<const Track2D*>::const_iterator it=tout_.begin(); it!=tout_.end(); ++it) {
cout<< "it->x_ = " << (*it)->x_ <<endl;
}
}
// V-sensors
for (unsigned ihit1=0; ihit1<pCTSensors_->v_hits[0].size(); ++ihit1) {
SensorHit* hit1 = pCTSensors_->v_hits[0][ihit1];
if (debug_) cout<< "hit1: " << *hit1 <<endl;
for (unsigned ihit2=0; ihit2<pCTSensors_->v_hits[1].size(); ++ihit2) {
SensorHit* hit2 = pCTSensors_->v_hits[1][ihit2];
if (debug_) cout<< "hit2: " << *hit2 <<endl;
if (hit1->sensorId_ < 0 && hit2->sensorId_ < 0) continue; // at least one of the hits should be "real"
Track2D* cRay2d = new ((*poolTrack2D_)[poolTrack2D_->GetLast()+1]) Track2D(hit1, hit2);
vin_.push_back(cRay2d);
}
}
for (unsigned ihit1=0; ihit1<pCTSensors_->v_hits[2].size(); ++ihit1) {
SensorHit* hit1 = pCTSensors_->v_hits[2][ihit1];
if (debug_) cout<< "hit1: " << *hit1 <<endl;
for (unsigned ihit2=0; ihit2<pCTSensors_->v_hits[3].size(); ++ihit2) {
SensorHit* hit2 = pCTSensors_->v_hits[3][ihit2];
if (debug_) cout<< "hit2: " << *hit2 <<endl;
if (hit1->sensorId_ < 0 && hit2->sensorId_ < 0) continue; // at least one of the hits should be "real"
Track2D* cRay2d = new ((*poolTrack2D_)[poolTrack2D_->GetLast()+1]) Track2D(hit1, hit2);
vout_.push_back(cRay2d);
}
}
if (debug_) {
cout<< "vin_" <<endl;
for (std::list<const Track2D*>::const_iterator it=vin_.begin(); it!=vin_.end(); ++it) {
cout<< "it->x_ = " << (*it)->x_ <<endl;
}
}
if (debug_) {
cout<< "vout_" <<endl;
for (std::list<const Track2D*>::const_iterator it=vout_.begin(); it!=vout_.end(); ++it) {
cout<< "it->x_ = " << (*it)->x_ <<endl;
}
}
}
void GenerateVSuperTracks2D(Double_t rmax=10.)
{
vSuperTracks_.clear();
// start from V-senosors: as a max we can reconstruct two tracks and only if they are from different V-sensors
for (std::list<const Track2D*>::const_iterator it=vin_.begin(); it!=vin_.end(); ++it) {
const Track2D* itrack = *it;
for (std::list<const Track2D*>::const_iterator ot=vout_.begin(); ot!=vout_.end(); ++ot) {
const Track2D* otrack = *ot;
//-- SuperTrack2D* superTrack = new SuperTrack2D(itrack, otrack);
SuperTrack2D* superTrack = new ((*poolSuperTrack2D_)[poolSuperTrack2D_->GetLast()+1]) SuperTrack2D(itrack, otrack);
vSuperTracks_.push_back(superTrack);
}
}
// apply filter on the distance between the hits in the plane u = 0
std::map<Double_t, const SuperTrack2D*> mapCloseTracks; // for the filter on the distance in the plane u = 0
for (std::list<const SuperTrack2D*>::const_iterator it=vSuperTracks_.begin(); it!=vSuperTracks_.end(); ++it) {
const SuperTrack2D* superTrack = *it;
mapCloseTracks[superTrack->Distance()] = superTrack;
}
if (debug_) cout<< "GenerateSuperTracks2D: vSuperTracks_.size() = " << vSuperTracks_.size() <<endl;
if (debug_) {
cout<< "resulting distance map from SuperTracks2D for V-board" <<endl;
for (std::map<Double_t, const SuperTrack2D*>::const_iterator it=mapCloseTracks.begin(); it!=mapCloseTracks.end(); ++it) {
Double_t distance = it->first;
cout<< std::distance<std::map<Double_t, const SuperTrack2D*>::const_iterator>(mapCloseTracks.begin(), it) << "\t distance = " << distance <<endl;
}
}
// 1) loop over map to remove the tracks with higher distance
// 2) check for hits overlap in the (small number) of passed tracks
if (debug_) cout<< "loop over the map to remove tracks with distance above the rmax = " << rmax <<endl;
//--const-- for (std::map<Double_t, const SuperTrack2D*>::const_iterator it=mapCloseTracks.begin(); it!=mapCloseTracks.end();)
for (std::map<Double_t, const SuperTrack2D*>::iterator it=mapCloseTracks.begin(); it!=mapCloseTracks.end();)
{
if (it->first < rmax) ++it;
else {
if (debug_) cout<< "remove track with distance " << it->first <<endl;
vSuperTracks_.remove(it->second);
//-- it = mapCloseTracks.erase(it);
mapCloseTracks.erase(it++);
}
}
if (debug_) cout<< "GenerateSuperTracks2D: vSuperTracks_.size() = " << vSuperTracks_.size() <<endl;
// make sure that the rest of tracks do not share the same hits
//--const-- for (std::map<Double_t, const SuperTrack2D*>::const_iterator it=mapCloseTracks.begin(); it!=mapCloseTracks.end(); ++it)
for (std::map<Double_t, const SuperTrack2D*>::iterator it=mapCloseTracks.begin(); it!=mapCloseTracks.end(); ++it)
{
//--const-- std::map<Double_t, const SuperTrack2D*>::const_iterator next = it;
std::map<Double_t, const SuperTrack2D*>::iterator next = it;
++next;
while (next != mapCloseTracks.end()) {
if (next->second->SharedHits(it->second)) {
vSuperTracks_.remove(next->second);
//-- next = mapCloseTracks.erase(next);
mapCloseTracks.erase(next++);
}
else ++next;
}
}
}
void GenerateTSuperTracks2D(Double_t rmax=10.)
{
tSuperTracks_.clear();
for (std::list<const Track2D*>::const_iterator it=tin_.begin(); it!=tin_.end(); ++it) {
const Track2D* itrack2D = *it;
for (std::list<const Track2D*>::const_iterator ot=tout_.begin(); ot!=tout_.end(); ++ot) {
const Track2D* otrack2D = *ot;
//-- SuperTrack2D* superTrack2D = new SuperTrack2D(itrack2D, otrack2D);
SuperTrack2D* superTrack2D = new ((*poolSuperTrack2D_)[poolSuperTrack2D_->GetLast()+1]) SuperTrack2D(itrack2D, otrack2D);
tSuperTracks_.push_back(superTrack2D);
}
}
// apply filter on the distance between the hits in the plane u = 0
std::map<Double_t, const SuperTrack2D*> mapCloseTracks; // for the filter on the distance in the plane u = 0
for (std::list<const SuperTrack2D*>::const_iterator it=tSuperTracks_.begin(); it!=tSuperTracks_.end(); ++it) {
const SuperTrack2D* superTrack = *it;
mapCloseTracks[superTrack->Distance()] = superTrack;
}
if (debug_) cout<< "GenerateSuperTracks2D: tSuperTracks_.size() = " << tSuperTracks_.size() <<endl;
if (debug_) {
cout<< "resulting distance map from SuperTracks2D for T-board" <<endl;
for (std::map<Double_t, const SuperTrack2D*>::const_iterator it=mapCloseTracks.begin(); it!=mapCloseTracks.end(); ++it) {
Double_t distance = it->first;
cout<< std::distance<std::map<Double_t, const SuperTrack2D*>::const_iterator>(mapCloseTracks.begin(), it) << "\t distance = " << distance <<endl;
}
}
// 1) loop over map to remove the tracks with higher distance
// 2) check for hits overlap in the (small number) of passed tracks
if (debug_) cout<< "loop over the map to remove tracks with distance above the rmax = " << rmax <<endl;
//--const-- for (std::map<Double_t, const SuperTrack2D*>::const_iterator it=mapCloseTracks.begin(); it!=mapCloseTracks.end();)
for (std::map<Double_t, const SuperTrack2D*>::iterator it=mapCloseTracks.begin(); it!=mapCloseTracks.end();)
{
if (it->first < rmax) ++it;
else {
if (debug_) cout<< "remove track with distance " << it->first <<endl;
tSuperTracks_.remove(it->second);
//-- it = mapCloseTracks.erase(it);
mapCloseTracks.erase(it++);
}
}
if (debug_) cout<< "GenerateSuperTracks2D: tSuperTracks_.size() = " << tSuperTracks_.size() <<endl;
// make sure that the rest of tracks do not share the same hits
//--const-- for (std::map<Double_t, const SuperTrack2D*>::const_iterator it=mapCloseTracks.begin(); it!=mapCloseTracks.end(); ++it)
for (std::map<Double_t, const SuperTrack2D*>::iterator it=mapCloseTracks.begin(); it!=mapCloseTracks.end(); ++it)
{
//--const-- std::map<Double_t, const SuperTrack2D*>::const_iterator next = it;
std::map<Double_t, const SuperTrack2D*>::iterator next = it;
++next;
while (next != mapCloseTracks.end()) {
if (next->second->SharedHits(it->second)) {
tSuperTracks_.remove(next->second);
//-- next = mapCloseTracks.erase(next);
mapCloseTracks.erase(next++);
}
else ++next;
}
}
}
void GenerateSuperTracks2D(Double_t rmax=10.) {
GenerateVSuperTracks2D(rmax);
// if (vSuperTracks_.size() > 2) return;
// else if (vSuperTracks_.size() == 2) {
// // check halves
// }
GenerateTSuperTracks2D(rmax);
}
void GenerateSuperTracks()
{
superTracks_.clear();
if (debug_) cout<< "GenerateSuperTracks: vSuperTracks_.size() = " << vSuperTracks_.size() << " tSuperTracks_.size() = " << tSuperTracks_.size() <<endl;
// inspect the number of T-super tracks 2D: maximum number is 2
if (tSuperTracks_.size() > 2) return;
// inspect the number of V-super tracks 2D: maximum number is 2.
// In case of 2 tracks they should be from different halves of the V-board (at least in one layer)
if (vSuperTracks_.size() > 2) return;
if (vSuperTracks_.size() == 2) {
const SuperTrack2D* track1 = vSuperTracks_.front();
const SuperTrack2D* track2 = vSuperTracks_.back();
bool same = true
&& track1->itrack2D_->hit1_->sensorId_ == track2->itrack2D_->hit1_->sensorId_
&& track1->itrack2D_->hit2_->sensorId_ == track2->itrack2D_->hit2_->sensorId_
&& track1->otrack2D_->hit1_->sensorId_ == track2->otrack2D_->hit1_->sensorId_
&& track1->otrack2D_->hit2_->sensorId_ == track2->otrack2D_->hit2_->sensorId_
;
if (same) {
if (debug_) cout<< "GenerateSuperTracks: same = " << same <<endl;
return;
}
}
// at this point we have as max two t-superTracks and no more than v-superTracks
// in principle, we should combine them to match V-board halves with the t-tracks
//
// leave that for future
//
if (vSuperTracks_.size() != 1) return;
if (tSuperTracks_.size() != 1) return;
// match the halves
//-- SuperTrack* superTrack = new SuperTrack(vSuperTracks_.front(), tSuperTracks_.front());
SuperTrack* superTrack = new ((*poolSuperTrack_)[poolSuperTrack_->GetLast()+1]) SuperTrack(vSuperTracks_.front(), tSuperTracks_.front());
superTracks_.push_back(superTrack);
}
};
class RecoEvent: public TObject {
public:
Bool_t ok; // error flag
Float_t deltaT;
TClonesArray* track; //->
Int_t nt; // the number of super tracks
Float_t a[5]; // Energy detector channels
Float_t ped[5];
Float_t sample[5][16]; // to plot e.g. channel 1: r->Draw("sample[1][]:Iteration$","Entry$==0")
Float_t wepl;
// additional info
Int_t nhit;
Int_t nhitv[4];
Int_t nhitt[4];
Int_t nhit_reco;
Int_t nhitv_reco[4];
Int_t nhitt_reco[4];
TClonesArray* firstHitv; //->
TClonesArray* firstHitt; //->
RecoEvent(): TObject(), ok(kTRUE), nt(0) {
track = new TClonesArray("SuperTrack");
firstHitv = new TClonesArray("SensorHit", 1);
firstHitt = new TClonesArray("SensorHit", 1);
}
~RecoEvent() {
delete track;
delete firstHitv;
delete firstHitt;
}
void clear() {
deltaT = 0;
track->Clear();
firstHitv->Clear();
firstHitt->Clear();
nt = 0;
for (int i=0; i<5; ++i) {
a[i] = 0;
ped[i] = 0;
}
for (int ichan=0; ichan<5; ++ichan) for (int isample=0; isample<16; ++isample) sample[ichan][isample] = 0;
wepl = -2000.;
}
Float_t SampleSum(Int_t chan, Int_t nfront, Int_t ntail, Double_t pedestal) const {
if (chan < 0 || chan > 4) return 0;
// find a position of the maximum
Int_t imax = 0;
// assumes that the number of samples is 16
Float_t sum = sample[chan][imax];
for (int isample=0; isample<16; ++isample) {
sum += sample[chan][isample];
if (sample[chan][isample] > sample[chan][imax]) {
imax = isample;
}
}
if (sum == 0) return 0; // there are no samples in this event
Int_t n1 = imax - nfront;
if (n1 < 0) n1 = 0;
Int_t n2 = imax + ntail;
if (n2 > 15) n2 = 15;
sum = 0;
for (int isample=n1; isample<=n2; ++isample) sum += sample[chan][isample];
sum -= (n2 - n1 + 1)*pedestal;
return sum;
}
void Extract(const Reco& reco) {
clear();
nhit = 0;
for (int ilayer=0; ilayer<4; ++ilayer) {
nhitv[ilayer] = reco.nhitv_[ilayer];
nhitt[ilayer] = reco.nhitt_[ilayer];
nhit += (nhitv[ilayer] + nhitt[ilayer]);
nhitv_reco[ilayer] = 0;
nhitt_reco[ilayer] = 0;
nhit_reco = 0;
}
for (std::list<const SensorHit*>::const_iterator it=reco.firstHitv_.begin(); it!=reco.firstHitv_.end(); ++it) {
const SensorHit* hit = *it;
new ((*firstHitv)[firstHitv->GetLast()+1]) SensorHit(*hit);
}
for (std::list<const SensorHit*>::const_iterator it=reco.firstHitt_.begin(); it!=reco.firstHitt_.end(); ++it) {
const SensorHit* hit = *it;
new ((*firstHitt)[firstHitt->GetLast()+1]) SensorHit(*hit);
}
deltaT = reco.deltaT_;
for (std::list<const SuperTrack*>::const_iterator it=reco.superTracks_.begin(); it!=reco.superTracks_.end(); ++it) {
const SuperTrack* superTrack = *it;
new ((*track)[track->GetLast()+1]) SuperTrack(*superTrack);
++nt;
if (superTrack->vTrack_->itrack2D_->hit1_->sensorId_ < 0) ++nhitv_reco[0];
if (superTrack->vTrack_->itrack2D_->hit2_->sensorId_ < 0) ++nhitv_reco[1];
if (superTrack->vTrack_->otrack2D_->hit1_->sensorId_ < 0) ++nhitv_reco[2];
if (superTrack->vTrack_->otrack2D_->hit2_->sensorId_ < 0) ++nhitv_reco[3];
if (superTrack->tTrack_->itrack2D_->hit1_->sensorId_ < 0) ++nhitt_reco[0];
if (superTrack->tTrack_->itrack2D_->hit2_->sensorId_ < 0) ++nhitt_reco[1];
if (superTrack->tTrack_->otrack2D_->hit1_->sensorId_ < 0) ++nhitt_reco[2];
if (superTrack->tTrack_->otrack2D_->hit2_->sensorId_ < 0) ++nhitt_reco[3];
}
nhit_reco = 0;
for (int ilayer=0; ilayer<4; ++ilayer) {
nhit_reco += nhitv_reco[ilayer];
nhit_reco += nhitt_reco[ilayer];
}
// Energy detector
//a[0] = reco.pCTEvent_->energyBoard[0].pulse[0];
//a[1] = reco.pCTEvent_->energyBoard[0].pulse[1];
//a[2] = reco.pCTEvent_->energyBoard[0].pulse[2];
//a[3] = reco.pCTEvent_->energyBoard[1].pulse[0];
//a[4] = reco.pCTEvent_->energyBoard[1].pulse[1];
/////////////////////////////
int brd=0;
///// //--orig int enrgTag0= thisEvent->Event->Board[0].enrgTag;
///// //--orig int enrgTag1= thisEvent->Event->Board[1].enrgTag;
///// // if (enrgTag0 != enrgTag1) cout << "enrg tag mismatch: " << enrgTag0 << " vs " << enrgTag1;
if (reco.pCTEvent_->energyBoard[brd].numChan>0 || reco.pCTEvent_->energyBoard[brd].numSamples>0) {
///// // if (thisEvent->Event->Board[brd].enrgTag != evtNum % 4) cout << "tag mismatch, energy tag=" << thisEvent->Event->Board[brd].enrgTag << "\n";
if (reco.pCTEvent_->energyBoard[brd].reduced) {
a[0] = reco.pCTEvent_->energyBoard[brd].pulse[0]; ped[0] = reco.pCTEvent_->energyBoard[brd].pedestal[0];
a[1] = reco.pCTEvent_->energyBoard[brd].pulse[1]; ped[1] = reco.pCTEvent_->energyBoard[brd].pedestal[1];
a[2] = reco.pCTEvent_->energyBoard[brd].pulse[2]; ped[2] = reco.pCTEvent_->energyBoard[brd].pedestal[2];
} else {
a[0] = 0.; a[1] = 0.; a[2] = 0.;
/// enrgSamp *thisSamp = thisEvent->Event->Board[brd].firstSample;
//EnergySample* energySample = (EnergySample*) reco.pCTEvent_->energyBoard[brd].samples->At(0);
//if (thisSamp != 0)
if (reco.pCTEvent_->energyBoard[brd].samples->GetLast()+1 > 0)
{
EnergySample* energySample0 = (EnergySample*) reco.pCTEvent_->energyBoard[brd].samples->At(0);
sample[0][0] = energySample0->pulse[0]; // assign the first sample of the RecoEvent::sample for the first energy board
sample[1][0] = energySample0->pulse[1];
sample[2][0] = energySample0->pulse[2];
int ped0 = energySample0->pulse[0]; ped[0] = ped0;
int ped1 = energySample0->pulse[1]; ped[1] = ped1;
int ped2 = energySample0->pulse[2]; ped[2] = ped2;
//while (thisSamp != 0)
for (int isample=1; isample<reco.pCTEvent_->energyBoard[brd].samples->GetLast()+1; ++isample)
{
EnergySample* energySample = (EnergySample*) reco.pCTEvent_->energyBoard[brd].samples->At(isample);
sample[0][isample] = energySample->pulse[0]; // assign the rest of 16 samples of the RecoEvent::sample for the first energy board
sample[1][isample] = energySample->pulse[1];
sample[2][isample] = energySample->pulse[2];
a[0] = a[0] + energySample->pulse[0] - ped0;
a[1] = a[1] + energySample->pulse[1] - ped1;
a[2] = a[2] + energySample->pulse[2] - ped2;
}
}
}
} else {
a[0] = 0; ped[0] = 0;
a[1] = 0; ped[1] = 0;
a[2] = 0; ped[2] = 0;
}
brd=1;
if (reco.pCTEvent_->energyBoard[brd].numChan>0 || reco.pCTEvent_->energyBoard[brd].numSamples>0) {
///// // if (thisEvent->Event->Board[brd].enrgTag != evtNum % 4) cout << "tag mismatch, energy tag=" << thisEvent->Event->Board[brd].enrgTag << "\n";
if (reco.pCTEvent_->energyBoard[brd].reduced) {
a[3] = reco.pCTEvent_->energyBoard[brd].pulse[0]; ped[3] = reco.pCTEvent_->energyBoard[brd].pedestal[0];
a[4] = reco.pCTEvent_->energyBoard[brd].pulse[1]; ped[4] = reco.pCTEvent_->energyBoard[brd].pedestal[1];
//--no such channel-- PhCh5 = reco.pCTEvent_->energyBoard[brd].pulse[2];
} else {
a[3] = 0.; a[4] = 0.; //--no such channel-- PhCh5 = 0.;
int ped3 = 0; int ped4 = 0; int ped5 = 0;
/// enrgSamp *thisSamp = thisEvent->Event->Board[brd].firstSample;
//EnergySample* energySample = (EnergySample*) reco.pCTEvent_->energyBoard[brd].samples->At(0);
//if (thisSamp != 0)
if (reco.pCTEvent_->energyBoard[brd].samples->GetLast()+1 > 0)
{
EnergySample* energySample0 = (EnergySample*) reco.pCTEvent_->energyBoard[brd].samples->At(0);
sample[3][0] = energySample0->pulse[0]; // assign the first sample of the RecoEvent::sample for the second energy board
sample[4][0] = energySample0->pulse[1];
ped3 = energySample0->pulse[0]; ped[3] = ped3;
ped4 = energySample0->pulse[1]; ped[4] = ped4;
ped5 = energySample0->pulse[2];
//while (thisSamp != 0)
for (int isample=1; isample<reco.pCTEvent_->energyBoard[brd].samples->GetLast()+1; ++isample)
{
EnergySample* energySample = (EnergySample*) reco.pCTEvent_->energyBoard[brd].samples->At(isample);
sample[3][isample] = energySample->pulse[0]; // assign the rest of 16 samples of the RecoEvent::sample for the second energy board
sample[4][isample] = energySample->pulse[1];
a[3] = a[3] + energySample->pulse[0] - ped3;
a[4] = a[4] + energySample->pulse[1] - ped4;
//--no such channel-- PhCh5 = PhCh5 + energySample->pulse[2] - ped5;
}
}
}
} else {
a[3] = 0; ped[3] = 0;
a[4] = 0; ped[4] = 0;
//--no such channel-- PhCh5 = 0;
}
/////////////////////////////
}
ClassDef(RecoEvent, 10);
};
#ifdef __MAKECINT__
#pragma link C++ class RecoEvent;
#endif
#endif // Reco_h
|
[
"zatserkl@gmail.com"
] |
zatserkl@gmail.com
|
86ced8b916a05bfbe0a2505c10335a536190ea4b
|
2ba7eac6d92fd7a9ddfe29a66cf099b30a86b9c4
|
/Project2/P2-1/gtest.cpp
|
c776e6539dbc1be7fe764ed52fa696a3baed1eb6
|
[] |
no_license
|
LiaoJJ/COP6726-Database-System-Implementation
|
746b82c7c8b3a3f9d8d530fab8fac05dbc1a7698
|
36770a6ab09cf924a98fb9ed393ddb0c5aaa82f2
|
refs/heads/main
| 2023-04-20T23:19:34.491291
| 2021-04-25T18:55:40
| 2021-04-25T18:55:40
| 332,445,285
| 6
| 7
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,403
|
cpp
|
#include "gtest/gtest.h"
#include <iostream>
#include "Record.h"
#include "DBFile.h"
#include "DBFile.cc"
#include "BigQ.h"
#include "BigQ.cc"
#include <stdlib.h>
using namespace std;
class BigQTest : public ::testing::Test {
protected:
BigQTest() {
// You can do set-up work for each test here.
}
~BigQTest() override {
// You can do clean-up work that doesn't throw exceptions here.
}
void SetUp() override {
// Code here will be called immediately after the constructor (right
// before each test).
// file.Open(1, "localTest/region.bin");
}
void TearDown() override {
// Code here will be called immediately after each test (right
// before the destructor).
// file.Close();
}
// File file;
char* regionFileName = "localTest/region.bin";
char* lineitemFileName = "localTest/lineitem.bin";
char* testFileName = "localTest/test.bin";
};
TEST_F(BigQTest, UpdateTopRecordForRunTest) {
// RecordComparer* comparer = new RecordComparer(new OrderMaker);
File file;
file.Open(1, regionFileName);
class Run* run = new class Run(&file, 0, 1);
Page bufferPage;
file.GetPage(&bufferPage, 0);
Record tempRecord;
bufferPage.GetFirst(&tempRecord);
while (bufferPage.GetFirst(&tempRecord) == 1) {
EXPECT_EQ(run->UpdateTopRecord(), 1);
}
EXPECT_EQ(run->UpdateTopRecord(), 0);
file.Close();
}
TEST_F(BigQTest, RecordComparerTest) {
File file;
file.Open(1, regionFileName);
//Initiate the proority queue for recard comparer
Schema* scheme = new Schema("catalog", "region");
OrderMaker* order = new OrderMaker(scheme);
priority_queue<Record*, vector<Record*>, RecordComparer> recordQueue (order);
ComparisonEngine comparisonEngine;
//Puting records into comparer based priority queue
Page bufferPage;
file.GetPage(&bufferPage, 0);
Record* readindRecord = new Record;
while (bufferPage.GetFirst(readindRecord)) {
recordQueue.push(readindRecord);
readindRecord = new Record;
}
bufferPage.EmptyItOut();
file.GetPage(&bufferPage, 0);
Record rec[2];
Record *last = NULL, *prev = NULL;
int i = 0;
while (bufferPage.GetFirst(&rec[i%2]) == 1) {
prev = last;
last = &rec[i%2];
if (prev && last) {
EXPECT_EQ(comparisonEngine.Compare(prev, last, order), -1);
}
i++;
}
file.Close();
}
TEST_F(BigQTest, RunComparerTest) {
//Initiate the proority queue for recard comparer
File file;
file.Open(1, lineitemFileName);
Schema* scheme = new Schema("catalog", "lineitem");
OrderMaker* order = new OrderMaker(scheme);
priority_queue<class Run*, vector<class Run*>, RunComparer> runQueue (order);
ComparisonEngine comparisonEngine;
class Run* run1 = new class Run(&file, 0, 1);
class Run* run2 = new class Run(&file, 1, 1);
runQueue.push(run1);
runQueue.push(run2);
//Take top record from two different run
Record one, two;
one.Copy(runQueue.top()->topRecord);
runQueue.pop();
two.Copy(runQueue.top()->topRecord);
runQueue.pop();
EXPECT_EQ(comparisonEngine.Compare(&one, &two, order), -1);
file.Close();
}
TEST_F(BigQTest, recordToRunTest) {
//Reading records from file to queue
File file;
file.Open(1, regionFileName);
Schema* scheme = new Schema("catalog", "region");
OrderMaker* order = new OrderMaker(scheme);
priority_queue<Record*, vector<Record*>, RecordComparer> recordQueue (order);
ComparisonEngine comparisonEngine;
Page bufferPage;
file.GetPage(&bufferPage, 0);
Record* readindRecord = new Record;
while (bufferPage.GetFirst(readindRecord)) {
recordQueue.push(readindRecord);
readindRecord = new Record;
}
//Writing records from queue to run
File testFile;
testFile.Open(0, testFileName);
Page testPage;
//Initiate the proority queue for recard comparer
int pageIndex = 0;
priority_queue<class Run*, vector<class Run*>, RunComparer> runQueue (order);
recordQueueToRun(recordQueue, runQueue, file, bufferPage, pageIndex);
EXPECT_EQ(recordQueue.size(), 0);
EXPECT_EQ(runQueue.size(), 1);
file.Close();
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
[
"519312579@qq.com"
] |
519312579@qq.com
|
0f49bdd721aa93feaf4cd2f6ebaf1ce787a1518a
|
e25b7bb3fd43f763f4e5dcb09cdda35b9a3f30a0
|
/net/third_party/quic/test_tools/crypto_test_utils_test.cc
|
ede4a833f74c10c53b6ef0f83a99a0062d8cf383
|
[
"BSD-3-Clause"
] |
permissive
|
trustcrypto/chromium
|
281ff06e944b1ff7da7a5005e41173ccc78eb2cd
|
6e3be4ab657ddd91505753ab67801efcf8541367
|
refs/heads/master
| 2023-03-08T03:58:49.920358
| 2018-12-26T20:55:44
| 2018-12-26T20:55:44
| 163,217,833
| 1
| 0
|
NOASSERTION
| 2018-12-26T21:07:41
| 2018-12-26T21:07:40
| null |
UTF-8
|
C++
| false
| false
| 7,065
|
cc
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/third_party/quic/test_tools/crypto_test_utils.h"
#include "net/test/gtest_util.h"
#include "net/third_party/quic/core/proto/crypto_server_config.pb.h"
#include "net/third_party/quic/core/quic_utils.h"
#include "net/third_party/quic/core/tls_server_handshaker.h"
#include "net/third_party/quic/platform/api/quic_ptr_util.h"
#include "net/third_party/quic/platform/api/quic_test.h"
#include "net/third_party/quic/platform/api/quic_text_utils.h"
#include "net/third_party/quic/test_tools/mock_clock.h"
namespace quic {
namespace test {
class ShloVerifier {
public:
ShloVerifier(
QuicCryptoServerConfig* crypto_config,
QuicSocketAddress server_addr,
QuicSocketAddress client_addr,
const QuicClock* clock,
QuicReferenceCountedPointer<QuicSignedServerConfig> signed_config,
QuicCompressedCertsCache* compressed_certs_cache)
: crypto_config_(crypto_config),
server_addr_(server_addr),
client_addr_(client_addr),
clock_(clock),
signed_config_(signed_config),
compressed_certs_cache_(compressed_certs_cache),
params_(new QuicCryptoNegotiatedParameters) {}
class ValidateClientHelloCallback : public ValidateClientHelloResultCallback {
public:
explicit ValidateClientHelloCallback(ShloVerifier* shlo_verifier)
: shlo_verifier_(shlo_verifier) {}
void Run(QuicReferenceCountedPointer<
ValidateClientHelloResultCallback::Result> result,
std::unique_ptr<ProofSource::Details> /* details */) override {
shlo_verifier_->ValidateClientHelloDone(result);
}
private:
ShloVerifier* shlo_verifier_;
};
std::unique_ptr<ValidateClientHelloCallback>
GetValidateClientHelloCallback() {
return QuicMakeUnique<ValidateClientHelloCallback>(this);
}
private:
void ValidateClientHelloDone(
const QuicReferenceCountedPointer<
ValidateClientHelloResultCallback::Result>& result) {
result_ = result;
crypto_config_->ProcessClientHello(
result_, /*reject_only=*/false,
/*connection_id=*/QuicConnectionIdFromUInt64(1), server_addr_,
client_addr_, AllSupportedVersions().front(), AllSupportedVersions(),
/*use_stateless_rejects=*/true,
/*server_designated_connection_id=*/EmptyQuicConnectionId(), clock_,
QuicRandom::GetInstance(), compressed_certs_cache_, params_,
signed_config_, /*total_framing_overhead=*/50, kDefaultMaxPacketSize,
GetProcessClientHelloCallback());
}
class ProcessClientHelloCallback : public ProcessClientHelloResultCallback {
public:
explicit ProcessClientHelloCallback(ShloVerifier* shlo_verifier)
: shlo_verifier_(shlo_verifier) {}
void Run(
QuicErrorCode error,
const QuicString& error_details,
std::unique_ptr<CryptoHandshakeMessage> message,
std::unique_ptr<DiversificationNonce> diversification_nonce,
std::unique_ptr<ProofSource::Details> proof_source_details) override {
shlo_verifier_->ProcessClientHelloDone(std::move(message));
}
private:
ShloVerifier* shlo_verifier_;
};
std::unique_ptr<ProcessClientHelloCallback> GetProcessClientHelloCallback() {
return QuicMakeUnique<ProcessClientHelloCallback>(this);
}
void ProcessClientHelloDone(std::unique_ptr<CryptoHandshakeMessage> message) {
// Verify output is a SHLO.
EXPECT_EQ(message->tag(), kSHLO)
<< "Fail to pass validation. Get " << message->DebugString();
}
QuicCryptoServerConfig* crypto_config_;
QuicSocketAddress server_addr_;
QuicSocketAddress client_addr_;
const QuicClock* clock_;
QuicReferenceCountedPointer<QuicSignedServerConfig> signed_config_;
QuicCompressedCertsCache* compressed_certs_cache_;
QuicReferenceCountedPointer<QuicCryptoNegotiatedParameters> params_;
QuicReferenceCountedPointer<ValidateClientHelloResultCallback::Result>
result_;
};
class CryptoTestUtilsTest : public QuicTest {};
TEST_F(CryptoTestUtilsTest, TestGenerateFullCHLO) {
MockClock clock;
QuicCryptoServerConfig crypto_config(
QuicCryptoServerConfig::TESTING, QuicRandom::GetInstance(),
crypto_test_utils::ProofSourceForTesting(), KeyExchangeSource::Default(),
TlsServerHandshaker::CreateSslCtx());
QuicSocketAddress server_addr;
QuicSocketAddress client_addr(QuicIpAddress::Loopback4(), 1);
QuicReferenceCountedPointer<QuicSignedServerConfig> signed_config(
new QuicSignedServerConfig);
QuicCompressedCertsCache compressed_certs_cache(
QuicCompressedCertsCache::kQuicCompressedCertsCacheSize);
CryptoHandshakeMessage full_chlo;
QuicCryptoServerConfig::ConfigOptions old_config_options;
old_config_options.id = "old-config-id";
delete crypto_config.AddDefaultConfig(QuicRandom::GetInstance(), &clock,
old_config_options);
QuicCryptoServerConfig::ConfigOptions new_config_options;
std::unique_ptr<QuicServerConfigProtobuf> primary_config(
crypto_config.GenerateConfig(QuicRandom::GetInstance(), &clock,
new_config_options));
primary_config->set_primary_time(clock.WallNow().ToUNIXSeconds());
std::unique_ptr<CryptoHandshakeMessage> msg(
crypto_config.AddConfig(std::move(primary_config), clock.WallNow()));
QuicStringPiece orbit;
ASSERT_TRUE(msg->GetStringPiece(kORBT, &orbit));
QuicString nonce;
CryptoUtils::GenerateNonce(
clock.WallNow(), QuicRandom::GetInstance(),
QuicStringPiece(reinterpret_cast<const char*>(orbit.data()),
sizeof(orbit.size())),
&nonce);
QuicString nonce_hex = "#" + QuicTextUtils::HexEncode(nonce);
char public_value[32];
memset(public_value, 42, sizeof(public_value));
QuicString pub_hex =
"#" + QuicTextUtils::HexEncode(public_value, sizeof(public_value));
QuicTransportVersion version(AllSupportedTransportVersions().front());
CryptoHandshakeMessage inchoate_chlo = crypto_test_utils::CreateCHLO(
{{"PDMD", "X509"},
{"AEAD", "AESG"},
{"KEXS", "C255"},
{"COPT", "SREJ"},
{"PUBS", pub_hex},
{"NONC", nonce_hex},
{"VER\0",
QuicVersionLabelToString(QuicVersionToQuicVersionLabel(version))}},
kClientHelloMinimumSize);
crypto_test_utils::GenerateFullCHLO(
inchoate_chlo, &crypto_config, server_addr, client_addr, version, &clock,
signed_config, &compressed_certs_cache, &full_chlo);
// Verify that full_chlo can pass crypto_config's verification.
ShloVerifier shlo_verifier(&crypto_config, server_addr, client_addr, &clock,
signed_config, &compressed_certs_cache);
crypto_config.ValidateClientHello(
full_chlo, client_addr.host(), server_addr, version, &clock,
signed_config, shlo_verifier.GetValidateClientHelloCallback());
}
} // namespace test
} // namespace quic
|
[
"commit-bot@chromium.org"
] |
commit-bot@chromium.org
|
84d9589d708a257955fab86f2cd369d54fa8ce4f
|
5d83739af703fb400857cecc69aadaf02e07f8d1
|
/Archive2/c8/4c9d4860e87ead/main.cpp
|
f321f1de55152b95fdbf5c1b212e75d9f769aaa0
|
[] |
no_license
|
WhiZTiM/coliru
|
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
|
2c72c048846c082f943e6c7f9fa8d94aee76979f
|
refs/heads/master
| 2021-01-01T05:10:33.812560
| 2015-08-24T19:09:22
| 2015-08-24T19:09:22
| 56,789,706
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 517
|
cpp
|
#include <iostream>
#include <vector>
#include <map>
using namespace std;
typedef vector<int> PrefList;
typedef map<int, PrefList> PrefMap;
typedef multimap<int, int> Matching;
map<int, int> CHcapacity ={{1,1},{2,1},{3,1}};
PrefMap PrefCHLists = {{1,{5,4,6}},{2,{4,6,5}},{3,{4,5,6}}};
PrefMap PrefONLists = {{4,{2,1,3}},{5,{3,1,2}},{6,{1,3,2}}};
int main()
{
Matching match={{1,4},{2,5},{3,6}};
Matching final=RVV(match);
}
Matching RVV(Matching m){
Matching mT=m;
map<int, int> S;
return mT;
}
|
[
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] |
francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df
|
043a3853907dc3f6acecf6f7952a034ca8eaff94
|
efd9e3980a2e8a131c1f1ab64a2f856b9d1bee6a
|
/libraries/ros_lib/diagnostic_msgs/KeyValue.h
|
3c9e64edb91ec9c770dddbbb01ecf4bba842385d
|
[] |
no_license
|
limhyon/arduimu
|
b520688a7132c147eb403473566a42dac719db50
|
b6725463c98a77d3f912de3464921dd5483f8673
|
refs/heads/master
| 2021-01-19T06:06:33.769806
| 2012-07-24T06:40:21
| 2012-07-24T06:40:21
| 5,151,087
| 4
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,736
|
h
|
#ifndef _ROS_diagnostic_msgs_KeyValue_h
#define _ROS_diagnostic_msgs_KeyValue_h
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include "ros/msg.h"
namespace diagnostic_msgs
{
class KeyValue : public ros::Msg
{
public:
char * key;
char * value;
virtual int serialize(unsigned char *outbuffer) const
{
int offset = 0;
uint32_t * length_key = (uint32_t *)(outbuffer + offset);
*length_key = strlen( (const char*) this->key);
offset += 4;
memcpy(outbuffer + offset, this->key, *length_key);
offset += *length_key;
uint32_t * length_value = (uint32_t *)(outbuffer + offset);
*length_value = strlen( (const char*) this->value);
offset += 4;
memcpy(outbuffer + offset, this->value, *length_value);
offset += *length_value;
return offset;
}
virtual int deserialize(unsigned char *inbuffer)
{
int offset = 0;
uint32_t length_key = *(uint32_t *)(inbuffer + offset);
offset += 4;
for(unsigned int k= offset; k< offset+length_key; ++k){
inbuffer[k-1]=inbuffer[k];
}
inbuffer[offset+length_key-1]=0;
this->key = (char *)(inbuffer + offset-1);
offset += length_key;
uint32_t length_value = *(uint32_t *)(inbuffer + offset);
offset += 4;
for(unsigned int k= offset; k< offset+length_value; ++k){
inbuffer[k-1]=inbuffer[k];
}
inbuffer[offset+length_value-1]=0;
this->value = (char *)(inbuffer + offset-1);
offset += length_value;
return offset;
}
const char * getType(){ return "diagnostic_msgs/KeyValue"; };
const char * getMD5(){ return "cf57fdc6617a881a88c16e768132149c"; };
};
}
#endif
|
[
"limhyon@gmail.com"
] |
limhyon@gmail.com
|
4e4c1614bd9650cdf9cff4d6a92716dffb2fb73b
|
01c029e89f2cec46f093e2766c3856339be022f2
|
/TSLS_Edit_Distance.cpp
|
52c5fce7144a010a01dfb0e2cf4f831f308b6e28
|
[] |
no_license
|
XiaoXiaoLui/LeetCode
|
f16c6213aa88b0454fb919cdf460fec74bb8ba60
|
f0c3c2f654571655075a21e0b02465a02caf7cb3
|
refs/heads/master
| 2021-01-11T02:08:42.353447
| 2016-10-26T09:28:49
| 2016-10-26T09:28:49
| 70,828,096
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,364
|
cpp
|
/******************************************************************************************
Edit Distance
******************************************************************************************/
#include <iostream>
#include <cstdio>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <string>
#include <cmath>
#include <cstring>
#include <queue>
#include <ctime>
using namespace std;
#define pii pair<int, int>
#define mp make_pair
typedef long long ll;
class Solution {
public:
int minDistance(string word1, string word2) {
dp.clear();
return solve(word1, word2, 0, 0);
}
int solve(const string &s1, const string &s2, int i, int j)
{
if (i >= s1.size())
{
return s2.size() - j;
}
if (j >= s2.size())
{
return s1.size() - i;
}
map<pii, int>::iterator iter;
if ((iter = dp.find(mp(i, j))) != dp.end())
{
return iter->second;
}
int res = 0;
if (s1[i] == s2[j])
{
res = solve(s1, s2, i + 1, j + 1);
}
else
{
res = solve(s1, s2, i + 1, j + 1) + 1; // modify
res = min(res, solve(s1, s2, i, j + 1) + 1); // insert
res = min(res, solve(s1, s2, i + 1, j) + 1); // erase
}
dp[mp(i, j)] = res;
return res;
}
map<pii, int> dp;
};
int main()
{
Solution S;
return 0;
}
|
[
"980821718@qq.com"
] |
980821718@qq.com
|
8b620a29dcb24dbb05d38ad71a6517f2eb01d1ed
|
2851759f8e9b36197858e9ae5307ea6239da5e2e
|
/system/ulib/fbl/include/fbl/unique_fd.h
|
d9e5b771e1ad96121de7e9468d57fe79181b6a28
|
[
"BSD-3-Clause",
"MIT"
] |
permissive
|
Allegra42/zircon
|
a1a809f005c04d4cf2af672c47a2f13161848ca0
|
50d20f11275ecdd47faa393e3ff6465cee07a670
|
refs/heads/master
| 2020-04-05T08:02:40.558430
| 2018-12-29T00:28:46
| 2018-12-29T23:42:27
| 156,698,935
| 1
| 1
|
NOASSERTION
| 2018-11-08T11:48:25
| 2018-11-08T11:48:24
| null |
UTF-8
|
C++
| false
| false
| 1,936
|
h
|
// Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include <stdlib.h>
#include <unistd.h>
#include <fbl/macros.h>
#include <fbl/type_support.h>
namespace fbl {
// A scoped file descriptor that automatically closes when it goes
// out of scope.
class unique_fd {
public:
constexpr unique_fd() : fd_(InvalidValue()) {}
explicit unique_fd(int fd) : fd_(fd) { }
static constexpr int InvalidValue() { return -1; }
~unique_fd() {
reset();
}
unique_fd(unique_fd&& o) : fd_(o.release()) {}
unique_fd& operator=(unique_fd&& o) {
reset(o.release());
return *this;
}
// Comparison against raw file descriptors (of the form fd == unique_fd)
bool operator==(int fd) const { return (fd_ == fd); }
bool operator!=(int fd) const { return (fd_ != fd); }
// Comparison against other unique_fd's.
bool operator==(const unique_fd& o) const { return fd_ == o.fd_; }
bool operator!=(const unique_fd& o) const { return fd_ != o.fd_; }
// move semantics only
DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(unique_fd);
fbl::unique_fd duplicate() {
return fbl::unique_fd(dup(fd_));
}
int release() {
int t = fd_;
fd_ = InvalidValue();
return t;
}
void reset(int t = InvalidValue()) {
if (fd_ != InvalidValue()) {
close(fd_);
}
fd_ = t;
}
void swap(unique_fd& other) {
int t = fd_;
fd_ = other.fd_;
other.fd_ = t;
}
int get() const {
return fd_;
}
bool is_valid() const {
return fd_ != InvalidValue();
}
explicit operator bool() const {
return is_valid();
}
explicit operator int() const {
return fd_;
}
private:
int fd_;
};
} // namespace fbl
|
[
"commit-bot@chromium.org"
] |
commit-bot@chromium.org
|
9c125f406393c4a12f5ca023356aaee03d52f126
|
56b65fbf1880a8323ab7dc15c9694d5975d2cd2c
|
/src/crypto/sha256.h
|
d5c89a6da03ec1759045af8679e45059f00a6d7d
|
[
"MIT"
] |
permissive
|
btclambo/BitcoinLambo
|
3e4043e9486ea42401f7d38fc5d5ebbbb38b005e
|
fc823516765338f06bce5ad8c7e3a5d6fe90f22b
|
refs/heads/master
| 2020-03-06T18:31:07.897658
| 2018-03-27T15:34:49
| 2018-03-27T15:34:49
| 127,008,721
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 836
|
h
|
// Copyright (c) 2014-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOINLAMBO_CRYPTO_SHA256_H
#define BITCOINLAMBO_CRYPTO_SHA256_H
#include <stdint.h>
#include <stdlib.h>
#include <string>
/** A hasher class for SHA-256. */
class CSHA256
{
private:
uint32_t s[8];
unsigned char buf[64];
uint64_t bytes;
public:
static const size_t OUTPUT_SIZE = 32;
CSHA256();
CSHA256& Write(const unsigned char* data, size_t len);
void Finalize(unsigned char hash[OUTPUT_SIZE]);
CSHA256& Reset();
};
/** Autodetect the best available SHA256 implementation.
* Returns the name of the implementation.
*/
std::string SHA256AutoDetect();
#endif // BITCOINLAMBO_CRYPTO_SHA256_H
|
[
"alfa.alvaro.rodriguez@gmail.com"
] |
alfa.alvaro.rodriguez@gmail.com
|
2c2c448a1761a7c240a35e6418b63c42d0432e29
|
556f83e394cd722ec5cc852e69adb12d2a0c78d1
|
/code/TimePredef.hpp
|
a937e3b194a031c85bb48b95452398a2cd876d61
|
[
"MIT"
] |
permissive
|
BiEchi/Programming-Assignment-1
|
aee2b506483fe34c242ff3468af7a48d88705edc
|
1d340ee27d7177062215e60dc4666ee72cb91dd2
|
refs/heads/main
| 2023-04-26T02:14:54.398342
| 2021-05-27T10:58:33
| 2021-05-27T10:58:33
| 368,122,637
| 1
| 0
|
MIT
| 2021-05-17T09:07:25
| 2021-05-17T09:07:24
| null |
UTF-8
|
C++
| false
| false
| 266
|
hpp
|
//
// TimePredef.hpp
// code
//
// Created by Jack's Macbook Pro on 2021/3/25.
//
#ifndef TimePredef_hpp
#define TimePredef_hpp
#include <iostream>
#include <cstring>
#include <ctime>
using namespace std;
extern time_t startTime;
#endif /* TimePredef_hpp */
|
[
"Haob.19@intl.zju.edu.cn"
] |
Haob.19@intl.zju.edu.cn
|
fb9500ab979c18b3d332614585aa4fafaa74ed60
|
ea99679b342d457b22832672e61eecb18512b25d
|
/src/core_write.cpp
|
8579ee84c9ffc42bc5b2eadd18107897fdac16bf
|
[
"MIT"
] |
permissive
|
eletaNetwork/eletaNetwork
|
ab5cb586c8ce13380eba1eaa58327e3ecb9ec755
|
c589089d189215d83a34534c82878d39b7cdda96
|
refs/heads/master
| 2020-03-08T19:27:51.153812
| 2018-04-13T06:01:43
| 2018-04-13T06:01:43
| 128,353,833
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,565
|
cpp
|
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "core_io.h"
#include "base58.h"
#include "primitives/transaction.h"
#include "script/script.h"
#include "script/standard.h"
#include "serialize.h"
#include "streams.h"
#include <univalue.h>
#include "util.h"
#include "utilmoneystr.h"
#include "utilstrencodings.h"
#include <boost/assign/list_of.hpp>
#include <boost/foreach.hpp>
using namespace std;
string FormatScript(const CScript& script)
{
string ret;
CScript::const_iterator it = script.begin();
opcodetype op;
while (it != script.end()) {
CScript::const_iterator it2 = it;
vector<unsigned char> vch;
if (script.GetOp2(it, op, &vch)) {
if (op == OP_0) {
ret += "0 ";
continue;
} else if ((op >= OP_1 && op <= OP_16) || op == OP_1NEGATE) {
ret += strprintf("%i ", op - OP_1NEGATE - 1);
continue;
} else if (op >= OP_NOP && op <= OP_NOP10) {
string str(GetOpName(op));
if (str.substr(0, 3) == string("OP_")) {
ret += str.substr(3, string::npos) + " ";
continue;
}
}
if (vch.size() > 0) {
ret += strprintf("0x%x 0x%x ", HexStr(it2, it - vch.size()), HexStr(it - vch.size(), it));
} else {
ret += strprintf("0x%x ", HexStr(it2, it));
}
continue;
}
ret += strprintf("0x%x ", HexStr(it2, script.end()));
break;
}
return ret.substr(0, ret.size() - 1);
}
const map<unsigned char, string> mapSigHashTypes =
boost::assign::map_list_of
(static_cast<unsigned char>(SIGHASH_ALL), string("ALL"))
(static_cast<unsigned char>(SIGHASH_ALL|SIGHASH_ANYONECANPAY), string("ALL|ANYONECANPAY"))
(static_cast<unsigned char>(SIGHASH_NONE), string("NONE"))
(static_cast<unsigned char>(SIGHASH_NONE|SIGHASH_ANYONECANPAY), string("NONE|ANYONECANPAY"))
(static_cast<unsigned char>(SIGHASH_SINGLE), string("SINGLE"))
(static_cast<unsigned char>(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY), string("SINGLE|ANYONECANPAY"))
;
/**
* Create the assembly string representation of a CScript object.
* @param[in] script CScript object to convert into the asm string representation.
* @param[in] fAttemptSighashDecode Whether to attempt to decode sighash types on data within the script that matches the format
* of a signature. Only pass true for scripts you believe could contain signatures. For example,
* pass false, or omit the this argument (defaults to false), for scriptPubKeys.
*/
string ScriptToAsmStr(const CScript& script, const bool fAttemptSighashDecode)
{
string str;
opcodetype opcode;
vector<unsigned char> vch;
CScript::const_iterator pc = script.begin();
while (pc < script.end()) {
if (!str.empty()) {
str += " ";
}
if (!script.GetOp(pc, opcode, vch)) {
str += "[error]";
return str;
}
if (0 <= opcode && opcode <= OP_PUSHDATA4) {
if (vch.size() <= static_cast<vector<unsigned char>::size_type>(4)) {
str += strprintf("%d", CScriptNum(vch, false).getint());
} else {
// the IsUnspendable check makes sure not to try to decode OP_RETURN data that may match the format of a signature
if (fAttemptSighashDecode && !script.IsUnspendable()) {
string strSigHashDecode;
// goal: only attempt to decode a defined sighash type from data that looks like a signature within a scriptSig.
// this won't decode correctly formatted public keys in Pubkey or Multisig scripts due to
// the restrictions on the pubkey formats (see IsCompressedOrUncompressedPubKey) being incongruous with the
// checks in CheckSignatureEncoding.
if (CheckSignatureEncoding(vch, SCRIPT_VERIFY_STRICTENC, NULL)) {
const unsigned char chSigHashType = vch.back();
if (mapSigHashTypes.count(chSigHashType)) {
strSigHashDecode = "[" + mapSigHashTypes.find(chSigHashType)->second + "]";
vch.pop_back(); // remove the sighash type byte. it will be replaced by the decode.
}
}
str += HexStr(vch) + strSigHashDecode;
} else {
str += HexStr(vch);
}
}
} else {
str += GetOpName(opcode);
}
}
return str;
}
string EncodeHexTx(const CTransaction& tx)
{
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
return HexStr(ssTx.begin(), ssTx.end());
}
void ScriptPubKeyToUniv(const CScript& scriptPubKey,
UniValue& out, bool fIncludeHex)
{
txnouttype type;
vector<CTxDestination> addresses;
int nRequired;
out.pushKV("asm", ScriptToAsmStr(scriptPubKey));
if (fIncludeHex)
out.pushKV("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end()));
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) {
out.pushKV("type", GetTxnOutputType(type));
return;
}
out.pushKV("reqSigs", nRequired);
out.pushKV("type", GetTxnOutputType(type));
UniValue a(UniValue::VARR);
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CEletaCoinAddress(addr).ToString());
out.pushKV("addresses", a);
}
void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry)
{
entry.pushKV("txid", tx.GetHash().GetHex());
entry.pushKV("version", tx.nVersion);
entry.pushKV("locktime", (int64_t)tx.nLockTime);
UniValue vin(UniValue::VARR);
BOOST_FOREACH(const CTxIn& txin, tx.vin) {
UniValue in(UniValue::VOBJ);
if (tx.IsCoinBase())
in.pushKV("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()));
else {
in.pushKV("txid", txin.prevout.hash.GetHex());
in.pushKV("vout", (int64_t)txin.prevout.n);
UniValue o(UniValue::VOBJ);
o.pushKV("asm", ScriptToAsmStr(txin.scriptSig, true));
o.pushKV("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()));
in.pushKV("scriptSig", o);
}
in.pushKV("sequence", (int64_t)txin.nSequence);
vin.push_back(in);
}
entry.pushKV("vin", vin);
UniValue vout(UniValue::VARR);
for (unsigned int i = 0; i < tx.vout.size(); i++) {
const CTxOut& txout = tx.vout[i];
UniValue out(UniValue::VOBJ);
UniValue outValue(UniValue::VNUM, FormatMoney(txout.nValue));
out.pushKV("value", outValue);
out.pushKV("n", (int64_t)i);
UniValue o(UniValue::VOBJ);
ScriptPubKeyToUniv(txout.scriptPubKey, o, true);
out.pushKV("scriptPubKey", o);
vout.push_back(out);
}
entry.pushKV("vout", vout);
if (!hashBlock.IsNull())
entry.pushKV("blockhash", hashBlock.GetHex());
entry.pushKV("hex", EncodeHexTx(tx)); // the hex-encoded transaction. used the name "hex" to be consistent with the verbose output of "getrawtransaction".
}
|
[
"38124337+eletaNetwork@users.noreply.github.com"
] |
38124337+eletaNetwork@users.noreply.github.com
|
501844de141de05c90c316318bcc0518f613db88
|
4122acc5bd9ee517fdfd1307bf8a04cc7c95599c
|
/mindspore/lite/src/ops/populate/common_populate.cc
|
8255473969877758af39d56eb1260e012a3b3039
|
[
"Apache-2.0",
"MIT",
"Libpng",
"LicenseRef-scancode-proprietary-license",
"LGPL-2.1-only",
"AGPL-3.0-only",
"MPL-2.0-no-copyleft-exception",
"IJG",
"Zlib",
"MPL-1.1",
"BSD-3-Clause",
"BSD-3-Clause-Open-MPI",
"MPL-1.0",
"GPL-2.0-only",
"MPL-2.0",
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] |
permissive
|
limberc/mindspore
|
655bb4fc582a85711e70c31e12f611cf1a0f422e
|
e294acdffc9246cb6d77ea18ea00d08244d30c59
|
refs/heads/master
| 2023-02-18T20:10:22.588348
| 2021-01-23T15:33:01
| 2021-01-23T15:33:01
| 322,821,027
| 0
| 0
|
Apache-2.0
| 2021-01-18T14:07:45
| 2020-12-19T10:27:43
| null |
UTF-8
|
C++
| false
| false
| 1,248
|
cc
|
/**
* Copyright 2019-2020 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/ops/primitive_c.h"
#include "src/ops/populate/populate_register.h"
namespace mindspore {
namespace lite {
OpParameter *PopulateCommonParameter(const mindspore::lite::PrimitiveC *primitive) {
auto *common_parameter = reinterpret_cast<OpParameter *>(malloc(sizeof(OpParameter)));
if (common_parameter == nullptr) {
MS_LOG(ERROR) << "malloc OpParameter failed.";
return nullptr;
}
memset(common_parameter, 0, sizeof(OpParameter));
return common_parameter;
}
Registry ZerosLikeParameterRegistry(schema::PrimitiveType_ZerosLike, PopulateCommonParameter);
} // namespace lite
} // namespace mindspore
|
[
"yeyunpeng2020@huawei.com"
] |
yeyunpeng2020@huawei.com
|
73bf4e0f6fbdf976be867badea6ddbefe469dacc
|
f69cec4bcba5618871d0eb21c94f62070e6208f1
|
/Exams/2021.2.09/C.cpp
|
526a6a18ab153d275821994e858a87b70d50a986
|
[] |
no_license
|
accoder666/temp
|
10204075f7081b7e25bd858df3b9f7d258779d7b
|
b38dcb9a45282503541c5fdb79d2f066ce2736c1
|
refs/heads/main
| 2023-07-02T17:14:37.053741
| 2021-08-11T03:31:44
| 2021-08-11T03:31:44
| 394,850,718
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,808
|
cpp
|
#include <cctype>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 1000010, sigma_size = 26;
struct node {
int len, link;
int nxt[sigma_size];
};
node t[maxn << 1];
int cnt, last;
int siz[maxn << 1];
struct edge {
int to, nxt;
};
edge G[maxn << 1];
int head[maxn << 1], Gcnt;
long long dfs(const int&);
int main() {
freopen("sub.in", "r", stdin);
freopen("sub.out", "w", stdout);
t[0].len = 0, t[0].link = -1, last = 0;
char ch = getchar();
while (!islower(ch)) ch = getchar();
int cur, u, v, c;
while (islower(ch)) {
t[cur = ++cnt].len = t[last].len + 1;
siz[cur] = 1;
u = last;
while (u != -1 && !t[u].nxt[ch - 'a']) t[u].nxt[ch - 'a'] = cur, u = t[u].link;
if (u == -1)
t[cur].link = 0;
else {
v = t[u].nxt[ch - 'a'];
if (t[u].len + 1 == t[v].len)
t[cur].link = v;
else {
c = ++cnt;
t[c].len = t[u].len + 1;
t[c].link = t[v].link;
memcpy(t[c].nxt, t[v].nxt, sizeof(t[c].nxt));
while (u != -1 && t[u].nxt[ch - 'a'] == v) t[u].nxt[ch - 'a'] = c, u = t[u].link;
t[v].link = t[cur].link = c;
}
}
last = cur;
ch = getchar();
}
for (int i = 1; i <= cnt; i++) G[++Gcnt] = { i, head[t[i].link] }, head[t[i].link] = Gcnt;
printf("%lld\n", dfs(0));
return 0;
}
long long dfs(const int& u) {
long long ret = 0, tmp;
for (int i = head[u]; i; i = G[i].nxt) {
if ((tmp = dfs(G[i].to)) > ret)
ret = tmp;
siz[u] += siz[G[i].to];
}
if (siz[u] != 1 && ret < (long long)siz[u] * t[u].len)
ret = (long long)siz[u] * t[u].len;
return ret;
}
|
[
"2201685475@qq.com"
] |
2201685475@qq.com
|
923877562aab22dd4dee8024f595fac6143df562
|
834abb946ce963e5922f1b683ac027fa4c6d9fe2
|
/Project2/JeffGrockowskiProject2.cpp
|
fab5df755ebf54a7bc1f244e5b30e66e669c13f1
|
[] |
no_license
|
JeffGrock/BMI_calculator
|
1cb1f082bf41d7650258b4d7dd614e4ac17f8d4e
|
6e0b3a67d5c8c60d7fad2472611003732ce8fb35
|
refs/heads/main
| 2023-03-12T05:00:00.642667
| 2021-02-25T18:11:06
| 2021-02-25T18:11:06
| 342,336,090
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,087
|
cpp
|
// Author: Jeff Grockowski
// Date: 06/10/2019
// CSCI 121 project 2
// Program allows user to calculate BMI, and the amount chocolate they can eat.
#include <iostream>
#include <string>
using namespace std;
int main() {
int const chocolateBarCal(230);
int weight, height, age;
double BMR, cBarsPerBMI;
string gender("A"), repeat("Y");
while((repeat == "Y") || (repeat == "y")) // While loop for entire program,
{ // allows user to repeat program until user changes the "repeat" variable through input at the end of the program
cout << "Welcome to my BMR calculator!\n";
cout << "Gender (M or F):";
cin >> gender;
while ((gender != "F") && (gender != "M") && (gender != "m") && (gender != "f")) // loop to ensure user entry matches one of the two BMI equations
{
cout << "invalid gender.\n";
cout << "Gender (M or F):";
cin >> gender;
}
cout << "Age (In years):"; // this block obtains the rest of the variables for BMR equation,
cin >> age; // this information pertains to both genders
cout << "Weight (in pounds):";
cin >> weight;
cout << "Height (In inches):";
cin >> height;
cout << endl;
if ((gender == "M") || (gender == "m")) // if else structure calculates the BMR and tells user the result based on gender input
{ // the else block is the female calculation
BMR = 66 + (6.3 * weight) + (12.9 * height) - (6.8 * age);
cBarsPerBMI = BMR / chocolateBarCal;
cout << "He needs " << BMR << " calories to maintain his weight.\n";
}
else
{
BMR = 655 + (4.3 * weight) + (4.7 * height) - (4.7 * age);
cBarsPerBMI = BMR / chocolateBarCal;
cout << "She needs " << BMR << " calories to maintain her weight.\n";
}
cout << "that is about " << cBarsPerBMI << " Chocolate bar's calories!\n"; // this block tells user the chocolate bars worth of BMI
cout << "would you like to do another calculation? (Y or N): "; // also confirms if user would like to recalculate.
cin >> repeat;
cout << endl;
}
cout << "Thanks for using my BMR calculator, Good Bye!\n";
return 0;
}
|
[
"jeff.grockowski@protonmail.com"
] |
jeff.grockowski@protonmail.com
|
d20ba589794b48efbaef3d6c5034d2548ae2dee6
|
aead066f3cfa3491e1c3d4b6b4189a7e08868ff6
|
/src/socket/Connection.h
|
f92c747469761752a08cca5c9daccba19bb1a132
|
[] |
no_license
|
thushear/AsyncWebServer
|
e0547954189d1911fd0f37c7a9bdd9a5ed507ebf
|
05f02f73fb45a85a83659515b8e78b602beef103
|
refs/heads/master
| 2021-01-18T23:52:48.480570
| 2015-06-02T08:51:42
| 2015-06-02T08:51:42
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,658
|
h
|
//
// Created by plter on 5/21/15.
//
#pragma once
#include <boost/asio/ip/tcp.hpp>
#include "ConnectionManager.h"
#include "Buffer.h"
namespace aws {
class ConnectionManager;
class OnSocketListener;
class Connection :public std::enable_shared_from_this<aws::Connection>{
friend class ServerSocket;
friend class ConnectionManager;
public:
typedef std::shared_ptr<aws::Connection> ConnectionPtr;
typedef std::function<void(ConnectionPtr socket,aws::InputBuffer & buffer,std::size_t bytes_transferred)> OnReceiveHandler;
private:
Connection(std::shared_ptr<boost::asio::ip::tcp::socket> asioSocket);
static std::shared_ptr<aws::Connection> create(std::shared_ptr<boost::asio::ip::tcp::socket> asioSocket_);
public:
virtual ~Connection();
public:
std::shared_ptr<boost::asio::ip::tcp::socket> getAsioSocket();
void start();
void close();
inline bool isClosed(){
return !running_;
}
public://set/get functions
inline void setConnectionManager(std::shared_ptr<aws::ConnectionManager> manager){
connection_manager_ = manager;
}
inline std::shared_ptr<aws::ConnectionManager> getConnectionManager(){
return connection_manager_;
}
inline void setOnCloseHandler(std::function<void(std::shared_ptr<aws::Connection> socket)> handler){
onCloseHandler_ = handler;
}
inline std::function<void(std::shared_ptr<aws::Connection> socket)> getOnCloseHandler(){
return onCloseHandler_;
}
inline void setOnConnectHandler(std::function<void(std::shared_ptr<aws::Connection> socket)> handler){
onConnectHandler_ = handler;
}
inline std::function<void(std::shared_ptr<aws::Connection> socket)> getOnConnectHandler(){
return onConnectHandler_;
}
inline void setOnReceiveHandler(OnReceiveHandler handler){
onReceiveHandler_ = handler;
}
inline OnReceiveHandler getOnReceiveHandler(){
return onReceiveHandler_;
}
protected:
void onClose();
void onConnect();
private:
void do_receive();
private:
std::shared_ptr<boost::asio::ip::tcp::socket> asioSocket_;
aws::InputBuffer buffer_;
std::shared_ptr<aws::ConnectionManager> connection_manager_;
bool running_;
std::function<void(ConnectionPtr socket)> onCloseHandler_;
std::function<void(ConnectionPtr socket)> onConnectHandler_;
OnReceiveHandler onReceiveHandler_;
};
}
|
[
"xtiqin@163.com"
] |
xtiqin@163.com
|
1d5d9ed7db6942bd48206e99fe56c4dc4ad4c19d
|
e5f57aae37a480cf40180d0a5664aaab5a0c0341
|
/vaca/Component.cpp
|
a5ec932ebb891f3811b06b8dfed1d899b11ca0bc
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
TheLightWay/vaca
|
6ddabf0cd12a46583b03cddc99d2b13da87a4e41
|
95728e6a5c41d9fe2c731f7767b7334b623f41ed
|
refs/heads/master
| 2023-06-10T09:47:28.085286
| 2023-04-12T02:52:15
| 2023-04-12T02:52:15
| 149,952,301
| 0
| 0
|
MIT
| 2018-09-23T05:56:48
| 2018-09-23T05:56:48
| null |
UTF-8
|
C++
| false
| false
| 1,609
|
cpp
|
// Vaca - Visual Application Components Abstraction
// Copyright (c) 2005-2010 David Capello
//
// This file is distributed under the terms of the MIT license,
// please read LICENSE.txt for more information.
#include "vaca/Component.h"
#include "vaca/SharedPtr.h"
#include "vaca/Property.h"
#include "vaca/Debug.h"
using namespace vaca;
/**
Creates a new component.
With the debug version of the library, you will get in the
@ref page_debug_log a line specifying when the component
was created.
*/
Component::Component()
{
VACA_TRACE("new Component (%p)\n", this);
}
/**
Destroys the component.
With the debug version of the library, you will get in the
@ref page_debug_log a line specifying when the component
was destroyed.
*/
Component::~Component()
{
VACA_TRACE("delete Component (%p)\n", this);
}
PropertyPtr Component::getProperty(const String& name)
{
Properties::iterator it = m_properties.find(name);
if (it != m_properties.end())
return it->second;
else
return PropertyPtr();
}
void Component::setProperty(PropertyPtr property)
{
m_properties[property->getName()] = property;
}
bool Component::hasProperty(const String& name)
{
Properties::iterator it = m_properties.find(name);
return it != m_properties.end();
}
void Component::removeProperty(const String& name)
{
Properties::iterator it = m_properties.find(name);
if (it != m_properties.end())
m_properties.erase(it);
}
const Component::Properties& Component::getProperties() const
{
return m_properties;
}
|
[
"davidcapello@gmail.com"
] |
davidcapello@gmail.com
|
b0371dbaf93a6e2ff33dcb6900bc8b6073b20fed
|
8447d06d0d5da3db2b3aae926ec66409b38fb140
|
/3rdPartLib/g2o/g2o/examples/slam2d/main_window.cpp
|
0ad4e0d898354b1ea8b789f6efba1ee3a10d1379
|
[
"GPL-3.0-or-later",
"LGPL-3.0-or-later",
"BSD-3-Clause",
"GPL-1.0-or-later",
"BSD-2-Clause"
] |
permissive
|
HKPolyU-UAV/FLVIS
|
60d0fecac6e10eb19a131d589a5c0ddf89198157
|
4ad31bbe5191ae2763c70a641c31337b1e06c9e2
|
refs/heads/master
| 2023-07-21T11:11:05.885918
| 2023-07-12T14:26:32
| 2023-07-12T14:26:32
| 197,144,164
| 145
| 37
|
BSD-2-Clause
| 2021-06-07T08:45:04
| 2019-07-16T07:33:55
|
C++
|
UTF-8
|
C++
| false
| false
| 3,766
|
cpp
|
// g2o - General Graph Optimization
// Copyright (C) 2011 R. Kuemmerle, G. Grisetti, W. Burgard
//
// This file is part of g2o.
//
// g2o is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// g2o is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with g2o. If not, see <http://www.gnu.org/licenses/>.
#include "main_window.h"
//#include "moc_main_window.cpp"
#include "g2o/core/sparse_optimizer.h"
#include "g2o/core/estimate_propagator.h"
#include <QFileDialog>
#include <fstream>
#include <iostream>
using namespace std;
MainWindow::MainWindow(QWidget * parent, Qt::WindowFlags flags) :
QMainWindow(parent, flags)
{
setupUi(this);
}
MainWindow::~MainWindow()
{
}
void MainWindow::on_actionLoad_triggered(bool)
{
viewer->graph->clear();
QString filename = QFileDialog::getOpenFileName(this, "Load g2o file", "", "g2o files (*.g2o);;All Files (*)");
if (! filename.isNull()) {
ifstream ifs(filename.toStdString().c_str());
viewer->graph->load(ifs);
cerr << "Graph loaded with " << viewer->graph->vertices().size() << " vertices and "
<< viewer->graph->edges().size() << " measurments" << endl;
}
viewer->update();
fixGraph();
}
void MainWindow::on_actionSave_triggered(bool)
{
QString filename = QFileDialog::getSaveFileName(this, "Save g2o file", "", "g2o files (*.g2o)");
if (! filename.isNull()) {
ofstream fout(filename.toStdString().c_str());
viewer->graph->save(fout);
if (fout.good())
cerr << "Saved " << filename.toStdString() << endl;
else
cerr << "Error while saving file" << endl;
}
}
void MainWindow::on_actionQuit_triggered(bool)
{
close();
}
void MainWindow::on_btnOptimize_clicked()
{
if (viewer->graph->vertices().size() == 0 || viewer->graph->edges().size() == 0) {
cerr << "Graph has no vertices / egdes" << endl;
return;
}
viewer->graph->initializeOptimization();
if (rbGauss->isChecked())
viewer->graph->setAlgorithm(solverGaussNewton);
else if (rbLevenberg->isChecked())
viewer->graph->setAlgorithm(solverLevenberg);
else
viewer->graph->setAlgorithm(solverGaussNewton);
int maxIterations = spIterations->value();
int iter = viewer->graph->optimize(maxIterations);
if (maxIterations > 0 && !iter){
cerr << "Optimization failed, result might be invalid" << endl;
}
if (cbCovariances->isChecked()) {
// TODO
//viewer->graph->solver()->computeMarginals();
}
viewer->drawCovariance = cbCovariances->isChecked();
viewer->update();
}
void MainWindow::on_btnInitialGuess_clicked()
{
viewer->graph->computeInitialGuess();
viewer->drawCovariance = false;
viewer->update();
}
void MainWindow::fixGraph()
{
if (viewer->graph->vertices().size() == 0 || viewer->graph->edges().size() == 0) {
return;
}
// check for vertices to fix to remove DoF
bool gaugeFreedom = viewer->graph->gaugeFreedom();
g2o::OptimizableGraph::Vertex* gauge = viewer->graph->findGauge();
if (gaugeFreedom) {
if (! gauge) {
cerr << "cannot find a vertex to fix in this thing" << endl;
return;
} else {
cerr << "graph is fixed by node " << gauge->id() << endl;
gauge->setFixed(true);
}
} else {
cerr << "graph is fixed by priors" << endl;
}
viewer->graph->setVerbose(true);
viewer->graph->computeActiveErrors();
}
|
[
"chensy1991@gmail.com"
] |
chensy1991@gmail.com
|
8562389987847c12a04e6b03c90970f9e416eded
|
cfa83be88b6725d9c88d780e08b6392a346f2e15
|
/cs4290/lab2/memory.h
|
d1d3f0371b21e842b8d23fe36cdd3dcab1048860
|
[] |
no_license
|
eugene-voronkov/architecture_projects
|
63a04babd711ecc4c5ce7eb7d79604282b162f3c
|
bb3d5c97ca93affdb471c4ac03509792ff3004c0
|
refs/heads/master
| 2021-01-21T08:09:06.740624
| 2016-01-05T17:06:34
| 2016-01-05T17:06:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,609
|
h
|
#ifndef MEMORY_H
#define MEMORY_H
#include<list>
#include<queue>
#include "knob.h"
#include "all_knobs.h"
typedef enum Mem_Req_State_enum {
MEM_INV,
MEM_NEW,
MEM_DRAM_IN,
MEM_DRAM_SCH,
MEM_DRAM_DONE,
MEM_DRAM_OUT,
MEM_MAX_REQ_STATE,
} Mem_Req_State;
typedef enum Mem_Req_Type_enum {
MRT_IFETCH,
MRT_DFETCH,
MRT_DSTORE,
MRT_IPRF,
MRT_DPRF,
MRT_WB,
MRT_SW_DPRF,
MAX_MEM_REQ_TYPE,
} Mem_Req_Type;
typedef struct mem_req_s {
Mem_Req_State m_state; /**< memory request state */
Mem_Req_Type m_type; /**< request type */
ADDRINT m_addr; /**< request address */
uint8_t m_size; /**< request size */
uint64_t m_rdy_cycle; /**< request ready cycle */
bool m_dirty; /**< wb request? */
bool m_done; /**< request done flag */
uint64_t m_id; /**< unique request id */
} mem_req_s;
typedef struct m_mshr_entry_s {
mem_req_s *m_mem_req;
bool valid;
UINT64 insert_time;
list<Op*> req_ops; /* array to hold request ops */
}m_mshr_entry_s;
typedef struct m_dram_s {
int m_bank_num;
int *m_row_id;
int *m_rdy_cycle;
}m_dram_s;
class memory_c {
public:
list <m_mshr_entry_s *> m_mshr; // mshr is an array of mshr_entries
list <m_mshr_entry_s *> m_mshr_free_list; // a collection of free mshr_entries
int m_mshr_size;
int m_dram_bank_num;
int m_block_size;
uint64_t m_unique_m_count;
list <mem_req_s *> dram_in_queue; /* in to DRAM */
list <mem_req_s *> dram_out_queue; /*out from DRAM */
/* dram structure */
list <mem_req_s *>* dram_bank_sch_queue; /* scheduler buffer for each DRAM bank */
int *dram_bank_open_row;
int *dram_bank_rdy_cycle;
m_mshr_entry_s * allocate_new_mshr_entry(void);
mem_req_s *get_new_mem_req(void);
void run_a_cycle(void);
void send_bus_in_queue(void);
void dram_schedule(void);
void push_dram_sch_queue(void);
void send_bus_out_queue(void);
void fill_queue(void);
void init_mem();
bool insert_mshr(Op *op);
void free_mshr_entry(m_mshr_entry_s *entry);
m_mshr_entry_s *search_matching_mshr(ADDRINT addr);
list<m_mshr_entry_s*>::iterator search_matching_mshr_itr(ADDRINT addr);
bool check_piggyback(Op *op);
bool store_load_forwarding(Op *op);
void dprint_queues(void);
void dprint_dram_banks(void);
};
extern KnobsContainer *g_knobsContainer; /* < knob container > */
extern all_knobs_c *g_knobs; /* < all knob variables > */
#endif // MEMORY_H
|
[
"eugene.voronkov@gmail.com"
] |
eugene.voronkov@gmail.com
|
da17ec3176d8e7c8124f6fcf644569f7dda673f1
|
a42195c736f18bec131f719288994d849d49593a
|
/packed_sphere.cpp
|
80e44f1d12d56014524ed03e4a17b280c9925370
|
[
"MIT"
] |
permissive
|
rishus/fat-spaces-in-sphere-arrangement
|
20966c3bd01435d2b2a83853553ba91863d3d5bf
|
6ef5b6dc22fdcb724226bcb23a5c1649b39a6bdb
|
refs/heads/master
| 2021-08-18T19:58:25.737951
| 2017-11-23T18:36:32
| 2017-11-23T18:36:32
| 111,831,860
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 374
|
cpp
|
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int side = 4;
for(int i = 0; i < side; ++i)
{
for(int j = 0; j < side; ++j)
{
for(int k = 0; k < side; ++k)
{
double x = 2 * i + j%2 + k%2;
double y = sqrt(3.0) * (j + ((1.0/3.0) * (k%2)));
double z = (2 * sqrt(6))/3.0 * k;
cout<<x<<" "<<y<<" "<<z<<endl;
}
}
}
}
|
[
"rishus@vt.edu"
] |
rishus@vt.edu
|
5b0beb00db96cfd62ad6b017f92a9c5a0ee268d5
|
2de8f5ba729a846f8ad5630272dd5b1f3b7b6e44
|
/src/Core/Gpackets/SS/GCSkillToTileOK3.h
|
9a747d26de9e96edf4d3f383d9b0bb936842e1c3
|
[] |
no_license
|
najosky/darkeden-v2-serverfiles
|
dc0f90381404953e3716bf71320a619eb10c3825
|
6e0015f5b8b658697228128543ea145a1fc4c559
|
refs/heads/master
| 2021-10-09T13:01:42.843224
| 2018-12-24T15:01:52
| 2018-12-24T15:01:52
| null | 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 4,894
|
h
|
//////////////////////////////////////////////////////////////////////
//
// Filename : GCSkillToTileOK3.h
// Written By : elca@ewestsoft.com
// Description : 기술 사용자는 볼수 있고, 당한자는 볼 수 없는 패킷
//
//////////////////////////////////////////////////////////////////////
#ifndef __GC_SKILL_TO_TILE_OK_3_H__
#define __GC_SKILL_TO_TILE_OK_3_H__
// include files
#include "Types.h"
#include "Exception.h"
#include "Packet.h"
#include "PacketFactory.h"
//////////////////////////////////////////////////////////////////////
//
// class GCSkillToTileOK3;
//
// 게임서버에서 클라이언트로 자신의 기술이 성공을 알려주기 위한 클래스
//
//////////////////////////////////////////////////////////////////////
class GCSkillToTileOK3 : public Packet {
public :
// constructor
GCSkillToTileOK3() throw();
// destructor
~GCSkillToTileOK3() throw();
public :
// 입력스트림(버퍼)으로부터 데이타를 읽어서 패킷을 초기화한다.
void read(SocketInputStream & iStream) throw(ProtocolException, Error);
// 출력스트림(버퍼)으로 패킷의 바이너리 이미지를 보낸다.
void write(SocketOutputStream & oStream) const throw(ProtocolException, Error);
// execute packet's handler
void execute(Player* pPlayer) throw(ProtocolException, Error);
// get packet id
PacketID_t getPacketID() const throw() { return PACKET_GC_SKILL_TO_TILE_OK_3; }
// get packet's body size
// 최적화시, 미리 계산된 정수를 사용한다.
// PacketSize_t getPacketSize() const throw() { return szSkillType + szObjectID +(szCoord* 2)
// + szDuration + szBYTE + szObjectID* m_CListNum; }
PacketSize_t getPacketSize() const throw() { return szSkillType + szObjectID +(szCoord* 2) + szBYTE;}
// get packet's name
string getPacketName() const throw() { return "GCSkillToTileOK3"; }
// get packet's debug string
string toString() const throw();
// get / set ObjectID
CEffectID_t getObjectID() const throw() { return m_ObjectID; }
void setObjectID(ObjectID_t ObjectID) throw() { m_ObjectID = ObjectID; }
// get / set SkillType
SkillType_t getSkillType() const throw() { return m_SkillType; }
void setSkillType(SkillType_t SkillType) throw() { m_SkillType = SkillType; }
// get / set Duration
// Duration_t getDuration() const throw() { return m_Duration; }
// void setDuration(Duration_t Duration) throw() { m_Duration = Duration; }
// get / set X, Y
Coord_t getX() { return m_X; }
void setX(Coord_t X) { m_X = X; }
Coord_t getY() { return m_Y; }
void setY(Coord_t Y) { m_Y = Y; }
// get / set Creature List Number
// BYTE getCListNum() const throw() { return m_CListNum; }
// void setCListNum(BYTE CListNum) throw() { m_CListNum = CListNum; }
// add / delete Creature List
// void addCListElement(ObjectID_t ObjectID) throw();
// Clear CreatureList
// void clearCList() throw() { m_CList.clear(); m_CListNum = 0; }
// pop front Element in Status List
// ObjectID_t popCListElement() throw() { ObjectID_t CreatureList = m_CList.front(); m_CList.pop_front(); return CreatureList; }
BYTE getGrade() const { return m_Grade; }
void setGrade( BYTE grade ) { m_Grade = grade; }
private :
// CEffectID
ObjectID_t m_ObjectID;
// SkillType
SkillType_t m_SkillType;
// Duration
// Duration_t m_Duration;
// X, Y Position
Coord_t m_X;
Coord_t m_Y;
// CreatureList Element Number
// BYTE m_CListNum;
// Creature List
// list<ObjectID_t> m_CList;
BYTE m_Grade;
};
//////////////////////////////////////////////////////////////////////
//
// class GCSkillToTileOK3Factory;
//
// Factory for GCSkillToTileOK3
//
//////////////////////////////////////////////////////////////////////
class GCSkillToTileOK3Factory : public PacketFactory {
public :
// constructor
GCSkillToTileOK3Factory() throw() {}
// destructor
virtual ~GCSkillToTileOK3Factory() throw() {}
public :
// create packet
Packet* createPacket() throw() { return new GCSkillToTileOK3(); }
// get packet name
string getPacketName() const throw() { return "GCSkillToTileOK3"; }
// get packet id
PacketID_t getPacketID() const throw() { return Packet::PACKET_GC_SKILL_TO_TILE_OK_3; }
// get Packet Max Size
// PacketSize_t getPacketMaxSize() const throw() { return szSkillType + szObjectID +(szCoord* 2)
// + szDuration + szBYTE + szObjectID + 255; }
// get Packet Max Size
PacketSize_t getPacketMaxSize() const throw() { return szSkillType + szObjectID +(szCoord* 2) + szBYTE; }
};
//////////////////////////////////////////////////////////////////////
//
// class GCSkillToTileOK3Handler;
//
//////////////////////////////////////////////////////////////////////
class GCSkillToTileOK3Handler {
public :
// execute packet's handler
static void execute(GCSkillToTileOK3* pGCSkillToTileOK3, Player* pPlayer) throw(Error);
};
#endif
|
[
"paulomatew@gmail.com"
] |
paulomatew@gmail.com
|
bfb7ae2786f011cc2fd99384f16177aee94ff618
|
6ce4add532471bb49d199ea632ed4af377735e38
|
/blif_solve_lib/log.h
|
fa5bf5edd6cca5ca7459ce83e78115a458214950
|
[
"MIT"
] |
permissive
|
appu226/FactorGraph
|
398688f188876eba27a67f327f97e8f0002f856d
|
b7cf6025339247b0d89740540a813097ca32774e
|
refs/heads/master
| 2023-08-17T15:07:21.512438
| 2023-06-18T17:22:11
| 2023-06-18T17:22:11
| 164,322,621
| 0
| 1
|
MIT
| 2023-02-12T21:49:24
| 2019-01-06T15:59:51
|
C++
|
UTF-8
|
C++
| false
| false
| 2,199
|
h
|
/*
Copyright 2019 Parakram Majumdar
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.
*/
#pragma once
#include <iostream>
#include <ctime>
namespace blif_solve {
// Verbosity for logging
enum Verbosity {
QUIET,
ERROR,
WARNING,
INFO,
DEBUG
};
Verbosity getVerbosity();
void setVerbosity(Verbosity verbosity);
Verbosity parseVerbosity(const std::string & verbosity_string);
#define blif_solve_log(verbosity, message) \
if (blif_solve::getVerbosity() >= blif_solve::verbosity) \
{ \
std::cout << "[" << #verbosity << "] " << message << std::endl; \
}
#define blif_solve_log_bdd(verbosity, message, ddm, bdd) \
if (blif_solve::getVerbosity() >= blif_solve::verbosity) \
{ \
std::cout << "[" << #verbosity << "] " << message << std::endl; \
bdd_print_minterms(ddm, bdd); \
}
// ****** Function *******
// duration
// takes a start and end chrono time
// and returns the duration in seconds as a double
// ***********************
template<typename T>
double duration(T const & start)
{
return static_cast<double>(std::clock() - start)/CLOCKS_PER_SEC;
}
inline auto now()
{
return std::clock();
}
} // end namespace blif_solve
|
[
"appu226@yahoo.co.in"
] |
appu226@yahoo.co.in
|
d5fa083e493cb7915d62f1634c4714ae1d76e8a8
|
48070285a8c93a24b4e568c3a45eade50838e6d2
|
/Example/Lua/BindAbstract.cpp
|
9975360a71a909180dd2603519c656878b8a9059
|
[
"MIT"
] |
permissive
|
ternence-li/LightInkLLM
|
8a3c54d4664e0cf64a454c7f8bd22fb4c434adff
|
b4387398b4ce45be0bc2d79ea38d93b81609f7c8
|
refs/heads/master
| 2021-09-21T23:23:09.357179
| 2018-09-02T17:27:49
| 2018-09-02T17:27:49
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,043
|
cpp
|
/* Copyright ChenDong(Wilbur), email <baisaichen@live.com>. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "LuaEngine/LuaEngine.h"
class CppClassAbs
{
public:
CppClassAbs() { LogMessage("new CppClassAbs"); }
virtual ~CppClassAbs() { LogMessage("delete CppClassAbs"); }
virtual void test_abstract() = 0;
};
class CppClassAbsInherit : public CppClassAbs
{
public:
CppClassAbsInherit() { LogMessage("new CppClassAbsInherit"); }
virtual ~CppClassAbsInherit() { LogMessage("delete CppClassAbsInherit"); }
virtual void test_abstract() { LogMessage("call --> virtual void CppClassAbsInherit.test_abstract()"); }
static LightInk::SharedPtrTS<CppClassAbs>::type get_shared() { return LightInk::SharedPtrTS<CppClassAbs>::type(static_cast<CppClassAbs *>(new CppClassAbsInherit)); }
static void check_shared(LightInk::SharedPtrTS<CppClassAbs>::type sp) { LogMessage("SharedPtrTS Use Count = {}", sp.use_count()); }
static int show_class_name(lua_State * L) { LogMessage("ClassName = {}", LightInk::LuaEngine::get_class_name(L, 1)); return 0; }
};
static void bind_cppclass(lua_State * lua)
{
LightInk::LuaModule(lua, "CppClassList")
[
LightInk::LuaRegisterAbstract<CppClassAbs>(lua, "CppClassAbs")
.def(&CppClassAbs::test_abstract, "test_abstract")
];
LightInk::LuaModule(lua, "CppClassList")
[
LightInk::LuaRegister<CppClassAbsInherit, void()>(lua, "CppClassAbsInherit", LightInk::BaseClassStrategy<CppClassAbs>())
.def(CppClassAbsInherit::get_shared, "get_shared")
.def(CppClassAbsInherit::check_shared, "check_shared")
.def(CppClassAbsInherit::show_class_name, "show_class_name")
];
}
void test_bind_abstract()
{
LogDebug("start...call...test_bind_abstract()");
LightInk::LuaEngine le;
le.init();
le.register_module(bind_cppclass);
le.add_package_path("../../Example/Lua/?.lua");
le.require_file("BindAbstract");
LogDebug("over...call...test_bind_abstract()");
}
|
[
"baisaichen@live.com"
] |
baisaichen@live.com
|
f41d41885bab9a639e39fb8071eb7590fdef1d43
|
4d96f3f730ec960a13cccb231ee024b7ac0693bd
|
/printout.cpp
|
abf652b5dc9febe025e74901b1eb9a1fc075860d
|
[
"MIT"
] |
permissive
|
daikai999/stairspeedtest-reborn
|
c21c7b2f44d40ed11697b8a65a7305e4c227542b
|
06fb03ddd68800a77515e8209de0f1f4bff76cac
|
refs/heads/master
| 2020-08-28T14:52:30.561834
| 2019-09-29T15:09:21
| 2019-09-29T15:09:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,479
|
cpp
|
#include <iostream>
#include <fstream>
#include "printout.h"
#include "version.h"
//define print-out messages
struct LOOKUP_ITEM
{
int index;
string info;
};
LOOKUP_ITEM SPEEDTEST_MESSAGES[] = {
{SPEEDTEST_MESSAGE_EOF, "\nSpeed Test done. Press any key to exit..."},
{SPEEDTEST_MESSAGE_WELCOME, "Welcome to Stair Speedtest " VERSION "!\nWhich stair do you want to test today? (Supports single Shadowsocks/ShadowsocksD/ShadowsocksR/V2Ray link and their subscribe links)\nIf you want to test more than one link, separate them with '|'.\nLink: "},
{SPEEDTEST_MESSAGE_MULTILINK, "Multiple link provided, parsing all nodes.\n\n"},
{SPEEDTEST_MESSAGE_FOUNDVMESS, "Found single V2Ray link.\n"},
{SPEEDTEST_MESSAGE_FOUNDSS, "Found single Shadowsocks link.\n"},
{SPEEDTEST_MESSAGE_FOUNDSSR, "Found single ShadowsocksR link.\n"},
{SPEEDTEST_MESSAGE_FOUNDSOCKS, "Found single Socks 5 link.\n"},
{SPEEDTEST_MESSAGE_FOUNDSUB, "Found subscribe link.\n"},
{SPEEDTEST_MESSAGE_FOUNDLOCAL, "Found local configure file.\n"},
{SPEEDTEST_MESSAGE_GROUP, "If you have imported an V2Ray subscribe link which doesn't contain a Group Name, you can specify a custom name below.\nIf you have imported an Shadowsocks/ShadowsocksR link which contains a Group Name, press Enter to skip.\nCustom Group Name: "},
{SPEEDTEST_MESSAGE_GOTSERVER, "\nCurrent Server Group: ?group? Remarks: ?remarks? Index: ?index?/?total?\n"},
{SPEEDTEST_MESSAGE_STARTPING, "Now performing TCP Ping...\n"},
{SPEEDTEST_MESSAGE_STARTGEOIP, "Now performing GeoIP parse...\n"},
{SPEEDTEST_MESSAGE_STARTGPING, "Now performing Google Ping...\n"},
{SPEEDTEST_MESSAGE_STARTSPEED, "Now performing Speed Test...\n"},
{SPEEDTEST_MESSAGE_STARTUPD, "Now performing Upload Test...\n"},
{SPEEDTEST_MESSAGE_GOTRESULT, "Result: DL.Speed: ?speed? Max.Speed: ?maxspeed? UL.Speed: ?ulspeed? Pk.Loss: ?pkloss? Avg.Ping: ?avgping? Google Ping: ?siteping?\n"},
{SPEEDTEST_MESSAGE_TRAFFIC, "Traffic used: ?traffic?\n"},
{SPEEDTEST_MESSAGE_PICSAVING, "Now exporting picture...\n"},
{SPEEDTEST_MESSAGE_PICSAVINGMULTI, "Now exporting picture for group ?id?...\n"},
{SPEEDTEST_MESSAGE_PICSAVED, "Result picture saved to \"?picpath?\".\n"},
{SPEEDTEST_MESSAGE_PICSAVEDMULTI, "Group ?id? result picture saved to \"?picpath?\".\n"},
{SPEEDTEST_MESSAGE_FETCHSUB, "Downloading subscription data...\n"},
{SPEEDTEST_MESSAGE_PARSING, "Parsing configuration file...\n"},
{SPEEDTEST_MESSAGE_BEGIN, "Speed Test will now begin.\n"},
{SPEEDTEST_MESSAGE_GOTGEOIP, "Parsed outbound server ISP: ?isp? Country Code: ?location?\n"},
{SPEEDTEST_ERROR_UNDEFINED, "Undefined error!\n"},
{SPEEDTEST_ERROR_WSAERR, "WSA Startup error!\n"},
{SPEEDTEST_ERROR_SOCKETERR, "Socket error!\n"},
{SPEEDTEST_ERROR_NORECOGLINK, "No valid link found. Please check your link.\n"},
{SPEEDTEST_ERROR_UNRECOGFILE, "This configure file is invalid. Please make sure this is an Shadowsocks/ShadowsocksR/v2rayN configuration file or a standard subscription file.\n"},
{SPEEDTEST_ERROR_NOCONNECTION, "Cannot connect to server.\n"},
{SPEEDTEST_ERROR_INVALIDSUB, "Nothing returned from subscribe link. Please check your subscribe link.\n"},
{SPEEDTEST_ERROR_NONODES, "No nodes found. Please check your subscribe link.\n"},
{SPEEDTEST_ERROR_NORESOLVE, "Cannot resolve server address.\n"},
{SPEEDTEST_ERROR_RETEST, "Speed Test returned no speed. Retesting...\n"},
{SPEEDTEST_ERROR_NOSPEED, "Speed Test returned no speed 2 times. Skipping...\n"},
{SPEEDTEST_ERROR_SUBFETCHERR, "Cannot fetch subscription data with direct connect. Trying with system proxy...\n"},
{SPEEDTEST_ERROR_GEOIPERR, "Cannot fetch GeoIP information. Skipping...\n"},
{-1, ""}
};
LOOKUP_ITEM SPEEDTEST_MESSAGES_RPC[] = {
{SPEEDTEST_MESSAGE_WELCOME, "{\"info\":\"started\"}\n"},
{SPEEDTEST_MESSAGE_EOF, "{\"info\":\"eof\"}\n"},
{SPEEDTEST_MESSAGE_FOUNDVMESS, "{\"info\":\"foundvmess\"}\n"},
{SPEEDTEST_MESSAGE_FOUNDSS, "{\"info\":\"foundss\"}\n"},
{SPEEDTEST_MESSAGE_FOUNDSSR, "{\"info\":\"foundssr\"}\n"},
{SPEEDTEST_MESSAGE_FOUNDSOCKS, "{\"info\":\"foundsocks\"}\n"},
{SPEEDTEST_MESSAGE_FOUNDSUB, "{\"info\":\"foundsub\"}\n"},
{SPEEDTEST_MESSAGE_FOUNDLOCAL, "{\"info\":\"foundlocal\"}\n"},
{SPEEDTEST_MESSAGE_FOUNDUPD, "{\"info\":\"foundupd\"}\n"},
{SPEEDTEST_MESSAGE_GOTSERVER, "{\"info\":\"gotserver\",\"id\":?id?,\"group\":\"?group?\",\"remarks\":\"?remarks?\"}\n"},
{SPEEDTEST_MESSAGE_STARTPING, "{\"info\":\"startping\",\"id\":?id?}\n"},
{SPEEDTEST_MESSAGE_GOTPING, "{\"info\":\"gotping\",\"id\":?id?,\"ping\":\"?avgping?\",\"loss\":\"?pkloss?\"}\n"},
{SPEEDTEST_MESSAGE_STARTGEOIP, "{\"info\":\"startgeoip\",\"id\":?id?}\n"},
{SPEEDTEST_MESSAGE_GOTGEOIP, "{\"info\":\"gotgeoip\",\"id\":?id?,\"isp\":\"?isp?\",\"location\":\"?location?\"}\n"},
{SPEEDTEST_MESSAGE_STARTSPEED, "{\"info\":\"startspeed\",\"id\":?id?}\n"},
{SPEEDTEST_MESSAGE_GOTSPEED, "{\"info\":\"gotspeed\",\"id\":?id?,\"speed\":\"?speed?\",\"maxspeed\":\"?maxspeed?\"}\n"},
{SPEEDTEST_MESSAGE_STARTUPD, "{\"info\":\"startupd\",\"id\":?id?}\n"},
{SPEEDTEST_MESSAGE_GOTUPD, "{\"info\":\"gotupd\",\"id\":?id?,\"ulspeed\":\"?ulspeed?\"}\n"},
{SPEEDTEST_MESSAGE_STARTGPING, "{\"info\":\"startgping\",\"id\":?id?}\n"},
{SPEEDTEST_MESSAGE_GOTGPING, "{\"info\":\"gotgping\",\"id\":?id?,\"ping\":\"?siteping?\"}\n"},
{SPEEDTEST_MESSAGE_TRAFFIC, "(\"info\":\"traffic\",\"size\":\"?traffic?\"}\n"},
{SPEEDTEST_MESSAGE_PICSAVING, "{\"info\":\"picsaving\"}\n"},
{SPEEDTEST_MESSAGE_PICSAVED, "{\"info\":\"picsaved\",\"path\":\"?picpath?\"}\n"},
{SPEEDTEST_MESSAGE_PICSAVEDMULTI, "{\"info\":\"picsaved\",\"path\":\"?picpath?\"}\n"},
{SPEEDTEST_MESSAGE_FETCHSUB, "{\"info\":\"fetchingsub\"}\n"},
{SPEEDTEST_MESSAGE_PARSING, "{\"info\":\"parsing\"}\n"},
{SPEEDTEST_MESSAGE_BEGIN, "{\"info\":\"begintest\"}\n"},
{SPEEDTEST_MESSAGE_PICDATA, "{\"info\":\"picdata\",\"data\":\"?data?\"}\n"},
{SPEEDTEST_ERROR_UNDEFINED, "{\"info\":\"error\",\"reason\":\"undef\"}\n"},
{SPEEDTEST_ERROR_WSAERR, "{\"info\":\"error\",\"reason\":\"wsaerr\"}\n"},
{SPEEDTEST_ERROR_SOCKETERR, "{\"info\":\"error\",\"reason\":\"socketerr\"}\n"},
{SPEEDTEST_ERROR_NORECOGLINK, "{\"info\":\"error\",\"reason\":\"norecoglink\"}\n"},
{SPEEDTEST_ERROR_UNRECOGFILE, "{\"info\":\"error\",\"reason\":\"unrecogfile\"}\n"},
{SPEEDTEST_ERROR_NOCONNECTION, "{\"info\":\"error\",\"reason\":\"noconnection\",\"id\":?id?}\n"},
{SPEEDTEST_ERROR_INVALIDSUB, "{\"info\":\"error\",\"reason\":\"invalidsub\"}\n"},
{SPEEDTEST_ERROR_NONODES, "{\"info\":\"error\",\"reason\":\"nonodes\"}\n"},
{SPEEDTEST_ERROR_NORESOLVE, "{\"info\":\"error\",\"reason\":\"noresolve\",\"id\":?id?}\n"},
{SPEEDTEST_ERROR_RETEST, "{\"info\":\"error\",\"reason\":\"retest\",\"id\":?id?}\n"},
{SPEEDTEST_ERROR_NOSPEED, "{\"info\":\"error\",\"reason\":\"nospeed\",\"id\":?id?}\n"},
{SPEEDTEST_ERROR_SUBFETCHERR, "{\"info\":\"error\",\"reason\":\"subfetcherr\"}\n"},
{SPEEDTEST_ERROR_GEOIPERR, "{\"info\":\"error\",\"reason\":\"geoiperr\",\"id\":?id?}\n"},
{-1, ""}
};
string lookUp(int index, LOOKUP_ITEM *items)
{
int i = 0;
while (0 <= items[i].index) {
if (items[i].index == index)
return items[i].info;
i++;
}
return string("");
}
string lookUp(int index, bool rpcmode)
{
if(rpcmode)
{
return lookUp(index, SPEEDTEST_MESSAGES_RPC);
} else {
return lookUp(index, SPEEDTEST_MESSAGES);
}
}
void printMsg(int index, nodeInfo *node, bool rpcmode)
{
string printout;
printout = lookUp(index, rpcmode);
if(printout.size() == 0)
{
return;
}
printout = replace_all_distinct(printout, "?group?", trim(node->group));
printout = replace_all_distinct(printout, "?remarks?", trim(node->remarks));
printout = replace_all_distinct(printout, "?id?", to_string(node->id));
printout = replace_all_distinct(printout, "?avgping?", node->avgPing);
printout = replace_all_distinct(printout, "?pkloss?", node->pkLoss);
printout = replace_all_distinct(printout, "?siteping?", node->sitePing);
printout = replace_all_distinct(printout, "?speed?", node->avgSpeed);
printout = replace_all_distinct(printout, "?maxspeed?", node->maxSpeed);
printout = replace_all_distinct(printout, "?ulspeed?", node->ulSpeed);
printout = replace_all_distinct(printout, "?traffic?", node->traffic);
if(rpcmode)
printout = replace_all_distinct(printout, "\\", "\\\\");
cout<<printout;
cout.clear();
cout.flush();
}
void printMsgWithDict(int index, bool rpcmode, vector<string> dict, vector<string> trans)
{
string printout;
printout = lookUp(index, rpcmode);
if(printout.size() == 0)
{
return;
}
for(unsigned int i = 0; i < dict.size(); i++)
{
printout = replace_all_distinct(printout, dict[i], trans[i]);
}
if(rpcmode)
printout = replace_all_distinct(printout, "\\", "\\\\");
cout<<printout;
cout.clear();
cout.flush();
}
void printMsgDirect(int index, bool rpcmode)
{
cout<<lookUp(index, rpcmode);
cout.clear();
cout.flush();
}
|
[
"49061470+tindy2013@users.noreply.github.com"
] |
49061470+tindy2013@users.noreply.github.com
|
cb3a5e079c958bd59ae282cd6932723fa1a3975e
|
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
|
/NT/shell/ext/timewarp/util.cpp
|
979e0bc3df4d8aa6f3a602d7b2a4ddb2afec932c
|
[] |
no_license
|
jjzhang166/WinNT5_src_20201004
|
712894fcf94fb82c49e5cd09d719da00740e0436
|
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
|
refs/heads/Win2K3
| 2023-08-12T01:31:59.670176
| 2021-10-14T15:14:37
| 2021-10-14T15:14:37
| 586,134,273
| 1
| 0
| null | 2023-01-07T03:47:45
| 2023-01-07T03:47:44
| null |
UTF-8
|
C++
| false
| false
| 9,065
|
cpp
|
#include "precomp.hxx"
#pragma hdrstop
#include <winnlsp.h> // NORM_STOP_ON_NULL
#include "resource.h"
#include "timewarp.h"
#include "util.h"
DWORD FormatString(LPWSTR *ppszResult, HINSTANCE hInstance, LPCWSTR pszFormat, ...)
{
DWORD dwResult;
va_list args;
LPWSTR pszFormatAlloc = NULL;
if (IS_INTRESOURCE(pszFormat))
{
if (LoadStringAlloc(&pszFormatAlloc, hInstance, PtrToUlong(pszFormat)))
{
pszFormat = pszFormatAlloc;
}
else
{
return 0;
}
}
va_start(args, pszFormat);
dwResult = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_STRING,
pszFormat,
0,
0,
(LPWSTR)ppszResult,
1,
&args);
va_end(args);
LocalFree(pszFormatAlloc);
return dwResult;
}
HRESULT FormatFriendlyDateName(LPWSTR *ppszResult, LPCWSTR pszName, const FILETIME UNALIGNED *pft, DWORD dwDateFlags)
{
WCHAR szDate[MAX_PATH];
SHFormatDateTime(pft, &dwDateFlags, szDate, ARRAYSIZE(szDate));
if (!FormatString(ppszResult, g_hInstance, MAKEINTRESOURCE(IDS_FOLDER_TITLE_FORMAT), pszName, szDate))
{
DWORD dwErr = GetLastError();
return HRESULT_FROM_WIN32(dwErr);
}
return S_OK;
}
void EliminateGMTPathSegment(LPWSTR pszPath)
{
LPWSTR pszGMT = wcsstr(pszPath, SNAPSHOT_MARKER);
if (pszGMT)
{
ASSERT(pszGMT >= pszPath && pszGMT < (pszPath + lstrlenW(pszPath)));
// It's tempting to just say "pszGMT + SNAPSHOT_NAME_LENGTH" here, but
// we might miss an intervening '\0' on a malformed path.
LPWSTR pszSeparator = wcschr(pszGMT, L'\\');
if (pszSeparator)
{
ASSERT(pszSeparator == pszGMT + SNAPSHOT_NAME_LENGTH);
ASSERT(pszSeparator < (pszGMT + lstrlenW(pszGMT)));
pszSeparator++; // skip '\\'
MoveMemory(pszGMT, pszSeparator, (lstrlenW(pszSeparator)+1)*sizeof(WCHAR));
}
else
{
// Truncate here
*pszGMT = L'\0';
// Remove the previous separator if we can
PathRemoveBackslashW(pszPath);
}
}
}
void EliminatePathPrefix(LPWSTR pszPath)
{
// Note that sometimes the "\\?\" is not at the beginning of the
// path. See CTimeWarpProp::_OnView in twprop.cpp.
LPWSTR pszPrefix = wcsstr(pszPath, L"\\\\?\\");
if (pszPrefix)
{
LPWSTR pszDest;
LPWSTR pszSrc;
ASSERT(pszPrefix >= pszPath && pszPrefix < (pszPath + lstrlenW(pszPath)));
if (CSTR_EQUAL == CompareStringW(LOCALE_SYSTEM_DEFAULT,
SORT_STRINGSORT | NORM_IGNORECASE | NORM_STOP_ON_NULL,
pszPrefix+4, 4,
L"UNC\\", 4))
{
// UNC case: preserve the 2 leading backslashes
pszDest = pszPrefix + 2;
pszSrc = pszPrefix + 8;
}
else
{
pszDest = pszPrefix;
pszSrc = pszPrefix + 4;
}
ASSERT(pszDest >= pszPath && pszSrc > pszDest && pszSrc <= (pszPath + lstrlenW(pszPath)));
MoveMemory(pszDest, pszSrc, (lstrlenW(pszSrc)+1)*sizeof(WCHAR));
}
}
HRESULT GetFSIDListFromTimeWarpPath(PIDLIST_ABSOLUTE *ppidlTarget, LPCWSTR pszPath, DWORD dwFileAttributes)
{
HRESULT hr;
LPWSTR pszDup;
hr = SHStrDup(pszPath, &pszDup);
if (SUCCEEDED(hr))
{
// Note that SHSimpleIDListFromPath (which is exported from shell32)
// is not good enough here. It always uses 0 for attributes, but
// we usually need FILE_ATTRIBUTE_DIRECTORY here.
EliminateGMTPathSegment(pszDup);
hr = SimpleIDListFromAttributes(pszDup, dwFileAttributes, ppidlTarget);
LocalFree(pszDup);
}
return hr;
}
class CFileSysBindData : public IFileSystemBindData
{
public:
CFileSysBindData();
// *** IUnknown methods ***
STDMETHODIMP QueryInterface(REFIID riid, void **ppvObj);
STDMETHODIMP_(ULONG) AddRef(void);
STDMETHODIMP_(ULONG) Release(void);
// IFileSystemBindData
STDMETHODIMP SetFindData(const WIN32_FIND_DATAW *pfd);
STDMETHODIMP GetFindData(WIN32_FIND_DATAW *pfd);
private:
~CFileSysBindData();
LONG _cRef;
WIN32_FIND_DATAW _fd;
};
CFileSysBindData::CFileSysBindData() : _cRef(1)
{
ZeroMemory(&_fd, sizeof(_fd));
}
CFileSysBindData::~CFileSysBindData()
{
}
HRESULT CFileSysBindData::QueryInterface(REFIID riid, void **ppv)
{
static const QITAB qit[] = {
QITABENT(CFileSysBindData, IFileSystemBindData), // IID_IFileSystemBindData
{ 0 },
};
return QISearch(this, qit, riid, ppv);
}
STDMETHODIMP_(ULONG) CFileSysBindData::AddRef(void)
{
return InterlockedIncrement(&_cRef);
}
STDMETHODIMP_(ULONG) CFileSysBindData::Release()
{
ASSERT( 0 != _cRef );
ULONG cRef = InterlockedDecrement(&_cRef);
if ( 0 == cRef )
{
delete this;
}
return cRef;
}
HRESULT CFileSysBindData::SetFindData(const WIN32_FIND_DATAW *pfd)
{
_fd = *pfd;
return S_OK;
}
HRESULT CFileSysBindData::GetFindData(WIN32_FIND_DATAW *pfd)
{
*pfd = _fd;
return S_OK;
}
STDAPI SHCreateFileSysBindCtx(const WIN32_FIND_DATAW *pfd, IBindCtx **ppbc)
{
HRESULT hres;
IFileSystemBindData *pfsbd = new CFileSysBindData();
if (pfsbd)
{
if (pfd)
{
pfsbd->SetFindData(pfd);
}
hres = CreateBindCtx(0, ppbc);
if (SUCCEEDED(hres))
{
BIND_OPTS bo = {sizeof(bo)}; // Requires size filled in.
bo.grfMode = STGM_CREATE;
(*ppbc)->SetBindOptions(&bo);
(*ppbc)->RegisterObjectParam(STR_FILE_SYS_BIND_DATA, pfsbd);
}
pfsbd->Release();
}
else
{
*ppbc = NULL;
hres = E_OUTOFMEMORY;
}
return hres;
}
STDAPI SHSimpleIDListFromFindData(LPCWSTR pszPath, const WIN32_FIND_DATAW *pfd, PIDLIST_ABSOLUTE *ppidl)
{
*ppidl = NULL;
IBindCtx *pbc;
HRESULT hr = SHCreateFileSysBindCtx(pfd, &pbc);
if (SUCCEEDED(hr))
{
hr = SHParseDisplayName(pszPath, pbc, ppidl, 0, NULL);
pbc->Release();
}
return hr;
}
STDAPI SimpleIDListFromAttributes(LPCWSTR pszPath, DWORD dwAttributes, PIDLIST_ABSOLUTE *ppidl)
{
WIN32_FIND_DATAW fd = {0};
fd.dwFileAttributes = dwAttributes;
// SHCreateFSIDList(pszPath, &fd, ppidl);
return SHSimpleIDListFromFindData(pszPath, &fd, ppidl);
}
//*************************************************************
//
// SizeofStringResource
//
// Purpose: Find the length (in chars) of a string resource
//
// Parameters: HINSTANCE hInstance - module containing the string
// UINT idStr - ID of string
//
//
// Return: UINT - # of chars in string, not including NULL
//
// Notes: Based on code from user32.
//
//*************************************************************
UINT
SizeofStringResource(HINSTANCE hInstance, UINT idStr)
{
UINT cch = 0;
HRSRC hRes = FindResource(hInstance, (LPTSTR)((LONG_PTR)(((USHORT)idStr >> 4) + 1)), RT_STRING);
if (NULL != hRes)
{
HGLOBAL hStringSeg = LoadResource(hInstance, hRes);
if (NULL != hStringSeg)
{
LPWSTR psz = (LPWSTR)LockResource(hStringSeg);
if (NULL != psz)
{
idStr &= 0x0F;
while(true)
{
cch = *psz++;
if (idStr-- == 0)
break;
psz += cch;
}
}
}
}
return cch;
}
//*************************************************************
//
// LoadStringAlloc
//
// Purpose: Loads a string resource into an alloc'd buffer
//
// Parameters: ppszResult - string resource returned here
// hInstance - module to load string from
// idStr - string resource ID
//
// Return: same as LoadString
//
// Notes: On successful return, the caller must
// LocalFree *ppszResult
//
//*************************************************************
int
LoadStringAlloc(LPWSTR *ppszResult, HINSTANCE hInstance, UINT idStr)
{
int nResult = 0;
UINT cch = SizeofStringResource(hInstance, idStr);
if (cch)
{
cch++; // for NULL
*ppszResult = (LPWSTR)LocalAlloc(LPTR, cch * sizeof(WCHAR));
if (*ppszResult)
nResult = LoadString(hInstance, idStr, *ppszResult, cch);
}
return nResult;
}
|
[
"seta7D5@protonmail.com"
] |
seta7D5@protonmail.com
|
f1fad2bbbe0c6384744e3e4d8b6a39763f25265e
|
8352ca72d4f1e8e8ebbbb7d6b07a4e0963be7f41
|
/DataServer/DataServer_TIP/TA_BASE/transactive/app/dataserver/CFDServer/src/SyncMarketDataForCFD.h
|
9693e02c5a07a2cd8b5f126f5e638848b1dda5f0
|
[] |
no_license
|
radtek/slin_code
|
114f61695fc1a23a018da727452c3c42f64ebe39
|
a0073e52d600839f7836c2b7673b45b4266259e2
|
refs/heads/master
| 2020-06-04T15:03:56.618177
| 2015-04-27T10:27:47
| 2015-04-27T10:27:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,429
|
h
|
#ifndef __CLASS_SYNC_MARKET_DATA_FOR_CFD_H__
#define __CLASS_SYNC_MARKET_DATA_FOR_CFD_H__
#include "CFDServerCommonData.h"
#include "BarCalculator.h"
#include "CFDRequest.h"
NS_BEGIN(TA_Base_App)
class CCFDServerUtilityFun;
class CCFDInstrumentBarInfo;
class CSyncMarketDataForCFD
{
public:
enum enSynType
{
SynType_BEGIN,
SynType_EQUAL,
SynType_SMALL,
SynType_BIGGER,
SynType_END,
};
enum enNextWorkType
{
NextWorkType_BEGIN,
NextWorkType_UseNewFirst_UseNewSecond,
NextWorkType_UseNewFirst_ReUseSecond,
NextWorkType_ReUseFirst_UseNewSecond,
NextWorkType_END,
};
public:
typedef std::list<CCFDInstrumentBarInfo*> LstCFDBarInfoT;
typedef std::list<CCFDInstrumentBarInfo*>::iterator LstCFDBarInfoIterT;
typedef std::list<MarketData*> LstBarInfoT;
typedef std::list<MarketData*>::iterator LstBarInfoIterT;
public:
CSyncMarketDataForCFD(const CCFDRequest& cfdRequest);
~CSyncMarketDataForCFD(void);
public:
void setCFDRequest(const CCFDRequest& cfdRequest);
int syncSingleCFDBarInfo(
const MarketData& nBarInfoFirst,
const MarketData& nBarInfoSecond,
LstCFDBarInfoT& lstCFDbarInfo,
enNextWorkType& nNextWorkType);
int clearCFDBarInfoList(LstCFDBarInfoT& lstCFDbarInfo);
private:
int _SyncSingleBarInfo(
const MarketData& nBarInfoFirst,
const MarketData& nBarInfoSecond,
LstBarInfoT& lstBarInfoFirst,
LstBarInfoT& lstBarInfoSecond,
enNextWorkType& nNextWorkType);
int _ClearBarInfoList(LstBarInfoT& lstBarInfo);
private:
int _SyncLstCFDBarInfo(LstBarInfoT& lstBarInfoFirst, LstBarInfoT& lstBarInfoSecond, LstCFDBarInfoT& lstCFDBarInfo);
int _SyncSingleBarInfoSynType( enSynType nSynType, const MarketData& nBarInfoFirst, const MarketData& nBarInfoSecond, LstBarInfoT& lstBarInfoFirst, LstBarInfoT& lstBarInfoSecond);
int _SyncSingleBarInfoSynTypeEqual( enSynType nSynType, const MarketData& nBarInfoFirst, const MarketData& nBarInfoSecond, LstBarInfoT& lstBarInfoFirst, LstBarInfoT& lstBarInfoSecond);
int _SyncSingleBarInfoSynTypeSmall( enSynType nSynType, const MarketData& nBarInfoFirst, const MarketData& nBarInfoSecond, LstBarInfoT& lstBarInfoFirst, LstBarInfoT& lstBarInfoSecond);
private:
CCFDServerUtilityFun* m_pUtilityFun;
CCFDRequest m_CFDRequest;
};
NS_END(TA_Base_App)
#endif // __CLASS_SYNC_MARKET_DATA_FOR_CFD_H__
|
[
"shenglonglinapple@gmail.com"
] |
shenglonglinapple@gmail.com
|
0f2cca11331527142c6a81af499eab6dc7be0635
|
776426915cb19273095dc9d8ad583d6847add5d4
|
/robot.cpp
|
aed800642b344117c1036f7ff20b3031aef98f1b
|
[] |
no_license
|
imharsh94/ALGO-DS
|
28832c9f843ee5a22463557c3493976399ad33cc
|
b9c131a2248c86da10f8df23606fdaef509c2d10
|
refs/heads/master
| 2020-08-11T21:22:37.082594
| 2019-10-12T10:37:32
| 2019-10-12T10:37:32
| 214,629,394
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 734
|
cpp
|
// codeforces educational round 53
#include<bits/stdc++.h>
using namespace std;
char s[200008];
int sx[200008],sy[200008];
int main()
{
int n,i,j,x,y,k;
cin>>n;
scanf("%s",s+1);
cin>>x>>y;
if(abs(x)+abs(y) > n ||(n+x+y)&1)
{
cout<<-1<<'\n';
return 0;
}
for(int i=1; i<=n; i++)
{
sx[i] = sx[i-1] + (s[i]=='L'?-1:(s[i]=='R'?1:0));
sy[i] = sy[i-1] + (s[i]=='D'?-1:(s[i]=='U'?1:0));
}
int ans = 1<<30;
for(int i=0,j=0; i<=n; i++)
{
while(j<=n && abs(sx[i]+sx[n]-sx[j]-x)+abs(sy[i]+sy[n]-sy[j]-y)>j-i)
j++;
if(j<=n)
ans = min(ans,j-i);
else
break;
}
cout<<ans<<endl;
return 0;
}
|
[
"vardhan.harsh94@gmail.com"
] |
vardhan.harsh94@gmail.com
|
cc5d35422b45c75f8146e02297f99e09fdcbddeb
|
82646fb7fe40db6dcdf238548128f7b633de94c0
|
/workspace/P65/src/32.cpp
|
9583afe2df05015dcd324b3057ed4780060bbe17
|
[] |
no_license
|
jtahstu/iCode
|
a7873618fe98e502c1e0e2fd0769d71b3adac756
|
42d0899945dbc1bab98092d21a1d946137a1795e
|
refs/heads/master
| 2021-01-10T22:55:47.677615
| 2016-10-23T12:42:38
| 2016-10-23T12:42:38
| 70,316,051
| 1
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 582
|
cpp
|
/*
* 32.cpp
* Created on: 2015年4月4日
* Author: jtahstu
*/
//32列出真分数序列
//按递增顺序依次列出所有分母为40,分子小于40的最简分数。
//
//*运行结果
//The fraction serials with demominator 40 is:
//1/40 3/40 7/40 9/40 11/40 13/40 17/40 19/40
//21/40 23/40 27/40 29/40 31/40 33/40 37/40 39/40
#include<iostream>
#include<cstdio>
using namespace std;
int gcd32(int a,int b){
return b==0?a:gcd32(b,a%b);
}
int main32()
{
for(int i=1;i<40;i++)
{if(gcd32(40,i)==1)
cout<<i<<"/40"<<" ";
}
return 0;
}
|
[
"root@jtahstu.com"
] |
root@jtahstu.com
|
b12965d715e6284202ba24cf0b677891f1f54dfc
|
12154201c2c4dc8968b690fa8237ebfe1932f60a
|
/SWEA/1232.cpp
|
2338641229460152f36e0dd2c7ef0b68a8baaa42
|
[] |
no_license
|
heon24500/PS
|
9cc028de3d9b1a26543b5bd498cfd5134d3d6de4
|
df901f6fc71f8c9d659b4c5397d44de9a2031a9d
|
refs/heads/master
| 2023-02-20T17:06:30.065944
| 2021-01-25T12:43:48
| 2021-01-25T12:43:48
| 268,433,390
| 2
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 1,359
|
cpp
|
/* 1232. [S/W 문제해결 기본] 9일차 - 사칙연산 */
#include <iostream>
#include <string>
#include <stack>
using namespace std;
const int N = 1001;
int tree[N][2];
string ops[N];
stack<int> s;
void init()
{
for (int i = 0; i < N; i++) {
tree[i][0] = 0;
tree[i][1] = 0;
ops[i] = "";
}
while (!s.empty()) {
s.pop();
}
}
bool isOperator(string str)
{
char ch = str[0];
if (ch == '+' || ch == '-' || ch == '*' || ch == '/') return true;
else return false;
}
int calc(string str)
{
char ch = str[0];
int b = s.top();
s.pop();
int a = s.top();
s.pop();
if (ch == '+') {
return a + b;
}
else if (ch == '-') {
return a - b;
}
else if (ch == '*') {
return a * b;
}
else if (ch == '/') {
return a / b;
}
}
void postorder(int t)
{
if (t == 0) return;
postorder(tree[t][0]);
postorder(tree[t][1]);
string str = ops[t];
int result;
if (isOperator(str)) result = calc(str);
else result = stoi(str);
s.push(result);
}
int main()
{
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
for (int t = 1; t <= 10; t++) {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
int num;
cin >> num;
cin >> ops[num];
if (isOperator(ops[num])) {
cin >> tree[num][0] >> tree[num][1];
}
}
postorder(1);
cout << "#" << t << " " << s.top() << '\n';
init();
}
return 0;
}
|
[
"heon24500@naver.com"
] |
heon24500@naver.com
|
19685e5b5a22d7397dc9a822a611b3ff326ebeaa
|
fa85329dbe03772df56547375154c5437ff2b076
|
/Zero_L/alfa/Mapa.h
|
fcb75d70277662fc2f59fdca83186436e309b06b
|
[
"Apache-2.0"
] |
permissive
|
Ninefrm/Unsingned
|
9597f3c3cf1c422adbbcbf36a41d0b97aa71aa9a
|
cf051f6aa6c9d93f8582539b2d36c64a41447a58
|
refs/heads/master
| 2021-08-24T05:07:38.657326
| 2017-12-08T05:12:47
| 2017-12-08T05:12:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,119
|
h
|
#ifndef _MAPA_H_
#define _MAPA_H_
#include <vector>
#include <random>
#include <curses.h>
#include <ctime>
#include "Obj.h"
#include "Wall.h"
#include "Character.h"
#include "Enemy.h"
#include "Sword.h"
class Mapa{
public:
Mapa();
Mapa(Character* , std::vector<Wall>, int, int);
bool wall_colision() const;//Verifica si el jugador colisiona con alguo de los muros
bool wall_colision(int, int) const;//Verifica si la posicion (x, y) colisiona con alguno de los muros
bool outside() const;
bool enemys_colision();
bool enemys_colision(const Obj&, int);
bool enemys_colision(const Sword espada);
void generate_enemy();
void move_enemys();
void move_agresive();
void draw_walls();//Dibuja los muros
void draw_enemys();
private:
int rows;
int cols;
std::mt19937 motor;
std::uniform_int_distribution<int> rand_x;
std::uniform_int_distribution<int> rand_y;
std::uniform_int_distribution<int> rand_mov;
std::vector<Wall> walls;
Character* player;
Enemy enemys;
bool inside;
};
#endif
|
[
"luiszavala@live.com.mx"
] |
luiszavala@live.com.mx
|
69c3bf5e4501e9b659ef06bc25505e9af4c9a44f
|
da726bce6d0f9ab1e63b9c04a2cb33976a0735a3
|
/lib/Transform/Mixed/DINodeRetriever.cpp
|
3cb1bfa7b68a68d6d30bd1e8b3b8fff30200fea7
|
[
"Apache-2.0",
"NCSA"
] |
permissive
|
dvm-system/tsar
|
c4017018a624100d50749004dc60e1f6b23fa99f
|
8ee33ff80702766d832e56aa37e82931aacd2ba3
|
refs/heads/master
| 2023-05-24T23:41:39.583393
| 2023-04-22T12:23:40
| 2023-04-22T12:24:17
| 212,194,441
| 19
| 20
|
Apache-2.0
| 2023-05-22T09:11:28
| 2019-10-01T20:35:07
|
C++
|
UTF-8
|
C++
| false
| false
| 7,908
|
cpp
|
//===- DIGlobalRetriever.cpp - Global Debug Info Retriever ------*- C++ -*-===//
//
// Traits Static Analyzer (SAPFOR)
//
// Copyright 2018 DVM System Group
//
// 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.
//
//===----------------------------------------------------------------------===//
//
// This file implements a pass which retrieves some debug information for
// global values if it is not presented in LLVM IR.
//
//===----------------------------------------------------------------------===//
#include "tsar/Analysis/KnownFunctionTraits.h"
#include "tsar/Analysis/Memory/Utils.h"
#include "tsar/Frontend/Clang/TransformationContext.h"
#include "tsar/Support/MetadataUtils.h"
#include "tsar/Support/Clang/Utils.h"
#include "tsar/Transform/Mixed/Passes.h"
#include <bcl/utility.h>
#include <clang/Basic/LangOptions.h>
#include <clang/AST/Decl.h>
#include <llvm/IR/DebugInfo.h>
#include <llvm/IR/DIBuilder.h>
#include <llvm/IR/InstIterator.h>
#include <llvm/IR/Module.h>
#include <llvm/Pass.h>
#include <llvm/Support/Path.h>
#include <llvm/Support/FileSystem.h>
using namespace clang;
using namespace llvm;
using namespace tsar;
namespace {
/// This retrieves some debug information for global values if it is not
/// presented in LLVM IR ('sapfor.dbg' metadata will be attached to globals).
class DINodeRetrieverPass : public ModulePass, private bcl::Uncopyable {
public:
static char ID;
DINodeRetrieverPass() : ModulePass(ID) {
initializeDINodeRetrieverPassPass(*PassRegistry::getPassRegistry());
}
bool runOnModule(llvm::Module &M) override;
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.getPreservesAll();
}
private:
/// Insert artificial metadata for allocas.
void insertDeclareIfNotExist(Function &F, DIFile *FileCU, DIBuilder &DIB) {
for (auto &I : instructions(F))
if (auto *AI = dyn_cast<AllocaInst>(&I)) {
auto &Ctx = AI->getContext();
auto AddrUses = FindDbgAddrUses(AI);
if (!AddrUses.empty()) {
for (auto *DbgInst : AddrUses) {
// Artificial variables without name may produce the same
// metdata-level locations for distinct lower level locations.
// This leads to incorrect metadata-level alias tree.
// So, replace this variable with the distinct one.
if (auto DIVar = DbgInst->getVariable())
if (DIVar->getFlags() & DINode::FlagArtificial &&
DIVar->getName().empty()) {
auto DistinctDIVar = DILocalVariable::getDistinct(
Ctx, DIVar->getScope(), "sapfor.var", DIVar->getFile(),
DIVar->getLine(), DIVar->getType(), DIVar->getArg(),
DIVar->getFlags(), DIVar->getAlignInBits(), nullptr);
DbgInst->setVariable(DistinctDIVar);
}
}
continue;
}
auto *DITy =
createStubType(*F.getParent(), AI->getType()->getAddressSpace(), DIB);
auto *DISub = F.getSubprogram();
auto *DIVar = DILocalVariable::getDistinct(
Ctx, DISub, "sapfor.var", FileCU, 0, DITy, 0,
DINode::FlagArtificial, AI->getAlign().value(), nullptr);
DIB.insertDeclare(AI, DIVar, DIExpression::get(Ctx, {}),
DILocation::get(AI->getContext(), 0, 0, DISub), AI->getParent());
}
}
};
} // namespace
char DINodeRetrieverPass::ID = 0;
INITIALIZE_PASS(DINodeRetrieverPass, "di-node-retriever",
"Debug Info Retriever", true, false)
bool DINodeRetrieverPass::runOnModule(llvm::Module &M) {
auto *TEP{getAnalysisIfAvailable<TransformationEnginePass>()};
auto &Ctx = M.getContext();
auto CUItr = M.debug_compile_units_begin();
assert(CUItr != M.debug_compile_units_end() &&
"At least one compile unit must be available!");
auto CU =
std::distance(CUItr, M.debug_compile_units_end()) == 1 ? *CUItr : nullptr;
SmallString<256> CWD;
auto DirName = CU ? CUItr->getDirectory()
: (llvm::sys::fs::current_path(CWD), StringRef(CWD));
auto *FileCU = CU ? CU->getFile() : nullptr;
DIBuilder DIB(M);
for (auto &GlobalVar : M.globals()) {
SmallVector<DIMemoryLocation, 1> DILocs;
if (findGlobalMetadata(&GlobalVar, DILocs))
continue;
DIFile *File = FileCU;
unsigned Line = 0;
// A name should be specified for global variables, otherwise LLVM IR is
// considered corrupted.
StringRef Name = "sapfor.var";
if (TEP && *TEP)
for (auto [CU, TfmCtxBase] : (*TEP)->contexts())
if (auto *TfmCtx{dyn_cast<ClangTransformationContext>(TfmCtxBase)})
if (auto D = TfmCtx->getDeclForMangledName(GlobalVar.getName())) {
auto &SrcMgr = TfmCtx->getRewriter().getSourceMgr();
auto FName =
SrcMgr.getFilename(SrcMgr.getExpansionLoc(D->getBeginLoc()));
File = DIB.createFile(FName, CU->getDirectory());
Line = SrcMgr.getPresumedLineNumber(
SrcMgr.getExpansionLoc(D->getBeginLoc()));
if (auto ND = dyn_cast<NamedDecl>(D))
Name = ND->getName();
break;
}
auto *DITy = createStubType(M, GlobalVar.getType()->getAddressSpace(), DIB);
auto *GV = DIGlobalVariable::getDistinct(
Ctx, File, Name, GlobalVar.getName(), File, Line, DITy,
GlobalVar.hasLocalLinkage(), !GlobalVar.isDeclaration(),
nullptr, nullptr, 0, nullptr);
auto *GVE =
DIGlobalVariableExpression::get(Ctx, GV, DIExpression::get(Ctx, {}));
GlobalVar.setMetadata("sapfor.dbg", GVE);
}
for (auto &F : M.functions()) {
if (F.getSubprogram()) {
insertDeclareIfNotExist(F, FileCU, DIB);
continue;
}
if (F.isIntrinsic() && (isDbgInfoIntrinsic(F.getIntrinsicID()) ||
isMemoryMarkerIntrinsic(F.getIntrinsicID())))
continue;
DIFile *File = FileCU;
unsigned Line = 0;
auto Flags = DINode::FlagZero;
MDString *Name = nullptr;
if (TEP && *TEP)
for (auto [CU, TfmCtxBase] : (*TEP)->contexts())
if (auto *TfmCtx{dyn_cast<ClangTransformationContext>(TfmCtxBase)})
if (auto *D = TfmCtx->getDeclForMangledName(F.getName())) {
auto &SrcMgr = TfmCtx->getRewriter().getSourceMgr();
auto FName =
SrcMgr.getFilename(SrcMgr.getExpansionLoc(D->getBeginLoc()));
File = DIB.createFile(FName, CU->getDirectory());
Line = SrcMgr.getPresumedLineNumber(
SrcMgr.getExpansionLoc(D->getBeginLoc()));
if (auto *FD = dyn_cast<FunctionDecl>(D)) {
SmallString<64> ExtraName;
Name = MDString::get(Ctx, getFunctionName(*FD, ExtraName));
if (FD->hasPrototype())
Flags |= DINode::FlagPrototyped;
if (FD->isImplicit())
Flags |= DINode::FlagArtificial;
}
}
auto SPFlags =
DISubprogram::toSPFlags(F.hasLocalLinkage(), !F.isDeclaration(), false);
auto *SP = DISubprogram::getDistinct(Ctx, File, Name,
MDString::get(Ctx, F.getName()), File, Line, nullptr, Line, nullptr,
0, 0, Flags, SPFlags, !F.isDeclaration() ? CU : nullptr);
F.setMetadata("sapfor.dbg", SP);
insertDeclareIfNotExist(F, FileCU, DIB);
}
return true;
}
ModulePass *llvm::createDINodeRetrieverPass() {
return new DINodeRetrieverPass();
}
|
[
"kaniandr@gmail.com"
] |
kaniandr@gmail.com
|
2013508685c406f26f59797369c25eab0f2a0d9f
|
cae8f9912d24273fa747f4f791989f1f6f12f247
|
/sketch_apr02a.ino
|
fe5d5df7452a0f7ae5a8a29c13e258d9eb96c716
|
[] |
no_license
|
vasudevgrover/Working-with-GSM-module-Arduino-
|
ae873f57e68d5b132fb093e64068f77b0f28b6e5
|
de6d2fbd860a8b16818449abe5d4b56ddd334f81
|
refs/heads/master
| 2020-12-24T20:42:52.744017
| 2016-04-12T16:32:15
| 2016-04-12T16:32:15
| 56,079,703
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 999
|
ino
|
#include <SoftwareSerial.h>
SoftwareSerial mySerial(9, 10);
void setup()
{
mySerial.begin(9600); //baud rate of GSM Module
Serial.begin(9600); //baud rate of Serial Monitor (Arduino)
delay(100);
}
void loop()
{
if (Serial.available()>0)
switch(Serial.read())
{
case 's':
SendMessage();
break;
case 'r':
RecieveMessage();
break;
}
if (mySerial.available()>0)
Serial.write(mySerial.read());
}
void SendMessage()
{
mySerial.println("AT+CMGF=1"); //Sets the GSM Module in Text Mode
delay(1000); // Delay of 1000 milli seconds or 1 second
mySerial.println("AT+CMGS=\"+91xxxxxxxxxx\"\r"); // Replace x with mobile number
delay(1000);
mySerial.println("SMS from GSM Module");// The SMS text you want to send
delay(100);
mySerial.println((char)26);// ASCII code of CTRL+Z
delay(1000);
}
void RecieveMessage()
{
mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS
delay(1000);
}
|
[
"vasudev.grover@gmail.com"
] |
vasudev.grover@gmail.com
|
d41cee16d53ba621cc3ee717d9856782a1494c4a
|
dc9c6f34e15ae60cdecd503117334f5db2276ecd
|
/065_LC_76_minimumWindowSubstring.cpp
|
1dc93d6013584627bd685f0e98f479aa08130792
|
[] |
no_license
|
z2z23n0/Algorithm
|
43c669958972b73dab95adf8314bbf219690c4d2
|
6582688bd387b2bb04eb39bafa58e0180f665bb4
|
refs/heads/master
| 2022-06-09T22:43:25.914800
| 2020-05-07T16:27:03
| 2020-05-08T16:27:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,360
|
cpp
|
//
// Created by Zeno on 2020/5/2.
//
class Solution {
public:
string minWindow(string s, string t) {
int start = 0; // record the beginning of the minium substring
int minLen = INT_MAX;
int left = 0, right = 0;
int match = 0; // record the match number between window and needs
unordered_map<char, int> window;
unordered_map<char, int> needs;
for (char c : t) {
needs[c]++;
}
// first, move right to very right
// if match == needs.size(), move left to right until match < needs.size()
while (right < s.size()) {
char c1 = s[right];
if (needs.count(c1)) {
window[c1]++;
if (window[c1] == needs[c1]) {
match++;
}
}
right++;
while (match == needs.size()) {
if (right - left < minLen) {
start = left;
minLen = right - left;
}
char c2 = s[left];
if (needs.count(c2)) {
window[c2]--;
if (window[c2] < needs[c2])
match--;
}
left++;
}
}
return minLen == INT_MAX ? "" : s.substr(start, minLen);
}
};
|
[
"zhangyuzechn@foxmail.com"
] |
zhangyuzechn@foxmail.com
|
39b97ce9f5501590918e6b55e5e29616e6b88809
|
bbe7671fd0218f4f53082aa29eaf8d4137d1b505
|
/cpp/hello/main.cpp
|
bbce233c482568dafe9aa3a06261570c71b8c916
|
[] |
no_license
|
b4rb4tron/projecten
|
da8650a694860b1e259fafd423eb249f7b2625cf
|
59f6a94a3b253ec1e9ac63d8ce31cbf493be887f
|
refs/heads/master
| 2021-07-06T07:22:11.864197
| 2018-10-25T09:51:43
| 2018-10-25T09:51:43
| 133,808,041
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 144
|
cpp
|
#include <iostream>
#include "test.h"
using namespace std;
int main()
{
cout << "Hello world!" << endl;
test newtest;
return 0;
}
|
[
"roger@snoeivanhout.nl"
] |
roger@snoeivanhout.nl
|
ec09caed19965ed57a38708dc834a6201362759b
|
492976adfdf031252c85de91a185bfd625738a0c
|
/src/Game/AI/Action/actionFreeMove.h
|
bdc2e801fa992746fe8831104b400403dea4acd7
|
[] |
no_license
|
zeldaret/botw
|
50ccb72c6d3969c0b067168f6f9124665a7f7590
|
fd527f92164b8efdb746cffcf23c4f033fbffa76
|
refs/heads/master
| 2023-07-21T13:12:24.107437
| 2023-07-01T20:29:40
| 2023-07-01T20:29:40
| 288,736,599
| 1,350
| 117
| null | 2023-09-03T14:45:38
| 2020-08-19T13:16:30
|
C++
|
UTF-8
|
C++
| false
| false
| 1,059
|
h
|
#pragma once
#include "KingSystem/ActorSystem/actAiAction.h"
namespace uking::action {
class FreeMove : public ksys::act::ai::Action {
SEAD_RTTI_OVERRIDE(FreeMove, ksys::act::ai::Action)
public:
explicit FreeMove(const InitArg& arg);
~FreeMove() override;
bool init_(sead::Heap* heap) override;
void enter_(ksys::act::ai::InlineParamPack* params) override;
void leave_() override;
void loadParams_() override;
protected:
void calc_() override;
// FIXME: remove this
u8 pad_0x20[0x40];
// static_param at offset 0x60
const float* mSpeed_s{};
// static_param at offset 0x68
const float* mSpeedAddRate_s{};
// static_param at offset 0x70
const float* mAngleSpeed_s{};
// static_param at offset 0x78
const bool* mIsChangeable_s{};
// static_param at offset 0x80
const bool* mIsIgnoreSameAS_s{};
// static_param at offset 0x88
const bool* mAllowPitchRotation_s{};
// static_param at offset 0x90
sead::SafeString mASKeyName_s{};
};
} // namespace uking::action
|
[
"leo@leolam.fr"
] |
leo@leolam.fr
|
9bd70c24d67b90e653467a6f72d5a3a7b0c226e6
|
651570891f9a418440f2611f3773e2498c6ce3be
|
/TRAC-IK package/baxter_sim_kinematics/src/arm_kinematics.cpp
|
6d13e7a0e60bbde7799b9220da56f008ef8b9d98
|
[] |
no_license
|
MartinFk/ReMa
|
aa22bb32f0d5e47b7e812a01ae407ad5444ec6ea
|
2233e53994952ac36bbab766834f817c26d3bdf6
|
refs/heads/master
| 2021-05-06T05:59:18.865847
| 2018-01-06T18:45:05
| 2018-01-06T18:45:05
| 115,284,971
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 18,653
|
cpp
|
/*********************************************************************
# Copyright (c) 2013-2015, Rethink Robotics
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. Neither the name of the Rethink Robotics 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.
*********************************************************************/
/**
* \author Hariharasudan Malaichamee
* \modified Martin Feick
* \desc library that performs the calculations for the IK,FK and Gravity compensation using the KDL library
*/
#include <cstring>
#include <ros/ros.h>
#include <baxter_sim_kinematics/arm_kinematics.h>
namespace arm_kinematics {
Kinematics::Kinematics()
: nh_private("~") {
}
bool Kinematics::init_grav() {
std::string urdf_xml, full_urdf_xml;
nh.param("urdf_xml", urdf_xml, std::string("robot_description"));
nh.searchParam(urdf_xml, full_urdf_xml);
ROS_DEBUG("Reading xml file from parameter server");
std::string result;
if (!nh.getParam(full_urdf_xml, result)) {
ROS_FATAL("Could not load the xml from parameter server: %s",
urdf_xml.c_str());
return false;
}
if (!nh.getParam("root_name", root_name)) {
ROS_FATAL("GenericIK: No tip name for gravity found on parameter server");
return false;
}
if (!nh.getParam("grav_right_name", grav_right_name)) {
ROS_FATAL("GenericIK: No tip name for gravity found on parameter server");
return false;
}
if (!nh.getParam("grav_left_name", grav_left_name)) {
ROS_FATAL("GenericIK: No tip name for gravity found on parameter server");
return false;
}
//Service client to set the gravity false for the limbs
ros::ServiceClient get_lp_client = nh.serviceClient<gazebo_msgs::GetLinkProperties>("/gazebo/get_link_properties");
//Wait for service to become available
get_lp_client.waitForExistence();
//Service client to set the gravity false for the limbs
ros::ServiceClient set_lp_client = nh.serviceClient<gazebo_msgs::SetLinkProperties>("/gazebo/set_link_properties");
//Wait for service to become availablestd::find(vector.begin(), vector.end(), item)!=vector.end()
set_lp_client.waitForExistence();
gazebo_msgs::SetLinkProperties setlinkproperties;
gazebo_msgs::GetLinkProperties getlinkproperties;
setlinkproperties.request.gravity_mode=0;
//Load the right chain and copy them to Right specific variables
tip_name = grav_right_name;
if (!loadModel(result)) {
ROS_FATAL("Could not load models!");
return false;
}
grav_chain_r = chain;
right_joint.clear();
right_joint.reserve(chain.getNrOfSegments());
std::vector<std::string>::iterator idx;
//Update the right_joint with the fixed joints from the URDF. Get each of the link's properties from GetLinkProperties service and
//call the SetLinkProperties service with the same set of parameters except for the gravity_mode, which would be disabled. This is
//to disable the gravity in the links, thereby to eliminate the need for gravity compensation
for (int i = 0; i < chain.getNrOfSegments(); i++) {
std::string seg_name = chain.getSegment(i).getName();
std::string joint_name = chain.getSegment(i).getJoint().getName();
idx = std::find(info.joint_names.begin(), info.joint_names.end(), joint_name);
if (idx != info.joint_names.end()) {
right_joint.push_back(*idx);
}
std::string link_name = chain.getSegment(i).getName();
getlinkproperties.request.link_name=link_name;
setlinkproperties.request.link_name=link_name;
get_lp_client.call(getlinkproperties);
setlinkproperties.request.com = getlinkproperties.response.com;
setlinkproperties.request.mass = getlinkproperties.response.mass;
setlinkproperties.request.ixx = getlinkproperties.response.ixx;
setlinkproperties.request.iyy = getlinkproperties.response.iyy;
setlinkproperties.request.izz = getlinkproperties.response.izz;
setlinkproperties.request.ixy = getlinkproperties.response.ixy;
setlinkproperties.request.iyz = getlinkproperties.response.iyz;
setlinkproperties.request.ixz = getlinkproperties.response.ixz;
setlinkproperties.request.gravity_mode = false;
set_lp_client.call(setlinkproperties);
}
//Create a gravity solver for the right chain
gravity_solver_r = new KDL::ChainIdSolver_RNE(grav_chain_r,
KDL::Vector(0.0, 0.0, -9.8));
//Load the left chain and copy them to Right specific variable
tip_name = grav_left_name;
if (!loadModel(result)) {
ROS_FATAL("Could not load models!");
return false;
}
grav_chain_l = chain;
left_joint.clear();
left_joint.reserve(chain.getNrOfSegments());
//Update the left_joint with the fixed joints from the URDF. Get each of the link's properties from GetLinkProperties service and
//call the SetLinkProperties service with the same set of parameters except for the gravity_mode, which would be disabled. This is
//to disable the gravity in the links, thereby to eliminate the need for gravity compensation
for (int i = 0; i < chain.getNrOfSegments(); i++) {
std::string seg_name = chain.getSegment(i).getName();
std::string joint_name = chain.getSegment(i).getJoint().getName();
idx = std::find(info.joint_names.begin(), info.joint_names.end(), joint_name);
if (idx != info.joint_names.end()) {
left_joint.push_back(*idx);
}
getlinkproperties.request.link_name=chain.getSegment(i).getName();
std::string link_name = chain.getSegment(i).getName();
getlinkproperties.request.link_name=link_name;
setlinkproperties.request.link_name=link_name;
get_lp_client.call(getlinkproperties);
setlinkproperties.request.com = getlinkproperties.response.com;
setlinkproperties.request.mass = getlinkproperties.response.mass;
setlinkproperties.request.ixx = getlinkproperties.response.ixx;
setlinkproperties.request.iyy = getlinkproperties.response.iyy;
setlinkproperties.request.izz = getlinkproperties.response.izz;
setlinkproperties.request.ixy = getlinkproperties.response.ixy;
setlinkproperties.request.iyz = getlinkproperties.response.iyz;
setlinkproperties.request.ixz = getlinkproperties.response.ixz;
setlinkproperties.request.gravity_mode = false;
set_lp_client.call(setlinkproperties);
}
//Create a gravity solver for the left chain
gravity_solver_l = new KDL::ChainIdSolver_RNE(grav_chain_l,
KDL::Vector(0.0, 0.0, -9.8));
return true;
}
/* Initializes the solvers and the other variables required
* @returns true is successful
*/
bool Kinematics::init(std::string tip, int &no_jts) {
// Get URDF XML
std::string urdf_xml, full_urdf_xml;
tip_name = tip;
nh.param("urdf_xml", urdf_xml, std::string("robot_description"));
nh.searchParam(urdf_xml, full_urdf_xml);
ROS_DEBUG("Reading xml file from parameter server");
std::string result;
if (!nh.getParam(full_urdf_xml, result)) {
ROS_FATAL("Could not load the xml from parameter server: %s",
urdf_xml.c_str());
return false;
}
// Get Root and Tip From Parameter Service
if (!nh.getParam("root_name", root_name)) {
ROS_FATAL("GenericIK: No root name found on parameter server");
return false;
}
// Load and Read Models
if (!loadModel(result)) {
ROS_FATAL("Could not load models!");
return false;
}
// Get Solver Parameters
int maxIterations;
double epsilon;
//KDL::Vector grav;
nh_private.param("maxIterations", maxIterations, 1000);
nh_private.param("epsilon", epsilon, 1e-2);
// Build Solvers
fk_solver = new KDL::ChainFkSolverPos_recursive(chain);
ik_solver_vel = new KDL::ChainIkSolverVel_pinv(chain);
ik_solver_pos = new KDL::ChainIkSolverPos_NR_JL(chain, joint_min, joint_max,
*fk_solver, *ik_solver_vel,
maxIterations, epsilon);
double eps = 1e-5;
double timeout = 0.005;
ik_solver = new TRAC_IK::TRAC_IK(chain, joint_min, joint_max, timeout, eps);
no_jts=num_joints;
return true;
}
/* Method to load all the values from the parameter server
* @returns true is successful
*/
bool Kinematics::loadModel(const std::string xml) {
urdf::Model robot_model;
KDL::Tree tree;
if (!robot_model.initString(xml)) {
ROS_FATAL("Could not initialize robot model");
return -1;
}
if (!kdl_parser::treeFromString(xml, tree)) {
ROS_ERROR("Could not initialize tree object");
return false;
}
if (!tree.getChain(root_name, tip_name, chain)) {
ROS_ERROR("Could not initialize chain object for root_name %s and tip_name %s",root_name.c_str(), tip_name.c_str());
return false;
}
if (!readJoints(robot_model)) {
ROS_FATAL("Could not read information about the joints");
return false;
}
return true;
}
/* Method to read the URDF model and extract the joints
* @returns true is successful
*/
bool Kinematics::readJoints(urdf::Model &robot_model) {
num_joints = 0;
boost::shared_ptr<const urdf::Link> link = robot_model.getLink(tip_name);
boost::shared_ptr<const urdf::Joint> joint;
for (int i = 0; i < chain.getNrOfSegments(); i++)
while (link && link->name != root_name) {
if (!(link->parent_joint)) {
break;
}
joint = robot_model.getJoint(link->parent_joint->name);
if (!joint) {
ROS_ERROR("Could not find joint: %s", link->parent_joint->name.c_str());
return false;
}
if (joint->type != urdf::Joint::UNKNOWN
&& joint->type != urdf::Joint::FIXED) {
ROS_INFO("adding joint: [%s]", joint->name.c_str());
num_joints++;
}
link = robot_model.getLink(link->getParent()->name);
}
joint_min.resize(num_joints);
joint_max.resize(num_joints);
info.joint_names.resize(num_joints);
info.link_names.resize(num_joints);
link = robot_model.getLink(tip_name);
unsigned int i = 0;
while (link && i < num_joints) {
joint = robot_model.getJoint(link->parent_joint->name);
if (joint->type != urdf::Joint::UNKNOWN
&& joint->type != urdf::Joint::FIXED) {
ROS_INFO("getting bounds for joint: [%s]", joint->name.c_str());
float lower, upper;
int hasLimits;
if (joint->type != urdf::Joint::CONTINUOUS) {
lower = joint->limits->lower;
upper = joint->limits->upper;
hasLimits = 1;
} else {
lower = -M_PI;
upper = M_PI;
hasLimits = 0;
}
int index = num_joints - i - 1;
joint_min.data[index] = lower;
joint_max.data[index] = upper;
info.joint_names[index] = joint->name;
info.link_names[index] = link->name;
i++;
}
link = robot_model.getLink(link->getParent()->name);
}
return true;
}
/* Method to calculate the torques required to apply at each of the joints for gravity compensation
* @returns true is successful
*/
bool arm_kinematics::Kinematics::getGravityTorques(
const sensor_msgs::JointState joint_configuration, baxter_core_msgs::SEAJointState &left_gravity, baxter_core_msgs::SEAJointState &right_gravity, bool isEnabled) {
bool res;
KDL::JntArray torques_l, torques_r;
KDL::JntArray jntPosIn_l, jntPosIn_r;
left_gravity.name = left_joint;
right_gravity.name = right_joint;
left_gravity.gravity_model_effort.resize(num_joints);
right_gravity.gravity_model_effort.resize(num_joints);
if (isEnabled) {
torques_l.resize(num_joints);
torques_r.resize(num_joints);
jntPosIn_l.resize(num_joints);
jntPosIn_r.resize(num_joints);
// Copying the positions of the joints relative to its index in the KDL chain
for (unsigned int j = 0; j < joint_configuration.name.size(); j++) {
for (unsigned int i = 0; i < num_joints; i++) {
if (joint_configuration.name[j] == left_joint.at(i)) {
jntPosIn_l(i) = joint_configuration.position[j];
break;
} else if (joint_configuration.name[j] == right_joint.at(i)) {
jntPosIn_r(i) = joint_configuration.position[j];
break;
}
}
}
KDL::JntArray jntArrayNull(num_joints);
KDL::Wrenches wrenchNull_l(grav_chain_l.getNrOfSegments(),
KDL::Wrench::Zero());
int code_l = gravity_solver_l->CartToJnt(jntPosIn_l, jntArrayNull,
jntArrayNull, wrenchNull_l,
torques_l);
KDL::Wrenches wrenchNull_r(grav_chain_r.getNrOfSegments(),
KDL::Wrench::Zero());
int code_r = gravity_solver_r->CartToJnt(jntPosIn_r, jntArrayNull,
jntArrayNull, wrenchNull_r,
torques_r);
//Check if the gravity was succesfully calculated by both the solvers
if (code_l >= 0 && code_r >= 0) {
for (unsigned int i = 0; i < num_joints; i++) {
left_gravity.gravity_model_effort[i] = torques_l(i);
right_gravity.gravity_model_effort[i] = torques_r(i);
}
return true;
} else {
ROS_ERROR_THROTTLE(
1.0,
"KT: Failed to compute gravity torques from KDL return code for left and right arms %d %d",
code_l, code_r);
return false;
}
} else {
for (unsigned int i = 0; i < num_joints; i++) {
left_gravity.gravity_model_effort[i]=0;
right_gravity.gravity_model_effort[i]=0;
}
}
return true;
}
/* Method to calculate the Joint index of a particular joint from the KDL chain
* @returns the index of the joint
*/
int Kinematics::getJointIndex(const std::string &name) {
for (unsigned int i = 0; i < info.joint_names.size(); i++) {
if (info.joint_names[i] == name)
return i;
}
return -1;
}
/* Method to calculate the KDL segment index of a particular segment from the KDL chain
* @returns the index of the segment
*/
int Kinematics::getKDLSegmentIndex(const std::string &name) {
int i = 0;
while (i < (int) chain.getNrOfSegments()) {
if (chain.getSegment(i).getJoint().getName() == name) {
return i + 1;
}
i++;
}
return -1;
}
/* Method to calculate the IK for the required end pose
* @returns true if successful
*/
bool arm_kinematics::Kinematics::getPositionIK(
const geometry_msgs::PoseStamped &pose_stamp,
const sensor_msgs::JointState &seed, sensor_msgs::JointState *result) {
geometry_msgs::PoseStamped pose_msg_in = pose_stamp;
tf::Stamped<tf::Pose> transform;
tf::Stamped<tf::Pose> transform_root;
tf::poseStampedMsgToTF(pose_msg_in, transform);
//Do the IK
KDL::JntArray jnt_pos_in;
KDL::JntArray jnt_pos_out;
jnt_pos_in.resize(num_joints);
// Copying the positions of the joints relative to its index in the KDL chain
for (unsigned int i = 0; i < num_joints; i++) {
int tmp_index = getJointIndex(seed.name[i]);
if (tmp_index >= 0) {
jnt_pos_in(tmp_index) = seed.position[i];
} else {
ROS_ERROR("i: %d, No joint index for %s", i, seed.name[i].c_str());
}
}
//Convert F to our root_frame
try {
tf_listener.transformPose(root_name, transform, transform_root);
} catch (...) {
ROS_ERROR("Could not transform IK pose to frame: %s", root_name.c_str());
return false;
}
KDL::Frame F_dest;
tf::transformTFToKDL(transform_root, F_dest);
//int ik_valid = ik_solver_pos->CartToJnt(jnt_pos_in, F_dest, jnt_pos_out);
int ik_valid=ik_solver->CartToJnt(jnt_pos_in, F_dest, jnt_pos_out);
if (ik_valid >= 0) {
result->name = info.joint_names;
result->position.resize(num_joints);
for (unsigned int i = 0; i < num_joints; i++) {
result->position[i] = jnt_pos_out(i);
ROS_DEBUG("IK Solution: %s %d: %f", result->name[i].c_str(), i,
jnt_pos_out(i));
}
return true;
} else {
ROS_DEBUG("An IK solution could not be found");
return false;
}
}
/* Method to calculate the FK for the required joint configuration
* @returns true if successful
*/
bool arm_kinematics::Kinematics::getPositionFK(
std::string frame_id, const sensor_msgs::JointState &joint_configuration,
geometry_msgs::PoseStamped &result) {
KDL::Frame p_out;
KDL::JntArray jnt_pos_in;
tf::Stamped<tf::Pose> tf_pose;
// Copying the positions of the joints relative to its index in the KDL chain
jnt_pos_in.resize(num_joints);
for (unsigned int i = 0; i < num_joints; i++) {
int tmp_index = getJointIndex(joint_configuration.name[i]);
if (tmp_index >= 0)
jnt_pos_in(tmp_index) = joint_configuration.position[i];
}
int num_segments = chain.getNrOfSegments();
ROS_DEBUG("Number of Segments in the KDL chain: %d", num_segments);
if (fk_solver->JntToCart(jnt_pos_in, p_out, num_segments) >= 0) {
tf_pose.frame_id_ = root_name;
tf_pose.stamp_ = ros::Time();
tf::poseKDLToTF(p_out, tf_pose);
try {
tf_listener.transformPose(frame_id, tf_pose, tf_pose);
} catch (...) {
ROS_ERROR("Could not transform FK pose to frame: %s", frame_id.c_str());
return false;
}
tf::poseStampedTFToMsg(tf_pose, result);
} else {
ROS_ERROR("Could not compute FK for endpoint.");
return false;
}
return true;
}
} //namespace
|
[
"martinfeick@yahoo.de"
] |
martinfeick@yahoo.de
|
58514e92995664918b86be20b589c90f7830c54f
|
cc7b87b6315b53d7682fd1d05481b929363014be
|
/C++/Volume C/P10042.cpp
|
964c6ece8fcd3684c2937d98e40627c7a3089872
|
[] |
no_license
|
ptargino/uvaOnlineJudge
|
b6d02a3c8cc084547247686da82ea0977c55f4af
|
b8922626122b013d8e668c6521504fce85958a7b
|
refs/heads/master
| 2020-05-19T16:19:34.010520
| 2012-06-30T21:21:06
| 2012-06-30T21:21:06
| 2,787,653
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,127
|
cpp
|
#include <math.h>
#include <iostream>
using namespace std;
bool isPrime(long int n) {
int root = (int) sqrt(n);
for (int i = 3; i < root; i += 2)
if (!(n % i))
return false;
return true;
}
int sumDigits(long n) {
int sum = 0;
while (n) {
sum += n % 10;
n /= 10;
}
return sum;
}
int main() {
long int n, root, i, j;
const long SIZE = 100000;
int MAX_ROOT = (int) sqrt(SIZE);
bool *prime = new bool[SIZE];
memset(prime, true, SIZE);
for (i = 3; i <= MAX_ROOT; i += 2)
if (isPrime(i))
for (j = 2 * i; j < SIZE; j += i)
prime[j] = false;
int sumA, sumB;
int t;
scanf("%d", &t);
for (; t; t--) {
scanf("%ld", &n);
n++;
while (true) {
long num = n;
sumA = 0;
sumB = sumDigits(n);
while (num % 2 == 0) {
sumA += 2;
num /= 2;
}
i = 3;
while (i <= num && num != 1) {
if (prime[i])
while (num % i == 0) {
sumA += sumDigits(i);
num /= i;
}
i += 2;
}
printf("%ld\n", n);
if (sumA == sumB) {
printf("%ld\n", n);
break;
} else {
n++;
}
}
}
}
|
[
"ptargino@gmail.com"
] |
ptargino@gmail.com
|
615641b86279bfc4c7533476181cb73ecfbd385a
|
f0b4ce0ba6972301435f182a6d4c02987ee17ab3
|
/whacAMole.cc
|
8ccc5d4730d71a60529367313bba7ad8cf98479c
|
[] |
no_license
|
gs0622/leetcode
|
b64bf1ac8d52ea473cac98b057a5edd1c8ff3591
|
ef9388f875c375f6f3cd290b04e457b416d860dc
|
refs/heads/master
| 2021-06-02T00:54:32.332803
| 2020-05-19T01:13:51
| 2020-05-19T01:13:51
| 20,798,407
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,489
|
cc
|
#include <bits/stdc++.h>
using namespace std;
class Solution {
public: // O(n) sliding window
int whatAMoleTwoMallets(vector<int>& A, int w) {
int n=A.size();
vector<int> sum(n,0);
for (int i=0; i<n; ++i) sum[i]=(i==0)? A[i]: A[i]+sum[i-1];
function<int(int,int)> getSum=[&](int i, int j) {
return (i==0)? sum[j]: sum[j]-sum[i-1];
};
pair<int,int> ids={n-2*w,n-w};
int mainSumTwoSubArr = getSum(n-2*w,n-w-1)+getSum(n-w,n-1);
pair<int,int> secSubArrMax={n-w,getSum(n-w,n-1)};
for (int i=n-2*w-1; i>=0; --i) {
int cur = getSum(i+w,i+2*w-1); // 1st:[n-w-1,n-2]
if (cur > secSubArrMax.second)
secSubArrMax={i+w,cur};
cur = getSum(i,i+w-1) + secSubArrMax.second;
if (cur>mainSumTwoSubArr)
mainSumTwoSubArr=cur, ids={i,secSubArrMax.first};
}
/*
for (int i=ids.first; i<ids.first+w; ++i) cout << A[i];
cout << endl;
for (int i=ids.second; i<ids.second+w; ++i) cout << A[i];
cout << endl;
*/
return mainSumTwoSubArr;
}
int whatAMole(vector<int>& A, int w) {
int n=A.size(),res=0,cur=0;
for (int i=0,j=0; i<n; ++i) {
if (A[i]==1) ++cur;
while ((i-j)>5) {
cur-=A[j++];
}
res=max(res,cur);
}
return res;
}
};
int main(){
Solution s;
vector<int> A1{0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0};
cout << s.whatAMole(A1,5) << endl;
vector<int> A2{0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0};
cout << s.whatAMoleTwoMallets(A2,5) << endl;
}
|
[
"gs0622@gmail.com"
] |
gs0622@gmail.com
|
49622d2936de25439968c35b7af165f44568c76d
|
cccfb7be281ca89f8682c144eac0d5d5559b2deb
|
/ash/components/phonehub/fake_camera_roll_download_manager.h
|
4d531c34b167ddd565953dec22279be5f1610752
|
[
"BSD-3-Clause"
] |
permissive
|
SREERAGI18/chromium
|
172b23d07568a4e3873983bf49b37adc92453dd0
|
fd8a8914ca0183f0add65ae55f04e287543c7d4a
|
refs/heads/master
| 2023-08-27T17:45:48.928019
| 2021-11-11T22:24:28
| 2021-11-11T22:24:28
| 428,659,250
| 1
| 0
|
BSD-3-Clause
| 2021-11-16T13:08:14
| 2021-11-16T13:08:14
| null |
UTF-8
|
C++
| false
| false
| 1,901
|
h
|
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ASH_COMPONENTS_PHONEHUB_FAKE_CAMERA_ROLL_DOWNLOAD_MANAGER_H_
#define ASH_COMPONENTS_PHONEHUB_FAKE_CAMERA_ROLL_DOWNLOAD_MANAGER_H_
#include <vector>
#include "ash/components/phonehub/camera_roll_download_manager.h"
#include "ash/components/phonehub/proto/phonehub_api.pb.h"
#include "base/containers/flat_map.h"
#include "chromeos/services/secure_channel/public/mojom/secure_channel_types.mojom.h"
namespace chromeos {
namespace phonehub {
class FakeCameraRollDownloadManager : public CameraRollDownloadManager {
public:
FakeCameraRollDownloadManager();
~FakeCameraRollDownloadManager() override;
// CameraRollDownloadManager:
void CreatePayloadFiles(
int64_t payload_id,
const chromeos::phonehub::proto::CameraRollItemMetadata& item_metadata,
CreatePayloadFilesCallback payload_files_callback) override;
void UpdateDownloadProgress(
chromeos::secure_channel::mojom::FileTransferUpdatePtr update) override;
void DeleteFile(int64_t payload_id) override;
void set_should_create_payload_files_succeed(
bool should_create_payload_files_succeed) {
should_create_payload_files_succeed_ = should_create_payload_files_succeed;
}
const std::vector<chromeos::secure_channel::mojom::FileTransferUpdatePtr>&
GetFileTransferUpdates(int64_t payload_id) const;
private:
bool should_create_payload_files_succeed_ = true;
// A map from payload IDs to the list of FileTransferUpdate received for each
// payload.
base::flat_map<
int64_t,
std::vector<chromeos::secure_channel::mojom::FileTransferUpdatePtr>>
payload_update_map_;
};
} // namespace phonehub
} // namespace chromeos
#endif // ASH_COMPONENTS_PHONEHUB_FAKE_CAMERA_ROLL_DOWNLOAD_MANAGER_H_
|
[
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] |
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.