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 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
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 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4f36de3b1fa5a052976455d87abd7fbe6ebfb315 | bcffab1693654b9d032525024991f6749c27c030 | /S2Engine/s2Renderer/src/AttributeBuffer.h | bd5f679cb33b1978be999dabb67c09bc956c91a6 | [] | no_license | danielevacca81/S2Engine | 9a954b6155033c0029033fc798d0d8df087a1224 | 113caabc9dc72ccf42742de77e35f733e14216ab | refs/heads/master | 2021-06-13T21:43:13.220620 | 2019-08-19T12:55:07 | 2019-08-19T12:55:07 | 133,978,244 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,961 | h | // AttributeBuffer.h
//
#ifndef ATTRIBUTEBUFFER_ONCE
#define ATTRIBUTEBUFFER_ONCE
#include "VertexBuffer.h"
#include "s2Renderer_API.h"
namespace s2 {
namespace Renderer {
/************************************************************************************************/
/* AttributeBuffer */
/************************************************************************************************/
class S2RENDERER_API AttributeBuffer
{
public:
enum ComponentDatatype
{
Byte,
UnsignedByte,
Short,
UnsignedShort,
Int,
UnsignedInt,
Float,
HalfFloat,
Double,
};
public:
//OBJECT_DECLARE_MOVEABLE( AttributeBuffer )
//OBJECT_DISABLE_COPY( AttributeBuffer )
AttributeBuffer();
~AttributeBuffer();
void set(
const VertexBuffer &buffer,
const ComponentDatatype &componentDatatype,
int numberOfComponents,
bool normalize = false,
int offset = 0,
int stride = 0 );
void attach( int loc );
void detach();
ComponentDatatype componentDatatype() const { return _componentDatatype; }
bool isValid() const { return _valid; }
int numberOfComponents() const { return _numberOfComponents; }
int offset() const { return _offset; }
bool normalize() const { return _normalize; }
//int sizeInBytes() const { return _size; }
int strideInBytes() const { return _stride; }
int numberOfVertices() const { return _vertexBuffer.sizeInBytes() / _stride; }
private:
VertexBuffer _vertexBuffer;
ComponentDatatype _componentDatatype;
int _location;
int _numberOfComponents;
int64_t _offset;
int64_t _stride;
bool _normalize;
bool _valid;
};
} // namespace Renderer
}
#endif | [
"d.vacca@idsgeoradar.com"
] | d.vacca@idsgeoradar.com |
f064275aeeb7b752f67536cae6a823a513e82bb9 | eb5058b44c68708f29e5573e3ff8d4bcceef550b | /v-spmines/Script.h | 4748b5230333385c6bafd50b37b4dd2e5a15a971 | [
"MIT"
] | permissive | root-cause/v-spmines | fb5ccea13393b02b33c5013711c46ee784731a9a | d62decaf0bafd540067159078de6d509dffae221 | refs/heads/master | 2022-04-20T16:44:31.392228 | 2020-04-17T10:35:05 | 2020-04-17T10:35:05 | 252,197,123 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 695 | h | #pragma once
#include "Logger.h"
struct MineSetData
{
Hash model;
std::vector<Hash> weaponHashes;
};
const unsigned int INPUT_VEH_HORN = 86;
const unsigned int MineCooldown = 750; // In milliseconds
void ScriptInit();
void ScriptUpdate();
void LoadModel(Hash modelHash);
Vector3 func_8595(const Vector3& vParam0, const Vector3& vParam1, float fParam2, float fParam3, float fParam4);
float func_8596(float fParam0, float fParam1, float fParam2, float fParam3, float fParam4);
void func_8597(Vehicle vehicleEntity, Hash vehicleModel, Vector3& uParam2, Vector3& uParam3, Vector3& uParam4, Vector3& uParam5);
static Logger ScriptLog(fmt::format("{}.log", MOD_NAME), LogLevel::LOG_INFO, true); | [
"32650536+root-cause@users.noreply.github.com"
] | 32650536+root-cause@users.noreply.github.com |
d23eabb61b74fb8579935364f45630048199a79d | 24f26275ffcd9324998d7570ea9fda82578eeb9e | /chrome/browser/extensions/api/web_request/web_request_api_unittest.cc | c5e4046588cd05558013c94dea6f0d306303bf2f | [
"BSD-3-Clause"
] | permissive | Vizionnation/chromenohistory | 70a51193c8538d7b995000a1b2a654e70603040f | 146feeb85985a6835f4b8826ad67be9195455402 | refs/heads/master | 2022-12-15T07:02:54.461083 | 2019-10-25T15:07:06 | 2019-10-25T15:07:06 | 217,557,501 | 2 | 1 | BSD-3-Clause | 2022-11-19T06:53:07 | 2019-10-25T14:58:54 | null | UTF-8 | C++ | false | false | 63,332 | 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 <stddef.h>
#include <stdint.h>
#include <map>
#include <memory>
#include <tuple>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/containers/queue.h"
#include "base/files/file_path.h"
#include "base/json/json_reader.h"
#include "base/json/json_string_value_serializer.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/memory/weak_ptr.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_split.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "base/values.h"
#include "chrome/browser/content_settings/cookie_settings_factory.h"
#include "chrome/browser/extensions/event_router_forwarder.h"
#include "chrome/browser/renderer_host/chrome_navigation_ui_data.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile.h"
#include "chrome/test/base/testing_profile_manager.h"
#include "components/content_settings/core/browser/cookie_settings.h"
#include "components/prefs/pref_member.h"
#include "components/sync_preferences/testing_pref_service_syncable.h"
#include "content/public/common/url_constants.h"
#include "content/public/test/browser_task_environment.h"
#include "extensions/browser/api/declarative_net_request/test_utils.h"
#include "extensions/browser/api/web_request/upload_data_presenter.h"
#include "extensions/browser/api/web_request/web_request_api.h"
#include "extensions/browser/api/web_request/web_request_api_constants.h"
#include "extensions/browser/api/web_request/web_request_api_helpers.h"
#include "extensions/browser/api/web_request/web_request_info.h"
#include "extensions/common/api/web_request.h"
#include "extensions/common/constants.h"
#include "extensions/common/extension_messages.h"
#include "extensions/common/features/feature.h"
#include "google_apis/gaia/gaia_urls.h"
#include "net/http/http_util.h"
#include "services/network/public/cpp/features.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest-message.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom-forward.h"
#if defined(OS_CHROMEOS)
#include "chromeos/login/login_state/scoped_test_public_session_login_state.h"
#include "components/crx_file/id_util.h"
#endif
namespace helpers = extension_web_request_api_helpers;
namespace keys = extension_web_request_api_constants;
namespace web_request = extensions::api::web_request;
using base::DictionaryValue;
using base::ListValue;
using base::Time;
using base::TimeDelta;
using base::Value;
using helpers::CalculateOnAuthRequiredDelta;
using helpers::CalculateOnBeforeRequestDelta;
using helpers::CalculateOnBeforeSendHeadersDelta;
using helpers::CalculateOnHeadersReceivedDelta;
using helpers::CharListToString;
using helpers::EventResponseDelta;
using helpers::EventResponseDeltas;
using helpers::ExtraInfoSpec;
using helpers::InDecreasingExtensionInstallationTimeOrder;
using helpers::MergeCancelOfResponses;
using helpers::MergeOnBeforeRequestResponses;
using helpers::RequestCookieModification;
using helpers::ResponseCookieModification;
using helpers::ResponseHeader;
using helpers::ResponseHeaders;
using helpers::StringToCharList;
using testing::ElementsAre;
using DNRRequestAction = extensions::declarative_net_request::RequestAction;
namespace extensions {
namespace {
constexpr const char kExampleUrl[] = "http://example.com";
// Returns whether |warnings| contains an extension for |extension_id|.
bool HasIgnoredAction(const helpers::IgnoredActions& ignored_actions,
const std::string& extension_id,
web_request::IgnoredActionType action_type) {
for (const auto& ignored_action : ignored_actions) {
if (ignored_action.extension_id == extension_id &&
ignored_action.action_type == action_type) {
return true;
}
}
return false;
}
} // namespace
// A mock event router that responds to events with a pre-arranged queue of
// Tasks.
class TestIPCSender : public IPC::Sender {
public:
using SentMessages = std::list<std::unique_ptr<IPC::Message>>;
// Adds a Task to the queue. We will fire these in order as events are
// dispatched.
void PushTask(const base::Closure& task) {
task_queue_.push(task);
}
size_t GetNumTasks() { return task_queue_.size(); }
SentMessages::const_iterator sent_begin() const {
return sent_messages_.begin();
}
SentMessages::const_iterator sent_end() const {
return sent_messages_.end();
}
private:
// IPC::Sender
bool Send(IPC::Message* message) override {
EXPECT_EQ(static_cast<uint32_t>(ExtensionMsg_DispatchEvent::ID),
message->type());
EXPECT_FALSE(task_queue_.empty());
base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
task_queue_.front());
task_queue_.pop();
sent_messages_.push_back(base::WrapUnique(message));
return true;
}
base::queue<base::Closure> task_queue_;
SentMessages sent_messages_;
};
class ExtensionWebRequestTest : public testing::Test {
public:
ExtensionWebRequestTest()
: task_environment_(content::BrowserTaskEnvironment::IO_MAINLOOP),
profile_manager_(TestingBrowserProcess::GetGlobal()) {}
protected:
void SetUp() override {
ASSERT_TRUE(profile_manager_.SetUp());
}
content::BrowserTaskEnvironment task_environment_;
TestingProfile profile_;
TestingProfileManager profile_manager_;
};
namespace {
// Create the numerical representation of |values|, strings passed as
// extraInfoSpec by the event handler. Returns true on success, otherwise false.
bool GenerateInfoSpec(content::BrowserContext* browser_context,
const std::string& values,
int* result) {
// Create a base::ListValue of strings.
base::ListValue list_value;
for (const std::string& cur :
base::SplitString(values, ",", base::KEEP_WHITESPACE,
base::SPLIT_WANT_NONEMPTY))
list_value.AppendString(cur);
return ExtraInfoSpec::InitFromValue(browser_context, list_value, result);
}
} // namespace
// Tests that |render_process_id| is not relevant for adding and removing
// listeners with |web_view_instance_id| = 0.
TEST_F(ExtensionWebRequestTest, AddAndRemoveListeners) {
std::string ext_id("abcdefghijklmnopabcdefghijklmnop");
ExtensionWebRequestEventRouter::RequestFilter filter;
const std::string kEventName(web_request::OnBeforeRequest::kEventName);
const std::string kSubEventName = kEventName + "/1";
EXPECT_EQ(
0u,
ExtensionWebRequestEventRouter::GetInstance()->GetListenerCountForTesting(
&profile_, kEventName));
// Add two non-webview listeners.
ExtensionWebRequestEventRouter::GetInstance()->AddEventListener(
&profile_, ext_id, ext_id, events::FOR_TEST, kEventName, kSubEventName,
filter, 0, 1 /* render_process_id */, 0, extensions::kMainThreadId,
blink::mojom::kInvalidServiceWorkerVersionId);
ExtensionWebRequestEventRouter::GetInstance()->AddEventListener(
&profile_, ext_id, ext_id, events::FOR_TEST, kEventName, kSubEventName,
filter, 0, 2 /* render_process_id */, 0, extensions::kMainThreadId,
blink::mojom::kInvalidServiceWorkerVersionId);
EXPECT_EQ(
2u,
ExtensionWebRequestEventRouter::GetInstance()->GetListenerCountForTesting(
&profile_, kEventName));
// Now remove the events without passing an explicit process ID.
ExtensionWebRequestEventRouter::EventListener::ID id1(
&profile_, ext_id, kSubEventName, 0, 0, extensions::kMainThreadId,
blink::mojom::kInvalidServiceWorkerVersionId);
ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id1,
false);
EXPECT_EQ(
1u,
ExtensionWebRequestEventRouter::GetInstance()->GetListenerCountForTesting(
&profile_, kEventName));
ExtensionWebRequestEventRouter::GetInstance()->RemoveEventListener(id1,
false);
EXPECT_EQ(
0u,
ExtensionWebRequestEventRouter::GetInstance()->GetListenerCountForTesting(
&profile_, kEventName));
}
namespace {
void TestInitFromValue(content::BrowserContext* browser_context,
const std::string& values,
bool expected_return_code,
int expected_extra_info_spec) {
int actual_info_spec;
bool actual_return_code =
GenerateInfoSpec(browser_context, values, &actual_info_spec);
EXPECT_EQ(expected_return_code, actual_return_code);
if (expected_return_code)
EXPECT_EQ(expected_extra_info_spec, actual_info_spec);
}
} // namespace
TEST_F(ExtensionWebRequestTest, InitFromValue) {
TestInitFromValue(&profile_, std::string(), true, 0);
// Single valid values.
TestInitFromValue(&profile_, "requestHeaders", true,
ExtraInfoSpec::REQUEST_HEADERS);
TestInitFromValue(&profile_, "responseHeaders", true,
ExtraInfoSpec::RESPONSE_HEADERS);
TestInitFromValue(&profile_, "blocking", true, ExtraInfoSpec::BLOCKING);
TestInitFromValue(&profile_, "asyncBlocking", true,
ExtraInfoSpec::ASYNC_BLOCKING);
TestInitFromValue(&profile_, "requestBody", true,
ExtraInfoSpec::REQUEST_BODY);
// Multiple valid values are bitwise-or'ed.
TestInitFromValue(&profile_, "requestHeaders,blocking", true,
ExtraInfoSpec::REQUEST_HEADERS | ExtraInfoSpec::BLOCKING);
// Any invalid values lead to a bad parse.
TestInitFromValue(&profile_, "invalidValue", false, 0);
TestInitFromValue(&profile_, "blocking,invalidValue", false, 0);
TestInitFromValue(&profile_, "invalidValue1,invalidValue2", false, 0);
// BLOCKING and ASYNC_BLOCKING are mutually exclusive.
TestInitFromValue(&profile_, "blocking,asyncBlocking", false, 0);
}
TEST(ExtensionWebRequestHelpersTest,
TestInDecreasingExtensionInstallationTimeOrder) {
EventResponseDelta a("ext_1", base::Time::FromInternalValue(0));
EventResponseDelta b("ext_2", base::Time::FromInternalValue(1000));
EXPECT_FALSE(InDecreasingExtensionInstallationTimeOrder(a, a));
EXPECT_FALSE(InDecreasingExtensionInstallationTimeOrder(a, b));
EXPECT_TRUE(InDecreasingExtensionInstallationTimeOrder(b, a));
}
TEST(ExtensionWebRequestHelpersTest, TestStringToCharList) {
base::ListValue list_value;
list_value.AppendInteger('1');
list_value.AppendInteger('2');
list_value.AppendInteger('3');
list_value.AppendInteger(0xFE);
list_value.AppendInteger(0xD1);
unsigned char char_value[] = {'1', '2', '3', 0xFE, 0xD1};
std::string string_value(reinterpret_cast<char *>(char_value), 5);
std::unique_ptr<base::ListValue> converted_list(
StringToCharList(string_value));
EXPECT_TRUE(list_value.Equals(converted_list.get()));
std::string converted_string;
EXPECT_TRUE(CharListToString(&list_value, &converted_string));
EXPECT_EQ(string_value, converted_string);
}
TEST(ExtensionWebRequestHelpersTest, TestCalculateOnBeforeRequestDelta) {
const bool cancel = true;
const GURL localhost("http://localhost");
EventResponseDelta delta = CalculateOnBeforeRequestDelta(
"extid", base::Time::Now(), cancel, localhost);
EXPECT_TRUE(delta.cancel);
EXPECT_EQ(localhost, delta.new_url);
}
TEST(ExtensionWebRequestHelpersTest, TestCalculateOnBeforeSendHeadersDelta) {
const bool cancel = true;
std::string value;
net::HttpRequestHeaders old_headers;
old_headers.SetHeader("key1", "value1");
old_headers.SetHeader("key2", "value2");
// Test adding a header.
net::HttpRequestHeaders new_headers_added;
new_headers_added.SetHeader("key1", "value1");
new_headers_added.SetHeader("key3", "value3");
new_headers_added.SetHeader("key2", "value2");
EventResponseDelta delta_added = CalculateOnBeforeSendHeadersDelta(
nullptr /* browser_context */, "extid", base::Time::Now(), cancel,
&old_headers, &new_headers_added, 0 /* extra_info_spec */);
EXPECT_TRUE(delta_added.cancel);
ASSERT_TRUE(delta_added.modified_request_headers.GetHeader("key3", &value));
EXPECT_EQ("value3", value);
// Test deleting a header.
net::HttpRequestHeaders new_headers_deleted;
new_headers_deleted.SetHeader("key1", "value1");
EventResponseDelta delta_deleted = CalculateOnBeforeSendHeadersDelta(
nullptr /* browser_context */, "extid", base::Time::Now(), cancel,
&old_headers, &new_headers_deleted, 0 /* extra_info_spec */);
ASSERT_EQ(1u, delta_deleted.deleted_request_headers.size());
ASSERT_EQ("key2", delta_deleted.deleted_request_headers.front());
// Test modifying a header.
net::HttpRequestHeaders new_headers_modified;
new_headers_modified.SetHeader("key1", "value1");
new_headers_modified.SetHeader("key2", "value3");
EventResponseDelta delta_modified = CalculateOnBeforeSendHeadersDelta(
nullptr /* browser_context */, "extid", base::Time::Now(), cancel,
&old_headers, &new_headers_modified, 0 /* extra_info_spec */);
EXPECT_TRUE(delta_modified.deleted_request_headers.empty());
ASSERT_TRUE(
delta_modified.modified_request_headers.GetHeader("key2", &value));
EXPECT_EQ("value3", value);
// Test modifying a header if extension author just appended a new (key,
// value) pair with a key that existed before. This is incorrect
// usage of the API that shall be handled gracefully.
net::HttpRequestHeaders new_headers_modified2;
new_headers_modified2.SetHeader("key1", "value1");
new_headers_modified2.SetHeader("key2", "value2");
new_headers_modified2.SetHeader("key2", "value3");
EventResponseDelta delta_modified2 = CalculateOnBeforeSendHeadersDelta(
nullptr /* browser_context */, "extid", base::Time::Now(), cancel,
&old_headers, &new_headers_modified, 0 /* extra_info_spec */);
EXPECT_TRUE(delta_modified2.deleted_request_headers.empty());
ASSERT_TRUE(
delta_modified2.modified_request_headers.GetHeader("key2", &value));
EXPECT_EQ("value3", value);
}
TEST(ExtensionWebRequestHelpersTest,
TestCalculateOnBeforeSendHeadersDeltaWithExtraHeaders) {
for (const std::string& name :
{"accept-encoding", "accept-language", "cookie", "referer"}) {
net::HttpRequestHeaders old_headers;
old_headers.SetHeader("key1", "value1");
// Test adding a special header.
net::HttpRequestHeaders new_headers = old_headers;
new_headers.SetHeader(name, "value");
EventResponseDelta delta = CalculateOnBeforeSendHeadersDelta(
nullptr /* browser_context */, "extid", base::Time::Now(), false,
&old_headers, &new_headers, 0 /* extra_info_spec */);
EXPECT_FALSE(delta.modified_request_headers.HasHeader(name));
// Test with extra headers in spec.
delta = CalculateOnBeforeSendHeadersDelta(
nullptr /* browser_context */, "extid", base::Time::Now(), false,
&old_headers, &new_headers, ExtraInfoSpec::EXTRA_HEADERS);
std::string value;
EXPECT_TRUE(delta.modified_request_headers.GetHeader(name, &value));
EXPECT_EQ("value", value);
// Test removing a special header.
new_headers = old_headers;
// Add header to old headers, it will be treated as removed.
old_headers.SetHeader(name, "value");
delta = CalculateOnBeforeSendHeadersDelta(
nullptr /* browser_context */, "extid", base::Time::Now(), false,
&old_headers, &new_headers, 0 /* extra_info_spec */);
EXPECT_TRUE(delta.deleted_request_headers.empty());
// Test with extra headers in spec.
delta = CalculateOnBeforeSendHeadersDelta(
nullptr /* browser_context */, "extid", base::Time::Now(), false,
&old_headers, &new_headers, ExtraInfoSpec::EXTRA_HEADERS);
EXPECT_THAT(delta.deleted_request_headers, ElementsAre(name));
}
}
TEST(ExtensionWebRequestHelpersTest, TestCalculateOnHeadersReceivedDelta) {
const bool cancel = true;
std::string base_headers_string =
"HTTP/1.0 200 OK\r\n"
"Key1: Value1\r\n"
"Key2: Value2, Bar\r\n"
"Key3: Value3\r\n"
"Key5: Value5, end5\r\n"
"X-Chrome-ID-Consistency-Response: Value6\r\n"
"\r\n";
auto base_headers = base::MakeRefCounted<net::HttpResponseHeaders>(
net::HttpUtil::AssembleRawHeaders(base_headers_string));
ResponseHeaders new_headers = {
{"kEy1", "Value1"}, // Unchanged
{"Key2", "Value1"}, // Modified
// Key3 is deleted
{"Key4", "Value4"}, // Added
{"Key5", "Value5, end5"}, // Unchanged
{"X-Chrome-ID-Consistency-Response", "Value1"} // Modified
};
GURL url;
// The X-Chrome-ID-Consistency-Response is a protected header, but only for
// Gaia URLs. It should be modifiable when sent from anywhere else.
// Non-Gaia URL:
EventResponseDelta delta = CalculateOnHeadersReceivedDelta(
"extid", base::Time::Now(), cancel, url, url, base_headers.get(),
&new_headers, 0 /* extra_info_spec */);
EXPECT_TRUE(delta.cancel);
EXPECT_THAT(
delta.added_response_headers,
ElementsAre(
ResponseHeader("Key2", "Value1"), ResponseHeader("Key4", "Value4"),
ResponseHeader("X-Chrome-ID-Consistency-Response", "Value1")));
EXPECT_THAT(delta.deleted_response_headers,
ElementsAre(ResponseHeader("Key2", "Value2, Bar"),
ResponseHeader("Key3", "Value3"),
ResponseHeader("X-Chrome-ID-Consistency-Response",
"Value6")));
// Gaia URL:
delta = CalculateOnHeadersReceivedDelta(
"extid", base::Time::Now(), cancel, GaiaUrls::GetInstance()->gaia_url(),
url, base_headers.get(), &new_headers, 0 /* extra_info_spec */);
EXPECT_TRUE(delta.cancel);
EXPECT_THAT(delta.added_response_headers,
ElementsAre(ResponseHeader("Key2", "Value1"),
ResponseHeader("Key4", "Value4")));
EXPECT_THAT(delta.deleted_response_headers,
ElementsAre(ResponseHeader("Key2", "Value2, Bar"),
ResponseHeader("Key3", "Value3")));
}
TEST(ExtensionWebRequestHelpersTest,
TestCalculateOnHeadersReceivedDeltaWithExtraHeaders) {
std::string base_headers_string =
"HTTP/1.0 200 OK\r\n"
"Key1: Value1\r\n";
auto base_headers = base::MakeRefCounted<net::HttpResponseHeaders>(
net::HttpUtil::AssembleRawHeaders(base_headers_string));
ResponseHeaders new_headers = {
{"Key1", "Value1"},
{"Set-Cookie", "cookie"},
};
EventResponseDelta delta = CalculateOnHeadersReceivedDelta(
"extid", base::Time::Now(), false, GURL(), GURL(), base_headers.get(),
&new_headers, 0 /* extra_info_spec */);
EXPECT_TRUE(delta.added_response_headers.empty());
EXPECT_TRUE(delta.deleted_response_headers.empty());
// Set-Cookie can be added if extra headers is set in options.
delta = CalculateOnHeadersReceivedDelta(
"extid", base::Time::Now(), false, GURL(), GURL(), base_headers.get(),
&new_headers, ExtraInfoSpec::EXTRA_HEADERS);
EXPECT_THAT(delta.added_response_headers,
ElementsAre(ResponseHeader("Set-Cookie", "cookie")));
EXPECT_TRUE(delta.deleted_response_headers.empty());
// Test deleting Set-Cookie header.
new_headers = {
{"Key1", "Value1"},
};
base_headers->AddCookie("cookie");
delta = CalculateOnHeadersReceivedDelta(
"extid", base::Time::Now(), false, GURL(), GURL(), base_headers.get(),
&new_headers, 0 /* extra_info_spec */);
EXPECT_TRUE(delta.added_response_headers.empty());
EXPECT_TRUE(delta.deleted_response_headers.empty());
delta = CalculateOnHeadersReceivedDelta(
"extid", base::Time::Now(), false, GURL(), GURL(), base_headers.get(),
&new_headers, ExtraInfoSpec::EXTRA_HEADERS);
EXPECT_TRUE(delta.added_response_headers.empty());
EXPECT_THAT(delta.deleted_response_headers,
ElementsAre(ResponseHeader("Set-Cookie", "cookie")));
}
TEST(ExtensionWebRequestHelpersTest, TestCalculateOnAuthRequiredDelta) {
const bool cancel = true;
base::string16 username = base::ASCIIToUTF16("foo");
base::string16 password = base::ASCIIToUTF16("bar");
net::AuthCredentials credentials(username, password);
EventResponseDelta delta = CalculateOnAuthRequiredDelta(
"extid", base::Time::Now(), cancel, credentials);
EXPECT_TRUE(delta.cancel);
ASSERT_TRUE(delta.auth_credentials.has_value());
EXPECT_EQ(username, delta.auth_credentials->username());
EXPECT_EQ(password, delta.auth_credentials->password());
}
TEST(ExtensionWebRequestHelpersTest, TestMergeCancelOfResponses) {
EventResponseDeltas deltas;
bool canceled = false;
// Single event that does not cancel.
{
EventResponseDelta d1("extid1", base::Time::FromInternalValue(1000));
d1.cancel = false;
deltas.push_back(std::move(d1));
}
MergeCancelOfResponses(deltas, &canceled);
EXPECT_FALSE(canceled);
// Second event that cancels the request
{
EventResponseDelta d2("extid2", base::Time::FromInternalValue(500));
d2.cancel = true;
deltas.push_back(std::move(d2));
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
MergeCancelOfResponses(deltas, &canceled);
EXPECT_TRUE(canceled);
}
TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeRequestResponses) {
EventResponseDeltas deltas;
helpers::IgnoredActions ignored_actions;
GURL effective_new_url;
// No redirect
{
EventResponseDelta d0("extid0", base::Time::FromInternalValue(0));
deltas.push_back(std::move(d0));
}
MergeOnBeforeRequestResponses(GURL(kExampleUrl), deltas, &effective_new_url,
&ignored_actions);
EXPECT_TRUE(effective_new_url.is_empty());
// Single redirect.
GURL new_url_1("http://foo.com");
{
EventResponseDelta d1("extid1", base::Time::FromInternalValue(1000));
d1.new_url = GURL(new_url_1);
deltas.push_back(std::move(d1));
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
MergeOnBeforeRequestResponses(GURL(kExampleUrl), deltas, &effective_new_url,
&ignored_actions);
EXPECT_EQ(new_url_1, effective_new_url);
EXPECT_TRUE(ignored_actions.empty());
// Ignored redirect (due to precedence).
GURL new_url_2("http://bar.com");
{
EventResponseDelta d2("extid2", base::Time::FromInternalValue(500));
d2.new_url = GURL(new_url_2);
deltas.push_back(std::move(d2));
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
MergeOnBeforeRequestResponses(GURL(kExampleUrl), deltas, &effective_new_url,
&ignored_actions);
EXPECT_EQ(new_url_1, effective_new_url);
EXPECT_EQ(1u, ignored_actions.size());
EXPECT_TRUE(HasIgnoredAction(ignored_actions, "extid2",
web_request::IGNORED_ACTION_TYPE_REDIRECT));
// Overriding redirect.
GURL new_url_3("http://baz.com");
{
EventResponseDelta d3("extid3", base::Time::FromInternalValue(1500));
d3.new_url = GURL(new_url_3);
deltas.push_back(std::move(d3));
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
MergeOnBeforeRequestResponses(GURL(kExampleUrl), deltas, &effective_new_url,
&ignored_actions);
EXPECT_EQ(new_url_3, effective_new_url);
EXPECT_EQ(2u, ignored_actions.size());
EXPECT_TRUE(HasIgnoredAction(ignored_actions, "extid1",
web_request::IGNORED_ACTION_TYPE_REDIRECT));
EXPECT_TRUE(HasIgnoredAction(ignored_actions, "extid2",
web_request::IGNORED_ACTION_TYPE_REDIRECT));
// Check that identical redirects don't cause a conflict.
{
EventResponseDelta d4("extid4", base::Time::FromInternalValue(2000));
d4.new_url = GURL(new_url_3);
deltas.push_back(std::move(d4));
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
MergeOnBeforeRequestResponses(GURL(kExampleUrl), deltas, &effective_new_url,
&ignored_actions);
EXPECT_EQ(new_url_3, effective_new_url);
EXPECT_EQ(2u, ignored_actions.size());
EXPECT_TRUE(HasIgnoredAction(ignored_actions, "extid1",
web_request::IGNORED_ACTION_TYPE_REDIRECT));
EXPECT_TRUE(HasIgnoredAction(ignored_actions, "extid2",
web_request::IGNORED_ACTION_TYPE_REDIRECT));
}
// This tests that we can redirect to data:// urls, which is considered
// a kind of cancelling requests.
TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeRequestResponses2) {
EventResponseDeltas deltas;
helpers::IgnoredActions ignored_actions;
GURL effective_new_url;
// Single redirect.
GURL new_url_0("http://foo.com");
{
EventResponseDelta d0("extid0", base::Time::FromInternalValue(2000));
d0.new_url = GURL(new_url_0);
deltas.push_back(std::move(d0));
}
MergeOnBeforeRequestResponses(GURL(kExampleUrl), deltas, &effective_new_url,
&ignored_actions);
EXPECT_EQ(new_url_0, effective_new_url);
// Cancel request by redirecting to a data:// URL. This shall override
// the other redirect but not cause any conflict warnings.
GURL new_url_1("data://foo");
{
EventResponseDelta d1("extid1", base::Time::FromInternalValue(1500));
d1.new_url = GURL(new_url_1);
deltas.push_back(std::move(d1));
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
MergeOnBeforeRequestResponses(GURL(kExampleUrl), deltas, &effective_new_url,
&ignored_actions);
EXPECT_EQ(new_url_1, effective_new_url);
EXPECT_TRUE(ignored_actions.empty());
// Cancel request by redirecting to the same data:// URL. This shall
// not create any conflicts as it is in line with d1.
GURL new_url_2("data://foo");
{
EventResponseDelta d2("extid2", base::Time::FromInternalValue(1000));
d2.new_url = GURL(new_url_2);
deltas.push_back(std::move(d2));
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
MergeOnBeforeRequestResponses(GURL(kExampleUrl), deltas, &effective_new_url,
&ignored_actions);
EXPECT_EQ(new_url_1, effective_new_url);
EXPECT_TRUE(ignored_actions.empty());
// Cancel redirect by redirecting to a different data:// URL. This needs
// to create a conflict.
GURL new_url_3("data://something_totally_different");
{
EventResponseDelta d3("extid3", base::Time::FromInternalValue(500));
d3.new_url = GURL(new_url_3);
deltas.push_back(std::move(d3));
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
MergeOnBeforeRequestResponses(GURL(kExampleUrl), deltas, &effective_new_url,
&ignored_actions);
EXPECT_EQ(new_url_1, effective_new_url);
EXPECT_EQ(1u, ignored_actions.size());
EXPECT_TRUE(HasIgnoredAction(ignored_actions, "extid3",
web_request::IGNORED_ACTION_TYPE_REDIRECT));
}
// This tests that we can redirect to about:blank, which is considered
// a kind of cancelling requests.
TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeRequestResponses3) {
EventResponseDeltas deltas;
helpers::IgnoredActions ignored_actions;
GURL effective_new_url;
// Single redirect.
GURL new_url_0("http://foo.com");
{
EventResponseDelta d0("extid0", base::Time::FromInternalValue(2000));
d0.new_url = GURL(new_url_0);
deltas.push_back(std::move(d0));
}
MergeOnBeforeRequestResponses(GURL(kExampleUrl), deltas, &effective_new_url,
&ignored_actions);
EXPECT_EQ(new_url_0, effective_new_url);
// Cancel request by redirecting to about:blank. This shall override
// the other redirect but not cause any conflict warnings.
GURL new_url_1("about:blank");
{
EventResponseDelta d1("extid1", base::Time::FromInternalValue(1500));
d1.new_url = GURL(new_url_1);
deltas.push_back(std::move(d1));
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
MergeOnBeforeRequestResponses(GURL(kExampleUrl), deltas, &effective_new_url,
&ignored_actions);
EXPECT_EQ(new_url_1, effective_new_url);
EXPECT_TRUE(ignored_actions.empty());
}
// This tests that WebSocket requests can not be redirected.
TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeRequestResponses4) {
EventResponseDeltas deltas;
helpers::IgnoredActions ignored_actions;
GURL effective_new_url;
// Single redirect.
{
EventResponseDelta delta("extid", base::Time::FromInternalValue(2000));
delta.new_url = GURL("http://foo.com");
deltas.push_back(std::move(delta));
}
MergeOnBeforeRequestResponses(GURL("ws://example.com"), deltas,
&effective_new_url, &ignored_actions);
EXPECT_EQ(GURL(), effective_new_url);
}
TEST(ExtensionWebRequestHelpersTest, TestMergeOnBeforeSendHeadersResponses) {
net::HttpRequestHeaders base_headers;
base_headers.SetHeader("key1", "value 1");
base_headers.SetHeader("key2", "value 2");
helpers::IgnoredActions ignored_actions;
std::string header_value;
EventResponseDeltas deltas;
// Check that we can handle not changing the headers.
{
EventResponseDelta d0("extid0", base::Time::FromInternalValue(2500));
deltas.push_back(std::move(d0));
}
bool request_headers_modified0;
std::set<std::string> ignore1, ignore2;
net::HttpRequestHeaders headers0;
headers0.MergeFrom(base_headers);
WebRequestInfoInitParams info_params;
WebRequestInfo info(std::move(info_params));
info.dnr_actions = std::vector<DNRRequestAction>();
MergeOnBeforeSendHeadersResponses(info, deltas, &headers0, &ignored_actions,
&ignore1, &ignore2,
&request_headers_modified0);
ASSERT_TRUE(headers0.GetHeader("key1", &header_value));
EXPECT_EQ("value 1", header_value);
ASSERT_TRUE(headers0.GetHeader("key2", &header_value));
EXPECT_EQ("value 2", header_value);
EXPECT_EQ(0u, ignored_actions.size());
EXPECT_FALSE(request_headers_modified0);
// Delete, modify and add a header.
{
EventResponseDelta d1("extid1", base::Time::FromInternalValue(2000));
d1.deleted_request_headers.push_back("key1");
d1.modified_request_headers.SetHeader("key2", "value 3");
d1.modified_request_headers.SetHeader("key3", "value 3");
deltas.push_back(std::move(d1));
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
ignore1.clear();
ignore2.clear();
bool request_headers_modified1;
net::HttpRequestHeaders headers1;
headers1.MergeFrom(base_headers);
MergeOnBeforeSendHeadersResponses(info, deltas, &headers1, &ignored_actions,
&ignore1, &ignore2,
&request_headers_modified1);
EXPECT_FALSE(headers1.HasHeader("key1"));
ASSERT_TRUE(headers1.GetHeader("key2", &header_value));
EXPECT_EQ("value 3", header_value);
ASSERT_TRUE(headers1.GetHeader("key3", &header_value));
EXPECT_EQ("value 3", header_value);
EXPECT_EQ(0u, ignored_actions.size());
EXPECT_TRUE(request_headers_modified1);
// Check that conflicts are atomic, i.e. if one header modification
// collides all other conflicts of the same extension are declined as well.
{
EventResponseDelta d2("extid2", base::Time::FromInternalValue(1500));
// This one conflicts:
d2.modified_request_headers.SetHeader("key3", "value 0");
d2.modified_request_headers.SetHeader("key4", "value 4");
deltas.push_back(std::move(d2));
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
ignore1.clear();
ignore2.clear();
bool request_headers_modified2;
net::HttpRequestHeaders headers2;
headers2.MergeFrom(base_headers);
MergeOnBeforeSendHeadersResponses(info, deltas, &headers2, &ignored_actions,
&ignore1, &ignore2,
&request_headers_modified2);
EXPECT_FALSE(headers2.HasHeader("key1"));
ASSERT_TRUE(headers2.GetHeader("key2", &header_value));
EXPECT_EQ("value 3", header_value);
ASSERT_TRUE(headers2.GetHeader("key3", &header_value));
EXPECT_EQ("value 3", header_value);
EXPECT_FALSE(headers2.HasHeader("key4"));
EXPECT_EQ(1u, ignored_actions.size());
EXPECT_TRUE(
HasIgnoredAction(ignored_actions, "extid2",
web_request::IGNORED_ACTION_TYPE_REQUEST_HEADERS));
EXPECT_TRUE(request_headers_modified2);
// Check that identical modifications don't conflict and operations
// can be merged.
{
EventResponseDelta d3("extid3", base::Time::FromInternalValue(1000));
d3.deleted_request_headers.push_back("key1");
d3.modified_request_headers.SetHeader("key2", "value 3");
d3.modified_request_headers.SetHeader("key5", "value 5");
deltas.push_back(std::move(d3));
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
ignore1.clear();
ignore2.clear();
bool request_headers_modified3;
net::HttpRequestHeaders headers3;
headers3.MergeFrom(base_headers);
MergeOnBeforeSendHeadersResponses(info, deltas, &headers3, &ignored_actions,
&ignore1, &ignore2,
&request_headers_modified3);
EXPECT_FALSE(headers3.HasHeader("key1"));
ASSERT_TRUE(headers3.GetHeader("key2", &header_value));
EXPECT_EQ("value 3", header_value);
ASSERT_TRUE(headers3.GetHeader("key3", &header_value));
EXPECT_EQ("value 3", header_value);
ASSERT_TRUE(headers3.GetHeader("key5", &header_value));
EXPECT_EQ("value 5", header_value);
EXPECT_EQ(1u, ignored_actions.size());
EXPECT_TRUE(
HasIgnoredAction(ignored_actions, "extid2",
web_request::IGNORED_ACTION_TYPE_REQUEST_HEADERS));
EXPECT_TRUE(request_headers_modified3);
// Check that headers removed by Declarative Net Request API can't be modified
// and result in a conflict.
ignored_actions.clear();
ignore1.clear();
ignore2.clear();
bool request_headers_modified4 = false;
net::HttpRequestHeaders headers4;
headers4.MergeFrom(base_headers);
DNRRequestAction remove_headers_action =
CreateRequestActionForTesting(DNRRequestAction::Type::REMOVE_HEADERS);
remove_headers_action.request_headers_to_remove = {"key5"};
info.dnr_actions = std::vector<DNRRequestAction>();
info.dnr_actions->push_back(std::move(remove_headers_action));
MergeOnBeforeSendHeadersResponses(info, deltas, &headers4, &ignored_actions,
&ignore1, &ignore2,
&request_headers_modified4);
// deleted by |d1|.
EXPECT_FALSE(headers4.HasHeader("key1"));
// Added by |d1|.
ASSERT_TRUE(headers4.GetHeader("key2", &header_value));
EXPECT_EQ("value 3", header_value);
// Removed by Declarative Net Request API.
EXPECT_FALSE(headers4.HasHeader("key5"));
EXPECT_EQ(2u, ignored_actions.size());
EXPECT_TRUE(
HasIgnoredAction(ignored_actions, "extid2",
web_request::IGNORED_ACTION_TYPE_REQUEST_HEADERS));
EXPECT_TRUE(
HasIgnoredAction(ignored_actions, "extid2",
web_request::IGNORED_ACTION_TYPE_REQUEST_HEADERS));
EXPECT_TRUE(
HasIgnoredAction(ignored_actions, "extid3",
web_request::IGNORED_ACTION_TYPE_REQUEST_HEADERS));
EXPECT_TRUE(request_headers_modified4);
}
// Ensure conflicts between different extensions are handled correctly with
// header names being interpreted in a case insensitive manner. Regression test
// for crbug.com/956795.
TEST(ExtensionWebRequestHelpersTest,
TestMergeOnBeforeSendHeadersResponses_Conflicts) {
// Have two extensions which both modify header "key1".
EventResponseDeltas deltas;
{
EventResponseDelta d1("extid1", base::Time::FromInternalValue(2000));
d1.modified_request_headers.SetHeader("key1", "ext1");
deltas.push_back(std::move(d1));
}
{
EventResponseDelta d2("extid2", base::Time::FromInternalValue(1000));
d2.modified_request_headers.SetHeader("KEY1", "ext2");
deltas.push_back(std::move(d2));
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
WebRequestInfoInitParams info_params;
WebRequestInfo info(std::move(info_params));
info.dnr_actions = std::vector<DNRRequestAction>();
helpers::IgnoredActions ignored_actions;
std::set<std::string> removed_headers, set_headers;
bool request_headers_modified = false;
net::HttpRequestHeaders headers;
headers.SetHeader("key1", "value 1");
MergeOnBeforeSendHeadersResponses(info, deltas, &headers, &ignored_actions,
&removed_headers, &set_headers,
&request_headers_modified);
std::string header_value;
ASSERT_TRUE(headers.GetHeader("key1", &header_value));
EXPECT_EQ("ext1", header_value);
EXPECT_EQ(1u, ignored_actions.size());
EXPECT_TRUE(request_headers_modified);
EXPECT_THAT(removed_headers, ::testing::IsEmpty());
EXPECT_THAT(set_headers, ElementsAre("key1"));
}
TEST(ExtensionWebRequestHelpersTest,
TestMergeOnBeforeSendHeadersResponses_Cookies) {
net::HttpRequestHeaders base_headers;
base_headers.SetHeader("Cookie",
"name=value; name2=value2; name3=\"value3\"");
helpers::IgnoredActions ignored_actions;
std::string header_value;
EventResponseDeltas deltas;
RequestCookieModification add_cookie;
add_cookie.type = helpers::ADD;
add_cookie.modification.emplace();
add_cookie.modification->name = "name4";
add_cookie.modification->value = "\"value 4\"";
RequestCookieModification add_cookie_2;
add_cookie_2.type = helpers::ADD;
add_cookie_2.modification.emplace();
add_cookie_2.modification->name = "name";
add_cookie_2.modification->value = "new value";
RequestCookieModification edit_cookie;
edit_cookie.type = helpers::EDIT;
edit_cookie.filter.emplace();
edit_cookie.filter->name = "name2";
edit_cookie.modification.emplace();
edit_cookie.modification->value = "new value";
RequestCookieModification remove_cookie;
remove_cookie.type = helpers::REMOVE;
remove_cookie.filter.emplace();
remove_cookie.filter->name = "name3";
RequestCookieModification* operations[] = {&add_cookie, &add_cookie_2,
&edit_cookie, &remove_cookie};
int64_t time = 0;
for (auto* operation : operations) {
EventResponseDelta delta("extid0",
base::Time::FromInternalValue(time++ * 5));
delta.request_cookie_modifications.push_back(std::move(*operation));
deltas.push_back(std::move(delta));
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
bool request_headers_modified1;
std::set<std::string> ignore1, ignore2;
net::HttpRequestHeaders headers1;
headers1.MergeFrom(base_headers);
ignored_actions.clear();
WebRequestInfoInitParams info_params;
WebRequestInfo info(std::move(info_params));
MergeOnBeforeSendHeadersResponses(info, deltas, &headers1, &ignored_actions,
&ignore1, &ignore2,
&request_headers_modified1);
EXPECT_TRUE(headers1.HasHeader("Cookie"));
ASSERT_TRUE(headers1.GetHeader("Cookie", &header_value));
EXPECT_EQ("name=new value; name2=new value; name4=\"value 4\"", header_value);
EXPECT_EQ(0u, ignored_actions.size());
EXPECT_FALSE(request_headers_modified1);
}
namespace {
std::string GetCookieExpirationDate(int delta_secs) {
const char* const kWeekDays[] = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
};
const char* const kMonthNames[] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
Time::Exploded exploded_time;
(Time::Now() + TimeDelta::FromSeconds(delta_secs)).UTCExplode(&exploded_time);
return base::StringPrintf("%s, %d %s %d %.2d:%.2d:%.2d GMT",
kWeekDays[exploded_time.day_of_week],
exploded_time.day_of_month,
kMonthNames[exploded_time.month - 1],
exploded_time.year,
exploded_time.hour,
exploded_time.minute,
exploded_time.second);
}
} // namespace
TEST(ExtensionWebRequestHelpersTest,
TestMergeCookiesInOnHeadersReceivedResponses) {
std::string header_value;
EventResponseDeltas deltas;
std::string cookie_expiration = GetCookieExpirationDate(1200);
std::string base_headers_string =
"HTTP/1.0 200 OK\r\n"
"Foo: Bar\r\n"
"Set-Cookie: name=value; DOMAIN=google.com; Secure\r\n"
"Set-Cookie: name2=value2\r\n"
"Set-Cookie: name3=value3\r\n"
"Set-Cookie: lBound1=value5; Expires=" + cookie_expiration + "\r\n"
"Set-Cookie: lBound2=value6; Max-Age=1200\r\n"
"Set-Cookie: lBound3=value7; Max-Age=2000\r\n"
"Set-Cookie: uBound1=value8; Expires=" + cookie_expiration + "\r\n"
"Set-Cookie: uBound2=value9; Max-Age=1200\r\n"
"Set-Cookie: uBound3=value10; Max-Age=2000\r\n"
"Set-Cookie: uBound4=value11; Max-Age=2500\r\n"
"Set-Cookie: uBound5=value12; Max-Age=600; Expires=" +
cookie_expiration + "\r\n"
"Set-Cookie: uBound6=removed; Max-Age=600\r\n"
"Set-Cookie: sessionCookie=removed; Max-Age=INVALID\r\n"
"Set-Cookie: sessionCookie2=removed\r\n"
"\r\n";
auto base_headers = base::MakeRefCounted<net::HttpResponseHeaders>(
net::HttpUtil::AssembleRawHeaders(base_headers_string));
// Check that we can handle if not touching the response headers.
{
EventResponseDelta d0("extid0", base::Time::FromInternalValue(3000));
deltas.push_back(std::move(d0));
}
scoped_refptr<net::HttpResponseHeaders> new_headers0;
MergeCookiesInOnHeadersReceivedResponses(GURL(), deltas, base_headers.get(),
&new_headers0);
EXPECT_FALSE(new_headers0.get());
ResponseCookieModification add_cookie;
add_cookie.type = helpers::ADD;
add_cookie.modification.emplace();
add_cookie.modification->name = "name4";
add_cookie.modification->value = "\"value4\"";
ResponseCookieModification edit_cookie;
edit_cookie.type = helpers::EDIT;
edit_cookie.filter.emplace();
edit_cookie.filter->name = "name2";
edit_cookie.modification.emplace();
edit_cookie.modification->value = "new value";
ResponseCookieModification edit_cookie_2;
edit_cookie_2.type = helpers::EDIT;
edit_cookie_2.filter.emplace();
edit_cookie_2.filter->secure = false;
edit_cookie_2.modification.emplace();
edit_cookie_2.modification->secure = true;
// Tests 'ageLowerBound' filter when cookie lifetime is set
// in cookie's 'max-age' attribute and its value is greater than
// the filter's value.
ResponseCookieModification edit_cookie_3;
edit_cookie_3.type = helpers::EDIT;
edit_cookie_3.filter.emplace();
edit_cookie_3.filter->name = "lBound1";
edit_cookie_3.filter->age_lower_bound = 600;
edit_cookie_3.modification.emplace();
edit_cookie_3.modification->value = "greater_1";
// Cookie lifetime is set in the cookie's 'expires' attribute.
ResponseCookieModification edit_cookie_4;
edit_cookie_4.type = helpers::EDIT;
edit_cookie_4.filter.emplace();
edit_cookie_4.filter->name = "lBound2";
edit_cookie_4.filter->age_lower_bound = 600;
edit_cookie_4.modification.emplace();
edit_cookie_4.modification->value = "greater_2";
// Tests equality of the cookie lifetime with the filter value when
// lifetime is set in the cookie's 'max-age' attribute.
// Note: we don't test the equality when the lifetime is set in the 'expires'
// attribute because the tests will be flaky. The reason is calculations will
// depend on fetching the current time.
ResponseCookieModification edit_cookie_5;
edit_cookie_5.type = helpers::EDIT;
edit_cookie_5.filter.emplace();
edit_cookie_5.filter->name = "lBound3";
edit_cookie_5.filter->age_lower_bound = 2000;
edit_cookie_5.modification.emplace();
edit_cookie_5.modification->value = "equal_2";
// Tests 'ageUpperBound' filter when cookie lifetime is set
// in cookie's 'max-age' attribute and its value is lower than
// the filter's value.
ResponseCookieModification edit_cookie_6;
edit_cookie_6.type = helpers::EDIT;
edit_cookie_6.filter.emplace();
edit_cookie_6.filter->name = "uBound1";
edit_cookie_6.filter->age_upper_bound = 2000;
edit_cookie_6.modification.emplace();
edit_cookie_6.modification->value = "smaller_1";
// Cookie lifetime is set in the cookie's 'expires' attribute.
ResponseCookieModification edit_cookie_7;
edit_cookie_7.type = helpers::EDIT;
edit_cookie_7.filter.emplace();
edit_cookie_7.filter->name = "uBound2";
edit_cookie_7.filter->age_upper_bound = 2000;
edit_cookie_7.modification.emplace();
edit_cookie_7.modification->value = "smaller_2";
// Tests equality of the cookie lifetime with the filter value when
// lifetime is set in the cookie's 'max-age' attribute.
ResponseCookieModification edit_cookie_8;
edit_cookie_8.type = helpers::EDIT;
edit_cookie_8.filter.emplace();
edit_cookie_8.filter->name = "uBound3";
edit_cookie_8.filter->age_upper_bound = 2000;
edit_cookie_8.modification.emplace();
edit_cookie_8.modification->value = "equal_4";
// Tests 'ageUpperBound' filter when cookie lifetime is greater
// than the filter value. No modification is expected to be applied.
ResponseCookieModification edit_cookie_9;
edit_cookie_9.type = helpers::EDIT;
edit_cookie_9.filter.emplace();
edit_cookie_9.filter->name = "uBound4";
edit_cookie_9.filter->age_upper_bound = 2501;
edit_cookie_9.modification.emplace();
edit_cookie_9.modification->value = "Will not change";
// Tests 'ageUpperBound' filter when both 'max-age' and 'expires' cookie
// attributes are provided. 'expires' value matches the filter, however
// no modification to the cookie is expected because 'max-age' overrides
// 'expires' and it does not match the filter.
ResponseCookieModification edit_cookie_10;
edit_cookie_10.type = helpers::EDIT;
edit_cookie_10.filter.emplace();
edit_cookie_10.filter->name = "uBound5";
edit_cookie_10.filter->age_upper_bound = 800;
edit_cookie_10.modification.emplace();
edit_cookie_10.modification->value = "Will not change";
ResponseCookieModification remove_cookie;
remove_cookie.type = helpers::REMOVE;
remove_cookie.filter.emplace();
remove_cookie.filter->name = "name3";
ResponseCookieModification remove_cookie_2;
remove_cookie_2.type = helpers::REMOVE;
remove_cookie_2.filter.emplace();
remove_cookie_2.filter->name = "uBound6";
remove_cookie_2.filter->age_upper_bound = 700;
ResponseCookieModification remove_cookie_3;
remove_cookie_3.type = helpers::REMOVE;
remove_cookie_3.filter.emplace();
remove_cookie_3.filter->name = "sessionCookie";
remove_cookie_3.filter->session_cookie = true;
ResponseCookieModification remove_cookie_4;
remove_cookie_4.type = helpers::REMOVE;
remove_cookie_4.filter.emplace();
remove_cookie_4.filter->name = "sessionCookie2";
remove_cookie_4.filter->session_cookie = true;
ResponseCookieModification* operations[] = {
&add_cookie, &edit_cookie, &edit_cookie_2, &edit_cookie_3,
&edit_cookie_4, &edit_cookie_5, &edit_cookie_6, &edit_cookie_7,
&edit_cookie_8, &edit_cookie_9, &edit_cookie_10, &remove_cookie,
&remove_cookie_2, &remove_cookie_3, &remove_cookie_4};
int64_t time = 0;
for (auto* operation : operations) {
EventResponseDelta delta("extid0",
base::Time::FromInternalValue(time++ * 5));
delta.response_cookie_modifications.push_back(std::move(*operation));
deltas.push_back(std::move(delta));
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
auto headers1 = base::MakeRefCounted<net::HttpResponseHeaders>(
net::HttpUtil::AssembleRawHeaders(base_headers_string));
scoped_refptr<net::HttpResponseHeaders> new_headers1;
MergeCookiesInOnHeadersReceivedResponses(GURL(), deltas, headers1.get(),
&new_headers1);
EXPECT_TRUE(new_headers1->HasHeader("Foo"));
size_t iter = 0;
std::string cookie_string;
std::set<std::string> expected_cookies;
expected_cookies.insert("name=value; domain=google.com; secure");
expected_cookies.insert("name2=value2; secure");
expected_cookies.insert("name4=\"value4\"; secure");
expected_cookies.insert(
"lBound1=greater_1; expires=" + cookie_expiration + "; secure");
expected_cookies.insert("lBound2=greater_2; max-age=1200; secure");
expected_cookies.insert("lBound3=equal_2; max-age=2000; secure");
expected_cookies.insert(
"uBound1=smaller_1; expires=" + cookie_expiration + "; secure");
expected_cookies.insert("uBound2=smaller_2; max-age=1200; secure");
expected_cookies.insert("uBound3=equal_4; max-age=2000; secure");
expected_cookies.insert("uBound4=value11; max-age=2500; secure");
expected_cookies.insert(
"uBound5=value12; max-age=600; expires=" + cookie_expiration+ "; secure");
std::set<std::string> actual_cookies;
while (new_headers1->EnumerateHeader(&iter, "Set-Cookie", &cookie_string))
actual_cookies.insert(cookie_string);
EXPECT_EQ(expected_cookies, actual_cookies);
}
TEST(ExtensionWebRequestHelpersTest, TestMergeOnHeadersReceivedResponses) {
helpers::IgnoredActions ignored_actions;
std::string header_value;
EventResponseDeltas deltas;
char base_headers_string[] =
"HTTP/1.0 200 OK\r\n"
"Key1: Value1\r\n"
"Key2: Value2, Foo\r\n"
"\r\n";
auto base_headers = base::MakeRefCounted<net::HttpResponseHeaders>(
net::HttpUtil::AssembleRawHeaders(base_headers_string));
// Check that we can handle if not touching the response headers.
{
EventResponseDelta d0("extid0", base::Time::FromInternalValue(3000));
deltas.push_back(std::move(d0));
}
bool response_headers_modified0;
scoped_refptr<net::HttpResponseHeaders> new_headers0;
GURL allowed_unsafe_redirect_url0;
WebRequestInfoInitParams info_params;
info_params.url = GURL(kExampleUrl);
WebRequestInfo info(std::move(info_params));
info.dnr_actions = std::vector<DNRRequestAction>();
MergeOnHeadersReceivedResponses(info, deltas, base_headers.get(),
&new_headers0, &allowed_unsafe_redirect_url0,
&ignored_actions,
&response_headers_modified0);
EXPECT_FALSE(new_headers0.get());
EXPECT_TRUE(allowed_unsafe_redirect_url0.is_empty());
EXPECT_EQ(0u, ignored_actions.size());
EXPECT_FALSE(response_headers_modified0);
{
EventResponseDelta d1("extid1", base::Time::FromInternalValue(2000));
d1.deleted_response_headers.push_back(ResponseHeader("KEY1", "Value1"));
d1.deleted_response_headers.push_back(
ResponseHeader("KEY2", "Value2, Foo"));
d1.added_response_headers.push_back(ResponseHeader("Key2", "Value3"));
d1.added_response_headers.push_back(ResponseHeader("Key3", "Foo"));
deltas.push_back(std::move(d1));
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
bool response_headers_modified1;
scoped_refptr<net::HttpResponseHeaders> new_headers1;
GURL allowed_unsafe_redirect_url1;
MergeOnHeadersReceivedResponses(info, deltas, base_headers.get(),
&new_headers1, &allowed_unsafe_redirect_url1,
&ignored_actions,
&response_headers_modified1);
ASSERT_TRUE(new_headers1.get());
EXPECT_TRUE(allowed_unsafe_redirect_url1.is_empty());
std::multimap<std::string, std::string> expected1;
expected1.insert(std::pair<std::string, std::string>("Key2", "Value3"));
expected1.insert(std::pair<std::string, std::string>("Key3", "Foo"));
size_t iter = 0;
std::string name;
std::string value;
std::multimap<std::string, std::string> actual1;
while (new_headers1->EnumerateHeaderLines(&iter, &name, &value)) {
actual1.insert(std::pair<std::string, std::string>(name, value));
}
EXPECT_EQ(expected1, actual1);
EXPECT_EQ(0u, ignored_actions.size());
EXPECT_TRUE(response_headers_modified1);
// Check that we replace response headers only once.
{
EventResponseDelta d2("extid2", base::Time::FromInternalValue(1500));
// Note that we use a different capitalization of KeY2. This should not
// matter.
d2.deleted_response_headers.push_back(
ResponseHeader("KeY2", "Value2, Foo"));
d2.added_response_headers.push_back(ResponseHeader("Key2", "Value4"));
deltas.push_back(std::move(d2));
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
bool response_headers_modified2;
scoped_refptr<net::HttpResponseHeaders> new_headers2;
GURL allowed_unsafe_redirect_url2;
MergeOnHeadersReceivedResponses(info, deltas, base_headers.get(),
&new_headers2, &allowed_unsafe_redirect_url2,
&ignored_actions,
&response_headers_modified2);
ASSERT_TRUE(new_headers2.get());
EXPECT_TRUE(allowed_unsafe_redirect_url2.is_empty());
iter = 0;
std::multimap<std::string, std::string> actual2;
while (new_headers2->EnumerateHeaderLines(&iter, &name, &value)) {
actual2.insert(std::pair<std::string, std::string>(name, value));
}
EXPECT_EQ(expected1, actual2);
EXPECT_EQ(1u, ignored_actions.size());
EXPECT_TRUE(
HasIgnoredAction(ignored_actions, "extid2",
web_request::IGNORED_ACTION_TYPE_RESPONSE_HEADERS));
EXPECT_TRUE(response_headers_modified2);
// Ensure headers removed by Declarative Net Request API can't be added by web
// request extensions and result in a conflict.
DNRRequestAction remove_headers_action =
CreateRequestActionForTesting(DNRRequestAction::Type::REMOVE_HEADERS);
remove_headers_action.response_headers_to_remove = {"key3"};
info.dnr_actions = std::vector<DNRRequestAction>();
info.dnr_actions->push_back(std::move(remove_headers_action));
ignored_actions.clear();
bool response_headers_modified3 = false;
scoped_refptr<net::HttpResponseHeaders> new_headers3;
GURL allowed_unsafe_redirect_url3;
MergeOnHeadersReceivedResponses(info, deltas, base_headers.get(),
&new_headers3, &allowed_unsafe_redirect_url3,
&ignored_actions,
&response_headers_modified3);
ASSERT_TRUE(new_headers3.get());
EXPECT_TRUE(allowed_unsafe_redirect_url3.is_empty());
iter = 0;
std::multimap<std::string, std::string> actual3;
while (new_headers3->EnumerateHeaderLines(&iter, &name, &value))
actual3.emplace(name, value);
std::multimap<std::string, std::string> expected3;
expected3.emplace("Key2", "Value4");
expected3.emplace("Key1", "Value1");
EXPECT_EQ(expected3, actual3);
EXPECT_EQ(1u, ignored_actions.size());
EXPECT_TRUE(
HasIgnoredAction(ignored_actions, "extid1",
web_request::IGNORED_ACTION_TYPE_RESPONSE_HEADERS));
EXPECT_TRUE(response_headers_modified3);
}
// Check that we do not delete too much
TEST(ExtensionWebRequestHelpersTest,
TestMergeOnHeadersReceivedResponsesDeletion) {
helpers::IgnoredActions ignored_actions;
std::string header_value;
EventResponseDeltas deltas;
char base_headers_string[] =
"HTTP/1.0 200 OK\r\n"
"Key1: Value1\r\n"
"Key1: Value2\r\n"
"Key1: Value3\r\n"
"Key2: Value4\r\n"
"\r\n";
auto base_headers = base::MakeRefCounted<net::HttpResponseHeaders>(
net::HttpUtil::AssembleRawHeaders(base_headers_string));
{
EventResponseDelta d1("extid1", base::Time::FromInternalValue(2000));
d1.deleted_response_headers.push_back(ResponseHeader("KEY1", "Value2"));
deltas.push_back(std::move(d1));
}
bool response_headers_modified1;
scoped_refptr<net::HttpResponseHeaders> new_headers1;
GURL allowed_unsafe_redirect_url1;
WebRequestInfoInitParams info_params;
info_params.url = GURL(kExampleUrl);
WebRequestInfo info(std::move(info_params));
info.dnr_actions = std::vector<DNRRequestAction>();
MergeOnHeadersReceivedResponses(info, deltas, base_headers.get(),
&new_headers1, &allowed_unsafe_redirect_url1,
&ignored_actions,
&response_headers_modified1);
ASSERT_TRUE(new_headers1.get());
EXPECT_TRUE(allowed_unsafe_redirect_url1.is_empty());
std::multimap<std::string, std::string> expected1;
expected1.insert(std::pair<std::string, std::string>("Key1", "Value1"));
expected1.insert(std::pair<std::string, std::string>("Key1", "Value3"));
expected1.insert(std::pair<std::string, std::string>("Key2", "Value4"));
size_t iter = 0;
std::string name;
std::string value;
std::multimap<std::string, std::string> actual1;
while (new_headers1->EnumerateHeaderLines(&iter, &name, &value)) {
actual1.insert(std::pair<std::string, std::string>(name, value));
}
EXPECT_EQ(expected1, actual1);
EXPECT_EQ(0u, ignored_actions.size());
EXPECT_TRUE(response_headers_modified1);
}
// Tests whether onHeadersReceived can initiate a redirect.
// The URL merge logic is shared with onBeforeRequest, so we only need to test
// whether the URLs are merged at all.
TEST(ExtensionWebRequestHelpersTest,
TestMergeOnHeadersReceivedResponsesRedirect) {
EventResponseDeltas deltas;
helpers::IgnoredActions ignored_actions;
char base_headers_string[] =
"HTTP/1.0 200 OK\r\n"
"\r\n";
auto base_headers = base::MakeRefCounted<net::HttpResponseHeaders>(
net::HttpUtil::AssembleRawHeaders(base_headers_string));
// No redirect
{
EventResponseDelta d0("extid0", base::Time::FromInternalValue(0));
deltas.push_back(std::move(d0));
}
bool response_headers_modified0;
scoped_refptr<net::HttpResponseHeaders> new_headers0;
GURL allowed_unsafe_redirect_url0;
WebRequestInfoInitParams info_params;
info_params.url = GURL(kExampleUrl);
WebRequestInfo info(std::move(info_params));
MergeOnHeadersReceivedResponses(info, deltas, base_headers.get(),
&new_headers0, &allowed_unsafe_redirect_url0,
&ignored_actions,
&response_headers_modified0);
EXPECT_FALSE(new_headers0.get());
EXPECT_TRUE(allowed_unsafe_redirect_url0.is_empty());
EXPECT_EQ(0u, ignored_actions.size());
EXPECT_FALSE(response_headers_modified0);
// Single redirect.
GURL new_url_1("http://foo.com");
{
EventResponseDelta d1("extid1", base::Time::FromInternalValue(1000));
d1.new_url = GURL(new_url_1);
deltas.push_back(std::move(d1));
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
bool response_headers_modified1;
scoped_refptr<net::HttpResponseHeaders> new_headers1;
GURL allowed_unsafe_redirect_url1;
MergeOnHeadersReceivedResponses(info, deltas, base_headers.get(),
&new_headers1, &allowed_unsafe_redirect_url1,
&ignored_actions,
&response_headers_modified1);
EXPECT_TRUE(new_headers1.get());
EXPECT_TRUE(new_headers1->HasHeaderValue("Location", new_url_1.spec()));
EXPECT_EQ(new_url_1, allowed_unsafe_redirect_url1);
EXPECT_TRUE(ignored_actions.empty());
EXPECT_FALSE(response_headers_modified1);
}
TEST(ExtensionWebRequestHelpersTest, TestMergeOnAuthRequiredResponses) {
helpers::IgnoredActions ignored_actions;
EventResponseDeltas deltas;
base::string16 username = base::ASCIIToUTF16("foo");
base::string16 password = base::ASCIIToUTF16("bar");
base::string16 password2 = base::ASCIIToUTF16("baz");
// Check that we can handle if not returning credentials.
{
EventResponseDelta d0("extid0", base::Time::FromInternalValue(3000));
deltas.push_back(std::move(d0));
}
net::AuthCredentials auth0;
bool credentials_set =
MergeOnAuthRequiredResponses(deltas, &auth0, &ignored_actions);
EXPECT_FALSE(credentials_set);
EXPECT_TRUE(auth0.Empty());
EXPECT_EQ(0u, ignored_actions.size());
// Check that we can set AuthCredentials.
{
EventResponseDelta d1("extid1", base::Time::FromInternalValue(2000));
d1.auth_credentials = net::AuthCredentials(username, password);
deltas.push_back(std::move(d1));
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
net::AuthCredentials auth1;
credentials_set =
MergeOnAuthRequiredResponses(deltas, &auth1, &ignored_actions);
EXPECT_TRUE(credentials_set);
EXPECT_FALSE(auth1.Empty());
EXPECT_EQ(username, auth1.username());
EXPECT_EQ(password, auth1.password());
EXPECT_EQ(0u, ignored_actions.size());
// Check that we set AuthCredentials only once.
{
EventResponseDelta d2("extid2", base::Time::FromInternalValue(1500));
d2.auth_credentials = net::AuthCredentials(username, password2);
deltas.push_back(std::move(d2));
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
net::AuthCredentials auth2;
credentials_set =
MergeOnAuthRequiredResponses(deltas, &auth2, &ignored_actions);
EXPECT_TRUE(credentials_set);
EXPECT_FALSE(auth2.Empty());
EXPECT_EQ(username, auth1.username());
EXPECT_EQ(password, auth1.password());
EXPECT_EQ(1u, ignored_actions.size());
EXPECT_TRUE(
HasIgnoredAction(ignored_actions, "extid2",
web_request::IGNORED_ACTION_TYPE_AUTH_CREDENTIALS));
// Check that we can set identical AuthCredentials twice without causing
// a conflict.
{
EventResponseDelta d3("extid3", base::Time::FromInternalValue(1000));
d3.auth_credentials = net::AuthCredentials(username, password);
deltas.push_back(std::move(d3));
}
deltas.sort(&InDecreasingExtensionInstallationTimeOrder);
ignored_actions.clear();
net::AuthCredentials auth3;
credentials_set =
MergeOnAuthRequiredResponses(deltas, &auth3, &ignored_actions);
EXPECT_TRUE(credentials_set);
EXPECT_FALSE(auth3.Empty());
EXPECT_EQ(username, auth1.username());
EXPECT_EQ(password, auth1.password());
EXPECT_EQ(1u, ignored_actions.size());
EXPECT_TRUE(
HasIgnoredAction(ignored_actions, "extid2",
web_request::IGNORED_ACTION_TYPE_AUTH_CREDENTIALS));
}
} // namespace extensions
| [
"rjkroege@chromium.org"
] | rjkroege@chromium.org |
5639f4067742fdf521bc682c04a78a93b9821da4 | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/git/hunk_6868.cpp | 71e4fa0eb9100f93409aacaa8bea739ead648aac | [] | no_license | ccdxc/logSurvey | eaf28e9c2d6307140b17986d5c05106d1fd8e943 | 6b80226e1667c1e0760ab39160893ee19b0e9fb1 | refs/heads/master | 2022-01-07T21:31:55.446839 | 2018-04-21T14:12:43 | 2018-04-21T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 121 | cpp | int cnt = 0;
struct rev_info rev;
+ discard_cache();
if (read_cache() < 0)
die("failed to read the cache");
| [
"993273596@qq.com"
] | 993273596@qq.com |
258ff26b604f9c467686af9651327569f9e0e803 | 4406eaedb7eb7bec64f6c9105c1da11707361a46 | /c8/interpret/logicboolexp.h | 6d06d156607672ca4532d36db12d20d5f4a07aac | [] | no_license | kotrenn/c8 | 8d1ecfc80167ea96111a79bd92c78bd772e7e003 | 80c416e4e6278b1ea0a244c4340a4991c657079d | refs/heads/master | 2021-01-09T23:42:31.920825 | 2015-04-07T17:00:31 | 2015-04-07T17:00:31 | 33,556,345 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 375 | h | #ifndef __LOGIC_BOOL_EXP_H
#define __LOGIC_BOOL_EXP_H
#include "boolexp.h"
class LogicBoolExp : public BoolExp
{
public:
LogicBoolExp(const string &op, BoolExp *lhs, BoolExp *rhs);
~LogicBoolExp();
bool eval(VarTable *vars,
FuncTable *funcs,
bool *retstat);
private:
string m_op;
BoolExp *m_lhs;
BoolExp *m_rhs;
};
#endif
| [
"kotrenn@gmail.com"
] | kotrenn@gmail.com |
cb8faaf80c9af6a46cee5bd1e2beb8fd519147bf | 7521fd6f1c5d536b47483797caee7642b57e48db | /Template/src/lightsource.cpp | 52817b521f3d51391c2af19fd37bc42a2d51fdfa | [] | no_license | belkacemlahouel/IN55_Diamant | 419aab703b4c9fe77dbd74179d0ea8236c882c13 | 28107c2b4e5130a22d30a9aad1df1aabd1ca9664 | refs/heads/master | 2021-01-14T12:14:52.665523 | 2015-06-14T22:14:42 | 2015-06-14T22:14:42 | 35,538,413 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,277 | cpp | #include "lightsource.h"
LightSource::LightSource(AbstractFramework* fw, GLuint id,
GLfloat posDir[4],
GLfloat ambient[4], GLfloat diffuse[4], GLfloat specular[4],
GLfloat constantAttenuation, GLfloat linearAttenuation, GLfloat quadraticAttenuation,
GLfloat spotDirection[3], GLfloat spotCutoff, GLfloat spotExponent)
{
this->m_Framework = fw;
this->id = id;
this->posDir = posDir;
this->ambient = ambient;
this->diffuse = diffuse;
this->specular = specular;
this->constantAttenuation = constantAttenuation;
this->linearAttenuation = linearAttenuation;
this->quadraticAttenuation = quadraticAttenuation;
this->spotDirection = spotDirection;
this->spotCutoff = spotCutoff;
this->spotExponent = spotExponent;
this->submitLight();
this->updateLight();
}
void LightSource::submitLight()
{
glUniform4fv(glGetUniformLocation(m_Framework->getCurrentShaderId(), "light.ambient"), 1, (GLfloat *) this->ambient);
glUniform4fv(glGetUniformLocation(m_Framework->getCurrentShaderId(), "light.diffuse"), 1, (GLfloat *) this->diffuse);
glUniform4fv(glGetUniformLocation(m_Framework->getCurrentShaderId(), "light.specular"), 1, (GLfloat *) this->specular);
glUniform1f(glGetUniformLocation(m_Framework->getCurrentShaderId(), "light.constantAttenuation"), this->constantAttenuation);
glUniform1f(glGetUniformLocation(m_Framework->getCurrentShaderId(), "light.linearAttenuation"), this->linearAttenuation);
glUniform1f(glGetUniformLocation(m_Framework->getCurrentShaderId(), "light.quadraticAttenuation"), this->quadraticAttenuation);
glUniform3fv(glGetUniformLocation(m_Framework->getCurrentShaderId(), "light.spotDirection"), 1, (GLfloat *) this->spotDirection);
glUniform1f(glGetUniformLocation(m_Framework->getCurrentShaderId(), "light.spotCutoff"), this->spotCutoff);
glUniform1f(glGetUniformLocation(m_Framework->getCurrentShaderId(), "light.spotExponent"), this->spotExponent);
}
void LightSource::updateLight()
{
glUniform4fv(glGetUniformLocation(m_Framework->getCurrentShaderId(), "light.posDir"), 1, (GLfloat *) this->posDir);
}
| [
"bourgeois.maxime@gmail.com"
] | bourgeois.maxime@gmail.com |
b25bcd4212c96176dce0f0aaa20c9f63061c5ba8 | ce71ba08e9094a4d76c8cc1e0cc7891ae016ff60 | /Lib/Chip/Unknown/Nuvoton/M051_Series/GP0_BITS.hpp | cc5087ea5608b326c2069f15817edbdc00fe96a5 | [
"Apache-2.0"
] | permissive | operativeF/Kvasir | 9bfe25e1844d41ffefe527f16117c618af50cde9 | dfbcbdc9993d326ef8cc73d99129e78459c561fd | refs/heads/master | 2020-04-06T13:12:59.381009 | 2019-01-25T18:43:17 | 2019-01-25T18:43:17 | 157,489,295 | 0 | 0 | Apache-2.0 | 2018-11-14T04:12:05 | 2018-11-14T04:12:04 | null | UTF-8 | C++ | false | false | 3,589 | hpp | #pragma once
#include <Register/Utility.hpp>
namespace Kvasir {
//Registers group
namespace Gp0BitsPx0Dout{ ///<Px.0 Data Output Value
using Addr = Register::Address<0x50004400,0xfffffffe,0x00000000,unsigned>;
///P0.0 I/O Pin Bit Output ControlSet this bit can control one GPIO pin output value1 = Set corresponding GPIO bit to high0 = Set corresponding GPIO bit to low
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> dout{};
}
namespace Gp0BitsPx1Dout{ ///<Px.1 Data Output Value
using Addr = Register::Address<0x50004404,0xfffffffe,0x00000000,unsigned>;
///P0.1 I/O Pin Bit Output ControlSet this bit can control one GPIO pin output value1 = Set corresponding GPIO bit to high0 = Set corresponding GPIO bit to low
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> dout{};
}
namespace Gp0BitsPx2Dout{ ///<Px.2 Data Output Value
using Addr = Register::Address<0x50004408,0xfffffffe,0x00000000,unsigned>;
///P0.2 I/O Pin Bit Output ControlSet this bit can control one GPIO pin output value1 = Set corresponding GPIO bit to high0 = Set corresponding GPIO bit to low
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> dout{};
}
namespace Gp0BitsPx3Dout{ ///<Px.3 Data Output Value
using Addr = Register::Address<0x5000440c,0xfffffffe,0x00000000,unsigned>;
///P0.3 I/O Pin Bit Output ControlSet this bit can control one GPIO pin output value1 = Set corresponding GPIO bit to high0 = Set corresponding GPIO bit to low
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> dout{};
}
namespace Gp0BitsPx4Dout{ ///<Px.4 Data Output Value
using Addr = Register::Address<0x50004410,0xfffffffe,0x00000000,unsigned>;
///P0.4 I/O Pin Bit Output ControlSet this bit can control one GPIO pin output value1 = Set corresponding GPIO bit to high0 = Set corresponding GPIO bit to low
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> dout{};
}
namespace Gp0BitsPx5Dout{ ///<Px.5 Data Output Value
using Addr = Register::Address<0x50004414,0xfffffffe,0x00000000,unsigned>;
///P0.5 I/O Pin Bit Output ControlSet this bit can control one GPIO pin output value1 = Set corresponding GPIO bit to high0 = Set corresponding GPIO bit to low
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> dout{};
}
namespace Gp0BitsPx6Dout{ ///<Px.6 Data Output Value
using Addr = Register::Address<0x50004418,0xfffffffe,0x00000000,unsigned>;
///P0.6 I/O Pin Bit Output ControlSet this bit can control one GPIO pin output value1 = Set corresponding GPIO bit to high0 = Set corresponding GPIO bit to low
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> dout{};
}
namespace Gp0BitsPx7Dout{ ///<Px.7 Data Output Value
using Addr = Register::Address<0x5000441c,0xfffffffe,0x00000000,unsigned>;
///P0.7 I/O Pin Bit Output ControlSet this bit can control one GPIO pin output value1 = Set corresponding GPIO bit to high0 = Set corresponding GPIO bit to low
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> dout{};
}
}
| [
"holmes.odin@gmail.com"
] | holmes.odin@gmail.com |
8f27924222edd7a63865cca2acb94b6a65884fd7 | e8049d9afac8628143181fefa3d8384e4893d033 | /Data/Vision/Base/Shaders/TextureSamplingHelpers.inc | 40b63f25b16e5c13a2b4259d15c3d609a832c136 | [] | no_license | ymko13/KaosuProject | 0a9d00b4d234cbe9f5578615d3bf230a0c275111 | db4c45edc1decc51949690c118dea98e86abf917 | refs/heads/master | 2021-01-22T11:47:26.601560 | 2014-04-07T15:45:58 | 2014-04-07T15:45:58 | 18,521,818 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,377 | inc |
#ifndef VISION_TEXTURE_SAMPLING_HELPERS
#define VISION_TEXTURE_SAMPLING_HELPERS
// (manual) bilinear filtering
#ifdef _VISION_DX11
float4 SampleBilinear(Texture2D tex, sampler textureSampler, float2 fPixelCoords, float2 fInvTexSize)
#else
#define SampleBilinear(_texture, _textureSampler, _fPixelCoords, _fInvTexSize) _SampleBilinear(_texture, _fPixelCoords, _fInvTexSize)
float4 _SampleBilinear(sampler2D tex, float2 fPixelCoords, float2 fInvTexSize)
#endif
{
#if defined(_VISION_XENON) || defined(_VISION_DX9)
float2 tmp = fPixelCoords - 0.5f;
float2 fractionalPart = frac(tmp); // frac is a direct GPU instruction, so it is faster than modf or floor (which both use frac)
float2 intPart = tmp - fractionalPart + 0.5f;
#else
float2 fractionalPart = frac(fPixelCoords);
float2 intPart = fPixelCoords - fractionalPart;
#endif
float2 lowerTexcoord = intPart * fInvTexSize;
float2 upperTexcoord = lowerTexcoord + fInvTexSize;
float4 colorLL = vTex2D(tex, textureSampler, lowerTexcoord);
float4 colorLR = vTex2D(tex, textureSampler, float2(upperTexcoord.x, lowerTexcoord.y));
float4 colorUL = vTex2D(tex, textureSampler, float2(lowerTexcoord.x, upperTexcoord.y));
float4 colorUR = vTex2D(tex, textureSampler, upperTexcoord);
return lerp(lerp(colorLL, colorLR, fractionalPart.x), lerp(colorUL, colorUR, fractionalPart.x), fractionalPart.y);
}
#endif
| [
"slow3d@gmail.com"
] | slow3d@gmail.com |
d6af7706ee7d368c1b857f7fdfdeb1c7ca6b3b65 | 6f36ab50dc7578f5ca161c5b861c68e839535b74 | /acm/p1803.cpp | 0c9a4560b4d1e625519c3134a28b1b60749ff2d1 | [] | no_license | RandyLambert/daily | 144e49eb945ce6b33a8d06c409b8db1318d01526 | be1634663d5248f7abcc92e4a42f193411ad5aca | refs/heads/master | 2021-06-24T01:45:54.574544 | 2021-04-14T16:15:35 | 2021-04-14T16:15:35 | 207,723,773 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 573 | cpp | #include<bits/stdc++.h>
using namespace std;
struct node {
int bi;
int mi;
}b[1000001];
bool cmp(const node a,const node b){
if(a.mi == b.mi){
return a.bi > b.bi;
}
else{
return a.mi < b.mi;
}
}
int main(){
int n,sum = 1;
scanf("%d",&n);
for(int i = 0;i < n;i++){
scanf("%d%d",&b[i].bi,&b[i].mi);
}
sort(b,b+n,cmp);
int time;
time=b[0].mi;
for(int j=1;j<=n;j++){
if(b[j].bi>=time){
sum++;
time=b[j].mi;
}
}
printf("%d",sum);
return 0;
}
| [
"1249604462@qq.com"
] | 1249604462@qq.com |
fc5408c512b92c1aa35e4a2cfef5ac195c8a6e8d | d9dfb5b3d0c4a8bd5214126c9ec511cae81c0219 | /src/Pyros3D/Materials/IMaterial.cpp | 4080d7113a39a38109d836c9afa19952d9b9fe80 | [
"MIT"
] | permissive | Fuatnow/Pyros3D | 6cbe1ff2a9b1d598248e931571dabd85601bcd61 | a1eac86160a95c2c25f118edc23683239c3ffdf3 | refs/heads/master | 2020-05-25T13:35:13.939899 | 2016-08-09T16:10:35 | 2016-08-09T16:10:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,117 | cpp | //============================================================================
// Name : IMaterial.cpp
// Author : Duarte Peixinho
// Version :
// Copyright : ;)
// Description : IMaterial Interface
//============================================================================
#include <Pyros3D/Materials/IMaterial.h>
namespace p3d {
uint32 IMaterial::_InternalID = 0;
IMaterial::IMaterial()
{
// Values By Default
isTransparent = false;
isWireFrame = false;
isCastingShadows = false;
cullFace = CullFace::BackFace;
depthBias = false;
depthTest = depthWrite = true;
depthTestMode = 0; // Less
forceDepthWrite = false;
blending = false;
// Set Internal ID
materialID = _InternalID;
// Increase Internal ID
_InternalID++;
}
void IMaterial::Destroy() {}
void IMaterial::SetOpacity(const f32 &opacity)
{
this->opacity = opacity;
AddUniform(Uniform("uOpacity",DataType::Float,&this->opacity));
}
void IMaterial::SetCullFace(const uint32 &face)
{
this->cullFace = face;
}
IMaterial::~IMaterial() {}
void IMaterial::SetTransparencyFlag(bool transparency)
{
isTransparent = transparency;
}
bool IMaterial::IsTransparent() const
{
if (isTransparent) return isTransparent;
else return (opacity<1);
}
uint32 IMaterial::GetCullFace() const
{
return cullFace;
}
const f32 &IMaterial::GetOpacity() const
{
return opacity;
}
void IMaterial::EnableCastingShadows()
{
isCastingShadows = true;
}
void IMaterial::DisableCastingShadows()
{
isCastingShadows = false;
}
bool IMaterial::IsCastingShadows()
{
return isCastingShadows;
}
void IMaterial::EnableDethBias(f32 factor, f32 units)
{
depthBias = true;
depthFactor = factor;
depthUnits = units;
}
void IMaterial::DisableDethBias()
{
depthBias = false;
}
// send uniforms
void IMaterial::SetUniformValue(std::string Uniform, int32 value)
{
StringID ID(MakeStringID(Uniform));
UserUniforms[ID].SetValue(&value,1);
}
void IMaterial::SetUniformValue(StringID UniformID, int32 value)
{
UserUniforms[UniformID].SetValue(&value,1);
}
void IMaterial::SetUniformValue(std::string Uniform, f32 value)
{
StringID ID(MakeStringID(Uniform));
UserUniforms[ID].SetValue(&value,1);
}
void IMaterial::SetUniformValue(StringID UniformID, f32 value)
{
UserUniforms[UniformID].SetValue(&value,1);
}
void IMaterial::SetUniformValue(StringID UniformID, void* value, const uint32 &elementCount)
{
UserUniforms[UniformID].SetValue(value,elementCount);
}
void IMaterial::SetUniformValue(std::string Uniform, void* value, const uint32 &elementCount)
{
StringID ID(MakeStringID(Uniform));
UserUniforms[ID].SetValue(value,elementCount);
}
void IMaterial::AddUniform(const Uniform &Data)
{
// Global Uniforms
if ((int)Data.Usage<DataUsage::Other)
{
GlobalUniforms.push_back(Data);
}
// Game Object Uniforms
else if ((int)Data.Usage>DataUsage::Other)
{
ModelUniforms.push_back(Data);
} else // User Specific
{
StringID ID(MakeStringID(Data.Name));
UserUniforms[ID]=Data;
}
}
void IMaterial::StartRenderWireFrame()
{
isWireFrame = true;
}
void IMaterial::StopRenderWireFrame()
{
isWireFrame = false;
}
bool IMaterial::IsWireFrame() const
{
return isWireFrame;
}
const uint32 &IMaterial::GetShader() const
{
return shaderProgram;
}
uint32 IMaterial::GetInternalID()
{
return materialID;
}
}
| [
"duarte.peixinho@gmail.com"
] | duarte.peixinho@gmail.com |
ad20353623a5a039b93fc31db85421dfc74d5e2a | 6f80725456e91d83cc22bd515a8a636460085039 | /baekjoon/15663.cpp | 5c7d1352c40f454f4f7147f0bb70de62a2551833 | [] | no_license | greedy0110/algorithm | 6061c9b48d93eb70b0dda6f40128325dee534047 | ce205f04d29a9d6d6d98060bf92aa5511eb09418 | refs/heads/master | 2023-09-04T16:06:33.552642 | 2021-11-10T00:59:39 | 2021-11-10T00:59:39 | 279,033,190 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,848 | cpp | //
// Created by 신승민 on 2021/04/11.
//
#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <stack>
#include <algorithm>
#include <queue>
#include <numeric>
#include <set>
#include <map>
using namespace std;
#define all(X) begin((X)), end((X))
#define endl '\n'
#define sz(X) (int)(X).size()
#define fi first
#define se second
#define fv(X) for(auto&_:(X))cin>>_
#define fv2(X) for(auto&_1:(X))for(auto&_2:_1)cin>>_2
#define repeat(i, X) for (int i=0; i<((X)); i++)
#define BIG 987654321
#define SUPER_BIG 987654321123456789
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pii;
typedef set<int> si;
typedef vector<vi> vvi;
typedef vector<bool> vb;
typedef vector<ll> vll;
typedef vector<pii> vpii;
typedef vector<vpii> vvpii;
typedef vector<string> vs;
typedef priority_queue<int, vi, greater<>> mq;
typedef priority_queue<pii, vpii, greater<>> mpq;
void solve();
void printvi(const vi &v, string deli = " ") {
for (auto i : v) {
cout << i << deli;
}
cout << endl;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
solve();
return 0;
}
vi arr;
vb visited;
set<vi> already_found;
int N, M;
void comb(vi &ret, int k) {
if (ret.size() == k) {
if (already_found.find(ret) == already_found.end()) {
already_found.insert(ret);
printvi(ret);
}
return;
}
for (int i = 1; i <= N; i++) {
if (visited[i]) continue;
visited[i] = true;
ret.push_back(arr[i]);
comb(ret, k);
ret.pop_back();
visited[i] = false;
}
}
void solve() {
cin >> N >> M;
arr = vi(N + 1);
visited = vb(N + 1, false);
repeat(i, N) {
cin >> arr[i + 1];
}
sort(all(arr));
vi ret;
comb(ret, M);
}
| [
"greedy0110@gmail.com"
] | greedy0110@gmail.com |
be577c4c4bffc88e8c90e50aef45a881052c8f78 | 031c92ee80a89e7a1f3d6c07781b2521741f19d8 | /GameEngine/GameEngine/ECS/ECSManager.h | 9d97aa9f7af4f23c0f9a44c6066acd23903194fa | [] | no_license | myuneeb90/GameEngine | ffde06b77d05b880ff8bb89c9f11d9e76a1a0676 | da87165df0fea5e9f57d7da12680baf0b8407e5a | refs/heads/master | 2020-03-27T19:36:44.449818 | 2018-10-03T18:43:41 | 2018-10-03T18:43:41 | 147,000,687 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,448 | h | #ifndef ECS_MANAGER_H
#define ECS_MANAGER_H
enum EntityComponentOrderID
{
ECOI_TRANSFORM = 0,
ECOI_RENDER = 1,
ECOI_CAMERA = 0
};
//struct IComponent;
class IEntity
{
public:
int ID;
vector<int> ComponentList;
public:
IEntity()
{
ID = 0;
}
~IEntity()
{
ComponentList.clear();
cout<<"Deleting Entity "<<ID<<endl;
}
void AddComponent(int componentId)
{
ComponentList.push_back(componentId);
}
};
struct IComponent
{
int ID;
ComponentIDType Type;
IComponent()
{
Type = CIT_BASE;
}
virtual ~IComponent()
{
}
};
struct ITransformComponent : public IComponent
{
Vector3f Position;
Vector3f Rotation;
Quaternion RotationQ;
Vector3f Scale;
RotationType RotType;
Matrix4x4f WorldMatrix;
ITransformComponent *Parent;
// float TransformValue;
ITransformComponent()
{
Position = Vector3f(0, 0, 0);
Rotation = Vector3f(0, 0, 0);
RotationQ = Quaternion(0, 0, 0, 1);
Scale = Vector3f(1, 1, 1);
Type = CIT_TRANSFORM;
RotType = RT_EULER;
WorldMatrix.Identity();
Parent = NULL;
//TransformValue = 0.0f;
}
ITransformComponent(Vector3f position, Vector3f rotation, Vector3f scale, ITransformComponent *parent)
{
Position = position;
Rotation = rotation;
RotationQ = Quaternion(0, 0, 0, 1);
Scale = scale;
Type = CIT_TRANSFORM;
RotType = RT_EULER;
WorldMatrix.Identity();
Parent = parent;
}
~ITransformComponent()
{
cout<<"Deleting Component "<<ID<<endl;
}
};
struct IRenderComponent : public IComponent
{
Mesh *MeshData;
Material *MaterialData;
//float RenderValue;
IRenderComponent()
{
MeshData = NULL;
MaterialData = NULL;
Type = CIT_RENDER;
// RenderValue = 0.0f;
}
IRenderComponent(Mesh *meshData, Material *materialData)
{
MeshData = meshData;
MaterialData = materialData;
Type = CIT_RENDER;
}
~IRenderComponent()
{
SAFE_DELETE(MeshData);
SAFE_DELETE(MaterialData);
cout<<"Deleting Component "<<ID<<endl;
}
};
struct IFPSCameraComponent : public IComponent
{
Vector3f Position;
Vector3f Up;
Vector3f Look;
Vector3f Right;
Vector3f LookAt;
Vector3f CamOffset;
Vector3f Velocity;
float Speed;
IFPSCameraComponent(Vector3f position, float speed)
{
Velocity = Vector3f(0.0f, 0.0f, 0.0f);
Up = Vector3f(0, 1, 0);
Right = Vector3f(1, 0, 0);
Look = Vector3f(0, 0, 1);
LookAt = Vector3f(0, 0, 1);
Position = position;
Speed = speed;
Type = CIT_FPSCAMERA;
}
};
enum ISystemType
{
IST_BASE = 0,
IST_TRANSFORM = 1,
IST_RENDER = 2,
IST_FPSCAMERA = 3
};
class ISystem
{
public:
ISystemType Type;
vector<ComponentIDType> TypeList;
vector<IEntity*> Group;
public:
ISystem()
{
Type = IST_BASE;
}
virtual ~ISystem()
{
Group.clear();
cout<<"Deleting System "<<Type<<endl;
}
void Add(IEntity *entity)
{
Group.push_back(entity);
}
virtual void Execute(vector<IComponent*> componentList) {}
};
class ITransformSystem : public ISystem
{
public:
ITransformSystem()
{
Type = IST_TRANSFORM;
TypeList.push_back(CIT_TRANSFORM);
}
virtual ~ITransformSystem()
{
}
void Execute(vector<IComponent*> componentList)
{
for(int i = 0; i < Group.size(); i++)
{
ITransformComponent *transform = (ITransformComponent*)componentList[Group[i]->ComponentList[ECOI_TRANSFORM]];
transform->WorldMatrix = ConstructWorldMatrix(transform, transform->Parent);
// transform->Rotation += Vector3f(0, 5.1f * GlobalRefs::Time->GetDeltaTime(), 0);
}
}
Matrix4x4f ConstructWorldMatrix(ITransformComponent *transform)
{
Matrix4x4f rotateXMatrix;
Matrix4x4f rotateYMatrix;
Matrix4x4f rotateZMatrix;
Matrix4x4f rotationMatrix;
Matrix4x4f scaleMatrix;
Matrix4x4f translationMatrix;
if(transform->RotType == RT_EULER)
{
rotateXMatrix = Matrix4x4f::RotateX(transform->Rotation.X);
rotateYMatrix = Matrix4x4f::RotateY(transform->Rotation.Y);
rotateZMatrix = Matrix4x4f::RotateZ(transform->Rotation.Z);
}
else
if(transform->RotType == RT_QUATERNION)
{
rotationMatrix = transform->RotationQ.ToRotationMatrixf();
}
scaleMatrix = Matrix4x4f::Scale(transform->Scale);
translationMatrix = Matrix4x4f::Translate(transform->Position);
if(transform->RotType == RT_EULER)
{
transform->WorldMatrix = rotateXMatrix * rotateYMatrix * rotateZMatrix * scaleMatrix * translationMatrix;
}
else
if(transform->RotType == RT_QUATERNION)
{
transform->WorldMatrix = rotationMatrix * scaleMatrix * translationMatrix;
}
return transform->WorldMatrix;
}
Matrix4x4f ConstructWorldMatrix(ITransformComponent *transform, ITransformComponent *parent)
{
Matrix4x4f rotateXMatrix;
Matrix4x4f rotateYMatrix;
Matrix4x4f rotateZMatrix;
Matrix4x4f rotationMatrix;
Matrix4x4f scaleMatrix;
Matrix4x4f translationMatrix;
if(transform->RotType == RT_EULER)
{
rotateXMatrix = Matrix4x4f::RotateX(transform->Rotation.X);
rotateYMatrix = Matrix4x4f::RotateY(transform->Rotation.Y);
rotateZMatrix = Matrix4x4f::RotateZ(transform->Rotation.Z);
}
else
if(transform->RotType == RT_QUATERNION)
{
rotationMatrix = transform->RotationQ.ToRotationMatrixf();
}
scaleMatrix = Matrix4x4f::Scale(transform->Scale);
translationMatrix = Matrix4x4f::Translate(transform->Position);
if(transform->RotType == RT_EULER)
{
transform->WorldMatrix = rotateXMatrix * rotateYMatrix * rotateZMatrix * scaleMatrix * translationMatrix;
}
else
if(transform->RotType == RT_QUATERNION)
{
transform->WorldMatrix = rotationMatrix * scaleMatrix * translationMatrix;
}
if(parent != NULL)
{
transform->WorldMatrix = transform->WorldMatrix * parent->WorldMatrix;
}
return transform->WorldMatrix;
}
};
class IRenderSystem : public ISystem
{
private:
vector<MeshFilter*> MeshFilterList;
vector<MaterialFilter*> MaterialFilterList;
bool PrepareFilters;
public:
IRenderSystem()
{
Type = IST_RENDER;
TypeList.push_back(CIT_TRANSFORM);
TypeList.push_back(CIT_RENDER);
PrepareFilters = false;
}
~IRenderSystem()
{
for(int i = 0; i < MeshFilterList.size(); ++i)
{
MeshFilter *meshFilter = MeshFilterList[i];
SAFE_DELETE(meshFilter);
}
MeshFilterList.clear();
for(int i = 0; i < MaterialFilterList.size(); ++i)
{
MaterialFilter *materialFilter = MaterialFilterList[i];
SAFE_DELETE(materialFilter);
}
MaterialFilterList.clear();
}
void Execute(vector<IComponent*> componentList)
{
if(PrepareFilters == false)
{
for(int i = 0; i < Group.size(); i++)
{
IRenderComponent *render = (IRenderComponent*)componentList[Group[i]->ComponentList[ECOI_RENDER]];
MeshFilter *meshFilter = new MeshFilter();
meshFilter->Construct(render->MeshData);
MeshFilterList.push_back(meshFilter);
MaterialFilter *materialFilter = new MaterialFilter(ShadersLib::CreateDefaultShader(render->MaterialData->DiffuseColor));
MaterialFilterList.push_back(materialFilter);
}
PrepareFilters = true;
}
GlobalRefs::Graphics->BeginRender(0.5f, 0.5f, 0.5f, 1.0f);
for(int i = 0; i < Group.size(); i++)
{
ITransformComponent *transform = (ITransformComponent*)componentList[Group[i]->ComponentList[ECOI_TRANSFORM]];
IRenderComponent *render = (IRenderComponent*)componentList[Group[i]->ComponentList[ECOI_RENDER]];
MeshFilter *meshFilter = MeshFilterList[i];
MaterialFilter *materialFilter = MaterialFilterList[i];
Matrix4x4f world = transform->WorldMatrix;
Matrix4x4f wvp;
wvp = world * GlobalRefs::Graphics->ViewMatrix * GlobalRefs::Graphics->ProjectionMatrix;
materialFilter->ShaderData->SetMatrix("WVP", wvp);
materialFilter->ShaderData->SetMatrix("World", world);
GlobalRefs::Graphics->DeviceContext->IASetVertexBuffers(0, 1, &meshFilter->VertexBuffer, &meshFilter->Stride, &meshFilter->Offset);
GlobalRefs::Graphics->DeviceContext->IASetIndexBuffer(meshFilter->IndexBuffer, DXGI_FORMAT_R32_UINT, 0);
GlobalRefs::Graphics->DeviceContext->IASetInputLayout(materialFilter->ShaderData->GetInputLayout());
if(materialFilter->ShaderData->GetShaderType() == ST_MESH)
{
GlobalRefs::Graphics->DeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
}
else
if(materialFilter->ShaderData->GetShaderType() == ST_LINE)
{
GlobalRefs::Graphics->DeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINELIST);
}
// Bind Textures And Materials Here
// Render Final Mesh
D3DX11_TECHNIQUE_DESC techDesc;
materialFilter->ShaderData->GetEffectTechnique()->GetDesc(&techDesc);
for(int p = 0; p < techDesc.Passes; p++)
{
materialFilter->ShaderData->GetEffectTechnique()->GetPassByIndex(p)->Apply(0, GlobalRefs::Graphics->DeviceContext);
GlobalRefs::Graphics->DeviceContext->DrawIndexed(meshFilter->MeshData->IndexCount, materialFilter->StartIndex, 0);
}
}
GlobalRefs::Graphics->EndRender();
}
};
class IFPSCameraSystem : public ISystem
{
public:
IFPSCameraSystem()
{
Type = IST_FPSCAMERA;
TypeList.push_back(CIT_FPSCAMERA);
this->ConstructPerspectiveMatrix(60.0f, (float)GlobalRefs::Window->ScreenWidth, (float)GlobalRefs::Window->ScreenHeight, 0.1f, 1000);
this->ConstructViewMatrix();
}
~IFPSCameraSystem()
{
}
void ConstructPerspectiveMatrix(float fieldOfView, float screenWidth, float screenHeight, float screenNear, float screenFar)
{
GlobalRefs::Graphics->ProjectionMatrix = Matrix4x4f::Perspective(fieldOfView, screenWidth / screenHeight, screenNear, screenFar);
}
void ConstructOrthographicMatrix(float screenWidth, float screenHeight, float screenNear, float screenFar)
{
GlobalRefs::Graphics->ProjectionMatrix = Matrix4x4f::Orthographic(0, screenWidth, 0, screenHeight, screenNear, screenFar);
}
void ConstructViewMatrix()
{
GlobalRefs::Graphics->ViewMatrix = Matrix4x4f::LookAtLH(Vector3f(0, 0, -5), Vector3f(0, 0, 1), Vector3f(0, 1, 0));
}
void Execute(vector<IComponent*> componentList)
{
//Group
for(int i = 0; i < Group.size(); i++)
{
IFPSCameraComponent *camera = (IFPSCameraComponent*)componentList[Group[i]->ComponentList[ECOI_CAMERA]];
float distance = camera->Speed * GlobalRefs::Time->GetDeltaTime();
float angle = 10.0f * GlobalRefs::Time->GetDeltaTime();
float rollSpeed = 100 * GlobalRefs::Time->GetDeltaTime();
// Keyboard Controller
if(GlobalRefs::Input->KeyDown(DIK_W))
{
camera->Velocity += camera->Look * distance;
}
if(GlobalRefs::Input->KeyDown(DIK_S))
{
camera->Velocity -= camera->Look * distance;
}
if(GlobalRefs::Input->KeyDown(DIK_A))
{
camera->Velocity -= camera->Right * distance;
}
if(GlobalRefs::Input->KeyDown(DIK_D))
{
camera->Velocity += camera->Right * distance;
}
if(GlobalRefs::Input->KeyDown(DIK_R))
{
camera->Velocity += camera->Up * distance;
}
if(GlobalRefs::Input->KeyDown(DIK_F))
{
camera->Velocity -= camera->Up * distance;
}
// Camera Pitch
if(GlobalRefs::Input->KeyDown(DIK_UP))
{
Matrix4x4f rotMatrix = Matrix4x4f::RotationAxis(camera->Right, Mathf::DegreeToRadian(-angle));
camera->Look = Matrix4x4f::Vec3TransformNormal(camera->Look, rotMatrix);
camera->Up = Matrix4x4f::Vec3TransformNormal(camera->Up, rotMatrix);
camera->Right = Matrix4x4f::Vec3TransformNormal(camera->Right, rotMatrix);
}
if(GlobalRefs::Input->KeyDown(DIK_DOWN))
{
Matrix4x4f rotMatrix = Matrix4x4f::RotationAxis(camera->Right, Mathd::DegreeToRadian(angle));
camera->Look = Matrix4x4f::Vec3TransformNormal(camera->Look, rotMatrix);
camera->Up = Matrix4x4f::Vec3TransformNormal(camera->Up, rotMatrix);
camera->Right = Matrix4x4f::Vec3TransformNormal(camera->Right, rotMatrix);
}
// Camera Yaw
if(GlobalRefs::Input->KeyDown(DIK_LEFT))
{
Matrix4x4f rotMatrix = Matrix4x4f::RotationAxis(camera->Up, Mathd::DegreeToRadian(-angle));
camera->Look = Matrix4x4f::Vec3TransformNormal(camera->Look, rotMatrix);
camera->Up = Matrix4x4f::Vec3TransformNormal(camera->Up, rotMatrix);
camera->Right = Matrix4x4f::Vec3TransformNormal(camera->Right, rotMatrix);
}
if(GlobalRefs::Input->KeyDown(DIK_RIGHT))
{
Matrix4x4f rotMatrix = Matrix4x4f::RotationAxis(camera->Up, Mathd::DegreeToRadian(angle));
camera->Look = Matrix4x4f::Vec3TransformNormal(camera->Look, rotMatrix);
camera->Up = Matrix4x4f::Vec3TransformNormal(camera->Up, rotMatrix);
camera->Right = Matrix4x4f::Vec3TransformNormal(camera->Right, rotMatrix);
}
// Camera Roll
if(GlobalRefs::Input->KeyDown(DIK_Q))
{
Matrix4x4f rotMatrix = Matrix4x4f::RotationAxis(camera->Look, Mathd::DegreeToRadian(rollSpeed));
camera->Look = Matrix4x4f::Vec3TransformNormal(camera->Look, rotMatrix);
camera->Up = Matrix4x4f::Vec3TransformNormal(camera->Up, rotMatrix);
camera->Right = Matrix4x4f::Vec3TransformNormal(camera->Right, rotMatrix);
}
if(GlobalRefs::Input->KeyDown(DIK_E))
{
Matrix4x4f rotMatrix = Matrix4x4f::RotationAxis(camera->Look, Mathd::DegreeToRadian(-rollSpeed));
camera->Look = Matrix4x4f::Vec3TransformNormal(camera->Look, rotMatrix);
camera->Up = Matrix4x4f::Vec3TransformNormal(camera->Up, rotMatrix);
camera->Right = Matrix4x4f::Vec3TransformNormal(camera->Right, rotMatrix);
}
// Mouse Controller
// if(GlobalRefs::Input->MouseButtonDown(1))
{
// Yaw
if(GlobalRefs::Input->GetMouseMovementX() != 0)
{
Matrix4x4f rotMatrix = Matrix4x4f::RotationAxis(camera->Up, Mathd::DegreeToRadian(GlobalRefs::Input->GetMouseMovementX() * angle));
camera->Look = Matrix4x4f::Vec3TransformNormal(camera->Look, rotMatrix);
camera->Up = Matrix4x4f::Vec3TransformNormal(camera->Up, rotMatrix);
camera->Right = Matrix4x4f::Vec3TransformNormal(camera->Right, rotMatrix);
}
// Pitch
if(GlobalRefs::Input->GetMouseMovementY() != 0)
{
Matrix4x4f rotMatrix = Matrix4x4f::RotationAxis(camera->Right, Mathd::DegreeToRadian(GlobalRefs::Input->GetMouseMovementY() * angle));
camera->Look = Matrix4x4f::Vec3TransformNormal(camera->Look, rotMatrix);
camera->Up = Matrix4x4f::Vec3TransformNormal(camera->Up, rotMatrix);
camera->Right = Matrix4x4f::Vec3TransformNormal(camera->Right, rotMatrix);
}
}
if(GlobalRefs::Input->KeyDown(DIK_Z))
{
camera->Speed += 0.01f * GlobalRefs::Time->GetDeltaTime();
}
if(GlobalRefs::Input->KeyDown(DIK_X))
{
camera->Speed -= 0.01f * GlobalRefs::Time->GetDeltaTime();
}
// Camera->SetPosition(Camera->GetPosition() + Velocity);
camera->Position = camera->Position + camera->Velocity;
// Camera->SetAudioListenerPosition(Camera->GetPosition());
camera->LookAt = /*Camera->GetPosition()*/camera->Position + camera->Look;
camera->Look.Normalize();
camera->Right = Vector3f::Cross(camera->Up, camera->Look);
camera->Right.Normalize();
camera->Up = Vector3f::Cross(camera->Look, camera->Right);
camera->Up.Normalize();
GlobalRefs::Graphics->ViewMatrix = Matrix4x4f::LookAtLH(camera->Position, camera->LookAt, camera->Up);
camera->Velocity = Vector3f::Lerp(camera->Velocity, Vector3f(0, 0, 0), GlobalRefs::Time->GetDeltaTime() * 4);
}
}
};
class ECSManager
{
private:
list<IEntity*> EntityList;
vector<IComponent*> ComponentList;
list<ISystem*> SystemList;
list<IEntity*>::iterator EIter;
// list<IComponent*>::iterator CIter;
list<ISystem*>::iterator SIter;
int EntityCount;
int ComponentCount;
int SystemCount;
public:
ECSManager();
virtual ~ECSManager();
void AddEntity(IEntity *entity);
void RemoveEntity(IEntity *entity);
void AddComponent(IEntity *entity, IComponent *component);
void RemoveComponent(IEntity *entity, IComponent *component);
void AddSystem(ISystem *system);
void RemoveSystem(ISystem *system);
void Update();
};
#endif | [
"m.yuneeb90@gmail.com"
] | m.yuneeb90@gmail.com |
acf6064f4e0b1bb015c73111c2cef76f1d775146 | 5540dda016c1699e24c85c1ebe6fa7d7427809f4 | /Trees/Centroid.cpp | 25de0ec6a03a5d29da8fbcb0ca7e688d6e6dacce | [] | no_license | tejas01101001/Competitive-coding | 8f5601610104148450c4d9a923be82be1ed51737 | d0f29301ae5867d6ace451aa58771f3190589711 | refs/heads/master | 2021-09-02T13:24:56.514912 | 2021-08-17T20:58:43 | 2021-08-17T20:58:43 | 226,728,595 | 22 | 17 | null | 2020-08-02T15:08:34 | 2019-12-08T20:41:15 | Makefile | UTF-8 | C++ | false | false | 887 | cpp | const int N = 2e5 + 5;
int n, nodes, eu, ev;
int siz[N], par_centroid[N];
set<int> adj[N];
void dfs(int s, int e)
{
nodes++;
siz[s] = 1;
for (auto u : adj[s])
{
if (u == e)
continue;
dfs(u, s);
siz[s] += siz[u];
}
}
int centroid(int s, int e)
{
for (auto u : adj[s])
{
if (u == e)
continue;
if (siz[u] > nodes / 2)
return centroid(u, s);
}
return s;
}
void decompose(int s, int e)
{
nodes = 0;
dfs(s, s);
int node = centroid(s, s);
par_centroid[node] = e;
for (auto u : adj[node])
{
adj[u].erase(node);
decompose(u,node);
}
}
int main()
{
kira;
cin >> n;
forz(i, n - 1)
{
cin >> eu >> ev;
adj[eu].insert(ev);
adj[ev].insert(eu);
}
decompose(1, 0);
run_time();
return 0;
} | [
"tejas18@iitg.ac.in"
] | tejas18@iitg.ac.in |
d6abb9892943de9d1525f9e9e3c07a987d2f2fa8 | 49ef54142ecdc7778ee789d23951ef730a506441 | /Queue/Queue Reversal.cpp | f7cd9d4d7a13d8640a27d2dd38b1a96734fef804 | [] | no_license | Ragul-SV/Data-Structures-and-Algorithms | fa7471fc24c93e04bf69804b4a978ec33c0d9b28 | ab35edb82f8f27eb23e98d2b73321022abfbe4e6 | refs/heads/master | 2023-06-05T07:14:03.551044 | 2021-06-24T17:14:00 | 2021-06-24T17:14:00 | 248,221,115 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 249 | cpp | queue<long long int> rev(queue<long long int> q)
{
stack<long long int> s;
while(!q.empty())
{
s.push(q.front());
q.pop();
}
while(!s.empty())
{
q.push(s.top());
s.pop();
}
return q;
}
| [
"noreply@github.com"
] | Ragul-SV.noreply@github.com |
4f4d211d55d9e77a1512958af35bf23c29a4985b | 394e1fe7ad1ca6d5d0b4b58d8bbb5ce6a5b0566c | /CarCam/CarCam.ino | 15f3684998dc4fce4eae8f9a1aea72c5fd26e7d6 | [] | no_license | JaimeNufio/Arduino-Projects | ee7b16c70209a3b77aa38febfaca0761cbbc62e8 | 0f26be97d7392e69a41f1eaa23238e3628697cec | refs/heads/master | 2021-01-25T10:50:14.147666 | 2018-08-27T23:49:03 | 2018-08-27T23:49:03 | 93,882,559 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,231 | ino | #include <SPI.h>
#include "RF24.h"
#include "nRF24L01.h"
#include <ArduCAM.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include "memorysaver.h"
//This demo can only work on OV2640_MINI_2MP or OV5642_MINI_5MP or OV5642_MINI_5MP_BIT_ROTATION_FIXED platform.
#if !(defined OV5642_MINI_5MP || defined OV5642_MINI_5MP_BIT_ROTATION_FIXED || defined OV2640_MINI_2MP || defined OV3640_MINI_3MP)
#error Please select the hardware platform and camera module in the ../libraries/ArduCAM/memorysaver.h file
#endif
#define SD_CS 14
const int SPI_CS = 15, camSign = 16;
ArduCAM myCAM( OV2640, SPI_CS );
RF24 myRadio (3,4);
struct package{
enum XDIRECTION {LEFT,RIGHT,CENTER};
enum YDIRECTION {FORWARD,BACKWARD,NONE};
XDIRECTION aX;
YDIRECTION aY;
XDIRECTION bX;
YDIRECTION bY;
int aValY, aValX, bValY, bValX;
bool buttonA, buttonB, readGyro;
byte packetTest = 0;
int errorX, errorY;
};
byte addresses[][6] = {"0"};
typedef struct package Package;
Package data;
int motorA[] = {7,6,5}; //last is the enable
int motorB[] = {8,9,17};
/////int control[] = {0,1};
int sign = 2;
float favor;
String X[] = {"LEFT","RIGHT","CENTER"};
String Y[] = {"FORWARD","BACKWARD","NONE"};
//x 0,505,1022
//y 0,515,1023
void myCAMSaveToSDFile(){
char str[8];
byte buf[256];
static int i = 0;
static int k = 0;
uint8_t temp = 0,temp_last=0;
uint32_t length = 0;
bool is_header = false;
File outFile;
//Flush the FIFO
myCAM.flush_fifo();
//Clear the capture done flag
myCAM.clear_fifo_flag();
//Start capture
myCAM.start_capture();
Serial.println(F("start Capture"));
while(!myCAM.get_bit(ARDUCHIP_TRIG , CAP_DONE_MASK));
Serial.println(F("Capture Done."));
length = myCAM.read_fifo_length();
Serial.print(F("The fifo length is :"));
Serial.println(length, DEC);
if (length >= MAX_FIFO_SIZE) //384K
{
Serial.println(F("Over size."));
return ;
}
if (length == 0 ) //0 kb
{
Serial.println(F("Size is 0."));
return ;
}
//Construct a file name
k = k + 1;
itoa(k, str, 10);
strcat(str, ".jpg");
//Open the new file
outFile = SD.open(str, O_WRITE | O_CREAT | O_TRUNC);
if(!outFile){
Serial.println(F("File open faild"));
return;
}
myCAM.CS_LOW();
myCAM.set_fifo_burst();
while ( length-- )
{
temp_last = temp;
temp = SPI.transfer(0x00);
//Read JPEG data from FIFO
if ( (temp == 0xD9) && (temp_last == 0xFF) ) //If find the end ,break while,
{
buf[i++] = temp; //save the last 0XD9
//Write the remain bytes in the buffer
myCAM.CS_HIGH();
outFile.write(buf, i);
//Close the file
outFile.close();
Serial.println(F("Image save OK."));
is_header = false;
i = 0;
}
if (is_header == true)
{
//Write image data to buffer if not full
if (i < 256)
buf[i++] = temp;
else
{
//Write 256 bytes image data to file
myCAM.CS_HIGH();
outFile.write(buf, 256);
i = 0;
buf[i++] = temp;
myCAM.CS_LOW();
myCAM.set_fifo_burst();
}
}
else if ((temp == 0xD8) & (temp_last == 0xFF))
{
is_header = true;
buf[i++] = temp_last;
buf[i++] = temp;
}
}
}
void setup() {
Serial.begin(115200);
pinMode(10,OUTPUT);
pinMode(10,HIGH);
for (int i = 0; i<3; i++){
pinMode(motorA[i],OUTPUT);
pinMode(motorB[i],OUTPUT);
}
// pinMode(control[0],INPUT);
// pinMode(control[1],INPUT);
pinMode(sign,OUTPUT);
pinMode(camSign,OUTPUT);
//default, forward.
digitalWrite(motorA[0],HIGH);
digitalWrite(motorB[0],HIGH);
digitalWrite(motorA[1],LOW);
digitalWrite(motorB[1],LOW);
digitalWrite(motorA[2],0);
digitalWrite(motorB[2],0);
// pinMode(10,OUTPUT);
digitalWrite(sign,LOW);
digitalWrite(camSign,LOW);
Serial.begin(115200);
// /*
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
uint8_t vid, pid;
uint8_t temp;
Wire.begin();
Serial.begin(115200);
Serial.println(F("ArduCAM Start!"));
//set the CS as an output:
pinMode(SPI_CS,OUTPUT);
// initialize SPI:
SPI.begin();
while(1){
//Check if the ArduCAM SPI bus is OK
myCAM.write_reg(ARDUCHIP_TEST1, 0x55);
temp = myCAM.read_reg(ARDUCHIP_TEST1);
if (temp != 0x55){
Serial.println(F("SPI interface Error!"));
delay(1000);continue;
}else{
Serial.println(F("SPI interface OK."));digitalWrite(camSign,HIGH);break;
}
}
//Initialize SD Card
while(!SD.begin(SD_CS)){
Serial.println(F("SD Card Error!"));delay(1000);
}
Serial.println(F("SD Card detected."));
#if defined (OV2640_MINI_2MP)
while(1){
//Check if the camera module type is OV2640
myCAM.wrSensorReg8_8(0xff, 0x01);
myCAM.rdSensorReg8_8(OV2640_CHIPID_HIGH, &vid);
myCAM.rdSensorReg8_8(OV2640_CHIPID_LOW, &pid);
if ((vid != 0x26 ) && (( pid != 0x41 ) || ( pid != 0x42 ))){
Serial.println(F("Can't find OV2640 module!"));
delay(1000);continue;
}
else{
Serial.println(F("OV2640 detected."));break;
}
}
#elif defined (OV3640_MINI_3MP)
while(1){
//Check if the camera module type is OV3640
myCAM.rdSensorReg16_8(OV3640_CHIPID_HIGH, &vid);
myCAM.rdSensorReg16_8(OV3640_CHIPID_LOW, &pid);
if ((vid != 0x36) || (pid != 0x4C)){
Serial.println(F("Can't find OV3640 module!"));
delay(1000);continue;
}else{
Serial.println(F("OV3640 detected."));break;
}
}
#else
while(1){
//Check if the camera module type is OV5642
myCAM.wrSensorReg16_8(0xff, 0x01);
myCAM.rdSensorReg16_8(OV5642_CHIPID_HIGH, &vid);
myCAM.rdSensorReg16_8(OV5642_CHIPID_LOW, &pid);
if((vid != 0x56) || (pid != 0x42)){
Serial.println(F("Can't find OV5642 module!"));
delay(1000);continue;
}
else{
Serial.println(F("OV5642 detected."));break;
}
}
#endif
myCAM.set_format(JPEG);
myCAM.InitCAM();
#if defined (OV2640_MINI_2MP)
myCAM.OV2640_set_JPEG_size(OV2640_320x240);
#elif defined (OV3640_MINI_3MP)
myCAM.OV3640_set_JPEG_size(OV3640_320x240);
#else
myCAM.write_reg(ARDUCHIP_TIM, VSYNC_LEVEL_MASK); //VSYNC is active HIGH
myCAM.OV5642_set_JPEG_size(OV5642_320x240);
#endif
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//*/
myRadio.begin();
myRadio.setChannel(115);
myRadio.setPALevel(RF24_PA_MAX); //switch MIN to MAX, HIgh or LOW
myRadio.setDataRate(RF24_250KBPS);//( RF24_250KBPS ) ;
myRadio.openReadingPipe(1, addresses[0]);
myRadio.startListening();
myRadio.printDetails();
Serial.println("Radio should be set");
// delay(1000);
digitalWrite(sign,HIGH);
digitalWrite(camSign,HIGH);
delay(500);
digitalWrite(sign,LOW);
digitalWrite(camSign,LOW);
delay(500);
digitalWrite(sign,HIGH);
digitalWrite(camSign,HIGH);
delay(500);
digitalWrite(sign,LOW);
digitalWrite(camSign,LOW);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
pinMode(14,OUTPUT);
}
void setSpd(){
int valX = data.aValX, valY = data.aValY;
favor = 150;//((float)valX)/(500*2); //255
valY=favor;
// if (data.aX == package::XDIRECTION::LEFT){
// Serial.println("LEFT");
analogWrite(motorA[2],(int)(valY));//Left Wheel
analogWrite(motorB[2],(int)valY);
// }else if (data.aX == package::XDIRECTION::RIGHT){
// Serial.println("RIGHT");
analogWrite(motorA[2],(int)valY);
analogWrite(motorB[2],(int)(valY));
// }else{
// Serial.println("not left or right");
analogWrite(motorA[2],favor);
analogWrite(motorB[2],favor);
//}
}
void spin(){
int valX = 150;//data.aValX;
Serial.println("spin!");
// Serial.print("spin-");
if (data.aX == package::XDIRECTION::LEFT){
digitalWrite(motorA[0],HIGH);
digitalWrite(motorB[0],LOW);
digitalWrite(motorA[1],LOW);
digitalWrite(motorB[1],HIGH);
analogWrite(motorA[2],valX);
analogWrite(motorB[2],valX);
// Serial.println("left");
}else if (data.aX == package::XDIRECTION::RIGHT){
analogWrite(motorA[2],valX);
analogWrite(motorB[2],valX);
digitalWrite(motorA[0],LOW);
digitalWrite(motorB[0],HIGH);
digitalWrite(motorA[1],HIGH);
digitalWrite(motorB[1],LOW);
// Serial.println("right");
}else{
digitalWrite(motorA[0],LOW);
digitalWrite(motorB[0],LOW);
digitalWrite(motorA[1],LOW);
digitalWrite(motorB[1],LOW);
analogWrite(motorA[1],0);
analogWrite(motorA[2],0);
}
}
void setDir(){
Serial.println(data.aValY);
if (data.aY == package::YDIRECTION::FORWARD){
digitalWrite(motorA[0],LOW);
digitalWrite(motorB[0],LOW);
digitalWrite(motorA[1],HIGH);
digitalWrite(motorB[1],HIGH);
// Serial.print("wheels forawrd");
// Serial.print(", favors ");
// Serial.println(X[data.x]);
setSpd();
}else if (data.aY == package::YDIRECTION::BACKWARD){
digitalWrite(motorA[0],HIGH);
digitalWrite(motorB[0],HIGH);
digitalWrite(motorA[1],LOW);
digitalWrite(motorB[1],LOW);
// Serial.print("wheels backward");
// Serial.print(", favors ");
// Serial.println(X[data.x]);
setSpd();
// }else if (data.aX == package::XDIRECTION::LEFT || data.aX == package::XDIRECTION::RIGHT){
// Serial.println("No Y movement, ");
// data.aValY = 0;
// spin();
}else if (data.aY == package::YDIRECTION::NONE){
Serial.println("No input");
analogWrite(motorA[1],0);
analogWrite(motorA[2],0);
digitalWrite(motorA[0],LOW);
digitalWrite(motorB[0],LOW);
digitalWrite(motorA[1],LOW);
digitalWrite(motorB[1],LOW);
}
if (data.aX != package::XDIRECTION::CENTER){
data.aValY = 0;
spin();
}
}
void loop() {
delay(5);
if (myRadio.available()) {
// digitalWrite(14,HIGH);
Serial.println("data");
if (data.packetTest != 0){
digitalWrite(sign,HIGH);
Serial.println(data.packetTest);
}
// bool done = false;
while (myRadio.available()){
digitalWrite(camSign,LOW);
//setDir();
myRadio.read( &data, sizeof(data) );
//delay(100);
Serial.println(data.buttonB);
if (data.buttonB==true){
Serial.println("SHOOT");
digitalWrite(camSign,HIGH);
myCAMSaveToSDFile();
delay(5000);
digitalWrite(camSign,LOW);
}
// /*
Serial.print("Ax:");
Serial.print(X[(&data)->aX]);
Serial.print(" | Ay:");
Serial.print(Y[(&data)->aY]);
Serial.print(" | Bx:");
Serial.print(X[(&data)->bX]);
Serial.print(" | By:");
Serial.print(Y[(&data)->bY]);
// */
}
setDir();
}else{
//digitalWrite(14,LOW);
digitalWrite(camSign,HIGH);
digitalWrite(sign, LOW);
Serial.println(":(");
Serial.println("No input");
}
/*
Serial.print("X: ");
Serial.print(X[x]);
Serial.print(" ");
Serial.print(valX);
Serial.print(" Y: ");
// Serial.print(Y[y]);
Serial.print(" ");
Serial.print(valY);
Serial.print(" with modifier ");
Serial.println(favor);
delay(200);
*/
}
| [
"jaimeenufio@gmail.com"
] | jaimeenufio@gmail.com |
df882816358ff173abaa3e8c035cfdd23674d434 | ad822f849322c5dcad78d609f28259031a96c98e | /SDK/ControlPanelButtonBase_nobacking_parameters.h | c4d39a5e8c2300df699c36ae040b776b17626228 | [] | no_license | zH4x-SDK/zAstroneer-SDK | 1cdc9c51b60be619202c0258a0dd66bf96898ac4 | 35047f506eaef251a161792fcd2ddd24fe446050 | refs/heads/main | 2023-07-24T08:20:55.346698 | 2021-08-27T13:33:33 | 2021-08-27T13:33:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,875 | h | #pragma once
#include "../SDK.h"
// Name: Astroneer-SDK, Version: 1.0.0
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Parameters
//---------------------------------------------------------------------------
// Function ControlPanelButtonBase_nobacking.ControlPanelButtonBase_nobacking_C.UpdateButtonVisuals
struct AControlPanelButtonBase_nobacking_C_UpdateButtonVisuals_Params
{
};
// Function ControlPanelButtonBase_nobacking.ControlPanelButtonBase_nobacking_C.UserConstructionScript
struct AControlPanelButtonBase_nobacking_C_UserConstructionScript_Params
{
};
// Function ControlPanelButtonBase_nobacking.ControlPanelButtonBase_nobacking_C.ButtonPressAnim__FinishedFunc
struct AControlPanelButtonBase_nobacking_C_ButtonPressAnim__FinishedFunc_Params
{
};
// Function ControlPanelButtonBase_nobacking.ControlPanelButtonBase_nobacking_C.ButtonPressAnim__UpdateFunc
struct AControlPanelButtonBase_nobacking_C_ButtonPressAnim__UpdateFunc_Params
{
};
// Function ControlPanelButtonBase_nobacking.ControlPanelButtonBase_nobacking_C.ButtonHoverJiggleAnim__FinishedFunc
struct AControlPanelButtonBase_nobacking_C_ButtonHoverJiggleAnim__FinishedFunc_Params
{
};
// Function ControlPanelButtonBase_nobacking.ControlPanelButtonBase_nobacking_C.ButtonHoverJiggleAnim__UpdateFunc
struct AControlPanelButtonBase_nobacking_C_ButtonHoverJiggleAnim__UpdateFunc_Params
{
};
// Function ControlPanelButtonBase_nobacking.ControlPanelButtonBase_nobacking_C.ReceiveBeginPlay
struct AControlPanelButtonBase_nobacking_C_ReceiveBeginPlay_Params
{
};
// Function ControlPanelButtonBase_nobacking.ControlPanelButtonBase_nobacking_C.BndEvt__Box_K2Node_ComponentBoundEvent_0_ComponentOnClickedSignature__DelegateSignature
struct AControlPanelButtonBase_nobacking_C_BndEvt__Box_K2Node_ComponentBoundEvent_0_ComponentOnClickedSignature__DelegateSignature_Params
{
class UPrimitiveComponent* TouchedComponent; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
struct FKey ButtonPressed; // (BlueprintVisible, BlueprintReadOnly, Parm)
};
// Function ControlPanelButtonBase_nobacking.ControlPanelButtonBase_nobacking_C.HandleButtonPressed
struct AControlPanelButtonBase_nobacking_C_HandleButtonPressed_Params
{
};
// Function ControlPanelButtonBase_nobacking.ControlPanelButtonBase_nobacking_C.BndEvt__Box_K2Node_ComponentBoundEvent_0_ComponentBeginCursorOverSignature__DelegateSignature
struct AControlPanelButtonBase_nobacking_C_BndEvt__Box_K2Node_ComponentBoundEvent_0_ComponentBeginCursorOverSignature__DelegateSignature_Params
{
class UPrimitiveComponent* TouchedComponent; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function ControlPanelButtonBase_nobacking.ControlPanelButtonBase_nobacking_C.BndEvt__Box_K2Node_ComponentBoundEvent_0_ComponentEndCursorOverSignature__DelegateSignature
struct AControlPanelButtonBase_nobacking_C_BndEvt__Box_K2Node_ComponentBoundEvent_0_ComponentEndCursorOverSignature__DelegateSignature_Params
{
class UPrimitiveComponent* TouchedComponent; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function ControlPanelButtonBase_nobacking.ControlPanelButtonBase_nobacking_C.HandleEnabledChanged
struct AControlPanelButtonBase_nobacking_C_HandleEnabledChanged_Params
{
bool Enable; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function ControlPanelButtonBase_nobacking.ControlPanelButtonBase_nobacking_C.HandleHoveredChanged
struct AControlPanelButtonBase_nobacking_C_HandleHoveredChanged_Params
{
bool Enable; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function ControlPanelButtonBase_nobacking.ControlPanelButtonBase_nobacking_C.CancelAnimations
struct AControlPanelButtonBase_nobacking_C_CancelAnimations_Params
{
};
// Function ControlPanelButtonBase_nobacking.ControlPanelButtonBase_nobacking_C.ExecuteUbergraph_ControlPanelButtonBase_nobacking
struct AControlPanelButtonBase_nobacking_C_ExecuteUbergraph_ControlPanelButtonBase_nobacking_Params
{
int EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
8dd13110e2762bfea2240e7d11b4f8ee11a8c4c5 | 8084569a8b0d97012cd12edd7609c9ccb0d9624e | /Inc/translator.hpp | b2f5c2cbedb47dcf5e5faba649526a87d6b5c709 | [] | no_license | niktob560/mcuterminaltranslator | 7c560b78f0db90edfe0ff38dcc834c6ef1cfcad8 | bf743ce5420d82dee9fbcfb6c95501bd50b019c2 | refs/heads/master | 2020-08-04T12:37:55.359689 | 2020-04-22T14:43:35 | 2020-04-22T14:43:35 | 212,139,656 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,395 | hpp | #include <string.h>
#include <stdint.h>
namespace translator
{
extern const uint8_t SYS_LEN;
#ifdef USE_MULTIDEVICE
constexpr uint8_t getSenderId(uint8_t* p)
{
return p[SYS_LEN];
}
#ifdef USE_DYNAMIC_ID
extern uint8_t myId;
inline void setMyId(uint8_t id)
{
myId = id;
}
inline uint8_t getMyId(void)
{
return myId;
}
#else
extern const uint8_t myId;
#endif
#endif
typedef uint32_t STR_LEN_DTYPE;
typedef uint16_t checksum_t;
const STR_LEN_DTYPE str_NAN = 0xFFFFFFFF;
const uint8_t TYPE_CMD = 0x01,
TYPE_VAR = 0x02,
TYPE_ARR = 0x03,
TYPE_BAD_LEN = 100,
TYPE_BAD_TYPE = 101,
TYPE_BAD_CHECKSUM = 102,
LEN_MASK = 0x3F;
//generate checksum for char array
checksum_t genCheckSum(const uint8_t* c);
//get len of payload
constexpr uint8_t getLen(const uint8_t* package)
{
return package[0] & LEN_MASK;
}
//get type of package
constexpr uint8_t getType(const uint8_t* package)
{
return static_cast<uint8_t>((package[0] & (~LEN_MASK)) >> 6);
}
//parse var from var package and write into toArr[id], return type of package
uint8_t parseVar(uint8_t* package, uint8_t* toArr, uint8_t elsize);
//parse array from array package and write into toArr[id], return type of package
uint8_t parseArr(uint8_t* package, uint8_t** toArr);
//parse array from array package and write into toArr(ignoring id), return type of package
uint8_t parseArrNoId(uint8_t* package, uint8_t* toArr);
//parse array id from array package
constexpr uint8_t parseArrId(uint8_t* package)
{
return package[SYS_LEN];
}
//parse cmd from package, call funcArr[cmd], return type of package, max num of funcs - 255, max len - 1
uint8_t parseCmd(uint8_t* package, void (*funcArr [])());
size_t parseCmd(uint8_t* package);
//parse input package, get payload, return type of package
uint8_t parsePacket(uint8_t* package, uint8_t* payloadto);
//compare 2 packets
bool equals(const uint8_t* p1, const uint8_t* p2);
//construct head byte
constexpr uint8_t getZeroByte(const uint8_t type, const uint8_t len)
{
return static_cast<uint8_t>(((type & 0x03) << 6) | (len & LEN_MASK));
}
//extratc checksum from packet
constexpr checksum_t getCheckSum(const uint8_t* package)
{
return static_cast<checksum_t>((package[1] << 8) | package[2]);
}
//gets cmd num at 'cmd', returns final package into target pointer
void generateCmd(const uint8_t cmd, uint8_t* tgt);
//validate checksum, type, len
bool validate(const uint8_t* package);
//create var package
void generateVar(const uint8_t id, const uint8_t varlen, const uint8_t* var, uint8_t *tgt);
//create array package
void generateArr(const uint8_t id, const uint8_t arrlen, const uint8_t elsize, const uint8_t* arr, uint8_t* tgt);
//check for package is full
bool isFull(uint8_t* package, const uint8_t len);
//validate header
bool isHeaderValid(uint8_t head);
}
| [
"niktob560@gmail.com"
] | niktob560@gmail.com |
b0ec51b39d053336032b0a50811d6993553b8e88 | c22f6b0fd28c8df7a0971fecb7a7fc00f0c0a564 | /LinkedList.h | d7030ef67c84609246b9a68d1450df41bcfc9e66 | [] | no_license | NathanYee412/practiceCplusplus | f8da530a538a4e50eadfb06fafdfaaad967fe49e | 988c6f2292a1a040b3bcc544bd94674c84d858d2 | refs/heads/main | 2023-03-11T05:18:34.234704 | 2021-02-20T22:29:13 | 2021-02-20T22:29:13 | 338,378,742 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,428 | h | #pragma once
#include<iostream>
using namespace std;
class Node {
public:
int val;
Node* next;
};
class LinkedList {
private:
Node* head;
public:
LinkedList() { head = NULL; }
~LinkedList() { };
void add(int num);
void removeNode(Node* node);
void displayList();
Node* reverseList(Node* head);
Node* getHead();
};
// return the head of the linked
Node* LinkedList::getHead() {
return head;
}
// Add a new node to the end of the linked list
void LinkedList::add(int num) {
Node* newNode = new Node();
newNode->val = num;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
}
else {
Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
// recursively reverse linked list
Node* LinkedList::reverseList(Node* head) {
if (head == NULL || head->next == NULL) {
return head;
}
Node* cur = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return cur;
}
// remove given node from list
void LinkedList::removeNode(Node* node) {
node->val = node->next->val;
node->next = node->next->next;
}
// display linked list
void LinkedList::displayList() {
Node* temp = head;
while (temp != NULL) {
cout << temp->val << endl;
temp = temp->next;
}
}
/*
// linked list destructor
LinkedList::~LinkedList() {
Node* nodeptr;
for (nodeptr = head; head; nodeptr = head) {
head = head->next;
delete nodeptr;
}
}
*/
| [
"nyee@csu.fullerton.edu"
] | nyee@csu.fullerton.edu |
85f011f08d07d570ae1c1b3e567724ecfa170142 | d73cf4af65fffc16c2326281fb7de3344566d6a1 | /TVM/NavigationDlg.h | 3c2a25723f64ef73a128c16eb9e7cad7aca7e44c | [] | no_license | yongchaohu/WH_DEVICE | c3299ddd63ff15ca5ba3fa476cb90eee01ddb541 | 5212d3b15dfcf5a542c0936ebf0e72ed66b85d05 | refs/heads/master | 2020-05-27T20:38:35.562316 | 2019-06-24T03:02:29 | 2019-06-24T03:02:29 | 188,782,571 | 0 | 0 | null | 2019-05-27T06:18:48 | 2019-05-27T06:18:48 | null | GB18030 | C++ | false | false | 2,209 | h | #pragma once
#include "BaseDlg.h"
#include "GroupBox.h"
#include "lable.h"
#include "OperationDlg.h"
#include "MenuMgr.h"
enum KEYBOARD
{
KEY_NOBODY = 0x0000, // 禁用维护键盘
KEY_NUMBER = 0x0001, // 数字键 0 ~ 9
KEY_DOT = 0x0002, // 圆点键 .
KEY_CLEAR = 0x0004, // 删除键 Backspace
KEY_ENTER = 0x0008, // 确认键 Enter
KEY_ESC = 0x0010, // 返回键 Esc
KEY_F1 = 0x0020, // F1 键 未使用
KEY_F2 = 0x0040, // F2 键 部分业务中的最终保存
KEY_F3 = 0x0080, // F3 键 返回上一级
KEY_F4 = 0x0100, // F4 键 未使用
KEY_F5 = 0x0200, // F5 键 上一页
KEY_F6 = 0x0400, // F6 键 下一页
KEY_INPUT = KEY_NUMBER | KEY_CLEAR | KEY_ENTER, // 常用组合 基本输入
KEY_RETURN = KEY_F3 | KEY_ESC, // 常用组合 返回菜单
KEY_PAGE = KEY_F5 | KEY_F6, // 常用组合 翻页
};
/**
@ brief 操作员菜单导航栏对话框
*/
class CNavigationDlg : public COperationDlg
{
DECLARE_DYNAMIC(CNavigationDlg)
DECLARE_MESSAGE_MAP()
public:
CNavigationDlg(CService* pService);
virtual ~CNavigationDlg();
enum { IDD = IDD_00301_CHARGE_RECEPT_DLG };
void SetKeyboard(DWORD keys); // 启用维护键盘指定按键
void DiableKeyboard(DWORD keys); // 禁用维护键盘指定按键
void ShowLevel(SERVICE_ID& serviceID); // 显示菜单级别
void AppendLevel(CString level); // 追加菜单级别
void DoService(SERVICE_ID& serviceID); // 启动业务
Menu_Item* SearchService(SERVICE_ID& serviceID); // 查找id对应的菜单
protected:
int OnCreate(LPCREATESTRUCT lpCreateStruct);
void OnDraw(CDC* pDC);
void OnMenuKindChanged(CMenuMgr::MENU_KIND&, CMenuMgr::MENU_KIND&);
void OnMenuItemStatusChanged(Menu_Item*);
void OnStartingService(CService* service);
void OnStartedService(CService* service);
static LRESULT CALLBACK KeyboardProc(int code, WPARAM wParam, LPARAM lParam);
private:
CRect m_navi_rect; // 导航栏内容显示区域
CString m_auto_level; // 自动获取的菜单级别
CString m_manual_level; // 手动追加的菜单级别
static DWORD m_hook_keys; // 启用指定按键,枚举 KeyBoard 按位与。
static HHOOK m_keyboard_hook; // 局部键盘钩子
};
| [
"1017943468@qq.com"
] | 1017943468@qq.com |
a293e9f371be336dfcecdd309655bfc344e40d80 | dccd1058e723b6617148824dc0243dbec4c9bd48 | /aoj/vol0/0015.cpp | cccc17096b91633a1807ae508f63869dd864d277 | [] | no_license | imulan/procon | 488e49de3bcbab36c624290cf9e370abfc8735bf | 2a86f47614fe0c34e403ffb35108705522785092 | refs/heads/master | 2021-05-22T09:24:19.691191 | 2021-01-02T14:27:13 | 2021-01-02T14:27:13 | 46,834,567 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 681 | cpp | #include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
int tcase;
cin >> tcase;
while(tcase--) {
string A, B, C = "";
cin >> A >> B;
unsigned sz = max(A.size(), B.size());
while(A.size()<sz) A = '0' + A;
while(B.size()<sz) B = '0' + B;
int c = 0;
for(int i=sz-1; i>=0; i--) {
//answer
C += (( (A[i]-'0') + (B[i]-'0') + c ) % 10 + '0');
//carry
c = ( (A[i]-'0') + (B[i]-'0') + c ) / 10;
}
if(c>0) C += (c + '0');
reverse(C.begin(), C.end());
if(C.size() > 80) cout << "overflow" << endl;
else cout << C << endl;
}
return 0;
} | [
"k0223.teru@gamil.com"
] | k0223.teru@gamil.com |
b5111f23688dbb50c98abde794483a992b9f84dd | 6bcdb9e8836cd60e972be865beb50fbfefdfa650 | /test/optional/combine.cpp | c1372f90b82e80985417df17161f12120f4df336 | [
"BSL-1.0"
] | permissive | pmiddend/fcppt | 4dbba03f7386c1e0d35c21aa0e88e96ed824957f | 9f437acbb10258e6df6982a550213a05815eb2be | refs/heads/master | 2020-09-22T08:54:49.438518 | 2019-11-30T14:14:04 | 2019-11-30T14:14:04 | 225,129,546 | 0 | 0 | BSL-1.0 | 2019-12-01T08:31:12 | 2019-12-01T08:31:11 | null | UTF-8 | C++ | false | false | 1,136 | cpp | // Copyright Carl Philipp Reh 2009 - 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <fcppt/optional/combine.hpp>
#include <fcppt/optional/object.hpp>
#include <fcppt/optional/output.hpp>
#include <fcppt/config/external_begin.hpp>
#include <catch2/catch.hpp>
#include <functional>
#include <fcppt/config/external_end.hpp>
TEST_CASE(
"optional::combine",
"[optional]"
)
{
typedef
fcppt::optional::object<
int
>
optional_int;
std::plus<
int
> const add{};
CHECK(
fcppt::optional::combine(
optional_int(
10
),
optional_int(
20
),
add
)
==
optional_int(
30
)
);
CHECK(
fcppt::optional::combine(
optional_int(
10
),
optional_int(),
add
)
==
optional_int(
10
)
);
CHECK(
fcppt::optional::combine(
optional_int(),
optional_int(
20
),
add
)
==
optional_int(
20
)
);
CHECK(
fcppt::optional::combine(
optional_int(),
optional_int(),
add
)
==
optional_int()
);
}
| [
"carlphilippreh@gmail.com"
] | carlphilippreh@gmail.com |
4f4fac23e0399dfa0706aabe9e04a6e7c6774b3a | 73c8a3179b944b63b2a798542896e4cdf0937b6e | /Codeforces/CantStopPlaying.cpp | b9dbaf5ab4dde58bf26eec1daab4480b4a4c9eb0 | [
"Apache-2.0"
] | permissive | aajjbb/contest-files | c151f1ab9b562ca91d2f8f4070cb0aac126a188d | 71de602a798b598b0365c570dd5db539fecf5b8c | refs/heads/master | 2023-07-23T19:34:12.565296 | 2023-07-16T00:57:55 | 2023-07-16T00:57:59 | 52,963,297 | 2 | 4 | null | 2017-08-03T20:12:19 | 2016-03-02T13:05:25 | C++ | UTF-8 | C++ | false | false | 2,231 | cpp | #include <bits/stdc++.h>
template<typename T> T gcd(T a, T b) {
if(!b) return a;
return gcd(b, a % b);
}
template<typename T> T lcm(T a, T b) {
return a * b / gcd(a, b);
}
template<typename T> void chmin(T& a, T b) { a = (a > b) ? b : a; }
template<typename T> void chmax(T& a, T b) { a = (a < b) ? b : a; }
int in() { int x; scanf("%d", &x); return x; }
using namespace std;
typedef long long Int;
typedef unsigned long long uInt;
typedef unsigned uint;
int T, N;
void compress(deque<pair<long long, int> >& arg, string& ans) {
vector<int> id_l, id_r;
while (arg.size() > 1 && arg[arg.size() - 1].first == arg[arg.size() - 2].first) {
id_r.push_back(arg[arg.size() - 1].second);
id_r.push_back(arg[arg.size() - 2].second);
arg.pop_back();
arg[arg.size() - 1].first *= 2LL;
}
while (arg.size() > 1 && arg[0].first == arg[1].first) {
id_l.push_back(arg[0].second);
id_l.push_back(arg[1].second);
arg.pop_front();
arg[0].first *= 2LL;
}
if (arg.size() > 1 && arg.front().first == arg.back().first) {
}
}
int main(void) {
cin >> T;
for (int t = 1; t <= T; t++) {
cin >> N;
string ans = "";
deque<pair<long long, int> > buffer;
for (int i = 0; i < N; i++) {
long long curr;
cin >> curr;
if (buffer.empty() || curr == buffer.back().first || curr > buffer.front().first) {
buffer.push_back(make_pair(curr, i));
ans += "r";
} else {
buffer.push_front(make_pair(curr, i));
ans += "l";
}
for (int j = 0; j < buffer.size(); j++) {
cout << buffer[j].first << " ";
}
cout << endl;
compress(buffer, ans);
for (int j = 0; j < buffer.size(); j++) {
cout << buffer[j].first << " ";
}
cout << endl;
}
if (buffer.size() == 1) {
cout << ans << "\n";
} else {
cout << "no\n";
}
}
return 0;
}
| [
"jefersonlsiq@gmail.com"
] | jefersonlsiq@gmail.com |
91e5e62d9f43870494299ebf2b18a33165030a31 | 0e514fb7dbe50b3367d81db17274819aa308b9b6 | /Headerfiles/New_Header/TTS.h | 5ac241e8dd3d96f836d101f956e42dbceee1a090 | [] | no_license | Randy1Burrell/DPLMusicCompileMagic | 5b7dbbcbace8ff796d8c262e5c803b3b7e0bda07 | c3c050c00390971a03c90c340b005c57c8bcc332 | refs/heads/master | 2021-05-04T10:35:40.518734 | 2017-12-05T22:54:45 | 2017-12-05T22:54:45 | 53,426,927 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,174 | h | /***********************************************************************
Syntax Anal - Interface for the SyntaxAnalysis class.
**********************************************************************/
#if !defined(_TTS_)
#define _TTS_
//Required Header files
//===============================================================================================================
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <sapi.h>
#include <atlconv.h>
//#include <atlexcept.h>
#include <stddef.h>
//#include "vcclr.h"
#include "atlbase.h"
#include "atlstr.h"
#include "comutil.h"
#include <sphelper.h>
#include <string>
#include <ctime>
#include <sapi.h>
#include <atlconv.h>
//===============================================================================================================
using namespace std;
class TTS
{
public:
void TTSRun(char val);
TTS(std::string in);
bool ConverTextToSpeech(string tt);
virtual ~TTS();
private:
void setText();
public:
char textt;
ISpVoice * pVoice;
wchar_t wtext;
//std::wstring wtext;
std::string text;
};
#endif | [
"Randy1burrell@yahoo.com"
] | Randy1burrell@yahoo.com |
40ba232e27e93bd1dc165f6575c9d30c9493e6f9 | c90daf06623258584a213c77a95f7eedcbf4aab2 | /loaders/frl_png/frl_png.cpp | 9b59fc2a96cb339955313b566aa791808e75e6c3 | [] | no_license | yellowcrescent/freyja | 9024edc66070aa72924ed7455f5bd374ded5ed16 | 4ae25822a17a1a6e48bda3d09c7f8e89882c49cc | refs/heads/master | 2021-05-26T21:27:45.929351 | 2013-04-29T08:36:30 | 2013-04-29T08:36:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,256 | cpp | /*
*
* Freyja Engine
* J. Hipps - http://jhipps.org/
* Copyright (c) 2013 Jacob Hipps/Neo-Retro Group
*
* Started - 22 Mar 2013
*
* Content Loaders - Core - PNG Loader
*
*/
#define ZLOADER_MAIN
#include "freyja.h"
#include "frl_png.h"
FRL_LOADER_TYPES frl_png_types[2] = { "PNG", NULL };
// Local declarations
void png_rowcall(png_structp png_ptr, png_uint_32 row, int pass);
int loader_init(FRE_RENDER_INIT_DATA* rdata) {
// link to Freyja Core functions
logthis = rdata->logthis_ptr;
fre_shutdown = rdata->fre_shutdown_ptr;
zlog_info("** %s - v%i.%i\n",LOADER_MODULE_NAME,LOADER_MODULE_VER_MAJOR,LOADER_MODULE_VER_MINOR);
zlog_info("** %s\n",LOADER_MODULE_VENDOR);
zlog_info("** Built %s\n",LOADER_MODULE_COMPILED);
return LOADER_MODULE_TYPE;
}
int loader_query_types(char* outstr, int maxsz) {
int tot_types = 0;
char *ttype;
for(int i = 0; i < 256; i++) {
ttype = frl_png_types[i].loader;
if(!ttype) {
tot_types = i;
break;
}
}
if(outstr) {
if(maxsz >= sizeof(FRL_LOADER_TYPES) * tot_types) {
memcpy(outstr,frl_png_types,tot_types);
} else {
zlog_warn("loader_query_types: outstr buffer size is insufficient! Nothing copied.\n");
}
}
zlog_debug("loader_query_types: outstr pointer is NULL. Returning only tot_types.\n");
return tot_types;
}
int decode_from_file(FILE* infile, void* dest_mem, int d_sz, int params) {
FRL_IMG_DATA* img_info = (FRL_IMG_DATA*)dest_mem;
img_info->type = FRL_TYPE_IMAGE;
img_info->type = FRL_IMG_RGBA;
int bpx = 3;
// check the header to make sure we've got a PNG
png_byte header[8];
fread(header,1,8,infile);
if(png_sig_cmp(header, 0, 8)) {
zlog_error("Not a PNG file!\n");
}
png_structp png_ptr;
png_infop info_ptr;
png_infop end_info;
if(!(png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL/*(png_voidp)user_error_ptr*/, NULL/*user_error_fn*/, NULL/*user_warning_fn*/))) {
zlog_error("PNG initilaization error!\n");
return 1;
}
if(!(info_ptr = png_create_info_struct(png_ptr))) {
png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
zlog_error("PNG initilaization error!\n");
return 1;
}
if(!(end_info = png_create_info_struct(png_ptr))) {
png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
zlog_error("PNG initilaization error!\n");
return 1;
}
// initialize file i/o
png_init_io(png_ptr, infile);
// tell libpng that we already read 8 bytes from the file to check for the signature/header
png_set_sig_bytes(png_ptr, 8);
// read it! take the low and broad way, which is good in this case, eh?
png_read_info(png_ptr, info_ptr);
// get parameters.
img_info->height = png_get_image_height(png_ptr, info_ptr);
img_info->width = png_get_image_width(png_ptr, info_ptr);
img_info->planes = 2; // 2D image
// FIXME: Force 32-bit depth and fill alpha accordingly if needed
img_info->depth = 32; //png_get_bit_depth(png_ptr, info_ptr);
// get the nearest powers of two
// FIXME: SKIP FOR NOW
int x_2com = img_info->width;
int y_2com = img_info->height;
/* FIXME **************
if(xpower2) {
x_2com = esm_find2com(img_info->width);
y_2com = esm_find2com(img_info->height);
}
*/
// add an alpha channel
bpx = 4; // 4 bytes/pixel
img_info->type = 4;
// this will make all the pixels of our image opaque and this ones
// that are simply the buffer zone be transparent
png_set_filler(png_ptr, 0xFF, PNG_FILLER_AFTER);
// allocate memory. ack.
if((img_info->data_ptr = (char*)calloc(x_2com,y_2com * bpx)) == NULL) {
zlog_error("decode_from_file: memory allocation error! bail out!\n");
}
int i;
// FIXME
png_bytep row_pointers[3200]; // negligence at work :)
for (i = 0; i < img_info->height; i++) {
// we just find the offset of each row. simple, eh?
row_pointers[i] = (png_byte*)((int)img_info->data_ptr + (x_2com * bpx * i));
}
// read the image!
png_read_image(png_ptr, row_pointers);
// die!
png_read_end(png_ptr, end_info);
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
return 0;
}
void png_rowcall(png_structp png_ptr, png_uint_32 row, int pass) {
/*
dots = (float(row) / float(png_img.height)) * PROG_DOTS;
if(dots != olddots) {
printf(".");
}
olddots = dots;
*/
return;
}
| [
"tetrisfrog@gmail.com"
] | tetrisfrog@gmail.com |
ed3e1b5f5d60202d89c5dc102334d30ce0d4d5e0 | f1ad9fd9a1b4e87c60a0dfbd5f6f14c936846a12 | /pros02-samples/train4.cpp | b594343b87b57a0b5dfe7a4e220a1842b8f05ff2 | [] | no_license | jencmart/bi-osy | 1c28efb96cca4be69377c85d4232316e2f983caf | 487cd0ac024bf6214e4fde3ff960fad9765ffcee | refs/heads/master | 2022-11-19T15:55:59.051615 | 2018-10-03T13:38:49 | 2018-10-03T13:38:49 | 281,677,595 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,344 | cpp | /* reseni s C++11 vlakny, mutexy a cond. var
*/
#include <cstdio>
#include <cstdlib>
#include <stdint.h>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <deque>
#include <algorithm>
#include <unistd.h>
using namespace std;
const int PLATFORM_MAX = 3;
class CTrain
{
public:
CTrain ( int id )
: m_ID ( id ),
m_Platform ( PLATFORM_MAX )
{
}
condition_variable m_Cond;
int m_ID;
int m_Platform;
};
// Do fronty cekajicich nechceme ukladat kopie CTrain, ale odkazy (reference) na
// existujici objekty. Obecne, neni dobry napad kopirovat objekty typu thread/mutex/cond_var.
// Kompilator se tomu brani, prislusne copy konstruktory jsou deleted.
// Bud muzeme ukladat ukazatele, nebo reference v podobe reference-wrapperu
deque<reference_wrapper<CTrain> > g_Waiting;
mutex g_Switch; /* vyhybka - zamek pro kritickou sekci vyberu koleje */
int g_Platform[PLATFORM_MAX]; /* priznaky obsazeni koleji */
//-------------------------------------------------------------------------------------------------
/* Vypis cekajicich vlaku + obsazeni koleji.
*/
void displayStation ( void )
{
// display in reverse order
for ( auto it = g_Waiting . rbegin (); it != g_Waiting . rend (); ++it )
printf ( " %2d ", it -> get () . m_ID );
printf ( "-> [" );
for ( int i = 0 ; i < PLATFORM_MAX; i ++ )
if ( g_Platform[i] )
printf ( " %2d ", g_Platform[i] );
else
printf ( " -- " );
printf ( "]\n" );
}
/*---------------------------------------------------------------------------*/
/* Najde volnou kolej, vrati jeji cislo. Predpoklada, ze volajici vlakno
* vlastni zamek g_Switch.
*/
inline int findPlatform ( void )
{
return find ( g_Platform, g_Platform + PLATFORM_MAX, 0 ) - g_Platform;
}
/*---------------------------------------------------------------------------*/
/* Prijezd do nadrazi
*
*/
int waitStation ( int id )
{
unique_lock<mutex> m ( g_Switch );
printf ( "Train %d arriving\n", id );
int pl;
if ( g_Waiting . size ()
|| ( pl = findPlatform () ) == PLATFORM_MAX )
{
// Nadrazi je obsazeno. Vlak musi cekat.
CTrain myself ( id );
g_Waiting . push_back ( myself );
// Zobrazeni
displayStation ();
// uspani & odemceni zamku, pri probuzeni kontrolujeme, ze jsme opravdu prvni na rade.
// (Mohlo by se stat,
// A pro extra spatne planovani by se mohlo stat, ze druhy probuzeny cekajici vlak
// ziska cpu drive nez prvni.
myself . m_Cond . wait ( m, [&pl, id] (void)
{
return ( pl = findPlatform () ) != PLATFORM_MAX
&& g_Waiting . front () . get () . m_ID == id; // tedy pokud nejsme prvni na rade nebo neni volno, zase se uspavame
} );
// mame jistotu, ze odstranujeme sebe z fronty cekajicich
g_Waiting . pop_front ();
// nepravdepodobne, ale mozne. Pokud by se podarilo probudit najednou dva cekajici vlaky
// a druhy ve fronte by se dostal k CPU drive nez prvni, pak se opet uspal (podminka u cond_wait)
// v takovem pripade by jej ale jiz nikdo neprobudil. Tedy z vlakna vlaku, ktery vjizdi na nadrazi
// jeste probudime pripadny dalsi vlak za nami ve fronte. Pokud dalsi vlak najde volnou kolej, obsadi ji
// (a pripadne probouzi i dalsi, ...)
if ( g_Waiting . size () )
g_Waiting . front () . get () . m_Cond . notify_one ();
}
// stale vlastnime mutex, tedy bezpecne obsazujeme kolej
g_Platform[pl] = id;
displayStation ();
printf ( "Train %d loading/unloading, platform %d\n", id, pl);
return pl;
}
/*---------------------------------------------------------------------------*/
void leaveStation ( int platform )
{
// Odjezd z nadrazi
unique_lock<mutex> m ( g_Switch );
printf ( "Train %d departed, platform %d now empty\n", g_Platform[platform], platform );
// Uvolnime kolej
g_Platform[platform] = 0;
displayStation ();
if ( g_Waiting . size () > 0 ) // Pokud nejaky vlak ceka, probudime jej.
g_Waiting . front () . get () . m_Cond . notify_one ();
}
/*---------------------------------------------------------------------------*/
/* Nahodne cislo od min do max.
*/
int randomRange ( int min, int max )
{
return (int)( min + 1.0 * rand () / RAND_MAX * ( max - min ));
}
/*---------------------------------------------------------------------------*/
/* Funkce vlakna - simulator vlaku.
* Vlakno dostane parametrem svuj identifikator - cislo od 1 do poctu vlaku
*/
void train ( int id )
{
while ( 1 )
{
int platform = waitStation ( (int) id );
// Nakladka/vykladka
usleep ( 1000 * randomRange ( 1000, 5000 ) );
leaveStation ( platform );
// Jizda vlaku
usleep ( 1000 * randomRange ( 2000, 10000 ) );
}
}
/*---------------------------------------------------------------------------*/
int main ( int argc, char * argv [] )
{
int thr;
vector<thread> trains;
if ( argc != 2
|| sscanf ( argv[1], "%d", &thr ) != 1 )
{
printf ( "usage: %s <thr>\n", argv[0] );
return 1;
}
for ( int i = 0; i < thr; i ++ )
trains . push_back ( thread ( train, i + 1 ) );
for ( auto & t : trains )
t . join ();
return 0;
}
| [
"martin.jenc@gmail.com"
] | martin.jenc@gmail.com |
823535febf981a69809859ec06a4e6a5d22c182d | 883887c3c84bd3ac4a11ac76414129137a1b643b | /Voip/VoipManServer/src/PipeProtocol/GetDevicesResultOut.cpp | 58c7033d8758e0a983f3de12ce3dd14b6e72bb45 | [] | no_license | 15831944/vAcademia | 4dbb36d9d772041e2716506602a602d516e77c1f | 447f9a93defb493ab3b6f6c83cbceb623a770c5c | refs/heads/master | 2022-03-01T05:28:24.639195 | 2016-08-18T12:32:22 | 2016-08-18T12:32:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,429 | cpp | #include "stdafx.h"
#include "include/PipeProtocol/GetDevicesResultOut.h"
CGetDevicesResultOut::CGetDevicesResultOut(byte aID, vecDeviceInfo *pInputDevicesInfo, vecDeviceInfo *pOutputDevicesInfo, byte abtNeedAnswerToRmml) : CCommonPipePacketOut( aID)
{
int size = (int)pInputDevicesInfo->size();
data->Add( size);
vecDeviceInfoIt it= pInputDevicesInfo->begin();
vecDeviceInfoIt end = pInputDevicesInfo->end();
for (; it!=end; ++it)
{
data->Add( it->nDeviceID);
byte nSoundSystem = (byte)it->nSoundSystem;
data->Add( nSoundSystem);
//data->Add( it->nSoundSystem);
std::wstring str = it->szDeviceName;
data->Add( str);
byte btSupports3D = (byte)it->bSupports3D;
data->Add( btSupports3D);
data->Add( it->nMaxInputChannels);
data->Add( it->nMaxOutputChannels);
std::wstring guid = it->sGUID;
data->Add( guid);
}
size = (int)pOutputDevicesInfo->size();
data->Add( size);
it= pOutputDevicesInfo->begin();
end = pOutputDevicesInfo->end();
for (; it!=end; ++it)
{
data->Add( it->nDeviceID);
byte nSoundSystem = (byte)it->nSoundSystem;
data->Add( nSoundSystem);
//data->Add( it->nSoundSystem);
std::wstring str = it->szDeviceName;
data->Add( str);
byte btSupports3D = (byte)it->bSupports3D;
data->Add( btSupports3D);
data->Add( it->nMaxInputChannels);
data->Add( it->nMaxOutputChannels);
std::wstring guid = it->sGUID;
data->Add( guid);
}
data->Add( abtNeedAnswerToRmml);
} | [
"ooo.vspaces@gmail.com"
] | ooo.vspaces@gmail.com |
884cf2d13823af1e35d06196c26de3b6b261bae7 | ba68c2eaefa2e30dbd145f898eaf98e314f492af | /src/Records/ANIO.cpp | ef0ca0f82bdf377fc6872cd268d89867e792ec1a | [
"Apache-2.0"
] | permissive | AWildErin/ESx-Reader | 2aae30386c66441e2124657d40adaf663ebd535e | fa7887c934141f7b0a956417392f2b618165cc34 | refs/heads/master | 2023-03-16T22:53:44.060605 | 2015-07-16T11:16:57 | 2015-07-16T11:16:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 438 | cpp | /*
* File: ANIO.cpp
* Author: Koncord <koncord at rwa.su>
*
* Created on 8 Апрель 2015 г., 22:23
*/
#include "ANIO.hpp"
using namespace std;
bool RecordANIO::DoParse()
{
const string subType = GetLabel();
if(subType == "EDID")
data.edid = GetString();
else if(subType == "DATA")
data.animation = GetData<formid>();
else if(ModelCollection()) {}
else return false;
return true;
}
| [
"koncord@rwa.su"
] | koncord@rwa.su |
0ebbbeec9c5651a67da0f030253b4fe5be8c9886 | 207bf930dda60c2c100fb5bc92a141f85e70b96e | /SAGE1.1Src/Demo 05/SAGE/Source/Common/AABB3.h | 8ea78acd5b09c7d36f921d8cd6878f5b050b2f67 | [] | no_license | dumppool/nvvg | 9a8ffd72b4cab086215ec38f6494cd234b5f7796 | 1a4f8d3bd03daedea8e07ea498d54066827104b3 | refs/heads/master | 2020-09-14T17:03:22.426495 | 2011-05-03T20:13:10 | 2011-05-03T20:13:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,657 | h | /// \file AABB3.h
/////////////////////////////////////////////////////////////////////////////
///
/// 3D Math Primer for Games and Graphics Development
///
/// AABB3.h - Declarations for class AABB3
///
/// Visit gamemath.com for the latest version of this file.
///
/// For more details, see AABB3.cpp
///
/////////////////////////////////////////////////////////////////////////////
#ifndef __AABB3_H_INCLUDED__
#define __AABB3_H_INCLUDED__
#ifndef __VECTOR3_H_INCLUDED__
#include "Vector3.h"
#endif
class Matrix4x3;
/// \brief Implements a 3D axially-aligned bounding box.
class AABB3 {
public:
// Public data
Vector3 min; ///< Specifies the minimum corner of the box.
Vector3 max; ///< Specifies the maximum corner of the box.
/// \brief Queries the box for its size along each dimension.
/// \return A vector containing the size of the box.
Vector3 size() const { return max - min; }
/// \brief Queries the box for its width (its size in the x-dimension).
/// \return The width of the box.
float xSize() { return max.x - min.x; }
/// \brief Queries the box for its height (its size in the y-dimension).
/// \return The height of the box.
float ySize() { return max.y - min.y; }
/// \brief Queries the box for its depth (its size in the z-dimension).
/// \return The depth of the box.
float zSize() { return max.z - min.z; }
/// \brief Queries the box for its center point
/// \return A vector indicating the center of the box.
Vector3 center() const { return (min + max) * .5f; }
/// \brief Queries the box for one of its corner points.
Vector3 corner(int i) const;
// Box operations
/// \brief Sets the box to empty.
void empty();
/// \brief Adds a point to the box, expanding the box if necessary.
void add(const Vector3 &p);
/// \brief Adds an AABB to the box, expanding the box if necessary.
void add(const AABB3 &box);
/// \brief Transforms the box and computes a new AABB.
void setToTransformedBox(const AABB3 &box, const Matrix4x3 &m);
// Containment/intersection tests
/// \brief Queries the box to see if it is empty.
bool isEmpty() const;
/// \brief Performs an AABB-point intersect test on this box.
bool contains(const Vector3 &p) const;
/// \brief Performs a closest-point test on this box.
Vector3 closestPointTo(const Vector3 &p) const;
/// \brief Performs an AABB-sphere intersect test on this box.
bool intersectsSphere(const Vector3 ¢er, float radius) const;
// Parametric intersection with a ray. Returns >1 if no intresection
/// \brief Performs a parametric AABB-ray intersection test on this box.
float rayIntersect(const Vector3 &rayOrg, const Vector3 &rayDelta,
Vector3 *returnNormal = 0) const;
/// \brief Classifies a box as being on one side or the other of a plane
int classifyPlane(const Vector3 &n, float d) const;
/// \brief Performs a dynamic AABB-plane intersection test.
float intersectPlane(const Vector3 &n, float planeD,
const Vector3 &dir) const;
/// \brief Performs an AABB-AABB intersection test.
static bool intersect(const AABB3 &box1, const AABB3 &box2,
AABB3 *boxIntersect = 0);
/// \brief Performs a dynamic AABB-AABB intersection test with one moving box.
static float intersectMoving(
const AABB3 &stationaryBox,
const AABB3 &movingBox,
const Vector3 &d);
/// \brief Performs a dynamic AABB-AABB intersection test with two moving boxes.
static float intersectMoving(
const AABB3 &box1,
const AABB3 &box2,
const Vector3 &d1,
const Vector3 &d2
);
};
/////////////////////////////////////////////////////////////////////////////
#endif // #ifndef __AABB3_H_INCLUDED__
| [
"c.a.russell@ou.edu"
] | c.a.russell@ou.edu |
0d4f69b10e51c2e815339d08a815cf570beb2f7a | 356a3ced7502c34b510bcd786f565bdf2a4c9492 | /ACM-ICPC/分块 cf 86d.cpp | 04e5f90e64b8de1dde306224728d9bb6c7edea63 | [] | no_license | philokey/Algorithm-Problems | bb1872b50a0d9ef4bc27fd40e5775ffb872eb858 | 774d515661647748372a1a1b6850063e04d37c03 | refs/heads/master | 2020-12-24T14:09:50.828232 | 2015-06-30T13:29:54 | 2015-06-30T13:29:54 | 38,310,200 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,512 | cpp | #include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <iostream>
#include <queue>
#define FI first
#define SE second
using namespace std;
typedef long long LL;
const double EPS = 1e-8;
const int MAXN = 1000005;
const int MAXM = 200005;
const int INF = 1111111111;
int cnt[MAXN],a[MAXM];
LL ans[MAXM];
struct Node{
int x,y,l,id;
bool operator <(const Node&a)const
{
return l<a.l||(l==a.l&&y<a.y);
}
}node[MAXM];
inline LL g(int i)
{
return (LL)((cnt[a[i]]<<1)+1)*a[i];
}
inline LL f(int i)
{
return (LL)(1-(cnt[a[i]]<<1))*a[i];
}
int px,py;
LL ret = 0;
int query(int x,int y,int p)
{
if(!p)
{
for(int i = x; i <= y; i++)
{
ret+=g(i);
cnt[a[i]]++;
}
}
else
{
for(int i = x; i < px; i++)
{
ret+=g(i);
cnt[a[i]]++;
}
for(int i = px; i < x; i++)
{
ret+=f(i);
cnt[a[i]]--;
}
for(int i = y+1; i <= py; i++)
{
ret+=f(i);
cnt[a[i]]--;
}
for(int i = py+1; i<=y; i++)
{
ret+=g(i);
cnt[a[i]]++;
}
}
px = x, py = y;
return ret;
}
int main()
{
//freopen("/home/qitaishui/code/in.txt","r",stdin);
int n,block,q;
int u,v;
scanf("%d%d",&n,&q);
for(int i = 1; i <= n; i++)
scanf("%d",&a[i]);
block = sqrt(n*1.0);
for(int i = 0; i < q; i++)
{
scanf("%d%d",&node[i].x,&node[i].y);
node[i].l = node[i].x/block;
node[i].id = i;
}
sort(node,node+q);
for(int i = 0; i < q; i++)
{
query(node[i].x,node[i].y,i);
ans[node[i].id] = ret;
}
for(int i = 0; i < q; i++)
printf("%lld\n",ans[i]);
return 0;
}
| [
"philokeys@gmail.com"
] | philokeys@gmail.com |
ba357ba051695a74c3597c71bc7f3c166d7c092b | babd1209c5738c5f0aebd6f04642b5f88b3a0990 | /src/editorbackend/ArchiveCreator.cpp | 6a1ede4ececd1dde0899094d3594218fb4547159 | [
"BSD-2-Clause"
] | permissive | LauriM/PropellerEngine | ec2ef2f65f27c1da01fc71e17339f59b73d1faee | d4063715bf57760318413e493c907ed342d70b0a | refs/heads/master | 2021-01-22T13:31:18.450580 | 2017-04-03T19:12:12 | 2017-04-03T19:12:12 | 49,952,388 | 15 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 2,920 | cpp | // Copyright (c) Lauri Mäkinen 2014 - 2015
// All rights reserved.
#include "editorbackend/precompiled.h"
#include "editorbackend/ArchiveCreator.h"
#include "editorbackend/CSharp/CSharpInstanceManager.h"
#include "engine/sys/FileSystem.h"
#include "engine/file/PropellerPackageVersion.h"
namespace editor {
REGISTER_CSHARPINSTANCE(ArchiveCreator);
bool ArchiveCreator::init()
{
registerEvent("addFolder", this, &ArchiveCreator::addFolderToArchive);
registerEvent("addFile", this, &ArchiveCreator::addFileToArchive);
registerEvent("build", this, &ArchiveCreator::buildArchive);
registerEvent("clear", this, &ArchiveCreator::clear);
return true;
}
void ArchiveCreator::addFolderToArchive(const String folder)
{
std::vector<String> files;
engine::sys::listFilesInDirectory(files, folder);
DEBUG_PRINT("files: " << files.size());
for (unsigned i = 0; i < files.size(); ++i)
addFileToArchive(files[i]);
}
void ArchiveCreator::addFileToArchive(const String file)
{
if (file == ".")
return;
if (file == "..")
return;
files.push_back(file);
DEBUG_PRINT("Adding " << file);
}
void ArchiveCreator::buildArchive(const String filename)
{
LOG_INFO("Building archive...");
engine::stream::BufferedOutputStream<engine::stream::SerializationEndian> header;
engine::stream::BufferedOutputStream<engine::stream::SerializationEndian> data;
// .pp header
header.write(PROPELLER_PACKAGE_IDENTIFIER, PROPELLER_PACKAGE_IDENTIFIER_SIZE);
header.write(unsigned(PROPELLER_PACKAGE_VERSION_ID));
header.write(files.size());
unsigned bufferSize = 15000;
char *buffer = (char*)malloc(bufferSize);
for (unsigned i = 0; i < files.size(); ++i)
{
FILE *file = NULL;
engine::sys::fileOpen(&file, "../data/" + files[i], "rb");
if (file == NULL)
{
LOG_WARNING("Could not open file: " << files[i]);
continue;
}
unsigned offset = data.getIndex();
fseek(file, 0L, SEEK_END);
unsigned size = ftell(file);
fseek(file, 0L, SEEK_SET);
header.write(files[i]); //filename
header.write(offset); //offset from data section start (first is 0)
header.write(size); //size
if (size > bufferSize)
{
bufferSize = size;
buffer = (char*)realloc(buffer, bufferSize);
DEBUG_PRINT("Resizing buffer to " << bufferSize);
}
fread_s(buffer, bufferSize, size, 1, file);
data.write(buffer, size);
LOG_INFO("file " << files[i] << " written offset: " << offset << " size: " << size);
DEBUG_PRINT("file " << files[i] << " written offset: " << offset << " size: " << size);
}
free(buffer);
std::ofstream output;
output.open(filename.c_str(), std::ios::binary);
output.write((char*)header.getData(), header.getIndex());
output.write((char*)data.getData(), data.getIndex());
output.close();
LOG_INFO("Archive build done: " << filename);
}
void ArchiveCreator::clear()
{
files.clear();
}
} | [
"lauri.sakari.makinen@gmail.com"
] | lauri.sakari.makinen@gmail.com |
4dc38d4addc84270a6c5d8a6cdcf0b99c6a1f9db | 06eb60c98f4d106fc3bb3d0b7e990828b87d714d | /Source/WebCore/platform/ColorChooserClient.h | 365c2396b65d6372543f979d6d3cbf723ad71b29 | [] | no_license | snyh/dui | 9486a81d97ec1173b161b6aef8fcea21066aebff | c4464629f1efdecae792ed3abc2a7fc9ce9b88db | refs/heads/master | 2021-01-25T08:28:55.224303 | 2013-10-23T00:42:02 | 2013-10-23T00:42:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,312 | h | /*
* Copyright (C) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 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 Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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.
*
*/
#ifndef ColorChooserClient_h
#define ColorChooserClient_h
#if ENABLE(INPUT_TYPE_COLOR)
#include "platform/ColorChooser.h"
#include "platform/graphics/IntRect.h"
#include <wtf/OwnPtr.h>
#include <wtf/PassOwnPtr.h>
#include <wtf/Vector.h>
namespace WebCore {
class Color;
class ColorChooserClient {
public:
virtual ~ColorChooserClient() { }
virtual void didChooseColor(const Color&) = 0;
virtual void didEndChooser() = 0;
virtual IntRect elementRectRelativeToRootView() const = 0;
virtual Color currentColor() = 0;
virtual bool shouldShowSuggestions() const = 0;
virtual Vector<Color> suggestions() const = 0;
};
} // namespace WebCore
#endif // ENABLE(INPUT_TYPE_COLOR)
#endif // ColorChooserClient_h
| [
"snyh@snyh.org"
] | snyh@snyh.org |
2351851f001b840b59db6278588cdbd2912e6457 | 73df58bb1c256e35465787c24135f85156694532 | /Engine/Source/Editor/UMGEditor/Private/TabFactory/PaletteTabSummoner.cpp | 61d3316f8cbb2603ef0d9e5d8428b471dfc18fcd | [] | no_license | igchesnok/AHRUnrealEngine | 9c003bf9988d58ece42be4af030ec6ec092cd12e | d300f83087a2d790f5bd9571dad441c67b2776b6 | refs/heads/master | 2021-01-18T17:49:35.497706 | 2014-10-09T22:32:35 | 2014-10-09T22:32:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,147 | cpp | // Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.
#include "UMGEditorPrivatePCH.h"
#include "PaletteTabSummoner.h"
#include "SPaletteView.h"
#include "UMGStyle.h"
#define LOCTEXT_NAMESPACE "UMG"
const FName FPaletteTabSummoner::TabID(TEXT("WidgetTemplates"));
FPaletteTabSummoner::FPaletteTabSummoner(TSharedPtr<class FWidgetBlueprintEditor> InBlueprintEditor)
: FWorkflowTabFactory(TabID, InBlueprintEditor)
, BlueprintEditor(InBlueprintEditor)
{
TabLabel = LOCTEXT("WidgetTemplatesTabLabel", "Palette");
TabIcon = FSlateIcon(FUMGStyle::GetStyleSetName(), "Palette.TabIcon");
bIsSingleton = true;
ViewMenuDescription = LOCTEXT("WidgetTemplates_ViewMenu_Desc", "Palette");
ViewMenuTooltip = LOCTEXT("WidgetTemplates_ViewMenu_ToolTip", "Show the Palette");
}
TSharedRef<SWidget> FPaletteTabSummoner::CreateTabBody(const FWorkflowTabSpawnInfo& Info) const
{
TSharedPtr<FWidgetBlueprintEditor> BlueprintEditorPtr = StaticCastSharedPtr<FWidgetBlueprintEditor>(BlueprintEditor.Pin());
return SNew(SPaletteView, BlueprintEditorPtr)
.AddMetaData<FTagMetaData>(FTagMetaData(TEXT("Palette")));
}
#undef LOCTEXT_NAMESPACE
| [
"unrealbot@users.noreply.github.com"
] | unrealbot@users.noreply.github.com |
57fa050a27e2035534d90287e9168a281f88f467 | 7a23875e9ef14d1a5b8c312636e83d711b0f23c3 | /C++/160. Intersection of Two Linked Lists/Intersection of Two Linked Lists.cpp | 773309cfeb414c08c10e8b1ff1be16e6c16d642a | [] | no_license | hanzhengbo/LeetCode | 0fd9a1275acc37fffa5470ee9019bc69d1c6d552 | 414d090ffa898516f9db2d39c90da8fc27e197f7 | refs/heads/master | 2020-03-07T09:41:23.860938 | 2018-05-17T15:19:03 | 2018-05-17T15:19:03 | 127,413,833 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 457 | cpp | //
// Created by 韩正博 on 18/4/26.
//
#include "../header.h"
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
set<ListNode*> setA;
while(headA){
setA.insert(headA);
headA = headA->next;
}
while(headB){
if(setA.find(headB)!=setA.end())
return headB;
headB = headB->next;
}
return NULL;
}
}; | [
"806850270@qq.com"
] | 806850270@qq.com |
ed9dcaaab51a203ee8beaa4d1adcdcdb4b2bff6c | f8180890efe64612a803646d12ac4920ad18ba1e | /实验5/Dijkstra.cpp | 3bef5d4554638e36b48b29143d47b04a1c832250 | [] | no_license | weiyuexin/DataStructure | 5e67010c699284b5154143b82ba48bb9dc1515ce | 07322be376a5a626ab8b4d4e2c6e8b47fe1a51ad | refs/heads/master | 2023-02-04T16:11:54.366419 | 2020-12-21T12:55:52 | 2020-12-21T12:55:52 | 323,334,841 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,451 | cpp | #include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
int map[110][110];//这就是map数组,存储图
int dis[10010];//dis数组,存储估计值
int book[10010];//book[i]代表这个点有没有被当做源点去搜索过,1为有,0为没有。这样就不会重复搜索了。
int n,m;
void dijkstra(int u)//主函数,参数是源点编号
{
memset(dis,88,sizeof(dis));//把dis数组附最大值
int start=u;//先从源点搜索
book[start]=1;//标记源点已经搜索过
for(int i=1;i<=n;i++)
{
dis[i]=min(dis[i],map[start][i]);//先更新一遍
}
for(int i=1;i<=n-1;i++)
{
int minn=9999999;
if(book[i]==0 && minn>dis[i])
{
minn=dis[i];
start=i;//找到离源点最近的点,然后把编号记录下来,用于搜索。
}
book[start]=1;
for(int j=1;j<=n;j++)
dis[j]=min(dis[j],dis[start]+map[start][j]);//以新的点来更新dis。
}
}
int main()
{
cin>>n>>m;
memset(map,88,sizeof(map));
for(int i=1;i<=m;i++)
{
int a,b,c;
cin>>a>>b>>c;
map[a][b]=c;
}
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
if(i==j)
map[i][j]=0;
dijkstra(1);//以1为源点。
for(int i=1;i<=n;i++)
cout<<dis[i]<<" ";
}
| [
"3022422894@qq.com"
] | 3022422894@qq.com |
eedf1181e4ff903f69559e3a5cc7047d928977db | 7cb4c865b3e6bab5c80828399e62f9dc3c990c8e | /pa1/testchain.cpp | 2a919c50947354a58ed73408b8891f28f4a01b24 | [] | no_license | jkwok2/cpsc221-pa | 264f040bfa57e3ea0543caa9157dcb3a406ca95f | 3aaddc9a360c84f4b08a80a0b2d7e109c3d8b561 | refs/heads/master | 2022-08-31T10:24:00.697903 | 2020-05-27T02:54:36 | 2020-05-27T02:54:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,282 | cpp | #define CATCH_CONFIG_MAIN
#include "cs221util/catch.hpp"
// headers from PA's main.cpp
#include "chain.h"
#include "block.h"
#include "cs221util/PNG.h"
using namespace cs221util;
using namespace std;
// chain copy constructor
TEST_CASE("chain::basic copy constructor", "[weight=1][part=chain]")
{
PNG pngin;
pngin.readFromFile("images/rosegarden.png");
Chain c(pngin, 18);
Chain d(c);
PNG result = d.render(18);
REQUIRE(result == pngin);
}
// chain copy constructor reverse
TEST_CASE("chain::basic copy constructor reverse", "[weight=1][part=chain]")
{
PNG pngin;
pngin.readFromFile("images/rosegarden.png");
Chain c(pngin, 18);
Chain d(c);
PNG result = d.renderBack(18);
REQUIRE(result == pngin);
}
TEST_CASE("chain::basic even mirror", "[weight=1][part=chain]")
{
PNG img(2, 1);
img.getPixel(0, 0)->h = 1;
img.getPixel(1, 0)->h = 2;
int cols = 2;
Chain c(img, cols);
c.mirror();
PNG res = c.render(cols);
HSLAPixel *p0 = res.getPixel(0, 0);
HSLAPixel *p1 = res.getPixel(1, 0);
REQUIRE(p0->h == 2);
REQUIRE(p1->h == 1);
}
TEST_CASE("chain::basic odd mirror", "[weight=1][part=chain]")
{
int cols = 3;
PNG img(cols, cols);
for (int x = 0; x < cols; x++)
{
for (int y = 0; y < cols; y++)
{
img.getPixel(x, y)->h = x;
}
}
Chain c(img, cols);
c.mirror();
PNG res = c.render(cols);
HSLAPixel *p0 = res.getPixel(0, 0);
HSLAPixel *p1 = res.getPixel(0, 1);
HSLAPixel *p2 = res.getPixel(0, 2);
REQUIRE(p0->h == 2);
REQUIRE(p1->h == 2);
REQUIRE(p2->h == 2);
p0 = res.getPixel(1, 0);
p1 = res.getPixel(1, 1);
p2 = res.getPixel(1, 2);
REQUIRE(p0->h == 1);
REQUIRE(p1->h == 1);
REQUIRE(p2->h == 1);
p0 = res.getPixel(2, 0);
p1 = res.getPixel(2, 1);
p2 = res.getPixel(2, 2);
REQUIRE(p0->h == 0);
REQUIRE(p1->h == 0);
REQUIRE(p2->h == 0);
}
TEST_CASE("chain::large odd mirror", "[weight=1][part=chain]")
{
int cols = 9;
PNG img(cols, cols);
for (int x = 0; x < cols; x++)
{
for (int y = 0; y < cols; y++)
{
img.getPixel(x, y)->h = x;
}
}
Chain c(img, cols);
c.mirror();
PNG res = c.render(cols);
for (int x = 0; x < cols; x++)
{
for (int y = 0; y < cols; y++)
{
int hVal = cols - 1 - x;
HSLAPixel *pr = res.getPixel(x, y);
REQUIRE(pr->h == hVal);
}
}
}
TEST_CASE("chain::basic rotate k = 0", "[weight=1][part=chain]")
{
int cols = 2;
PNG img(cols, 1);
img.getPixel(0, 0)->h = 1;
img.getPixel(1, 0)->h = 2;
Chain c(img, cols);
c.rotate(0);
PNG res = c.render(cols);
HSLAPixel *p0 = res.getPixel(0, 0);
HSLAPixel *p1 = res.getPixel(1, 0);
REQUIRE(p0->h == 1);
REQUIRE(p1->h == 2);
}
TEST_CASE("chain::basic rotate k = 1", "[weight=1][part=chain]")
{
int cols = 2;
PNG img(cols, 1);
img.getPixel(0, 0)->h = 1;
img.getPixel(1, 0)->h = 2;
Chain c(img, cols);
c.rotate(1);
PNG res = c.render(cols);
HSLAPixel *p0 = res.getPixel(0, 0);
HSLAPixel *p1 = res.getPixel(1, 0);
REQUIRE(p0->h == 2);
REQUIRE(p1->h == 1);
}
TEST_CASE("chain::long rotate k = 1", "[weight=1][part=chain]")
{
int cols = 5;
PNG img(cols, 1);
img.getPixel(0, 0)->h = 0;
img.getPixel(1, 0)->h = 1;
img.getPixel(2, 0)->h = 2;
img.getPixel(3, 0)->h = 3;
img.getPixel(4, 0)->h = 4;
Chain c(img, cols);
c.rotate(1);
PNG res = c.render(cols);
HSLAPixel *p0 = res.getPixel(0, 0);
HSLAPixel *p1 = res.getPixel(1, 0);
HSLAPixel *p2 = res.getPixel(2, 0);
HSLAPixel *p3 = res.getPixel(3, 0);
HSLAPixel *p4 = res.getPixel(4, 0);
REQUIRE(p0->h == 1);
REQUIRE(p1->h == 2);
REQUIRE(p2->h == 3);
REQUIRE(p3->h == 4);
REQUIRE(p4->h == 0);
}
TEST_CASE("chain::basic rotate k = 2", "[weight=1][part=chain]")
{
int cols = 5;
PNG img(cols, 1);
img.getPixel(0, 0)->h = 0;
img.getPixel(1, 0)->h = 1;
img.getPixel(2, 0)->h = 2;
img.getPixel(3, 0)->h = 3;
img.getPixel(4, 0)->h = 4;
Chain c(img, cols);
c.rotate(2);
PNG res = c.render(cols);
HSLAPixel *p0 = res.getPixel(0, 0);
HSLAPixel *p1 = res.getPixel(1, 0);
HSLAPixel *p2 = res.getPixel(2, 0);
HSLAPixel *p3 = res.getPixel(3, 0);
HSLAPixel *p4 = res.getPixel(4, 0);
REQUIRE(p0->h == 2);
REQUIRE(p1->h == 1);
REQUIRE(p2->h == 4);
REQUIRE(p3->h == 3);
REQUIRE(p4->h == 0);
}
TEST_CASE("chain::wrapping rotate k = 3", "[weight=1][part=chain]")
{
int cols = 5;
PNG img(cols, 1);
img.getPixel(0, 0)->h = 0;
img.getPixel(1, 0)->h = 1;
img.getPixel(2, 0)->h = 2;
img.getPixel(3, 0)->h = 3;
img.getPixel(4, 0)->h = 4;
Chain c(img, cols);
c.rotate(3);
PNG res = c.render(cols);
HSLAPixel *p0 = res.getPixel(0, 0);
HSLAPixel *p1 = res.getPixel(1, 0);
HSLAPixel *p2 = res.getPixel(2, 0);
HSLAPixel *p3 = res.getPixel(3, 0);
HSLAPixel *p4 = res.getPixel(4, 0);
REQUIRE(p0->h == 3);
REQUIRE(p1->h == 4);
REQUIRE(p2->h == 2);
REQUIRE(p3->h == 1);
REQUIRE(p4->h == 0);
}
| [
"hall.jerry9@gmail.com"
] | hall.jerry9@gmail.com |
c83f7fc6b2ee64c0cad1c0816f897629af9438a9 | 711e5c8b643dd2a93fbcbada982d7ad489fb0169 | /XPSP1/NT/enduser/speech/tts/truetalk/backend/tips.cpp | 37b7851faa551e0efcb798fb9b6002b4f64ed7b1 | [] | no_license | aurantst/windows-XP-SP1 | 629a7763c082fd04d3b881e0d32a1cfbd523b5ce | d521b6360fcff4294ae6c5651c539f1b9a6cbb49 | refs/heads/master | 2023-03-21T01:08:39.870106 | 2020-09-28T08:10:11 | 2020-09-28T08:10:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,494 | cpp | /******************************************************************************
* tips.cpp *
*----------*
*
*------------------------------------------------------------------------------
* Copyright (c) 1996-1997 Entropic Research Laboratory, Inc.
* Copyright (C) 1998 Entropic, Inc
* Copyright (C) 2000 Microsoft Corporation Date: 03/02/00-12/4/00
* All Rights Reserved
*
********************************************************************* mplumpe was PACOG ***/
#include "tips.h"
#include "SynthUnit.h"
#include "sigproc.h"
#include <vapiIo.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <limits.h>
#include <assert.h>
#include "ftol.h"
const double CTips::m_iDefaultPeriod = .01; //10 msec.
const double CTips::m_dMinF0 = 15.0; // Absolute minimum F0 alowed
const int CTips::m_iHalfHanLen_c = 1024;
/*****************************************************************************
* CTips::CTips *
*--------------*
* Description:
*
******************************************************************* PACOG ***/
CTips::CTips (int iOptions)
{
m_fLptips = (bool) (iOptions & LpTips);
m_fRtips = (iOptions & RTips) != 0;
m_iSampFormat = 0;
m_iSampFreq = 0;
m_dGain = 1.0;
m_pfF0 = 0;
m_iNumF0 = 0;
m_dRunTime = 0.0;
m_dF0SampFreq = 0.0;
m_dF0TimeNext = 0.0;
m_dF0TimeStep = 0.0;
m_dF0Value = 0.0;
m_dAcumF0 = 0.0;
m_iF0Idx = 0;
m_dLastEpochTime = 0.0;
m_dNewEpochTime = 0.0;
m_aBuffer[0].m_pdSamples = 0;
m_aBuffer[1].m_pdSamples = 0;
m_iLpcOrder = 0;
m_pdFiltMem = 0;
m_pdInterpCoef = 0;
m_pdLastCoef = 0;
m_pUnit = 0;
m_psSynthSamples = 0;
m_iNumSynthSamples = 0;
m_adHalfHanning = 0;
}
/*****************************************************************************
* CTips::~CTips *
*---------------*
* Description:
*
******************************************************************* mplumpe ***/
CTips::~CTips ()
{
if (m_pdFiltMem)
{
delete[] m_pdFiltMem;
}
if (m_pdInterpCoef)
{
delete[] m_pdInterpCoef;
}
if (m_pdLastCoef)
{
delete[] m_pdLastCoef;
}
if (m_aBuffer[0].m_pdSamples)
{
delete[] m_aBuffer[0].m_pdSamples;
}
if (m_aBuffer[1].m_pdSamples)
{
delete[] m_aBuffer[1].m_pdSamples;
}
if (m_psSynthSamples)
{
delete[] m_psSynthSamples;
}
if (m_adHalfHanning)
{
delete [] m_adHalfHanning;
}
}
/*****************************************************************************
* CTips::Init *
*-------------*
* Description:
*
******************************************************************* mplumpe ***/
int CTips::Init (int iSampFormat, int iSampFreq)
{
int i;
assert (iSampFreq>0);
m_iSampFreq = iSampFreq;
m_iSampFormat = iSampFormat;
int iPeriodLen = (int) (iSampFreq * m_iDefaultPeriod);
// Delete old buffers, if they exist
if (m_aBuffer[0].m_pdSamples)
{
delete[] m_aBuffer[0].m_pdSamples;
}
if (m_aBuffer[1].m_pdSamples)
{
delete[] m_aBuffer[1].m_pdSamples;
}
// Allocate new ones, and initialize them to Zero.
// NOTE: Only need to allocate buffer[1], really, since they'll be rotated before
// synthesis.
if ((m_aBuffer[0].m_pdSamples = new double[2 * iPeriodLen]) == 0 )
{
return 0;
}
//memset(m_aBuffer[0].m_pdSamples, 0, sizeof(double) * 2 * iPeriodLen);
if ((m_aBuffer[1].m_pdSamples = new double [2 * iPeriodLen]) == 0)
{
return 0;
}
memset(m_aBuffer[1].m_pdSamples, 0, sizeof(double) * 2 * iPeriodLen);
m_aBuffer[0].m_iNumSamples = 2 * iPeriodLen;
m_aBuffer[0].m_iCenter = iPeriodLen;
m_aBuffer[0].m_dDelay = 0.0;
m_aBuffer[1].m_iNumSamples = 2 * iPeriodLen;
m_aBuffer[1].m_iCenter = iPeriodLen;
m_aBuffer[1].m_dDelay = 0.0;
//
// make Hanning buffer
//
if (m_adHalfHanning)
{
delete m_adHalfHanning;
}
if ((m_adHalfHanning = new double [m_iHalfHanLen_c]) == 0)
{
return 0;
}
for (i=0; i < m_iHalfHanLen_c; i++)
{
m_adHalfHanning[i] = 0.5-0.5*cos(M_PI*i/m_iHalfHanLen_c);
}
if (m_fLptips)
{
return LpcInit();
}
return 1;
}
/*****************************************************************************
* CTips::SetGain *
*----------------*
* Description:
*
******************************************************************* PACOG ***/
void CTips::SetGain (double dGain)
{
assert (dGain>=0.0);
m_dGain = dGain;
}
/*****************************************************************************
* CTips::GetGain *
*----------------*
* Description:
*
******************************************************************* PACOG ***/
double CTips::GetGain ()
{
return m_dGain;
}
/*****************************************************************************
* CTips::NewSentence *
*--------------------*
* Description:
*
******************************************************************* PACOG ***/
void CTips::NewSentence (float* pfF0, int iNumF0, int iF0SampFreq)
{
assert (pfF0);
assert (iNumF0>0);
assert (iF0SampFreq>0);
m_pfF0 = pfF0;
m_iNumF0 = iNumF0;
m_dF0SampFreq = iF0SampFreq;
m_dF0TimeStep = 1.0/iF0SampFreq;
m_dRunTime = 0.0;
m_dF0TimeNext = 0.0;
m_dAcumF0 = 0.0;
m_iF0Idx = 0;
m_dLastEpochTime = 0.0;
m_dNewEpochTime = 0.0;
}
/*****************************************************************************
* CTips::NewUnit *
*----------------*
* Description:
* Gets a new unit to synthesize, and does some analysis on it.
******************************************************************* PACOG ***/
int CTips::NewUnit (CSynth* pUnit)
{
if (pUnit)
{
m_pUnit = pUnit;
if (m_fLptips)
{
if (!m_pUnit->LpcAnalysis(m_iSampFreq, m_iLpcOrder))
{
return 0;
}
}
if ( Prosody (pUnit) == -1)
{
return 0;
}
return 1;
}
return 0;
}
/*****************************************************************************
* CTips::Prosody *
*----------------*
* Description:
* We get synthesis epochs track for a segment. F0 curve integration is
* therefore carried out here. The sampling frequency chosen is high enough
* as to reduce jitter to an umperceivable level, but that depends on the
* synthesis module being capable of synthesizing at that interval.
*
******************************************************************* PACOG ***/
int CTips::Prosody ( CSynth* pUnit )
{
double dF0IntegralTime = 0.0;
assert (m_pfF0 && m_iNumF0>0);
if (m_dNewEpochTime != m_dLastEpochTime)
{
if ((pUnit->m_pdSynEpochs = new double[2]) == 0)
{
return -1;
}
pUnit->m_pdSynEpochs[0] = m_dLastEpochTime;
pUnit->m_pdSynEpochs[1] = m_dNewEpochTime;
pUnit->m_iNumSynEpochs = 2;
}
else
{
if ((pUnit->m_pdSynEpochs = new double[1]) == 0)
{
return -1;
}
pUnit->m_pdSynEpochs[0] = m_dNewEpochTime;
pUnit->m_iNumSynEpochs = 1;
}
while ( m_dRunTime < pUnit->m_dRunTimeLimit ||
// Find an extra epoch, for the overlapping period
// if the last epoch doesn't already cross the segment limit
pUnit->m_pdSynEpochs[pUnit->m_iNumSynEpochs-1] < pUnit->m_dRunTimeLimit)
{
if (m_dRunTime >= m_dF0TimeNext)
{
m_dF0Value = m_pfF0[m_iF0Idx];
if (m_iF0Idx < m_iNumF0-1)
{
m_iF0Idx++;
}
if (m_dF0Value<=0.0)
{
m_dF0Value = 100.0; // Best choice is f0=100Hz
}
else if (m_dF0Value <= m_dMinF0)
{
m_dF0Value = m_dMinF0;
}
m_dF0TimeNext += m_dF0TimeStep;
}
dF0IntegralTime = (1.0 - m_dAcumF0) / m_dF0Value;
if (dF0IntegralTime >= m_dF0TimeStep)
{
m_dRunTime += m_dF0TimeStep;
m_dAcumF0 += m_dF0Value * m_dF0TimeStep;
}
else
{
m_dRunTime += dF0IntegralTime;
m_dAcumF0 = 0;
//Got epoch
m_dLastEpochTime = m_dNewEpochTime;
m_dNewEpochTime = m_dRunTime;
//Reallocate the synthesis epochs array
double* pdSynEpochs = new double[pUnit->m_iNumSynEpochs + 1];
if (!pdSynEpochs)
{
return -1;
}
memcpy(pdSynEpochs, pUnit->m_pdSynEpochs, pUnit->m_iNumSynEpochs * sizeof(double));
delete[] pUnit->m_pdSynEpochs;
pUnit->m_pdSynEpochs = pdSynEpochs;
// And add a new epoch
pUnit->m_pdSynEpochs[pUnit->m_iNumSynEpochs] = m_dNewEpochTime;
pUnit->m_iNumSynEpochs++;
}
}
if (pUnit->m_iNumSynEpochs <3)
{
delete[] pUnit->m_pdSynEpochs;
pUnit->m_pdSynEpochs = 0;
return 0;
}
// Synthesis epochs are in absolute synthesis time
double epStartTime = ((long)(pUnit->m_pdSynEpochs[0] * m_iSampFreq)) / (double)m_iSampFreq;
for (int i=0; i<pUnit->m_iNumSynEpochs; i++)
{
pUnit->m_pdSynEpochs[i] -= epStartTime;
}
return pUnit->FindPrecedent ();
}
/*****************************************************************************
* CTips::Pending *
*----------------*
* Description:
*
******************************************************************* PACOG ***/
int CTips::Pending ()
{
return m_pUnit != 0;
}
/*****************************************************************************
* CTips::NextPeriod *
*-------------------*
* Description:
*
******************************************************************* PACOG ***/
int CTips::NextPeriod (short** ppnSamples, int *piNumSamples)
{
int iPeriodLen;
assert (ppnSamples && piNumSamples> 0);
if (m_pUnit)
{
iPeriodLen = m_pUnit->NextBuffer (this);
if ( iPeriodLen > 0 )
{
Synthesize (iPeriodLen);
*ppnSamples = m_psSynthSamples;
*piNumSamples = iPeriodLen;
return 1;
}
else
{
delete m_pUnit;
m_pUnit = 0;
}
}
return 0;
}
/*****************************************************************************
* CTips::FillBuffer *
*-------------------*
* Description:
*
******************************************************************* PACOG ***/
int CTips::SetBuffer ( double* pdSamples, int iNumSamples, int iCenter, double dDelay, double* pdLpcCoef)
{
// Advance buffers
delete[] m_aBuffer[0].m_pdSamples;
m_aBuffer[0] = m_aBuffer[1];
m_aBuffer[1].m_pdSamples = pdSamples;
m_aBuffer[1].m_iNumSamples = iNumSamples;
m_aBuffer[1].m_iCenter = iCenter;
m_aBuffer[1].m_dDelay = dDelay;
m_pdNewCoef = pdLpcCoef;
return 1;
}
/*****************************************************************************
* CTips::Synthesize *
*-------------------*
* Description:
*
******************************************************************* PACOG ***/
int CTips::Synthesize (int iPeriodLen)
{
double* pdPeriodSamples = 0;
double* windowedLeft = 0;
int leftSize;
double* windowedRight = 0;
int rightSize;
double *p1, *p2;
int i;
assert (iPeriodLen);
if (m_fRtips)
{
NonIntegerDelay (m_aBuffer[1].m_pdSamples, m_aBuffer[1].m_iNumSamples, m_aBuffer[1].m_dDelay);
}
if (!GetWindowedSignal(0, iPeriodLen, &windowedLeft, &leftSize))
{
goto error;
}
if (!GetWindowedSignal(1, iPeriodLen, &windowedRight, &rightSize) )
{
goto error;
}
assert (windowedLeft && leftSize);
assert (windowedRight && rightSize);
if (!windowedLeft || !leftSize || !windowedRight || !rightSize )
{
goto error;
}
if ((pdPeriodSamples = new double[iPeriodLen]) == 0)
{
goto error;
}
p1=windowedLeft;
p2=windowedRight;
for (i=0; i<iPeriodLen - rightSize && i<leftSize; i++)
{
pdPeriodSamples[i] = *p1++;
}
// If windows overlap, they are added
for ( ;i<leftSize; i++)
{
pdPeriodSamples[i] = *p1++ + *p2++;
}
// Else, we fill the space with zeros
for (; i<iPeriodLen - rightSize; i++)
{
pdPeriodSamples[i] = 0.0;
}
for (;i<iPeriodLen;i++)
{
pdPeriodSamples[i] = *p2++;
}
delete[] windowedLeft;
delete[] windowedRight;
if (m_fLptips)
{
LpcSynth (pdPeriodSamples, iPeriodLen);
}
// reuse the same buffer if possible
if ( m_iNumSynthSamples < iPeriodLen )
{
if (m_psSynthSamples)
{
delete[] m_psSynthSamples;
}
if ((m_psSynthSamples = new short[iPeriodLen]) == 0)
{
goto error;
}
m_iNumSynthSamples = iPeriodLen;
}
for (i=0; i<iPeriodLen; i++)
{
m_psSynthSamples[i] = ClipData(pdPeriodSamples[i]);
}
delete[] pdPeriodSamples;
return 1;
error:
if (pdPeriodSamples)
{
delete[] pdPeriodSamples;
}
if (windowedLeft)
{
delete[] windowedLeft;
}
if (windowedRight)
{
delete[] windowedRight;
}
return 0;
}
/*****************************************************************************
* CTips::GetWindowedSignal *
*----------------------------*
* Description:
*
******************************************************************* PACOG ***/
int CTips::GetWindowedSignal (int whichBuffer, int iPeriodLen,
double** windowed, int* nWindowed)
{
double* sampPtr;
int nSamples;
int from;
if (whichBuffer==0)
{
sampPtr = m_aBuffer[0].m_pdSamples + m_aBuffer[0].m_iCenter;
nSamples = __min(iPeriodLen, (m_aBuffer[0].m_iNumSamples - m_aBuffer[0].m_iCenter));
}
else
{
from = __max(0, m_aBuffer[1].m_iCenter - iPeriodLen);
sampPtr = m_aBuffer[1].m_pdSamples + from;
nSamples = m_aBuffer[1].m_iCenter - from;
}
if (nSamples)
{
if ((*windowed = new double[nSamples]) == 0)
{
return 0;
}
*nWindowed = nSamples;
memcpy (*windowed, sampPtr, nSamples * sizeof(**windowed));
if (whichBuffer==0)
{
HalfHanning (*windowed, nSamples, 1.0, WindowSecondHalf);
}
else
{
HalfHanning (*windowed, nSamples, 1.0, WindowFirstHalf);
}
return 1;
}
else
{
fprintf (stderr, "NULL vector in GetWindowedSignal\n");
}
return 0;
}
/*****************************************************************************
* CTips::HalfHanning *
*--------------------*
* Description:
* 12/4/00 - Since ampl wasn't being used, I'm now asserting it equal
* to 1 and ignoring it. Also, a large hanning window is
* pre-computed and interpolated here, instead of being
* calculated here.
*
******************************************************************* mplumpe ***/
void CTips::HalfHanning (double* x, int xLen, double ampl, int whichHalf)
{
double delta;
double dk;
int start;
int sign;
int i;
assert (1 == ampl);
if (x && xLen)
{
delta = m_iHalfHanLen_c / xLen;
dk=0.; // FTOL function does rounding. If casting to int, need to start at 0.5 to get rounding
/*
* When multiplying by the second half, the window function is the same,
* but we multiply from the last sample in the vector to the first
* NOTE: The first sample is multiplyed by 0 in the case of the first
* half, and by 1 (*ampl, of course) in the case of the second half.
*/
switch (whichHalf)
{
case WindowSecondHalf:
start=xLen;
sign=-1;
break;
case WindowFirstHalf:
x[0]=0.0;
start=0;
sign=1;
break;
default:
fprintf(stderr, "Hanning, should especify a half window\n");
return;
}
for (i=1; i<xLen; i++)
{
dk += delta;
x[start+sign*i] *= m_adHalfHanning[FTOL(dk)];
}
}
}
/*****************************************************************************
* CTips::ClipData *
*-----------------*
* Description:
* 12/4/00 - now using the FTOL function, since the compiler doesn't do
* the conversion efficiently.
* 1/18/01 - The FTOL function rounds, whereas casting truncates. So,
* we no longer need to ad .5 for pos numbers and subtract .5
* for negative numbers.
*
******************************************************************* mplumpe ***/
short CTips::ClipData (double x)
{
if (x > SHRT_MAX )
{
return SHRT_MAX;
}
if (x < SHRT_MIN )
{
return SHRT_MIN;
}
return (short)FTOL(x);
}
/*****************************************************************************
* CTips::LpcInit *
*----------------*
* Description:
*
******************************************************************* PACOG ***/
bool CTips::LpcInit ()
{
m_iLpcOrder = LpcOrder (m_iSampFreq);
if ((m_pdFiltMem = new double [m_iLpcOrder]) == 0)
{
goto error;
}
memset( m_pdFiltMem, 0, m_iLpcOrder * sizeof (*m_pdFiltMem));
if ((m_pdInterpCoef = new double [m_iLpcOrder]) == 0)
{
goto error;
}
memset( m_pdInterpCoef, 0, m_iLpcOrder * sizeof (*m_pdInterpCoef));
if ((m_pdLastCoef = new double [m_iLpcOrder]) == 0)
{
goto error;
}
memset( m_pdLastCoef, 0, m_iLpcOrder * sizeof (*m_pdLastCoef));
return true;
error:
LpcFreeAll();
return false;
}
/*****************************************************************************
* CTips::LpcSynth *
*--------------------*
* Description:
*
******************************************************************* PACOG ***/
void CTips::LpcSynth (double* pdPeriod, int iPeriodLen)
{
double alfa;
int i;
int j;
for (i=0; i<iPeriodLen; i++)
{
alfa = i/(double)iPeriodLen;
for (j=0; j<m_iLpcOrder ; j++) {
m_pdInterpCoef[j] = (1.0 - alfa) * m_pdLastCoef[j] + alfa * m_pdNewCoef[j];
}
ParcorFilterSyn(pdPeriod+i, 1, m_pdInterpCoef, m_pdFiltMem, m_iLpcOrder );
}
memcpy( m_pdLastCoef, m_pdNewCoef, m_iLpcOrder * sizeof(*m_pdLastCoef));
}
/*****************************************************************************
* CTips::LpcFreeAll *
*----------------------*
* Description:
*
******************************************************************* PACOG ***/
void CTips::LpcFreeAll()
{
if (m_pdFiltMem)
{
delete[] m_pdFiltMem;
m_pdFiltMem = 0;
}
if (m_pdInterpCoef)
{
delete[] m_pdInterpCoef;
m_pdInterpCoef = 0;
}
if (m_pdLastCoef)
{
delete[] m_pdLastCoef;
m_pdInterpCoef = 0;
}
}
| [
"112426112@qq.com"
] | 112426112@qq.com |
1876ae7abdffba07daaf42c61a2673be4bbb87b1 | 62bf789f19f500aa5aa20f6911573cc0c59902c7 | /ecs/src/model/ReleaseDedicatedHostResult.cc | 15439f6229b4b5c2dc17c2e107deb63bf3ae2cde | [
"Apache-2.0"
] | permissive | liuyuhua1984/aliyun-openapi-cpp-sdk | 0288f0241812e4308975a62a23fdef2403cfd13a | 600883d23a243eb204e39f15505f1f976df57929 | refs/heads/master | 2020-07-04T09:47:49.901987 | 2019-08-13T14:13:11 | 2019-08-13T14:13:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,297 | cc | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/ecs/model/ReleaseDedicatedHostResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Ecs;
using namespace AlibabaCloud::Ecs::Model;
ReleaseDedicatedHostResult::ReleaseDedicatedHostResult() :
ServiceResult()
{}
ReleaseDedicatedHostResult::ReleaseDedicatedHostResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
ReleaseDedicatedHostResult::~ReleaseDedicatedHostResult()
{}
void ReleaseDedicatedHostResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
}
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
1b6653139e5c807a0697da6b88cc034fcf11718e | 15aa6fd07023d53624a399d464f4bb9e90494ece | /iocore/net/quic/QUICKeyGenerator.cc | 98d091d87259963a515ec1ff456ac7c44d4efdc1 | [
"BSD-3-Clause",
"OpenSSL",
"MIT",
"ISC",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-openssl",
"Apache-2.0",
"LicenseRef-scancode-ssleay-windows",
"BSD-2-Clause",
"HPND",
"TCL",
"LicenseRef-scancode-unknown",
"LicenseRef-scancode-public-domain"
] | permissive | tomoatan/trafficserver | d1f414f07862289b559150ce151afe3bfd6eb6ad | fcbf60bdfe0d26bfe54cb1967439e7a5e8a7270f | refs/heads/master | 2023-06-30T10:19:17.141785 | 2020-07-16T00:14:29 | 2020-07-16T00:14:29 | 280,100,954 | 0 | 0 | Apache-2.0 | 2020-07-16T08:41:14 | 2020-07-16T08:41:13 | null | UTF-8 | C++ | false | false | 5,936 | cc | /** @file
*
* A key generator for QUIC connection
*
* @section license License
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "QUICKeyGenerator.h"
#include <openssl/ssl.h>
#include "tscore/ink_assert.h"
#include "tscore/Diags.h"
#include "QUICHKDF.h"
#include "QUICDebugNames.h"
using namespace std::literals;
constexpr static uint8_t QUIC_VERSION_1_SALT[] = {
0xc3, 0xee, 0xf7, 0x12, 0xc7, 0x2e, 0xbb, 0x5a, 0x11, 0xa7, 0xd2, 0x43, 0x2b, 0xb4, 0x63, 0x65, 0xbe, 0xf9, 0xf5, 0x02,
};
constexpr static std::string_view LABEL_FOR_CLIENT_INITIAL_SECRET("client in"sv);
constexpr static std::string_view LABEL_FOR_SERVER_INITIAL_SECRET("server in"sv);
constexpr static std::string_view LABEL_FOR_KEY("quic key"sv);
constexpr static std::string_view LABEL_FOR_IV("quic iv"sv);
constexpr static std::string_view LABEL_FOR_HP("quic hp"sv);
void
QUICKeyGenerator::generate(uint8_t *hp_key, uint8_t *pp_key, uint8_t *iv, size_t *iv_len, QUICConnectionId cid)
{
const QUIC_EVP_CIPHER *cipher = this->_get_cipher_for_initial();
const EVP_MD *md = EVP_sha256();
uint8_t secret[512];
size_t secret_len = sizeof(secret);
QUICHKDF hkdf(md);
switch (this->_ctx) {
case Context::CLIENT:
this->_generate_initial_secret(secret, &secret_len, hkdf, cid, LABEL_FOR_CLIENT_INITIAL_SECRET.data(),
LABEL_FOR_CLIENT_INITIAL_SECRET.length(), EVP_MD_size(md));
if (is_debug_tag_set("vv_quic_crypto")) {
uint8_t print_buf[1024 + 1];
QUICDebug::to_hex(print_buf, secret, secret_len);
Debug("vv_quic_crypto", "client_in_secret=%s", print_buf);
}
break;
case Context::SERVER:
this->_generate_initial_secret(secret, &secret_len, hkdf, cid, LABEL_FOR_SERVER_INITIAL_SECRET.data(),
LABEL_FOR_SERVER_INITIAL_SECRET.length(), EVP_MD_size(md));
if (is_debug_tag_set("vv_quic_crypto")) {
uint8_t print_buf[1024 + 1];
QUICDebug::to_hex(print_buf, secret, secret_len);
Debug("vv_quic_crypto", "server_in_secret=%s", print_buf);
}
break;
}
this->_generate(hp_key, pp_key, iv, iv_len, hkdf, secret, secret_len, cipher);
}
void
QUICKeyGenerator::regenerate(uint8_t *hp_key, uint8_t *pp_key, uint8_t *iv, size_t *iv_len, const uint8_t *secret,
size_t secret_len, const QUIC_EVP_CIPHER *cipher, QUICHKDF &hkdf)
{
this->_generate(hp_key, pp_key, iv, iv_len, hkdf, secret, secret_len, cipher);
}
int
QUICKeyGenerator::_generate(uint8_t *hp_key, uint8_t *pp_key, uint8_t *iv, size_t *iv_len, QUICHKDF &hkdf, const uint8_t *secret,
size_t secret_len, const QUIC_EVP_CIPHER *cipher)
{
// Generate key, iv, and hp_key
// key = HKDF-Expand-Label(S, "quic key", "", key_length)
// iv = HKDF-Expand-Label(S, "quic iv", "", iv_length)
// hp_key = HKDF-Expand-Label(S, "quic hp", "", hp_key_length)
size_t dummy;
this->_generate_key(pp_key, &dummy, hkdf, secret, secret_len, this->_get_key_len(cipher));
this->_generate_iv(iv, iv_len, hkdf, secret, secret_len, this->_get_iv_len(cipher));
this->_generate_hp(hp_key, &dummy, hkdf, secret, secret_len, this->_get_key_len(cipher));
return 0;
}
int
QUICKeyGenerator::_generate_initial_secret(uint8_t *out, size_t *out_len, QUICHKDF &hkdf, QUICConnectionId cid, const char *label,
size_t label_len, size_t length)
{
uint8_t client_connection_id[QUICConnectionId::MAX_LENGTH];
size_t cid_len = 0;
uint8_t initial_secret[512];
size_t initial_secret_len = sizeof(initial_secret);
// TODO: do not extract initial secret twice
QUICTypeUtil::write_QUICConnectionId(cid, client_connection_id, &cid_len);
if (hkdf.extract(initial_secret, &initial_secret_len, QUIC_VERSION_1_SALT, sizeof(QUIC_VERSION_1_SALT), client_connection_id,
cid.length()) != 1) {
return -1;
}
if (is_debug_tag_set("vv_quic_crypto")) {
uint8_t print_buf[1024 + 1];
QUICDebug::to_hex(print_buf, initial_secret, initial_secret_len);
Debug("vv_quic_crypto", "initial_secret=%s", print_buf);
}
hkdf.expand(out, out_len, initial_secret, initial_secret_len, reinterpret_cast<const char *>(label), label_len, length);
return 0;
}
int
QUICKeyGenerator::_generate_key(uint8_t *out, size_t *out_len, QUICHKDF &hkdf, const uint8_t *secret, size_t secret_len,
size_t key_length) const
{
return hkdf.expand(out, out_len, secret, secret_len, LABEL_FOR_KEY.data(), LABEL_FOR_KEY.length(), key_length);
}
int
QUICKeyGenerator::_generate_iv(uint8_t *out, size_t *out_len, QUICHKDF &hkdf, const uint8_t *secret, size_t secret_len,
size_t iv_length) const
{
return hkdf.expand(out, out_len, secret, secret_len, LABEL_FOR_IV.data(), LABEL_FOR_IV.length(), iv_length);
}
int
QUICKeyGenerator::_generate_hp(uint8_t *out, size_t *out_len, QUICHKDF &hkdf, const uint8_t *secret, size_t secret_len,
size_t hp_length) const
{
return hkdf.expand(out, out_len, secret, secret_len, LABEL_FOR_HP.data(), LABEL_FOR_HP.length(), hp_length);
}
| [
"maskit@apache.org"
] | maskit@apache.org |
d139f19ec8228b4a8229eda3143c1facb974b9e8 | 3f3095dbf94522e37fe897381d9c76ceb67c8e4f | /Current/ENUM_MutatorWarning_enums.hpp | 3bbd81125170109d058204c2c92a7f476c4661e0 | [] | no_license | DRG-Modding/Header-Dumps | 763c7195b9fb24a108d7d933193838d736f9f494 | 84932dc1491811e9872b1de4f92759616f9fa565 | refs/heads/main | 2023-06-25T11:11:10.298500 | 2023-06-20T13:52:18 | 2023-06-20T13:52:18 | 399,652,576 | 8 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 136 | hpp | namespace ENUM_MutatorWarning {
enum Type {
NewEnumerator0 = 0,
NewEnumerator4 = 1,
ENUM_MAX = 2,
};
}
| [
"bobby45900@gmail.com"
] | bobby45900@gmail.com |
48bfa4e93183bec066ce82a4004823e7359e05a4 | 57c13dd620429552257a86e6a2bbd7367340cfd0 | /Demo04/Demo04.cpp | 76acbec3b2cf4bc9d3af445319ab8c6eb11f398c | [
"Apache-2.0"
] | permissive | Nazul/MSC-CG_OpenGL | 23d9c3c4a3ea9654192b83858a1cf34300f85fa4 | 3c7d157ad98268197f59e8d2823dd5fafe8902bf | refs/heads/master | 2023-05-25T09:23:26.274641 | 2023-05-22T02:17:04 | 2023-05-22T02:17:04 | 50,739,343 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,512 | cpp | //**********************************************************
// ITESO - Master's Degree in Computer Systems
// Computer Graphics
// Demo 04 - Analytic and Parametric Surfaces
//
// Mario Contreras (705080)
//
//*********************************************************
#include "stdafx.h"
#include <math.h>
#include <string>
#include "GL\glew.h"
#include "GL\glut.h"
#include "GL\freeglut.h"
#include "Matrix4D.h"
#include "MeshMathSurface.h"
#ifdef _DEBUG
#include <iostream>
#endif
#define REFRESH_MILISECS 100
#define WINDOW_WIDTH 640
#define WINDOW_HEIGHT 480
#define INCREMENT 0.01f
#define PI 3.141592f
bool bRotateX, bRotateY, bRotateZ, bScaleUp, bScaleDown, bForward, bBackward, bLeft, bRight, bUp, bDown, bWireframe = false;
MATRIX4D T;
MATRIX4D R;
MATRIX4D Vi;
CMeshMathSurface g_EggCarton;
CMeshMathSurface g_Plate;
CMeshMathSurface g_Sphere;
CMeshMathSurface g_Bananas;
CMeshMathSurface g_Flower;
float SinCos(float x, float y) {
return 0.3f * cosf(3.0f * x * PI) * sinf(3.0f * y * PI);
}
float x2y2(float x, float y) {
return 0.4f * x * x * y * y;
}
VECTOR4D Sphere(float u, float v) {
VECTOR4D V;
float r = 0.4f;
V.x = r * (cosf(2.0f * PI * u) * sinf(PI * v));
V.y = r * (sinf(2.0f * PI * u) * sinf(PI * v));
V.z = r * (cosf(PI * v));
V.w = 1.0f;
return V;
}
VECTOR4D Bananas(float u, float v) {
VECTOR4D V;
V.x = 0.2f * ((2.0f + sinf(2 * PI * v) * sinf(2.0f * PI * u)) * sinf(3.0f * PI * v));
V.y = 0.2f * (sinf(2.0f * PI * v) * cosf(2.0f * PI * u) + 4.0f * v - 2.0f);
V.z = 0.2f * ((2.0f + sinf(2.0f * PI * v) * sinf(2.0f * PI * u)) * cosf(3.0f * PI * v));
V.w = 1.0f;
return V;
}
VECTOR4D Dini(float u, float v) {
VECTOR4D V;
float a = 1.0f;
float b = 0.2f;
V.x = 0.5f * (a * cosf(u) * sinf(v));
V.y = 0.5f * (a * sinf(u) * sinf(v));
V.z = 0.5f * (a * (cosf(v) + logf(tanf(v * 0.5f))) + b * u);
V.w = 1.0f;
return V;
}
void renderScene(void) {
int sx = glutGet(GLUT_WINDOW_WIDTH);
int sy = glutGet(GLUT_WINDOW_HEIGHT);
MATRIX4D SAspect = Scaling((float)sy / sx, 1, 1);
//MATRIX4D SAspect = Scaling(1, (float)sx / sy, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if(bWireframe)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
else
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glBegin(GL_TRIANGLES);
g_EggCarton.Draw(SAspect * T * Translation(0.0f, 0.0f, -1.0f));
g_Plate.Draw(SAspect * T * Translation(0.0f, 0.0f, -0.1f));
g_Sphere.Draw(SAspect * T * Translation(0.4f, 0.4f, 0.32f));
g_Bananas.Draw(SAspect * T * Translation(0.45f, 0.45f, 0.48f));
g_Flower.Draw(SAspect * T * Translation(-0.5f, 0.5f, 0.8f));
glEnd();
glutSwapBuffers();
}
void animateScene(int value) {
glutTimerFunc(REFRESH_MILISECS, animateScene, 0);
static float scale = 1.0f;
VECTOR4D Speed = { 0.02f, 0.02f, 0.02f, 0.0f };
MATRIX4D P = PerspectiveWidthHeightRH(0.5f, 0.5f, 1.0f, 10.0f);
MATRIX4D InvV = FastInverse(Vi);
VECTOR4D XDir = { InvV.m00, InvV.m10, InvV.m20, 0.0f };
VECTOR4D YDir = { InvV.m01, InvV.m11, InvV.m21, 0.0f };
VECTOR4D ZDir = { InvV.m02, InvV.m12, InvV.m22, 0.0f };
VECTOR4D EyePos = { InvV.m03, InvV.m13, InvV.m23, 1.0f };
if (bLeft)
EyePos = EyePos + XDir * Speed;
if (bRight)
EyePos = EyePos - XDir * Speed;
if (bDown)
EyePos = EyePos + YDir * Speed;
if (bUp)
EyePos = EyePos - YDir * Speed;
if (bBackward)
EyePos = EyePos + ZDir * Speed;
if (bForward)
EyePos = EyePos - ZDir * Speed;
InvV.m03 = EyePos.x;
InvV.m13 = EyePos.y;
InvV.m23 = EyePos.z;
Vi = FastInverse(InvV);
if (bRotateX)
R = R * RotationX(INCREMENT);
if (bRotateY)
R = R * RotationY(INCREMENT);
if (bRotateZ)
R = R * RotationZ(INCREMENT);
if (bScaleUp)
scale += INCREMENT;
if (bScaleDown)
scale -= INCREMENT;
T = (P * Vi) * R * Scaling(scale, scale, scale);
glutPostRedisplay();
}
void keyHandler(unsigned char key, int x, int y) {
#ifdef _DEBUG
std::cout << key << " pressed" << std::endl;
#endif
switch (key) {
case 27:
glutLeaveMainLoop();
break;
case '+':
bScaleUp = true;
break;
case '-':
bScaleDown = true;
break;
case '2':
bDown = true;
break;
case '4':
bLeft = true;
break;
case '6':
bRight = true;
break;
case '7':
bBackward = true;
break;
case '8':
bUp = true;
break;
case '9':
bForward = true;
break;
case 'S':
case 's':
bRotateZ = true;
break;
case 'W':
case 'w':
bWireframe = !bWireframe;
break;
case 'X':
case 'x':
bRotateX = !bRotateX;
break;
case 'Y':
case 'y':
bRotateY = !bRotateY;
break;
case 'Z':
case 'z':
bRotateZ = !bRotateZ;
break;
}
glutPostRedisplay();
}
void keyUpHandler(unsigned char key, int x, int y) {
#ifdef _DEBUG
std::cout << key << " released" << std::endl;
#endif
switch (key) {
case '+':
bScaleUp = false;
break;
case '-':
bScaleDown = false;
break;
case '2':
bDown = false;
break;
case '4':
bLeft = false;
break;
case '6':
bRight = false;
break;
case '7':
bBackward = false;
break;
case '8':
bUp = false;
break;
case '9':
bForward = false;
break;
case 'S':
case 's':
bRotateZ = false;
break;
}
glutPostRedisplay();
}
int main(int argc, char **argv) {
bool gameMode = false;
int startX = 100, startY = 100;
VECTOR4D Target = { 0.0f, 0.0f, 0.0f, 1.0f };
VECTOR4D Eye = { 3.0f, 3.0f, 3.0f, 1.0f };
VECTOR4D Up = { 0.0f, 0.0f, 1.0f, 0.0f };
VECTOR4D r = { 1, 0, 0, 1 };
VECTOR4D g = { 0, 1, 0, 1 };
VECTOR4D b = { 0, 0, 1, 1 };
VECTOR4D w = { 1, 1, 1, 1 };
VECTOR4D y = { 1, 1, 0, 1 };
// Init GLUT and create Window
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
if (argc > 1) {
if (std::string(argv[1]) == "-game") {
glutGameModeString("1024x768:32");
if (glutGameModeGet(GLUT_GAME_MODE_POSSIBLE)) {
gameMode = true;
glutEnterGameMode();
}
}
if (std::string(argv[1]) == "-center") {
startX = glutGet(GLUT_SCREEN_WIDTH) / 2 - WINDOW_WIDTH / 2;
startY = glutGet(GLUT_SCREEN_HEIGHT) / 2 - WINDOW_HEIGHT / 2;
}
}
if (!gameMode) {
glutInitWindowPosition(startX, startY);
glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
glutCreateWindow("MSC GC 705080 - Demo 4 (Analytic and Parametric Surfaces)");
}
// Initialize viewport and rotation matrix
Vi = View(Eye, Target, Up);
R = Identity();
// Create surfaces
g_EggCarton.BuildAnalyticSurface(30, 30, -1, -1, 2.0f / (30 - 1), 2.0f / (30 - 1), SinCos);
g_EggCarton.SetColor(r, g, b, w);
g_Plate.BuildAnalyticSurface(40, 40, -1, -1, 2.0f / (40 - 1), 2.0f / (40 - 1), x2y2);
g_Plate.SetColor(r, g, b, w);
g_Sphere.BuildParametricSurface(30, 30, -1, -1, 1.0f / (30 - 1), 1.0f / (30 - 1), Sphere);
g_Sphere.SetColor(r, b, b, r);
g_Flower.BuildParametricSurface(100, 30, -1, -1, 1.0f / (10 - 1), 1.0f / (10 - 1), Dini);
g_Flower.SetColor(b, w, w, b);
g_Bananas.BuildParametricSurface(30, 30, -1, -1, 1.0f / (30 - 1), 1.0f / (30 - 1), Bananas);
g_Bananas.SetColor(y, w, w, y);
// Register callbacks
glutDisplayFunc(renderScene);
glutKeyboardFunc(keyHandler);
glutKeyboardUpFunc(keyUpHandler);
glutTimerFunc(REFRESH_MILISECS, animateScene, 0);
// Enter GLUT event processing cycle
glEnable(GL_DEPTH_TEST);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glutMainLoop();
return 0;
}
//EOF
| [
"marioc@nazul.net"
] | marioc@nazul.net |
5a2c4d4b539c1a549cb7545033538b9ba7ea3300 | 8c65df6a098b3ea65e5447a1c4d27aba571b9817 | /test/array/tuple.cpp | 79b60b2477b85298b2fdfa05797d8f2d4a67cc1c | [] | no_license | tianyu/sky | 24956da0e946cf92203f83f63de10517951ea58b | a46e1a8eb0125ed2d8dd5a2afddfaffcb6a8fd64 | refs/heads/master | 2020-04-09T15:11:21.874971 | 2013-07-23T05:12:30 | 2013-07-23T05:12:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,175 | cpp | #include "../gtest.h"
#include <vector>
#include "common.hpp"
namespace {
template<typename P>
struct Array_AsTuple : public ::testing::Test
{};
using Types = ::testing::Types<
IntParam<2>,
IntParam<2, 3>,
IntParam<2, 0>,
IntParam<2, 3, 2>
>;
TYPED_TEST_CASE(Array_AsTuple, Types);
void expect_eq(int const&one, int const&two)
{
EXPECT_EQ(one, two);
}
template<std::size_t... Ns>
void expect_eq(sky::array<int, Ns...> const&one,
sky::array<int, Ns...> const&two)
{
auto end_it = one.end();
auto one_it = one.begin();
auto two_it = two.begin();
while (one_it != end_it) {
expect_eq(*one_it++, *two_it++);
}
}
} // namespace
TYPED_TEST(Array_AsTuple, Tuple_Size)
{
auto tuple_size = std::tuple_size<typename TypeParam::array_type>::value;
EXPECT_EQ((TypeParam::num_rows), tuple_size);
}
TYPED_TEST(Array_AsTuple, Tuple_Element)
{
using tuple_element = typename std::tuple_element<0,
typename TypeParam::array_type>::type;
using expected_type = typename TypeParam::row_type;
EXPECT_SAME(expected_type, tuple_element);
}
TYPED_TEST(Array_AsTuple, Get_Lvalue_IsNoExcept)
{
using std::get;
auto array = TypeParam::make_array();
EXPECT_TRUE(noexcept(get<0>(array)));
}
TYPED_TEST(Array_AsTuple, Get_Lvalue)
{
using std::get;
auto array = TypeParam::make_array();
using expected_type = typename TypeParam::row_type&;
using return_type = decltype(get<0>(array));
EXPECT_SAME(expected_type, return_type);
constexpr auto halfway = std::size_t(TypeParam::num_rows/2);
auto expected = array[halfway];
auto actual = get<halfway>(array);
expect_eq(expected, actual);
}
TYPED_TEST(Array_AsTuple, Get_Rvalue_IsNoExcept)
{
using std::get;
auto array = TypeParam::make_array();
EXPECT_TRUE(noexcept(get<0>(std::move(array))));
}
TYPED_TEST(Array_AsTuple, Get_Rvalue)
{
using std::get;
auto array = TypeParam::make_array();
using expected_type = typename TypeParam::row_type&&;
using return_type = decltype(get<0>(std::move(array)));
EXPECT_SAME(expected_type, return_type);
constexpr auto halfway = std::size_t(TypeParam::num_rows/2);
auto expected = array[halfway];
auto actual = get<halfway>(std::move(array));
expect_eq(expected, actual);
}
TYPED_TEST(Array_AsTuple, Get_ConstLvalue_IsNoExcept)
{
using std::get;
const auto array = TypeParam::make_array();
EXPECT_TRUE(noexcept(get<0>(array)));
}
TYPED_TEST(Array_AsTuple, Get_ConstLvalue_IsConstexpr)
{
using std::get;
constexpr const auto array = typename TypeParam::array_type{};
constexpr auto row = get<0>(array);
(void) row;
}
TYPED_TEST(Array_AsTuple, Get_ConstLvalue)
{
using std::get;
const auto array = TypeParam::make_array();
using expected_type = typename TypeParam::row_type const&;
using return_type = decltype(get<0>(array));
EXPECT_SAME(expected_type, return_type);
constexpr auto halfway = std::size_t(TypeParam::num_rows/2);
auto expected = array[halfway];
auto actual = get<halfway>(array);
expect_eq(expected, actual);
}
| [
"tian.tian098@gmail.com"
] | tian.tian098@gmail.com |
b59f54eebc6183bc5947df8ab0f9b0382fd04a9f | b7139acb3448d39dbeb8597c7f65d4a378ddc330 | /2015/chapter_5/examples/5_19.cpp | 6b00363fb1b5854eff321d487e378b3777cee48a | [] | no_license | linsallyzhao/earlyobjects-exercises | 3f88e2d48674fdd431ecfd7e57c0fe2fa30c93f8 | 746a2489eb135fee8c04c74e3e763b07853e6796 | refs/heads/master | 2021-08-24T13:27:43.256219 | 2017-12-10T00:38:56 | 2017-12-10T00:38:56 | 113,711,078 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 534 | cpp | #include <iostream>
#include <fstream>
int main()
{
std::ofstream outputFile;
int numberOfDays;
double sales;
std::cout << "For how many days do you have sales? ";
std::cin >> numberOfDays;
outputFile.open("Sales");
for (int count = 1; count <= numberOfDays; count++)
{
std::cout << "Enter the sales for day " << count << ": ";
std::cin >> sales;
outputFile << sales << std::endl;
}
outputFile.close();
std::cout << "Data written to Sales.\n";
return 0;
}
| [
"lin.sally.zhao@gmail.com"
] | lin.sally.zhao@gmail.com |
17612006b60f92b283fbe7d3e758ec75bd1046f4 | 0932ff127a29ea9206f6343c81ab66407ba92a06 | /10000~10999/10951.cpp | 22eee563536e47cc3ca69b45e79ce4ce2117c11f | [] | no_license | rama0126/algorithm-practice | 78c2cf9140fdc64aeaa8b38084829e879b95ad75 | a9188770b070f0476b8a78262deb5010eb24ce2d | refs/heads/main | 2023-06-10T08:13:45.148663 | 2021-07-06T09:34:57 | 2021-07-06T09:34:57 | 341,581,831 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 263 | cpp | #include <iostream>
#include <queue>
using namespace std;
int main() {
queue<int> q;
int* sum = new int;
while (1) {
int A, B;
cin >> A >> B;
if (cin.eof())
break;
q.push(A + B);
}
while(!q.empty())
{
cout << q.front() << "\n";
q.pop();
}
} | [
"60171895@mju.ac.kr"
] | 60171895@mju.ac.kr |
3d89a8b77f2dc42a063093728c8e7f2852bda644 | 6ea50d800eaf5690de87eea3f99839f07c662c8b | /ver.0.14.0/HellSpringFeature.h | c336e2665af5a0878f59d51efa48213d271730ed | [] | no_license | Toku555/MCPE-Headers | 73eefeab8754a9ce9db2545fb0ea437328cade9e | b0806aebd8c3f4638a1972199623d1bf686e6497 | refs/heads/master | 2021-01-15T20:53:23.115576 | 2016-09-01T15:38:27 | 2016-09-01T15:38:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 205 | h | #pragma once
class HellSpringFeature{
public:
HellSpringFeature(BlockID,bool);
void place(BlockSource &,BlockPos const&,Random &);
void ~HellSpringFeature();
void ~HellSpringFeature();
};
| [
"sinigami3427@gmail.com"
] | sinigami3427@gmail.com |
e7eaa7940f65dc73ff9d61695026786a021a2e9e | c61a803556c3aa1743f2f46b67648322e02ad812 | /Unreal/Plugins/AirSim/Source/DetectionComponent.cpp | adb35825949fdd817f0ca37173fdcebca8013859 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | zhaohywork/AirSim | 31274a991ca4714a172462e6312edb7b207421fb | 83119a648e2fe79a2f072243cb81b2e31aebd571 | refs/heads/master | 2021-12-01T20:56:16.809963 | 2021-06-08T17:37:29 | 2021-06-08T17:37:29 | 162,536,388 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,171 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "DetectionComponent.h"
#include <Components/SceneCaptureComponent2D.h>
#include <Components/StaticMeshComponent.h>
#include <DrawDebugHelpers.h>
#include <Engine/Engine.h>
#include <Engine/StaticMesh.h>
#include <Engine/TextureRenderTarget2D.h>
#include <EngineUtils.h>
#include <Math/UnrealMathUtility.h>
#include <Kismet/KismetSystemLibrary.h>
#include <Kismet/KismetMathLibrary.h>
#include <Engine/EngineTypes.h>
UDetectionComponent::UDetectionComponent()
: max_distance_to_camera_(20000.f)
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = true;
PrimaryComponentTick.bStartWithTickEnabled = false;
}
void UDetectionComponent::BeginPlay()
{
Super::BeginPlay();
scene_capture_component_2D_ = CastChecked<USceneCaptureComponent2D>(GetAttachParent());
object_filter_ = FObjectFilter();
}
void UDetectionComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
}
const TArray<FDetectionInfo>& UDetectionComponent::getDetections()
{
cached_detections_.Empty();
for (TActorIterator<AActor> actor_itr(GetWorld()); actor_itr; ++actor_itr) {
AActor* actor = *actor_itr;
if (object_filter_.matchesActor(actor)) {
if (FVector::Distance(actor->GetActorLocation(), GetComponentLocation()) <= max_distance_to_camera_) {
FBox2D box_2D_out;
if (texture_target_ && calcBoundingFromViewInfo(actor, box_2D_out)) {
FDetectionInfo detection;
detection.Actor = actor;
detection.Box2D = box_2D_out;
FBox box_3D = actor->GetComponentsBoundingBox(true);
detection.Box3D = FBox(getRelativeLocation(box_3D.Min), getRelativeLocation(box_3D.Max));
detection.RelativeTransform = FTransform(getRelativeRotation(actor->GetActorLocation(), actor->GetActorRotation()),
getRelativeLocation(actor->GetActorLocation()));
cached_detections_.Add(detection);
}
}
}
}
return cached_detections_;
}
bool UDetectionComponent::calcBoundingFromViewInfo(AActor* actor, FBox2D& box_out)
{
FVector origin;
FVector extend;
actor->GetActorBounds(false, origin, extend);
TArray<FVector> points;
TArray<FVector2D> points_2D;
bool is_in_camera_view = false;
// get render target for texture size
FRenderTarget* render_target = texture_target_->GameThread_GetRenderTargetResource();
// initialize viewinfo for projection matrix
FMinimalViewInfo info;
info.Location = scene_capture_component_2D_->GetComponentTransform().GetLocation();
info.Rotation = scene_capture_component_2D_->GetComponentTransform().GetRotation().Rotator();
info.FOV = scene_capture_component_2D_->FOVAngle;
info.ProjectionMode = scene_capture_component_2D_->ProjectionType;
info.AspectRatio = float(texture_target_->SizeX) / float(texture_target_->SizeY);
info.OrthoNearClipPlane = 1;
info.OrthoFarClipPlane = 100000;
info.bConstrainAspectRatio = true;
// calculate 3D corner Points of bounding box
points.Add(origin + FVector(extend.X, extend.Y, extend.Z));
points.Add(origin + FVector(-extend.X, extend.Y, extend.Z));
points.Add(origin + FVector(extend.X, -extend.Y, extend.Z));
points.Add(origin + FVector(-extend.X, -extend.Y, extend.Z));
points.Add(origin + FVector(extend.X, extend.Y, -extend.Z));
points.Add(origin + FVector(-extend.X, extend.Y, -extend.Z));
points.Add(origin + FVector(extend.X, -extend.Y, -extend.Z));
points.Add(origin + FVector(-extend.X, -extend.Y, -extend.Z));
// initialize pixel values
FVector2D min_pixel(texture_target_->SizeX, texture_target_->SizeY);
FVector2D max_pixel(0, 0);
FIntRect screen_rect(0, 0, texture_target_->SizeX, texture_target_->SizeY);
// initialize projection data for sceneview
FSceneViewProjectionData projection_data;
projection_data.ViewOrigin = info.Location;
// do some voodoo rotation that is somehow mandatory and stolen from UGameplayStatics::ProjectWorldToScreen
projection_data.ViewRotationMatrix = FInverseRotationMatrix(info.Rotation) * FMatrix(
FPlane(0, 0, 1, 0),
FPlane(1, 0, 0, 0),
FPlane(0, 1, 0, 0),
FPlane(0, 0, 0, 1));
if (scene_capture_component_2D_->bUseCustomProjectionMatrix) {
projection_data.ProjectionMatrix = scene_capture_component_2D_->CustomProjectionMatrix;
}
else {
projection_data.ProjectionMatrix = info.CalculateProjectionMatrix();
}
projection_data.SetConstrainedViewRectangle(screen_rect);
// Project Points to pixels and get the corner pixels
for (FVector& point : points) {
FVector2D Pixel(0, 0);
FSceneView::ProjectWorldToScreen((point), screen_rect, projection_data.ComputeViewProjectionMatrix(), Pixel);
is_in_camera_view |= (Pixel != screen_rect.Min) && (Pixel != screen_rect.Max) && screen_rect.Contains(FIntPoint(Pixel.X, Pixel.Y));
points_2D.Add(Pixel);
max_pixel.X = FMath::Max(Pixel.X, max_pixel.X);
max_pixel.Y = FMath::Max(Pixel.Y, max_pixel.Y);
min_pixel.X = FMath::Min(Pixel.X, min_pixel.X);
min_pixel.Y = FMath::Min(Pixel.Y, min_pixel.Y);
}
// If actor in camera view - check if it's actually visible or hidden
// Check against 8 extend points
bool is_visible = false;
if (is_in_camera_view) {
FHitResult result;
bool is_world_hit;
for (FVector& point : points) {
is_world_hit = GetWorld()->LineTraceSingleByChannel(result, GetComponentLocation(), point, ECC_WorldStatic);
if (is_world_hit) {
if (result.Actor == actor) {
is_visible = true;
break;
}
}
}
// If actor in camera view but didn't hit any point out of 8 extend points,
// check against 10 random points
if (!is_visible) {
for (int i = 0; i < 10; i++) {
FVector point = UKismetMathLibrary::RandomPointInBoundingBox(origin, extend);
is_world_hit = GetWorld()->LineTraceSingleByChannel(result, GetComponentLocation(), point, ECC_WorldStatic);
if (is_world_hit) {
if (result.Actor == actor) {
is_visible = true;
break;
}
}
}
}
}
FBox2D box_out_temp = FBox2D(min_pixel, max_pixel);
box_out.Min.X = FMath::Clamp<float>(box_out_temp.Min.X, 0, texture_target_->SizeX);
box_out.Min.Y = FMath::Clamp<float>(box_out_temp.Min.Y, 0, texture_target_->SizeY);
box_out.Max.X = FMath::Clamp<float>(box_out_temp.Max.X, 0, texture_target_->SizeX);
box_out.Max.Y = FMath::Clamp<float>(box_out_temp.Max.Y, 0, texture_target_->SizeY);
return is_in_camera_view && is_visible;
}
FVector UDetectionComponent::getRelativeLocation(FVector in_location)
{
return GetComponentTransform().InverseTransformPosition(in_location);
}
FRotator UDetectionComponent::getRelativeRotation(FVector in_location, FRotator in_rotation)
{
FTransform camera_transform(GetComponentRotation(), GetComponentLocation());
FTransform relative_object_transform = camera_transform.GetRelativeTransform(FTransform(in_rotation, in_location));
return relative_object_transform.Rotator();
}
| [
"alonfaraj@gmail.com"
] | alonfaraj@gmail.com |
911448ada8350a14cc81ac3229efc983d2aa7e57 | ef8be8c701374bb15922869643867c719fbafefb | /shieldsio.hpp | eb970539b2998f88120a45c17fb8744824d165c5 | [] | no_license | makutamoto/atcoder-badges-for-m5stickc | 9be98e123d58cd9cfa22e6fa18a0d5baaaed3286 | 3e1119d289e4b6b7a80d9c030b84b97e9b0b7773 | refs/heads/master | 2022-12-07T05:34:43.521132 | 2020-09-03T11:38:49 | 2020-09-03T11:38:49 | 292,552,422 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 181 | hpp | #ifndef SHIELDSIO_HPP
#define SHIELDSIO_HPP
class ShieldsIO {
public:
String endpoint;
String label, message, color;
ShieldsIO(String endpoint);
void fetch();
};
#endif
| [
"34860673+makutamoto@users.noreply.github.com"
] | 34860673+makutamoto@users.noreply.github.com |
37c6a9518726ce61c8ed93721af0bab2fe035b65 | 4472b6cde9ac0feadc12fee9c856eb90a032e5e1 | /C++/src/PolycarpQuadMinmax.cpp | 56baa25f951c615b91fd7714a74cf03d74b79ac3 | [
"LicenseRef-scancode-us-govt-public-domain"
] | permissive | johndpope/icarous | 3fb4c3cf72ab1d5e676393e380b6da71db848205 | 6a1ffc94eba053bf186c21997ffac411f8b1cff6 | refs/heads/master | 2020-06-10T19:53:12.719610 | 2016-11-29T03:54:23 | 2016-11-29T03:54:23 | 75,891,609 | 1 | 0 | null | 2016-12-08T01:38:40 | 2016-12-08T01:38:40 | null | UTF-8 | C++ | false | false | 1,227 | cpp | /*
* PolycarpQuadMinmax - determining if a univariate quadratic passes below a threshold on an interval
*
* Contact: Anthony Narkawicz (anthony.narkawicz@nasa.gov), George Hagen (george.hagen@nasa.gov)
*
* Copyright (c) 2015-2016 United States Government as represented by
* the National Aeronautics and Space Administration. No copyright
* is claimed in the United States under Title 17, U.S.Code. All Other
* Rights Reserved.
*/
#include "PolycarpQuadMinmax.h"
namespace larcfm {
double PolycarpQuadMinmax::quadratic(double a,double b,double c,double x) {
return a*x*x+b*x+c;
}
double PolycarpQuadMinmax::quad_min_int(double a,double b,double c,double xl,double xu) {
if ((a<=0 && quadratic(a,b,c,xl)>=quadratic(a,b,c,xu))) return xu;
else if (a<=0) return xl;
else if (2*a*xl<=-b && -b<=2*a*xu) return -b/(2*a);
else if (-b<2*a*xl) return xl;
else return xu;
}
bool PolycarpQuadMinmax::quad_min_le_D_int(double ap,double b,double c,double xl,double xu,double D) {
if (xl>xu) return false;
else if (2*ap*xl<=-b && -b<=2*ap*xu) return (b*b-4*ap*(c-D)>0);
else if (quadratic(ap,b,c-D,xl)<0 || quadratic(ap,b,c-D,xu)<0) return true;
else return false;
}
}
| [
"cesaramh@gmail.com"
] | cesaramh@gmail.com |
e8ad5cc1dc2484cb32172a6afdece4ed430f3c17 | a57017ad34617494c3ade1d1276e57ef884fc500 | /Asteroids/Asteroids/Asteroids/Collision.cpp | f3dfa8f3b072b5ea7e308e5a69c1a360bc9089ca | [] | no_license | ledgerdamayn/asteroids | 95ee983241fd3085e5233aef3d610c1cee077b6a | 8cfc032fb224da3232d45f7bfbff890c979bc221 | refs/heads/master | 2021-01-01T16:34:18.319335 | 2014-10-24T21:12:47 | 2014-10-24T21:12:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,298 | cpp | #ifdef _M_IX86
#include <windows.h>
#else
#include <stream.h>
#endif
#define _USE_MATH_DEFINES
#include <GL/gl.h>
#include <GL/glu.h>
#include <glut.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include "Collision.h"
#include <iostream>
namespace Asteroids {
bool point_in_circle( float point[3] , float center[3] , float radius ) {
float distance = sqrt( pow( point[0] - center[0] , 2 ) + pow( point[1] - center[1] , 2 ) );
return ( distance <= radius );
}
bool line_segment_in_circle( Vertex * v1 , Vertex * v2 , float center[3] , float radius ) {
float d_x = v2->x() - v1->x();
float d_y = v2->y() - v1->y();
float d = pow( d_x , 2 ) + pow( d_y , 2 );
float d2 = ( v1->x() - center[0] ) * ( v2->y() - center[1] ) - ( v2->x() - center[0] ) * ( v1->y() - center[1] );
float delta = pow( radius , 2 ) * d - pow( d2 , 2 );
// if ( delta >= 0.0f )
// std::cout << delta << " " << center[0] << " " << center[1] << " " << radius << "\n";
if ( delta < 0.0f )
return false;
else {
float sign_d_y = ( d_y < 0.0f ) ? -1.0f : 1.0f;
float x1 = ( d2 * d_y + sign_d_y * d_x * sqrt( delta ) ) / d;
float x2 = ( d2 * d_y - sign_d_y * d_x * sqrt( delta ) ) / d;
float y1 = ( -1.0f * d2 * d_x + abs( d_y ) * sqrt( delta ) ) / d;
float y2 = ( -1.0f * d2 * d_x - abs( d_y ) * sqrt( delta ) ) / d;
if ( point_on_line_segment( x1 , y1 , v1 , v2 ) || point_on_line_segment( x2 , y2 , v1 , v2 ) )
return true;
}
return false;
}
bool point_on_line_segment( float x , float y , Vertex * v1 , Vertex * v2 ) {
float cross_product = ( y - v1->y() ) * ( v2->x() - v1->x() ) - ( x - v1->x() ) * ( v2->y() - v1->y() );
// std::cout << x << " " << y << "\n";
// std::cout << cross_product << "\n";
if ( abs( cross_product ) > 0.0000001f )
return false;
float dot_product = ( x - v1->x() ) * ( v2->x() - x ) + ( y - v1->y() ) * ( v2->y() - y );
if ( dot_product < 0.0f )
return false;
float squared_length = pow( ( v2->x() - v1->x() ) , 2 ) + pow( ( v2->y() - v1->y() ) , 2 );
if ( dot_product > squared_length )
return false;
return true;
}
bool line_segment_intersection( Vertex * v1_1 , Vertex * v1_2 , Vertex * v2_1 , Vertex * v2_2 ) {
float d = ( v2_2->y() - v2_1->y() ) * ( v1_2->x() - v1_1->x() ) - ( v2_2->x() - v2_1->x() ) * ( v1_2->y() - v1_1->y() );
float t1 = ( v2_2->x() - v2_1->x() ) * ( v1_1->y() - v2_1->y() ) - ( v2_2->y() - v2_1->y() ) * ( v1_1->x() - v2_1->x() );
float t2 = ( v1_2->x() - v1_1->x() ) * ( v1_1->y() - v2_1->y() ) - ( v1_2->y() - v1_1->y() ) * ( v1_1->x() - v2_1->x() );
if ( d == 0 )
return ( t1 == 0 || t2 == 0 );
t1 /= d;
t2 /= d;
return ( t1 > 0 && t1 < 1 && t2 > 0 && t2 < 1 );
}
// TO-DO: Prevent creation of repeated Vertex objects
bool point_in_triangle( Vertex * point , Triangle * triangle ) {
int intersections = 0;
Vertex * v = new Vertex( 100000.0f , 100000.0f , 0 );
if ( line_segment_intersection( point , v , triangle->v[0] , triangle->v[1] ) )
intersections += 1;
if ( line_segment_intersection( point , v , triangle->v[1] , triangle->v[2] ) )
intersections += 1;
if ( line_segment_intersection( point , v , triangle->v[2] , triangle->v[0] ) )
intersections += 1;
return ( intersections % 2 != 0 );
}
} | [
"kcsalvad@ncsu.edu"
] | kcsalvad@ncsu.edu |
8300b6ad0320773aa27f7f978217b96f61e57d08 | 3e4bf27bec8ff26a28e9d89c2dae5d1d8b55a696 | /hackerrank/10_days_of_statistics/day8/01_least_square_regression_line.cpp | ea695018cce1ac38d26f77e521ada023a80813c8 | [] | no_license | ixomaxip/cpp | 40c31482d28db4083edefcb8c4a49ec4a075b046 | 706f2d5939eabb19c6dbcf68a42c1aba8c309977 | refs/heads/master | 2021-06-26T04:19:58.710000 | 2020-12-08T18:50:34 | 2020-12-08T18:50:34 | 184,742,617 | 0 | 0 | null | 2020-12-08T18:10:05 | 2019-05-03T11:14:29 | C++ | UTF-8 | C++ | false | false | 1,723 | cpp | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <string>
#include <sstream>
using namespace std;
double mean(const vector<double>& arr) {
int sum = 0;
for (auto& i : arr) {
sum += i;
}
return sum / double(arr.size());
}
double stddev(const vector<double>& arr) {
double m = mean(arr);
double sum = 0.0;
for (const auto& i : arr) {
double x = i - m;
sum += x * x;
}
return sqrt(sum / arr.size());
}
double cov(const vector<double>& X, const vector<double>& Y, const size_t N) {
double mX = mean(X);
double mY = mean(Y);
double sum = 0;
for (size_t i = 0; i < N; i++) {
sum += (X[i] - mX) * (Y[i] - mY);
}
return sum / N;
}
class linear_model
{
public:
linear_model() {};
~linear_model() {};
void fit(const vector<double>& X, const vector<double>& Y, size_t N) {
double sdX = stddev(X);
double mX = mean(X);
double mY = mean(Y);
this->intercept = cov(X, Y, N) / sdX / sdX;
this->coeff = mY - this->intercept * mX;
return;
}
double predict(double x) {
return this->intercept * x + this->coeff;
}
double intercept;
double coeff;
};
int main() {
size_t N = 5;
// vector<double> X = {1, 2, 3, 4, 5};
// vector<double> Y = {2, 1, 4, 3, 5};
vector<double> X, Y;
for (size_t i = 0; i < N; i++) {
double x, y;
cin >> x >> y;
X.push_back(x);
Y.push_back(y);
}
linear_model lm;
lm.fit(X, Y, N);
double pred = lm.predict(80);
cout << fixed << setprecision(3);
cout << pred << endl;
return 0;
}
| [
"max.white.rabbit@gmail.com"
] | max.white.rabbit@gmail.com |
297b162f067e4a2443a58b1b5b8e5e10a03504bd | d7ef1300dc1b4d6174788605bf2f19ece12a1708 | /other/old_scripts/fitting/bw_test.cxx | e9e074aed6a63f40958719960ad306a7f6f5605d | [] | no_license | libov/zeus | 388a2d49eb83f098c06008cb23b6ab42ae42e0e5 | a0ca857ede59c74cace29924503d78670e10fe7b | refs/heads/master | 2021-01-01T05:51:48.516178 | 2014-12-03T09:14:02 | 2014-12-03T09:14:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 776 | cxx | Double_t bw(Double_t *x,Double_t *par)
{
Double_t M=par[0]; // peak position
Double_t G=par[1]; // peak width
Double_t m=x[0]; // function variable
Double_t ReBW=0, // Real part of ith peak
ImBW=0, // Imaginary part of ith peak
den=0; // denominator of ith peak
Double_t temp1=0,
temp2=0;
temp1=M*M-m*m;
temp2=M*sqrt(G);
den=TMath::Power(temp1,2)+TMath::Power((M*G),2);
ReBW=(temp1*temp2)/den;
ImBW=(temp2*M*G)/den;
Double_t total=0;
total=par[2]*(ReBW**2+ImBW**2);
return total;
}
int bw_test()
{
TF1 *bw1=new TF1("bw1",bw,0,3,3);
Double_t par[50];
par[0]=1.3;
par[1]=0.184;
par[2]=1.;
bw1->SetParameters(&par[0]);
cout<<"Area= "<<bw1->Integral(par[0]-3*par[1],par[0]+3*par[1])<<endl;
bw1->Draw("l");
return 0;
} | [
"libov@mail.desy.de"
] | libov@mail.desy.de |
2c3025ae87b79634374e87d0e388cd787d184a8c | 6812289a29e83597df6011c8a3c46c0328e4420b | /include/CTRPluginFramework/System/Hook.hpp | 9d5337f3e5e06a356c123c39dd37de9f178b96b6 | [] | no_license | Zetta-D/libctrpf-0.7.0 | 2ba94a5329a7809fe91524bf4821d25ff22d61c3 | 75944c183528aadb083c7275655c507d20f642a9 | refs/heads/main | 2023-04-13T12:09:15.633167 | 2021-04-11T11:24:13 | 2021-04-11T11:24:13 | 356,829,480 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,299 | hpp | #ifndef CTRPLUGINFRAMEWORK_SYSTEM_HOOK_H
#define CTRPLUGINFRAMEWORK_SYSTEM_HOOK_H
#include "types.h"
#include <type_traits>
namespace CTRPluginFramework
{
enum
{
USE_LR_TO_RETURN = 1 << 0, ///< Enable the use of bx lr to return from callback. LR will be properly restored after the callback is executed
EXECUTE_OI_BEFORE_CB = 1 << 1, ///< If the instruction overwritten by the hook (target) must be executed before the callback
EXECUTE_OI_AFTER_CB = 1 << 2, ///< If the instruction overwritten by the hook (target) must be executed after the callback
MITM_MODE = 1 << 3, ///< This mode is perfect to intercepts functions calls
WRAP_SUB = 1 << 4, ///< Wraps a subroutine call
HOOK_DEFAULT_PARAMS = USE_LR_TO_RETURN | EXECUTE_OI_BEFORE_CB,
};
enum class HookResult
{
Success,
InvalidContext, ///< The HookContext obj linked to the Hook obj is invalid (Should not happen)
InvalidAddress, ///< The target address was not reachable
AddressAlreadyHooked, ///< A hook is already enabled to the same address
TooManyHooks, ///< You attained the maximum of enabled hooks (current limit: 91)
HookParamsError, ///< The parameters of your hook seems off
TargetInstructionCannotBeHandledAutomatically, ///< The target's instruction is position dependent (PC) hence using ExecuteOverwrittenInstructionBeforeCallback or ExecuteOverwrittenInstructionAfterCallback is impossible.
};
struct HookContext
{
s32 refcount;
u32 flags;
u32 targetAddress;
u32 returnAddress;
u32 callbackAddress;
u32 callbackAddress2;
u32 overwrittenInstr;
u32 index;
// Bunch of functions to be used inside a hook's function body
static HookContext& GetCurrent(void);
// The functions below are to be used only with MITM_MODE hooks
template <typename TResult, typename... Args>
typename std::enable_if<!std::is_same<TResult, void>::value, TResult>::type
OriginalFunction(Args... args)
{
using FPtr = TResult(*)(Args...);
FPtr fptr = reinterpret_cast<FPtr>(GetCallCode());
if (fptr)
return fptr(args...);
return (TResult)fptr;
}
template <typename TResult, typename... Args>
typename std::enable_if<std::is_same<TResult, void>::value, void>::type
OriginalFunction(Args... args)
{
using FPtr = void(*)(Args...);
FPtr fptr = reinterpret_cast<FPtr>(GetCallCode());
if (fptr)
fptr(args...);
}
private:
void *GetCallCode(void);
};
struct Hook
{
Hook(void);
// Warning: copies share the same HookContext
Hook(const Hook& hook);
Hook(Hook&& hook) noexcept;
Hook& operator=(const Hook& hook);
Hook& operator=(Hook&& hook) noexcept;
~Hook(void);
/**
* \brief Initialize hook target and callback. Hook's return address is set to targetAddr + 4
* \param targetAddr The address to hook to
* \param callbackAddr The callback to be called by the hook
* \return A reference to Hook obj
*/
Hook& Initialize(u32 targetAddr, u32 callbackAddr);
/**
* \brief Initialize a hook for mitm mode (apply the required flags)
* \param targetAddr The address to hook to
* \param callbackAddr The callback to be called by the hook
* \return A reference to Hook obj
*/
Hook& InitializeForMitm(u32 targetAddr, u32 callbackAddr);
/**
* \brief Initialize a hook for subroutine wrapping (apply the required flags)
* \param targetAddr The address with the subroutine call to wrap (BL only)
* \param beforeCallback The callback to be called before the subroutine (can be null)
* \param afterCallback The callback to be called after the subroutine (can be null)
* \return A reference to Hook obj
*/
Hook& InitializeForSubWrap(u32 targetAddr, u32 beforeCallback, u32 afterCallback);
/**
* \brief Apply the specified flags to the hook. Must be done before enabling the hook otherwise nothing happens
* \param flags The new hook settings
* \return A reference to the Hook obj
*/
Hook& SetFlags(u32 flags);
/**
* \brief Set the return address of the hook (default: target + 4)
* \param returnAddr The address for the hook to return to
* \return A reference to the Hook obj
*/
Hook& SetReturnAddress(u32 returnAddr);
/**
* \brief Check if the hook is applied or not
* \return true if the hook is applied, false otherwise
*/
bool IsEnabled(void);
/**
* \brief Apply the hook
* \return Return the result of the operation (see HookResult for more infos)
*/
HookResult Enable(void);
/**
* \brief Disable the hook
* \return Return the result of the operation (see HookResult for more infos)
*/
HookResult Disable(void);
const HookContext& GetContext(void) const;
private:
HookContext *_ctx;
};
// Bunch of functions to be used inside a hook's function body (asm)
extern "C"
{
/**
* \brief Get a pointer to the current hook's context (see HookContext)
* \return A pointer to current HookContext
*/
void * ctrpfHook__GetCurrent(void);
/**
* \brief Execute the original function. Only available for mitm hooks.
* If the function takes some args, just set the registers accordingly
* \return return value of original function
*/
void * ctrpfHook__ExecuteOriginalFunction(void);
}
}
#endif
| [
"noreply@github.com"
] | Zetta-D.noreply@github.com |
437a499e179fc612fa7c6698a4c91c66d6401147 | c69118b46cdc2b7b6560debbeb8f8a67a9693ce9 | /Onyx/src/GraphicSystem.cpp | 5f52c3ff6cf67575d766d37a7dff57e92fa1e4a7 | [] | no_license | MrShedman/Onyx | 50c9f6fb2cd71ed97ba57e50307d6449483a6ca9 | 7cdab90ecf52eca7d7a528bc5b8e0b9af29825c1 | refs/heads/master | 2021-04-26T23:38:33.653141 | 2018-03-04T21:14:33 | 2018-03-04T21:14:33 | 123,829,588 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 750 | cpp | #include "GraphicSystem.hpp"
#include "SFML\Window\Window.hpp"
void GraphicSystem::init(sf::Window* window)
{
this->window = window;
// Enable Z-buffer read and write
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL); // for wireframe rendering
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_MULTISAMPLE);
std::cout << "\nLoading Shaders..." << std::endl;
if (!modelShader.loadFromFile("./res/shaders/model.vert", "./res/shaders/model.frag"))
{
}
camera.init(window);
camera.setPosition(0.5f, 0.75f, 1.6f);
camera.rotate(Vector3f::yAxis(), degrees(180));
camera.rotate(Vector3f::xAxis(), degrees(-20));
ground.create();
}
void GraphicSystem::render()
{
ground.render(modelShader, camera);
} | [
"roscoacer@googlemail.com"
] | roscoacer@googlemail.com |
f97ad39bdae69226b25ebf6d87d31d34b4338c54 | fc0725b0841099b52266012f4d362ddbde7be195 | /pixel/pixel/audio/audio.h | b76c83d23afd1d9a2608d50e614ee1cdfb1e93d0 | [] | no_license | antiomiae/pixel | 6118671c8cb59c12fbc969fdf654ad0d5f6e7afe | 377fb8e9e8ebd951c628183d4752b3289735eb92 | refs/heads/master | 2021-04-27T12:07:25.385742 | 2019-03-15T03:23:44 | 2019-03-15T03:23:44 | 122,574,251 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,399 | h |
#ifndef PIXEL_MAIN_AUDIO_CONTROLLER_H
#define PIXEL_MAIN_AUDIO_CONTROLLER_H
#include <soloud.h>
#include <soloud_wav.h>
#include <soloud_wavstream.h>
#include <unordered_map>
#include <string>
#include <memory>
namespace pixel
{
class AudioCache
{
public:
AudioCache() = default;
private:
};
class AudioController
{
public:
AudioController() = default;
AudioController(const AudioController&) = delete;
void init()
{
engine_.init();
}
SoLoud::handle play(SoLoud::AudioSource& source)
{
return engine_.play(source);
}
void set_background_music(const std::string& path)
{
auto& source_ptr = source_cache_[path];
if (!source_ptr) {
source_ptr = std::make_unique<SoLoud::WavStream>();
static_cast<SoLoud::WavStream&>(*source_ptr).load(path.c_str());
source_ptr->setLooping(1);
}
engine_.stop(background_music_voice_handle_);
background_music_voice_handle_ = engine_.play(*source_ptr);
engine_.setProtectVoice(background_music_voice_handle_, true);
}
~AudioController()
{
engine_.deinit();
}
private:
SoLoud::Soloud engine_{};
std::unordered_map<std::string, std::unique_ptr<SoLoud::AudioSource>> source_cache_{};
SoLoud::handle background_music_voice_handle_;
};
};
#endif //PIXEL_MAIN_AUDIO_CONTROLLER_H
| [
"antiomiae@gmail.com"
] | antiomiae@gmail.com |
5ec310af1fd53e140f68e585fd3c858ea20a5766 | 136ba41aad52da9b40fe4a44c7e8edae1efad783 | /lib/multiply_const_impl.cc | a0c5cfce4512d3839ad30e33fb0417c182439ff8 | [] | no_license | mfkiwl/gr-cuda | c2cab5e198a99effce6b8648b20f1c4fc6373474 | d877d45121a6b65b5056e575eca8c236d0aec733 | refs/heads/main | 2023-08-26T01:43:32.237936 | 2021-11-03T12:36:33 | 2021-11-03T12:36:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,345 | cc | /* -*- c++ -*- */
/*
* Copyright 2021 Josh Morman.
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
#include "multiply_const_impl.h"
#include <gnuradio/io_signature.h>
#include <gnuradio/cuda/cuda_error.h>
#include <gnuradio/cuda/cuda_buffer.h>
template <typename T>
void exec_kernel_multiply_const(const T* in,
T* out,
T k,
int grid_size,
int block_size,
size_t n,
cudaStream_t stream);
template <typename T>
void get_block_and_grid(int* minGrid, int* minBlock);
namespace gr {
namespace cuda {
template <class T>
typename multiply_const<T>::sptr multiply_const<T>::make(T k, size_t vlen)
{
return gnuradio::make_block_sptr<multiply_const_impl<T>>(k, vlen);
}
template <class T>
multiply_const_impl<T>::multiply_const_impl(T k, size_t vlen)
: gr::sync_block("multiply_const",
io_signature::make(1, 1, sizeof(T) * vlen, cuda_buffer::type),
io_signature::make(1, 1, sizeof(T) * vlen, cuda_buffer::type)),
d_k(k),
d_vlen(vlen)
{
get_block_and_grid<T>(&d_min_grid_size, &d_block_size);
check_cuda_errors(cudaStreamCreate(&d_stream));
}
template <class T>
int multiply_const_impl<T>::work(int noutput_items,
gr_vector_const_void_star& input_items,
gr_vector_void_star& output_items)
{
auto in = static_cast<const T*>(input_items[0]);
auto out = static_cast<T*>(output_items[0]);
int gridSize = (noutput_items + d_block_size - 1) / d_block_size;
exec_kernel_multiply_const<T>(in,
out,
d_k,
gridSize,
d_block_size,
noutput_items,
d_stream);
cudaStreamSynchronize(d_stream);
// Tell runtime system how many output items we produced.
return noutput_items;
}
template class multiply_const<std::int16_t>;
template class multiply_const<std::int32_t>;
template class multiply_const<float>;
template class multiply_const<gr_complex>;
} /* namespace cuda */
} /* namespace gr */
| [
"jmorman@gnuradio.org"
] | jmorman@gnuradio.org |
2addf1508019f88d2b36b64826b4092205d0c99e | 895c9e22ca063119e5ddeeb99067b3089c190d31 | /Binary_search/Search_for_a_Range.cpp | 80f443800b417f1482e67233ef98b606d7e9abe5 | [] | no_license | shivamgoel008/Data-Structure-and-Algorithms | 5c543877c6201d89de5a5393d748fa27025282b1 | 82b4694a92f8383ae867b98f2e0f2e6bfbe862b1 | refs/heads/main | 2023-08-22T20:06:20.270832 | 2021-10-09T06:02:04 | 2021-10-09T06:02:04 | 352,412,307 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,230 | cpp | vector<int> Solution::searchRange(const vector<int> &v, int key) {
int first,second,n;
n=v.size();
vector<int>ans;
if(v.size()==0){
ans.push_back(-1);
ans.push_back(-1);
return ans;
}
int lower=-1;
first=0;
second=n-1;
while(first<=second)
{
int mid=(first+second)/2;
if(v[mid]==key and mid>=0)
{
lower=mid;
second=mid-1;
}
else if(v[mid]<key)
first=mid+1;
else if(v[mid]>key)
second=mid-1;
}
int upper=-1;
first=0;
second=n-1;
while(first<=second)
{
int mid=(first+second)/2;
if(v[mid]==key and mid>=0)
{
upper=mid;
first=mid+1;
}
else if(v[mid]<key)
first=mid+1;
else if(v[mid]>key)
second=mid-1;
}
// cout<<lower<<" "<<upper<<endl;
ans.push_back(lower);
ans.push_back(upper);
return ans;
}
| [
"55030452+shivamgoel008@users.noreply.github.com"
] | 55030452+shivamgoel008@users.noreply.github.com |
a1a7f04a59e289e2aa8cd4fb1cd59c7e0e177447 | da0617f2fec242846d5153c05752d61c25070ad8 | /http_server/stack/server/AWSHttpServerSocketFactory.h | 6cccf57b2a877dc613d2514710e0b63af606125e | [
"BSD-3-Clause"
] | permissive | aaronshang/duderino | 3fb8b360b685809245303db7aa4958fb97f0cc00 | 9479b4efa3735289c404cf5e1a865d2101c17fa5 | refs/heads/master | 2020-12-25T04:30:13.325522 | 2013-05-13T20:29:52 | 2013-05-13T20:29:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,496 | h | /* Copyright (c) 2009 Yahoo! Inc. All rights reserved.
* The copyrights embodied in the content of this file are licensed by Yahoo! Inc.
* under the BSD (revised) open source license.
*/
#ifndef AWS_HTTP_SERVER_SOCKET_FACTORY_H
#define AWS_HTTP_SERVER_SOCKET_FACTORY_H
#ifndef AWS_HTTP_SERVER_SOCKET_H
#include <AWSHttpServerSocket.h>
#endif
#ifndef ESF_EMBEDDED_LIST_H
#include <ESFEmbeddedList.h>
#endif
#ifndef ESF_MUTEX_H
#include <ESFMutex.h>
#endif
#ifndef ESF_DISCARD_ALLOCATOR_H
#include <ESFDiscardAllocator.h>
#endif
#ifndef AWS_HTTP_SERVER_COUNTERS_H
#include <AWSHttpServerCounters.h>
#endif
#ifndef AWS_HTTP_SERVER_HANDLER_H
#include <AWSHttpServerHandler.h>
#endif
/** A factory that creates and reuses AWSHttpServerSockets
*/
class AWSHttpServerSocketFactory
{
public:
AWSHttpServerSocketFactory(AWSHttpServerCounters *counters,
ESFLogger *logger);
virtual ~AWSHttpServerSocketFactory();
ESFError initialize();
void destroy();
AWSHttpServerSocket *create(AWSHttpServerHandler *handler, ESFTCPSocket::AcceptData *acceptData);
void release(AWSHttpServerSocket *socket);
/** Placement new.
*
* @param size The size of the object.
* @param allocator The source of the object's memory.
* @return Memory for the new object or NULL if the memory allocation failed.
*/
inline void *operator new(size_t size, ESFAllocator *allocator)
{
return allocator->allocate( size );
}
private:
// Disabled
AWSHttpServerSocketFactory(const AWSHttpServerSocketFactory &);
AWSHttpServerSocketFactory &operator=(const AWSHttpServerSocketFactory &);
class CleanupHandler : public ESFCleanupHandler
{
public:
/** Constructor
*/
CleanupHandler(AWSHttpServerSocketFactory *factory);
/** Destructor
*/
virtual ~CleanupHandler();
/** Destroy an object
*
* @param object The object to destroy
*/
virtual void destroy(ESFObject *object);
private:
// Disabled
CleanupHandler(const CleanupHandler &);
void operator=(const CleanupHandler &);
AWSHttpServerSocketFactory *_factory;
};
ESFLogger *_logger;
AWSHttpServerCounters *_counters;
ESFDiscardAllocator _allocator;
ESFEmbeddedList _embeddedList;
ESFMutex _mutex;
CleanupHandler _cleanupHandler;
};
#endif /* ! AWS_HTTP_SERVER_SOCKET_FACTORY_H */
| [
"jtblatt@yahoo.com"
] | jtblatt@yahoo.com |
123223608ba1c60c3cbbb07f9e0b86975a773b44 | d27c930671d65f65132eeb19d02caf26b22a6f21 | /Sort/QuickSort/test.cpp | 3ac0ca01a4567b63e447806b3372cba941975e6c | [] | no_license | dengxinlong/DataStructure_zuochengyun | adedd32da8fadcbdd057a001b34fcd77231b4c24 | c44fa4b851f69314b12f36d3dedf476252213993 | refs/heads/master | 2023-01-06T02:06:27.683796 | 2020-11-04T06:48:51 | 2020-11-04T06:48:51 | 263,318,156 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 246 | cpp | #include <time.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
using namespace std;
int main(void)
{
srand(time(NULL));
for (int i = 0; i < 10; i++) {
cout << rand() % 10 / 10.0 << " ";
}
cout << endl;
}
| [
"1552549826@qq.com"
] | 1552549826@qq.com |
ae963d13d0d0d7be152af2157e54398e730d26b0 | 0ef832d8eaedc16253cc220bc704a52597d248fe | /newntui/activex/datasource/src/datasource.cpp | 6310e95e3a090d92c52d6e1d2d3c9de4a9f47757 | [
"BSD-2-Clause"
] | permissive | radtek/software-emancipation-discover | 9c0474b1abe1a8a3f91be899a834868ee0edfc18 | bec6f4ef404d72f361d91de954eae9a3bd669ce3 | refs/heads/master | 2020-05-24T19:03:26.967346 | 2015-11-21T22:23:54 | 2015-11-21T22:23:54 | 187,425,106 | 1 | 0 | BSD-2-Clause | 2019-05-19T02:26:08 | 2019-05-19T02:26:07 | null | UTF-8 | C++ | false | false | 3,904 | cpp | /*************************************************************************
* Copyright (c) 2015, Synopsys, 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS *
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR *
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT *
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, *
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT *
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, *
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY *
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE *
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
*************************************************************************/
// DataSource.cpp : Implementation of CDataSourceApp and DLL registration.
#include "stdafx.h"
#include "DataSource.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
CDataSourceApp NEAR theApp;
const GUID CDECL BASED_CODE _tlid =
{ 0x77b20db, 0x934, 0x11d2, { 0xae, 0xe6, 0, 0xa0, 0xc9, 0xb7, 0x1d, 0xc4 } };
const WORD _wVerMajor = 1;
const WORD _wVerMinor = 0;
////////////////////////////////////////////////////////////////////////////
// CDataSourceApp::InitInstance - DLL initialization
BOOL CDataSourceApp::InitInstance()
{
BOOL bInit = COleControlModule::InitInstance();
if (bInit)
{
// TODO: Add your own module initialization code here.
}
return bInit;
}
////////////////////////////////////////////////////////////////////////////
// CDataSourceApp::ExitInstance - DLL termination
int CDataSourceApp::ExitInstance()
{
// TODO: Add your own module termination code here.
return COleControlModule::ExitInstance();
}
/////////////////////////////////////////////////////////////////////////////
// DllRegisterServer - Adds entries to the system registry
STDAPI DllRegisterServer(void)
{
AFX_MANAGE_STATE(_afxModuleAddrThis);
if (!AfxOleRegisterTypeLib(AfxGetInstanceHandle(), _tlid))
return ResultFromScode(SELFREG_E_TYPELIB);
if (!COleObjectFactoryEx::UpdateRegistryAll(TRUE))
return ResultFromScode(SELFREG_E_CLASS);
return NOERROR;
}
/////////////////////////////////////////////////////////////////////////////
// DllUnregisterServer - Removes entries from the system registry
STDAPI DllUnregisterServer(void)
{
AFX_MANAGE_STATE(_afxModuleAddrThis);
if (!AfxOleUnregisterTypeLib(_tlid, _wVerMajor, _wVerMinor))
return ResultFromScode(SELFREG_E_TYPELIB);
if (!COleObjectFactoryEx::UpdateRegistryAll(FALSE))
return ResultFromScode(SELFREG_E_CLASS);
return NOERROR;
}
| [
"ktransue@synopsys.com"
] | ktransue@synopsys.com |
af0b000488048b0e676d930f67212d5ca9e295dd | 6981101706ebd1e0637ae041f43ff3b853650c22 | /BWDI/PlayerType.h | 7ce38c50ebf518f1b45358c02a46ea9866939424 | [] | no_license | RadicalZephyr/bwdi | 2eaddbd67d189e0712922852dda5934a46ff1438 | d984fdb3f4addfbf69013fb4275c5a2dd5cc7f49 | refs/heads/master | 2021-01-10T18:31:08.030935 | 2011-08-22T23:36:35 | 2011-08-22T23:36:35 | 2,251,731 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 127 | h | #pragma once
#include <Util\StaticString.h>
namespace BWDI
{
struct PlayerType
{
Util::StaticString<32> name;
};
}
| [
"earthlingzephyr@gmail.com"
] | earthlingzephyr@gmail.com |
fe569ac17af4a26581c6f79bbcb67db332205345 | e697163a3846548b43b81c3e3eed16339305531d | /xContests/535/c.cpp | 16723d55217c9772b0b30c6342bb28bb76fb602e | [] | no_license | cgupta3131/CodeForces_CC | 259ba08d91bd8d495a516c5dc6b408461fdfe6d9 | b6ac266d3ab0f60949c52905de026e9b171db868 | refs/heads/master | 2020-03-28T02:02:28.325624 | 2019-07-24T19:35:31 | 2019-07-24T19:35:31 | 147,543,471 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,316 | cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unordered_map<int, int> umapii;
typedef unordered_map<int, bool> umapib;
typedef unordered_map<string, int> umapsi;
typedef unordered_map<string, string> umapss;
typedef map<string, int> mapsi;
typedef map<pair<int, int>, int> mappiii;
typedef map<int, int> mapii;
typedef map<int, bool> mapib;
typedef pair<int, int> pii;
typedef pair<pii,int> ppi;
typedef pair<long long, long long> pll;
typedef unordered_set<int> useti;
typedef set<int> seti;
#define uset unordered_set
#define it iterator
#define mp make_pair
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define allp(x) (x)->begin(), (x)->end()
#define f first
#define s second
#define MOD 1000000007
//cin.ignore(numeric_limits<streamsize>::max(), '\n'); -> Clears the input buffer
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n;
cin >> n;
string s;
cin >> s;
if(n == 1)
{
cout << 0 << endl;
cout << s << endl;
return 0;
}
if(n == 2)
{
if(s[0] == s[1])
{
cout << 1 << endl;
if(s[0] == 'G')
cout << "GB" << "\n";
else if(s[0] == 'B')
cout << "BR" << "\n";
else if(s[0] == 'R')
cout << "RG" << "\n";
return 0;
}
else
{
cout << 0 << endl;
cout << s << endl;
return 0;
}
}
int max = -1;
int conf = -1;
int count = 0;
for(int i=0;i<n;i++)
{
if(i%3 == 0 && s[i] == 'R')
count++;
if(i%3 == 1 && s[i] == 'G')
count++;
if(i%3 == 2 && s[i] == 'B')
count++;
}
if(count > max)
{
max = count;
conf = 1;
}
count = 0;
for(int i=0;i<n;i++)
{
if(i%3 == 0 && s[i] == 'R')
count++;
if(i%3 == 2 && s[i] == 'G')
count++;
if(i%3 == 1 && s[i] == 'B')
count++;
}
if(count > max)
{
max = count;
conf = 2;
}
count = 0;
for(int i=0;i<n;i++)
{
if(i%3 == 1 && s[i] == 'R')
count++;
if(i%3 == 0 && s[i] == 'G')
count++;
if(i%3 == 2 && s[i] == 'B')
count++;
}
if(count > max)
{
max = count;
conf = 3;
}
count = 0;
for(int i=0;i<n;i++)
{
if(i%3 == 1 && s[i] == 'R')
count++;
if(i%3 == 2 && s[i] == 'G')
count++;
if(i%3 == 0 && s[i] == 'B')
count++;
}
if(count > max)
{
max = count;
conf = 4;
}
count = 0;
for(int i=0;i<n;i++)
{
if(i%3 == 2 && s[i] == 'R')
count++;
if(i%3 == 0 && s[i] == 'G')
count++;
if(i%3 == 1 && s[i] == 'B')
count++;
}
if(count > max)
{
max = count;
conf = 5;
}
count = 0;
for(int i=0;i<n;i++)
{
if(i%3 == 2 && s[i] == 'R')
count++;
if(i%3 == 1 && s[i] == 'G')
count++;
if(i%3 == 0 && s[i] == 'B')
count++;
}
if(count > max)
{
max = count;
conf = 6;
}
cout << n - max << endl;
if(conf == 1)
{
for(int i=0;i<n;i++)
{
if(i%3==0)
cout << "R";
else if(i%3 == 1)
cout << "G";
else
cout << "B";
}
cout << endl;
}
if(conf == 2)
{
for(int i=0;i<n;i++)
{
if(i%3==0)
cout << "R";
else if(i%3 == 2)
cout << "G";
else
cout << "B";
}
cout << endl;
}
if(conf == 3)
{
for(int i=0;i<n;i++)
{
if(i%3==1)
cout << "R";
else if(i%3 == 0)
cout << "G";
else
cout << "B";
}
cout << endl;
}
if(conf == 4)
{
for(int i=0;i<n;i++)
{
if(i%3==1)
cout << "R";
else if(i%3 == 2)
cout << "G";
else
cout << "B";
}
cout << endl;
}
if(conf == 5)
{
for(int i=0;i<n;i++)
{
if(i%3==2)
cout << "R";
else if(i%3 == 0)
cout << "G";
else
cout << "B";
}
cout << endl;
}
if(conf == 6)
{
for(int i=0;i<n;i++)
{
if(i%3==2)
cout << "R";
else if(i%3 == 1)
cout << "G";
else
cout << "B";
}
cout << endl;
}
return 0 ;
}
| [
"cgupta3131@gmail.com"
] | cgupta3131@gmail.com |
0a347797d3e29549a31e198bd103c7755c9778d8 | b16236a633a566d171ec069bfa36cb7116a191d2 | /project1/scanner.cpp | ac64fd9aff0223b151c258066ae7e7ecea77fd45 | [] | no_license | daralim1987/cmpsci4280 | 273ee7cbe833ee2d6d3259660a4adf79c0964eb9 | fd8837d9915115d32e315876f41a7e306dfbbe98 | refs/heads/master | 2020-11-25T23:17:17.670787 | 2019-12-18T17:02:33 | 2019-12-18T17:02:33 | 228,886,221 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 193 | cpp | /* Dara Lim */
/* CS4280 */
/* Project 1 */
#include <string>
#include "token.h"
#include "scanner.h"
using namespace std;
Token scanner(string s)
{
Token token (s);
return token;
}
| [
"daralim97@yahoo.com"
] | daralim97@yahoo.com |
923f6db961826f835540a548ca055dc74f3649a6 | d51674480aad7fb6a5a954271b14e565711c1113 | /ARGameTests/BulletDynamics/ConstraintSolver/btContactConstraint.cpp | 6da45eb73d1798cf62097e349f3eaec707dac072 | [] | no_license | cedricfoucault/AsteRoids | 9e91198525579e20393e60b22df71c331892aa2c | 43ded100505e3c949b3655825672c07c936423bf | refs/heads/master | 2021-01-10T21:30:03.609152 | 2014-10-15T03:36:20 | 2014-10-15T03:36:20 | 20,145,265 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,643 | cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btContactConstraint.h"
#include "btRigidBody.h"
#include "btVector3.h"
#include "btJacobianEntry.h"
#include "btContactSolverInfo.h"
#include "btMinMax.h"
#include "btManifoldPoint.h"
btContactConstraint::btContactConstraint(btPersistentManifold* contactManifold,btRigidBody& rbA,btRigidBody& rbB)
:btTypedConstraint(CONTACT_CONSTRAINT_TYPE,rbA,rbB),
m_contactManifold(*contactManifold)
{
}
btContactConstraint::~btContactConstraint()
{
}
void btContactConstraint::setContactManifold(btPersistentManifold* contactManifold)
{
m_contactManifold = *contactManifold;
}
void btContactConstraint::getInfo1 (btConstraintInfo1* info)
{
}
void btContactConstraint::getInfo2 (btConstraintInfo2* info)
{
}
void btContactConstraint::buildJacobian()
{
}
#include "btContactConstraint.h"
#include "btRigidBody.h"
#include "btVector3.h"
#include "btJacobianEntry.h"
#include "btContactSolverInfo.h"
#include "btMinMax.h"
#include "btManifoldPoint.h"
//response between two dynamic objects without friction and no restitution, assuming 0 penetration depth
btScalar resolveSingleCollision(
btRigidBody* body1,
btCollisionObject* colObj2,
const btVector3& contactPositionWorld,
const btVector3& contactNormalOnB,
const btContactSolverInfo& solverInfo,
btScalar distance)
{
btRigidBody* body2 = btRigidBody::upcast(colObj2);
const btVector3& normal = contactNormalOnB;
btVector3 rel_pos1 = contactPositionWorld - body1->getWorldTransform().getOrigin();
btVector3 rel_pos2 = contactPositionWorld - colObj2->getWorldTransform().getOrigin();
btVector3 vel1 = body1->getVelocityInLocalPoint(rel_pos1);
btVector3 vel2 = body2? body2->getVelocityInLocalPoint(rel_pos2) : btVector3(0,0,0);
btVector3 vel = vel1 - vel2;
btScalar rel_vel;
rel_vel = normal.dot(vel);
btScalar combinedRestitution = 0.f;
btScalar restitution = combinedRestitution* -rel_vel;
btScalar positionalError = solverInfo.m_erp *-distance /solverInfo.m_timeStep ;
btScalar velocityError = -(1.0f + restitution) * rel_vel;// * damping;
btScalar denom0 = body1->computeImpulseDenominator(contactPositionWorld,normal);
btScalar denom1 = body2? body2->computeImpulseDenominator(contactPositionWorld,normal) : 0.f;
btScalar relaxation = 1.f;
btScalar jacDiagABInv = relaxation/(denom0+denom1);
btScalar penetrationImpulse = positionalError * jacDiagABInv;
btScalar velocityImpulse = velocityError * jacDiagABInv;
btScalar normalImpulse = penetrationImpulse+velocityImpulse;
normalImpulse = 0.f > normalImpulse ? 0.f: normalImpulse;
body1->applyImpulse(normal*(normalImpulse), rel_pos1);
if (body2)
body2->applyImpulse(-normal*(normalImpulse), rel_pos2);
return normalImpulse;
}
//bilateral constraint between two dynamic objects
void resolveSingleBilateral(btRigidBody& body1, const btVector3& pos1,
btRigidBody& body2, const btVector3& pos2,
btScalar distance, const btVector3& normal,btScalar& impulse ,btScalar timeStep)
{
(void)timeStep;
(void)distance;
btScalar normalLenSqr = normal.length2();
btAssert(btFabs(normalLenSqr) < btScalar(1.1));
if (normalLenSqr > btScalar(1.1))
{
impulse = btScalar(0.);
return;
}
btVector3 rel_pos1 = pos1 - body1.getCenterOfMassPosition();
btVector3 rel_pos2 = pos2 - body2.getCenterOfMassPosition();
//this jacobian entry could be re-used for all iterations
btVector3 vel1 = body1.getVelocityInLocalPoint(rel_pos1);
btVector3 vel2 = body2.getVelocityInLocalPoint(rel_pos2);
btVector3 vel = vel1 - vel2;
btJacobianEntry jac(body1.getCenterOfMassTransform().getBasis().transpose(),
body2.getCenterOfMassTransform().getBasis().transpose(),
rel_pos1,rel_pos2,normal,body1.getInvInertiaDiagLocal(),body1.getInvMass(),
body2.getInvInertiaDiagLocal(),body2.getInvMass());
btScalar jacDiagAB = jac.getDiagonal();
btScalar jacDiagABInv = btScalar(1.) / jacDiagAB;
btScalar rel_vel = jac.getRelativeVelocity(
body1.getLinearVelocity(),
body1.getCenterOfMassTransform().getBasis().transpose() * body1.getAngularVelocity(),
body2.getLinearVelocity(),
body2.getCenterOfMassTransform().getBasis().transpose() * body2.getAngularVelocity());
btScalar a;
a=jacDiagABInv;
rel_vel = normal.dot(vel);
//todo: move this into proper structure
btScalar contactDamping = btScalar(0.2);
#ifdef ONLY_USE_LINEAR_MASS
btScalar massTerm = btScalar(1.) / (body1.getInvMass() + body2.getInvMass());
impulse = - contactDamping * rel_vel * massTerm;
#else
btScalar velocityImpulse = -contactDamping * rel_vel * jacDiagABInv;
impulse = velocityImpulse;
#endif
}
| [
"cedric.foucault@gmail.com"
] | cedric.foucault@gmail.com |
4277f603a04ecd9458c26b07589cbd231736e92d | 2dd03e8a4ffb4b0c64978f4910a230012e0db477 | /Arduino库文件/AccelStepper_PCF8574/AccelStepper_PCF8574.h | ea90737fe21a01ac04b4d773db6f24dda654e9d3 | [] | no_license | 3294713004wlb/Libraries_for_Mixly | 7b8ea14e99cdcdb47e855e762df95334cd355088 | 845f78f5ed49f4b6e33f2a7e51a1e55dab1ea0c4 | refs/heads/master | 2020-12-27T17:21:03.210904 | 2020-04-26T03:55:05 | 2020-04-26T03:55:05 | 237,985,898 | 9 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 41,084 | h | // AccelStepper_PCF8574.h
//
/// \mainpage AccelStepper_PCF8574 library for Arduino
///
/// This is the Arduino AccelStepper_PCF8574 library.
/// It provides an object-oriented interface for 2, 3 or 4 pin stepper motors and motor drivers.
///
/// The standard Arduino IDE includes the Stepper library
/// (http://arduino.cc/en/Reference/Stepper) for stepper motors. It is
/// perfectly adequate for simple, single motor applications.
///
/// AccelStepper_PCF8574 significantly improves on the standard Arduino Stepper library in several ways:
/// \li Supports acceleration and deceleration
/// \li Supports multiple simultaneous steppers, with independent concurrent stepping on each stepper
/// \li API functions never delay() or block
/// \li Supports 2, 3 and 4 wire steppers, plus 3 and 4 wire half steppers.
/// \li Supports alternate stepping functions to enable support of AFMotor (https://github.com/adafruit/Adafruit-Motor-Shield-library)
/// \li Supports stepper drivers such as the Sparkfun EasyDriver (based on 3967 driver chip)
/// \li Very slow speeds are supported
/// \li Extensive API
/// \li Subclass support
///
/// The latest version of this documentation can be downloaded from
/// http://www.airspayce.com/mikem/arduino/AccelStepper_PCF8574
/// The version of the package that this documentation refers to can be downloaded
/// from http://www.airspayce.com/mikem/arduino/AccelStepper_PCF8574/AccelStepper_PCF8574-1.59.zip
///
/// Example Arduino programs are included to show the main modes of use.
///
/// You can also find online help and discussion at http://groups.google.com/group/accelstepper
/// Please use that group for all questions and discussions on this topic.
/// Do not contact the author directly, unless it is to discuss commercial licensing.
/// Before asking a question or reporting a bug, please read
/// - http://en.wikipedia.org/wiki/Wikipedia:Reference_desk/How_to_ask_a_software_question
/// - http://www.catb.org/esr/faqs/smart-questions.html
/// - http://www.chiark.greenend.org.uk/~shgtatham/bugs.html
///
/// Tested on Arduino Diecimila and Mega with arduino-0018 & arduino-0021
/// on OpenSuSE 11.1 and avr-libc-1.6.1-1.15,
/// cross-avr-binutils-2.19-9.1, cross-avr-gcc-4.1.3_20080612-26.5.
/// Tested on Teensy http://www.pjrc.com/teensy including Teensy 3.1 built using Arduino IDE 1.0.5 with
/// teensyduino addon 1.18 and later.
///
/// \par Installation
///
/// Install in the usual way: unzip the distribution zip file to the libraries
/// sub-folder of your sketchbook.
///
/// \par Theory
///
/// This code uses speed calculations as described in
/// "Generate stepper-motor speed profiles in real time" by David Austin
/// http://fab.cba.mit.edu/classes/MIT/961.09/projects/i0/Stepper_Motor_Speed_Profile.pdf or
/// http://www.embedded.com/design/mcus-processors-and-socs/4006438/Generate-stepper-motor-speed-profiles-in-real-time or
/// http://web.archive.org/web/20140705143928/http://fab.cba.mit.edu/classes/MIT/961.09/projects/i0/Stepper_Motor_Speed_Profile.pdf
/// with the exception that AccelStepper_PCF8574 uses steps per second rather than radians per second
/// (because we dont know the step angle of the motor)
/// An initial step interval is calculated for the first step, based on the desired acceleration
/// On subsequent steps, shorter step intervals are calculated based
/// on the previous step until max speed is achieved.
///
/// \par Adafruit Motor Shield V2
///
/// The included examples AFMotor_* are for Adafruit Motor Shield V1 and do not work with Adafruit Motor Shield V2.
/// See https://github.com/adafruit/Adafruit_Motor_Shield_V2_Library for examples that work with Adafruit Motor Shield V2.
///
/// \par Donations
///
/// This library is offered under a free GPL license for those who want to use it that way.
/// We try hard to keep it up to date, fix bugs
/// and to provide free support. If this library has helped you save time or money, please consider donating at
/// http://www.airspayce.com or here:
///
/// \htmlonly <form action="https://www.paypal.com/cgi-bin/webscr" method="post"><input type="hidden" name="cmd" value="_donations" /> <input type="hidden" name="business" value="mikem@airspayce.com" /> <input type="hidden" name="lc" value="AU" /> <input type="hidden" name="item_name" value="Airspayce" /> <input type="hidden" name="item_number" value="AccelStepper_PCF8574" /> <input type="hidden" name="currency_code" value="USD" /> <input type="hidden" name="bn" value="PP-DonationsBF:btn_donateCC_LG.gif:NonHosted" /> <input type="image" alt="PayPal — The safer, easier way to pay online." name="submit" src="https://www.paypalobjects.com/en_AU/i/btn/btn_donateCC_LG.gif" /> <img alt="" src="https://www.paypalobjects.com/en_AU/i/scr/pixel.gif" width="1" height="1" border="0" /></form> \endhtmlonly
///
/// \par Trademarks
///
/// AccelStepper_PCF8574 is a trademark of AirSpayce Pty Ltd. The AccelStepper_PCF8574 mark was first used on April 26 2010 for
/// international trade, and is used only in relation to motor control hardware and software.
/// It is not to be confused with any other similar marks covering other goods and services.
///
/// \par Copyright
///
/// This software is Copyright (C) 2010-2018 Mike McCauley. Use is subject to license
/// conditions. The main licensing options available are GPL V2 or Commercial:
///
/// \par Open Source Licensing GPL V2
/// This is the appropriate option if you want to share the source code of your
/// application with everyone you distribute it to, and you also want to give them
/// the right to share who uses it. If you wish to use this software under Open
/// Source Licensing, you must contribute all your source code to the open source
/// community in accordance with the GPL Version 2 when your application is
/// distributed. See https://www.gnu.org/licenses/gpl-2.0.html
///
/// \par Commercial Licensing
/// This is the appropriate option if you are creating proprietary applications
/// and you are not prepared to distribute and share the source code of your
/// application. To purchase a commercial license, contact info@airspayce.com
///
/// \par Revision History
/// \version 1.0 Initial release
///
/// \version 1.1 Added speed() function to get the current speed.
/// \version 1.2 Added runSpeedToPosition() submitted by Gunnar Arndt.
/// \version 1.3 Added support for stepper drivers (ie with Step and Direction inputs) with _pins == 1
/// \version 1.4 Added functional contructor to support AFMotor, contributed by Limor, with example sketches.
/// \version 1.5 Improvements contributed by Peter Mousley: Use of microsecond steps and other speed improvements
/// to increase max stepping speed to about 4kHz. New option for user to set the min allowed pulse width.
/// Added checks for already running at max speed and skip further calcs if so.
/// \version 1.6 Fixed a problem with wrapping of microsecond stepping that could cause stepping to hang.
/// Reported by Sandy Noble.
/// Removed redundant _lastRunTime member.
/// \version 1.7 Fixed a bug where setCurrentPosition() did not always work as expected.
/// Reported by Peter Linhart.
/// \version 1.8 Added support for 4 pin half-steppers, requested by Harvey Moon
/// \version 1.9 setCurrentPosition() now also sets motor speed to 0.
/// \version 1.10 Builds on Arduino 1.0
/// \version 1.11 Improvments from Michael Ellison:
/// Added optional enable line support for stepper drivers
/// Added inversion for step/direction/enable lines for stepper drivers
/// \version 1.12 Announce Google Group
/// \version 1.13 Improvements to speed calculation. Cost of calculation is now less in the worst case,
/// and more or less constant in all cases. This should result in slightly beter high speed performance, and
/// reduce anomalous speed glitches when other steppers are accelerating.
/// However, its hard to see how to replace the sqrt() required at the very first step from 0 speed.
/// \version 1.14 Fixed a problem with compiling under arduino 0021 reported by EmbeddedMan
/// \version 1.15 Fixed a problem with runSpeedToPosition which did not correctly handle
/// running backwards to a smaller target position. Added examples
/// \version 1.16 Fixed some cases in the code where abs() was used instead of fabs().
/// \version 1.17 Added example ProportionalControl
/// \version 1.18 Fixed a problem: If one calls the funcion runSpeed() when Speed is zero, it makes steps
/// without counting. reported by Friedrich, Klappenbach.
/// \version 1.19 Added MotorInterfaceType and symbolic names for the number of pins to use
/// for the motor interface. Updated examples to suit.
/// Replaced individual pin assignment variables _pin1, _pin2 etc with array _pin[4].
/// _pins member changed to _interface.
/// Added _pinInverted array to simplify pin inversion operations.
/// Added new function setOutputPins() which sets the motor output pins.
/// It can be overridden in order to provide, say, serial output instead of parallel output
/// Some refactoring and code size reduction.
/// \version 1.20 Improved documentation and examples to show need for correctly
/// specifying AccelStepper_PCF8574::FULL4WIRE and friends.
/// \version 1.21 Fixed a problem where desiredSpeed could compute the wrong step acceleration
/// when _speed was small but non-zero. Reported by Brian Schmalz.
/// Precompute sqrt_twoa to improve performance and max possible stepping speed
/// \version 1.22 Added Bounce.pde example
/// Fixed a problem where calling moveTo(), setMaxSpeed(), setAcceleration() more
/// frequently than the step time, even
/// with the same values, would interfere with speed calcs. Now a new speed is computed
/// only if there was a change in the set value. Reported by Brian Schmalz.
/// \version 1.23 Rewrite of the speed algorithms in line with
/// http://fab.cba.mit.edu/classes/MIT/961.09/projects/i0/Stepper_Motor_Speed_Profile.pdf
/// Now expect smoother and more linear accelerations and decelerations. The desiredSpeed()
/// function was removed.
/// \version 1.24 Fixed a problem introduced in 1.23: with runToPosition, which did never returned
/// \version 1.25 Now ignore attempts to set acceleration to 0.0
/// \version 1.26 Fixed a problem where certina combinations of speed and accelration could cause
/// oscillation about the target position.
/// \version 1.27 Added stop() function to stop as fast as possible with current acceleration parameters.
/// Also added new Quickstop example showing its use.
/// \version 1.28 Fixed another problem where certain combinations of speed and acceleration could cause
/// oscillation about the target position.
/// Added support for 3 wire full and half steppers such as Hard Disk Drive spindle.
/// Contributed by Yuri Ivatchkovitch.
/// \version 1.29 Fixed a problem that could cause a DRIVER stepper to continually step
/// with some sketches. Reported by Vadim.
/// \version 1.30 Fixed a problem that could cause stepper to back up a few steps at the end of
/// accelerated travel with certain speeds. Reported and patched by jolo.
/// \version 1.31 Updated author and distribution location details to airspayce.com
/// \version 1.32 Fixed a problem with enableOutputs() and setEnablePin on Arduino Due that
/// prevented the enable pin changing stae correctly. Reported by Duane Bishop.
/// \version 1.33 Fixed an error in example AFMotor_ConstantSpeed.pde did not setMaxSpeed();
/// Fixed a problem that caused incorrect pin sequencing of FULL3WIRE and HALF3WIRE.
/// Unfortunately this meant changing the signature for all step*() functions.
/// Added example MotorShield, showing how to use AdaFruit Motor Shield to control
/// a 3 phase motor such as a HDD spindle motor (and without using the AFMotor library.
/// \version 1.34 Added setPinsInverted(bool pin1Invert, bool pin2Invert, bool pin3Invert, bool pin4Invert, bool enableInvert)
/// to allow inversion of 2, 3 and 4 wire stepper pins. Requested by Oleg.
/// \version 1.35 Removed default args from setPinsInverted(bool, bool, bool, bool, bool) to prevent ambiguity with
/// setPinsInverted(bool, bool, bool). Reported by Mac Mac.
/// \version 1.36 Changed enableOutputs() and disableOutputs() to be virtual so can be overridden.
/// Added new optional argument 'enable' to constructor, which allows you toi disable the
/// automatic enabling of outputs at construction time. Suggested by Guido.
/// \version 1.37 Fixed a problem with step1 that could cause a rogue step in the
/// wrong direction (or not,
/// depending on the setup-time requirements of the connected hardware).
/// Reported by Mark Tillotson.
/// \version 1.38 run() function incorrectly always returned true. Updated function and doc so it returns true
/// if the motor is still running to the target position.
/// \version 1.39 Updated typos in keywords.txt, courtesey Jon Magill.
/// \version 1.40 Updated documentation, including testing on Teensy 3.1
/// \version 1.41 Fixed an error in the acceleration calculations, resulting in acceleration of haldf the intended value
/// \version 1.42 Improved support for FULL3WIRE and HALF3WIRE output pins. These changes were in Yuri's original
/// contribution but did not make it into production.<br>
/// \version 1.43 Added DualMotorShield example. Shows how to use AccelStepper_PCF8574 to control 2 x 2 phase steppers using the
/// Itead Studio Arduino Dual Stepper Motor Driver Shield model IM120417015.<br>
/// \version 1.44 examples/DualMotorShield/DualMotorShield.ino examples/DualMotorShield/DualMotorShield.pde
/// was missing from the distribution.<br>
/// \version 1.45 Fixed a problem where if setAcceleration was not called, there was no default
/// acceleration. Reported by Michael Newman.<br>
/// \version 1.45 Fixed inaccuracy in acceleration rate by using Equation 15, suggested by Sebastian Gracki.<br>
/// Performance improvements in runSpeed suggested by Jaakko Fagerlund.<br>
/// \version 1.46 Fixed error in documentation for runToPosition().
/// Reinstated time calculations in runSpeed() since new version is reported
/// not to work correctly under some circumstances. Reported by Oleg V Gavva.<br>
/// \version 1.48 2015-08-25
/// Added new class MultiStepper that can manage multiple AccelStepper_PCF8574s,
/// and cause them all to move
/// to selected positions at such a (constant) speed that they all arrive at their
/// target position at the same time. Suitable for X-Y flatbeds etc.<br>
/// Added new method maxSpeed() to AccelStepper_PCF8574 to return the currently configured maxSpeed.<br>
/// \version 1.49 2016-01-02
/// Testing with VID28 series instrument stepper motors and EasyDriver.
/// OK, although with light pointers
/// and slow speeds like 180 full steps per second the motor movement can be erratic,
/// probably due to some mechanical resonance. Best to accelerate through this speed.<br>
/// Added isRunning().<br>
/// \version 1.50 2016-02-25
/// AccelStepper_PCF8574::disableOutputs now sets the enable pion to OUTPUT mode if the enable pin is defined.
/// Patch from Piet De Jong.<br>
/// Added notes about the fact that AFMotor_* examples do not work with Adafruit Motor Shield V2.<br>
/// \version 1.51 2016-03-24
/// Fixed a problem reported by gregor: when resetting the stepper motor position using setCurrentPosition() the
/// stepper speed is reset by setting _stepInterval to 0, but _speed is not
/// reset. this results in the stepper motor not starting again when calling
/// setSpeed() with the same speed the stepper was set to before.
/// \version 1.52 2016-08-09
/// Added MultiStepper to keywords.txt.
/// Improvements to efficiency of AccelStepper_PCF8574::runSpeed() as suggested by David Grayson.
/// Improvements to speed accuracy as suggested by David Grayson.
/// \version 1.53 2016-08-14
/// Backed out Improvements to speed accuracy from 1.52 as it did not work correctly.
/// \version 1.54 2017-01-24
/// Fixed some warnings about unused arguments.
/// \version 1.55 2017-01-25
/// Fixed another warning in MultiStepper.cpp
/// \version 1.56 2017-02-03
/// Fixed minor documentation error with DIRECTION_CCW and DIRECTION_CW. Reported by David Mutterer.
/// Added link to Binpress commercial license purchasing.
/// \version 1.57 2017-03-28
/// _direction moved to protected at the request of Rudy Ercek.
/// setMaxSpeed() and setAcceleration() now correct negative values to be positive.
/// \version 1.58 2018-04-13
/// Add initialisation for _enableInverted in constructor.
/// \version 1.59 2018-08-28
/// Update commercial licensing, remove binpress.
///
/// \author Mike McCauley (mikem@airspayce.com) DO NOT CONTACT THE AUTHOR DIRECTLY: USE THE LISTS
// Copyright (C) 2009-2013 Mike McCauley
// $Id: AccelStepper_PCF8574.h,v 1.27 2016/08/14 10:26:54 mikem Exp mikem $
#ifndef AccelStepper_PCF8574_h
#define AccelStepper_PCF8574_h
#include <Wire.h>
#include "PCF8574.h"
#include <stdlib.h>
#if ARDUINO >= 100
#include <Arduino.h>
#else
#include <WProgram.h>
#include <wiring.h>
#endif
// These defs cause trouble on some versions of Arduino
#undef round
/////////////////////////////////////////////////////////////////////
/// \class AccelStepper_PCF8574 AccelStepper_PCF8574.h <AccelStepper_PCF8574.h>
/// \brief Support for stepper motors with acceleration etc.
///
/// This defines a single 2 or 4 pin stepper motor, or stepper moter with fdriver chip, with optional
/// acceleration, deceleration, absolute positioning commands etc. Multiple
/// simultaneous steppers are supported, all moving
/// at different speeds and accelerations.
///
/// \par Operation
/// This module operates by computing a step time in microseconds. The step
/// time is recomputed after each step and after speed and acceleration
/// parameters are changed by the caller. The time of each step is recorded in
/// microseconds. The run() function steps the motor once if a new step is due.
/// The run() function must be called frequently until the motor is in the
/// desired position, after which time run() will do nothing.
///
/// \par Positioning
/// Positions are specified by a signed long integer. At
/// construction time, the current position of the motor is consider to be 0. Positive
/// positions are clockwise from the initial position; negative positions are
/// anticlockwise. The current position can be altered for instance after
/// initialization positioning.
///
/// \par Caveats
/// This is an open loop controller: If the motor stalls or is oversped,
/// AccelStepper_PCF8574 will not have a correct
/// idea of where the motor really is (since there is no feedback of the motor's
/// real position. We only know where we _think_ it is, relative to the
/// initial starting point).
///
/// \par Performance
/// The fastest motor speed that can be reliably supported is about 4000 steps per
/// second at a clock frequency of 16 MHz on Arduino such as Uno etc.
/// Faster processors can support faster stepping speeds.
/// However, any speed less than that
/// down to very slow speeds (much less than one per second) are also supported,
/// provided the run() function is called frequently enough to step the motor
/// whenever required for the speed set.
/// Calling setAcceleration() is expensive,
/// since it requires a square root to be calculated.
///
/// Gregor Christandl reports that with an Arduino Due and a simple test program,
/// he measured 43163 steps per second using runSpeed(),
/// and 16214 steps per second using run();
class AccelStepper_PCF8574
{
public:
/// \brief Symbolic names for number of pins.
/// Use this in the pins argument the AccelStepper_PCF8574 constructor to
/// provide a symbolic name for the number of pins
/// to use.
typedef enum
{
FUNCTION = 0, ///< Use the functional interface, implementing your own driver functions (internal use only)
DRIVER = 1, ///< Stepper Driver, 2 driver pins required
FULL2WIRE = 2, ///< 2 wire stepper, 2 motor pins required
FULL3WIRE = 3, ///< 3 wire stepper, such as HDD spindle, 3 motor pins required
FULL4WIRE = 4, ///< 4 wire full stepper, 4 motor pins required
HALF3WIRE = 6, ///< 3 wire half stepper, such as HDD spindle, 3 motor pins required
HALF4WIRE = 8 ///< 4 wire half stepper, 4 motor pins required
} MotorInterfaceType;
/// Constructor. You can have multiple simultaneous steppers, all moving
/// at different speeds and accelerations, provided you call their run()
/// functions at frequent enough intervals. Current Position is set to 0, target
/// position is set to 0. MaxSpeed and Acceleration default to 1.0.
/// The motor pins will be initialised to OUTPUT mode during the
/// constructor by a call to enableOutputs().
/// \param[in] interface Number of pins to interface to. Integer values are
/// supported, but it is preferred to use the \ref MotorInterfaceType symbolic names.
/// AccelStepper_PCF8574::DRIVER (1) means a stepper driver (with Step and Direction pins).
/// If an enable line is also needed, call setEnablePin() after construction.
/// You may also invert the pins using setPinsInverted().
/// AccelStepper_PCF8574::FULL2WIRE (2) means a 2 wire stepper (2 pins required).
/// AccelStepper_PCF8574::FULL3WIRE (3) means a 3 wire stepper, such as HDD spindle (3 pins required).
/// AccelStepper_PCF8574::FULL4WIRE (4) means a 4 wire stepper (4 pins required).
/// AccelStepper_PCF8574::HALF3WIRE (6) means a 3 wire half stepper, such as HDD spindle (3 pins required)
/// AccelStepper_PCF8574::HALF4WIRE (8) means a 4 wire half stepper (4 pins required)
/// Defaults to AccelStepper_PCF8574::FULL4WIRE (4) pins.
/// \param[in] pin1 Arduino digital pin number for motor pin 1. Defaults
/// to pin 2. For a AccelStepper_PCF8574::DRIVER (interface==1),
/// this is the Step input to the driver. Low to high transition means to step)
/// \param[in] pin2 Arduino digital pin number for motor pin 2. Defaults
/// to pin 3. For a AccelStepper_PCF8574::DRIVER (interface==1),
/// this is the Direction input the driver. High means forward.
/// \param[in] pin3 Arduino digital pin number for motor pin 3. Defaults
/// to pin 4.
/// \param[in] pin4 Arduino digital pin number for motor pin 4. Defaults
/// to pin 5.
/// \param[in] enable If this is true (the default), enableOutputs() will be called to enable
/// the output pins at construction time.
AccelStepper_PCF8574(PCF8574 *device, uint8_t interface = AccelStepper_PCF8574::FULL4WIRE, uint8_t pin1 = 2, uint8_t pin2 = 3, uint8_t pin3 = 4, uint8_t pin4 = 5, bool enable = true);
/// Alternate Constructor which will call your own functions for forward and backward steps.
/// You can have multiple simultaneous steppers, all moving
/// at different speeds and accelerations, provided you call their run()
/// functions at frequent enough intervals. Current Position is set to 0, target
/// position is set to 0. MaxSpeed and Acceleration default to 1.0.
/// Any motor initialization should happen before hand, no pins are used or initialized.
/// \param[in] forward void-returning procedure that will make a forward step
/// \param[in] backward void-returning procedure that will make a backward step
/// Set the target position. The run() function will try to move the motor (at most one step per call)
/// from the current position to the target position set by the most
/// recent call to this function. Caution: moveTo() also recalculates the speed for the next step.
/// If you are trying to use constant speed movements, you should call setSpeed() after calling moveTo().
/// \param[in] absolute The desired absolute position. Negative is
/// anticlockwise from the 0 position.
void moveTo(long absolute);
/// Set the target position relative to the current position
/// \param[in] relative The desired position relative to the current position. Negative is
/// anticlockwise from the current position.
void move(long relative);
/// Poll the motor and step it if a step is due, implementing
/// accelerations and decelerations to acheive the target position. You must call this as
/// frequently as possible, but at least once per minimum step time interval,
/// preferably in your main loop. Note that each call to run() will make at most one step, and then only when a step is due,
/// based on the current speed and the time since the last step.
/// \return true if the motor is still running to the target position.
boolean run();
/// Poll the motor and step it if a step is due, implementing a constant
/// speed as set by the most recent call to setSpeed(). You must call this as
/// frequently as possible, but at least once per step interval,
/// \return true if the motor was stepped.
boolean runSpeed();
/// Sets the maximum permitted speed. The run() function will accelerate
/// up to the speed set by this function.
/// Caution: the maximum speed achievable depends on your processor and clock speed.
/// The default maxSpeed is 1.0 steps per second.
/// \param[in] speed The desired maximum speed in steps per second. Must
/// be > 0. Caution: Speeds that exceed the maximum speed supported by the processor may
/// Result in non-linear accelerations and decelerations.
void setMaxSpeed(float speed);
/// returns the maximum speed configured for this stepper
/// that was previously set by setMaxSpeed();
/// \return The currently configured maximum speed
float maxSpeed();
/// Sets the acceleration/deceleration rate.
/// \param[in] acceleration The desired acceleration in steps per second
/// per second. Must be > 0.0. This is an expensive call since it requires a square
/// root to be calculated. Dont call more ofthen than needed
void setAcceleration(float acceleration);
/// Sets the desired constant speed for use with runSpeed().
/// \param[in] speed The desired constant speed in steps per
/// second. Positive is clockwise. Speeds of more than 1000 steps per
/// second are unreliable. Very slow speeds may be set (eg 0.00027777 for
/// once per hour, approximately. Speed accuracy depends on the Arduino
/// crystal. Jitter depends on how frequently you call the runSpeed() function.
/// The speed will be limited by the current value of setMaxSpeed()
void setSpeed(float speed);
/// The most recently set speed
/// \return the most recent speed in steps per second
float speed();
/// The distance from the current position to the target position.
/// \return the distance from the current position to the target position
/// in steps. Positive is clockwise from the current position.
long distanceToGo();
/// The most recently set target position.
/// \return the target position
/// in steps. Positive is clockwise from the 0 position.
long targetPosition();
/// The currently motor position.
/// \return the current motor position
/// in steps. Positive is clockwise from the 0 position.
long currentPosition();
/// Resets the current position of the motor, so that wherever the motor
/// happens to be right now is considered to be the new 0 position. Useful
/// for setting a zero position on a stepper after an initial hardware
/// positioning move.
/// Has the side effect of setting the current motor speed to 0.
/// \param[in] position The position in steps of wherever the motor
/// happens to be right now.
void setCurrentPosition(long position);
/// Moves the motor (with acceleration/deceleration)
/// to the target position and blocks until it is at
/// position. Dont use this in event loops, since it blocks.
void runToPosition();
/// Runs at the currently selected speed until the target position is reached
/// Does not implement accelerations.
/// \return true if it stepped
boolean runSpeedToPosition();
/// Moves the motor (with acceleration/deceleration)
/// to the new target position and blocks until it is at
/// position. Dont use this in event loops, since it blocks.
/// \param[in] position The new target position.
void runToNewPosition(long position);
/// Sets a new target position that causes the stepper
/// to stop as quickly as possible, using the current speed and acceleration parameters.
void stop();
/// Disable motor pin outputs by setting them all LOW
/// Depending on the design of your electronics this may turn off
/// the power to the motor coils, saving power.
/// This is useful to support Arduino low power modes: disable the outputs
/// during sleep and then reenable with enableOutputs() before stepping
/// again.
/// If the enable Pin is defined, sets it to OUTPUT mode and clears the pin to disabled.
virtual void disableOutputs();
/// Enable motor pin outputs by setting the motor pins to OUTPUT
/// mode. Called automatically by the constructor.
/// If the enable Pin is defined, sets it to OUTPUT mode and sets the pin to enabled.
virtual void enableOutputs();
/// Sets the minimum pulse width allowed by the stepper driver. The minimum practical pulse width is
/// approximately 20 microseconds. Times less than 20 microseconds
/// will usually result in 20 microseconds or so.
/// \param[in] minWidth The minimum pulse width in microseconds.
void setMinPulseWidth(unsigned int minWidth);
/// Sets the enable pin number for stepper drivers.
/// 0xFF indicates unused (default).
/// Otherwise, if a pin is set, the pin will be turned on when
/// enableOutputs() is called and switched off when disableOutputs()
/// is called.
/// \param[in] enablePin Arduino digital pin number for motor enable
/// \sa setPinsInverted
void setEnablePin(uint8_t enablePin = 0xff);
/// Sets the inversion for stepper driver pins
/// \param[in] directionInvert True for inverted direction pin, false for non-inverted
/// \param[in] stepInvert True for inverted step pin, false for non-inverted
/// \param[in] enableInvert True for inverted enable pin, false (default) for non-inverted
void setPinsInverted(bool directionInvert = false, bool stepInvert = false, bool enableInvert = false);
/// Sets the inversion for 2, 3 and 4 wire stepper pins
/// \param[in] pin1Invert True for inverted pin1, false for non-inverted
/// \param[in] pin2Invert True for inverted pin2, false for non-inverted
/// \param[in] pin3Invert True for inverted pin3, false for non-inverted
/// \param[in] pin4Invert True for inverted pin4, false for non-inverted
/// \param[in] enableInvert True for inverted enable pin, false (default) for non-inverted
void setPinsInverted(bool pin1Invert, bool pin2Invert, bool pin3Invert, bool pin4Invert, bool enableInvert);
/// Checks to see if the motor is currently running to a target
/// \return true if the speed is not zero or not at the target position
bool isRunning();
protected:
/// \brief Direction indicator
/// Symbolic names for the direction the motor is turning
typedef enum
{
DIRECTION_CCW = 0, ///< Counter-Clockwise
DIRECTION_CW = 1 ///< Clockwise
} Direction;
/// Forces the library to compute a new instantaneous speed and set that as
/// the current speed. It is called by
/// the library:
/// \li after each step
/// \li after change to maxSpeed through setMaxSpeed()
/// \li after change to acceleration through setAcceleration()
/// \li after change to target position (relative or absolute) through
/// move() or moveTo()
void computeNewSpeed();
/// Low level function to set the motor output pins
/// bit 0 of the mask corresponds to _pin[0]
/// bit 1 of the mask corresponds to _pin[1]
/// You can override this to impment, for example serial chip output insted of using the
/// output pins directly
virtual void setOutputPins(uint8_t mask);
/// Called to execute a step. Only called when a new step is
/// required. Subclasses may override to implement new stepping
/// interfaces. The default calls step1(), step2(), step4() or step8() depending on the
/// number of pins defined for the stepper.
/// \param[in] step The current step phase number (0 to 7)
virtual void step(long step);
/// Called to execute a step using stepper functions (pins = 0) Only called when a new step is
/// required. Calls _forward() or _backward() to perform the step
/// \param[in] step The current step phase number (0 to 7)
virtual void step0(long step);
/// Called to execute a step on a stepper driver (ie where pins == 1). Only called when a new step is
/// required. Subclasses may override to implement new stepping
/// interfaces. The default sets or clears the outputs of Step pin1 to step,
/// and sets the output of _pin2 to the desired direction. The Step pin (_pin1) is pulsed for 1 microsecond
/// which is the minimum STEP pulse width for the 3967 driver.
/// \param[in] step The current step phase number (0 to 7)
virtual void step1(long step);
/// Called to execute a step on a 2 pin motor. Only called when a new step is
/// required. Subclasses may override to implement new stepping
/// interfaces. The default sets or clears the outputs of pin1 and pin2
/// \param[in] step The current step phase number (0 to 7)
virtual void step2(long step);
/// Called to execute a step on a 3 pin motor, such as HDD spindle. Only called when a new step is
/// required. Subclasses may override to implement new stepping
/// interfaces. The default sets or clears the outputs of pin1, pin2,
/// pin3
/// \param[in] step The current step phase number (0 to 7)
virtual void step3(long step);
/// Called to execute a step on a 4 pin motor. Only called when a new step is
/// required. Subclasses may override to implement new stepping
/// interfaces. The default sets or clears the outputs of pin1, pin2,
/// pin3, pin4.
/// \param[in] step The current step phase number (0 to 7)
virtual void step4(long step);
/// Called to execute a step on a 3 pin motor, such as HDD spindle. Only called when a new step is
/// required. Subclasses may override to implement new stepping
/// interfaces. The default sets or clears the outputs of pin1, pin2,
/// pin3
/// \param[in] step The current step phase number (0 to 7)
virtual void step6(long step);
/// Called to execute a step on a 4 pin half-steper motor. Only called when a new step is
/// required. Subclasses may override to implement new stepping
/// interfaces. The default sets or clears the outputs of pin1, pin2,
/// pin3, pin4.
/// \param[in] step The current step phase number (0 to 7)
virtual void step8(long step);
/// Current direction motor is spinning in
/// Protected because some peoples subclasses need it to be so
boolean _direction; // 1 == CW
private:
PCF8574 *_device;
/// Number of pins on the stepper motor. Permits 2 or 4. 2 pins is a
/// bipolar, and 4 pins is a unipolar.
uint8_t _interface; // 0, 1, 2, 4, 8, See MotorInterfaceType
/// Arduino pin number assignments for the 2 or 4 pins required to interface to the
/// stepper motor or driver
uint8_t _pin[4];
/// Whether the _pins is inverted or not
uint8_t _pinInverted[4];
/// The current absolution position in steps.
long _currentPos; // Steps
/// The target position in steps. The AccelStepper_PCF8574 library will move the
/// motor from the _currentPos to the _targetPos, taking into account the
/// max speed, acceleration and deceleration
long _targetPos; // Steps
/// The current motos speed in steps per second
/// Positive is clockwise
float _speed; // Steps per second
/// The maximum permitted speed in steps per second. Must be > 0.
float _maxSpeed;
/// The acceleration to use to accelerate or decelerate the motor in steps
/// per second per second. Must be > 0
float _acceleration;
float _sqrt_twoa; // Precomputed sqrt(2*_acceleration)
/// The current interval between steps in microseconds.
/// 0 means the motor is currently stopped with _speed == 0
unsigned long _stepInterval;
/// The last step time in microseconds
unsigned long _lastStepTime;
/// The minimum allowed pulse width in microseconds
unsigned int _minPulseWidth;
/// Is the direction pin inverted?
///bool _dirInverted; /// Moved to _pinInverted[1]
/// Is the step pin inverted?
///bool _stepInverted; /// Moved to _pinInverted[0]
/// Is the enable pin inverted?
bool _enableInverted;
/// Enable pin for stepper driver, or 0xFF if unused.
uint8_t _enablePin;
/// The pointer to a forward-step procedure
void (*_forward)();
/// The pointer to a backward-step procedure
void (*_backward)();
/// The step counter for speed calculations
long _n;
/// Initial step size in microseconds
float _c0;
/// Last step size in microseconds
float _cn;
/// Min step size in microseconds based on maxSpeed
float _cmin; // at max speed
};
/// @example Random.pde
/// Make a single stepper perform random changes in speed, position and acceleration
/// @example Overshoot.pde
/// Check overshoot handling
/// which sets a new target position and then waits until the stepper has
/// achieved it. This is used for testing the handling of overshoots
/// @example MultipleSteppers.pde
/// Shows how to multiple simultaneous steppers
/// Runs one stepper forwards and backwards, accelerating and decelerating
/// at the limits. Runs other steppers at the same time
/// @example ConstantSpeed.pde
/// Shows how to run AccelStepper_PCF8574 in the simplest,
/// fixed speed mode with no accelerations
/// @example Blocking.pde
/// Shows how to use the blocking call runToNewPosition
/// Which sets a new target position and then waits until the stepper has
/// achieved it.
/// @example AFMotor_MultiStepper.pde
/// Control both Stepper motors at the same time with different speeds
/// and accelerations.
/// @example AFMotor_ConstantSpeed.pde
/// Shows how to run AccelStepper_PCF8574 in the simplest,
/// fixed speed mode with no accelerations
/// @example ProportionalControl.pde
/// Make a single stepper follow the analog value read from a pot or whatever
/// The stepper will move at a constant speed to each newly set posiiton,
/// depending on the value of the pot.
/// @example Bounce.pde
/// Make a single stepper bounce from one limit to another, observing
/// accelrations at each end of travel
/// @example Quickstop.pde
/// Check stop handling.
/// Calls stop() while the stepper is travelling at full speed, causing
/// the stepper to stop as quickly as possible, within the constraints of the
/// current acceleration.
/// @example MotorShield.pde
/// Shows how to use AccelStepper_PCF8574 to control a 3-phase motor, such as a HDD spindle motor
/// using the Adafruit Motor Shield http://www.ladyada.net/make/mshield/index.html.
/// @example DualMotorShield.pde
/// Shows how to use AccelStepper_PCF8574 to control 2 x 2 phase steppers using the
/// Itead Studio Arduino Dual Stepper Motor Driver Shield
/// model IM120417015
#endif
| [
"3294713004@qq.com"
] | 3294713004@qq.com |
964d89da3d045db5d88b3eda748c69f971e110db | 129e2a4cc80b570c41380dadf6cb935d5e6345a5 | /AOJ/Introduction/ITP1_2_B.Range.cpp | a4de3b1e85ca0fa40aa01d627a329f3d9df9c638 | [] | no_license | Shusei-E/Online_Judge | 0ca1845fdfe06c81b493e097c75c8b1cf83b951f | 7b10a8e9003636c1e02c50494cbff40ef16cc153 | refs/heads/master | 2021-01-11T06:55:04.147158 | 2018-06-03T12:53:06 | 2018-06-03T12:53:06 | 72,335,819 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 185 | cpp | #include <iostream>
using namespace std;
int main(){
int a, b, c;
cin >> a >> b >> c;
if (a < b && b < c){
cout<<"Yes"<<endl;
}else{
cout << "No" << endl;
}
return 0;
}
| [
"noreply@github.com"
] | Shusei-E.noreply@github.com |
5d4d7b71d1937711986e61f28cdffbe26095922b | f22f1c9b9f0265295be7cb83433fcba66b620776 | /core/lang/src/main/c++/jcpp/nio/JHeapByteBuffer.cpp | fb05f3840c9433ff945dace9391ca75935386678 | [] | no_license | egelor/jcpp-1 | 63c72c3257b52b37a952344a62fa43882247ba6e | 9b5a180b00890d375d2e8a13b74ab5039ac4388c | refs/heads/master | 2021-05-09T03:46:22.585245 | 2015-08-07T16:04:20 | 2015-08-07T16:04:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,528 | cpp | #include "jcpp/nio/JHeapByteBuffer.h"
using namespace jcpp::nio;
namespace jcpp {
namespace nio {
JHeapByteBuffer::JHeapByteBuffer(jint cap, jint lim)
:JByteBuffer(getClazz(), -1, 0, lim, cap,new JPrimitiveByteArray(cap), 0)
{ }
JHeapByteBuffer::JHeapByteBuffer(JPrimitiveByteArray* buf, jint off, jint len)
:JByteBuffer(getClazz(), -1, off, off+len, buf->size(),buf,0)
{ }
JHeapByteBuffer::JHeapByteBuffer(JPrimitiveByteArray* buf, jint mark, jint pos, jint lim, jint cap, jint off)
:JByteBuffer(getClazz(), mark, pos, lim, cap, buf, off)
{ }
jint JHeapByteBuffer::ix(jint i)
{
return i + offset;
}
JByteBuffer* JHeapByteBuffer::compact() {
JSystem::arraycopy(hb, ix(position()), hb, ix(0), remaining());
position(remaining());
limit(capacity());
discardMark();
return this;
}
jbool JHeapByteBuffer::isDirect()
{
return false;
}
jbyte JHeapByteBuffer::get()
{
return hb->getByte(ix(nextGetIndex()));
}
jbyte JHeapByteBuffer::get(jint i)
{
return hb->getByte(ix(checkIndex(i)));
}
JByteBuffer* JHeapByteBuffer::get(JPrimitiveByteArray* dst, jint offset, jint length)
{
checkBounds(offset, length, dst->size());
if (length > remaining())
throw new JBufferUnderflowException();
for (int i=offset; i < offset+length; i++){
dst->setByte(i, this->get());
}
return this;
}
JByteBuffer* JHeapByteBuffer::put(jbyte x)
{
hb->setByte(nextPutIndex(), x);
return this;
}
JByteBuffer* JHeapByteBuffer::put(jint i, jbyte x)
{
hb->setByte(ix(checkIndex(i)), x);
return this;
}
JByteBuffer* JHeapByteBuffer::put(JPrimitiveByteArray* src, jint offset, jint length)
{
checkBounds(offset, length, src->size());
if (length > remaining())
throw new JBufferOverflowException();
for (int i=offset; i < offset+length; i++){
this->put(src->getByte(i));
}
return this;
}
JByteBuffer* JHeapByteBuffer::put(JByteBuffer* src)
{
if (src->isInstanceOf(JHeapByteBuffer::getClazz())){
if (src==this)
throw new JIllegalArgumentException();
JHeapByteBuffer* sb = reinterpret_cast<JHeapByteBuffer*>(src);
int n = sb->remaining();
if (n > remaining())
throw new JBufferOverflowException();
JSystem::arraycopy(sb->hb, sb->ix(sb->position()), hb, ix(position()), n);
sb->position(position()+n);
position(position()+n);
} else if (src->isDirect()){
jint n = src->remaining();
if (n > remaining())
throw new JBufferOverflowException();
src->get(hb, ix(position()), n);
position(position() + n);
}else{
JByteBuffer::put(src);
}
return this;
}
jchar JHeapByteBuffer::getChar()
{
return JBits::getChar(hb, ix(nextGetIndex(2)), bigEndian);
}
jchar JHeapByteBuffer::getChar(jint i)
{
return JBits::getChar(hb, ix(checkIndex(i, 2)), bigEndian);
}
JByteBuffer* JHeapByteBuffer::putChar(jchar x)
{
JBits::putChar(hb, ix(nextPutIndex(2)), x, bigEndian);
return this;
}
JByteBuffer* JHeapByteBuffer::putChar(jint i, jchar x)
{
JBits::putChar(hb, ix(checkIndex(i, 2)), x, bigEndian);
return this;
}
JCharBuffer* JHeapByteBuffer::asCharBuffer()
{
jint size = this->remaining() >> 1;
jint off = offset + position();
return ( bigEndian? (JCharBuffer*)(new JByteBufferAsCharBufferB(this, -1, 0, size, size, off))
: (JCharBuffer*)(new JByteBufferAsCharBufferL(this, -1, 0, size, size, off))
);
}
JHeapByteBuffer::~JHeapByteBuffer()
{ }
}
}
| [
"mimi4930"
] | mimi4930 |
e6f73fb59b3124b14bfc1d51fe899e8df15d7fc4 | d43c6e4153c64b2070409348494f2fbc789765ba | /CourtLocalisation/CamCalModel/CamCalModelmain.cpp | 710916a896611bfa4a84c4aac1aad5716a08d4a7 | [] | no_license | abuzaina/RoboticsLab | 98d3a803d4962c1da5ccfa4cfeac920c41d35b6a | daeb2b861bfd599e72f84951fff1413cca935b4c | refs/heads/master | 2021-01-14T08:50:33.410863 | 2016-08-02T13:31:07 | 2016-08-02T13:31:07 | 64,407,541 | 0 | 0 | null | 2016-07-28T15:36:59 | 2016-07-28T15:36:58 | null | UTF-8 | C++ | false | false | 11,104 | cpp | #include <opencv2/opencv.hpp>
#include <iostream>
#include <stdio.h>
using namespace std;
using namespace cv;
const float PI = 3.14159265;
bool intersection(Point2f o1, Point2f p1, Point2f o2, Point2f p2, Point2f &r);
cv::Point2f lineIntersection(cv::Point &p1, cv::Point &p2, cv::Point &p3, cv::Point &p4);
char key;
int main() {
VideoCapture cap("Y:/cvdev/vollyballVids/v4.mp4");
if (!cap.isOpened()) // check if we succeeded
return -1;
// Camera Calibration
/*Mat cameraMatrix, distCoeffs;
FileStorage fs("C:\\out_camera_data.xml", FileStorage::READ);
if (fs.isOpened()) {
fs["Camera_Matrix"] >> cameraMatrix;
fs["Distortion_Coefficients"] >> distCoeffs;
fs.release();
}*/
// system("pause");
for (;;)
{
Mat temp, frame;
cap >> frame; // get a new frame from camera
// frame = imread("Y:/cvdev/vollyballVids/c6.jpg");
//cv::resize(frame, frame, cv::Size(2992 / 2, 1000));
// cv::undistort(temp, frame, cameraMatrix, distCoeffs);
const float THRES = 20;
cv::Mat image = frame.clone();
// court points
// convert to gray scale
cv::Mat image_gray;
cv::cvtColor(image, image_gray, CV_BGR2GRAY);
// compute structure matrix within the pixel neighborhood
// gradient x
cv::Mat image_gradient_x;
cv::Sobel(image_gray, image_gradient_x, image_gray.depth(), 1, 0);
cv::convertScaleAbs(image_gradient_x, image_gradient_x);
cv::threshold(image_gradient_x, image_gradient_x, 100, 200, cv::THRESH_TOZERO);
// gradient y
cv::Mat image_gradient_y;
cv::Sobel(image_gray, image_gradient_y, image_gray.depth(), 0, 1);
//cv::convertScaleAbs(image_gradient_y, image_gradient_y);
cv::threshold(image_gradient_y, image_gradient_y, 100, 200, cv::THRESH_TOZERO);
cv::Mat image_gradient;
cv::addWeighted(image_gradient_y, 1, image_gradient_x, 1, 0, image_gradient);
vector<Vec4i> lines;
HoughLinesP(image_gradient, lines, 1, CV_PI / 180, 50, 50, 10);
for (size_t i = 0; i < lines.size(); i++)
{
Vec4i l = lines[i];
line(image, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA);
}
cv::imshow("image", image);
#if 0
// Apply Hough transform to find the lines
std::vector<cv::Vec2f> lines;
cv::HoughLines(image_gradient_y, lines, 1, CV_PI / 180, 120);
// group the lines according to the theta
std::vector<std::vector<int>> groups(lines.size(), std::vector<int>(lines.size()));
for (int i = 0; i < lines.size(); ++i)
for (int j = 0; j < lines.size(); ++j)
groups[i][j] = -1;
if (lines.size() > 0)
groups[0][0] = 0;
int num_groups = 1;
for (size_t i = 1; i < lines.size(); ++i) {
float min_distance = image.rows*image.cols;
int min_index = 0;
for (size_t ii = 0; ii < num_groups; ++ii) {
int line_index = groups[ii][0];
float distance_rho = std::abs(lines[i][0] - lines[line_index][0]);
float distance_theta = std::abs(lines[i][1] - lines[line_index][1]);
float distance = distance_theta * 180 / PI + distance_rho;
if (distance < min_distance) {
min_distance = distance;
min_index = ii;
}
}
// not belong to any groups, add one group
if (min_distance > THRES) {
num_groups++;
groups[num_groups - 1][0] = i;
}
else {// append to the end
for (size_t ii = 0; ii < lines.size(); ++ii) {
if (groups[min_index][ii] == -1) {
groups[min_index][ii] = i;
break;
}
}
}
}
cv::Mat color_dst2; // for drawing lines
cv::cvtColor(image_gradient_y, color_dst2, CV_GRAY2BGR);
std::vector<std::vector<float> > refine_lines(num_groups, std::vector<float>(3)); // 0: rho, 1: theta, 3: 1 for horizontal and -1 for vertical
for (int i = 0; i < num_groups; ++i) {
float sum_rho = 0;
float sum_theta = 0;
int count = 0;
for (int j = 0; j < lines.size(); ++j) {
int line_index = groups[i][j];
if (line_index != -1) {
count++;
sum_rho += lines[line_index][0];
sum_theta += lines[line_index][1];
}
else
break;
}
float rho = sum_rho / (float)count;
float theta = sum_theta / (float)count;
refine_lines[i][0] = rho;
refine_lines[i][1] = theta;
if (theta > PI*(1.0 / 3.0) && theta < PI*(2.0 / 3.0))
refine_lines[i][2] = 1;
else
refine_lines[i][2] = -1;
double a = cos(theta), b = sin(theta);
double x0 = a*rho, y0 = b*rho;
cv::Point pt1(cvRound(x0 + 1000 * (-b)),
cvRound(y0 + 1000 * (a)));
cv::Point pt2(cvRound(x0 - 1000 * (-b)),
cvRound(y0 - 1000 * (a)));
if (refine_lines[i][2] > 0) // horizontal
line(color_dst2, pt1, pt2, cv::Scalar(0, 0, 255), 1, 8);
else // vertical
line(color_dst2, pt1, pt2, cv::Scalar(0, 255, 0), 1, 8);
}
// Get the min and max two vertical lines &
// the min 2 horizontal lines as the reference lines
float min_ver_rho = 1000000;
float max_ver_rho = -1000000;
int min_ver_index = 0;
int max_ver_index = 0;
float max_hor_rho_1 = -1000000;
float max_hor_rho_2 = -1000001;
int max_hor_index_1 = 0;
int max_hor_index_2 = 0;
for (int i = 0; i < num_groups; ++i) {
float rho = refine_lines[i][0];
if (refine_lines[i][2] > 0) { // horizontal
if (rho > max_hor_rho_1) {
max_hor_rho_2 = max_hor_rho_1;
max_hor_rho_1 = rho;
max_hor_index_2 = max_hor_index_1;
max_hor_index_1 = i;
}
else if (rho > max_hor_rho_2) {
max_hor_rho_2 = rho;
max_hor_index_2 = i;
}
}
else { // vertical
if (rho < min_ver_rho) {
min_ver_rho = rho;
min_ver_index = i;
}
if (rho > max_ver_rho) {
max_ver_rho = rho;
max_ver_index = i;
}
}
}
int indices[4];
indices[0] = max_hor_index_1;
indices[1] = max_hor_index_2;
indices[2] = min_ver_index;
indices[3] = max_ver_index;
std::vector<std::vector<cv::Point> > points(4, std::vector<cv::Point>(2));
for (int i = 0; i < 4; ++i) {
int index = indices[i];
float rho = refine_lines[index][0];
float theta = refine_lines[index][1];
double a = cos(theta), b = sin(theta);
double x0 = a*rho, y0 = b*rho;
points[i][0] = cv::Point(cvRound(x0 + 1000 * (-b)),
cvRound(y0 + 1000 * (a)));
points[i][1] = cv::Point(cvRound(x0 - 1000 * (-b)),
cvRound(y0 - 1000 * (a)));
}
cv::Point2f p1 = lineIntersection(points[0][0], points[0][1], points[2][0], points[2][1]);
cv::circle(color_dst2, p1, 3, cv::Scalar(255, 0, 0), 3);
cv::Point2f p2 = lineIntersection(points[0][0], points[0][1], points[3][0], points[3][1]);
cv::circle(color_dst2, p2, 3, cv::Scalar(0, 255, 0), 3);
cv::Point2f p3 = lineIntersection(points[1][0], points[1][1], points[2][0], points[2][1]);
cv::circle(color_dst2, p3, 3, cv::Scalar(0, 0, 255), 3);
cv::Point2f p4 = lineIntersection(points[1][0], points[1][1], points[3][0], points[3][1]);
cv::circle(color_dst2, p4, 3, cv::Scalar(255, 255, 255), 3);
imshow("color dst 2", color_dst2);
std::vector<cv::Point2f> point_array_src(4);
point_array_src[0] = p1;
point_array_src[1] = p2;
point_array_src[2] = p3;
point_array_src[3] = p4;
std::vector<cv::Point2f> point_array_dst(4);
point_array_dst[0] = cv::Point2f(530, 370);
point_array_dst[1] = cv::Point2f(10, 370);
point_array_dst[2] = cv::Point2f(530, 10);
point_array_dst[3] = cv::Point2f(10, 10);
cv::Mat homography1 = cv::findHomography(point_array_src, point_array_dst);
cv::Mat homography2 = cv::findHomography(point_array_dst, point_array_src);
point_array_dst[0] = cv::Point2f(26, 18);
point_array_dst[1] = cv::Point2f(0, 18);
point_array_dst[2] = cv::Point2f(26, 0);
point_array_dst[3] = cv::Point2f(0, 0);
cv::Mat homography3 = cv::findHomography(point_array_src, point_array_dst);
cv::Mat image_32fc3;
image.convertTo(image_32fc3, CV_32FC3);
cv::Mat transform_image;
cv::warpPerspective(image, transform_image, homography1, cv::Size(540, 380));
imshow("transform", transform_image);
// volleyball model
std::vector<std::vector<cv::Point2f> > line_segments(4, std::vector<cv::Point2f>(2));
line_segments[0][0] = cv::Point2f(10, 10);
line_segments[0][1] = cv::Point2f(10, 370);
line_segments[1][0] = cv::Point2f(10, 370);
line_segments[1][1] = cv::Point2f(530, 370);
line_segments[2][0] = cv::Point2f(530, 370);
line_segments[2][1] = cv::Point2f(530, 10);
line_segments[3][0] = cv::Point2f(530, 10);
line_segments[3][1] = cv::Point2f(10, 10);
cv::Mat color_dst3 = image.clone();
std::vector<cv::Point2f> middle_line(2);
for (int i = 0; i < line_segments.size(); ++i) {
std::vector<cv::Point2f> src_points(2);
std::vector<cv::Point2f> dst_points(2);
src_points[0] = line_segments[i][0];
src_points[1] = line_segments[i][1];
perspectiveTransform(src_points, dst_points, homography2);
cv::line(color_dst3, dst_points[0], dst_points[1], cv::Scalar(0, 255 / 7 * (i + 1), 0), 3, 4);
if (i == 4) {
middle_line[0] = dst_points[0];
middle_line[1] = dst_points[1];
}
}
Mat framehsv, img_violet;
cvtColor(frame, framehsv, CV_BGR2HSV);
Mat channels[3];
split(frame, channels);
cv::inRange(framehsv, cv::Scalar(147, 92, 35), cv::Scalar(171, 230, 173), img_violet);
Mat element = getStructuringElement(MORPH_ELLIPSE,
Size(5, 5),
Point(3, 3));
/// Apply the dilation operation
erode(img_violet, img_violet, element);
element = getStructuringElement(MORPH_ELLIPSE,
Size(5, 5),
Point(3, 3));
dilate(img_violet, img_violet, element);
cv::Mat out;
Mat g = Mat::zeros(Size(frame.rows, frame.cols), CV_8UC1);
cv::Mat in[] = { img_violet, img_violet, img_violet };
cv::merge(in, 3, out);
cv::addWeighted(color_dst3, 1, out, 1, 0.0, out);
double sum = 0, sumi = 0, sumj = 0;
double count = 0;
for (double i = 0; i < img_violet.rows; i += 1.)
for (double j = 0; j < img_violet.cols; j += 1.)
if (img_violet.at<bool>(i, j)) {
sum++;
count += 1.;
sumi += i;
sumj += j;
}
cv::Mat violet_masked;
cv::circle(out, cv::Point((int)(sumj / count), (int)(sumi / count)), sqrt(sum / PI), Scalar(0, 255, 0));
vector<Point2f> scene_points, mapped_coord;
scene_points.push_back(cv::Point2f(sumj / count, sumi / count));
perspectiveTransform(scene_points, mapped_coord, homography3);
cout << mapped_coord[0].x << ", " << mapped_coord[0].y << endl;
imshow("court", out);
#endif
waitKey(30);
}
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
}
cv::Point2f lineIntersection(cv::Point &p1, cv::Point &p2, cv::Point &p3, cv::Point &p4) {
float bx = p2.x - p1.x;
float by = p2.y - p1.y;
float dx = p4.x - p3.x;
float dy = p4.y - p3.y;
float b_dot_d_perp = bx*dy - by*dx;
if (b_dot_d_perp == 0) {
return NULL;
}
float cx = p3.x - p1.x;
float cy = p3.y - p1.y;
float t = (cx*dy - cy*dx) / b_dot_d_perp;
return cv::Point2f(p1.x + t*bx, p1.y + t*by);
}
bool intersection(Point2f o1, Point2f p1, Point2f o2, Point2f p2, Point2f &r) {
Point2f x = o2 - o1;
Point2f d1 = p1 - o1;
Point2f d2 = p2 - o2;
float cross = d1.x*d2.y - d1.y*d2.x;
if (abs(cross) < /*EPS*/1e-8)
return false;
double t1 = (x.x * d2.y - x.y * d2.x) / cross;
r = o1 + d1 * t1;
return true;
} | [
"anas.abuzaina@gmail.com"
] | anas.abuzaina@gmail.com |
e68c945251e9cede58c4e0fa954dd626e99ddaf6 | 55ee5259b9b167f05c53a862d266ccc42d64eb6a | /trunk/SonarGaussian/WindowTool/TopologicalMatch/WFTopologicalMatch.cpp | 85cc894dbad0bd51753ef281ed329a9d06c7db16 | [] | no_license | matheusbg8/SonarGraph | 0829a4477271a34ead6c2aaaed5ac810dcada515 | 88beb18a6650194b352b195fc2a22cf256ec9cc8 | refs/heads/master | 2021-01-19T11:14:58.651049 | 2017-02-16T23:18:05 | 2017-02-16T23:18:05 | 82,235,034 | 10 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,258 | cpp | #include "WFTopologicalMatch.h"
#include "WindowTool/WindowTool.h"
#include "Drawing/Drawing.h"
FrameSD *WFTopologicalMatch::frame(unsigned i)
{
// Yes, we are breaking some SOLID principles of OO Programming
// if you know a better way to solve this, please send me a e-mail
// matheusbg8@gmail.com, thank you!
return (FrameSD *) wt->frames[i];
}
WFTopologicalMatch::WFTopologicalMatch():
leftSelecGaussian(-1),
rightSelecGaussian(-1),
showVertexMatch(true),
sonar(sonarConfig),
sonarConfig("../SonarGaussian/Configs.ini")
{
sonar.setStoreImgs(false);
if(showVertexMatch)
{
namedWindow("VertexMatch", 1);
}
}
void WFTopologicalMatch::start()
{
// wt->currentLeftFrame = 129;
// wt->currentRighFrame = 130;
}
Frame *WFTopologicalMatch::newFrame(const string &fileName, unsigned frameNumber)
{
// New empty Sonar Descriptor
sds.push_back(0x0);
return new FrameSD(fileName,frameNumber);
}
void WFTopologicalMatch::keyPress(char c)
{
switch(c)
{
case 'u':
sonar.segmentationCalibUI(wt->selectedFrameImg());
break;
case '1':
break;
case '2':
break;
case '3':
break;
case '4':
break;
case 'b':
break;
}
}
void WFTopologicalMatch::mouseEvent(int event, int x, int y)
{
}
void WFTopologicalMatch::renderProcess(Mat &leftImg, int leftId, Mat &rightImg, int rightId)
{
SonarDescritor *rightSD = sds[rightId],
*leftSD = sds[leftId];
Drawing::drawDescriptorColor(rightImg,rightSD,Scalar(0,0,255),Scalar(0,255,0),false,false,false,true,true,false);
Drawing::drawDescriptorColor(leftImg,leftSD,Scalar(0,0,255),Scalar(0,255,0),false,false,false,true,true,false);
}
void WFTopologicalMatch::renderFrameTogether(Mat &screen,
const Scalar_<float> &el, unsigned leftFrameId,
const Scalar_<float> &er, unsigned rightFrameId)
{
// Draw texts
char tempStr[200];
sprintf(tempStr,
"Left Gaussian %d",
leftSelecGaussian);
putText(screen,tempStr,
Point2f(30.f, wt->windowSize.height-10),
FONT_HERSHEY_COMPLEX,0.5,
Scalar(255,255,255),2);
sprintf(tempStr,
"Right Gaussian %d",
rightSelecGaussian);
putText(screen,tempStr,
Point2f(wt->windowSize.width*0.5f + 30.f, wt->windowSize.height-10),
FONT_HERSHEY_COMPLEX,0.5,
Scalar(255,255,255),2);
Drawing::drawMatchings(screen,el,er,
sds[leftFrameId]->gaussians,
sds[rightFrameId]->gaussians,
matchInfo,Scalar(255.f,255.f,0));
}
void WFTopologicalMatch::processImages(Mat &leftImg, int leftId, Mat &rightImg, int rightId)
{
if(sds[leftId] == 0x0)
{
sds[leftId] = sonar.newImageDirect(leftImg);
}
if(sds[rightId] == 0x0)
{
sds[rightId] = sonar.newImageDirect(rightImg);
}
matchInfo.clear();
sonar.computeMatchs(sds[leftId], sds[rightId], matchInfo);
cout << "Processed frames rightId "
<< rightId
<< " and leftId "
<< leftId
<< endl;
}
| [
"matheusbg8@gmail.com"
] | matheusbg8@gmail.com |
48014e30f85b5dfb61dad56c5da7bfe2a23f090c | 3a081d4404ca28bdcaa59f74301c9b0bdfc64581 | /洛谷题单/7-4 树形动规/P2585/P2585.cpp | 94c56af0c48ea4618b17da32939f0a3e869e2f6b | [] | no_license | little-czy/luogu | 2ec6dcf75bd21b720d84130184da35a185ecdf21 | fe138a43d8de1c5ac3170e8873f134d1dca13a37 | refs/heads/master | 2022-12-16T00:40:21.880901 | 2020-09-13T02:40:11 | 2020-09-13T02:40:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,026 | cpp | #include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 5e5 + 5;
struct node
{
int l, r;
char c;
} no[maxn];
int head[maxn], total, dpmin[maxn][3], dpmax[maxn][3];
string s;
void init()
{
int now = ++total;
no[now].c = s[total - 1];
switch (s[total - 1])
{
case '1':
no[now].l = now + 1;
init();
break;
case '2':
no[now].l = now + 1;
init();
no[now].r = total + 1;
init();
break;
}
}
void print(int x)
{
cout << no[x].c << endl;
if (no[x].l)
print(no[x].l);
if (no[x].r)
print(no[x].r);
}
void dfs(int x)
{
if (dpmin[x][0])
return;
switch (no[x].c)
{
case '0':
dpmin[x][0] = dpmin[x][2] = 0;
dpmin[x][1] = 1;
dpmax[x][0] = dpmax[x][1] = 1;
dpmax[x][2] = 0;
break;
case '1':
dfs(no[x].l);
dpmin[x][1] = 1 + dpmin[no[x].l][2];
dpmin[x][2] = dpmin[no[x].l][0];
dpmin[x][0] = min(dpmin[x][1], dpmin[x][2]);
dpmax[x][1] = 1 + dpmax[no[x].l][2];
dpmax[x][2] = dpmax[no[x].l][0];
dpmax[x][0] = max(dpmax[x][1], dpmax[x][2]);
break;
case '2':
dfs(no[x].l);
dfs(no[x].r);
dpmin[x][1] = 1 + dpmin[no[x].l][2] + dpmin[no[x].r][2];
dpmin[x][2] = min(dpmin[no[x].l][2] + dpmin[no[x].r][1], dpmin[no[x].l][1] + dpmin[no[x].r][2]);
dpmin[x][0] = min(dpmin[x][1], dpmin[x][2]);
dpmax[x][1] = 1 + dpmax[no[x].l][2] + dpmax[no[x].r][2];
dpmax[x][2] = max(dpmax[no[x].l][2] + dpmax[no[x].r][1], dpmax[no[x].l][1] + dpmax[no[x].r][2]);
dpmax[x][0] = max(dpmax[x][1], dpmax[x][2]);
break;
default:
break;
}
}
int main()
{
freopen("in", "r", stdin);
ios::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr);
cin >> s;
init();
// print(1);
dfs(1);
cout << dpmax[1][0] << " " << dpmin[1][0] << endl;
return 0;
}
| [
"czy000123@qq.com"
] | czy000123@qq.com |
e4ada76217f96171a8bc46ed4c5e0c6c0fd18fa7 | 4296ad62fc2d1c0111af5e9c9ef5b8336256674e | /src/hitachi2020/a.cpp | f1cedca1540b28aea65314e2b3049a03aa8b64f2 | [] | no_license | emakryo/cmpro | 8aa50db1d84fb85e515546f37e675121be9de5c2 | 81db478cc7da06a9b99a7888e39952ddb82cdbe5 | refs/heads/master | 2023-02-09T12:36:47.893287 | 2023-01-23T12:07:03 | 2023-01-23T12:07:03 | 79,899,196 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 666 | cpp | #include<bits/stdc++.h>
#include<boost/variant.hpp>
using namespace std;
typedef long long ll;
typedef vector<boost::variant<bool, ll, int, string, double, char*, const char*>> anys;
template<typename T> inline void pr(const vector<T> &xs){
for(int i=0; i<xs.size()-1; i++) cout<<xs[i]<<" ";
(xs.empty()?cout:(cout<<xs[xs.size()-1]))<<endl;
}
#ifdef DEBUG
#define debug(...) pr(anys{__VA_ARGS__})
#define debugv(x) pr((x))
#else
#define debug(...)
#define debugv(x)
#endif
int main(){
string S;
cin >> S;
string ans = S.size()%2==0 ? "Yes" : "Nom;
for(int i=0; i<S.size(); i++){
if(S[i]!=(i%2==0?'h':'i')) ans = "No";
}
cout << ans << endl;
return 0;
}
| [
"ryosuke.kamesawa@dena.com"
] | ryosuke.kamesawa@dena.com |
cb32cf8df2bf6f54b00f53c3bd87403aaccc46ae | acf7796906e59d64f285a88574406e1b9d4cd453 | /165-B/165-B-102065535.cpp | 0576549d37f7e288bb945378f87f4254ecce0d89 | [] | no_license | samnoon1971/Codeforces | 13fd99aa13a1d57792c7a0b9042c9f1fc3a14deb | a31444c717944d2c81f75af7a3e6650fb41ccf1d | refs/heads/main | 2023-03-07T18:46:31.705957 | 2021-02-18T19:52:34 | 2021-02-18T19:52:34 | 340,160,077 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,618 | cpp | #include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/detail/standard_policies.hpp>
using namespace std;
using namespace __gnu_pbds;
/// faster.
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#define samnoon ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define ll long long int
#define ld long double
#define ull unsigned long long int
#define pii pair < int, int>
#define pll pair < ll, ll>
#define MOD 1000000007
#define ff first
#define ss second
#define pb push_back
#define eb emplace_back
#define sc scanf
#define pf printf
#define scin(x) scanf("%d",&(x))
#define scin2(x,y) scanf("%d %d",&(x),&(y))
#define scin3(x,y,z) scanf("%d %d %d",&(x),&(y),&(z))
#define scln(x) scanf("%lld",&(x))
#define scln2(x,y) scanf("%lld %lld",&(x),&(y))
#define scln3(x,y,z) scanf("%lld %lld %lld",&(x),&(y),&(z))
#define min3(a,b,c) min(a,min(b,c))
#define min4(a,b,c,d) min(d,min(a,min(b,c)))
#define max3(a,b,c) max(a,max(b,c))
#define max4(a,b,c,d) max(d,max(a,max(b,c)))
#define ms(a,b) memset(a,b,sizeof(a))
#define mp make_pair
#define gcd(a, b) __gcd(a,b)
#define lcm(a, b) ((a)*(b)/gcd(a,b))
#define input freopen("input.txt","rt", stdin)
#define output freopen("output.txt","wt", stdout)
#define PI acos(-1.0)
#define zero(a) memset(a,0,sizeof a)
#define all(v) v.begin(),v.end()
#define Max(v) *max_element(all(v))
#define Min(v) *min_element(all(v))
#define Upper(c,x) (upper_bound(c.begin(),c.end(),x)-c.begin())
#define Lower(c,x) (lower_bound(c.begin(),c.end(),x)-c.begin())
#define Unique(X) (X).erase(unique(all(X)),(X).end())
#define no cout << "NO" << endl ;
#define yes cout << "YES" << endl ;
#define segment_tree int Lnode = node << 1 , Rnode = Lnode + 1 , mid = ( b + e ) >> 1 ;
#define Count(C, x) count(C.begin(), C.end(), x)
///sum accumulate( v.begin(), v.begin() + k, 0LL )///bool operator < ( const Node& p ) const{ return cost < p.cost ; }
///priority_queue<int,vector<int>,greater<int> >pq;///std::set<ll, std::greater<ll> > Set;///string str = "abcdefghijklmnopqrstuvwxyz";///string s2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ;
///string s = bitset<64>( n ).to_string() ; ll val = bitset< 64 >( s ).to_ullong() ;
///--------------Graph Moves--------------------------------------
const int fx[] = {+1,-1,+0,+0}; const int fy[] = {+0,+0,+1,-1};
///const int fx[] = {+0,+0,+1,-1,-1,+1,-1,+1}; ///King's move ///const int fy[] = {-1,+1,+0,+0,+1,+1,-1,-1}; ///king's Move
///const int fx[] = {-2,-2,-1,-1,+1,+1,+2,+2}; ///knight's move ///const int fy[] = {-1,+1,-2,+2,-2,+2,-1,+1}; ///knight's move
///---------------------------------------------------------------
typedef tree< int, null_type, less<int>, rb_tree_tag,tree_order_statistics_node_update> ordered_set;
typedef tree<pair<int, int>,null_type,less<pair<int, int>>,rb_tree_tag,tree_order_statistics_node_update> ordered_multiset;
/// Modular arithmetic
inline void normal(ll &a) { a %= MOD; (a < 0) && (a += MOD); }
inline ll modMul(ll a, ll b) { a %= MOD, b %= MOD; normal(a), normal(b); return (a*b)%MOD; }
inline ll modAdd(ll a, ll b) { a %= MOD, b %= MOD; normal(a), normal(b); return (a+b)%MOD; }
inline ll modSub(ll a, ll b) { a %= MOD, b %= MOD; normal(a), normal(b); a -= b; normal(a); return a; }
inline ll modPow(ll b, ll p) { ll r = 1; while(p) { if(p&1) r = modMul(r, b); b = modMul(b, b); p >>= 1; } return r; }
inline ll modInverse(ll a) { return modPow(a, MOD-2); } /// When MOD is prime.
inline ll modDiv(ll a, ll b) { return modMul(a, modInverse(b)); }
/** Debugging Tool **/
#define error(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }
void err(istream_iterator<string> it) {}
template<typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args)
{
cerr << *it << " = " << a << endl;
err(++it, args...);
}
///
///--------------------**********----------------------------------
ll binpow(ll a, ll b)
{
ll res = 1;
while (b > 0)
{
if (b & 1)
res = res * a;
a = a * a;
b >>= 1;
}
return res;
}
const ll MAXN = 2e5+10;
struct disjoint{
ll fa[MAXN];
ll sz[MAXN];
void Build(ll n)
{
for(ll i = 0; i<=n; i++) fa[i]=i, sz[i] = 1;
}
ll Find(ll x)
{
return x==fa[x]?x:fa[x]=Find(fa[x]);
}
void Union(ll a, ll b)
{
a = Find(a), b = Find(b);
if(sz[a] < sz[b]) swap(a,b);
fa[b] = a;
sz[a] += sz[b];
}
ll Size(ll n)
{
return sz[n];
}
};
ll n, k;
bool ok(ll m)
{
ll x = 1;
ll sum = 0;
while(m / x)
{
ll cnt = m / x;
x = x * k;
sum += cnt;
// error(sum);
if(sum >= n)
return true;
else if(cnt == 0)
return false;
}
return false;
}
int main()
{
//samnoon;
ll t;
t = 1;
// cin >> t;
while(t--)
{
cin >> n >> k;
ll l = 0, r = 3e9;
while(l <= r)
{
ll m = (l + r) / 2;
//error(m);
if(ok(m))
{
r = m - 1;
}
else
{
l = m + 1;
}
}
cout << r + 1 << endl;
}
return 0;
}
/* stuff you should look for
* int overflow, array bounds
* special cases (n=1?)
* do smth instead of nothing and stay organized
* WRITE STUFF DOWN
* DON'T GET STUCK ON ONE APPROACH
*/ | [
"samnoonabrar@gmail.com"
] | samnoonabrar@gmail.com |
621a69fdd539a7008f56f69c2f695e77cd97238c | 9889e7fd73314382fb2f9e8f63d92cf3254b75fb | /Vaango/src/CCA/Components/Schedulers/BB_mod_Feb142023/DetailedDependency.h | 2bc0098a78c4ece517b2f441282b61e8c72c3837 | [] | no_license | bbanerjee/ParSim | 0b05f43cff8e878658dc179b4a604eabd873f594 | 87f87816b146f40013a5e6648dfe20f6d2d002bb | refs/heads/master | 2023-04-27T11:30:36.252023 | 2023-04-13T22:04:50 | 2023-04-13T22:04:50 | 13,608,512 | 16 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 4,420 | h | /*
* The MIT License
*
* Copyright (c) 1997-2021 The University of Utah
* Copyright (c) 2022-2023 Biswajit Banerjee
*
* 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 CCA_COMPONENTS_SCHEDULERS_DETAILED_DEP_H
#define CCA_COMPONENTS_SCHEDULERS_DETAILED_DEP_H
#include <Core/Grid/Patch.h>
#include <Core/Grid/Task.h>
#include <list>
namespace Uintah {
class DetailedTask;
struct DetailedDep
{
public:
enum CommCondition
{
Always,
FirstIteration,
SubsequentIterations
};
DetailedDep(DetailedDep* next_in,
Task::Dependency* comp_in,
Task::Dependency* req_in,
DetailedTask* toTask_in,
const Patch* fromPatch_in,
int matl_in,
const IntVector& low_in,
const IntVector& high_in,
CommCondition cond_in)
: m_next(next_in)
, m_comp(comp_in)
, m_req(req_in)
, m_from_patch(fromPatch_in)
, m_low(low_in)
, m_high(high_in)
, m_matl(matl_in)
, m_comm_condition(cond_in)
, m_patch_low(low_in)
, m_patch_high(high_in)
{
ASSERT(Min(high_in - low_in, IntVector(1, 1, 1)) == IntVector(1, 1, 1));
USE_IF_ASSERTS_ON(Patch::VariableBasis basis = Patch::translateTypeToBasis(
req_in->var->typeDescription()->getType(), true);)
ASSERT(
fromPatch_in == 0 ||
(Min(
m_low,
fromPatch_in->getExtraLowIndex(basis, req_in->var->getBoundaryLayer())) ==
fromPatch_in->getExtraLowIndex(basis, req_in->var->getBoundaryLayer())));
ASSERT(
fromPatch_in == 0 ||
(Max(
m_high,
fromPatch_in->getExtraHighIndex(basis, req_in->var->getBoundaryLayer())) ==
fromPatch_in->getExtraHighIndex(basis, req_in->var->getBoundaryLayer())));
m_to_tasks.push_back(toTask_in);
}
// eliminate copy, assignment and move
DetailedDep(const DetailedDep&) = delete;
DetailedDep& operator=(const DetailedDep&) = delete;
DetailedDep(DetailedDep&&) = delete;
DetailedDep& operator=(DetailedDep&&) = delete;
// As an arbitrary convention, non-data dependency have a nullptr fromPatch.
// These types of dependencies exist between a modifying task and any task
// that requires the data (from ghost cells in particular) before it is
// modified, preventing the possibility of modifying data while it is being
// used.
bool isNonDataDependency() const { return (m_from_patch == nullptr); }
DetailedDep* m_next;
Task::Dependency* m_comp;
Task::Dependency* m_req;
std::list<DetailedTask*> m_to_tasks;
const Patch* m_from_patch;
IntVector m_low;
IntVector m_high;
int m_matl;
// this is to satisfy a need created by the DynamicLoadBalancer. To keep it
// unrestricted on when it can perform, and to avoid a costly second recompile
// on the next timestep, we add a comm condition which will send/recv data
// based on whether some condition is met at run time - in this case whether
// it is the first execution or not.
CommCondition m_comm_condition;
// for SmallMessages - if we don't copy the complete patch, we need to know
// the range so we can store all segments properly
IntVector m_patch_low;
IntVector m_patch_high;
};
std::ostream&
operator<<(std::ostream& out, const Uintah::DetailedDep& task);
} // namespace Uintah
#endif // CCA_COMPONENTS_SCHEDULERS_DETAILED_DEP_H
| [
"b.banerjee.nz@gmail.com"
] | b.banerjee.nz@gmail.com |
461e5034d4a12266f3e1182986dd79fd2ce22b3d | 9d388c0fc1b97b0b14882a2d41c57456aac19597 | /11 - 22-04/Binario/Binario/pilha.h | 7cb4039b813fc35509996cb1bfe89327aa192fe9 | [] | no_license | renanb4/estrutura-de-dados-I | c241e880f48c693ec3bb1045a45fae0e42075a35 | 0fd98d94c7cda52360ae8251520d3c0c65e7bf44 | refs/heads/master | 2022-11-27T05:02:49.953857 | 2020-07-25T00:10:51 | 2020-07-25T00:10:51 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 926 | h | #include <iostream>
using namespace std;
typedef struct
{
int topo;
int vetor[100];
}Pilha;
//Criar nova pilha
Pilha* cria()
{
//p = malloc(sizeof(Pilha))
Pilha* p = new Pilha();
p->topo = 0;
return p;
}
//Verificar se a pilha está cheia
int cheia(Pilha* p)
{
return (p->topo == 100);
}
//Verificar se a pilha está vazia
int vazia(Pilha* p)
{
return (p->topo == 0);
}
//Inserir novo valor na pilha
//Retorna mensagem se a pilha estiver cheia
void push(Pilha* p, int valor)
{
if (cheia(p))
{
cout << "Pilha cheia!" << endl;
exit(1);//sai da função push
}
p->vetor[p->topo] = valor;
p->topo++;
}
//criar função para remover item da pilha
//retornar mensagem se a pilha estiver vazia.
char pop(Pilha* p)
{
int elem;
if (vazia(p))
{
cout << "Pilha vazia!" << endl;
exit(1);
}
elem = p->vetor[p->topo - 1];
p->topo--;
cout << elem;
return elem;
}
void liberar(Pilha* p)
{
delete p;
} | [
"renan_barbosa91@hotmail.com"
] | renan_barbosa91@hotmail.com |
bc0f11082d0f9a18ff3dd8500860780ce4bb6840 | 0c48f9123bdd92609af09b1668ca62e686e7b9bb | /PaintTool/DrawErase.cpp | b49aa61b70c9d6920c5fa817cae12f2b4f961de9 | [] | no_license | fengzixu/PaintTool | 758364b4ded44f809ad2cb35aeb644392a8ac9df | 4b30a293502123f097cf563aef32832b5c171908 | refs/heads/master | 2021-01-18T15:16:49.063144 | 2015-07-06T09:07:56 | 2015-07-06T09:07:56 | 38,359,045 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,797 | cpp | #include "stdafx.h"
#include "DrawErase.h"
#include "DrawManager.h"
Paint_Struct CDrawErase::ms_static_struct = {0};
CDrawErase::CDrawErase()
{
}
CDrawErase::~CDrawErase()
{
}
BOOL CDrawErase::ChangeCursorResource(HCURSOR& hCursor)
{
hCursor = AtlLoadCursor(IDC_ERRSOR_CURSOR);
::SetClassLong(m_Hwnd,GCL_HCURSOR,(LONG)(hCursor));
::ShowCursor(TRUE);
return 0;
}
BOOL CDrawErase::WriteDC(RECT& rcClient, HPEN& hPen)
{
HPEN hOldPen = NULL;
hOldPen = (HPEN)::SelectObject(ms_static_struct.m_hCompatibleDC, hPen);
::MoveToEx(ms_static_struct.m_hCompatibleDC, m_nStartx + 5, m_nStarty +5, NULL);
::LineTo(ms_static_struct.m_hCompatibleDC, m_nEndx + 5, m_nEndy + 5);
::BitBlt(
m_Hdc, 0, 0
, rcClient.right - rcClient.left
, rcClient.bottom - rcClient.top
, ms_static_struct.m_hCompatibleDC
, 0, 0, SRCCOPY
);
::SelectObject(ms_static_struct.m_hCompatibleDC,hOldPen);
return TRUE;
}
BOOL CDrawErase::Draw()
{
BOOL bRect = FALSE;
RECT rcClient = {0};
HCURSOR hCursor = NULL;
Point start_point(m_nStartx, m_nStarty);
Point end_point(m_nEndx, m_nEndy);
HPEN hPen = CreatePen(PS_SOLID, 15, RGB(255,255,255));
::GetClientRect(m_Hwnd, &rcClient);
CPublicResourceManager::GetInstance()->_ClearFrontStack();
if (FALSE == CDrawManager::GetInstance()->GetCurveFlag())
{
ms_static_struct = CPublicResourceManager::GetInstance()->_PopDCFromBackStack();
CDrawManager::GetInstance()->SetCurveFlag(TRUE);
}
ChangeCursorResource(hCursor);
WriteDC(rcClient, hPen);
if (DROW == m_bStack_flag)
{
CPublicResourceManager::GetInstance()->_PushDCToBackStack(ms_static_struct);
}
bRect = True;
return bRect;
} | [
"fengzixu@163.com"
] | fengzixu@163.com |
ac8dc03b47167bf77c7d36ade65931d114591ab0 | 2457fac37458d89da47d5d84407edc579ada8d2c | /server/space.pb.h | 85aaf2aa021c0c6d90324906faf07db6e90c72e0 | [] | no_license | bakwc/SpaceCapture | 01c5a21a2af9a5c27336c577ef22d67242dff71f | 1d7d1923c85f0ea4a89d9a2417c3642bbf910219 | refs/heads/master | 2020-06-04T13:31:45.264733 | 2014-01-26T09:57:20 | 2014-01-26T09:57:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 32,053 | h | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: space.proto
#ifndef PROTOBUF_space_2eproto__INCLUDED
#define PROTOBUF_space_2eproto__INCLUDED
#include <string>
#include <google/protobuf/stubs/common.h>
#if GOOGLE_PROTOBUF_VERSION < 2004000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 2004001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/repeated_field.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/generated_message_reflection.h>
// @@protoc_insertion_point(includes)
namespace Space {
// Internal implementation detail -- do not call these.
void protobuf_AddDesc_space_2eproto();
void protobuf_AssignDesc_space_2eproto();
void protobuf_ShutdownFile_space_2eproto();
class TControl;
class TPlanet;
class TShip;
class TPlayer;
class TWorld;
// ===================================================================
class TControl : public ::google::protobuf::Message {
public:
TControl();
virtual ~TControl();
TControl(const TControl& from);
inline TControl& operator=(const TControl& from) {
CopyFrom(from);
return *this;
}
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _unknown_fields_;
}
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const ::google::protobuf::Descriptor* descriptor();
static const TControl& default_instance();
void Swap(TControl* other);
// implements Message ----------------------------------------------
TControl* New() const;
void CopyFrom(const ::google::protobuf::Message& from);
void MergeFrom(const ::google::protobuf::Message& from);
void CopyFrom(const TControl& from);
void MergeFrom(const TControl& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::google::protobuf::Metadata GetMetadata() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// required int32 PlanetFrom = 1;
inline bool has_planetfrom() const;
inline void clear_planetfrom();
static const int kPlanetFromFieldNumber = 1;
inline ::google::protobuf::int32 planetfrom() const;
inline void set_planetfrom(::google::protobuf::int32 value);
// required int32 PlanetTo = 2;
inline bool has_planetto() const;
inline void clear_planetto();
static const int kPlanetToFieldNumber = 2;
inline ::google::protobuf::int32 planetto() const;
inline void set_planetto(::google::protobuf::int32 value);
// required int32 EnergyPercent = 3;
inline bool has_energypercent() const;
inline void clear_energypercent();
static const int kEnergyPercentFieldNumber = 3;
inline ::google::protobuf::int32 energypercent() const;
inline void set_energypercent(::google::protobuf::int32 value);
// required string PlayerName = 4;
inline bool has_playername() const;
inline void clear_playername();
static const int kPlayerNameFieldNumber = 4;
inline const ::std::string& playername() const;
inline void set_playername(const ::std::string& value);
inline void set_playername(const char* value);
inline void set_playername(const char* value, size_t size);
inline ::std::string* mutable_playername();
inline ::std::string* release_playername();
// @@protoc_insertion_point(class_scope:Space.TControl)
private:
inline void set_has_planetfrom();
inline void clear_has_planetfrom();
inline void set_has_planetto();
inline void clear_has_planetto();
inline void set_has_energypercent();
inline void clear_has_energypercent();
inline void set_has_playername();
inline void clear_has_playername();
::google::protobuf::UnknownFieldSet _unknown_fields_;
::google::protobuf::int32 planetfrom_;
::google::protobuf::int32 planetto_;
::std::string* playername_;
::google::protobuf::int32 energypercent_;
mutable int _cached_size_;
::google::protobuf::uint32 _has_bits_[(4 + 31) / 32];
friend void protobuf_AddDesc_space_2eproto();
friend void protobuf_AssignDesc_space_2eproto();
friend void protobuf_ShutdownFile_space_2eproto();
void InitAsDefaultInstance();
static TControl* default_instance_;
};
// -------------------------------------------------------------------
class TPlanet : public ::google::protobuf::Message {
public:
TPlanet();
virtual ~TPlanet();
TPlanet(const TPlanet& from);
inline TPlanet& operator=(const TPlanet& from) {
CopyFrom(from);
return *this;
}
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _unknown_fields_;
}
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const ::google::protobuf::Descriptor* descriptor();
static const TPlanet& default_instance();
void Swap(TPlanet* other);
// implements Message ----------------------------------------------
TPlanet* New() const;
void CopyFrom(const ::google::protobuf::Message& from);
void MergeFrom(const ::google::protobuf::Message& from);
void CopyFrom(const TPlanet& from);
void MergeFrom(const TPlanet& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::google::protobuf::Metadata GetMetadata() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// required int32 ID = 1;
inline bool has_id() const;
inline void clear_id();
static const int kIDFieldNumber = 1;
inline ::google::protobuf::int32 id() const;
inline void set_id(::google::protobuf::int32 value);
// required int32 X = 2;
inline bool has_x() const;
inline void clear_x();
static const int kXFieldNumber = 2;
inline ::google::protobuf::int32 x() const;
inline void set_x(::google::protobuf::int32 value);
// required int32 Y = 3;
inline bool has_y() const;
inline void clear_y();
static const int kYFieldNumber = 3;
inline ::google::protobuf::int32 y() const;
inline void set_y(::google::protobuf::int32 value);
// required int32 Radius = 4;
inline bool has_radius() const;
inline void clear_radius();
static const int kRadiusFieldNumber = 4;
inline ::google::protobuf::int32 radius() const;
inline void set_radius(::google::protobuf::int32 value);
// required int32 PlayerId = 5;
inline bool has_playerid() const;
inline void clear_playerid();
static const int kPlayerIdFieldNumber = 5;
inline ::google::protobuf::int32 playerid() const;
inline void set_playerid(::google::protobuf::int32 value);
// required int32 Energy = 6;
inline bool has_energy() const;
inline void clear_energy();
static const int kEnergyFieldNumber = 6;
inline ::google::protobuf::int32 energy() const;
inline void set_energy(::google::protobuf::int32 value);
// @@protoc_insertion_point(class_scope:Space.TPlanet)
private:
inline void set_has_id();
inline void clear_has_id();
inline void set_has_x();
inline void clear_has_x();
inline void set_has_y();
inline void clear_has_y();
inline void set_has_radius();
inline void clear_has_radius();
inline void set_has_playerid();
inline void clear_has_playerid();
inline void set_has_energy();
inline void clear_has_energy();
::google::protobuf::UnknownFieldSet _unknown_fields_;
::google::protobuf::int32 id_;
::google::protobuf::int32 x_;
::google::protobuf::int32 y_;
::google::protobuf::int32 radius_;
::google::protobuf::int32 playerid_;
::google::protobuf::int32 energy_;
mutable int _cached_size_;
::google::protobuf::uint32 _has_bits_[(6 + 31) / 32];
friend void protobuf_AddDesc_space_2eproto();
friend void protobuf_AssignDesc_space_2eproto();
friend void protobuf_ShutdownFile_space_2eproto();
void InitAsDefaultInstance();
static TPlanet* default_instance_;
};
// -------------------------------------------------------------------
class TShip : public ::google::protobuf::Message {
public:
TShip();
virtual ~TShip();
TShip(const TShip& from);
inline TShip& operator=(const TShip& from) {
CopyFrom(from);
return *this;
}
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _unknown_fields_;
}
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const ::google::protobuf::Descriptor* descriptor();
static const TShip& default_instance();
void Swap(TShip* other);
// implements Message ----------------------------------------------
TShip* New() const;
void CopyFrom(const ::google::protobuf::Message& from);
void MergeFrom(const ::google::protobuf::Message& from);
void CopyFrom(const TShip& from);
void MergeFrom(const TShip& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::google::protobuf::Metadata GetMetadata() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// required int32 X = 1;
inline bool has_x() const;
inline void clear_x();
static const int kXFieldNumber = 1;
inline ::google::protobuf::int32 x() const;
inline void set_x(::google::protobuf::int32 value);
// required int32 Y = 2;
inline bool has_y() const;
inline void clear_y();
static const int kYFieldNumber = 2;
inline ::google::protobuf::int32 y() const;
inline void set_y(::google::protobuf::int32 value);
// required int32 PlayerID = 3;
inline bool has_playerid() const;
inline void clear_playerid();
static const int kPlayerIDFieldNumber = 3;
inline ::google::protobuf::int32 playerid() const;
inline void set_playerid(::google::protobuf::int32 value);
// @@protoc_insertion_point(class_scope:Space.TShip)
private:
inline void set_has_x();
inline void clear_has_x();
inline void set_has_y();
inline void clear_has_y();
inline void set_has_playerid();
inline void clear_has_playerid();
::google::protobuf::UnknownFieldSet _unknown_fields_;
::google::protobuf::int32 x_;
::google::protobuf::int32 y_;
::google::protobuf::int32 playerid_;
mutable int _cached_size_;
::google::protobuf::uint32 _has_bits_[(3 + 31) / 32];
friend void protobuf_AddDesc_space_2eproto();
friend void protobuf_AssignDesc_space_2eproto();
friend void protobuf_ShutdownFile_space_2eproto();
void InitAsDefaultInstance();
static TShip* default_instance_;
};
// -------------------------------------------------------------------
class TPlayer : public ::google::protobuf::Message {
public:
TPlayer();
virtual ~TPlayer();
TPlayer(const TPlayer& from);
inline TPlayer& operator=(const TPlayer& from) {
CopyFrom(from);
return *this;
}
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _unknown_fields_;
}
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const ::google::protobuf::Descriptor* descriptor();
static const TPlayer& default_instance();
void Swap(TPlayer* other);
// implements Message ----------------------------------------------
TPlayer* New() const;
void CopyFrom(const ::google::protobuf::Message& from);
void MergeFrom(const ::google::protobuf::Message& from);
void CopyFrom(const TPlayer& from);
void MergeFrom(const TPlayer& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::google::protobuf::Metadata GetMetadata() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// required int32 ID = 1;
inline bool has_id() const;
inline void clear_id();
static const int kIDFieldNumber = 1;
inline ::google::protobuf::int32 id() const;
inline void set_id(::google::protobuf::int32 value);
// required string Name = 2;
inline bool has_name() const;
inline void clear_name();
static const int kNameFieldNumber = 2;
inline const ::std::string& name() const;
inline void set_name(const ::std::string& value);
inline void set_name(const char* value);
inline void set_name(const char* value, size_t size);
inline ::std::string* mutable_name();
inline ::std::string* release_name();
// @@protoc_insertion_point(class_scope:Space.TPlayer)
private:
inline void set_has_id();
inline void clear_has_id();
inline void set_has_name();
inline void clear_has_name();
::google::protobuf::UnknownFieldSet _unknown_fields_;
::std::string* name_;
::google::protobuf::int32 id_;
mutable int _cached_size_;
::google::protobuf::uint32 _has_bits_[(2 + 31) / 32];
friend void protobuf_AddDesc_space_2eproto();
friend void protobuf_AssignDesc_space_2eproto();
friend void protobuf_ShutdownFile_space_2eproto();
void InitAsDefaultInstance();
static TPlayer* default_instance_;
};
// -------------------------------------------------------------------
class TWorld : public ::google::protobuf::Message {
public:
TWorld();
virtual ~TWorld();
TWorld(const TWorld& from);
inline TWorld& operator=(const TWorld& from) {
CopyFrom(from);
return *this;
}
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _unknown_fields_;
}
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const ::google::protobuf::Descriptor* descriptor();
static const TWorld& default_instance();
void Swap(TWorld* other);
// implements Message ----------------------------------------------
TWorld* New() const;
void CopyFrom(const ::google::protobuf::Message& from);
void MergeFrom(const ::google::protobuf::Message& from);
void CopyFrom(const TWorld& from);
void MergeFrom(const TWorld& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::google::protobuf::Metadata GetMetadata() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// repeated .Space.TPlanet Planets = 1;
inline int planets_size() const;
inline void clear_planets();
static const int kPlanetsFieldNumber = 1;
inline const ::Space::TPlanet& planets(int index) const;
inline ::Space::TPlanet* mutable_planets(int index);
inline ::Space::TPlanet* add_planets();
inline const ::google::protobuf::RepeatedPtrField< ::Space::TPlanet >&
planets() const;
inline ::google::protobuf::RepeatedPtrField< ::Space::TPlanet >*
mutable_planets();
// repeated .Space.TShip Ships = 2;
inline int ships_size() const;
inline void clear_ships();
static const int kShipsFieldNumber = 2;
inline const ::Space::TShip& ships(int index) const;
inline ::Space::TShip* mutable_ships(int index);
inline ::Space::TShip* add_ships();
inline const ::google::protobuf::RepeatedPtrField< ::Space::TShip >&
ships() const;
inline ::google::protobuf::RepeatedPtrField< ::Space::TShip >*
mutable_ships();
// repeated .Space.TPlayer Players = 3;
inline int players_size() const;
inline void clear_players();
static const int kPlayersFieldNumber = 3;
inline const ::Space::TPlayer& players(int index) const;
inline ::Space::TPlayer* mutable_players(int index);
inline ::Space::TPlayer* add_players();
inline const ::google::protobuf::RepeatedPtrField< ::Space::TPlayer >&
players() const;
inline ::google::protobuf::RepeatedPtrField< ::Space::TPlayer >*
mutable_players();
// @@protoc_insertion_point(class_scope:Space.TWorld)
private:
::google::protobuf::UnknownFieldSet _unknown_fields_;
::google::protobuf::RepeatedPtrField< ::Space::TPlanet > planets_;
::google::protobuf::RepeatedPtrField< ::Space::TShip > ships_;
::google::protobuf::RepeatedPtrField< ::Space::TPlayer > players_;
mutable int _cached_size_;
::google::protobuf::uint32 _has_bits_[(3 + 31) / 32];
friend void protobuf_AddDesc_space_2eproto();
friend void protobuf_AssignDesc_space_2eproto();
friend void protobuf_ShutdownFile_space_2eproto();
void InitAsDefaultInstance();
static TWorld* default_instance_;
};
// ===================================================================
// ===================================================================
// TControl
// required int32 PlanetFrom = 1;
inline bool TControl::has_planetfrom() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void TControl::set_has_planetfrom() {
_has_bits_[0] |= 0x00000001u;
}
inline void TControl::clear_has_planetfrom() {
_has_bits_[0] &= ~0x00000001u;
}
inline void TControl::clear_planetfrom() {
planetfrom_ = 0;
clear_has_planetfrom();
}
inline ::google::protobuf::int32 TControl::planetfrom() const {
return planetfrom_;
}
inline void TControl::set_planetfrom(::google::protobuf::int32 value) {
set_has_planetfrom();
planetfrom_ = value;
}
// required int32 PlanetTo = 2;
inline bool TControl::has_planetto() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void TControl::set_has_planetto() {
_has_bits_[0] |= 0x00000002u;
}
inline void TControl::clear_has_planetto() {
_has_bits_[0] &= ~0x00000002u;
}
inline void TControl::clear_planetto() {
planetto_ = 0;
clear_has_planetto();
}
inline ::google::protobuf::int32 TControl::planetto() const {
return planetto_;
}
inline void TControl::set_planetto(::google::protobuf::int32 value) {
set_has_planetto();
planetto_ = value;
}
// required int32 EnergyPercent = 3;
inline bool TControl::has_energypercent() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void TControl::set_has_energypercent() {
_has_bits_[0] |= 0x00000004u;
}
inline void TControl::clear_has_energypercent() {
_has_bits_[0] &= ~0x00000004u;
}
inline void TControl::clear_energypercent() {
energypercent_ = 0;
clear_has_energypercent();
}
inline ::google::protobuf::int32 TControl::energypercent() const {
return energypercent_;
}
inline void TControl::set_energypercent(::google::protobuf::int32 value) {
set_has_energypercent();
energypercent_ = value;
}
// required string PlayerName = 4;
inline bool TControl::has_playername() const {
return (_has_bits_[0] & 0x00000008u) != 0;
}
inline void TControl::set_has_playername() {
_has_bits_[0] |= 0x00000008u;
}
inline void TControl::clear_has_playername() {
_has_bits_[0] &= ~0x00000008u;
}
inline void TControl::clear_playername() {
if (playername_ != &::google::protobuf::internal::kEmptyString) {
playername_->clear();
}
clear_has_playername();
}
inline const ::std::string& TControl::playername() const {
return *playername_;
}
inline void TControl::set_playername(const ::std::string& value) {
set_has_playername();
if (playername_ == &::google::protobuf::internal::kEmptyString) {
playername_ = new ::std::string;
}
playername_->assign(value);
}
inline void TControl::set_playername(const char* value) {
set_has_playername();
if (playername_ == &::google::protobuf::internal::kEmptyString) {
playername_ = new ::std::string;
}
playername_->assign(value);
}
inline void TControl::set_playername(const char* value, size_t size) {
set_has_playername();
if (playername_ == &::google::protobuf::internal::kEmptyString) {
playername_ = new ::std::string;
}
playername_->assign(reinterpret_cast<const char*>(value), size);
}
inline ::std::string* TControl::mutable_playername() {
set_has_playername();
if (playername_ == &::google::protobuf::internal::kEmptyString) {
playername_ = new ::std::string;
}
return playername_;
}
inline ::std::string* TControl::release_playername() {
clear_has_playername();
if (playername_ == &::google::protobuf::internal::kEmptyString) {
return NULL;
} else {
::std::string* temp = playername_;
playername_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString);
return temp;
}
}
// -------------------------------------------------------------------
// TPlanet
// required int32 ID = 1;
inline bool TPlanet::has_id() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void TPlanet::set_has_id() {
_has_bits_[0] |= 0x00000001u;
}
inline void TPlanet::clear_has_id() {
_has_bits_[0] &= ~0x00000001u;
}
inline void TPlanet::clear_id() {
id_ = 0;
clear_has_id();
}
inline ::google::protobuf::int32 TPlanet::id() const {
return id_;
}
inline void TPlanet::set_id(::google::protobuf::int32 value) {
set_has_id();
id_ = value;
}
// required int32 X = 2;
inline bool TPlanet::has_x() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void TPlanet::set_has_x() {
_has_bits_[0] |= 0x00000002u;
}
inline void TPlanet::clear_has_x() {
_has_bits_[0] &= ~0x00000002u;
}
inline void TPlanet::clear_x() {
x_ = 0;
clear_has_x();
}
inline ::google::protobuf::int32 TPlanet::x() const {
return x_;
}
inline void TPlanet::set_x(::google::protobuf::int32 value) {
set_has_x();
x_ = value;
}
// required int32 Y = 3;
inline bool TPlanet::has_y() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void TPlanet::set_has_y() {
_has_bits_[0] |= 0x00000004u;
}
inline void TPlanet::clear_has_y() {
_has_bits_[0] &= ~0x00000004u;
}
inline void TPlanet::clear_y() {
y_ = 0;
clear_has_y();
}
inline ::google::protobuf::int32 TPlanet::y() const {
return y_;
}
inline void TPlanet::set_y(::google::protobuf::int32 value) {
set_has_y();
y_ = value;
}
// required int32 Radius = 4;
inline bool TPlanet::has_radius() const {
return (_has_bits_[0] & 0x00000008u) != 0;
}
inline void TPlanet::set_has_radius() {
_has_bits_[0] |= 0x00000008u;
}
inline void TPlanet::clear_has_radius() {
_has_bits_[0] &= ~0x00000008u;
}
inline void TPlanet::clear_radius() {
radius_ = 0;
clear_has_radius();
}
inline ::google::protobuf::int32 TPlanet::radius() const {
return radius_;
}
inline void TPlanet::set_radius(::google::protobuf::int32 value) {
set_has_radius();
radius_ = value;
}
// required int32 PlayerId = 5;
inline bool TPlanet::has_playerid() const {
return (_has_bits_[0] & 0x00000010u) != 0;
}
inline void TPlanet::set_has_playerid() {
_has_bits_[0] |= 0x00000010u;
}
inline void TPlanet::clear_has_playerid() {
_has_bits_[0] &= ~0x00000010u;
}
inline void TPlanet::clear_playerid() {
playerid_ = 0;
clear_has_playerid();
}
inline ::google::protobuf::int32 TPlanet::playerid() const {
return playerid_;
}
inline void TPlanet::set_playerid(::google::protobuf::int32 value) {
set_has_playerid();
playerid_ = value;
}
// required int32 Energy = 6;
inline bool TPlanet::has_energy() const {
return (_has_bits_[0] & 0x00000020u) != 0;
}
inline void TPlanet::set_has_energy() {
_has_bits_[0] |= 0x00000020u;
}
inline void TPlanet::clear_has_energy() {
_has_bits_[0] &= ~0x00000020u;
}
inline void TPlanet::clear_energy() {
energy_ = 0;
clear_has_energy();
}
inline ::google::protobuf::int32 TPlanet::energy() const {
return energy_;
}
inline void TPlanet::set_energy(::google::protobuf::int32 value) {
set_has_energy();
energy_ = value;
}
// -------------------------------------------------------------------
// TShip
// required int32 X = 1;
inline bool TShip::has_x() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void TShip::set_has_x() {
_has_bits_[0] |= 0x00000001u;
}
inline void TShip::clear_has_x() {
_has_bits_[0] &= ~0x00000001u;
}
inline void TShip::clear_x() {
x_ = 0;
clear_has_x();
}
inline ::google::protobuf::int32 TShip::x() const {
return x_;
}
inline void TShip::set_x(::google::protobuf::int32 value) {
set_has_x();
x_ = value;
}
// required int32 Y = 2;
inline bool TShip::has_y() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void TShip::set_has_y() {
_has_bits_[0] |= 0x00000002u;
}
inline void TShip::clear_has_y() {
_has_bits_[0] &= ~0x00000002u;
}
inline void TShip::clear_y() {
y_ = 0;
clear_has_y();
}
inline ::google::protobuf::int32 TShip::y() const {
return y_;
}
inline void TShip::set_y(::google::protobuf::int32 value) {
set_has_y();
y_ = value;
}
// required int32 PlayerID = 3;
inline bool TShip::has_playerid() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void TShip::set_has_playerid() {
_has_bits_[0] |= 0x00000004u;
}
inline void TShip::clear_has_playerid() {
_has_bits_[0] &= ~0x00000004u;
}
inline void TShip::clear_playerid() {
playerid_ = 0;
clear_has_playerid();
}
inline ::google::protobuf::int32 TShip::playerid() const {
return playerid_;
}
inline void TShip::set_playerid(::google::protobuf::int32 value) {
set_has_playerid();
playerid_ = value;
}
// -------------------------------------------------------------------
// TPlayer
// required int32 ID = 1;
inline bool TPlayer::has_id() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void TPlayer::set_has_id() {
_has_bits_[0] |= 0x00000001u;
}
inline void TPlayer::clear_has_id() {
_has_bits_[0] &= ~0x00000001u;
}
inline void TPlayer::clear_id() {
id_ = 0;
clear_has_id();
}
inline ::google::protobuf::int32 TPlayer::id() const {
return id_;
}
inline void TPlayer::set_id(::google::protobuf::int32 value) {
set_has_id();
id_ = value;
}
// required string Name = 2;
inline bool TPlayer::has_name() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void TPlayer::set_has_name() {
_has_bits_[0] |= 0x00000002u;
}
inline void TPlayer::clear_has_name() {
_has_bits_[0] &= ~0x00000002u;
}
inline void TPlayer::clear_name() {
if (name_ != &::google::protobuf::internal::kEmptyString) {
name_->clear();
}
clear_has_name();
}
inline const ::std::string& TPlayer::name() const {
return *name_;
}
inline void TPlayer::set_name(const ::std::string& value) {
set_has_name();
if (name_ == &::google::protobuf::internal::kEmptyString) {
name_ = new ::std::string;
}
name_->assign(value);
}
inline void TPlayer::set_name(const char* value) {
set_has_name();
if (name_ == &::google::protobuf::internal::kEmptyString) {
name_ = new ::std::string;
}
name_->assign(value);
}
inline void TPlayer::set_name(const char* value, size_t size) {
set_has_name();
if (name_ == &::google::protobuf::internal::kEmptyString) {
name_ = new ::std::string;
}
name_->assign(reinterpret_cast<const char*>(value), size);
}
inline ::std::string* TPlayer::mutable_name() {
set_has_name();
if (name_ == &::google::protobuf::internal::kEmptyString) {
name_ = new ::std::string;
}
return name_;
}
inline ::std::string* TPlayer::release_name() {
clear_has_name();
if (name_ == &::google::protobuf::internal::kEmptyString) {
return NULL;
} else {
::std::string* temp = name_;
name_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString);
return temp;
}
}
// -------------------------------------------------------------------
// TWorld
// repeated .Space.TPlanet Planets = 1;
inline int TWorld::planets_size() const {
return planets_.size();
}
inline void TWorld::clear_planets() {
planets_.Clear();
}
inline const ::Space::TPlanet& TWorld::planets(int index) const {
return planets_.Get(index);
}
inline ::Space::TPlanet* TWorld::mutable_planets(int index) {
return planets_.Mutable(index);
}
inline ::Space::TPlanet* TWorld::add_planets() {
return planets_.Add();
}
inline const ::google::protobuf::RepeatedPtrField< ::Space::TPlanet >&
TWorld::planets() const {
return planets_;
}
inline ::google::protobuf::RepeatedPtrField< ::Space::TPlanet >*
TWorld::mutable_planets() {
return &planets_;
}
// repeated .Space.TShip Ships = 2;
inline int TWorld::ships_size() const {
return ships_.size();
}
inline void TWorld::clear_ships() {
ships_.Clear();
}
inline const ::Space::TShip& TWorld::ships(int index) const {
return ships_.Get(index);
}
inline ::Space::TShip* TWorld::mutable_ships(int index) {
return ships_.Mutable(index);
}
inline ::Space::TShip* TWorld::add_ships() {
return ships_.Add();
}
inline const ::google::protobuf::RepeatedPtrField< ::Space::TShip >&
TWorld::ships() const {
return ships_;
}
inline ::google::protobuf::RepeatedPtrField< ::Space::TShip >*
TWorld::mutable_ships() {
return &ships_;
}
// repeated .Space.TPlayer Players = 3;
inline int TWorld::players_size() const {
return players_.size();
}
inline void TWorld::clear_players() {
players_.Clear();
}
inline const ::Space::TPlayer& TWorld::players(int index) const {
return players_.Get(index);
}
inline ::Space::TPlayer* TWorld::mutable_players(int index) {
return players_.Mutable(index);
}
inline ::Space::TPlayer* TWorld::add_players() {
return players_.Add();
}
inline const ::google::protobuf::RepeatedPtrField< ::Space::TPlayer >&
TWorld::players() const {
return players_;
}
inline ::google::protobuf::RepeatedPtrField< ::Space::TPlayer >*
TWorld::mutable_players() {
return &players_;
}
// @@protoc_insertion_point(namespace_scope)
} // namespace Space
#ifndef SWIG
namespace google {
namespace protobuf {
} // namespace google
} // namespace protobuf
#endif // SWIG
// @@protoc_insertion_point(global_scope)
#endif // PROTOBUF_space_2eproto__INCLUDED
| [
"ozinov@quantion.ru"
] | ozinov@quantion.ru |
6578863a54eaf8f34e206e3a550911570d53ca2b | 40fa7b7b351746d200da9d62e091b0ea7d33dced | /Sketch.cpp | 4c12574960955c49d00017a708e166e741484006 | [] | no_license | baorepo/MG126-Shutter | 51e1b384158f32702d9417b6e610deb65c950af8 | ee250ca20e748637a413d0d78b6c4ccac65a693d | refs/heads/master | 2020-04-17T07:36:15.626839 | 2019-01-18T09:15:22 | 2019-01-18T09:15:22 | 166,376,845 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,696 | cpp | /*Begining of Auto generated code by Atmel studio */
#include <Arduino.h>
/*End of auto generated code by Atmel studio */
/*
*
* 2019 Copyright (c) Seeed Technology Inc. All right reserved.
* Author:Baozhu zuo (zuobaozhu@gmail.com)
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
* OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "MG126_Ble.h"
//Beginning of Auto generated function prototypes by Atmel Studio
//End of Auto generated function prototypes by Atmel Studio
#define CS_PIN 7
#define IRQ_PIN 6
MG126_Ble_Class MG126_Ble(CS_PIN,IRQ_PIN);
//Ble Shutter example
void setup() {
// put your setup code here, to run once:
Serial1.begin(9600);
while (!Serial1);
Serial1.println("\n");
Serial1.println("configure Ble ...");
MG126_Ble.ble_init();
Serial1.println("Ble run ...");
//MG126_Ble.io_init();
// Serial1.print("Mac: ");
// Serial1.println((char*)MG126_Ble.get_ble_mac_addr());
}
void loop() {
// put your main code here, to run repeatedly:
//delay(1);
if(digitalRead(IRQ_PIN) == 0)
ble_run(0);
} | [
"baozhu.zuo@gmail.com"
] | baozhu.zuo@gmail.com |
dd509acf57b575d2ff1cc4f6e22243ad5bbfa5cb | 377d6c510e0abd34dfe0a71b745b8a6730bbb773 | /spider_robot_v3.0/controler_v3.0/controler_v3.0.ino | 3139d700cd9a9ac55994b3e13dbe719f7395b8d3 | [] | no_license | nobaa36/-CS50-s---Final-project-spider-robot | 6990deefcbc71ee6702d07999d9bb9fb4175e3ed | 04441eb787b57ffa03682e5ba4e64fd47e407818 | refs/heads/master | 2020-06-23T00:21:32.267071 | 2019-07-23T14:09:29 | 2019-07-23T14:09:29 | 198,443,702 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,347 | ino | #include <LiquidCrystal.h> // lcd library
#include <SPI.h>
#include "RF24.h"
const uint64_t pipe = 0xE8E8F0F0E1LL;
RF24 radio(9,10);
LiquidCrystal lcd(2, 8, 3, 4, 5, 6);
bool sending=false;
byte data[5];
bool spiderMode=true; // true=walking , false=tricks
void setup() {
Serial.begin(115200);
radio.begin();
radio.openWritingPipe(pipe);
pinMode(18,INPUT_PULLUP);
pinMode(19,INPUT_PULLUP);
lcd.begin(16, 2);
chooseMode();
}
void loop() {
if (spiderMode){
data[4]=1;
}else {
data[4]=0;
}
sendData();
if (digitalRead(18)==LOW){
delay(500);
chooseMode();
}
}
void sendData(){
byte leftHorizontal=map(analogRead(A0),0,1023,0,255);
byte leftVertical=map(analogRead(A1),0,1023,0,255);
byte rightVertical=map(analogRead(A2),0,1023,0,255);
byte rightHorizontal=map(analogRead(A3),0,1023,0,255);
data[1]=leftVertical;
data[0]=leftHorizontal;
data[3]=rightVertical;
data[2]=rightHorizontal;
Serial.print(data[0]);
Serial.print(" , ");
Serial.print(data[1]);
Serial.print(" , ");
Serial.print(data[2]);
Serial.print(" , ");
Serial.print(data[3]);
Serial.print(" , ");
Serial.println(data[4]);
sending=false;
while (!sending){
sending=radio.write(data, sizeof(data));
}
}
| [
"nobaa36@github.com"
] | nobaa36@github.com |
27dba47bd76ac7b29e0df3c892009e28565899b4 | 5bfaaaddb5db1a5962bf39d18d44f50ee8fe5c01 | /ALIEN2.cpp | f5150aca56d3f3bfae9cb6fe657b06e4a4888635 | [] | no_license | gsagarcoep/Spoj | 2a86c6c945eaa4634b7bdc5d386197ac19d17d1a | 78209d9ee386ad07055e1018aaf25d3cdd80be57 | refs/heads/master | 2020-03-25T18:24:11.383085 | 2014-09-26T21:02:54 | 2014-09-26T21:02:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,846 | cpp | /*
10471. Aliens at the train, again!
Problem code: ALIEN2
The Alien who doesn’t like to see humans has moved to an Urban City (Yes, a little ironic) and now she’s facing a double-train system, but still, the alien hates humans, so she wants to see the minimum quantity of people possible in her way to the university at the two trains.
The Alien has some sort of anthropophobia, this means she has a phobia to the people or the society, knowing this, she tells you that can only see K persons in the train, if she sees more than that, she will have a panic attack.
With her special powers, the alien knows how much people is on every station of the train A and the train B, she asked you to make a program that, given the number of people in the stations of the train A and B and the maximum number of people she wants to see, you give her the number of stations she will have to cross and the minimum persons found in those stations. Knowing that:
The Alien starts from train A or B (she can choose where to start) but from the station 1.
She can switch from train A or B or viceversa, if she does this, she will see Ai+Bi people, being “i” the station she’s at that moment.
If she sees strictly more persons than the specified, she will automatically exit the train.
INPUT:
The input will contain two integers N (1<=N<=10,000) and K (1<=65,000) being the number of stations and the maximum number of people that the alien wants to see, then, 2 lines will follow, each containing N integers separated by a single space denoting the number of people found in the j-th station of the i-th train. (1<=Ni<=100)
OUTPUT:
Two single numbers denoting the number of stations passed and the people seen.
SAMPLE DATA:
INPUT:
3 10
9 2 4
1 2 9
OUTPUT:
3 9
INPUT2:
5 10
1 7 1 1 1
2 2 2 2 2
OUTPUT2:
5 9
Explanation I/O 1: The alien starts at the train B station 1, she sees 1 people, she continues to the station 2 and then decides to change the train, the alien have seen 4 more people, and then she continues at the train A up to the station 3. At this point the Alien will see (1+4+4) people (9) and has passed 3 stations.
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
int main()
{
int N,k;
scanf("%d%d",&N,&k);
int* arr=(int*)malloc(N*sizeof(int));
int* brr=(int*)malloc(N*sizeof(int));
for(int i=0;i<N;i++)
scanf("%d",&arr[i]);
for(int i=0;i<N;i++)
scanf("%d",&brr[i]);
int i=0;
int temp=0;
for(i=1;i<N;i++)
{
int t1=arr[i],t2=brr[i];
arr[i]=arr[i]+arr[i-1];
brr[i]=brr[i]+brr[i-1];
if(brr[i]>arr[i]+t2)
{
brr[i]=arr[i]+t2;
}
else if(arr[i]>brr[i]+t1)
{
arr[i]=brr[i]+t1;
}
if(arr[i] > k && brr[i]> k)
break;
if(arr[i]>brr[i])
temp=brr[i];
else temp=arr[i];
}
printf("%d %d\n",i,temp);
return 0;
}
| [
"gsagarcoep@gmail.com"
] | gsagarcoep@gmail.com |
a7a755c133c8dfe73c6dda56400fa7efd477c2e6 | b3017c05b608961a8d3a6ebc58cce50c1349291a | /ZGeom/src/Laplacian.cpp | e78ab2197c1a829712260f4876453ff4f9e2ce21 | [] | no_license | sunyzm/ZGeometry | c3db5a4d1287855fab050446124264dd92018ff6 | 65baecab370760df37192765120c22d1eaaa7af8 | refs/heads/master | 2021-01-23T17:30:42.889280 | 2016-12-03T17:51:22 | 2016-12-03T17:51:22 | 5,421,261 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,508 | cpp | #include "Laplacian.h"
#include <map>
#include "EigenCompute.h"
#include "geometry_processing.h"
#include "arithmetic.h"
#include "timer.h"
#include "zassert.h"
namespace ZGeom {
using namespace std;
using ZGeom::Vec3d;
void Laplacian::decompose( int nEig, MatlabEngineWrapper* ep, EigenSystem& eigSys, bool generalized /*= true*/ ) const
{
runtime_assert(ep->isOpened(), "Matlab engine not opened!");
CStopWatch timer;
timer.startTimer();
EigenCompute eigenCompute(ep);
if (generalized) {
#ifdef _DEBUG
std::cout << "Do generalized eigendecomposition!\n";
#endif
eigenCompute.solveGenSym(mLS, mW, nEig, eigSys);
} else {
#ifdef _DEBUG
std::cout << "Do standard eigendecomposition!\n";
#endif
eigenCompute.solveStdSym(mLS, nEig, eigSys);
}
timer.stopTimer("-- Decomposition time: ", "s", std::cout);
}
void Laplacian::decomposeGeneralized(int nEig, MatlabEngineWrapper* ep, EigenSystem& eigSys, const SparseMatrix<double>& matB) const
{
runtime_assert(ep->isOpened(), "Matlab engine not opened!");
CStopWatch timer;
timer.startTimer();
EigenCompute eigenCompute(ep);
std::cout << "Do generalized eigendecomposition!\n";
eigenCompute.solveGenSym(mLS, matB, nEig, eigSys);
timer.stopTimer("Decomposition time: ", "s", std::cout);
}
void Laplacian::computeSubLaplacian( const std::vector<int>& vSelected, Laplacian& subLaplacian ) const
{
const int subSize = (int)vSelected.size();
subLaplacian.mOrder = subSize;
mW.computeSubMatrix(vSelected, subLaplacian.mW);
mLS.computeSubMatrix(vSelected, subLaplacian.mLS);
//TODO:
//subLaplacian.mLS.makeLaplacian();
}
ZGeom::SparseMatrix<double> Laplacian::getSparseMatrix() const
{
SparseMatrix<double> result = getLS();
vector<double> vWeight = getW().getDiagonal();
for (MatElem<double> &elem : result.allElements()) {
elem.mVal /= vWeight[elem.row() - 1];
}
return result;
}
void Laplacian::constructTutte(CMesh* tmesh)
{
// L = D^-1 * (A - D)
mOrder = tmesh->vertCount();
mLS = constructMeshMatrix(*tmesh, ZGeom::MM_GRAPH_LAPLACE);
mLS.scale(-1.0);
mW = constructMeshMatrix(*tmesh, ZGeom::MM_DEGREE);
mSymmetric = false;
}
void Laplacian::constructUmbrella(CMesh* tmesh)
{
// L = A - D
mOrder = tmesh->vertCount();
mLS = constructMeshMatrix(*tmesh, ZGeom::MM_GRAPH_LAPLACE);
mLS.scale(-1);
mW.setToIdentity(mOrder); // set vertex weight matrix to identity; the attained Laplacian becomes symmetric
mSymmetric = true;
}
void Laplacian::constructGeometricUmbrella(CMesh *tmesh)
{
cerr << "constructGeometricUmbrella not defined yet! " << endl;
exit(-1);
mSymmetric = true;
}
void Laplacian::constructNormalizedUmbrella(CMesh* tmesh)
{
/* L = D^(-1/2) * (D-A) * D^(-1/2) */
mOrder = tmesh->vertCount();
mLS = constructMeshMatrix(*tmesh, ZGeom::MM_NORMALIZED_GRAPH_LAPLACE);
mLS.scale(-1);
mW.setToIdentity(mOrder);
mSymmetric = true;
}
/* Construct negative discrete Laplace operator */
void Laplacian::constructCotFormula(CMesh* tmesh)
{
const int vertCount = tmesh->vertCount();
mOrder = vertCount;
std::vector<int> vII, vJJ;
std::vector<double> vSS;
std::vector<double> vWeights(vertCount);
std::vector<double> diagW(vertCount, 0);
for (int vIdx = 0; vIdx < vertCount; ++vIdx) //for every vertex
{
double amix = 0; //mixed area
const CVertex* vi = tmesh->vert(vIdx);
for (int j = 0; j < vi->outValence(); ++j) {
const CHalfEdge* e0 = vi->getHalfEdge(j);
const CHalfEdge* e1 = e0->nextHalfEdge();
const CHalfEdge* e2 = e1->nextHalfEdge();
const CVertex* vj = e0->vert(1);
const CHalfEdge* e2twin = e2->twinHalfEdge();
double len0 = e0->length();
double len1 = e1->length();
double len2 = e2->length();
amix += ZGeom::calMixedTriArea(len0, len1, len2);
double cot_a11(0), cot_a12(0), cot_a21(0), cot_a22(0);
ZGeom::triangleCot(len0, len1, len2, cot_a11, cot_a12);
if (e0->twinHalfEdge() != NULL) {
const CHalfEdge* e10 = e0->twinHalfEdge();
const CHalfEdge* e11 = e10->nextHalfEdge();
const CHalfEdge* e12 = e11->nextHalfEdge();
len1 = e11->length();
len2 = e12->length();
ZGeom::triangleCot(len0, len1, len2, cot_a21, cot_a22);
}
double cota = (cot_a11 + cot_a21) / 2.0;
vII.push_back(vIdx + 1);
vJJ.push_back(vj->getIndex() + 1);
vSS.push_back(cota);
diagW[vIdx] -= cota;
if (e2twin == NULL) { //met an boundary fan edge
const CHalfEdge* e20 = e2;
const CHalfEdge* e21 = e20->nextHalfEdge();
const CHalfEdge* e22 = e21->nextHalfEdge();
len0 = e20->length();
len1 = e21->length();
len2 = e22->length();
double cot_a1, cot_a2;
ZGeom::triangleCot(len0, len1, len2, cot_a1, cot_a2);
double cota = cot_a1 / 2.0;
vII.push_back(vIdx + 1);
vJJ.push_back(e20->getVertIndex(0) + 1);
vSS.push_back(cota);
diagW[vIdx] -= cota;
}
} // for each incident halfedge
vWeights[vIdx] = amix;
}
for (int vIdx = 0; vIdx < vertCount; ++vIdx) {
vII.push_back(vIdx + 1);
vJJ.push_back(vIdx + 1);
vSS.push_back(diagW[vIdx]);
}
mLS.convertFromCOO(mOrder, mOrder, vII, vJJ, vSS);
mW.convertFromDiagonal(vWeights);
mSymmetric = false;
}
void Laplacian::constructSymCot(CMesh* tmesh)
{
const int vertCount = tmesh->vertCount();
constructCotFormula(tmesh);
mW.setToIdentity(vertCount);
mSymmetric = true;
}
void Laplacian::constructAniso(CMesh *tmesh)
{
vector<double> vMeanCurv = ZGeom::getMeshCurvatures(*tmesh, VertCurvature::MEAN);
vector<double> vVertAreas = computeMeshVertArea(*tmesh, ZGeom::VA_MIXED_VORONOI);
vector<Vec3d> vNormals = ZGeom::getMeshVertNormals(*tmesh);
const int vertCount = tmesh->vertCount();
mOrder = vertCount;
std::vector<int> vII, vJJ;
std::vector<double> vSS;
mW.convertFromDiagonal(vVertAreas);
for (int vIdx = 0; vIdx < vertCount; ++vIdx) //for every vertex
{
const CVertex *vi = tmesh->vert(vIdx);
vector<int> vNeighbor = tmesh->getVertNeighborVerts(vIdx, 1, false);
vector<double> edgeWeights(vNeighbor.size());
for (size_t k = 0; k < vNeighbor.size(); ++k) {
const CVertex *vj = tmesh->vert(vNeighbor[k]);
Vec3d pij = vi->pos() - vj->pos();
pij.normalize();
Vec3d nij = vNormals[vIdx] + vNormals[vNeighbor[k]];
nij.normalize();
double cij = pow(fabs(pij.dot(nij)), 0.25);
edgeWeights[k] = exp(-cij) - exp(-1);
}
double totalWeight = std::accumulate(edgeWeights.begin(), edgeWeights.end(), 0.);
for (size_t k = 0; k < vNeighbor.size(); ++k) {
vII.push_back(vIdx + 1);
vJJ.push_back(vNeighbor[k] + 1);
vSS.push_back(edgeWeights[k]);
}
vII.push_back(vIdx + 1);
vJJ.push_back(vIdx + 1);
vSS.push_back(-totalWeight);
}
mLS.convertFromCOO(mOrder, mOrder, vII, vJJ, vSS);
mSymmetric = false;
}
} // end of namespace | [
"mzhong@cs.stonybrook.edu"
] | mzhong@cs.stonybrook.edu |
d1066a06bd363a4f127df6249a63b966c1f355ab | e69a09a9f74052e34e5b85fba9ead50fa51f69b0 | /common/lock_table/test_lock_table.cpp | 0c7623e4f157866123267eab08c81e5b8b8b86b8 | [
"ISC"
] | permissive | JiaboSun/db2 | aa55cf7e46d25724fca9a1d013ed8fe574e00142 | 22967988d0a53226b28759e00f59cbc028e31e0c | refs/heads/master | 2022-12-03T14:40:21.065918 | 2020-08-31T08:59:53 | 2020-08-31T09:01:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,560 | cpp | //
// Created by rrzhang on 2020/6/3.
//
#include <iostream>
#include <vector>
#include <thread>
#include <cassert>
#include "lock_table.h"
#include "util/profiler.h"
#include "util/string_util.h"
using namespace std;
#define lock_table_test_num (10000)
#define test_thread_num (30)
/// 定义一个全为 0 的数组,几个线程并发对所有的位置都加 ++,最后验证是否所有的值都为线程数
void Test_Lock_Table() {
dbx1000::LockTable *lockTable = new dbx1000::LockTable();
lockTable->Init(0, lock_table_test_num, 0);
dbx1000::Profiler profiler;
int a[lock_table_test_num];
for (int i = 0; i < lock_table_test_num; i++) { a[i] = 0; }
vector<thread> threads_write;
/// write && read
profiler.Start();
for (int i = 0; i < test_thread_num; i++) {
threads_write.emplace_back(thread(
[&]() {
for (uint64_t j = 0; j < lock_table_test_num; j++) {
assert(RC::RCOK == lockTable->Lock(j, dbx1000::LockMode::X));
a[j]++;
assert(RC::RCOK == lockTable->UnLock(j));
}
}
));
}
for (int i = 0; i < 20; i++) {
threads_write.emplace_back(thread(
[&]() {
for (uint64_t j = 0; j < lock_table_test_num; j++) {
assert(RC::RCOK == lockTable->Lock(j, dbx1000::LockMode::S));
assert(RC::RCOK == lockTable->UnLock(j));
}
}
));
}
for (int i = 0; i < test_thread_num + 20; i++) {
threads_write[i].join();
}
profiler.End();
cout << test_thread_num << " threads write time : " << profiler.Nanos() << " nanos." << endl;
/// read
profiler.Clear();
profiler.Start();
vector<thread> threads_read;
for (int i = 0; i < test_thread_num; i++) {
threads_read.emplace_back(thread(
[&]() {
for (uint64_t j = 0; j < lock_table_test_num; j++) {
assert(RC::RCOK == lockTable->Lock(j, dbx1000::LockMode::S));
assert(a[j] == test_thread_num);
assert(RC::RCOK == lockTable->UnLock(j));
}
}
));
}
for (int i = 0; i < test_thread_num; i++) {
threads_read[i].join();
}
profiler.End();
cout << test_thread_num << " threads write time : " << profiler.Nanos() << " nanos." << endl;
delete lockTable;
}
| [
"1531883380@qq.com"
] | 1531883380@qq.com |
ddf19824a8a3c0ad6b52f192dc5f6a5957c7e1c4 | e0bfa5d80450d5a0208f5ab61ef1e59ac4bfe669 | /List/PlaylistItem.cpp | 078d88995104cbd4dcb1c3cd56ad4175681468a3 | [] | no_license | hasiburalrahman/List | 807e0f4f766d4ce680764f118251b4ad500f7ee1 | 0951131654ccc3db6c57349a6b1e6e03562e2053 | refs/heads/master | 2023-02-19T19:08:18.147944 | 2021-01-19T08:44:45 | 2021-01-19T08:44:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 617 | cpp | #include <iostream>
#include <string>
#include "PlaylistItem.hpp"
using namespace std;
PlaylistItem::PlaylistItem(std::string title, double length, std::string genre) : title_(title), length_(length), genre_(genre) {}
std::string PlaylistItem::getTitle() const {
return title_;
}
double PlaylistItem::getLength() const {
return length_;
}
std::string PlaylistItem::getGenre() const {
return genre_;
}
void PlaylistItem::setTitle(std::string title) {
title_ = title;
}
void PlaylistItem::setLength(double length) {
length_ = length;
}
void PlaylistItem::setGenre(std::string genre) {
genre_ = genre;
}
| [
"62037316+Popcornguy1@users.noreply.github.com"
] | 62037316+Popcornguy1@users.noreply.github.com |
26dccbb8bfececda98cb78f2464423c459b64224 | 1d928c3f90d4a0a9a3919a804597aa0a4aab19a3 | /c++/JUCE/2015/8/juce_TextDiff.cpp | 4b07015b2bb2e285b4d5e3065bf67ac15400d39c | [] | no_license | rosoareslv/SED99 | d8b2ff5811e7f0ffc59be066a5a0349a92cbb845 | a062c118f12b93172e31e8ca115ce3f871b64461 | refs/heads/main | 2023-02-22T21:59:02.703005 | 2021-01-28T19:40:51 | 2021-01-28T19:40:51 | 306,497,459 | 1 | 1 | null | 2020-11-24T20:56:18 | 2020-10-23T01:18:07 | null | UTF-8 | C++ | false | false | 8,584 | cpp | /*
==============================================================================
This file is part of the juce_core module of the JUCE library.
Copyright (c) 2015 - ROLI Ltd.
Permission to use, copy, modify, and/or distribute this software for any purpose with
or without fee is hereby granted, provided that the above copyright notice and this
permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
------------------------------------------------------------------------------
NOTE! This permissive ISC license applies ONLY to files within the juce_core module!
All other JUCE modules are covered by a dual GPL/commercial license, so if you are
using any other modules, be sure to check that you also comply with their license.
For more details, visit www.juce.com
==============================================================================
*/
struct TextDiffHelpers
{
enum { minLengthToMatch = 3,
maxComplexity = 16 * 1024 * 1024 };
struct StringRegion
{
StringRegion (const String& s) noexcept
: text (s.getCharPointer()), start (0), length (s.length()) {}
StringRegion (const String::CharPointerType t, int s, int len) noexcept
: text (t), start (s), length (len) {}
void incrementStart() noexcept { ++text; ++start; --length; }
String::CharPointerType text;
int start, length;
};
static void addInsertion (TextDiff& td, const String::CharPointerType text, int index, int length)
{
TextDiff::Change c;
c.insertedText = String (text, (size_t) length);
c.start = index;
c.length = 0;
td.changes.add (c);
}
static void addDeletion (TextDiff& td, int index, int length)
{
TextDiff::Change c;
c.start = index;
c.length = length;
td.changes.add (c);
}
static void diffSkippingCommonStart (TextDiff& td, StringRegion a, StringRegion b)
{
for (;;)
{
const juce_wchar ca = *a.text;
const juce_wchar cb = *b.text;
if (ca != cb || ca == 0)
break;
a.incrementStart();
b.incrementStart();
}
diffRecursively (td, a, b);
}
static void diffRecursively (TextDiff& td, StringRegion a, StringRegion b)
{
int indexA = 0, indexB = 0;
const int len = findLongestCommonSubstring (a.text, a.length, indexA,
b.text, b.length, indexB);
if (len >= minLengthToMatch)
{
if (indexA > 0 && indexB > 0)
diffSkippingCommonStart (td, StringRegion (a.text, a.start, indexA),
StringRegion (b.text, b.start, indexB));
else if (indexA > 0)
addDeletion (td, b.start, indexA);
else if (indexB > 0)
addInsertion (td, b.text, b.start, indexB);
diffRecursively (td, StringRegion (a.text + (indexA + len), a.start + indexA + len, a.length - indexA - len),
StringRegion (b.text + (indexB + len), b.start + indexB + len, b.length - indexB - len));
}
else
{
if (a.length > 0) addDeletion (td, b.start, a.length);
if (b.length > 0) addInsertion (td, b.text, b.start, b.length);
}
}
static int findLongestCommonSubstring (String::CharPointerType a, const int lenA, int& indexInA,
String::CharPointerType b, const int lenB, int& indexInB) noexcept
{
if (lenA == 0 || lenB == 0)
return 0;
if (lenA * lenB > maxComplexity)
return findCommonSuffix (a, lenA, indexInA,
b, lenB, indexInB);
const size_t scratchSpace = sizeof (int) * (2 + 2 * (size_t) lenB);
int* const lines = (int*) alloca (scratchSpace);
zeromem (lines, scratchSpace);
int* l0 = lines;
int* l1 = l0 + lenB + 1;
int loopsWithoutImprovement = 0;
int bestLength = 0;
for (int i = 0; i < lenA; ++i)
{
const juce_wchar ca = a.getAndAdvance();
String::CharPointerType b2 (b);
for (int j = 0; j < lenB; ++j)
{
if (ca != b2.getAndAdvance())
{
l1[j + 1] = 0;
}
else
{
const int len = l0[j] + 1;
l1[j + 1] = len;
if (len > bestLength)
{
loopsWithoutImprovement = 0;
bestLength = len;
indexInA = i;
indexInB = j;
}
}
}
if (++loopsWithoutImprovement > 100)
break;
std::swap (l0, l1);
}
indexInA -= bestLength - 1;
indexInB -= bestLength - 1;
return bestLength;
}
static int findCommonSuffix (String::CharPointerType a, const int lenA, int& indexInA,
String::CharPointerType b, const int lenB, int& indexInB) noexcept
{
int length = 0;
a += lenA - 1;
b += lenB - 1;
while (length < lenA && length < lenB && *a == *b)
{
--a;
--b;
++length;
}
indexInA = lenA - length;
indexInB = lenB - length;
return length;
}
};
TextDiff::TextDiff (const String& original, const String& target)
{
TextDiffHelpers::diffSkippingCommonStart (*this, original, target);
}
String TextDiff::appliedTo (String text) const
{
for (int i = 0; i < changes.size(); ++i)
text = changes.getReference(i).appliedTo (text);
return text;
}
bool TextDiff::Change::isDeletion() const noexcept
{
return insertedText.isEmpty();
}
String TextDiff::Change::appliedTo (const String& text) const noexcept
{
return text.replaceSection (start, length, insertedText);
}
//==============================================================================
//==============================================================================
#if JUCE_UNIT_TESTS
class DiffTests : public UnitTest
{
public:
DiffTests() : UnitTest ("TextDiff class") {}
static String createString (Random& r)
{
juce_wchar buffer[500] = { 0 };
for (int i = r.nextInt (numElementsInArray (buffer) - 1); --i >= 0;)
{
if (r.nextInt (10) == 0)
{
do
{
buffer[i] = (juce_wchar) (1 + r.nextInt (0x10ffff - 1));
}
while (! CharPointer_UTF16::canRepresent (buffer[i]));
}
else
buffer[i] = (juce_wchar) ('a' + r.nextInt (3));
}
return CharPointer_UTF32 (buffer);
}
void testDiff (const String& a, const String& b)
{
TextDiff diff (a, b);
const String result (diff.appliedTo (a));
expectEquals (result, b);
}
void runTest() override
{
beginTest ("TextDiff");
Random r = getRandom();
testDiff (String::empty, String::empty);
testDiff ("x", String::empty);
testDiff (String::empty, "x");
testDiff ("x", "x");
testDiff ("x", "y");
testDiff ("xxx", "x");
testDiff ("x", "xxx");
for (int i = 1000; --i >= 0;)
{
String s (createString (r));
testDiff (s, createString (r));
testDiff (s + createString (r), s + createString (r));
}
}
};
static DiffTests diffTests;
#endif
| [
"rodrigosoaresilva@gmail.com"
] | rodrigosoaresilva@gmail.com |
f8791d142097fa7bc417246463638b121daca79c | 5bf606713e9e7e906ddd20c52840216a86c98544 | /syntactic analysis/experiment1.h | be83ff7f2ffeafe7d69f900778867f8c9d8c7bbb | [] | no_license | BertrandGauss/Compiler | ac42eec674fe5cd0cd1df461b1edebb8fc5a43a9 | 49072682f2515c3f12d7afc2d74698c77d1fb9f4 | refs/heads/main | 2023-06-29T10:52:33.797954 | 2021-07-26T09:14:27 | 2021-07-26T09:14:27 | 367,775,965 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 364 | h | #ifndef _EXPERIMENT1_H
#define _EXPERIMENT1_H
#include <string>
#include <map>
using namespace std;
#define GRAMMAR_BASE 40 //动态生成的基值
struct node{
string word;
string type;
int number;
int row;
int col;
node* next;
};
void initKeyword();
void initDelimiter();
void initOperate();
void init();
node* lex();
int* getRowCol();
#endif
| [
"noreply@github.com"
] | BertrandGauss.noreply@github.com |
bb02d62fcfb73710722651cfb14b8cf0402f7d8b | 34874bd874c9e3016c9f4af332294e4f605b0e35 | /lab_8/at_home/ChequingAccount.cpp | 75c8bec40ae797f03d1806ded1be3f50f8f0c8c0 | [] | no_license | JelaniThompson/OOP244-1 | a8917156f1101663cb4b1258ab152e02090b345e | b4ac98db1038ec76daf67e2df381d96980588ec9 | refs/heads/master | 2020-03-09T14:49:52.857761 | 2018-04-06T17:17:56 | 2018-04-06T17:17:56 | 128,844,409 | 1 | 0 | null | 2018-04-09T23:11:51 | 2018-04-09T23:11:51 | null | UTF-8 | C++ | false | false | 1,776 | cpp | // OOP244 Workshop 8: Virtual Functions and Abstract Base Classes
// File: ChequingAccount.cpp
// Version: 2.0
// Date: 2017/12/11
// Author: Chris Szalwinski, based on previous work by Heidar Davoudi
// Description:
// This file implements the ChequingAccount class
///////////////////////////////////////////////////
#include "ChequingAccount.h"
using namespace std;
namespace sict {
// constructor initializes balance and transaction fee
//
ChequingAccount::ChequingAccount(double initBalance, double transactionFee, double monthEndFee) : Account(initBalance) {
(transactionFee > 0) ? m_Transaction = transactionFee : m_Transaction = 0.0;
(monthEndFee > 0) ? m_MonthEnd = monthEndFee : m_MonthEnd = 0.0;
}
// credit (add) an amount to the account balance and charge fee
// returns bool indicating whether money was credited
//
bool ChequingAccount::credit(double amtToCredit) {
Account::debit(m_Transaction);
return Account::credit(amtToCredit);
}
// debit (subtract) an amount from the account balance and charge fee
// returns bool indicating whether money was debited
//
bool ChequingAccount::debit(double amtToDebit) {
return Account::debit(amtToDebit + m_Transaction);
}
// monthEnd debits month end fee
//
void ChequingAccount::monthEnd() {
Account::debit(m_MonthEnd + m_Transaction);
}
// display inserts account information into ostream os
//
void ChequingAccount::display(std::ostream& os) const {
os << "Account type: Chequing" << std::endl;
os.unsetf(std::ios::floatfield);
os.precision(2);
os.setf(std::ios::fixed, std::ios::floatfield);
os << "Balance: $" << balance() << std::endl;
os << "Per Transaction Fee: " << m_Transaction << std::endl;
os << "Monthly Fee: " << m_MonthEnd << std::endl;
}
}
| [
"leanjunio@live.com"
] | leanjunio@live.com |
26b310e2d1b0b74c172398b58851d37a4d3b7ec7 | a09274b324f25cf167090f6b75b3f5eb56a6e1b5 | /2/2hw/3/SortedSetTest.h | bd1a70613ad602ae1a6b58fb62a21726e829c3f1 | [] | no_license | shurik111333/homework | e409ddd5a0250c9544b2513ecf6c38a1ba98e65c | 7a97089572f1c316fd2bae620bfba8ff796822f1 | refs/heads/master | 2020-05-21T12:33:33.080528 | 2017-06-03T09:44:52 | 2017-06-03T09:44:52 | 47,825,887 | 1 | 1 | null | 2017-06-03T09:44:53 | 2015-12-11T12:36:12 | C++ | UTF-8 | C++ | false | false | 3,704 | h | #pragma once
#include <QtCore/QObject>
#include <QtTest/QtTest>
#include "ListArray.h"
#include "SortedSet.h"
class SortedSetTest : public QObject
{
Q_OBJECT
public:
explicit SortedSetTest(QObject *parent = 0)
:QObject(parent)
{}
private:
SortedSet *set;
ListArray *getList(int size)
{
ListArray *list = new ListArray(size);
for (int i = 0; i < size; i++)
{
list->insert(i, i);
}
return list;
}
private slots:
void init()
{
set = new SortedSet();
}
void cleanup()
{
set->clear();
delete set;
}
// SortedSet::empty() ----------------------------------
void testEmptySet()
{
QVERIFY(set->empty());
}
void testAddFewElementsAndCheckEmpty()
{
for (int i = 1; i < 10; i++)
{
set->add(getList(i));
QVERIFY(!set->empty());
}
}
// SortedSet::remove() ---------------------------------
void testRemoveFromEmptySet()
{
for (int i = 1; i < 5; i++)
{
ListArray *list = getList(i);
QVERIFY(!set->remove(list));
delete list;
}
}
void testAddAndRemoveOneElement()
{
set->add(getList(5));
ListArray *list = getList(5);
QVERIFY(set->remove(list));
delete list;
QVERIFY(set->empty());
}
void testRemoveFewElements()
{
for (int i = 1; i < 10; i++)
{
set->add(getList(i));
}
for (int i = 9; i > 0; i--)
{
ListArray *list = getList(i);
QVERIFY(set->remove(list));
delete list;
QCOMPARE(set->getCount(), i - 1);
}
}
// SortedSet::clear() ----------------------------------
void testSetClear()
{
for (int i = 1; i < 10; i++)
{
set->add(getList(i));
}
set->clear();
QVERIFY(set->empty());
}
//SortedSet::min() --------------------------------
void testGetMinWhenAddIncreasingSequence()
{
for (int i = 1; i < 10; i++)
{
set->add(getList(i));
}
for (int i = 1; i < 10; i++)
{
QCOMPARE(set->min()->getCount(), i);
set->remove(set->min());
}
}
void testGetMinWhenAddDecresingSequence()
{
for (int i = 9; i > 0; i--)
{
set->add(getList(i));
}
for (int i = 1; i < 10; i++)
{
QCOMPARE(set->min()->getCount(), i);
set->remove(set->min());
}
}
// SortedSet::max() --------------------------------
void testGetMaxWhenAddDecresingSequence()
{
for (int i = 9; i > 0; i--)
{
set->add(getList(i));
}
for (int i = 1; i < 10; i++)
{
QCOMPARE(set->max()->getCount(), 10 - i);
set->remove(set->max());
}
}
void testGetMaxWhenAddIncreasingSequence()
{
for (int i = 1; i < 10; i++)
{
set->add(getList(i));
}
for (int i = 1; i < 10; i++)
{
QCOMPARE(set->max()->getCount(), 10 - i);
set->remove(set->max());
}
}
// SortedSet::contains() ----------------------------------------
void testContainsAllAddElements()
{
for (int i = 1; i < 10; i++)
{
set->add(getList(i));
}
for (int i = 1; i < 10; i++)
{
ListArray *list = getList(i);
QVERIFY(set->contains(list));
delete list;
}
}
// SortedSet::getCount() ----------------------------------------
void testCountOfEmptySet()
{
QCOMPARE(set->getCount(), 0);
}
void testCountOfNonEmptyStack()
{
for (int i = 1; i < 10; i++)
{
set->add(getList(i));
QCOMPARE(set->getCount(), i);
}
}
// Equals elements ----------------------------------------------
void testTwoEqualElements()
{
set->add(getList(5));
QVERIFY(!set->add(getList(5)));
QCOMPARE(set->getCount(), 1);
}
void testAddEqualElement()
{
set->add(getList(3));
set->add(getList(6));
QVERIFY(!set->add(getList(6)));
QCOMPARE(set->getCount(), 2);
}
void testAddFewEqualElements()
{
set->add(getList(4));
for (int i = 0; i < 5; i++)
{
QVERIFY(!set->add(getList(4)));
}
QCOMPARE(set->getCount(), 1);
}
};
| [
"chudov.aleksandr94@gmail.com"
] | chudov.aleksandr94@gmail.com |
877767cd24647a3660e7ebc889f8c4015f451c9f | cdf33722eaca84c015c16fb090bd05d70c9ae626 | /superglue-master/include/sg/option/savedag.hpp | 6f3755b044aa69e14c126d854d27aeb1d32efa92 | [
"0BSD"
] | permissive | sbillah/GeneralUtility | ad19ce0d58a9eb7b4a7670c56a75ef58b1228f3d | 63633f31168add091e7536596707d346000df536 | refs/heads/master | 2021-01-23T06:35:44.652783 | 2017-01-11T00:17:35 | 2017-01-11T00:17:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,854 | hpp | #ifndef SG_SAVEDAG_HPP_INCLUDED
#define SG_SAVEDAG_HPP_INCLUDED
//
// collect DAG log data
//
#include "sg/option/log.hpp"
#include "sg/core/accessutil.hpp"
#include "sg/core/spinlock.hpp"
#include "sg/platform/gettime.hpp"
#include <fstream>
#include <string>
#include <sstream>
#include <map>
#include <set>
#include <vector>
namespace sg {
template<typename Options> class Handle;
namespace detail {
struct Node {
std::string name;
std::string style;
int type;
Time::TimeUnit time_stamp;
Node(const std::string &name_,
const std::string &style_,
int type_)
: name(name_), style(style_), type(type_) {
time_stamp = Time::getTime();
}
};
struct TaskFinish {
size_t taskid;
size_t handleid;
size_t version;
TaskFinish(size_t taskid_,
size_t handleid_,
size_t version_)
: taskid(taskid_), handleid(handleid_), version(version_)
{}
};
struct TaskDependency {
size_t taskid;
size_t handleid;
size_t version;
size_t type;
TaskDependency(size_t taskid_,
size_t handleid_,
size_t version_,
size_t type_)
: taskid(taskid_), handleid(handleid_), version(version_), type(type_)
{}
};
struct LogDagData {
SpinLock spinlock;
std::vector<Node> nodes;
std::map<size_t, size_t> tasknodes;
std::map< std::pair<size_t, size_t>, size_t> datanodes;
std::vector<size_t> ranks;
std::vector<TaskFinish> task_finish;
std::vector<TaskDependency> task_dependency;
void clear() {
nodes.clear();
tasknodes.clear();
datanodes.clear();
ranks.clear();
task_finish.clear();
task_dependency.clear();
}
};
// ===========================================================================
// GetStyle
// ===========================================================================
template<typename T>
class TypeHasGetStyle {
private:
typedef char yes;
typedef struct { char dummy[2]; } no;
template<typename U, std::string (U::*)()> struct TypeCheck {};
template<typename U> static yes test(TypeCheck<U, &U::get_style>*);
template<typename U> static no test(...);
public:
enum { value = (sizeof(test<T>(0)) == sizeof(yes)) };
};
template<typename Options, bool> struct GetStyle {
static std::string get_style(TaskBase<Options> *) {
return "";
}
};
template<typename Options>
struct GetStyle<Options, true> {
static std::string get_style(TaskBase<Options> *task) {
return task->get_style();
}
};
template<typename Options>
std::string get_style(TaskBase<Options> *task) {
return GetStyle<Options, TypeHasGetStyle< TaskBase<Options> >::value >::get_style(task);
}
} // namespace detail
// ===========================================================================
// Option Logging_DAG
// ===========================================================================
template<typename Options>
class SaveDAG {
typedef typename Options::version_t version_t;
private:
static size_t add_node(detail::LogDagData &data, std::string name, std::string style, size_t type) {
data.nodes.push_back(detail::Node(name, style, type));
return data.nodes.size()-1;
}
static void register_task_node(detail::LogDagData &data, TaskBase<Options> *task) {
size_t taskId = task->get_global_id();
if (data.tasknodes.find(taskId) != data.tasknodes.end())
return;
std::stringstream ss;
ss << task;
size_t new_node = add_node(data, ss.str(), get_style(task), 0);
data.tasknodes[taskId] = new_node;
}
static void register_data_node(detail::LogDagData &data, Handle<Options> *handle, size_t version) {
size_t handleId = handle->get_global_id();
std::pair<size_t, size_t> id(handleId, version);
if (data.datanodes.find(id) != data.datanodes.end())
return;
std::stringstream ss;
ss << "$" << handle << "_{" << version << "}$";
size_t new_node = add_node(data, ss.str(), "[shape=rectangle,style=filled,fillcolor=gray]", 1);
data.datanodes[id] = new_node;
}
public:
static detail::LogDagData &get_dag_data() {
static detail::LogDagData data;
return data;
}
static void task_finish(TaskBase<Options> *task, Handle<Options> *handle, size_t newVersion) {
detail::LogDagData &data(get_dag_data());
SpinLockScoped lock(data.spinlock);
// have to register nodes here, as we cannot get name otherwise.
register_data_node(data, handle, newVersion);
data.task_finish.push_back(detail::TaskFinish(task->get_global_id(), handle->get_global_id(), newVersion));
}
static void add_dependency(TaskBase<Options> *task, Handle<Options> *handle, version_t required_version, int type) {
detail::LogDagData &data(get_dag_data());
SpinLockScoped lock(data.spinlock);
// have to register nodes here, as we cannot get name otherwise.
register_task_node(data, task);
register_data_node(data, handle, required_version);
data.task_dependency.push_back(detail::TaskDependency(task->get_global_id(),
handle->get_global_id(),
required_version, type));
}
static void new_rank() {
detail::LogDagData &data(get_dag_data());
if (data.nodes.empty())
return;
if (!data.ranks.empty()) {
size_t old = data.ranks[data.ranks.size()-1];
if (data.nodes.size() == old)
return;
}
data.ranks.push_back(data.nodes.size());
};
};
} // namespace sg
#endif // SG_SAVEDAG_HPP_INCLUDED
| [
"hjs"
] | hjs |
7418ee260fbac79ce6bfd90b8fc9feb3269c3031 | 95271f115e73cf1df433b6280f866312bc833739 | /09.quickSort.cpp | 3433f286df857f73dbbaf1191e4142dcf8bf4e2d | [] | no_license | AkisAya/ZJU_DSA_2016 | 11a3c570d4d6d3be56425498f1cb43c6687dd457 | dde9cf812496f7bfb9603a91dd503a5197dae85f | refs/heads/master | 2020-11-30T16:46:24.286706 | 2016-11-25T07:54:22 | 2016-11-25T07:54:22 | 67,231,248 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,241 | cpp | #include <stdio.h>
void swap(int *a, int *b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
void qSort(int a[], int low, int high) {
// int pivot = a[low];
int pivotPoint;
int medium = (low + high) / 2;
if (a[low] >= a[high] && a[low] <= a[medium] || a[low] <= a[high] && a[low] >= a[medium])
pivotPoint = low;
else if(a[medium] >= a[high] && a[medium] <= a[low] || a[medium] >= a[low] && a[medium] <= a[high])
pivotPoint = medium;
else
pivotPoint = high;
int pivot = a[pivotPoint];
int left = low, right = high;
if(low >= high) return;
swap(&a[pivotPoint], &a[right]); // swap the pivot with the last one
while(1) {
while((low < high) && (pivot >= a[low])) low++;
while((low < high) && (pivot <= a[high])) high--;
if(low < high)
swap(&a[low], &a[high]);
else
break;
}
swap(&a[low], &a[right]); // swap the pivot with the last one
qSort(a, left, low-1);
qSort(a, low+1, right);
}
void quickSort(int a[], int N) {
qSort(a, 0, N-1);
}
void print(int a[], int n) {
printf("%d", a[0]);
for(int i = 1; i < n; i++)
printf(" %d", a[i]);
}
int main() {
int N;
scanf("%d", &N);
int a[N];
for(int i = 0; i < N; i++)
scanf("%d", &a[i]);
quickSort(a, N);
print(a, N);
return 0;
}
| [
"akikevinsama@gmail.com"
] | akikevinsama@gmail.com |
0dbb80462eb0e18496442f2de4efd8b4849610c4 | e98e505de1a1a3542189125ef4bdde147f9c77cd | /ui/aura/mus/input_method_mus_unittest.cc | bafcfe4593c1886a6e64eac51daa9315425d4225 | [
"BSD-3-Clause"
] | permissive | jesonlay/chromium | b98fca219ab71d230df9a758252058a18e075a06 | 292532fedbb55d68a83b46c106fd04849a47571d | refs/heads/master | 2022-12-16T15:25:13.723395 | 2017-03-20T14:36:34 | 2017-03-20T15:37:49 | 158,929,892 | 0 | 0 | NOASSERTION | 2018-11-24T11:32:20 | 2018-11-24T11:32:19 | null | UTF-8 | C++ | false | false | 3,663 | cc | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/aura/mus/input_method_mus.h"
#include "services/ui/public/interfaces/ime/ime.mojom.h"
#include "ui/aura/test/aura_test_base.h"
#include "ui/aura/test/mus/input_method_mus_test_api.h"
#include "ui/aura/window.h"
#include "ui/base/ime/input_method_delegate.h"
namespace aura {
namespace {
// Empty implementation of InputMethodDelegate.
class TestInputMethodDelegate : public ui::internal::InputMethodDelegate {
public:
TestInputMethodDelegate() {}
~TestInputMethodDelegate() override {}
// ui::internal::InputMethodDelegate:
ui::EventDispatchDetails DispatchKeyEventPostIME(ui::KeyEvent* key) override {
return ui::EventDispatchDetails();
}
private:
DISALLOW_COPY_AND_ASSIGN(TestInputMethodDelegate);
};
using ProcessKeyEventCallback = base::Callback<void(bool)>;
using ProcessKeyEventCallbacks = std::vector<ProcessKeyEventCallback>;
using EventResultCallback = base::Callback<void(ui::mojom::EventResult)>;
// InputMethod implementation that queues up the callbacks supplied to
// ProcessKeyEvent().
class TestInputMethod : public ui::mojom::InputMethod {
public:
TestInputMethod() {}
~TestInputMethod() override {}
ProcessKeyEventCallbacks* process_key_event_callbacks() {
return &process_key_event_callbacks_;
}
// ui::ime::InputMethod:
void OnTextInputTypeChanged(ui::TextInputType text_input_type) override {}
void OnCaretBoundsChanged(const gfx::Rect& caret_bounds) override {}
void ProcessKeyEvent(std::unique_ptr<ui::Event> key_event,
const ProcessKeyEventCallback& callback) override {
process_key_event_callbacks_.push_back(callback);
}
void CancelComposition() override {}
private:
ProcessKeyEventCallbacks process_key_event_callbacks_;
DISALLOW_COPY_AND_ASSIGN(TestInputMethod);
};
} // namespace
using InputMethodMusTest = test::AuraTestBaseMus;
namespace {
// Used in closure supplied to processing the event.
void RunFunctionWithEventResult(bool* was_run, ui::mojom::EventResult result) {
*was_run = true;
}
} // namespace
TEST_F(InputMethodMusTest, PendingCallbackRunFromDestruction) {
aura::Window window(nullptr);
window.Init(ui::LAYER_NOT_DRAWN);
bool was_event_result_callback_run = false;
// Create an InputMethodMus and foward an event to it.
{
TestInputMethodDelegate input_method_delegate;
InputMethodMus input_method_mus(&input_method_delegate, &window);
TestInputMethod test_input_method;
InputMethodMusTestApi::SetInputMethod(&input_method_mus,
&test_input_method);
std::unique_ptr<EventResultCallback> callback =
base::MakeUnique<EventResultCallback>(base::Bind(
&RunFunctionWithEventResult, &was_event_result_callback_run));
InputMethodMusTestApi::CallSendKeyEventToInputMethod(
&input_method_mus, ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_RETURN, 0),
std::move(callback));
// Add a null callback as well, to make sure null is deal with.
InputMethodMusTestApi::CallSendKeyEventToInputMethod(
&input_method_mus, ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_RETURN, 0),
nullptr);
// The event should have been queued.
EXPECT_EQ(2u, test_input_method.process_key_event_callbacks()->size());
// Callback should not have been run yet.
EXPECT_FALSE(was_event_result_callback_run);
}
// When the destructor is run the callback should be run.
EXPECT_TRUE(was_event_result_callback_run);
}
} // namespace aura
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
ac2bdeeb2a7eddbc06c9c693d0c13fa7d00a896c | bb6ebff7a7f6140903d37905c350954ff6599091 | /ui/views/bubble/bubble_delegate_unittest.cc | 9070c2fe758afc980a8c1859e383c6301453a164 | [
"BSD-3-Clause"
] | permissive | PDi-Communication-Systems-Inc/lollipop_external_chromium_org | faa6602bd6bfd9b9b6277ce3cd16df0bd26e7f2f | ccadf4e63dd34be157281f53fe213d09a8c66d2c | refs/heads/master | 2022-12-23T18:07:04.568931 | 2016-04-11T16:03:36 | 2016-04-11T16:03:36 | 53,677,925 | 0 | 1 | BSD-3-Clause | 2022-12-09T23:46:46 | 2016-03-11T15:49:07 | C++ | UTF-8 | C++ | false | false | 10,340 | 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 "ui/base/hit_test.h"
#include "ui/views/bubble/bubble_delegate.h"
#include "ui/views/bubble/bubble_frame_view.h"
#include "ui/views/test/test_widget_observer.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_observer.h"
namespace views {
namespace {
class TestBubbleDelegateView : public BubbleDelegateView {
public:
TestBubbleDelegateView(View* anchor_view)
: BubbleDelegateView(anchor_view, BubbleBorder::TOP_LEFT),
view_(new View()) {
view_->SetFocusable(true);
AddChildView(view_);
}
virtual ~TestBubbleDelegateView() {}
void SetAnchorRectForTest(gfx::Rect rect) {
SetAnchorRect(rect);
}
void SetAnchorViewForTest(View* view) {
SetAnchorView(view);
}
// BubbleDelegateView overrides:
virtual View* GetInitiallyFocusedView() OVERRIDE { return view_; }
virtual gfx::Size GetPreferredSize() const OVERRIDE {
return gfx::Size(200, 200);
}
private:
View* view_;
DISALLOW_COPY_AND_ASSIGN(TestBubbleDelegateView);
};
class BubbleDelegateTest : public ViewsTestBase {
public:
BubbleDelegateTest() {}
virtual ~BubbleDelegateTest() {}
// Creates a test widget that owns its native widget.
Widget* CreateTestWidget() {
Widget* widget = new Widget();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget->Init(params);
return widget;
}
private:
DISALLOW_COPY_AND_ASSIGN(BubbleDelegateTest);
};
} // namespace
TEST_F(BubbleDelegateTest, CreateDelegate) {
scoped_ptr<Widget> anchor_widget(CreateTestWidget());
BubbleDelegateView* bubble_delegate = new BubbleDelegateView(
anchor_widget->GetContentsView(), BubbleBorder::NONE);
bubble_delegate->set_color(SK_ColorGREEN);
Widget* bubble_widget = BubbleDelegateView::CreateBubble(bubble_delegate);
EXPECT_EQ(bubble_delegate, bubble_widget->widget_delegate());
EXPECT_EQ(bubble_widget, bubble_delegate->GetWidget());
test::TestWidgetObserver bubble_observer(bubble_widget);
bubble_widget->Show();
BubbleBorder* border = bubble_delegate->GetBubbleFrameView()->bubble_border();
EXPECT_EQ(bubble_delegate->arrow(), border->arrow());
EXPECT_EQ(bubble_delegate->color(), border->background_color());
EXPECT_FALSE(bubble_observer.widget_closed());
bubble_widget->CloseNow();
EXPECT_TRUE(bubble_observer.widget_closed());
}
TEST_F(BubbleDelegateTest, CloseAnchorWidget) {
scoped_ptr<Widget> anchor_widget(CreateTestWidget());
BubbleDelegateView* bubble_delegate = new BubbleDelegateView(
anchor_widget->GetContentsView(), BubbleBorder::NONE);
// Preventing close on deactivate should not prevent closing with the anchor.
bubble_delegate->set_close_on_deactivate(false);
Widget* bubble_widget = BubbleDelegateView::CreateBubble(bubble_delegate);
EXPECT_EQ(bubble_delegate, bubble_widget->widget_delegate());
EXPECT_EQ(bubble_widget, bubble_delegate->GetWidget());
EXPECT_EQ(anchor_widget, bubble_delegate->anchor_widget());
test::TestWidgetObserver bubble_observer(bubble_widget);
EXPECT_FALSE(bubble_observer.widget_closed());
bubble_widget->Show();
EXPECT_EQ(anchor_widget, bubble_delegate->anchor_widget());
EXPECT_FALSE(bubble_observer.widget_closed());
// TODO(msw): Remove activation hack to prevent bookkeeping errors in:
// aura::test::TestActivationClient::OnWindowDestroyed().
scoped_ptr<Widget> smoke_and_mirrors_widget(CreateTestWidget());
EXPECT_FALSE(bubble_observer.widget_closed());
// Ensure that closing the anchor widget also closes the bubble itself.
anchor_widget->CloseNow();
EXPECT_TRUE(bubble_observer.widget_closed());
}
// This test checks that the bubble delegate is capable to handle an early
// destruction of the used anchor view. (Animations and delayed closure of the
// bubble will call upon the anchor view to get its location).
TEST_F(BubbleDelegateTest, CloseAnchorViewTest) {
// Create an anchor widget and add a view to be used as an anchor view.
scoped_ptr<Widget> anchor_widget(CreateTestWidget());
scoped_ptr<View> anchor_view(new View());
anchor_widget->GetContentsView()->AddChildView(anchor_view.get());
TestBubbleDelegateView* bubble_delegate = new TestBubbleDelegateView(
anchor_view.get());
// Prevent flakes by avoiding closing on activation changes.
bubble_delegate->set_close_on_deactivate(false);
Widget* bubble_widget = BubbleDelegateView::CreateBubble(bubble_delegate);
// Check that the anchor view is correct and set up an anchor view rect.
// Make sure that this rect will get ignored (as long as the anchor view is
// attached).
EXPECT_EQ(anchor_view, bubble_delegate->GetAnchorView());
const gfx::Rect set_anchor_rect = gfx::Rect(10, 10, 100, 100);
bubble_delegate->SetAnchorRectForTest(set_anchor_rect);
const gfx::Rect view_rect = bubble_delegate->GetAnchorRect();
EXPECT_NE(view_rect.ToString(), set_anchor_rect.ToString());
// Create the bubble.
bubble_widget->Show();
EXPECT_EQ(anchor_widget, bubble_delegate->anchor_widget());
// Remove now the anchor view and make sure that the original found rect
// is still kept, so that the bubble does not jump when the view gets deleted.
anchor_widget->GetContentsView()->RemoveChildView(anchor_view.get());
anchor_view.reset();
EXPECT_EQ(NULL, bubble_delegate->GetAnchorView());
EXPECT_EQ(view_rect.ToString(), bubble_delegate->GetAnchorRect().ToString());
}
// Testing that a move of the anchor view will lead to new bubble locations.
TEST_F(BubbleDelegateTest, TestAnchorRectMovesWithViewTest) {
// Create an anchor widget and add a view to be used as anchor view.
scoped_ptr<Widget> anchor_widget(CreateTestWidget());
TestBubbleDelegateView* bubble_delegate = new TestBubbleDelegateView(
anchor_widget->GetContentsView());
BubbleDelegateView::CreateBubble(bubble_delegate);
anchor_widget->GetContentsView()->SetBounds(10, 10, 100, 100);
const gfx::Rect view_rect = bubble_delegate->GetAnchorRect();
anchor_widget->GetContentsView()->SetBounds(20, 10, 100, 100);
const gfx::Rect view_rect_2 = bubble_delegate->GetAnchorRect();
EXPECT_NE(view_rect.ToString(), view_rect_2.ToString());
}
TEST_F(BubbleDelegateTest, ResetAnchorWidget) {
scoped_ptr<Widget> anchor_widget(CreateTestWidget());
BubbleDelegateView* bubble_delegate = new BubbleDelegateView(
anchor_widget->GetContentsView(), BubbleBorder::NONE);
// Make sure the bubble widget is parented to a widget other than the anchor
// widget so that closing the anchor widget does not close the bubble widget.
scoped_ptr<Widget> parent_widget(CreateTestWidget());
bubble_delegate->set_parent_window(parent_widget->GetNativeView());
// Preventing close on deactivate should not prevent closing with the parent.
bubble_delegate->set_close_on_deactivate(false);
Widget* bubble_widget = BubbleDelegateView::CreateBubble(bubble_delegate);
EXPECT_EQ(bubble_delegate, bubble_widget->widget_delegate());
EXPECT_EQ(bubble_widget, bubble_delegate->GetWidget());
EXPECT_EQ(anchor_widget, bubble_delegate->anchor_widget());
test::TestWidgetObserver bubble_observer(bubble_widget);
EXPECT_FALSE(bubble_observer.widget_closed());
// Showing and hiding the bubble widget should have no effect on its anchor.
bubble_widget->Show();
EXPECT_EQ(anchor_widget, bubble_delegate->anchor_widget());
bubble_widget->Hide();
EXPECT_EQ(anchor_widget, bubble_delegate->anchor_widget());
// Ensure that closing the anchor widget clears the bubble's reference to that
// anchor widget, but the bubble itself does not close.
anchor_widget->CloseNow();
EXPECT_NE(anchor_widget, bubble_delegate->anchor_widget());
EXPECT_FALSE(bubble_observer.widget_closed());
// TODO(msw): Remove activation hack to prevent bookkeeping errors in:
// aura::test::TestActivationClient::OnWindowDestroyed().
scoped_ptr<Widget> smoke_and_mirrors_widget(CreateTestWidget());
EXPECT_FALSE(bubble_observer.widget_closed());
// Ensure that closing the parent widget also closes the bubble itself.
parent_widget->CloseNow();
EXPECT_TRUE(bubble_observer.widget_closed());
}
TEST_F(BubbleDelegateTest, InitiallyFocusedView) {
scoped_ptr<Widget> anchor_widget(CreateTestWidget());
BubbleDelegateView* bubble_delegate = new BubbleDelegateView(
anchor_widget->GetContentsView(), BubbleBorder::NONE);
Widget* bubble_widget = BubbleDelegateView::CreateBubble(bubble_delegate);
EXPECT_EQ(bubble_delegate->GetInitiallyFocusedView(),
bubble_widget->GetFocusManager()->GetFocusedView());
bubble_widget->CloseNow();
}
TEST_F(BubbleDelegateTest, NonClientHitTest) {
scoped_ptr<Widget> anchor_widget(CreateTestWidget());
TestBubbleDelegateView* bubble_delegate =
new TestBubbleDelegateView(anchor_widget->GetContentsView());
BubbleDelegateView::CreateBubble(bubble_delegate);
BubbleFrameView* frame = bubble_delegate->GetBubbleFrameView();
const int border = frame->bubble_border()->GetBorderThickness();
struct {
const int point;
const int hit;
} cases[] = {
{ border, HTNOWHERE },
{ border + 50, HTCLIENT },
{ 1000, HTNOWHERE },
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
gfx::Point point(cases[i].point, cases[i].point);
EXPECT_EQ(cases[i].hit, frame->NonClientHitTest(point))
<< " with border: " << border << ", at point " << cases[i].point;
}
}
TEST_F(BubbleDelegateTest, VisibleWhenAnchorWidgetBoundsChanged) {
scoped_ptr<Widget> anchor_widget(CreateTestWidget());
BubbleDelegateView* bubble_delegate = new BubbleDelegateView(
anchor_widget->GetContentsView(), BubbleBorder::NONE);
Widget* bubble_widget = BubbleDelegateView::CreateBubble(bubble_delegate);
test::TestWidgetObserver bubble_observer(bubble_widget);
EXPECT_FALSE(bubble_observer.widget_closed());
bubble_widget->Show();
EXPECT_TRUE(bubble_widget->IsVisible());
anchor_widget->SetBounds(gfx::Rect(10, 10, 100, 100));
EXPECT_TRUE(bubble_widget->IsVisible());
}
} // namespace views
| [
"mrobbeloth@pdiarm.com"
] | mrobbeloth@pdiarm.com |
9dab9792675fbe235086b247505f7b9b67009960 | 3b38e11bd517ba7825bc23ad890fe0150cfd2bf2 | /src/fspinbox.h | c171f53b79238441539e0af8d998b3cf49eee06d | [] | no_license | eschneeweiss/Umass_RoboCup_Logger | a1b9a7f265f8dce139e92ebb1a0c8964803ceb1c | cc2ced98c75f4c44e96754d619be5e17810c6f88 | refs/heads/master | 2020-09-21T05:42:59.737244 | 2016-10-12T19:48:53 | 2016-10-12T19:48:53 | 67,076,577 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 396 | h | #ifndef FSPINBOX_H
#define FSPINBOX_H
#include <QWidget>
#include <QSpinBox>
using namespace std;
class fSpinBox : public QSpinBox
{
Q_OBJECT
public:
explicit fSpinBox(QWidget *parent = 0);
virtual void stepBy(int step);
signals:
void frameChanged(int frame);
private slots:
void stepDown();
void stepUp();
void editingFinishedHandler();
};
#endif // FSPINBOX_H
| [
"eschneeweiss@umass.edu"
] | eschneeweiss@umass.edu |
e8dc833d83201895d8158f573cb35af829a157fc | b59fee706f75c9a347c8687b1ab7110ec52a69e7 | /hphp/runtime/ext/ext_asio.h | 4298ce23d15a0a923005cd805ece2659149e29b6 | [
"PHP-3.01",
"Zend-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | renesugar/hiphop-php | 4391d30b4a05bad1400aa999155bc83ab1f40086 | 4eb05b745fd3018a6d9e51464cae06a4465ee142 | refs/heads/master | 2020-04-11T04:51:03.875501 | 2013-09-11T18:05:53 | 2013-09-13T19:35:48 | 136,534,446 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 19,452 | h | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) |
| Copyright (c) 1997-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#ifndef incl_HPHP_EXT_ASIO_H_
#define incl_HPHP_EXT_ASIO_H_
#include "hphp/runtime/base/base-includes.h"
#include "hphp/runtime/ext/asio/asio_session.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
int f_asio_get_current_context_idx();
Object f_asio_get_running_in_context(int ctx_idx);
Object f_asio_get_running();
void f_asio_set_on_failed_callback(CVarRef on_failed_cb);
void f_asio_set_on_started_callback(CVarRef on_started_cb);
///////////////////////////////////////////////////////////////////////////////
// class WaitHandle
/**
* A wait handle is an object that describes operation that is potentially
* asynchronous. A WaitHandle class is a base class of all such objects. There
* are multiple types of wait handles, this is their hierarchy:
*
* WaitHandle - abstract wait handle
* StaticWaitHandle - statically finished wait handle
* StaticResultWaitHandle - statically succeeded wait handle with result
* StaticExceptionWaitHandle - statically failed wait handle with exception
* WaitableWaitHandle - wait handle that can be waited for
* BlockableWaitHandle - wait handle that can be blocked by other WH
* ContinuationWaitHandle - Continuation-powered asynchronous execution
* GenArrayWaitHandle - wait handle representing an array of WHs
* GenMapWaitHandle - wait handle representing an Map of WHs
* GenVectorWaitHandle - wait handle representing an Vector of WHs
* SetResultToRefWaitHandle - wait handle that sets result to reference
* RescheduleWaitHandle - wait handle that reschedules execution
*
* A wait handle can be either synchronously joined (waited for the operation
* to finish) or passed in various contexts as a dependency and waited for
* asynchronously (such as using yield mechanism of ContinuationWaitHandle or
* passed as an array member of GenArrayWaitHandle).
*/
FORWARD_DECLARE_CLASS_BUILTIN(WaitHandle);
class c_WaitHandle : public ExtObjectData {
public:
DECLARE_CLASS(WaitHandle, WaitHandle, ObjectData)
// need to implement
public: c_WaitHandle(Class* cls = c_WaitHandle::s_cls);
public: ~c_WaitHandle();
public: void t___construct();
public: static void ti_setonjoincallback(CVarRef callback);
public: Object t_getwaithandle();
public: void t_import();
public: Variant t_join();
public: bool t_isfinished();
public: bool t_issucceeded();
public: bool t_isfailed();
public: int64_t t_getid();
public: String t_getname();
public: Object t_getexceptioniffailed();
public:
static c_WaitHandle* fromCell(Cell* cell) {
return (
cell->m_type == KindOfObject &&
cell->m_data.pobj->instanceof(s_cls)
) ? static_cast<c_WaitHandle*>(cell->m_data.pobj) : nullptr;
}
bool isFinished() { return getState() <= STATE_FAILED; }
bool isSucceeded() { return getState() == STATE_SUCCEEDED; }
bool isFailed() { return getState() == STATE_FAILED; }
Cell& getResult() {
assert(isSucceeded());
return m_resultOrException;
}
ObjectData* getException() {
assert(isFailed());
return m_resultOrException.m_data.pobj;
}
virtual String getName() = 0;
protected:
uint8_t getState() { return o_subclassData.u8[0]; }
void setState(uint8_t state) { o_subclassData.u8[0] = state; }
static const int8_t STATE_SUCCEEDED = 0;
static const int8_t STATE_FAILED = 1;
Cell m_resultOrException;
};
///////////////////////////////////////////////////////////////////////////////
// class StaticWaitHandle
/**
* A static wait handle is a wait handle that is statically finished. The result
* of the operation is always available and waiting for the wait handle finishes
* immediately.
*/
FORWARD_DECLARE_CLASS_BUILTIN(StaticWaitHandle);
class c_StaticWaitHandle : public c_WaitHandle {
public:
DECLARE_CLASS(StaticWaitHandle, StaticWaitHandle, WaitHandle)
// need to implement
public: c_StaticWaitHandle(Class* cls = c_StaticWaitHandle::s_cls);
public: ~c_StaticWaitHandle();
public: void t___construct();
};
///////////////////////////////////////////////////////////////////////////////
// class StaticResultWaitHandle
/**
* A wait handle that is statically succeeded with a result.
*/
FORWARD_DECLARE_CLASS_BUILTIN(StaticResultWaitHandle);
class c_StaticResultWaitHandle : public c_StaticWaitHandle {
public:
DECLARE_CLASS(StaticResultWaitHandle, StaticResultWaitHandle, StaticWaitHandle)
// need to implement
public: c_StaticResultWaitHandle(Class* cls = c_StaticResultWaitHandle::s_cls);
public: ~c_StaticResultWaitHandle();
public: void t___construct();
public: static Object ti_create(CVarRef result);
public:
static p_StaticResultWaitHandle Create(const Cell& result);
String getName();
};
///////////////////////////////////////////////////////////////////////////////
// class StaticExceptionWaitHandle
/**
* A wait handle that is statically failed with an exception.
*/
FORWARD_DECLARE_CLASS_BUILTIN(StaticExceptionWaitHandle);
class c_StaticExceptionWaitHandle : public c_StaticWaitHandle {
public:
DECLARE_CLASS(StaticExceptionWaitHandle, StaticExceptionWaitHandle, StaticWaitHandle)
// need to implement
public: c_StaticExceptionWaitHandle(Class* cls = c_StaticExceptionWaitHandle::s_cls);
public: ~c_StaticExceptionWaitHandle();
public: void t___construct();
public: static Object ti_create(CObjRef exception);
public:
static p_StaticExceptionWaitHandle Create(ObjectData* exception);
String getName();
};
///////////////////////////////////////////////////////////////////////////////
// class WaitableWaitHandle
/**
* A waitable wait handle is a wait handle that can be waited for by a blockable
* wait handle if a result is not yet available. Once the wait handle finishes,
* all blocked wait handles are notified.
*/
class AsioContext;
FORWARD_DECLARE_CLASS_BUILTIN(BlockableWaitHandle);
FORWARD_DECLARE_CLASS_BUILTIN(WaitableWaitHandle);
class c_WaitableWaitHandle : public c_WaitHandle {
public:
DECLARE_CLASS(WaitableWaitHandle, WaitableWaitHandle, WaitHandle)
// need to implement
public: c_WaitableWaitHandle(Class* cls = c_WaitableWaitHandle::s_cls);
public: ~c_WaitableWaitHandle();
public: void t___construct();
public: int t_getcontextidx();
public: Object t_getcreator();
public: Array t_getparents();
public: Array t_getdependencystack();
public:
AsioContext* getContext() {
assert(isInContext());
return AsioSession::Get()->getContext(getContextIdx());
}
c_BlockableWaitHandle* addParent(c_BlockableWaitHandle* parent);
virtual void enterContext(context_idx_t ctx_idx) = 0;
void join();
protected:
void setResult(const Cell& result);
void setException(ObjectData* exception);
context_idx_t getContextIdx() { return o_subclassData.u8[1]; }
void setContextIdx(context_idx_t ctx_idx) { o_subclassData.u8[1] = ctx_idx; }
bool isInContext() { return getContextIdx(); }
c_BlockableWaitHandle* getFirstParent() { return m_firstParent; }
virtual c_WaitableWaitHandle* getChild();
bool hasCycle(c_WaitableWaitHandle* start);
static const int8_t STATE_NEW = 2;
private:
c_ContinuationWaitHandle* m_creator;
c_BlockableWaitHandle* m_firstParent;
};
///////////////////////////////////////////////////////////////////////////////
// class BlockableWaitHandle
/**
* A blockable wait handle is a wait handle that can be blocked by a waitable
* wait handle it is waiting for. Once a wait handle blocking this wait handle
* is finished, a notification is received and the operation can be resumed.
*/
FORWARD_DECLARE_CLASS_BUILTIN(BlockableWaitHandle);
class c_BlockableWaitHandle : public c_WaitableWaitHandle {
public:
DECLARE_CLASS(BlockableWaitHandle, BlockableWaitHandle, WaitableWaitHandle)
// need to implement
public: c_BlockableWaitHandle(Class* cls = c_BlockableWaitHandle::s_cls);
public: ~c_BlockableWaitHandle();
public: void t___construct();
public:
c_BlockableWaitHandle* getNextParent();
c_BlockableWaitHandle* unblock();
void exitContextBlocked(context_idx_t ctx_idx);
protected:
void blockOn(c_WaitableWaitHandle* child);
virtual void onUnblocked() = 0;
c_WaitableWaitHandle* getChild() = 0;
static const int8_t STATE_BLOCKED = 3;
private:
void reportCycle(c_WaitableWaitHandle* start);
c_BlockableWaitHandle* m_nextParent;
};
///////////////////////////////////////////////////////////////////////////////
// class ContinuationWaitHandle
/**
* A continuation wait handle represents a basic unit of asynchronous execution
* powered by continuation object. An asynchronous program can be written using
* continuations; a dependency on another wait handle is set up by yielding such
* wait handle, giving control of the execution back to the asio framework.
*/
FORWARD_DECLARE_CLASS_BUILTIN(Continuation);
FORWARD_DECLARE_CLASS_BUILTIN(ContinuationWaitHandle);
class c_ContinuationWaitHandle : public c_BlockableWaitHandle {
public:
DECLARE_CLASS(ContinuationWaitHandle, ContinuationWaitHandle, BlockableWaitHandle)
// need to implement
public: c_ContinuationWaitHandle(Class* cls = c_ContinuationWaitHandle::s_cls);
public: ~c_ContinuationWaitHandle();
public: void t___construct();
public: static void ti_setoncreatecallback(CVarRef callback);
public: static void ti_setonyieldcallback(CVarRef callback);
public: static void ti_setonsuccesscallback(CVarRef callback);
public: static void ti_setonfailcallback(CVarRef callback);
public: Object t_getprivdata();
public: void t_setprivdata(CObjRef data);
public:
static void Create(c_Continuation* continuation);
void run();
uint16_t getDepth() { return m_depth; }
String getName();
void enterContext(context_idx_t ctx_idx);
void exitContext(context_idx_t ctx_idx);
bool isRunning() { return getState() == STATE_RUNNING; }
String getFileName();
int getLineNumber();
protected:
void onUnblocked();
c_WaitableWaitHandle* getChild();
private:
void initialize(c_Continuation* continuation, uint16_t depth);
void markAsSucceeded(const Cell& result);
void markAsFailed(CObjRef exception);
p_Continuation m_continuation;
p_WaitHandle m_child;
Object m_privData;
uint16_t m_depth;
static const int8_t STATE_SCHEDULED = 4;
static const int8_t STATE_RUNNING = 5;
};
///////////////////////////////////////////////////////////////////////////////
// class GenArrayWaitHandle
/**
* A wait handle that waits for an array of wait handles. The wait handle
* finishes once all wait handles in the array are finished. The result value
* preserves structure (order and keys) of the original array. If one of the
* wait handles failed, the exception is propagated by failure.
*/
FORWARD_DECLARE_CLASS_BUILTIN(GenArrayWaitHandle);
class c_GenArrayWaitHandle : public c_BlockableWaitHandle {
public:
DECLARE_CLASS(GenArrayWaitHandle, GenArrayWaitHandle, BlockableWaitHandle)
// need to implement
public: c_GenArrayWaitHandle(Class* cls = c_GenArrayWaitHandle::s_cls);
public: ~c_GenArrayWaitHandle();
public: void t___construct();
public: static void ti_setoncreatecallback(CVarRef callback);
public: static Object ti_create(CArrRef dependencies);
public:
String getName();
void enterContext(context_idx_t ctx_idx);
protected:
void onUnblocked();
c_WaitableWaitHandle* getChild();
private:
void initialize(CObjRef exception, CArrRef deps,
ssize_t iter_pos, c_WaitableWaitHandle* child);
Object m_exception;
Array m_deps;
ssize_t m_iterPos;
};
///////////////////////////////////////////////////////////////////////////////
// class GenMapWaitHandle
/**
* A wait handle that waits for a map of wait handles. The wait handle
* finishes once all wait handles in the map are finished. The result value
* preserves the keys of the original map. If one of the wait handles failed,
* the exception is propagated by failure.
*/
FORWARD_DECLARE_CLASS_BUILTIN(GenMapWaitHandle);
FORWARD_DECLARE_CLASS_BUILTIN(Map);
class c_GenMapWaitHandle : public c_BlockableWaitHandle {
public:
DECLARE_CLASS(GenMapWaitHandle, GenMapWaitHandle, BlockableWaitHandle)
// need to implement
public: c_GenMapWaitHandle(Class* cls = c_GenMapWaitHandle::s_cls);
public: ~c_GenMapWaitHandle();
public: void t___construct();
public: static void ti_setoncreatecallback(CVarRef callback);
public: static Object ti_create(CVarRef dependencies);
public:
String getName();
void enterContext(context_idx_t ctx_idx);
protected:
void onUnblocked();
c_WaitableWaitHandle* getChild();
private:
void initialize(CObjRef exception, c_Map* deps,
ssize_t iter_pos, c_WaitableWaitHandle* child);
Object m_exception;
p_Map m_deps;
ssize_t m_iterPos;
};
///////////////////////////////////////////////////////////////////////////////
// class GenVectorWaitHandle
/**
* A wait handle that waits for a vector of wait handles. The wait handle
* finishes once all wait handles in the vector are finished. The result value
* preserves order of the original vector. If one of the wait handles failed,
* the exception is propagated by failure.
*/
FORWARD_DECLARE_CLASS_BUILTIN(GenVectorWaitHandle);
FORWARD_DECLARE_CLASS_BUILTIN(Vector);
class c_GenVectorWaitHandle : public c_BlockableWaitHandle {
public:
DECLARE_CLASS(GenVectorWaitHandle, GenVectorWaitHandle, BlockableWaitHandle)
// need to implement
public: c_GenVectorWaitHandle(Class* cls = c_GenVectorWaitHandle::s_cls);
public: ~c_GenVectorWaitHandle();
public: void t___construct();
public: static void ti_setoncreatecallback(CVarRef callback);
public: static Object ti_create(CVarRef dependencies);
public:
String getName();
void enterContext(context_idx_t ctx_idx);
protected:
void onUnblocked();
c_WaitableWaitHandle* getChild();
private:
void initialize(CObjRef exception, c_Vector* deps,
int64_t iter_pos, c_WaitableWaitHandle* child);
Object m_exception;
p_Vector m_deps;
int64_t m_iterPos;
};
///////////////////////////////////////////////////////////////////////////////
// class SetResultToRefWaitHandle
/**
* A wait handle that waits for a given dependency and sets its result to
* a given reference once completed.
*/
FORWARD_DECLARE_CLASS_BUILTIN(SetResultToRefWaitHandle);
class c_SetResultToRefWaitHandle : public c_BlockableWaitHandle {
public:
DECLARE_CLASS(SetResultToRefWaitHandle, SetResultToRefWaitHandle, BlockableWaitHandle)
// need to implement
public: c_SetResultToRefWaitHandle(Class* cls = c_SetResultToRefWaitHandle::s_cls);
public: ~c_SetResultToRefWaitHandle();
public: void t___construct();
public: static void ti_setoncreatecallback(CVarRef callback);
public: static Object ti_create(CObjRef wait_handle, VRefParam ref);
public:
String getName();
void enterContext(context_idx_t ctx_idx);
protected:
void onUnblocked();
c_WaitableWaitHandle* getChild();
private:
void initialize(c_WaitableWaitHandle* wait_handle, RefData* ref);
void markAsSucceeded(const Cell& result);
void markAsFailed(CObjRef exception);
p_WaitableWaitHandle m_child;
RefData* m_ref;
};
///////////////////////////////////////////////////////////////////////////////
// class RescheduleWaitHandle
extern const int q_RescheduleWaitHandle$$QUEUE_DEFAULT;
extern const int q_RescheduleWaitHandle$$QUEUE_NO_PENDING_IO;
/**
* A wait handle that is enqueued into a given priority queue and once desired
* execution priority is eligible for execution, it succeeds with a null result.
*
* RescheduleWaitHandle is guaranteed to never finish immediately.
*/
FORWARD_DECLARE_CLASS_BUILTIN(RescheduleWaitHandle);
class c_RescheduleWaitHandle : public c_WaitableWaitHandle {
public:
DECLARE_CLASS(RescheduleWaitHandle, RescheduleWaitHandle, WaitableWaitHandle)
// need to implement
public: c_RescheduleWaitHandle(Class* cls = c_RescheduleWaitHandle::s_cls);
public: ~c_RescheduleWaitHandle();
public: void t___construct();
public: static Object ti_create(int queue, int priority);
public:
void run();
String getName();
void enterContext(context_idx_t ctx_idx);
void exitContext(context_idx_t ctx_idx);
private:
void initialize(uint32_t queue, uint32_t priority);
uint32_t m_queue;
uint32_t m_priority;
static const int8_t STATE_SCHEDULED = 3;
};
///////////////////////////////////////////////////////////////////////////////
// class ExternalThreadEventWaitHandle
/**
* A wait handle that synchronizes against C++ operation in external thread.
*
* See asio_external_thread_event.h for more details.
*/
class AsioExternalThreadEvent;
FORWARD_DECLARE_CLASS_BUILTIN(ExternalThreadEventWaitHandle);
class c_ExternalThreadEventWaitHandle : public c_WaitableWaitHandle, public Sweepable {
public:
DECLARE_CLASS(ExternalThreadEventWaitHandle, ExternalThreadEventWaitHandle, WaitableWaitHandle)
// need to implement
public: c_ExternalThreadEventWaitHandle(Class* cls = c_ExternalThreadEventWaitHandle::s_cls);
public: ~c_ExternalThreadEventWaitHandle();
public: void t___construct();
public:
static c_ExternalThreadEventWaitHandle* Create(AsioExternalThreadEvent* event,
ObjectData* priv_data);
c_ExternalThreadEventWaitHandle* getNextToProcess() {
assert(getState() == STATE_WAITING);
return m_nextToProcess;
}
void setNextToProcess(c_ExternalThreadEventWaitHandle* next) {
assert(getState() == STATE_WAITING);
m_nextToProcess = next;
}
ObjectData* getPrivData() { return m_privData.get(); }
void setIndex(uint32_t ete_idx) {
assert(getState() == STATE_WAITING);
m_index = ete_idx;
}
void abandon(bool sweeping);
void process();
String getName();
void enterContext(context_idx_t ctx_idx);
void exitContext(context_idx_t ctx_idx);
private:
void initialize(AsioExternalThreadEvent* event, ObjectData* priv_data);
void destroyEvent();
c_ExternalThreadEventWaitHandle* m_nextToProcess;
AsioExternalThreadEvent* m_event;
Object m_privData;
uint32_t m_index;
static const uint8_t STATE_WAITING = 3;
};
///////////////////////////////////////////////////////////////////////////////
}
#endif // incl_HPHP_EXT_ASIO_H_
| [
"sgolemon@fb.com"
] | sgolemon@fb.com |
6db522f69c6ce356275b6e6cb7754e830d33392b | d0bfd49ff4e7abc04c2431cf76ce833a03568c96 | /src/vast/concept/parseable/vast/subnet.h | a6e31c0de2aaa528ba2fb78029fdd22b5ccabb4e | [
"BSD-3-Clause"
] | permissive | pmos69/vast | 3896a2a5cae33fb866053532c4171b8d59c8f989 | b95576ed4b41fed8ed29e50c8b8590fb51c511ae | refs/heads/master | 2021-01-21T15:17:57.929700 | 2015-11-17T16:28:11 | 2015-11-17T16:28:11 | 43,690,048 | 0 | 0 | null | 2015-10-05T14:39:54 | 2015-10-05T14:39:54 | null | UTF-8 | C++ | false | false | 1,229 | h | #ifndef VAST_CONCEPT_PARSEABLE_VAST_SUBNET_H
#define VAST_CONCEPT_PARSEABLE_VAST_SUBNET_H
#include "vast/subnet.h"
#include "vast/concept/parseable/core/parser.h"
#include "vast/concept/parseable/numeric/integral.h"
#include "vast/concept/parseable/vast/address.h"
namespace vast {
template <>
struct access::parser<subnet> : vast::parser<access::parser<subnet>> {
using attribute = subnet;
static auto make() {
using namespace parsers;
auto addr = make_parser<address>{};
auto prefix = u8.with([](auto x) { return x <= 128; });
return addr >> '/' >> prefix;
}
template <typename Iterator>
bool parse(Iterator& f, Iterator const& l, unused_type) const {
static auto p = make();
return p.parse(f, l, unused);
}
template <typename Iterator>
bool parse(Iterator& f, Iterator const& l, subnet& a) const {
static auto p = make();
auto t = std::tie(a.network_, a.length_);
if (!p.parse(f, l, t))
return false;
a.initialize();
return true;
}
};
template <>
struct parser_registry<subnet> {
using type = access::parser<subnet>;
};
namespace parsers {
static auto const net = make_parser<vast::subnet>();
} // namespace parsers
} // namespace vast
#endif
| [
"vallentin@icir.org"
] | vallentin@icir.org |
d25f445e7de8f4a60ceee4cbeeb75298232ced06 | d899c8e5edcb95c614f22c53cbe8cadd452d1462 | /misc/own/benelux/2018/C.cpp | fd5e3199f50bf72b258568d1025293e0ff158f5a | [] | no_license | calgagi/competitive_programming | b99d321690c811c29d8ef39025549a7fa58d9b00 | 9986779baaf3486e82391a2b8b2e5bec74f2df11 | refs/heads/master | 2021-07-05T23:52:14.457183 | 2020-08-13T06:44:21 | 2020-08-13T06:44:21 | 149,514,638 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 651 | cpp | // Calvin Gagliano
// Oregon State University
// Competitive Programming Template
#include <bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int v; cin >> v;
float x = sqrt(v);
// Surface area = 2( a*b + a*c + b*c )
// Two of the values must be less than sqrt(V)
int m = (int) INFINITY;
for (int i = 1; i <= (int) x; i++) {
for (int j = 1; j <= (int) x; j++) {
float y = (float) v / ((float) i * (float) j);
if (floor(y) == y)
m = min(m, 2 * (i*j + i * (int) y + j * (int) y));
}
}
cout << m << endl;
return 0;
}
| [
"calgagi@gmail.com"
] | calgagi@gmail.com |
d515837ea79aa95cca72f496a068562aa582bdc3 | 0b98eb5f9298c666d8feabe078c1ddf22cbb0d91 | /src/features/Chams.cpp | 550ec449d31e0d92a9f36dee96ca030a8c8b7d9a | [
"MIT"
] | permissive | kingking888/Sensum | ce2302f0b0e80dcddaedd9aa61a3af93488bd424 | 7a09438ec18ddfbf8c36088151fdf4b368189ac2 | refs/heads/master | 2023-08-15T14:07:52.564308 | 2021-09-25T17:51:09 | 2021-09-25T17:51:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,100 | cpp | #include "../settings/settings.h"
#include "../features/features.h"
#include "../hooks/hooks.h"
#include "../settings/globals.h"
#include "../classids.h"
namespace chams
{
void render_players(const bool& ignorez, const bool& flat, const bool& wireframe, const Color& visible_color, const Color& occluded_color)
{
static IMaterial* material = g::mat_system->FindMaterial("debug/debugambientcube", TEXTURE_GROUP_OTHER);
const auto color = ignorez ? occluded_color : visible_color;
material->ColorModulate(color.r() / 255.0f, color.g() / 255.0f, color.b() / 255.0f);
material->AlphaModulate(color.a() / 255.0f);
material->SetMaterialVarFlag(MATERIAL_VAR_IGNOREZ, ignorez);
material->SetMaterialVarFlag(MATERIAL_VAR_WIREFRAME, wireframe);
material->SetMaterialVarFlag(MATERIAL_VAR_FLAT, flat);
/*material->FindVar("$envmap")->SetStringValue("env_cubemap");
material->FindVar("$envmaptint")->SetVectorValue(.3f, .3f, .3f);
material->FindVar("$envmapcontrast")->SetIntValue(1);
material->FindVar("$envmapsaturation")->SetFloatValue(1.0f);
material->FindVar("$phong")->SetIntValue(1);
material->FindVar("$phongexponent")->SetFloatValue(15.0f);
material->FindVar("$normalmapalphaenvmask")->SetIntValue(1);
material->FindVar("$phongboost")->SetFloatValue(6.0f);*/
g::mdl_render->ForcedMaterialOverride(material);
}
void on_draw_model_execute(IMatRenderContext* ctx, const DrawModelState_t& state, const ModelRenderInfo_t& info, matrix3x4_t* bone)
{
c_base_player* player = c_base_player::GetPlayerByIndex(info.entity_index);
static auto original = hooks::draw_model_execute::original;
const char* model_name = info.pModel->szName;
static IMaterial* material = g::mat_system->FindMaterial("debug/debugambientcube", TEXTURE_GROUP_MODEL);
if (info.entity_index > 0 && info.entity_index <= 64)
{
if (player && g::local_player)
{
if (player->m_iTeamNum() != g::local_player->m_iTeamNum()) //enemy chams
{
if (!settings::chams::enemy::enabled)
return;
Color vis = settings::chams::enemy::color_visible;
Color not_vis = settings::chams::enemy::color_not_visible;
bool flat = settings::chams::enemy::flat;
bool wireframe = settings::chams::enemy::wireframe;
if (!settings::chams::enemy::visible_only)
{
render_players(true, flat, wireframe, vis, not_vis);
original(g::mdl_render, ctx, &state, &info, bone);
}
render_players(false, flat, wireframe, vis, not_vis);
}
else if (player->m_iTeamNum() == g::local_player->m_iTeamNum() && player != g::local_player)
{
if (!settings::chams::teammates::enabled)
return;
Color vis = settings::chams::teammates::color_visible;
Color not_vis = settings::chams::teammates::color_not_visible;
bool flat = settings::chams::teammates::flat;
bool wireframe = settings::chams::enemy::wireframe;
if (!settings::chams::enemy::visible_only)
{
render_players(true, flat, wireframe, vis, not_vis);
original(g::mdl_render, ctx, &state, &info, bone);
}
render_players(false, flat, wireframe, vis, not_vis);
}
else if (player == g::local_player)
{
if (!settings::chams::localplayer::enabled)
return;
Color vis = settings::chams::localplayer::color;
bool flat = settings::chams::localplayer::flat;
bool wireframe = settings::chams::localplayer::wireframe;
render_players(false, flat, wireframe, vis, vis);
original(g::mdl_render, ctx, &state, &info, bone);
}
}
}
if (settings::chams::misc::weapon_chams) //Since I dont know the perfomance difference between strstr and std::string.find,
{ // I will use strstr, more research needed.
if (strstr(model_name, "weapons/v")) //Weapons in hand.
{
if (!strstr(model_name, "arms") && !strstr(model_name, "ied_dropped")) //ied is c4 on ground/on back.
{
material->ColorModulate(Color::Green.r() / 255.0f, Color::Green.g() / 255.0f, Color::Green.b() / 255.0f);
material->AlphaModulate(Color::Green.a() / 255.0f);
material->SetMaterialVarFlag(MATERIAL_VAR_IGNOREZ, false);
g::mdl_render->ForcedMaterialOverride(material);
}
}
}
if (settings::chams::misc::arms_chams)
{
if (strstr(model_name, "arms"))
{
if (!strstr(model_name, "ied_dropped")) //ied is c4 on ground/on back.
{
material->ColorModulate(Color::Blue.r() / 255.0f, Color::Blue.g() / 255.0f, Color::Blue.b() / 255.0f);
material->AlphaModulate(Color::Blue.a() / 255.0f);
material->SetMaterialVarFlag(MATERIAL_VAR_IGNOREZ, false);
g::mdl_render->ForcedMaterialOverride(material);
}
}
}
if (settings::chams::misc::accesories_chams)
{
if (strstr(model_name, "_dropped.mdl") && strstr(model_name, "weapons/w")) //Weapons on back.
{
if (!strstr(model_name, "arms") && !strstr(model_name, "ied_dropped")) //ied is c4 on ground/on back.
{
material->ColorModulate(Color::Green.r() / 255.0f, Color::Green.g() / 255.0f, Color::Green.b() / 255.0f);
material->AlphaModulate(Color::Green.a() / 255.0f);
material->SetMaterialVarFlag(MATERIAL_VAR_IGNOREZ, false);
g::mdl_render->ForcedMaterialOverride(material);
}
}
if (strstr(model_name, "weapons/w")) //Weapons in enemy hands.
{
if (!strstr(model_name, "arms") && !strstr(model_name, "ied_dropped")) //ied is c4 on ground/on back.
{
material->ColorModulate(Color::White.r() / 255.0f, Color::White.g() / 255.0f, Color::White.b() / 255.0f);
material->AlphaModulate(Color::White.a() / 255.0f);
material->SetMaterialVarFlag(MATERIAL_VAR_IGNOREZ, false);
g::mdl_render->ForcedMaterialOverride(material);
}
}
if (strstr(model_name, "defuser")) //Defuse kit on body.
{
if (!strstr(model_name, "arms") && !strstr(model_name, "ied_dropped")) //ied is c4 on ground/on back.
{
material->ColorModulate(Color::Red.r() / 255.0f, Color::Red.g() / 255.0f, Color::Red.b() / 255.0f);
material->AlphaModulate(Color::Red.a() / 255.0f);
material->SetMaterialVarFlag(MATERIAL_VAR_IGNOREZ, false);
g::mdl_render->ForcedMaterialOverride(material);
}
}
}
}
void misc_chams()
{
static IMaterial* mat = g::mat_system->FindMaterial("debug/debugambientcube", TEXTURE_GROUP_MODEL);
for (int i = 0; i < g::entity_list->GetHighestEntityIndex(); i++) {
auto entity = reinterpret_cast<c_base_player*>(g::entity_list->GetClientEntity(i));
auto grenade = reinterpret_cast<c_base_combat_weapon*>(g::entity_list->GetClientEntity(i));
if (entity && entity != g::local_player) {
auto client_class = entity->GetClientClass();
auto model_name = g::mdl_info->GetModelName(entity->GetModel());
if (settings::chams::misc::planted_bomb_chams)
{
if (client_class->m_ClassID == classids::CPlantedC4 || client_class->m_ClassID == classids::CBaseAnimating)
{
g::render_view->SetColorModulation(settings::chams::misc::color_planted_bomb_chams.r() / 255.f, settings::chams::misc::color_planted_bomb_chams.g() / 255.f, settings::chams::misc::color_planted_bomb_chams.b() / 255.f);
mat->SetMaterialVarFlag(MATERIAL_VAR_IGNOREZ, true);
g::mdl_render->ForcedMaterialOverride(mat);
entity->DrawModel(1, 255);
}
}
if (settings::chams::misc::nade_chams && grenade && grenade->m_nExplodeEffectTickBegin() < 1)
{
if (client_class->m_ClassID == classids::CHEGrenade || client_class->m_ClassID == classids::CFlashbang
|| client_class->m_ClassID == classids::CMolotovGrenade || client_class->m_ClassID == classids::CMolotovProjectile
|| client_class->m_ClassID == classids::CIncendiaryGrenade || client_class->m_ClassID == classids::CDecoyGrenade
|| client_class->m_ClassID == classids::CDecoyProjectile || client_class->m_ClassID == classids::CSmokeGrenade
|| client_class->m_ClassID == classids::CSmokeGrenadeProjectile || client_class->m_ClassID == classids::ParticleSmokeGrenade
|| client_class->m_ClassID == classids::CBaseCSGrenade || client_class->m_ClassID == classids::CBaseCSGrenadeProjectile
|| client_class->m_ClassID == classids::CBaseGrenade || client_class->m_ClassID == classids::CBaseParticleEntity
|| client_class->m_ClassID == classids::CSensorGrenade || client_class->m_ClassID == classids::CSensorGrenadeProjectile)
{
g::render_view->SetColorModulation(settings::chams::misc::color_nade_chams.r() / 255.f, settings::chams::misc::color_nade_chams.g() / 255.f, settings::chams::misc::color_nade_chams.b() / 255.f);
mat->SetMaterialVarFlag(MATERIAL_VAR_IGNOREZ, true);
g::mdl_render->ForcedMaterialOverride(mat);
entity->DrawModel(1, 255);
}
}
if (settings::chams::misc::dropped_weapons)
{
if (client_class->m_ClassID == classids::CAK47 || client_class->m_ClassID == classids::CDEagle || client_class->m_ClassID == classids::CC4 ||
client_class->m_ClassID >= classids::CWeaponAug && client_class->m_ClassID <= classids::CWeaponXM1014)
{
g::render_view->SetColorModulation(settings::chams::misc::color_dropped_weapons_chams.r() / 255.f, settings::chams::misc::color_dropped_weapons_chams.g() / 255.f, settings::chams::misc::color_dropped_weapons_chams.b() / 255.f);
//g::render_view->SetBlend(settings::chams::misc::color_dropped_bomb_chams.a() / 255.f);
mat->SetMaterialVarFlag(MATERIAL_VAR_IGNOREZ, true);
g::mdl_render->ForcedMaterialOverride(mat);
entity->DrawModel(1, 255);
}
}
if (settings::chams::misc::dropped_defusekit_chams)
{
if (client_class->m_ClassID == classids::CEconEntity)
{
g::render_view->SetColorModulation(settings::chams::misc::color_dropped_defusekit_chams.r() / 255.f, settings::chams::misc::color_dropped_defusekit_chams.g() / 255.f, settings::chams::misc::color_dropped_defusekit_chams.b() / 255.f);
mat->SetMaterialVarFlag(MATERIAL_VAR_IGNOREZ, true);
g::mdl_render->ForcedMaterialOverride(mat);
entity->DrawModel(1, 255);
}
}
}
}
}
} | [
"44605473+martinjanas@users.noreply.github.com"
] | 44605473+martinjanas@users.noreply.github.com |
0ed6003c7a1239e817bfc032ff158880550d13ce | 33a82980352cf366b9c288cf8a74d2740272d90b | /print/XPSDrvSmpl/src/filters/booklet/bkprps.cpp | dce58de0f6b7ba3e62d73e634986a4d1a0a4413f | [
"MS-PL"
] | permissive | microkatz/Windows-driver-samples | d249ecb8ab1be5a05bf8644ebeaca0bf13db1dad | 98a43841cb18b034c7808bc570c47556e332df2f | refs/heads/master | 2022-05-09T17:42:10.796047 | 2022-04-20T20:47:03 | 2022-04-20T20:47:03 | 161,238,613 | 2 | 0 | MS-PL | 2022-04-20T20:47:03 | 2018-12-10T21:28:00 | C | UTF-8 | C++ | false | false | 2,189 | cpp | /*++
Copyright (c) 2005 Microsoft Corporation
All rights reserved.
THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.
File Name:
bkprps.cpp
Abstract:
Booklet properties class implementation. The booklet properties class
is responsible for interpreting booklet data appropriate to the booklet
filter.
--*/
#include "precomp.h"
#include "debug.h"
#include "globals.h"
#include "bkprps.h"
using XDPrintSchema::Binding::BindingData;
using XDPrintSchema::Binding::JobBindAllDocuments;
using XDPrintSchema::Binding::None;
/*++
Routine Name:
CBkPTProperties::CBkPTProperties
Routine Description:
Default constructor for the booklet PrintTicket properties class which
sets the internal binding setting to the setting supplied
Arguments:
bindingData - Structure containing the booklet binding settings
from the PrintTicket
Return Value:
None
--*/
CBkPTProperties::CBkPTProperties(
_In_ CONST BindingData& bindingData
) :
m_bindData(bindingData)
{
}
/*++
Routine Name:
CBkPTProperties::~CBkPTProperties
Routine Description:
Default destructor for the CBkPTProperties class
Arguments:
None
Return Value:
None
--*/
CBkPTProperties::~CBkPTProperties()
{
}
/*++
Routine Name:
CBkPTProperties::GetScope
Routine Description:
Method to return the booklet scope which can be either none, job wide or document wide
Arguments:
pBkScope - Booklet printing scope which can be None, Job wide or Document
Return Value:
HRESULT
S_OK - On success
E_* - On error
--*/
HRESULT
CBkPTProperties::GetScope(
_Out_ EBookletScope* pBkScope
)
{
HRESULT hr = S_OK;
if (SUCCEEDED(hr = CHECK_POINTER(pBkScope, E_POINTER)))
{
*pBkScope = CBkPTProperties::None;
if (m_bindData.bindOption != None)
{
*pBkScope = m_bindData.bindFeature == JobBindAllDocuments ? CBkPTProperties::Job : CBkPTProperties::Document;
}
}
ERR_ON_HR(hr);
return hr;
}
| [
"cdwilsonjr@gmail.com"
] | cdwilsonjr@gmail.com |
4bef56a799cc9fc72081723b5d7529d5a4101599 | 4b9b6ad85d91c9ad2b7ffa39b00142a9e87f3c9f | /elements/collision/aabb.cpp | 80c453c44270a829adacc6c4544e6acea9c8fa07 | [
"MIT"
] | permissive | netghost-developer/elements | ed02589f8179584e7999b74a7871cea2bb3a2427 | 31574ee5423b291d58b1169fa84f27938ce9666b | refs/heads/master | 2020-07-06T10:57:52.212130 | 2017-03-27T18:59:13 | 2017-03-27T18:59:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,906 | cpp | /*
The MIT License (MIT)
Copyright (c) 2016 Alexey Yegorov
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 "aabb.h"
namespace eps {
namespace collision {
aabb::aabb(const math::vec3 & min, const math::vec3 & max)
: min_(min)
, max_(max)
, center_((min + max) * 0.5f)
, size_(max - min)
{}
aabb update(const aabb & bounds, const math::mat4 & m)
{
math::vec3 min;
math::vec3 max;
float e, f;
for(size_t i = 0; i < 3; ++i)
{
min[i] = max[i] = m[3][i];
for(size_t j = 0; j < 3; ++j)
{
e = m[j][i] * bounds.min()[j];
f = m[j][i] * bounds.max()[j];
if(e < f)
{
min[i] += e;
max[i] += f;
}
else
{
min[i] += f;
max[i] += e;
}
}
}
return aabb(min, max);
}
} /* collision */
} /* eps */
| [
"yegorov.alex@gmail.com"
] | yegorov.alex@gmail.com |
a46b80ac35151343ac4a886cc578c122e360a42a | e763b855be527d69fb2e824dfb693d09e59cdacb | /aws-cpp-sdk-route53domains/source/model/GetOperationDetailRequest.cpp | 0d179e6d719a9420642056be40cef88ffa372c33 | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | 34234344543255455465/aws-sdk-cpp | 47de2d7bde504273a43c99188b544e497f743850 | 1d04ff6389a0ca24361523c58671ad0b2cde56f5 | refs/heads/master | 2023-06-10T16:15:54.618966 | 2018-05-07T23:32:08 | 2018-05-07T23:32:08 | 132,632,360 | 1 | 0 | Apache-2.0 | 2023-06-01T23:20:47 | 2018-05-08T15:56:35 | C++ | UTF-8 | C++ | false | false | 1,406 | cpp | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/route53domains/model/GetOperationDetailRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Route53Domains::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
GetOperationDetailRequest::GetOperationDetailRequest() :
m_operationIdHasBeenSet(false)
{
}
Aws::String GetOperationDetailRequest::SerializePayload() const
{
JsonValue payload;
if(m_operationIdHasBeenSet)
{
payload.WithString("OperationId", m_operationId);
}
return payload.WriteReadable();
}
Aws::Http::HeaderValueCollection GetOperationDetailRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "Route53Domains_v20140515.GetOperationDetail"));
return headers;
}
| [
"henso@amazon.com"
] | henso@amazon.com |
7b9ffc6f7b8499bb8853fea2382a317c76896758 | 3e70eda6819fec5bf5ba2299573b333a3a610131 | /gf/db/ser/src/Cgf_item.cpp | d3ca8399be26896f2779e61a939559ea2994a1ac | [] | no_license | dawnbreaks/taomee | cdd4f9cecaf659d134d207ae8c9dd2247bef97a1 | f21b3633680456b09a40036d919bf9f58c9cd6d7 | refs/heads/master | 2021-01-17T10:45:31.240038 | 2013-03-14T08:10:27 | 2013-03-14T08:10:27 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 5,965 | cpp | #include <algorithm>
#include "db_error.h"
#include "Cgf_item.h"
using namespace std;
const char* item_count_column = "count";
//¼ÓÈë
Cgf_item::Cgf_item(mysql_interface * db, Citem_change_log * p_log_in)
:CtableRoute( db,"GF" ,"t_gf_item","userid")
{
p_log = p_log_in;
}
int Cgf_item::get_user_item_list(userid_t userid,uint32_t role_regtime, uint32_t* p_count,
gf_get_user_item_list_out_item** pp_list)
{
GEN_SQLSTR(this->sqlstr,"select itemid,count from %s \
where userid=%u and role_regtime=%u and count>0;",
this->get_table_name(userid), userid, role_regtime);
STD_QUERY_WHILE_BEGIN(this->sqlstr, pp_list, p_count);
INT_CPY_NEXT_FIELD( (*pp_list+i)->itemid );
INT_CPY_NEXT_FIELD( (*pp_list+i)->count );
STD_QUERY_WHILE_END();
}
int Cgf_item::clear_role_item(userid_t userid,uint32_t role_regtime)
{
GEN_SQLSTR(this->sqlstr,"delete from %s where userid=%u and role_regtime=%u;",
this->get_table_name(userid), userid, role_regtime);
return this->exec_update_list_sql(this->sqlstr,SUCC);
}
int Cgf_item::set_item_int_value(userid_t userid,uint32_t role_regtime, uint32_t itemid ,const char * field_type , uint32_t value)
{
sprintf( this->sqlstr, "update %s set %s =%u where %s=%u and role_regtime=%u and itemid=%u;" ,
this->get_table_name(userid), field_type, value, this->id_name, userid, role_regtime, itemid );
return this->exec_update_sql(this->sqlstr, USER_ID_NOFIND_ERR );
}
inline int Cgf_item::insert_table(userid_t userid, uint32_t role_regtime, uint32_t itemid, uint32_t count)
{
sprintf( this->sqlstr, "insert into %s (userid,role_regtime,itemid,count) values \
(%u, %u, %u, %u)" ,
this->get_table_name(userid), userid, role_regtime, itemid, count);
return this->exec_insert_sql (this->sqlstr, GF_ITEM_EXISTED_ERR );
}
int Cgf_item::insert_item(userid_t userid, uint32_t role_regtime, uint32_t itemid, uint32_t count, uint32_t max_item_bag_grid_count)
{
uint32_t kind_num = 0;
int ret = get_item_kind_cnt(userid, role_regtime, &kind_num);
if (ret != SUCC)
{
return ret;
}
if (kind_num >= max_item_bag_grid_count)
{
return GF_ITEM_KIND_MAX_ERR;
}
return insert_table(userid, role_regtime, itemid, count);
}
int Cgf_item::del_item(userid_t userid, uint32_t role_regtime, uint32_t itemid)
{
sprintf( this->sqlstr, "delete from %s where userid=%u and role_regtime=%u and itemid=%u ;" ,
this->get_table_name(userid), userid, role_regtime, itemid);
return this->exec_update_sql(this->sqlstr, GF_ITEM_NOFIND_ERR );
}
int Cgf_item::reduce_item_int_value(userid_t userid, uint32_t role_regtime, uint32_t itemid,
const char* column_type, uint32_t del_num, bool log_flg)
{
uint32_t db_num = 0;
int ret = this->get_item_int_value(userid, role_regtime, itemid, column_type, &db_num);
if (ret != SUCC)
{
return ret;
}
if (log_flg) {
if (del_num != 0xFFFFFFFF) {
p_log->add(time(NULL), item_change_log_opt_type_del ,userid, itemid, del_num);
} else {
p_log->add(time(NULL), item_change_log_opt_type_del ,userid, itemid, db_num);
}
}
if (db_num == del_num)
{
ret = this->del_item(userid, role_regtime, itemid);
if (ret != SUCC)
{
return ret;
}
}
else if (db_num > del_num)
{
ret = this->set_item_int_value(userid, role_regtime, itemid,
column_type, db_num-del_num);
if (ret != SUCC)
{
return ret;
}
}
else if (del_num == 0xFFFFFFFF)
{
ret = this->del_item(userid, role_regtime, itemid);
if (ret != SUCC)
{
return ret;
}
return GF_ITEM_NOTENOUGH_ERR;
}
else
{
return GF_ITEM_NOTENOUGH_ERR;
}
return SUCC;
}
int Cgf_item::get_item_int_value(userid_t userid, uint32_t role_regtime, uint32_t itemid,
const char* column_type,uint32_t *p_count)
{
sprintf( this->sqlstr, "select %s from %s where userid=%u and role_regtime=%u \
and itemid=%u ;" ,
column_type, this->get_table_name(userid), userid, role_regtime, itemid);
STD_QUERY_ONE_BEGIN(sqlstr, GF_ITEM_NOFIND_ERR);
INT_CPY_NEXT_FIELD (*p_count);
STD_QUERY_ONE_END();
}
int Cgf_item::get_item_kind_cnt(userid_t userid, uint32_t role_regtime, uint32_t *p_count)
{
sprintf( this->sqlstr, "select count(*) from %s where userid=%u and role_regtime=%u ;" ,
this->get_table_name(userid), userid, role_regtime);
STD_QUERY_ONE_BEGIN(sqlstr, GF_ITEM_NOFIND_ERR);
INT_CPY_NEXT_FIELD (*p_count);
STD_QUERY_ONE_END();
}
int Cgf_item::get_item_cnt_by_itemid(userid_t userid, uint32_t role_regtime, uint32_t *p_count, uint32_t id)
{
sprintf( this->sqlstr, "select sum(count) from %s where userid=%u and role_regtime=%u and itemid=%u;" ,
this->get_table_name(userid), userid, role_regtime, id);
STD_QUERY_ONE_BEGIN(sqlstr, GF_ITEM_NOFIND_ERR);
INT_CPY_NEXT_FIELD (*p_count);
STD_QUERY_ONE_END();
}
int Cgf_item::add_item(userid_t userid, uint32_t role_regtime, uint32_t itemid,uint32_t count,uint32_t max_num, uint32_t max_item_bag_grid_count,
item_change_log_opt_type is_vip_opt, bool log_flg)
{
uint32_t db_num = 0;
DEBUG_LOG("ADD ITEM %u count:%u %u", itemid, count, max_num);
if (count>max_num)
return VALUE_OUT_OF_RANGE_ERR;
if (log_flg) {
p_log->add(time(NULL), is_vip_opt ,userid, itemid, count);
}
int ret = this->get_item_int_value(userid, role_regtime, itemid, item_count_column, &db_num);
if (ret != SUCC && ret != GF_ITEM_NOFIND_ERR)
{
return ret;
}
else if (ret == GF_ITEM_NOFIND_ERR)
{
return this->insert_item(userid, role_regtime, itemid, count, max_item_bag_grid_count);
}
else if (db_num + count > max_num)
{
return VALUE_OUT_OF_RANGE_ERR;
}
else
{
GEN_SQLSTR(this->sqlstr,"update %s set count=count+%u \
where userid=%u and role_regtime=%u and itemid=%u; ",
this->get_table_name(userid), count, userid, role_regtime, itemid);
return this->exec_update_sql (this->sqlstr, GF_ITEM_NOFIND_ERR);
}
}
| [
"smyang.ustc@gmail.com"
] | smyang.ustc@gmail.com |
0f99b4f5a81190ca20f8b7b8aac34bbc0828732a | fe77ffe4952beafaca37fc7b9a0d9f471643a7c4 | /OOP - projekat - Aleksa/Strategija.h | 7124d8bd4aaa165f0672ea611565506ab594e362 | [] | no_license | lukapfekg/Public-Transport-System | 13c8e62a430d417f4742c08bdaa2772deae09b4b | 48057357bf56bb17b306c3177a9e73dc9f96df22 | refs/heads/master | 2023-08-12T13:46:22.371648 | 2021-10-03T21:06:43 | 2021-10-03T21:06:43 | 413,195,736 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 896 | h | #pragma once
#include <vector>
#include "Linija.h"
#include "Stajaliste.h"
class Strategija {
public:
Strategija() {}
virtual std::string execute(std::vector<std::vector<std::pair<Stajaliste*, Linija*>>>* v);
virtual int condition(std::pair<int, Linija*> path[], int path_index);
std::string ispis(std::vector<std::pair<Stajaliste*, Linija*>>* v);
};
class NaprednaStrategijaA : public Strategija {
public:
NaprednaStrategijaA() :Strategija() {}
std::string execute(std::vector<std::vector<std::pair<Stajaliste*, Linija*>>>* v) override;
int condition(std::pair<int, Linija*> path[], int path_index) override;
};
class NaprednaStrategijaB : public Strategija {
public:
NaprednaStrategijaB() :Strategija() {}
std::string execute(std::vector<std::vector<std::pair<Stajaliste*, Linija*>>>* v) override;
int condition(std::pair<int, Linija*> path[], int path_index) override;
}; | [
"lukaorigin97@hotmail.com"
] | lukaorigin97@hotmail.com |
7f15de1782b1455dad897fac81e39acb89f6301d | 471a1b87795a2da5d87a52025b1d5d6a2c2d7de9 | /Library/BigFix/DataRef.h | 1955e0d8620ac5ef8f93f1e94c3547fe8bd64364 | [
"Apache-2.0"
] | permissive | briangreenery/bfarchive | 9bc63ab821433ded8a81ee7f2f5f17f5d9952583 | ed29d6fa9f035e61011351d0a9e703a51a28dca4 | refs/heads/master | 2021-01-17T05:31:44.999043 | 2014-07-18T11:28:23 | 2014-07-18T11:28:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,017 | h | #ifndef BigFix_DataRef_h
#define BigFix_DataRef_h
#include <stdint.h>
#include <string>
namespace BigFix
{
class DataRef
{
public:
DataRef() : m_start( 0 ), m_end( 0 ) {}
DataRef( const uint8_t* start, const uint8_t* end )
: m_start( start ), m_end( end )
{
}
explicit DataRef( const std::string& s )
: m_start( reinterpret_cast<const uint8_t*>( s.data() ) )
, m_end( m_start + s.size() )
{
}
template <size_t n>
explicit DataRef( const char ( &literal )[n] )
: m_start( reinterpret_cast<const uint8_t*>( literal ) )
, m_end( m_start + n - 1 )
{
}
const uint8_t* Start() const { return m_start; }
const uint8_t* End() const { return m_end; }
size_t Length() const { return m_end - m_start; }
bool IsEmpty() const { return m_start == m_end; }
uint8_t operator[]( size_t n ) const;
DataRef Slice( size_t start, size_t length );
private:
const uint8_t* m_start;
const uint8_t* m_end;
};
}
bool operator==( BigFix::DataRef, BigFix::DataRef );
#endif
| [
"briangreenery@gmail.com"
] | briangreenery@gmail.com |
9866363eb6b7c837ec431445f5b7b51a78af2884 | 72b564d98e01af9a54c5735bdd894e7a18712cac | /Numerical Methods/2/gaus_method.cpp | 5b324debec6f0800607d412032d4ccfcd25921d4 | [] | no_license | linyasha/BSU | 0a16bfd87705034caa749b0bc5a3d48129c250f9 | 731e3d66e87a7fecb49abfc94187a06ec0dafff9 | refs/heads/main | 2023-04-16T03:46:25.949583 | 2021-04-22T23:17:05 | 2021-04-22T23:17:05 | 328,188,020 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,531 | cpp | #include "SLE.h"
bool slu_gaus(vector<vector<double>> matrix, vector<double>& x) {
for(int i = 0; i < matrix.size(); i++) {
try {
permutation_max(matrix, i);
}
catch(std::domain_error& e) {
cout << e.what();
return 0;
}
double milty = 1 / matrix[i][i];
for(int g = i; g < matrix[0].size(); g++) {
matrix[i][g] *= milty;
}
vector<double> help_line = matrix[i];
for(int k = i + 1; k < matrix.size(); k++) {
milty = (-matrix[k][i]);
for(int e = 0; e < matrix[0].size(); e++) {
matrix[k][e] += help_line[e] * milty;
}
}
}
creat_solution_vector(matrix, x);
return 1;
}
double residual(const vector<vector<double>>& matrix, const vector<double>& x) {
double max = 0;
for(int i = 0; i < matrix.size(); i++) {
double help = 0;
for(int j = 0; j < x.size(); j++) {
help += matrix[i][j] * x[j];
}
if(fabs(help - matrix[i][matrix[0].size() - 1]) > max) max = fabs(help - matrix[i][matrix[0].size() - 1]);
}
return max;
}
void coutMatrix(vector<vector<double>>& matrix) {
for(int i = 0; i < matrix.size(); i++) {
for(int j = 0; j < matrix[0].size(); j++) {
cout << " " << matrix[i][j];
}
cout << '\n';
}
}
void permutation_max(vector<vector<double>>& matrix, int j) {
double max = fabs(matrix[j][j]);
int coord_max = j;
for(int i = j + 1; i < matrix.size(); i++) {
if(fabs(matrix[i][j]) > max) {
max = fabs(matrix[i][j]);
coord_max = i;
}
}
if (max <= eps) {
throw std::domain_error("Solution not found");
}
else {
if(coord_max != j) matrix[coord_max].swap(matrix[j]);
}
}
void creat_solution_vector(vector<vector<double>> matrix,vector<double>& x) {
vector<double> help_vector (matrix.size(), 0);
for(int i = matrix.size() - 1; i >= 0; i--) {
help_vector[i] = matrix[i][matrix[0].size() - 1] / matrix[i][i];
for(int j = i - 1; j >= 0; j--) {
matrix[j][matrix[0].size() - 1] -= matrix[j][i] * help_vector[i];
}
}
x = help_vector;
}
| [
"alynko17@gmail.com"
] | alynko17@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.