hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 77k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 653k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
54a2408ceeedf2c24a17f3501e5dd355dc4906f8 | 9,375 | cc | C++ | content/browser/service_worker/service_worker_context_unittest.cc | Acidburn0zzz/chromium-1 | 4c08f442d2588a2c7cfaa117a55bd87d2ac32f9a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/browser/service_worker/service_worker_context_unittest.cc | Acidburn0zzz/chromium-1 | 4c08f442d2588a2c7cfaa117a55bd87d2ac32f9a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/browser/service_worker/service_worker_context_unittest.cc | Acidburn0zzz/chromium-1 | 4c08f442d2588a2c7cfaa117a55bd87d2ac32f9a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/public/browser/service_worker_context.h"
#include "base/files/scoped_temp_dir.h"
#include "base/logging.h"
#include "base/message_loop/message_loop.h"
#include "content/browser/browser_thread_impl.h"
#include "content/browser/service_worker/embedded_worker_registry.h"
#include "content/browser/service_worker/embedded_worker_test_helper.h"
#include "content/browser/service_worker/service_worker_context_core.h"
#include "content/browser/service_worker/service_worker_registration.h"
#include "content/browser/service_worker/service_worker_storage.h"
#include "content/common/service_worker/service_worker_messages.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "content/public/test/test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace content {
namespace {
void SaveResponseCallback(bool* called,
int64* store_result,
ServiceWorkerStatusCode status,
int64 result) {
*called = true;
*store_result = result;
}
ServiceWorkerContextCore::RegistrationCallback MakeRegisteredCallback(
bool* called,
int64* store_result) {
return base::Bind(&SaveResponseCallback, called, store_result);
}
void CallCompletedCallback(bool* called, ServiceWorkerStatusCode) {
*called = true;
}
ServiceWorkerContextCore::UnregistrationCallback MakeUnregisteredCallback(
bool* called) {
return base::Bind(&CallCompletedCallback, called);
}
void ExpectRegisteredWorkers(
bool expect_pending,
bool expect_active,
ServiceWorkerStatusCode status,
const scoped_refptr<ServiceWorkerRegistration>& registration) {
ASSERT_EQ(SERVICE_WORKER_OK, status);
if (expect_pending)
EXPECT_TRUE(registration->pending_version());
else
EXPECT_FALSE(registration->pending_version());
if (expect_active)
EXPECT_TRUE(registration->active_version());
else
EXPECT_FALSE(registration->active_version());
}
} // namespace
class ServiceWorkerContextTest : public testing::Test {
public:
ServiceWorkerContextTest()
: browser_thread_bundle_(TestBrowserThreadBundle::IO_MAINLOOP),
render_process_id_(99) {}
virtual void SetUp() OVERRIDE {
context_.reset(new ServiceWorkerContextCore(base::FilePath(), NULL));
helper_.reset(new EmbeddedWorkerTestHelper(
context_.get(), render_process_id_));
}
virtual void TearDown() OVERRIDE {
helper_.reset();
context_.reset();
}
protected:
TestBrowserThreadBundle browser_thread_bundle_;
scoped_ptr<ServiceWorkerContextCore> context_;
scoped_ptr<EmbeddedWorkerTestHelper> helper_;
const int render_process_id_;
};
// Make sure basic registration is working.
TEST_F(ServiceWorkerContextTest, Register) {
int64 registration_id = -1L;
bool called = false;
context_->RegisterServiceWorker(
GURL("http://www.example.com/*"),
GURL("http://www.example.com/service_worker.js"),
render_process_id_,
MakeRegisteredCallback(&called, ®istration_id));
ASSERT_FALSE(called);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(called);
EXPECT_EQ(2UL, helper_->ipc_sink()->message_count());
EXPECT_TRUE(helper_->inner_ipc_sink()->GetUniqueMessageMatching(
ServiceWorkerMsg_InstallEvent::ID));
EXPECT_NE(-1L, registration_id);
context_->storage()->FindRegistrationForId(
registration_id,
base::Bind(&ExpectRegisteredWorkers,
false /* expect_pending */,
true /* expect_active */));
base::RunLoop().RunUntilIdle();
}
class RejectInstallTestHelper : public EmbeddedWorkerTestHelper {
public:
RejectInstallTestHelper(ServiceWorkerContextCore* context,
int mock_render_process_id)
: EmbeddedWorkerTestHelper(context, mock_render_process_id) {}
virtual void OnInstallEvent(int embedded_worker_id,
int request_id,
int active_version_id) OVERRIDE {
SimulateSendMessageToBrowser(
embedded_worker_id,
request_id,
ServiceWorkerHostMsg_InstallEventFinished(
blink::WebServiceWorkerEventResultRejected));
}
};
// Test registration when the service worker rejects the install event. The
// registration callback should indicate success, but there should be no pending
// or active worker in the registration.
TEST_F(ServiceWorkerContextTest, Register_RejectInstall) {
helper_.reset(
new RejectInstallTestHelper(context_.get(), render_process_id_));
int64 registration_id = -1L;
bool called = false;
context_->RegisterServiceWorker(
GURL("http://www.example.com/*"),
GURL("http://www.example.com/service_worker.js"),
render_process_id_,
MakeRegisteredCallback(&called, ®istration_id));
ASSERT_FALSE(called);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(called);
EXPECT_EQ(2UL, helper_->ipc_sink()->message_count());
EXPECT_TRUE(helper_->inner_ipc_sink()->GetUniqueMessageMatching(
ServiceWorkerMsg_InstallEvent::ID));
EXPECT_NE(-1L, registration_id);
context_->storage()->FindRegistrationForId(
registration_id,
base::Bind(&ExpectRegisteredWorkers,
false /* expect_pending */,
false /* expect_active */));
base::RunLoop().RunUntilIdle();
}
// Test registration when there is an existing registration with no pending or
// active worker.
TEST_F(ServiceWorkerContextTest, Register_DuplicateScriptNoActiveWorker) {
helper_.reset(
new RejectInstallTestHelper(context_.get(), render_process_id_));
int64 old_registration_id = -1L;
bool called = false;
context_->RegisterServiceWorker(
GURL("http://www.example.com/*"),
GURL("http://www.example.com/service_worker.js"),
render_process_id_,
MakeRegisteredCallback(&called, &old_registration_id));
ASSERT_FALSE(called);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(called);
EXPECT_EQ(2UL, helper_->ipc_sink()->message_count());
int64 new_registration_id = -1L;
called = false;
context_->RegisterServiceWorker(
GURL("http://www.example.com/*"),
GURL("http://www.example.com/service_worker.js"),
render_process_id_,
MakeRegisteredCallback(&called, &new_registration_id));
ASSERT_FALSE(called);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(called);
EXPECT_EQ(old_registration_id, new_registration_id);
// Our current implementation does the full registration flow on re-register,
// so the worker receives another start message and install message.
EXPECT_EQ(4UL, helper_->ipc_sink()->message_count());
}
// Make sure registrations are cleaned up when they are unregistered.
TEST_F(ServiceWorkerContextTest, Unregister) {
GURL pattern("http://www.example.com/*");
bool called = false;
int64 registration_id = -1L;
context_->RegisterServiceWorker(
pattern,
GURL("http://www.example.com/service_worker.js"),
render_process_id_,
MakeRegisteredCallback(&called, ®istration_id));
ASSERT_FALSE(called);
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(called);
called = false;
context_->UnregisterServiceWorker(
pattern, render_process_id_, MakeUnregisteredCallback(&called));
ASSERT_FALSE(called);
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(called);
}
// Make sure that when a new registration replaces an existing
// registration, that the old one is cleaned up.
TEST_F(ServiceWorkerContextTest, RegisterNewScript) {
GURL pattern("http://www.example.com/*");
bool called = false;
int64 old_registration_id = -1L;
context_->RegisterServiceWorker(
pattern,
GURL("http://www.example.com/service_worker.js"),
render_process_id_,
MakeRegisteredCallback(&called, &old_registration_id));
ASSERT_FALSE(called);
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(called);
called = false;
int64 new_registration_id = -1L;
context_->RegisterServiceWorker(
pattern,
GURL("http://www.example.com/service_worker_new.js"),
render_process_id_,
MakeRegisteredCallback(&called, &new_registration_id));
ASSERT_FALSE(called);
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(called);
ASSERT_NE(old_registration_id, new_registration_id);
}
// Make sure that when registering a duplicate pattern+script_url
// combination, that the same registration is used.
TEST_F(ServiceWorkerContextTest, RegisterDuplicateScript) {
GURL pattern("http://www.example.com/*");
GURL script_url("http://www.example.com/service_worker.js");
bool called = false;
int64 old_registration_id = -1L;
context_->RegisterServiceWorker(
pattern,
script_url,
render_process_id_,
MakeRegisteredCallback(&called, &old_registration_id));
ASSERT_FALSE(called);
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(called);
called = false;
int64 new_registration_id = -1L;
context_->RegisterServiceWorker(
pattern,
script_url,
render_process_id_,
MakeRegisteredCallback(&called, &new_registration_id));
ASSERT_FALSE(called);
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(called);
ASSERT_EQ(old_registration_id, new_registration_id);
}
} // namespace content
| 31.779661 | 80 | 0.730773 |
54a47a460b163f0d3a76d7153685638c52a9e81b | 2,135 | cc | C++ | deadrec_montecarlo_gyro/DeadRecMonteCarlo.cc | ryuichiueda/ProbabilisticRaspiMouse | de1c58f93d664d15d4b3f8f99c5a2ce6e56240c4 | [
"MIT"
] | 5 | 2015-08-08T09:25:35.000Z | 2022-02-17T04:43:10.000Z | deadrec_montecarlo_gyro/DeadRecMonteCarlo.cc | ryuichiueda/ProbabilisticRaspiMouse | de1c58f93d664d15d4b3f8f99c5a2ce6e56240c4 | [
"MIT"
] | null | null | null | deadrec_montecarlo_gyro/DeadRecMonteCarlo.cc | ryuichiueda/ProbabilisticRaspiMouse | de1c58f93d664d15d4b3f8f99c5a2ce6e56240c4 | [
"MIT"
] | null | null | null | #include "DeadRecMonteCarlo.h"
#include <iostream>
#include <limits.h>
#include <cmath>
using namespace std;
DeadRecMonteCarlo::DeadRecMonteCarlo(int num, ifstream *ifs)
{
Pose p{0.0,0.0,0.0};
m_poses.insert(m_poses.begin(),num,p);
m_rand_ifs = ifs;
m_step = 0;
m_distance_max_noise_ratio = 0.05; // 5% noise
m_direction_max_noise_ratio = 0.01; // 1% noise
}
DeadRecMonteCarlo::~DeadRecMonteCarlo()
{
}
void DeadRecMonteCarlo::motionUpdate(double fw_delta_mm,double side_delta_mm,double t_delta_deg)
{
double t_delta_rad = t_delta_deg * 3.141592 / 180;
for(auto &p : m_poses){
//xy方向
double pos_noise = m_distance_max_noise_ratio * getDoubleRand();
double pos_noise_angle = getDoubleRand() * 2 * 3.141592;
double x_noise = pos_noise * cos(pos_noise_angle);
double y_noise = pos_noise * sin(pos_noise_angle);
p.x_mm += fw_delta_mm * (cos(p.t_rad) + x_noise) + side_delta_mm * sin(p.t_rad);
p.y_mm += fw_delta_mm * (sin(p.t_rad) + y_noise) + side_delta_mm * cos(p.t_rad);
//theta方向
double ratio = m_direction_max_noise_ratio * (2*getDoubleRand()-1.0);
p.t_rad += t_delta_rad * (1.0 + ratio);
}
m_step++;
}
void DeadRecMonteCarlo::pointReset(double x_mm,double y_mm,double t_deg,
double pos_max_noise_mm,double dir_max_noise_deg)
{
for(auto &p : m_poses){
double dir_noise = dir_max_noise_deg *(2*getDoubleRand() - 1.0);
double pos_noise = pos_max_noise_mm * getDoubleRand();
double pos_noise_angle = getDoubleRand() * 2 * 3.141592;
double x_noise = pos_noise * cos(pos_noise_angle);
double y_noise = pos_noise * sin(pos_noise_angle);
p = {x_mm+x_noise, y_mm+y_noise, (t_deg + dir_noise)/180*3.141592};
}
}
// from 0 to UINT_MAX
unsigned int DeadRecMonteCarlo::getIntRand()
{
char buf[4];
m_rand_ifs->read(buf,4);
return (buf[0]<<24) + (buf[1]<<16) + (buf[2]<<8) + buf[3];
}
// from 0.0 to 1.0
double DeadRecMonteCarlo::getDoubleRand()
{
return (double)getIntRand() / UINT_MAX;
}
void DeadRecMonteCarlo::print(ofstream *ofs)
{
for(auto &p : m_poses){
*ofs << m_step << " " << (int)p.x_mm << " " << (int)p.y_mm << " "
<< (int)(p.t_rad / 3.141592 * 180) << endl;
}
}
| 26.6875 | 96 | 0.694145 |
54a900df45ab89a3259ef4d311d1653fe67ab3c8 | 2,098 | hpp | C++ | linkedlist.hpp | joshroybal/cpp-data_structures | 3a570547d096da07c0b65ac0049d58e8d37f8dc3 | [
"MIT"
] | null | null | null | linkedlist.hpp | joshroybal/cpp-data_structures | 3a570547d096da07c0b65ac0049d58e8d37f8dc3 | [
"MIT"
] | null | null | null | linkedlist.hpp | joshroybal/cpp-data_structures | 3a570547d096da07c0b65ac0049d58e8d37f8dc3 | [
"MIT"
] | null | null | null | #ifndef LINKEDLIST_HPP
#define LINKEDLIST_HPP
#include <iostream>
#include <iomanip>
template <class T>
class LinkedList
{
public:
LinkedList() { head_ = 0; }
~LinkedList() { destroy_(head_); }
void Add(const T& k) { head_ = add_(k); }
void Reverse() { head_ = reverse_(head_, 0); }
int Size() const { return size_(head_, 0); }
void Print() const { print_(head_); }
void Report() const;
private:
struct Node;
Node* head_;
void destroy_(Node*);
Node* add_(const T&);
Node* reverse_(Node*, Node*);
int size_(const Node*, int) const;
void print_(const Node*) const;
void printnode_(const Node*) const;
};
template <class T>
struct LinkedList<T>::Node {
Node(const T& k, Node* p=0) : key(k), next(p) {}
T key;
Node* next;
void print() const
{
std::cout << std::setw(10) << this << ':';
std::cout << std::setw(20) << key;
std::cout << std::setw(10) << next << std::endl;
}
};
template <class T>
void LinkedList<T>::Report() const
{
Print();
std::cout << "size = " << Size() << std::endl;
}
template <class T>
void LinkedList<T>::destroy_(Node* node)
{
if (!node) return;
Node* next = node->next;
delete node;
node = 0;
destroy_(next);
}
template <class T>
typename LinkedList<T>::Node* LinkedList<T>::add_(const T& k)
{
return new Node(k, head_);
}
template <class T>
typename LinkedList<T>::Node* LinkedList<T>::reverse_(Node* head, Node* prev)
{
if (!head) return(prev);
Node* body = head->next;
head->next = prev;
return reverse_(body, head);
}
template <class T>
int LinkedList<T>::size_(const Node* node, int siz) const
{
if (!node) return siz;
return size_(node->next, ++siz);
}
template <class T>
void LinkedList<T>::print_(const Node* node) const
{
if (!node) return;
printnode_(node);
print_(node->next);
}
template <class T>
void LinkedList<T>::printnode_(const Node* node) const
{
if (!node) {
std::cout << std::setw(10) << node << std::endl;
return;
}
node->print();
}
#endif
| 20.98 | 77 | 0.596759 |
54a9ea3d1cf584a8d1505c07faf72697055e4aa0 | 26,301 | cpp | C++ | Vault/Source/Vault/Private/SLoaderWindow.cpp | Unreal-Vault/Vault-Dev | 5232794276b238c700c9f4a5fc5bfc4082612f04 | [
"MIT"
] | 11 | 2020-11-04T13:51:19.000Z | 2022-02-24T23:11:44.000Z | Vault/Source/Vault/Private/SLoaderWindow.cpp | Unreal-Vault/Vault-Dev | 5232794276b238c700c9f4a5fc5bfc4082612f04 | [
"MIT"
] | null | null | null | Vault/Source/Vault/Private/SLoaderWindow.cpp | Unreal-Vault/Vault-Dev | 5232794276b238c700c9f4a5fc5bfc4082612f04 | [
"MIT"
] | 3 | 2022-01-23T10:14:56.000Z | 2022-03-30T13:35:10.000Z | // Copyright Daniel Orchard 2020
#include "SLoaderWindow.h"
#include "Vault.h"
#include "VaultSettings.h"
#include "MetadataOps.h"
#include "SAssetPackTile.h"
#include "VaultStyle.h"
#include "AssetPublisher.h"
#include "VaultTypes.h"
#include "ImageUtils.h"
#include "EditorStyleSet.h"
#include "PakFileUtilities.h"
#include "EditorFramework/AssetImportData.h"
#include "AssetImportTask.h"
#include "AssetToolsModule.h"
#define LOCTEXT_NAMESPACE "SVaultLoader"
const int32 SLoaderWindow::THUMBNAIL_BASE_HEIGHT = 415;
const int32 SLoaderWindow::THUMBNAIL_BASE_WIDTH = 415;
const int32 SLoaderWindow::TILE_BASE_HEIGHT = 465;
const int32 SLoaderWindow::TILE_BASE_WIDTH = 415;
namespace VaultColumnNames
{
static const FName TagCheckedColumnName(TEXT("Flag"));
static const FName TagNameColumnName(TEXT("Tag Name"));
static const FName TagCounterColumnName(TEXT("Used"));
};
class VAULT_API STagFilterRow : public SMultiColumnTableRow<FTagFilteringItemPtr>
{
public:
SLATE_BEGIN_ARGS(STagFilterRow) {}
SLATE_ARGUMENT(FTagFilteringItemPtr, TagData)
SLATE_ARGUMENT(TSharedPtr<SLoaderWindow>, ParentWindow)
SLATE_END_ARGS()
void Construct(const FArguments& InArgs, const TSharedRef<STableViewBase>& OwnerTableView)
{
TagData = InArgs._TagData;
ParentWindow = InArgs._ParentWindow;
SMultiColumnTableRow<FTagFilteringItemPtr>::Construct(FSuperRowType::FArguments().Padding(1.0f), OwnerTableView);
}
void OnCheckBoxStateChanged(ECheckBoxState NewCheckedState)
{
const bool Filter = NewCheckedState == ECheckBoxState::Checked;
ParentWindow->ModifyActiveTagFilters(TagData->Tag, Filter);
}
virtual TSharedRef<SWidget> GenerateWidgetForColumn(const FName& ColumnName) override
{
static const FMargin ColumnItemPadding(5, 0, 5, 0);
if (ColumnName == VaultColumnNames::TagCheckedColumnName)
{
return SNew(SCheckBox)
.IsChecked(false)
.OnCheckStateChanged(this, &STagFilterRow::OnCheckBoxStateChanged);
}
else if (ColumnName == VaultColumnNames::TagNameColumnName)
{
return SNew(STextBlock)
.Text(FText::FromString(TagData->Tag));
}
else if (ColumnName == VaultColumnNames::TagCounterColumnName)
{
return SNew(STextBlock)
.Text(FText::FromString(FString::FromInt(TagData->UseCount)));
}
else
{
return SNullWidget::NullWidget;
}
}
private:
FTagFilteringItemPtr TagData;
TSharedPtr<SLoaderWindow> ParentWindow;
};
class VAULT_API SDeveloperFilterRow : public SMultiColumnTableRow<FDeveloperFilteringItemPtr>
{
public:
SLATE_BEGIN_ARGS(SDeveloperFilterRow) {}
SLATE_ARGUMENT(FDeveloperFilteringItemPtr, Entry)
SLATE_ARGUMENT(TSharedPtr<SLoaderWindow>, ParentWindow)
SLATE_END_ARGS()
void Construct(const FArguments& InArgs, const TSharedRef<STableViewBase>& OwnerTableView)
{
Entry = InArgs._Entry;
ParentWindow = InArgs._ParentWindow;
SMultiColumnTableRow<FDeveloperFilteringItemPtr>::Construct(FSuperRowType::FArguments().Padding(1.0f), OwnerTableView);
}
void OnCheckBoxStateChanged(ECheckBoxState NewCheckedState)
{
const bool Filter = NewCheckedState == ECheckBoxState::Checked;
ParentWindow->ModifyActiveDevFilters(Entry->Developer, Filter);
}
virtual TSharedRef<SWidget> GenerateWidgetForColumn(const FName& ColumnName) override
{
static const FMargin ColumnItemPadding(5, 0, 5, 0);
if (ColumnName == VaultColumnNames::TagCheckedColumnName)
{
return SNew(SCheckBox)
.IsChecked(false)
.OnCheckStateChanged(this, &SDeveloperFilterRow::OnCheckBoxStateChanged);
}
else if (ColumnName == VaultColumnNames::TagNameColumnName)
{
return SNew(STextBlock)
.Text(FText::FromName(Entry->Developer));
}
else if (ColumnName == VaultColumnNames::TagCounterColumnName)
{
return SNew(STextBlock)
.Text(FText::FromString(FString::FromInt(Entry->UseCount)));
}
else
{
return SNullWidget::NullWidget;
}
}
private:
FDeveloperFilteringItemPtr Entry;
TSharedPtr<SLoaderWindow> ParentWindow;
};
void SLoaderWindow::Construct(const FArguments& InArgs, const TSharedRef<SDockTab>& ConstructUnderMajorTab, const TSharedPtr<SWindow>& ConstructUnderWindow)
{
RefreshAvailableFiles();
PopulateBaseAssetList();
PopulateTagArray();
PopulateDeveloperNameArray();
// Bind to our publisher so we can refresh automatically when the user publishes an asset (they wont need to import it, but its a visual feedback for the user to check it appeared in the library
UAssetPublisher::OnVaultPackagingCompletedDelegate.BindRaw(this, &SLoaderWindow::OnNewAssetPublished);
// Construct the Holder for the Metadata List
MetadataWidget = SNew(SVerticalBox);
// Set the Default Scale for Sliders.
TileUserScale = 0.5;
const float TILE_SCALED_WIDTH = TILE_BASE_WIDTH * TileUserScale;
const float TILE_SCALED_HEIGHT = TILE_BASE_HEIGHT * TileUserScale;
// Main Widget
TSharedRef<SVerticalBox> LoaderRoot = SNew(SVerticalBox)
+ SVerticalBox::Slot()
.FillHeight(1.0f)
[
// Primary 3 Boxes go in Here
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
[
SNew(SSplitter)
.Orientation(Orient_Horizontal)
+SSplitter::Slot()
.Value(0.2f)
[
SNew(SBorder)
.BorderImage(FEditorStyle::GetBrush("ToolPanel.GroupBorder"))
.Padding(FMargin(4.0f, 4.0f))
[
// Left Sidebar!
SNew(SVerticalBox)
+SVerticalBox::Slot()
.Padding(0,3,0,5)
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("VaultLoaderSidebarHeaderLabel", "FILTERING"))
.TextStyle(FVaultStyle::Get(), "MetaTitleText")
]
// Asset List Amount
+ SVerticalBox::Slot()
.AutoHeight()
.HAlign(HAlign_Left)
.VAlign(VAlign_Top)
.Padding(0,0,0,5)
[
SNew(STextBlock)
.Text(this, &SLoaderWindow::DisplayTotalAssetsInLibrary)
]
// Tag filtering
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(SListView<FTagFilteringItemPtr>)
.SelectionMode(ESelectionMode::Single)
.ListItemsSource(&TagCloud)
.OnGenerateRow(this, &SLoaderWindow::MakeTagFilterViewWidget)
.HeaderRow
(
SNew(SHeaderRow)
+ SHeaderRow::Column(VaultColumnNames::TagCheckedColumnName)
.DefaultLabel(LOCTEXT("FilteringBoolLabel", "Filter"))
.FixedWidth(40.0f)
+ SHeaderRow::Column(VaultColumnNames::TagNameColumnName)
.DefaultLabel(LOCTEXT("TagFilteringTagNameLabel", "Tags"))
+ SHeaderRow::Column(VaultColumnNames::TagCounterColumnName)
.DefaultLabel(LOCTEXT("TagFilteringCounterLabel", "Used"))
)
]
// Developer Filtering
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(SListView<FDeveloperFilteringItemPtr>)
.SelectionMode(ESelectionMode::Single)
.ListItemsSource(&DeveloperCloud)
.OnGenerateRow(this, &SLoaderWindow::MakeDeveloperFilterViewWidget)
.HeaderRow
(
SNew(SHeaderRow)
+ SHeaderRow::Column(VaultColumnNames::TagCheckedColumnName)
.DefaultLabel(LOCTEXT("FilteringBoolLabel", "Filter"))
.FixedWidth(40.0f)
+ SHeaderRow::Column(VaultColumnNames::TagNameColumnName)
.DefaultLabel(LOCTEXT("TagFilteringTagNameLabel", "Tags"))
+ SHeaderRow::Column(VaultColumnNames::TagCounterColumnName)
.DefaultLabel(LOCTEXT("TagFilteringCounterLabel", "Used"))
)
]
// Misc Filtering
+SVerticalBox::Slot()
// Spacer
+ SVerticalBox::Slot()
[
SNew(SSpacer)
]
// Selected Asset metadata
+ SVerticalBox::Slot()
] // close SBorder
] // ~Close Left Splitter Area
// Center Area!
+SSplitter::Slot()
.Value(0.6f)
[
SNew(SBorder)
.BorderImage(FEditorStyle::GetBrush("ToolPanel.GroupBorder"))
.Padding(FMargin(4.0f, 4.0f))
[
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.FillWidth(1)
.Padding(FMargin(0,3,0,0))
[
// Center content area
SAssignNew(SearchBox, SSearchBox)
.HintText(LOCTEXT("SearchBoxHintText", "Search..."))
.OnTextChanged(this, &SLoaderWindow::OnSearchBoxChanged)
.OnTextCommitted(this, &SLoaderWindow::OnSearchBoxCommitted)
.DelayChangeNotificationsWhileTyping(false)
.Visibility(EVisibility::Visible)
.Style(FVaultStyle::Get(), "AssetSearchBar")
.AddMetaData<FTagMetaData>(FTagMetaData(TEXT("AssetSearch")))
]
+ SHorizontalBox::Slot()
.Padding(FMargin(15.f,0.f, 5.f, 0.f))
.AutoWidth()
[
SAssignNew(StrictSearchCheckBox, SCheckBox)
.Style(FCoreStyle::Get(), "ToggleButtonCheckbox")
.Padding(FMargin( 5.f,0.f ))
.ToolTipText(LOCTEXT("StrictSearchToolTip", "Search only the Pack Names"))
[
SNew(SBox)
.VAlign(VAlign_Center)
.HAlign(HAlign_Center)
.Padding(FMargin(4.f,2.f))
[
SNew(STextBlock)
.Text(LOCTEXT("StrictSearchCheckBox", "Strict Search"))
]
]
]
]
// Tile View
+ SVerticalBox::Slot()
.FillHeight(1.0f)
[
SNew(SBox)
.Padding(FMargin(5,5,5,5))
[
SAssignNew(TileView, STileView<TSharedPtr<FVaultMetadata>>)
.ItemWidth(TILE_SCALED_WIDTH)
.ItemHeight(TILE_SCALED_HEIGHT)
.ItemAlignment(EListItemAlignment::EvenlyDistributed)
.ListItemsSource(&FilteredAssetItems)
.OnGenerateTile(this, &SLoaderWindow::MakeTileViewWidget)
.SelectionMode(ESelectionMode::Single)
.OnSelectionChanged(this, &SLoaderWindow::OnAssetTileSelectionChanged)
.OnMouseButtonDoubleClick(this, &SLoaderWindow::OnAssetTileDoubleClicked)
.OnContextMenuOpening(this, &SLoaderWindow::OnAssetTileContextMenuOpened)
]
]
// Bottom Bar
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(SButton)
.Text(LOCTEXT("RefreshLibraryScreenBtnLbl", "Refresh Library"))
.OnClicked(this, &SLoaderWindow::OnRefreshLibraryClicked)
]
+ SHorizontalBox::Slot()
[
SNew(SSpacer)
]
+ SHorizontalBox::Slot()
[
// Scale Slider
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
.HAlign(HAlign_Right)
.Padding(FMargin(0, 0, 0, 0))
[
SNew(STextBlock)
.Text(LOCTEXT("ScaleSliderLabel", "Thumbnail Scale"))
.Justification(ETextJustify::Right)
]
+ SHorizontalBox::Slot()
[
SAssignNew(UserScaleSlider, SSlider)
.Value(TileUserScale)
.MinValue(0.2)
.OnValueChanged(this, &SLoaderWindow::OnThumbnailSliderValueChanged)
]
]
]
] // close border for center area
] // ~ Close Center Area Splitter
// Metadata Zone
+ SSplitter::Slot()
.Value(0.2f)
[
SNew(SBorder)
.BorderImage(FEditorStyle::GetBrush("ToolPanel.GroupBorder"))
.Padding(FMargin(4.0f, 4.0f))
[
// Left Sidebar!
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("VaultLoaderRightSidebarHeaderLabel", "METADATA"))
.TextStyle(FVaultStyle::Get(), "MetaTitleText")
]
+ SVerticalBox::Slot()
.FillHeight(1)
[
SNew(SBox)
[
MetadataWidget.ToSharedRef()
]
]
]
]
] // ~ hbox
]; // ~ LoaderRoot
ChildSlot
[
SNew(SBorder)
.BorderImage(FEditorStyle::GetBrush("ToolPanel.DarkGroupBorder"))
.Padding(FMargin(2.f,2.f))
[
LoaderRoot
]
];
}
void SLoaderWindow::Tick(const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime)
{
}
void SLoaderWindow::PopulateBaseAssetList()
{
FilteredAssetItems.Empty();
for (FVaultMetadata Meta : MetaFilesCache)
{
FilteredAssetItems.Add(MakeShareable(new FVaultMetadata(Meta)));
}
}
// Only shows tags that are actually used, no empty tags will appear.
void SLoaderWindow::PopulateTagArray()
{
// Empty Tag Container
TagCloud.Empty();
// Create a map version of the array for more efficient searching.
TMap<FString, FTagFilteringItemPtr> TagCloudMap;
// For each Asset in our global list of assets...
for (auto Asset : MetaFilesCache)
{
// Get each tag belonging to that asset...
for (const FString AssetTag : Asset.Tags)
{
// If we already have a tag stored for it, increment the use counter
if (TagCloudMap.Contains(AssetTag))
{
TagCloudMap.Find(AssetTag)->Get()->UseCount++;
}
// otherwise, add a new tag to our list.
else
{
FTagFilteringItemPtr TagTemp = MakeShareable(new FTagFilteringItem);
TagTemp->Tag = AssetTag;
TagTemp->UseCount = 1;
TagCloudMap.Add(AssetTag, TagTemp);
}
}
}
// The Map version is easier to work with during generation, but since we have to use an Array, we convert our cloud map into an array now:
TagCloudMap.GenerateValueArray(TagCloud);
}
void SLoaderWindow::PopulateDeveloperNameArray()
{
// Developer Array
DeveloperCloud.Empty();
TMap<FName, int32> DevAssetCounter;
for (auto AssetItem : FilteredAssetItems)
{
if (DevAssetCounter.Contains(AssetItem->Author))
{
int Count = *DevAssetCounter.Find(AssetItem->Author);
Count++;
DevAssetCounter.Add(AssetItem->Author, Count);
}
else
{
DevAssetCounter.Add(AssetItem->Author, 1);
}
}
for (auto dev : DevAssetCounter)
{
FDeveloperFilteringItemPtr DevTemp = MakeShareable(new FDeveloperFilteringItem);
DevTemp->Developer = dev.Key;
DevTemp->UseCount = dev.Value;
DeveloperCloud.AddUnique(DevTemp);
}
}
TSharedRef<ITableRow> SLoaderWindow::MakeTileViewWidget(TSharedPtr<FVaultMetadata> AssetItem, const TSharedRef<STableViewBase>& OwnerTable)
{
return SNew(STableRow<TSharedPtr<FVaultMetadata>>, OwnerTable)
.Style(FEditorStyle::Get(), "ContentBrowser.AssetListView.TableRow")
.Padding(FMargin(5.0f, 5.0f, 5.0f, 25.0f))
[
SNew(SAssetTileItem)
.AssetItem(AssetItem)
];
}
TSharedRef<ITableRow> SLoaderWindow::MakeTagFilterViewWidget(FTagFilteringItemPtr inTag, const TSharedRef<STableViewBase>& OwnerTable)
{
return SNew(STagFilterRow, OwnerTable)
.TagData(inTag)
.ParentWindow(SharedThis(this));
}
TSharedRef<ITableRow> SLoaderWindow::MakeDeveloperFilterViewWidget(FDeveloperFilteringItemPtr Entry, const TSharedRef<STableViewBase>& OwnerTable)
{
return SNew(SDeveloperFilterRow, OwnerTable)
.Entry(Entry)
.ParentWindow(SharedThis(this));
}
void SLoaderWindow::OnAssetTileSelectionChanged(TSharedPtr<FVaultMetadata> InItem, ESelectInfo::Type SelectInfo)
{
// Checks if anything is selected
if (TileView->GetNumItemsSelected() > 0)
{
ConstructMetadataWidget(InItem);
return;
}
// If no selection, clear the active metadata.
MetadataWidget->ClearChildren();
}
void SLoaderWindow::OnAssetTileDoubleClicked(TSharedPtr<FVaultMetadata> InItem)
{
// #todo Add Item to Project on Double Click
LoadAssetPackIntoProject(InItem);
}
TSharedPtr<SWidget> SLoaderWindow::OnAssetTileContextMenuOpened()
{
// Lets check we have stuff selected, we only want the context menu on selected items. No need to open on a blank area
if (TileView->GetNumItemsSelected() == 0)
{
return SNullWidget::NullWidget;
}
// Store our selected item for any future operations.
TSharedPtr<FVaultMetadata> SelectedAsset = TileView->GetSelectedItems()[0];
FMenuBuilder MenuBuilder(true, nullptr, nullptr, true);
static const FName FilterSelectionHook("AssetContextMenu");
MenuBuilder.BeginSection(FilterSelectionHook, LOCTEXT("AssetContextMenuLabel", "Vault Asset"));
{
MenuBuilder.AddMenuEntry(LOCTEXT("ACM_AddToProjectLabel", "Add To Project"), FText::GetEmpty(), FSlateIcon(),
FUIAction(FExecuteAction::CreateLambda([this, SelectedAsset]()
{
LoadAssetPackIntoProject(SelectedAsset);
}),
FCanExecuteAction(),
FGetActionCheckState(),
FIsActionButtonVisible()));
MenuBuilder.AddMenuEntry(LOCTEXT("ACM_EditVaultAssetDetailsLabel", "Edit Asset"), FText::GetEmpty(), FSlateIcon(),
FUIAction(FExecuteAction::CreateLambda([this, SelectedAsset]()
{
const FString LibraryPath = FVaultSettings::Get().GetAssetLibraryRoot();
const FString MetaFilePath = LibraryPath / SelectedAsset->PackName.ToString() + ".meta";
// Rather than provide a tonne of edit options in engine and a load of extra UI support, for the time being lets just open the file in a text editor
FPlatformProcess::LaunchFileInDefaultExternalApplication(*MetaFilePath);
}),
FCanExecuteAction(),
FGetActionCheckState(),
FIsActionButtonVisible()));
MenuBuilder.AddMenuEntry(LOCTEXT("ACM_DeleteVaultAssetLabel", "Delete Asset"), FText::GetEmpty(), FSlateIcon(),
FUIAction(FExecuteAction::CreateLambda([this, SelectedAsset]()
{
// Open a Msg dialog to confirm deletion
const EAppReturnType::Type Confirmation = FMessageDialog::Open(EAppMsgType::YesNo, LOCTEXT("DeleteViaContextMsg", "Are you sure you want to delete this asset from the Vault Library \nThis option cannot be undone." ));
if (Confirmation == EAppReturnType::Yes)
{
// Delete Pack. Handles all the UI stuff from here as well as the file deletes.
DeleteAssetPack(SelectedAsset);
}
}),
FCanExecuteAction(),
FGetActionCheckState(),
FIsActionButtonVisible()));
}
MenuBuilder.EndSection();
return MenuBuilder.MakeWidget();
}
void SLoaderWindow::OnSearchBoxChanged(const FText& inSearchText)
{
//FilteredAssetItems.Empty();
// If its now empty, it was probably cleared or backspaced through, so we need to reapply just the filter based results.
if (inSearchText.IsEmpty())
{
UpdateFilteredAssets();
return;
}
// Store Strict Search - This controls if we only search pack name, or various data entries.
const bool bStrictSearch = StrictSearchCheckBox->GetCheckedState() == ECheckBoxState::Checked;
const FString SearchString = inSearchText.ToString();
// Holder for the newly filtered Results:
TArray<TSharedPtr<FVaultMetadata>> SearchMatchingEntries;
// Instead of searching raw meta, we search the filtered results, so this respects the tag and dev filters first, and we search within that.
for (auto Meta : FilteredAssetItems)
{
if (Meta->PackName.ToString().Contains(SearchString))
{
SearchMatchingEntries.Add(Meta);
continue;
}
if (bStrictSearch == false)
{
if (Meta->Author.ToString().Contains(SearchString) || Meta->Description.Contains(SearchString))
{
SearchMatchingEntries.Add(Meta);
}
}
}
FilteredAssetItems = SearchMatchingEntries;
TileView->RebuildList();
TileView->ScrollToTop();
}
void SLoaderWindow::OnSearchBoxCommitted(const FText& InFilterText, ETextCommit::Type CommitType)
{
OnSearchBoxChanged(InFilterText);
}
void SLoaderWindow::ConstructMetadataWidget(TSharedPtr<FVaultMetadata> AssetMeta)
{
// Safety Catches for Null Assets. Should never occur.
if (!MetadataWidget.IsValid())
{
UE_LOG(LogVault, Error, TEXT("Error - Metadata Ptr is Null."));
return;
}
if (!AssetMeta.IsValid() || !AssetMeta->IsMetaValid())
{
UE_LOG(LogVault, Error, TEXT("Error - Metadata Incoming Data is Null."));
return;
}
// Padding between words
const FMargin WordPadding = FMargin(0.f,12.f,0.f,0.f);
MetadataWidget->ClearChildren();
// Pack Name
MetadataWidget->AddSlot()
.AutoHeight()
.Padding(WordPadding)
[
SNew(STextBlock)
.Text(FText::FromName(AssetMeta->PackName))
];
// Description
MetadataWidget->AddSlot()
.AutoHeight()
.Padding(WordPadding)
[
SNew(STextBlock)
.AutoWrapText(true)
//.Text(FText::Format(LOCTEXT("Meta_DescLbl", "Description: \n{0}"), FText::FromString(AssetMeta->Description)))
.Text(FText::FromString(AssetMeta->Description))
];
// Author
MetadataWidget->AddSlot()
.AutoHeight()
.Padding(WordPadding)
[
SNew(STextBlock)
.Text(FText::Format(LOCTEXT("Meta_AuthorLbl", "Author: {0}"), FText::FromName(AssetMeta->Author)))
];
// Creation Date
MetadataWidget->AddSlot()
.AutoHeight()
.Padding(WordPadding)
[
SNew(STextBlock)
.Text(FText::Format(LOCTEXT("Meta_CreationLbl", "Created: {0}"), FText::FromString(AssetMeta->CreationDate.ToString())))
];
// Last Modified Date
MetadataWidget->AddSlot()
.AutoHeight()
.Padding(WordPadding)
[
SNew(STextBlock)
.Text(FText::Format(LOCTEXT("Meta_LastModifiedLbl", "Last Modified: {0}"), FText::FromString(AssetMeta->LastModified.ToString())))
];
// Tags List - Header
MetadataWidget->AddSlot()
.AutoHeight()
.Padding(WordPadding)
[
SNew(STextBlock)
.AutoWrapText(true)
//.Text(FText::Format(LOCTEXT("Meta_TagsLbl", "Tags: {0}"), FText::FromString(FString::Join(AssetMeta->Tags.Array(), TEXT(",")))))
.Text(LOCTEXT("Meta_TagsLbl", "Tags:"))
];
// Tags, Per Tag. Instead of using Join, we add them as separate lines for ease of reading
for (auto MyTag : AssetMeta->Tags)
{
MyTag.TrimStartAndEndInline();
const FText TagName = FText::FromString(MyTag);
//MyTag.RemoveSpacesInline();
MetadataWidget->AddSlot()
.AutoHeight()
[
SNew(STextBlock)
.Text(FText::Format(LOCTEXT("PerTagKeyFor{0}", "- {1}"), TagName, TagName))
];
}
// Object List
MetadataWidget->AddSlot()
.AutoHeight()
.Padding(WordPadding)
[
SNew(STextBlock)
.AutoWrapText(true)
.Text(FText::Format(LOCTEXT("Meta_FilesLbl", "Files: {0}"), FText::FromString(FString::Join(AssetMeta->ObjectsInPack.Array(), TEXT(",")))))
];
}
void SLoaderWindow::LoadAssetPackIntoProject(TSharedPtr<FVaultMetadata> InPack)
{
// Root Directory
const FString LibraryPath = FVaultSettings::Get().GetAssetLibraryRoot();
// All files live in same directory, so we just do some string mods to get the pack file that matches the meta file.
const FString AssetToImportTemp = LibraryPath / InPack->PackName.ToString() + ".upack";
// UPacks import natively with Unreal, so no need to try to use the PakUtilities, better to use the native importer and let Unreal handle the Pak concepts.
FAssetToolsModule& AssetToolsModule = FModuleManager::Get().LoadModuleChecked<FAssetToolsModule>("AssetTools");
// Set up our Import Task
UAssetImportTask* Task = NewObject<UAssetImportTask>();
Task->AddToRoot();
Task->bAutomated = true;
Task->bReplaceExisting = true;
Task->bSave = true;
Task->Filename = AssetToImportTemp;
Task->DestinationPath = "/Game";
TArray<UAssetImportTask*> Tasks;
Tasks.Add(Task);
AssetToolsModule.Get().ImportAssetTasks(Tasks);
// Allow GC to collect
Task->RemoveFromRoot();
}
void SLoaderWindow::DeleteAssetPack(TSharedPtr<FVaultMetadata> InPack)
{
// Confirmation will have occurred already for this operation (Might be changed in future to have confirmation here)
UE_LOG(LogVault, Display, TEXT("Deleting File(s) from Vault: %s"), *InPack->PackName.ToString());
const FString LibraryPath = FVaultSettings::Get().GetAssetLibraryRoot();
const FString FilePathAbsNoExt = LibraryPath / InPack->PackName.ToString();
const FString AbsThumbnailPath = FilePathAbsNoExt + ".png";
const FString AbsMetaPath = FilePathAbsNoExt + ".meta";
const FString AbsPackPath = FilePathAbsNoExt + ".upack";
IFileManager::Get().Delete(*AbsThumbnailPath, true);
IFileManager::Get().Delete(*AbsMetaPath, true);
IFileManager::Get().Delete(*AbsPackPath, true);
MetaFilesCache.Remove(*InPack);
RefreshLibrary();
//UpdateFilteredAssets();
//TileView->RebuildList();
}
void SLoaderWindow::RefreshAvailableFiles()
{
MetaFilesCache = FMetadataOps::FindAllMetadataInLibrary();
}
// Applies the List of filters all together.
void SLoaderWindow::UpdateFilteredAssets()
{
FilteredAssetItems.Empty();
// Special Condition to check if all boxes are cleared:
if (ActiveTagFilters.Num() == 0 && ActiveDevFilters.Num() == 0)
{
PopulateBaseAssetList();
TileView->RebuildList();
TileView->ScrollToTop();
return;
}
for (auto Asset : MetaFilesCache)
{
// Apply all filtered Tags
for (auto UserTag : Asset.Tags)
{
if (ActiveTagFilters.Contains(UserTag))
{
FilteredAssetItems.Add(MakeShareable(new FVaultMetadata(Asset)));
break;
}
}
// Apply All Developer Tags
if (ActiveDevFilters.Contains(Asset.Author))
{
FilteredAssetItems.Add(MakeShareable(new FVaultMetadata(Asset)));
continue;
}
}
TileView->RebuildList();
TileView->ScrollToTop();
}
void SLoaderWindow::OnThumbnailSliderValueChanged(float Value)
{
TileUserScale = Value;
TileView->SetItemWidth(TILE_BASE_WIDTH * TileUserScale);
TileView->SetItemHeight(TILE_BASE_HEIGHT * TileUserScale);
TileView->RebuildList();
}
FText SLoaderWindow::DisplayTotalAssetsInLibrary() const
{
int assetCount = FMetadataOps::FindAllMetadataInLibrary().Num();
FText Display = FText::Format(LOCTEXT("displayassetcountlabel", "Total Assets in library: {0}"),assetCount);
return Display;
}
FReply SLoaderWindow::OnRefreshLibraryClicked()
{
RefreshLibrary();
return FReply::Handled();
}
void SLoaderWindow::RefreshLibrary()
{
RefreshAvailableFiles();
PopulateTagArray();
PopulateDeveloperNameArray();
//SearchBox->AdvanceSearch//
//TileView->RebuildList();
UpdateFilteredAssets();
}
void SLoaderWindow::OnNewAssetPublished()
{
RefreshLibrary();
}
void SLoaderWindow::ModifyActiveTagFilters(FString TagModified, bool bFilterThis)
{
UE_LOG(LogVault, Display, TEXT("Enabling Tag Filter For %s"), *TagModified);
if (bFilterThis)
{
// Push our Active Tag into our Set of Tags currently being searched
ActiveTagFilters.Add(TagModified);
UpdateFilteredAssets();
return;
}
ActiveTagFilters.Remove(TagModified);
UpdateFilteredAssets();
}
void SLoaderWindow::ModifyActiveDevFilters(FName DevModified, bool bFilterThis)
{
UE_LOG(LogVault, Display, TEXT("Enabling Dev Filter %s"), *DevModified.ToString());
if (bFilterThis)
{
ActiveDevFilters.Add(DevModified);
UpdateFilteredAssets();
return;
}
ActiveDevFilters.Remove(DevModified);
UpdateFilteredAssets();
}
#undef LOCTEXT_NAMESPACE | 27.685263 | 222 | 0.705943 |
54ab167058ce125f5fa40b23910f9857416f3ac2 | 276 | hpp | C++ | src/Time.hpp | matheuscscp/parallel-programming-final-project | 088934d2cf188e2953de773424e877d78933ae3f | [
"MIT"
] | 2 | 2019-05-26T17:13:23.000Z | 2019-06-09T05:48:57.000Z | src/Time.hpp | matheuscscp/delta-stepping | 088934d2cf188e2953de773424e877d78933ae3f | [
"MIT"
] | null | null | null | src/Time.hpp | matheuscscp/delta-stepping | 088934d2cf188e2953de773424e877d78933ae3f | [
"MIT"
] | null | null | null | /*
* Time.hpp
*
* Created on: Nov 20, 2014
* Author: matheus
*/
#ifndef TIME_HPP_
#define TIME_HPP_
#include <sys/time.h>
class Stopwatch {
private:
timeval i;
public:
Stopwatch();
void start();
float time() const;
};
#endif /* TIME_HPP_ */
| 12 | 28 | 0.594203 |
54ab50e9d1dc5c0ea91d3cb67f1434487d879004 | 681 | cpp | C++ | C++/holes.cpp | MADHAVAN001/Competitive-Programming-Practice | ca895315078880b403f4656677f60905681e7b86 | [
"MIT"
] | null | null | null | C++/holes.cpp | MADHAVAN001/Competitive-Programming-Practice | ca895315078880b403f4656677f60905681e7b86 | [
"MIT"
] | null | null | null | C++/holes.cpp | MADHAVAN001/Competitive-Programming-Practice | ca895315078880b403f4656677f60905681e7b86 | [
"MIT"
] | null | null | null | using namespace std;
#include<stdio.h>
#include<iostream>
int main()
{
int num_lines;
int count[50];
char text[50][100];
std::cout<<"This is the program to count number of holes in text";
std::cout<<endl<<"Please enter the number of lines follwed by each of the lines: ";
cin>>num_lines;
for(int i = 0;i<num_lines;i++)
{
cin>>text[i];
count[i] = 0;
for(int j = 0;text[i][j] != '\0';j++)
{
if(text[i][j] == 'A' || text[i][j] == 'O' || text[i][j] == 'R' || text[i][j] == 'D' || text[i][j] == 'P' ||text[i][j] == 'Q')
count[i]++;
else if(text[i][j] == 'B')
count[i]+=2;
}
}
std::cout<<endl;
for(int i = 0;i<num_lines;i++)
std::cout<<count[i]<<endl;
return 0;
}
| 20.636364 | 127 | 0.562408 |
54ab7ccc3f96c9c82b3d77678a96f0a80fb2ec06 | 51 | hpp | C++ | src/boost_metaparse_limit_sequence_size.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_metaparse_limit_sequence_size.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_metaparse_limit_sequence_size.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/metaparse/limit_sequence_size.hpp>
| 25.5 | 50 | 0.843137 |
54b018813113477897e3df2360859fed801e2c3f | 18,212 | cpp | C++ | source/tflite-model/trained_model_compiled.cpp | LetsOKdo/dance-activated-microbit | 812c14169f4b8c61acbfc1ff0a7aeed4546eda13 | [
"MIT"
] | 3 | 2021-07-12T05:38:00.000Z | 2022-03-02T14:55:23.000Z | source/tflite-model/trained_model_compiled.cpp | LetsOKdo/dance-activated-microbit | 812c14169f4b8c61acbfc1ff0a7aeed4546eda13 | [
"MIT"
] | null | null | null | source/tflite-model/trained_model_compiled.cpp | LetsOKdo/dance-activated-microbit | 812c14169f4b8c61acbfc1ff0a7aeed4546eda13 | [
"MIT"
] | null | null | null | /* Generated by Edge Impulse
*
* 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.
*/
// Generated on: 11.11.2020 18:46:14
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include "edge-impulse-sdk/tensorflow/lite/c/builtin_op_data.h"
#include "edge-impulse-sdk/tensorflow/lite/c/common.h"
#include "edge-impulse-sdk/tensorflow/lite/micro/kernels/micro_ops.h"
#if defined __GNUC__
#define ALIGN(X) __attribute__((aligned(X)))
#elif defined _MSC_VER
#define ALIGN(X) __declspec(align(X))
#elif defined __TASKING__
#define ALIGN(X) __align(X)
#endif
namespace {
constexpr int kTensorArenaSize = 144;
uint8_t* tensor_arena = NULL;
static uint8_t* current_location;
static uint8_t* tensor_boundary;
template <int SZ, class T> struct TfArray {
int sz; T elem[SZ];
};
enum used_operators_e {
OP_FULLY_CONNECTED, OP_SOFTMAX, OP_LAST
};
struct TensorInfo_t { // subset of TfLiteTensor used for initialization from constant memory
TfLiteAllocationType allocation_type;
TfLiteType type;
void* data;
TfLiteIntArray* dims;
size_t bytes;
TfLiteQuantization quantization;
};
struct NodeInfo_t { // subset of TfLiteNode used for initialization from constant memory
struct TfLiteIntArray* inputs;
struct TfLiteIntArray* outputs;
void* builtin_data;
used_operators_e used_op_index;
};
TfLiteContext ctx{};
TfLiteTensor tflTensors[11];
TfLiteRegistration registrations[OP_LAST];
TfLiteNode tflNodes[4];
const TfArray<2, int> tensor_dimension0 = { 2, { 1,33 } };
const TfArray<1, float> quant0_scale = { 1, { 359.61181640625, } };
const TfArray<1, int> quant0_zero = { 1, { -128 } };
const TfLiteAffineQuantization quant0 = { (TfLiteFloatArray*)&quant0_scale, (TfLiteIntArray*)&quant0_zero, 0 };
const ALIGN(8) int32_t tensor_data1[20] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, };
const TfArray<1, int> tensor_dimension1 = { 1, { 20 } };
const TfArray<1, float> quant1_scale = { 1, { 0.99230742454528809, } };
const TfArray<1, int> quant1_zero = { 1, { 0 } };
const TfLiteAffineQuantization quant1 = { (TfLiteFloatArray*)&quant1_scale, (TfLiteIntArray*)&quant1_zero, 0 };
const ALIGN(8) int32_t tensor_data2[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, };
const TfArray<1, int> tensor_dimension2 = { 1, { 10 } };
const TfArray<1, float> quant2_scale = { 1, { 0.73306155204772949, } };
const TfArray<1, int> quant2_zero = { 1, { 0 } };
const TfLiteAffineQuantization quant2 = { (TfLiteFloatArray*)&quant2_scale, (TfLiteIntArray*)&quant2_zero, 0 };
const ALIGN(8) int32_t tensor_data3[2] = { 0, 0, };
const TfArray<1, int> tensor_dimension3 = { 1, { 2 } };
const TfArray<1, float> quant3_scale = { 1, { 1.3037328720092773, } };
const TfArray<1, int> quant3_zero = { 1, { 0 } };
const TfLiteAffineQuantization quant3 = { (TfLiteFloatArray*)&quant3_scale, (TfLiteIntArray*)&quant3_zero, 0 };
const ALIGN(8) int8_t tensor_data4[20*33] = {
-82, -76, -66, 21, -13, 18, -95, -81, -91, 24, 114, -53, -74, 113, 57, 125, 117, -32, 89, -70, 111, -102, 120, -80, -62, -62, -102, 56, -40, -35, -69, -100, 29,
10, 20, -6, -53, 19, 107, 70, 95, -102, 72, 58, -60, -31, -105, -75, -49, -52, -102, 86, 55, -5, -68, -102, -73, 32, -75, 26, 51, -70, -1, 92, 104, -119,
8, -109, -86, 58, 9, 34, -106, -20, -72, 21, -32, -27, -80, -26, 74, -98, -75, -28, 97, -113, 74, -13, -52, 33, -45, 111, 20, -55, -10, -68, -72, 99, -97,
-125, -41, -103, 41, 26, 29, -90, 15, 13, 95, -5, -108, 14, 50, 1, -60, -38, -29, 115, 70, -117, -77, 114, -15, -23, 103, 3, -47, 87, 14, -6, 82, 5,
-5, 62, -78, 69, 30, 101, -99, -53, 18, 32, 33, -4, -13, -32, -106, -13, -67, -61, 23, 15, 10, -51, -52, 20, -19, -59, 97, 42, 103, -7, 4, -70, -68,
69, -60, -14, -12, 5, 52, 37, 47, 5, -92, -52, -70, 117, -52, 98, 24, -55, 46, 79, 103, -60, -109, -16, -32, -74, 64, 26, -40, 72, 47, 60, 121, 12,
-81, 118, -6, -32, -37, 45, 45, -24, -49, 74, -91, -84, -112, -79, 114, 33, -18, 67, 36, -42, 23, -9, 121, -85, 40, 10, -50, 32, 38, -22, 61, -26, -70,
-40, 118, -80, -24, -102, 113, 17, -111, 101, -96, 73, -58, -86, -44, -67, -7, 2, -91, 15, -29, -26, -91, -118, -27, -22, -101, 83, 37, 44, 88, -102, 94, -111,
40, 49, 48, -115, 74, 58, -39, -22, 55, -90, -121, 120, 7, -40, -124, -69, 23, -18, 95, 7, -6, -30, -23, -64, -52, 108, -103, 30, 94, -1, -37, 40, -52,
0, 29, 17, 61, -99, -3, -5, -41, 57, -15, 10, -41, -53, -9, 16, -52, 34, 104, 93, -101, 66, -74, -3, 108, 99, -86, -37, -72, 110, 69, -97, 44, 5,
-88, -91, -106, -84, 121, -33, 46, 3, 21, 90, 16, 109, 30, 107, -4, -82, -69, 80, -32, -7, -67, 12, 85, -100, -44, 48, -80, 76, 49, -92, 120, -12, -104,
98, 64, -7, -18, 9, 121, 28, 80, 99, 108, -30, 104, 12, -76, -74, 54, 12, 76, 98, 90, 71, -50, -9, 21, 79, -85, -26, 99, -80, 76, -100, 41, -86,
41, 78, 16, -72, 89, -43, 28, -57, -20, 107, -12, -63, -90, 96, 103, -120, 57, -10, -119, -31, -116, -26, 104, -24, -104, -18, -93, 32, 90, -53, 78, -44, -42,
6, 22, -42, 75, 9, -35, 53, -28, 32, 83, 110, 103, 53, -52, -3, 24, -75, -65, 36, 98, -112, -47, 44, -54, -125, 89, 61, 15, 99, -59, -123, 115, 29,
-70, -119, 119, -53, 63, -42, 66, 76, 8, -48, -94, -20, -94, -33, 17, -15, -61, -55, -54, -69, 21, 56, -65, 50, 73, 4, -85, -16, -45, 13, 18, 0, 93,
-79, 109, -43, 42, -32, 105, -79, -66, -16, 91, -74, 54, -53, -35, 115, -93, -16, 87, 77, 80, 31, -57, 25, -104, -59, -44, 70, 41, 6, 15, -112, -103, -114,
-82, 111, 80, 26, 3, 8, -5, -49, -6, 46, 12, -90, -61, -100, -70, 66, 91, 66, -95, -8, -49, -101, -46, 99, 83, 55, -19, 23, 127, 118, 15, -14, -4,
-43, 17, -103, -94, 117, -40, 31, 97, -59, 21, 21, 61, 35, -27, -8, -27, 15, -12, -59, 102, -104, -25, 78, -87, 117, -4, -76, 127, 80, 72, 77, 32, 31,
-74, -18, 104, 111, 80, 52, 5, -76, -28, -23, -95, -79, 95, -10, -45, 87, -41, -19, -104, -20, 70, -102, -29, 125, -70, -93, 96, -26, 30, -1, 72, 53, 105,
-42, 48, 76, 52, 19, -11, -6, -107, 100, 101, -32, 87, -13, -41, 93, 35, 24, -120, 27, -24, -39, 69, 98, -110, 75, 106, -8, 103, -113, -124, -121, -94, 125,
};
const TfArray<2, int> tensor_dimension4 = { 2, { 20,33 } };
const TfArray<1, float> quant4_scale = { 1, { 0.002759384922683239, } };
const TfArray<1, int> quant4_zero = { 1, { 0 } };
const TfLiteAffineQuantization quant4 = { (TfLiteFloatArray*)&quant4_scale, (TfLiteIntArray*)&quant4_zero, 0 };
const ALIGN(8) int8_t tensor_data5[10*20] = {
-82, -9, 29, 16, 98, -76, -37, 17, -101, -114, -43, -71, 102, 91, -33, -2, -109, 12, -39, 10,
-77, 15, -62, 44, 21, 9, 81, -52, -53, -88, 17, -94, -30, -39, -96, -109, -51, 76, 54, -103,
-86, 89, 35, -53, 77, 5, 56, -45, 100, 97, -81, -47, 28, -106, 39, -33, -23, 122, -98, -34,
-88, -23, -80, -94, -11, 54, 78, 88, 103, -82, 96, 51, 5, -78, -29, 114, 31, 32, 28, -74,
18, 3, -69, -93, -123, 98, -50, -10, -73, 113, 3, -119, -106, 40, -23, 22, 17, -111, 110, 28,
78, 91, -99, 4, -74, -27, -1, -32, 115, -111, -127, 109, -96, 48, -62, 94, -107, -17, -107, 88,
91, -39, 11, 90, 73, -36, 12, 53, 48, 97, -60, 66, -121, -13, -6, -15, 44, -27, 41, -55,
-73, 112, -60, -107, -33, -15, -31, -90, 99, 77, 80, 112, -16, 1, -26, -47, -64, 26, -44, 48,
-74, 72, 3, 49, 118, -8, 63, -119, -23, -85, 45, 84, 101, 111, -20, 57, -98, 101, -6, 9,
-40, 43, 30, 97, -95, 74, 87, -60, 87, -42, -19, 39, -95, -33, -94, 25, 120, 118, -34, 105,
};
const TfArray<2, int> tensor_dimension5 = { 2, { 10,20 } };
const TfArray<1, float> quant5_scale = { 1, { 0.0036247593816369772, } };
const TfArray<1, int> quant5_zero = { 1, { 0 } };
const TfLiteAffineQuantization quant5 = { (TfLiteFloatArray*)&quant5_scale, (TfLiteIntArray*)&quant5_zero, 0 };
const ALIGN(8) int8_t tensor_data6[2*10] = {
-36, -127, -16, -118, 11, -83, 59, 80, 4, 51,
73, -117, -7, 109, 101, 66, 59, -3, 27, -6,
};
const TfArray<2, int> tensor_dimension6 = { 2, { 2,10 } };
const TfArray<1, float> quant6_scale = { 1, { 0.0054330769926309586, } };
const TfArray<1, int> quant6_zero = { 1, { 0 } };
const TfLiteAffineQuantization quant6 = { (TfLiteFloatArray*)&quant6_scale, (TfLiteIntArray*)&quant6_zero, 0 };
const TfArray<2, int> tensor_dimension7 = { 2, { 1,20 } };
const TfArray<1, float> quant7_scale = { 1, { 202.2373046875, } };
const TfArray<1, int> quant7_zero = { 1, { -128 } };
const TfLiteAffineQuantization quant7 = { (TfLiteFloatArray*)&quant7_scale, (TfLiteIntArray*)&quant7_zero, 0 };
const TfArray<2, int> tensor_dimension8 = { 2, { 1,10 } };
const TfArray<1, float> quant8_scale = { 1, { 239.962158203125, } };
const TfArray<1, int> quant8_zero = { 1, { -128 } };
const TfLiteAffineQuantization quant8 = { (TfLiteFloatArray*)&quant8_scale, (TfLiteIntArray*)&quant8_zero, 0 };
const TfArray<2, int> tensor_dimension9 = { 2, { 1,2 } };
const TfArray<1, float> quant9_scale = { 1, { 83.309806823730469, } };
const TfArray<1, int> quant9_zero = { 1, { -115 } };
const TfLiteAffineQuantization quant9 = { (TfLiteFloatArray*)&quant9_scale, (TfLiteIntArray*)&quant9_zero, 0 };
const TfArray<2, int> tensor_dimension10 = { 2, { 1,2 } };
const TfArray<1, float> quant10_scale = { 1, { 0.00390625, } };
const TfArray<1, int> quant10_zero = { 1, { -128 } };
const TfLiteAffineQuantization quant10 = { (TfLiteFloatArray*)&quant10_scale, (TfLiteIntArray*)&quant10_zero, 0 };
const TfLiteFullyConnectedParams opdata0 = { kTfLiteActRelu, kTfLiteFullyConnectedWeightsFormatDefault, false, false };
const TfArray<3, int> inputs0 = { 3, { 0,4,1 } };
const TfArray<1, int> outputs0 = { 1, { 7 } };
const TfLiteFullyConnectedParams opdata1 = { kTfLiteActRelu, kTfLiteFullyConnectedWeightsFormatDefault, false, false };
const TfArray<3, int> inputs1 = { 3, { 7,5,2 } };
const TfArray<1, int> outputs1 = { 1, { 8 } };
const TfLiteFullyConnectedParams opdata2 = { kTfLiteActNone, kTfLiteFullyConnectedWeightsFormatDefault, false, false };
const TfArray<3, int> inputs2 = { 3, { 8,6,3 } };
const TfArray<1, int> outputs2 = { 1, { 9 } };
const TfLiteSoftmaxParams opdata3 = { 1 };
const TfArray<1, int> inputs3 = { 1, { 9 } };
const TfArray<1, int> outputs3 = { 1, { 10 } };
const TensorInfo_t tensorData[] = {
{ kTfLiteArenaRw, kTfLiteInt8, tensor_arena + 0, (TfLiteIntArray*)&tensor_dimension0, 33, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant0))}, },
{ kTfLiteMmapRo, kTfLiteInt32, (void*)tensor_data1, (TfLiteIntArray*)&tensor_dimension1, 80, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant1))}, },
{ kTfLiteMmapRo, kTfLiteInt32, (void*)tensor_data2, (TfLiteIntArray*)&tensor_dimension2, 40, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant2))}, },
{ kTfLiteMmapRo, kTfLiteInt32, (void*)tensor_data3, (TfLiteIntArray*)&tensor_dimension3, 8, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant3))}, },
{ kTfLiteMmapRo, kTfLiteInt8, (void*)tensor_data4, (TfLiteIntArray*)&tensor_dimension4, 660, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant4))}, },
{ kTfLiteMmapRo, kTfLiteInt8, (void*)tensor_data5, (TfLiteIntArray*)&tensor_dimension5, 200, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant5))}, },
{ kTfLiteMmapRo, kTfLiteInt8, (void*)tensor_data6, (TfLiteIntArray*)&tensor_dimension6, 20, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant6))}, },
{ kTfLiteArenaRw, kTfLiteInt8, tensor_arena + 48, (TfLiteIntArray*)&tensor_dimension7, 20, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant7))}, },
{ kTfLiteArenaRw, kTfLiteInt8, tensor_arena + 0, (TfLiteIntArray*)&tensor_dimension8, 10, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant8))}, },
{ kTfLiteArenaRw, kTfLiteInt8, tensor_arena + 16, (TfLiteIntArray*)&tensor_dimension9, 2, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant9))}, },
{ kTfLiteArenaRw, kTfLiteInt8, tensor_arena + 0, (TfLiteIntArray*)&tensor_dimension10, 2, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant10))}, },
};const NodeInfo_t nodeData[] = {
{ (TfLiteIntArray*)&inputs0, (TfLiteIntArray*)&outputs0, const_cast<void*>(static_cast<const void*>(&opdata0)), OP_FULLY_CONNECTED, },
{ (TfLiteIntArray*)&inputs1, (TfLiteIntArray*)&outputs1, const_cast<void*>(static_cast<const void*>(&opdata1)), OP_FULLY_CONNECTED, },
{ (TfLiteIntArray*)&inputs2, (TfLiteIntArray*)&outputs2, const_cast<void*>(static_cast<const void*>(&opdata2)), OP_FULLY_CONNECTED, },
{ (TfLiteIntArray*)&inputs3, (TfLiteIntArray*)&outputs3, const_cast<void*>(static_cast<const void*>(&opdata3)), OP_SOFTMAX, },
};
static std::vector<void*> overflow_buffers;
static TfLiteStatus AllocatePersistentBuffer(struct TfLiteContext* ctx,
size_t bytes, void** ptr) {
if (current_location - bytes < tensor_boundary) {
// OK, this will look super weird, but.... we have CMSIS-NN buffers which
// we cannot calculate beforehand easily.
*ptr = malloc(bytes);
if (*ptr == NULL) {
printf("ERR: Failed to allocate persistent buffer of size %u\n", bytes);
return kTfLiteError;
}
overflow_buffers.push_back(*ptr);
return kTfLiteOk;
}
current_location -= bytes;
*ptr = current_location;
return kTfLiteOk;
}
typedef struct {
size_t bytes;
void *ptr;
} scratch_buffer_t;
static std::vector<scratch_buffer_t> scratch_buffers;
static TfLiteStatus RequestScratchBufferInArena(struct TfLiteContext* ctx, size_t bytes,
int* buffer_idx) {
scratch_buffer_t b;
b.bytes = bytes;
TfLiteStatus s = AllocatePersistentBuffer(ctx, b.bytes, &b.ptr);
if (s != kTfLiteOk) {
return s;
}
scratch_buffers.push_back(b);
*buffer_idx = scratch_buffers.size() - 1;
return kTfLiteOk;
}
static void* GetScratchBuffer(struct TfLiteContext* ctx, int buffer_idx) {
if (buffer_idx > static_cast<int>(scratch_buffers.size()) - 1) {
return NULL;
}
return scratch_buffers[buffer_idx].ptr;
}
} // namespace
TfLiteStatus trained_model_init( void*(*alloc_fnc)(size_t,size_t) ) {
tensor_arena = (uint8_t*) alloc_fnc(16, kTensorArenaSize);
current_location = tensor_arena + kTensorArenaSize;
tensor_boundary = tensor_arena;
ctx.AllocatePersistentBuffer = &AllocatePersistentBuffer;
ctx.RequestScratchBufferInArena = &RequestScratchBufferInArena;
ctx.GetScratchBuffer = &GetScratchBuffer;
ctx.tensors = tflTensors;
ctx.tensors_size = 11;
for(size_t i = 0; i < 11; ++i) {
tflTensors[i].type = tensorData[i].type;
tflTensors[i].is_variable = 0;
tflTensors[i].allocation_type = tensorData[i].allocation_type;
tflTensors[i].bytes = tensorData[i].bytes;
tflTensors[i].dims = tensorData[i].dims;
if(tflTensors[i].allocation_type == kTfLiteArenaRw){
uint8_t* start = (uint8_t*) ((uintptr_t)tensorData[i].data + (uintptr_t) tensor_arena);
uint8_t* end = start + tensorData[i].bytes;
tflTensors[i].data.data = start;
if (end > tensor_boundary) {
tensor_boundary = end;
}
}
else{
tflTensors[i].data.data = tensorData[i].data;
}
tflTensors[i].quantization = tensorData[i].quantization;
if (tflTensors[i].quantization.type == kTfLiteAffineQuantization) {
TfLiteAffineQuantization const* quant = ((TfLiteAffineQuantization const*)(tensorData[i].quantization.params));
tflTensors[i].params.scale = quant->scale->data[0];
tflTensors[i].params.zero_point = quant->zero_point->data[0];
}
}
registrations[OP_FULLY_CONNECTED] = *tflite::ops::micro::Register_FULLY_CONNECTED();
registrations[OP_SOFTMAX] = *tflite::ops::micro::Register_SOFTMAX();
for(size_t i = 0; i < 4; ++i) {
tflNodes[i].inputs = nodeData[i].inputs;
tflNodes[i].outputs = nodeData[i].outputs;
tflNodes[i].builtin_data = nodeData[i].builtin_data;
tflNodes[i].custom_initial_data = nullptr;
tflNodes[i].custom_initial_data_size = 0;
if (registrations[nodeData[i].used_op_index].init) {
tflNodes[i].user_data = registrations[nodeData[i].used_op_index].init(&ctx, (const char*)tflNodes[i].builtin_data, 0);
}
}
for(size_t i = 0; i < 4; ++i) {
if (registrations[nodeData[i].used_op_index].prepare) {
TfLiteStatus status = registrations[nodeData[i].used_op_index].prepare(&ctx, &tflNodes[i]);
if (status != kTfLiteOk) {
return status;
}
}
}
return kTfLiteOk;
}
static const int inTensorIndices[] = {
0,
};
TfLiteTensor* trained_model_input(int index) {
return &ctx.tensors[inTensorIndices[index]];
}
static const int outTensorIndices[] = {
10,
};
TfLiteTensor* trained_model_output(int index) {
return &ctx.tensors[outTensorIndices[index]];
}
TfLiteStatus trained_model_invoke() {
for(size_t i = 0; i < 4; ++i) {
TfLiteStatus status = registrations[nodeData[i].used_op_index].invoke(&ctx, &tflNodes[i]);
if (status != kTfLiteOk) {
return status;
}
}
return kTfLiteOk;
}
TfLiteStatus trained_model_reset( void (*free_fnc)(void* ptr) ) {
free_fnc(tensor_arena);
scratch_buffers.clear();
for (size_t ix = 0; ix < overflow_buffers.size(); ix++) {
free(overflow_buffers[ix]);
}
overflow_buffers.clear();
return kTfLiteOk;
}
| 55.52439 | 180 | 0.652152 |
2a5ad1457cc8348ebe8d3ce6d5a3492f80578b89 | 2,210 | cc | C++ | nucleus/io/vcf_roundtrip_test.cc | gaybro8777/nucleus | 3bd27ac076a6f3f93e49a27ed60661858e727dda | [
"BSD-3-Clause"
] | 721 | 2018-03-30T14:34:17.000Z | 2022-03-23T00:09:18.000Z | nucleus/io/vcf_roundtrip_test.cc | aktaseren/nucleus | 3cc9412be81ed86a99fd7eb086ee94afe852759b | [
"Apache-2.0"
] | 38 | 2018-03-31T09:02:23.000Z | 2022-03-23T21:16:41.000Z | nucleus/io/vcf_roundtrip_test.cc | aktaseren/nucleus | 3cc9412be81ed86a99fd7eb086ee94afe852759b | [
"Apache-2.0"
] | 123 | 2018-03-30T21:51:18.000Z | 2021-12-13T06:59:31.000Z | /*
* Copyright 2019 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <memory>
#include <vector>
#include <gmock/gmock-generated-matchers.h>
#include <gmock/gmock-matchers.h>
#include <gmock/gmock-more-matchers.h>
#include "tensorflow/core/platform/test.h"
#include "nucleus/io/vcf_reader.h"
#include "nucleus/io/vcf_writer.h"
#include "nucleus/platform/types.h"
#include "nucleus/protos/variants.pb.h"
#include "nucleus/testing/protocol-buffer-matchers.h"
#include "nucleus/testing/test_utils.h"
#include "nucleus/vendor/status_matchers.h"
namespace nucleus {
namespace {
using genomics::v1::Variant;
} // namespace
// Read from a vcf file and write to a bcf file. The bcf file should have the
// same contents as the vcf file.
TEST(VcfRoundtripTest, ReadVCFWriteBCF) {
string input_file = GetTestData("test_sites.vcf");
string output_file = MakeTempFile("output.bcf.gz");
auto reader = std::move(
VcfReader::FromFile(input_file, genomics::v1::VcfReaderOptions())
.ValueOrDie());
auto writer = std::move(VcfWriter::ToFile(output_file, reader->Header(),
genomics::v1::VcfWriterOptions())
.ValueOrDie());
std::vector<Variant> expected_variants = as_vector(reader->Iterate());
for (const auto& v : expected_variants) {
ASSERT_THAT(writer->Write(v), IsOK());
}
writer = nullptr;
auto output_reader = std::move(
VcfReader::FromFile(output_file, genomics::v1::VcfReaderOptions())
.ValueOrDie());
EXPECT_THAT(as_vector(output_reader->Iterate()),
testing::Pointwise(EqualsProto(), expected_variants));
}
} // namespace nucleus
| 34.53125 | 77 | 0.701357 |
2a5b1d43a6c5dbb0d6a6fa542e67d6192c1ef1f8 | 2,458 | cpp | C++ | clients/cpp-pistache-server/generated/model/StringParameterValue.cpp | PankTrue/swaggy-jenkins | aca35a7cca6e1fcc08bd399e05148942ac2f514b | [
"MIT"
] | 23 | 2017-08-01T12:25:26.000Z | 2022-01-25T03:44:11.000Z | clients/cpp-pistache-server/generated/model/StringParameterValue.cpp | PankTrue/swaggy-jenkins | aca35a7cca6e1fcc08bd399e05148942ac2f514b | [
"MIT"
] | 35 | 2017-06-14T03:28:15.000Z | 2022-02-14T10:25:54.000Z | clients/cpp-pistache-server/generated/model/StringParameterValue.cpp | PankTrue/swaggy-jenkins | aca35a7cca6e1fcc08bd399e05148942ac2f514b | [
"MIT"
] | 11 | 2017-08-31T19:00:20.000Z | 2021-12-19T12:04:12.000Z | /**
* Swaggy Jenkins
* Jenkins API clients generated from Swagger / Open API specification
*
* OpenAPI spec version: 1.1.1
* Contact: blah@cliffano.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "StringParameterValue.h"
namespace org {
namespace openapitools {
namespace server {
namespace model {
StringParameterValue::StringParameterValue()
{
m__class = "";
m__classIsSet = false;
m_Name = "";
m_NameIsSet = false;
m_Value = "";
m_ValueIsSet = false;
}
StringParameterValue::~StringParameterValue()
{
}
void StringParameterValue::validate()
{
// TODO: implement validation
}
nlohmann::json StringParameterValue::toJson() const
{
nlohmann::json val = nlohmann::json::object();
if(m__classIsSet)
{
val["_class"] = ModelBase::toJson(m__class);
}
if(m_NameIsSet)
{
val["name"] = ModelBase::toJson(m_Name);
}
if(m_ValueIsSet)
{
val["value"] = ModelBase::toJson(m_Value);
}
return val;
}
void StringParameterValue::fromJson(nlohmann::json& val)
{
if(val.find("_class") != val.end())
{
setClass(val.at("_class"));
}
if(val.find("name") != val.end())
{
setName(val.at("name"));
}
if(val.find("value") != val.end())
{
setValue(val.at("value"));
}
}
std::string StringParameterValue::getClass() const
{
return m__class;
}
void StringParameterValue::setClass(std::string const& value)
{
m__class = value;
m__classIsSet = true;
}
bool StringParameterValue::classIsSet() const
{
return m__classIsSet;
}
void StringParameterValue::unset_class()
{
m__classIsSet = false;
}
std::string StringParameterValue::getName() const
{
return m_Name;
}
void StringParameterValue::setName(std::string const& value)
{
m_Name = value;
m_NameIsSet = true;
}
bool StringParameterValue::nameIsSet() const
{
return m_NameIsSet;
}
void StringParameterValue::unsetName()
{
m_NameIsSet = false;
}
std::string StringParameterValue::getValue() const
{
return m_Value;
}
void StringParameterValue::setValue(std::string const& value)
{
m_Value = value;
m_ValueIsSet = true;
}
bool StringParameterValue::valueIsSet() const
{
return m_ValueIsSet;
}
void StringParameterValue::unsetValue()
{
m_ValueIsSet = false;
}
}
}
}
}
| 17.941606 | 91 | 0.663548 |
2a5fa2c4b14955a5b98a9a263ce85d4c4965dfb4 | 412 | cpp | C++ | PTA/GPLT/L1-C/010.cpp | cnsteven/online-judge | 60ee841a97e2bc0dc9c7b23fe5daa186898ab8b7 | [
"MIT"
] | 1 | 2019-05-04T10:28:32.000Z | 2019-05-04T10:28:32.000Z | PTA/GPLT/L1-C/010.cpp | cnsteven/online-judge | 60ee841a97e2bc0dc9c7b23fe5daa186898ab8b7 | [
"MIT"
] | null | null | null | PTA/GPLT/L1-C/010.cpp | cnsteven/online-judge | 60ee841a97e2bc0dc9c7b23fe5daa186898ab8b7 | [
"MIT"
] | 3 | 2020-12-31T04:36:38.000Z | 2021-07-25T07:39:31.000Z | #include <iostream>
using namespace std;
int main() {
int a[3], i, j, t;
for (i = 0; i < 3; i++) {
cin >> a[i];
}
for (i = 0; i < 3; i++) {
for (j = i + 1; j < 3; j++) {
if (a[i] > a[j]) {
t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
cout << a[0] << "->" << a[1] << "->" << a[2];
return 0;
}
| 18.727273 | 49 | 0.26699 |
2a664c5cf5e630d6683e8571819067dd25e5e2cf | 1,044 | cpp | C++ | src/utils/chrono.cpp | Ymagis/EclairLooks | c04fb1af1160305fb1dbffb2ea92cc478cd70b31 | [
"BSD-3-Clause"
] | 9 | 2019-07-03T13:11:33.000Z | 2021-10-06T13:55:31.000Z | src/utils/chrono.cpp | Ymagis/EclairLooks | c04fb1af1160305fb1dbffb2ea92cc478cd70b31 | [
"BSD-3-Clause"
] | 1 | 2019-07-09T09:04:59.000Z | 2019-08-06T13:23:47.000Z | src/utils/chrono.cpp | Ymagis/EclairLooks | c04fb1af1160305fb1dbffb2ea92cc478cd70b31 | [
"BSD-3-Clause"
] | 4 | 2019-07-02T15:03:43.000Z | 2019-09-28T14:33:03.000Z | #include "chrono.h"
using namespace std::chrono;
Chrono::Chrono()
: _paused(false)
{
}
Chrono::~Chrono()
{
}
void Chrono::start()
{
// reset chrono if already running
_startTime = ClockT::now();
_current_duration = DurationT::zero();
}
void Chrono::pause()
{
if(!_paused)
{
_current_duration = ClockT::now() - _startTime;
_paused = true;
}
}
void Chrono::resume()
{
if(_paused == true)
{
_startTime = ClockT::now();
_paused = false;
}
}
float Chrono::ellapsed(DurationType dt)
{
if(!_paused)
{
_current_duration += ClockT::now() - _startTime;
_startTime = ClockT::now();
}
float ellapsed = 0;
switch(dt)
{
case MINUTES :
ellapsed = duration_cast<minutes>(_current_duration).count();
break;
case SECONDS :
ellapsed = duration_cast<seconds>(_current_duration).count();
break;
case MILLISECONDS :
ellapsed = duration_cast<milliseconds>(_current_duration).count();
break;
case NANOSECONDS :
ellapsed = duration_cast<nanoseconds>(_current_duration).count();
}
return ellapsed;
} | 15.58209 | 69 | 0.675287 |
2a67473bd414db7b92dafbc301b5b719af1fa3eb | 1,372 | cpp | C++ | tps_base_link/src/tps_base_link.cpp | WRS-TNK/wrs_tnk_robot | 9cfaa5b1fab2c5a707ee434effe5a838b62424b7 | [
"MIT"
] | 1 | 2019-08-16T07:10:24.000Z | 2019-08-16T07:10:24.000Z | tps_base_link/src/tps_base_link.cpp | WRS-TNK/wrs_tnk_robot | 9cfaa5b1fab2c5a707ee434effe5a838b62424b7 | [
"MIT"
] | null | null | null | tps_base_link/src/tps_base_link.cpp | WRS-TNK/wrs_tnk_robot | 9cfaa5b1fab2c5a707ee434effe5a838b62424b7 | [
"MIT"
] | null | null | null | #include <ros/ros.h>
#include <tf2/LinearMath/Vector3.h>
#include <tf2/LinearMath/Quaternion.h>
#include <tf2/LinearMath/Matrix3x3.h>
#include <tf2_ros/transform_listener.h>
#include <geometry_msgs/TransformStamped.h>
#include <tf2_ros/transform_broadcaster.h>
int main(int argc, char** argv)
{
ros::init(argc, argv, "tps_base_link");
ros::NodeHandle n;
tf2_ros::Buffer tfBuffer;
tf2_ros::TransformListener tfListener(tfBuffer);
tf2_ros::TransformBroadcaster tb;
geometry_msgs::TransformStamped ts;
ros::Rate r(25.0);
while(ros::ok()){
geometry_msgs::TransformStamped transform;
try{
transform = tfBuffer.lookupTransform("map", "base_link", ros::Time(0));
}
catch (tf2::TransformException &ex){
ROS_ERROR("%s", ex.what());
ros::Duration(1.0).sleep();
continue;
}
ts.header.stamp = transform.header.stamp;
ts.header.frame_id = "map";
ts.child_frame_id = "tps_base_link";
ts.transform.translation.x = transform.transform.translation.x;
ts.transform.translation.y = transform.transform.translation.y;
ts.transform.translation.z = 0;
tf2::Quaternion rotation;
rotation.setRPY(0, 0, 0);
ts.transform.rotation.x = rotation.x();
ts.transform.rotation.y = rotation.y();
ts.transform.rotation.z = rotation.z();
ts.transform.rotation.w = rotation.w();
tb.sendTransform(ts);
r.sleep();
}
return 0;
}
| 24.945455 | 74 | 0.710641 |
2a6a133a0da6177d07c15430399e586a273213c1 | 5,355 | cpp | C++ | src/Q3D/Core/QMaterial.cpp | 565353780/opengl-automaskobj | bae7c35a0aece5a09ec67b02241aff58932c6daf | [
"MIT"
] | null | null | null | src/Q3D/Core/QMaterial.cpp | 565353780/opengl-automaskobj | bae7c35a0aece5a09ec67b02241aff58932c6daf | [
"MIT"
] | null | null | null | src/Q3D/Core/QMaterial.cpp | 565353780/opengl-automaskobj | bae7c35a0aece5a09ec67b02241aff58932c6daf | [
"MIT"
] | null | null | null | #include "QMaterial.h"
#include <qgl.h>
#include <cmath>
namespace GCL
{
QMaterial::QMaterial(QObject *parent) : QOpenGLShaderProgram(parent)
{
this->initializeOpenGLFunctions();
}
QMaterial::~QMaterial()
{
this->clearTextures();
}
void QMaterial::clearTextures()
{
foreach (auto texture, local_textures_)
{
if(texture->isCreated())
{
texture->destroy();
}
}
local_textures_.clear();
for(auto tid : local_texture_ids_)
{
if(glIsTexture(tid))
{
glDeleteTextures(1, &tid);
}
}
local_texture_ids_.clear();
}
void QMaterial::linkShaders(const QString &vert_filename, const QString &frag_filename)
{
this->addShaderFromSourceFile(QOpenGLShader::Vertex, vert_filename);
this->addShaderFromSourceFile(QOpenGLShader::Fragment, frag_filename);
this->link();
}
void QMaterial::addUniformValue(const char *name, GLfloat f)
{
UniformType ut;
ut.f_val_ = f;
ut.type_ = UniformType::Float;
uniform_map_[name] = ut;
}
void QMaterial::addUniformValue(const char *name, GLint val)
{
UniformType ut;
ut.i_val_ = val;
ut.type_ = UniformType::Int;
uniform_map_[name] = ut;
}
void QMaterial::addUniformTexture(const char *name, GLuint tex_id, bool add_to_local)
{
UniformType ut;
ut.tex_id_ = tex_id;
ut.type_ = UniformType::Texture;
uniform_map_[name] = ut;
if(add_to_local)
{
local_texture_ids_.push_back(tex_id);
}
}
GLuint QMaterial::addUniformTextureImage(const char *name, const QImage &image, QOpenGLTexture::Filter minfilter, QOpenGLTexture::Filter magfilter, QOpenGLTexture::WrapMode warpmode)
{
std::shared_ptr< QOpenGLTexture > texture(new QOpenGLTexture(image));
texture->create();
texture->bind();
texture->setMinificationFilter(minfilter);
texture->setMagnificationFilter(magfilter);
texture->setWrapMode(warpmode);
addUniformTexture(name, texture->textureId());
local_textures_.push_back(texture);
return texture->textureId();
}
QVector4D QMaterial::packInt(uint val)
{
QVector4D v;
v.setX(val % 256);
val /= 256;
v.setY(val % 256);
val /= 256;
v.setZ(val % 256);
val /= 256;
v.setW(255 - val % 256);
return v / 255.0;
}
uint QMaterial::unpackInt(QVector4D v)
{
uint sum = 0;
v *= 255.0;
sum += int(v.x());
sum += int(v.y()) * 256;
sum += int(v.z()) * 256 * 256;
sum += (255 - int(v.w())) * 256 * 256 * 256;
return sum;
}
QVector4D QMaterial::pack(double val)
{
if(val >= 1.0) val = 0.999999;
if(val < 0) val = 0;
QVector4D bit_shift(256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0);
QVector4D bit_mask(0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);
QVector4D res = (val * bit_shift);
for(int i = 0; i < 4; i++)
{
res[i] = res[i] - floor(res[i]);
}
res -= QVector4D(res.x(), res.x(), res.y(), res.z()) * bit_mask;
return QVector4D(res.w(), res.z(), res.y(), res.x());
}
double QMaterial::unpack(QVector4D v)
{
QVector4D bit_shift(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);
double depth = QVector4D::dotProduct(QVector4D(v.w(), v.z(), v.y(), v.x()), bit_shift);
return depth;
}
void QMaterial::setUniforms(int &active_texture_count)
{
for(auto iter = uniform_map_.cbegin(); iter != uniform_map_.cend(); iter++)
{
const UniformType& ut = iter.value();
if(ut.type_ == UniformType::Float)
{
this->setUniformValue(iter.key().toLocal8Bit().data(), ut.f_val_);
}
else if(ut.type_ == UniformType::Int)
{
this->setUniformValue(iter.key().toLocal8Bit().data(), ut.i_val_);
}
else if(ut.type_ == UniformType::Texture)
{
glActiveTexture(GL_TEXTURE0 + active_texture_count);
glBindTexture(GL_TEXTURE_2D, ut.tex_id_);
this->setUniformValue(iter.key().toLocal8Bit().data(), active_texture_count);
active_texture_count++;
}
else if(ut.type_ == UniformType::Vec2)
{
QVector2D v;
v[0] = ut.v_val_[0];
v[1] = ut.v_val_[1];
this->setUniformValue(iter.key().toLocal8Bit().data(), v);
}
else if(ut.type_ == UniformType::Vec3)
{
QVector3D v;
v[0] = ut.v_val_[0];
v[1] = ut.v_val_[1];
v[2] = ut.v_val_[2];
this->setUniformValue(iter.key().toLocal8Bit().data(), v);
}
else if(ut.type_ == UniformType::Vec4)
{
QVector4D v;
v = ut.v_val_;
this->setUniformValue(iter.key().toLocal8Bit().data(), v);
}
}
}
void QMaterial::addUniformValue(const char *name, QVector2D v)
{
UniformType ut;
ut.v_val_[0] = v[0];
ut.v_val_[1] = v[1];
ut.type_ = UniformType::Vec2;
uniform_map_[name] = ut;
}
void QMaterial::addUniformValue(const char *name, QVector3D v)
{
UniformType ut;
ut.v_val_[0] = v[0];
ut.v_val_[1] = v[1];
ut.v_val_[2] = v[2];
ut.type_ = UniformType::Vec3;
uniform_map_[name] = ut;
}
void QMaterial::addUniformValue(const char *name, QVector4D v)
{
UniformType ut;
ut.v_val_ = v;
ut.type_ = UniformType::Vec4;
uniform_map_[name] = ut;
}
}
| 25.140845 | 182 | 0.596078 |
2a716f151aa21b1f2c44232d9976c37867ed224e | 981 | cpp | C++ | USACO/2014/feb/hopscotch_bronze.cpp | nalinbhardwaj/olympiad | 6b640d8cef2fa16fb4e9776f8416575519357edf | [
"MIT"
] | 1 | 2018-12-14T07:51:26.000Z | 2018-12-14T07:51:26.000Z | USACO/2014/feb/hopscotch_bronze.cpp | nalinbhardwaj/olympiad | 6b640d8cef2fa16fb4e9776f8416575519357edf | [
"MIT"
] | null | null | null | USACO/2014/feb/hopscotch_bronze.cpp | nalinbhardwaj/olympiad | 6b640d8cef2fa16fb4e9776f8416575519357edf | [
"MIT"
] | 1 | 2019-06-23T10:34:19.000Z | 2019-06-23T10:34:19.000Z | /*
PROG: COW
LANG: C++
ID: nibnalin
*/
//USACO February Contest
#include <fstream>
#include <vector>
#include <climits>
using namespace std;
vector<vector<int> > grid;
vector< vector<long> > memtable;
int ans(long x, long y) {
if(memtable[x][y] == INT_MIN)
{
long paths = 0;
for(long i = (x-1);i >= 0;i--)
{
for(long j = (y-1);j >= 0;j--)
{
if(grid[x][y] != grid[i][j])
{
paths += ans(i, j);
}
}
}
memtable[x][y] = paths;
return paths;
}
else
return memtable[x][y];
}
int main(void)
{
ifstream fin ("hopscotch.in");
ofstream fout ("hopscotch.out");
long r, c;
fin >> r >> c;
grid.clear();
grid.resize(r, vector<int>(c));
memtable.clear();
memtable.resize(r, vector<long>(c, INT_MIN));
for(int i = 0;i < r;i++)
{
string tmp;
fin >> tmp;
for(int j = 0;j < c;j++)
{
if(tmp[j] == 'R')
grid[i][j] = 1;
else
grid[i][j] = 0;
}
}
memtable[0][0] = 1;
fout << ans(r-1, c-1) << endl; //Recurse, memoize
} | 16.081967 | 50 | 0.540265 |
2a726400bd33639500ddc9632ca84fdbc3f59744 | 1,570 | cpp | C++ | src/generator.cpp | demize/mergesort_parallel | 8b3c614ac3a60752e8c74bb4281fed04ec49c0e6 | [
"MIT"
] | null | null | null | src/generator.cpp | demize/mergesort_parallel | 8b3c614ac3a60752e8c74bb4281fed04ec49c0e6 | [
"MIT"
] | null | null | null | src/generator.cpp | demize/mergesort_parallel | 8b3c614ac3a60752e8c74bb4281fed04ec49c0e6 | [
"MIT"
] | null | null | null | /* generator.cpp - generates a list of random numbers
* Julian Heisz
* Algorithms and Data Structures Final Project
* Winter 2015
*/
#pragma comment(lib, "advapi32.lib")
#include <iostream>
#include <windows.h>
#include <Wincrypt.h>
using namespace std;
int main(int argc, char** argv)
{
if(argc != 4)
{
cout << "Usage: " << argv[0] << " [size of list] [max number] [output file]" << endl;
return 1;
}
int size = atoi(argv[1]);
int mod = atoi(argv[2]);
if(size <= 0 || mod <= 0)
{
cout << "Usage: " << argv[0] << " [size of list] [max number] [output file]" << endl;
return 1;
}
FILE *out;
HCRYPTPROV phprov; // Necessary for random number generation
// Acquire the cryptographic context
if(!CryptAcquireContext(&phprov, NULL, NULL, PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
{
cout << "Error acquiring cyptographic context!" << endl;
return 2;
}
const DWORD length = sizeof(unsigned int);
BYTE buf[length] = {};
out = fopen(argv[3], "a");
if(out == NULL)
{
cout << "Error opening output file" << endl;
return 4;
}
for(int i = 0; i < size; i++)
{
// Generate a byte array the same length as an int
if(!CryptGenRandom(phprov, length, buf))
{
cout << "Error generating random number!" << endl;
return 3;
}
// Cast the byte array to an int and write it to the file
fprintf(out, "%u\n", ((*reinterpret_cast<unsigned int *>(buf)) % mod) + 1);
}
// Cleanup
fclose(out);
CryptReleaseContext(phprov, 0);
}
| 22.428571 | 89 | 0.601911 |
2a7337f9cdbf75041e5ccc49cc0a2c08423d85b3 | 21,980 | cpp | C++ | src/prod/src/systemservices/ServiceRoutingAgent.cpp | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/src/systemservices/ServiceRoutingAgent.cpp | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/src/systemservices/ServiceRoutingAgent.cpp | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 300 | 2018-03-14T21:57:17.000Z | 2019-05-06T20:07:00.000Z | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace std;
using namespace Common;
using namespace Federation;
using namespace Hosting2;
using namespace Naming;
using namespace Transport;
using namespace ServiceModel;
using namespace SystemServices;
// *** Private ServiceRoutingAgent::Impl
StringLiteral const TraceComponent("ServiceRoutingAgent");
class ServiceRoutingAgent::Impl
: public RootedObject
, private NodeTraceComponent<Common::TraceTaskCodes::SystemServices>
{
public:
Impl(
__in IpcServer & ipcServer,
__in FederationSubsystem & federation,
__in IHostingSubsystem & hosting,
__in IGateway & naming,
ComponentRoot const & root)
: RootedObject(root)
, NodeTraceComponent(federation.Instance)
, ipcServer_(ipcServer)
, federation_(federation)
, hosting_(hosting)
, naming_(naming)
{
REGISTER_MESSAGE_HEADER(SystemServiceFilterHeader);
WriteInfo(TraceComponent, "{0} ctor", this->TraceId);
}
virtual ~Impl()
{
WriteInfo(TraceComponent, "{0} ~dtor", this->TraceId);
}
ErrorCode Open();
ErrorCode Close();
void Abort();
private:
class RequestAsyncOperationBase
: public TimedAsyncOperation
, public NodeActivityTraceComponent<TraceTaskCodes::SystemServices>
{
public:
RequestAsyncOperationBase(
Impl & owner,
MessageUPtr && message,
ErrorCodeValue::Enum error,
TimeSpan const timeout,
AsyncCallback const & callback,
AsyncOperationSPtr const & root)
: TimedAsyncOperation(timeout, callback, root)
, NodeActivityTraceComponent(owner.NodeInstance, FabricActivityHeader::FromMessage(*message).ActivityId)
, owner_(owner)
, request_(move(message))
, error_(error)
, reply_()
{
}
virtual ~RequestAsyncOperationBase() { }
MessageUPtr && TakeReply() { return move(reply_); }
protected:
virtual void OnStart(AsyncOperationSPtr const & thisSPtr) { this->TryComplete(thisSPtr, error_); }
void SetReply(MessageUPtr && reply) { reply_.swap(reply); }
Impl & owner_;
MessageUPtr request_;
ErrorCodeValue::Enum error_;
private:
MessageUPtr reply_;
};
class ServiceToNodeAsyncOperation : public RequestAsyncOperationBase
{
public:
ServiceToNodeAsyncOperation(
Impl & owner,
MessageUPtr && message,
IpcReceiverContextUPtr && receiverContext,
TimeSpan const timeout,
AsyncCallback const & callback,
AsyncOperationSPtr const & root)
: RequestAsyncOperationBase(
owner,
move(message),
ErrorCodeValue::Success,
timeout,
callback,
root)
, receiverContext_(move(receiverContext))
{
}
ServiceToNodeAsyncOperation(
Impl & owner,
ErrorCodeValue::Enum error,
IpcReceiverContextUPtr && receiverContext,
TimeSpan const timeout,
AsyncCallback const & callback,
AsyncOperationSPtr const & root)
: RequestAsyncOperationBase(
owner,
MessageUPtr(),
error,
timeout,
callback,
root)
, receiverContext_(move(receiverContext))
{
}
virtual ~ServiceToNodeAsyncOperation() { }
__declspec (property(get=get_IpcReceiverContext)) IpcReceiverContext const & ReceiverContext;
IpcReceiverContext const & get_IpcReceiverContext() const { return *receiverContext_; }
protected:
virtual void OnStart(AsyncOperationSPtr const &);
private:
void OnNodeProcessingComplete(AsyncOperationSPtr const &, bool expectedCompletedSynchronously);
IpcReceiverContextUPtr receiverContext_;
};
class NodeToServiceAsyncOperation : public RequestAsyncOperationBase
{
public:
NodeToServiceAsyncOperation(
Impl & owner,
MessageUPtr && message,
RequestReceiverContextUPtr && receiverContext,
TimeSpan const timeout,
AsyncCallback const & callback,
AsyncOperationSPtr const & root)
: RequestAsyncOperationBase(
owner,
move(message),
ErrorCodeValue::Success,
timeout,
callback,
root)
, receiverContext_(move(receiverContext))
{
}
NodeToServiceAsyncOperation(
Impl & owner,
ErrorCodeValue::Enum error,
RequestReceiverContextUPtr && receiverContext,
TimeSpan const timeout,
AsyncCallback const & callback,
AsyncOperationSPtr const & root)
: RequestAsyncOperationBase(
owner,
MessageUPtr(),
error,
timeout,
callback,
root)
, receiverContext_(move(receiverContext))
{
}
virtual ~NodeToServiceAsyncOperation() { }
__declspec (property(get=get_RequestReceiverContext)) RequestReceiverContext & ReceiverContext;
RequestReceiverContext & get_RequestReceiverContext() { return *receiverContext_; }
protected:
virtual void OnStart(AsyncOperationSPtr const &);
private:
ErrorCode GetHostId(ServiceTypeIdentifier const &, __out wstring & clientId);
void OnForwardToServiceComplete(AsyncOperationSPtr const &, bool expectedCompletedSynchronously);
RequestReceiverContextUPtr receiverContext_;
};
void Cleanup();
bool IsValidRequest(MessageUPtr const &);
void ProcessIpcRequest(MessageUPtr &&, IpcReceiverContextUPtr &&);
void OnIpcRequestComplete(AsyncOperationSPtr const &, bool expectedCompletedSynchronously);
void SendIpcReply(MessageUPtr &&, IpcReceiverContext const &);
void OnIpcFailure(ErrorCode const &, IpcReceiverContext const &, ActivityId const & activityId);
void ProcessFederationRequest(MessageUPtr &&, RequestReceiverContextUPtr &&);
void OnFederationRequestComplete(AsyncOperationSPtr const &, bool expectedCompletedSynchronously);
void SendFederationReply(MessageUPtr &&, RequestReceiverContext &);
void OnFederationFailure(ErrorCode const &, RequestReceiverContext &);
AsyncOperationSPtr BeginRouteGatewayMessage(
MessageUPtr & message,
TimeSpan,
AsyncCallback const &,
AsyncOperationSPtr const & );
ErrorCode EndRouteGatewayMessage(
AsyncOperationSPtr const &,
_Out_ Transport::MessageUPtr & );
IpcServer & ipcServer_;
FederationSubsystem & federation_;
IHostingSubsystem & hosting_;
IGateway & naming_;
}; // end class Impl
ServiceRoutingAgent::~ServiceRoutingAgent()
{
}
ErrorCode ServiceRoutingAgent::Impl::Open()
{
WriteInfo(
TraceComponent,
"{0} registering federation",
this->TraceId);
ComponentRootSPtr root = this->Root.CreateComponentRoot();
ipcServer_.RegisterMessageHandler(
Actor::ServiceRoutingAgent,
[this, root] (MessageUPtr & message, IpcReceiverContextUPtr & receiverContext)
{
this->ProcessIpcRequest(move(message), move(receiverContext));
},
false);
federation_.RegisterMessageHandler(
Actor::ServiceRoutingAgent,
[] (MessageUPtr &, OneWayReceiverContextUPtr &)
{
Assert::CodingError("ServiceRoutingAgent does not support oneway messages");
},
[this, root] (MessageUPtr & message, RequestReceiverContextUPtr & receiverContext)
{
this->ProcessFederationRequest(move(message), move(receiverContext));
},
false);
naming_.RegisterGatewayMessageHandler(
Actor::ServiceRoutingAgent,
[this, root] (MessageUPtr &message, TimeSpan timeout, AsyncCallback const& callback, AsyncOperationSPtr const& parent)
{
return BeginRouteGatewayMessage(message, timeout, callback, parent);
},
[this, root](AsyncOperationSPtr const& operation, _Out_ MessageUPtr & reply)
{
return EndRouteGatewayMessage(operation, reply);
});
return ErrorCodeValue::Success;
}
ErrorCode ServiceRoutingAgent::Impl::Close()
{
this->Cleanup();
return ErrorCodeValue::Success;
}
void ServiceRoutingAgent::Impl::Abort()
{
this->Cleanup();
}
void ServiceRoutingAgent::Impl::Cleanup()
{
federation_.UnRegisterMessageHandler(Actor::ServiceRoutingAgent);
ipcServer_.UnregisterMessageHandler(Actor::ServiceRoutingAgent);
naming_.UnRegisterGatewayMessageHandler(Actor::ServiceRoutingAgent);
}
bool ServiceRoutingAgent::Impl::IsValidRequest(MessageUPtr const & message)
{
if (!message)
{
WriteInfo(TraceComponent, "{0} null request", this->TraceId);
return false;
}
if (message->Actor != Actor::ServiceRoutingAgent)
{
WriteInfo(TraceComponent, "{0} invalid actor: {1}", this->TraceId, message->Actor);
return false;
}
TimeoutHeader timeoutHeader;
if (!message->Headers.TryReadFirst(timeoutHeader))
{
WriteInfo(TraceComponent, "{0} missing timeout header: {1}", this->TraceId, message->Action);
return false;
}
return true;
}
//
// *** IPC
//
void ServiceRoutingAgent::Impl::ProcessIpcRequest(MessageUPtr && message, IpcReceiverContextUPtr && receiverContext)
{
if (!IsValidRequest(message))
{
this->OnIpcFailure(ErrorCodeValue::InvalidMessage, *receiverContext, ActivityId(Guid::Empty()));
return;
}
auto timeoutHeader = TimeoutHeader::FromMessage(*message);
if (message->Action == ServiceRoutingAgentMessage::ServiceRouteRequestAction)
{
auto operation = AsyncOperation::CreateAndStart<ServiceToNodeAsyncOperation>(
*this,
move(message),
move(receiverContext),
timeoutHeader.Timeout,
[this](AsyncOperationSPtr const & operation) { this->OnIpcRequestComplete(operation, false); },
this->Root.CreateAsyncOperationRoot());
this->OnIpcRequestComplete(operation, true);
}
else
{
WriteInfo(TraceComponent, "{0} invalid action: {1}", this->TraceId, message->Action);
auto operation = AsyncOperation::CreateAndStart<ServiceToNodeAsyncOperation>(
*this,
ErrorCodeValue::InvalidMessage,
move(receiverContext),
timeoutHeader.Timeout,
[this](AsyncOperationSPtr const & operation) { this->OnIpcRequestComplete(operation, false); },
this->Root.CreateAsyncOperationRoot());
this->OnIpcRequestComplete(operation, true);
}
}
void ServiceRoutingAgent::Impl::OnIpcRequestComplete(AsyncOperationSPtr const & operation, bool expectedCompletedSynchronously)
{
if (operation->CompletedSynchronously != expectedCompletedSynchronously)
{
return;
}
auto casted = AsyncOperation::End<ServiceToNodeAsyncOperation>(operation);
if (casted->Error.IsSuccess())
{
MessageUPtr reply = casted->TakeReply();
// There used to be an IpcServer/IpcClient bug that miscalculates the message header signature
// when there are deleted headers. Preserve the Compact() here anyway as good practice.
//
reply->Headers.Compact();
this->SendIpcReply(move(reply), casted->ReceiverContext);
}
else
{
this->OnIpcFailure(casted->Error, casted->ReceiverContext, casted->ActivityId);
}
}
void ServiceRoutingAgent::Impl::SendIpcReply(MessageUPtr && reply, IpcReceiverContext const & receiverContext)
{
receiverContext.Reply(move(reply));
}
void ServiceRoutingAgent::Impl::OnIpcFailure(ErrorCode const & error, IpcReceiverContext const & receiverContext, ActivityId const & activityId)
{
auto reply = ServiceRoutingAgentMessage::CreateIpcFailureMessage(IpcFailureBody(error.ReadValue()), activityId);
this->SendIpcReply(move(reply), receiverContext);
}
//
// *** Federation
//
void ServiceRoutingAgent::Impl::ProcessFederationRequest(MessageUPtr && message, RequestReceiverContextUPtr && receiverContext)
{
if (!IsValidRequest(message))
{
this->OnFederationFailure(ErrorCodeValue::InvalidMessage, *receiverContext);
return;
}
auto timeoutHeader = TimeoutHeader::FromMessage(*message);
if (message->Action == ServiceRoutingAgentMessage::ServiceRouteRequestAction)
{
auto operation = AsyncOperation::CreateAndStart<NodeToServiceAsyncOperation>(
*this,
move(message),
move(receiverContext),
timeoutHeader.Timeout,
[this](AsyncOperationSPtr const & operation) { this->OnFederationRequestComplete(operation, false); },
this->Root.CreateAsyncOperationRoot());
this->OnFederationRequestComplete(operation, true);
}
else
{
WriteInfo(TraceComponent, "{0} invalid action: {1}", this->TraceId, message->Action);
auto operation = AsyncOperation::CreateAndStart<NodeToServiceAsyncOperation>(
*this,
ErrorCodeValue::InvalidMessage,
move(receiverContext),
timeoutHeader.Timeout,
[this](AsyncOperationSPtr const & operation) { this->OnFederationRequestComplete(operation, false); },
this->Root.CreateAsyncOperationRoot());
this->OnFederationRequestComplete(operation, true);
}
}
void ServiceRoutingAgent::Impl::OnFederationRequestComplete(AsyncOperationSPtr const & operation, bool expectedCompletedSynchronously)
{
if (operation->CompletedSynchronously != expectedCompletedSynchronously)
{
return;
}
auto casted = AsyncOperation::End<NodeToServiceAsyncOperation>(operation);
if (casted->Error.IsSuccess())
{
this->SendFederationReply(casted->TakeReply(), casted->ReceiverContext);
}
else
{
this->OnFederationFailure(casted->Error, casted->ReceiverContext);
}
}
void ServiceRoutingAgent::Impl::SendFederationReply(MessageUPtr && reply, RequestReceiverContext & receiverContext)
{
receiverContext.Reply(move(reply));
}
void ServiceRoutingAgent::Impl::OnFederationFailure(ErrorCode const & error, RequestReceiverContext & receiverContext)
{
receiverContext.Reject(error);
}
// ** Gateway
AsyncOperationSPtr ServiceRoutingAgent::Impl::BeginRouteGatewayMessage(
MessageUPtr & message,
TimeSpan timeout,
AsyncCallback const & callback,
AsyncOperationSPtr const & parent)
{
AsyncOperationSPtr operation;
if (message->Action == ServiceRoutingAgentMessage::ServiceRouteRequestAction)
{
operation = AsyncOperation::CreateAndStart<NodeToServiceAsyncOperation>(
*this,
move(message),
nullptr, // RequestReceiverContextUPtr
timeout,
callback,
parent);
}
else
{
WriteInfo(TraceComponent, "{0} invalid action in Gateway routing message: {1}", this->TraceId, message->Action);
operation = AsyncOperation::CreateAndStart<NodeToServiceAsyncOperation>(
*this,
ErrorCodeValue::InvalidMessage,
nullptr, // RequestReceiverContextUPtr
timeout,
callback,
parent);
}
return operation;
}
ErrorCode ServiceRoutingAgent::Impl::EndRouteGatewayMessage(
AsyncOperationSPtr const& operation,
MessageUPtr &reply)
{
auto casted = AsyncOperation::End<NodeToServiceAsyncOperation>(operation);
if (casted->Error.IsSuccess())
{
reply = casted->TakeReply();
}
return casted->Error;
}
// *** ServiceToNodeAsyncOperation
void ServiceRoutingAgent::Impl::ServiceToNodeAsyncOperation::OnStart(AsyncOperationSPtr const & thisSPtr)
{
if (error_ != ErrorCodeValue::Success)
{
RequestAsyncOperationBase::OnStart(thisSPtr);
return;
}
ErrorCode error = ServiceRoutingAgentMessage::UnwrapFromIpc(*request_);
if (error.IsSuccess())
{
WriteNoise(
TraceComponent,
"{0} forwarding request {1}:{2} to Naming",
this->TraceId,
request_->Actor,
request_->Action);
auto operation = owner_.naming_.BeginProcessRequest(
request_->Clone(),
this->RemainingTime,
[this](AsyncOperationSPtr const & operation) { this->OnNodeProcessingComplete(operation, false); },
thisSPtr);
this->OnNodeProcessingComplete(operation, true);
}
else
{
this->TryComplete(thisSPtr, error);
}
}
void ServiceRoutingAgent::Impl::ServiceToNodeAsyncOperation::OnNodeProcessingComplete(
AsyncOperationSPtr const & operation,
bool expectedCompletedSynchronously)
{
if (operation->CompletedSynchronously != expectedCompletedSynchronously) { return; }
MessageUPtr reply;
ErrorCode error = owner_.naming_.EndProcessRequest(operation, reply);
if (error.IsSuccess())
{
this->SetReply(move(reply));
}
this->TryComplete(operation->Parent, error);
}
// *** NodeToServiceAsyncOperation
void ServiceRoutingAgent::Impl::NodeToServiceAsyncOperation::OnStart(AsyncOperationSPtr const & thisSPtr)
{
if (error_ != ErrorCodeValue::Success)
{
RequestAsyncOperationBase::OnStart(thisSPtr);
return;
}
ServiceRoutingAgentHeader routingAgentHeader;
if (!request_->Headers.TryReadFirst(routingAgentHeader))
{
TRACE_ERROR_AND_TESTASSERT(TraceComponent, "ServiceRoutingAgentHeader missing: {0}", request_->MessageId);
this->TryComplete(thisSPtr, ErrorCodeValue::InvalidMessage);
return;
}
wstring hostId;
ErrorCode error = this->GetHostId(routingAgentHeader.TypeId, hostId);
if (error.IsSuccess())
{
error = ServiceRoutingAgentMessage::RewrapForRoutingAgentProxy(*request_, routingAgentHeader);
}
if (error.IsSuccess())
{
WriteNoise(
TraceComponent,
"{0} forwarding request {1} to host {2}",
this->TraceId,
routingAgentHeader,
hostId);
// There used to be an IpcServer/IpcClient bug that miscalculates the message header signature
// when there are deleted headers. Preserve the Compact() here anyway as good practice.
//
request_->Headers.Compact();
auto operation = owner_.ipcServer_.BeginRequest(
request_->Clone(),
hostId,
this->RemainingTime,
[this](AsyncOperationSPtr const & operation) { this->OnForwardToServiceComplete(operation, false); },
thisSPtr);
this->OnForwardToServiceComplete(operation, true);
}
else
{
this->TryComplete(thisSPtr, error);
}
}
ErrorCode ServiceRoutingAgent::Impl::NodeToServiceAsyncOperation::GetHostId(
ServiceTypeIdentifier const & serviceTypeId,
__out wstring & hostId)
{
auto error = owner_.hosting_.GetHostId(
VersionedServiceTypeIdentifier(serviceTypeId, ServicePackageVersionInstance()),
SystemServiceApplicationNameHelper::SystemServiceApplicationName,
hostId);
if (!error.IsSuccess())
{
WriteInfo(
TraceComponent,
"{0} host Id for service type {1} not found: {2}",
this->TraceId,
serviceTypeId,
error);
}
return error;
}
void ServiceRoutingAgent::Impl::NodeToServiceAsyncOperation::OnForwardToServiceComplete(
AsyncOperationSPtr const & operation,
bool expectedCompletedSynchronously)
{
if (operation->CompletedSynchronously != expectedCompletedSynchronously)
{
return;
}
MessageUPtr reply;
ErrorCode error = owner_.ipcServer_.EndRequest(operation, reply);
if (error.IsError(ErrorCodeValue::CannotConnectToAnonymousTarget))
{
// Translate to an error that is retryable at the gateway.
// It will re-resolve and resend the request.
//
error = ErrorCodeValue::MessageHandlerDoesNotExistFault;
}
if (error.IsSuccess())
{
error = ServiceRoutingAgentMessage::ValidateIpcReply(*reply);
if (error.IsSuccess())
{
this->SetReply(move(reply));
}
}
this->TryComplete(operation->Parent, error);
}
// *** Public ServiceRoutingAgent
ServiceRoutingAgent::ServiceRoutingAgent(
__in IpcServer & ipcServer,
__in FederationSubsystem & federation,
__in IHostingSubsystem & hosting,
__in IGateway & naming,
ComponentRoot const & root)
: implUPtr_(make_unique<Impl>(
ipcServer,
federation,
hosting,
naming,
root))
{
}
ServiceRoutingAgentUPtr ServiceRoutingAgent::Create(
__in IpcServer & ipcServer,
__in FederationSubsystem & federation,
__in IHostingSubsystem & hosting,
__in IGateway & naming,
ComponentRoot const & root)
{
return unique_ptr<ServiceRoutingAgent>(new ServiceRoutingAgent(ipcServer, federation, hosting, naming, root));
}
ErrorCode ServiceRoutingAgent::OnOpen()
{
return implUPtr_->Open();
}
ErrorCode ServiceRoutingAgent::OnClose()
{
return implUPtr_->Close();
}
void ServiceRoutingAgent::OnAbort()
{
implUPtr_->Abort();
}
| 30.698324 | 144 | 0.655096 |
2a75e213076961ba296d5a5866f686977fed0115 | 1,045 | hpp | C++ | dart/utils/amc/ReadSkeleton.hpp | jyf588/nimblephysics | 6c09228f0abcf7aa3526a8dd65cd2541aff32c4a | [
"BSD-2-Clause"
] | 2 | 2021-09-30T06:23:29.000Z | 2022-03-09T09:59:09.000Z | dart/utils/amc/ReadSkeleton.hpp | jyf588/nimblephysics | 6c09228f0abcf7aa3526a8dd65cd2541aff32c4a | [
"BSD-2-Clause"
] | null | null | null | dart/utils/amc/ReadSkeleton.hpp | jyf588/nimblephysics | 6c09228f0abcf7aa3526a8dd65cd2541aff32c4a | [
"BSD-2-Clause"
] | 1 | 2021-08-20T13:56:14.000Z | 2021-08-20T13:56:14.000Z | #ifndef AMC_READSKELETON_HPP
#define AMC_READSKELETON_HPP
#include <string>
#include <vector>
#include "Skeleton.hpp"
using std::string;
using std::vector;
bool ReadSkeleton(string filename, Library::Skeleton& into);
bool ReadSkeletonV(string filename, Library::Skeleton& into);
// read 'amc' file format (automatically will call below on '.bmc' and '.v',
// though):
bool ReadAnimation(
string filename, Library::Skeleton const& on, vector<double>& positions);
// read the 'bmc' binary format (somewhat faster, probably):
bool ReadAnimationBin(
string filename, Library::Skeleton const& on, vector<double>& positions);
// read the '.v' file format:
bool ReadAnimationV(
string filename, Library::Skeleton const& on, vector<double>& positions);
// copies skel into transformer, but making it into an euler-angle skeleton
// pose.skeleton = &transformer;
// pose.to_angles(angles);
// angles.to_pose(pose);
void get_euler_skeleton(
Library::Skeleton& transformer, const Library::Skeleton& skel);
#endif // READSKELETON_HPP
| 30.735294 | 77 | 0.747368 |
2a760ab3d73648d5df9057572aa0c23fb98e8d87 | 9,193 | cpp | C++ | src/storage/http/StorageHttpDownloadHandler.cpp | xuguruogu/nebula | 50af1ae440415f89cc98b2b2567b53771310ac63 | [
"Apache-2.0"
] | null | null | null | src/storage/http/StorageHttpDownloadHandler.cpp | xuguruogu/nebula | 50af1ae440415f89cc98b2b2567b53771310ac63 | [
"Apache-2.0"
] | null | null | null | src/storage/http/StorageHttpDownloadHandler.cpp | xuguruogu/nebula | 50af1ae440415f89cc98b2b2567b53771310ac63 | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2019 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#include "storage/http/StorageHttpDownloadHandler.h"
#include "webservice/Common.h"
#include "process/ProcessUtils.h"
#include "fs/FileUtils.h"
#include "hdfs/HdfsHelper.h"
#include "kvstore/Part.h"
#include "thread/GenericThreadPool.h"
#include <proxygen/httpserver/RequestHandler.h>
#include <proxygen/lib/http/ProxygenErrorEnum.h>
#include <proxygen/httpserver/ResponseBuilder.h>
#include <mutex>
DEFINE_int32(download_thread_num, 3, "download thread number");
namespace nebula {
namespace storage {
using proxygen::HTTPMessage;
using proxygen::HTTPMethod;
using proxygen::ProxygenError;
using proxygen::UpgradeProtocol;
using proxygen::ResponseBuilder;
void StorageHttpDownloadHandler::init(nebula::hdfs::HdfsHelper *helper,
nebula::thread::GenericThreadPool *pool,
nebula::kvstore::KVStore *kvstore,
std::vector<std::string> paths) {
helper_ = helper;
pool_ = pool;
kvstore_ = kvstore;
paths_ = paths;
CHECK_NOTNULL(helper_);
CHECK_NOTNULL(pool_);
CHECK_NOTNULL(kvstore_);
CHECK(!paths_.empty());
}
void StorageHttpDownloadHandler::onRequest(std::unique_ptr<HTTPMessage> headers) noexcept {
if (headers->getMethod().value() != HTTPMethod::GET) {
// Unsupported method
err_ = HttpCode::E_UNSUPPORTED_METHOD;
return;
}
if (!headers->hasQueryParam("host") ||
!headers->hasQueryParam("port") ||
!headers->hasQueryParam("path") ||
!headers->hasQueryParam("parts") ||
!headers->hasQueryParam("space")) {
LOG(ERROR) << "Illegal Argument";
err_ = HttpCode::E_ILLEGAL_ARGUMENT;
return;
}
hdfsHost_ = headers->getQueryParam("host");
hdfsPort_ = headers->getIntQueryParam("port");
hdfsPath_ = headers->getQueryParam("path");
if (headers->hasQueryParam("options")) {
options_.assign(headers->getQueryParam("options"));
}
auto existStatus = helper_->exist(hdfsHost_, hdfsPort_, hdfsPath_, options_);
if (!existStatus.ok()) {
LOG(ERROR) << "Run Hdfs Test failed. " << existStatus.status().toString();
err_ = HttpCode::E_ILLEGAL_ARGUMENT;
}
bool exist = existStatus.value();
if (!exist) {
LOG(ERROR) << "Hdfs non exist. hdfs://" << hdfsHost_ << ":" << hdfsPort_ << hdfsPath_;
err_ = HttpCode::E_ILLEGAL_ARGUMENT;
return;
}
spaceID_ = headers->getIntQueryParam("space");
auto partitions = headers->getQueryParam("parts");
folly::split(",", partitions, parts_, true);
if (parts_.empty()) {
LOG(ERROR) << "Partitions should be not empty";
err_ = HttpCode::E_ILLEGAL_ARGUMENT;
return;
}
if (headers->hasQueryParam("tag")) {
auto& tag = headers->getQueryParam("tag");
tag_.assign(folly::to<TagID>(tag));
}
if (headers->hasQueryParam("edge")) {
auto& edge = headers->getQueryParam("edge");
edge_.assign(folly::to<EdgeType>(edge));
}
for (auto &path : paths_) {
std::string downloadRootPath = folly::stringPrintf(
"%s/nebula/%d/download", path.c_str(), spaceID_);
std::string downloadRootPathEdge = downloadRootPath + "/edge";
std::string downloadRootPathTag = downloadRootPath + "/tag";
std::string downloadRootPathGeneral = downloadRootPath + "/general";
std::string downloadPath;
if (edge_.has_value()) {
downloadPath = folly::stringPrintf(
"%s/%d",
downloadRootPathEdge.c_str(), edge_.value());
} else if (tag_.has_value()) {
downloadPath = folly::stringPrintf(
"%s/%d",
downloadRootPathTag.c_str(), tag_.value());
} else {
downloadPath = downloadRootPathGeneral;
}
fs::FileUtils::remove(downloadPath.c_str(), true);
fs::FileUtils::makeDir(downloadPath);
}
}
void StorageHttpDownloadHandler::onBody(std::unique_ptr<folly::IOBuf>) noexcept {
// Do nothing, we only support GET
}
void StorageHttpDownloadHandler::onEOM() noexcept {
switch (err_) {
case HttpCode::E_UNSUPPORTED_METHOD:
ResponseBuilder(downstream_)
.status(WebServiceUtils::to(HttpStatusCode::METHOD_NOT_ALLOWED),
WebServiceUtils::toString(HttpStatusCode::METHOD_NOT_ALLOWED))
.sendWithEOM();
return;
case HttpCode::E_ILLEGAL_ARGUMENT:
ResponseBuilder(downstream_)
.status(WebServiceUtils::to(HttpStatusCode::BAD_REQUEST),
WebServiceUtils::toString(HttpStatusCode::BAD_REQUEST))
.sendWithEOM();
return;
default:
break;
}
if (helper_->checkHadoopPath()) {
if (downloadSSTFiles()) {
ResponseBuilder(downstream_)
.status(WebServiceUtils::to(HttpStatusCode::OK),
WebServiceUtils::toString(HttpStatusCode::OK))
.body("SSTFile download successfully")
.sendWithEOM();
} else {
ResponseBuilder(downstream_)
.status(WebServiceUtils::to(HttpStatusCode::FORBIDDEN),
WebServiceUtils::toString(HttpStatusCode::FORBIDDEN))
.body("SSTFile download failed")
.sendWithEOM();
}
} else {
LOG(ERROR) << "HADOOP_HOME not exist";
ResponseBuilder(downstream_)
.status(WebServiceUtils::to(HttpStatusCode::NOT_FOUND),
WebServiceUtils::toString(HttpStatusCode::NOT_FOUND))
.sendWithEOM();
}
}
void StorageHttpDownloadHandler::onUpgrade(UpgradeProtocol) noexcept {
// Do nothing
}
void StorageHttpDownloadHandler::requestComplete() noexcept {
delete this;
}
void StorageHttpDownloadHandler::onError(ProxygenError error) noexcept {
LOG(ERROR) << "Web Service StorageHttpDownloadHandler got error: "
<< proxygen::getErrorString(error);
}
bool StorageHttpDownloadHandler::downloadSSTFiles() {
std::vector<folly::SemiFuture<bool>> futures;
for (auto& part : parts_) {
PartitionID partId;
try {
partId = folly::to<PartitionID>(part);
} catch (const std::exception& ex) {
LOG(ERROR) << "Invalid part: \"" << part << "\"";
return false;
}
auto hdfsPartPath = folly::stringPrintf("%s/%d", hdfsPath_.c_str(), partId);
auto existStatus = helper_->exist(hdfsHost_, hdfsPort_, hdfsPartPath, options_);
if (!existStatus.ok()) {
LOG(ERROR) << "Run Hdfs Test failed. " << existStatus.status().toString();
return false;
}
bool exist = existStatus.value();
if (!exist) {
LOG(WARNING) << "Hdfs path non exist. hdfs://"
<< hdfsHost_ << ":" << hdfsPort_ << hdfsPartPath;
continue;
}
auto partResult = kvstore_->part(spaceID_, partId);
if (!ok(partResult)) {
LOG(ERROR) << "Can't found space: " << spaceID_ << ", part: " << partId;
return false;
}
auto partDataRoot = value(partResult)->engine()->getDataRoot();
std::string localPath;
if (edge_.has_value()) {
localPath = folly::stringPrintf(
"%s/download/edge/%d", partDataRoot, edge_.value());
} else if (tag_.has_value()) {
localPath = folly::stringPrintf(
"%s/download/tag/%d", partDataRoot, tag_.value());
} else {
localPath = folly::stringPrintf(
"%s/download/general", partDataRoot);
}
auto downloader = [this, hdfsPartPath, localPath] {
auto resultStatus = this->helper_->copyToLocal(
hdfsHost_, hdfsPort_, hdfsPartPath, localPath, options_);
if (!resultStatus.ok()) {
LOG(ERROR) << "Run Hdfs CopyToLocal failed. "
<< resultStatus.status().toString();
return false;
}
auto result = std::move(resultStatus).value();
return result.empty();
};
auto future = pool_->addTask(downloader);
futures.push_back(std::move(future));
}
bool successfully{true};
folly::collectAll(futures).thenValue([&](const std::vector<folly::Try<bool>>& tries) {
for (const auto& t : tries) {
if (t.hasException()) {
LOG(ERROR) << "Download Failed: " << t.exception();
successfully = false;
break;
}
if (!t.value()) {
successfully = false;
break;
}
}
}).wait();
LOG(INFO) << "Download tasks have finished";
return successfully;
}
} // namespace storage
} // namespace nebula
| 34.82197 | 94 | 0.589579 |
2a76f8f4ffcc98ceb57bede3502eab783f260a31 | 562 | hh | C++ | mimosa/git/commit.hh | abique/mimosa | 42c0041b570b55a24c606a7da79c70c9933c07d4 | [
"MIT"
] | 24 | 2015-01-19T16:38:24.000Z | 2022-01-15T01:25:30.000Z | mimosa/git/commit.hh | abique/mimosa | 42c0041b570b55a24c606a7da79c70c9933c07d4 | [
"MIT"
] | 2 | 2017-01-07T10:47:06.000Z | 2018-01-16T07:19:57.000Z | mimosa/git/commit.hh | abique/mimosa | 42c0041b570b55a24c606a7da79c70c9933c07d4 | [
"MIT"
] | 7 | 2015-01-19T16:38:31.000Z | 2020-12-12T19:10:30.000Z | #pragma once
# include <git2.h>
# include "../mimosa/mimosa/non-copyable.hh"
namespace mimosa
{
namespace git
{
class Commit : public NonCopyable
{
public:
inline Commit() : commit_(nullptr) {}
inline Commit(git_repository *repo, const git_oid *id) {
git_commit_lookup(&commit_, repo, id);
}
inline ~Commit() { git_commit_free(commit_); }
inline git_commit** ref() { return &commit_; }
inline operator git_commit *() const { return commit_; }
private:
git_commit *commit_;
};
}
}
| 19.37931 | 62 | 0.617438 |
2a7787d11a1172271f751bacc12720ae9cb1f8aa | 5,069 | cpp | C++ | petanque/src/exprs.cpp | Liblor/arybo | 9b98bda682ccd6d0c7e2ffd66281711b46ae23ed | [
"BSD-3-Clause"
] | 223 | 2016-09-12T16:31:12.000Z | 2022-03-14T08:32:04.000Z | petanque/src/exprs.cpp | Liblor/arybo | 9b98bda682ccd6d0c7e2ffd66281711b46ae23ed | [
"BSD-3-Clause"
] | 17 | 2016-11-02T15:20:15.000Z | 2021-10-02T23:30:58.000Z | petanque/src/exprs.cpp | Liblor/arybo | 9b98bda682ccd6d0c7e2ffd66281711b46ae23ed | [
"BSD-3-Clause"
] | 33 | 2016-09-13T07:28:31.000Z | 2022-01-18T07:06:42.000Z | // Copyright (c) 2016 Adrien Guinet <adrien@guinet.me>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the <organization> nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <algorithm>
#include <pa/algos.h>
#include <pa/exprs.h>
#include <pa/cast.h>
#include <pa/simps.h>
bool pa::Expr::ExprArgsStorage::args_less_than(pa::ExprArgs const& a, pa::ExprArgs const& b)
{
if (a.size() < b.size()) {
return true;
}
if (a.size() > b.size()) {
return false;
}
return std::lexicographical_compare(std::begin(a), std::end(a), std::begin(b), std::end(b));
}
bool pa::Expr::ExprArgsStorage::args_equal_with(pa::ExprArgs const& a, pa::ExprArgs const& b)
{
return a == b;
}
bool pa::Expr::operator==(Expr const& o) const
{
if (type() != o.type()) {
return false;
}
return call([&o] (auto const& t) { typedef decltype(t) E; return t == expr_assert_cast<E const&>(o); });
}
bool pa::Expr::operator<(Expr const& o) const
{
if (type() != o.type()) {
return type() < o.type();
}
return call([&o] (auto const& e) { typedef decltype(e) E; return e < expr_assert_cast<E const&>(o); });
}
bool pa::Expr::is_anf() const
{
auto const* add = expr_dynamic_cast<pa::ExprAdd const*>(this);
if (!add) {
return false;
}
for (Expr const& a: add->args()) {
if (auto const* mul = expr_dynamic_cast<pa::ExprMul const*>(&a)) {
for (Expr const& s: mul->args()) {
if (!s.is_sym()) {
return false;
}
}
}
else
if (auto const* imm = expr_dynamic_cast<pa::ExprImm const*>(&a)) {
if (imm->value() != true) {
return false;
}
}
else
if (!a.is_sym()) {
return false;
}
}
return true;
}
unsigned pa::Expr::anf_esf_max_degree() const
{
assert(is_anf());
for (auto it = args().rbegin(); it != args().rend(); ++it) {
if (it->is_mul()) {
return it->args().size();
}
}
return 0;
}
bool pa::Expr::contains(Expr const& o) const
{
if (type() != o.type()) {
if (has_args()) {
return args().find(o) != args().cend();
}
return false;
}
if ((!has_args()) || (o.args().size() == args().size())) {
return (*this == o);
}
// If this is the same type, checks that arguments of 'o' are inside our expression.
// Assumes than 'o' and ourself are sorted
assert(std::is_sorted(args().begin(), args().end()));
assert(std::is_sorted(o.args().begin(), o.args().end()));
if (o.args().size() > args().size()) {
return false;
}
auto it_o = o.args().begin();
const auto it_o_end = o.args().end();
const auto it_end = args().end();
auto it_find = args().begin();
while (it_o != it_o_end) {
it_find = args().find(*it_o, it_find);
if (it_find == it_end) {
return false;
}
++it_o;
++it_find;
}
return true;
}
uint64_t pa::Expr::hash() const
{
return call([](auto const& e) { return e.hash(); });
}
void pa::ExprESF::expand()
{
if (degree() == 1) {
// Fast path, just transform it into an addition
set_type(expr_type_id::add_type);
return;
}
ExprAdd ret;
ExprArgs& args_ret = ret.args();
ExprArgs const& args_ = args();
draw_without_replacement<size_t>(degree(), nargs(),
[&args_ret,&args_](size_t const* idxes, size_t const n)
{
if (n == 0) {
return true;
}
Expr tmp = args_[idxes[0]];
for (size_t i = 1; i < n; i++) {
Expr const& cur_a = args_[idxes[i]];
if (cur_a.is_imm()) {
ExprImm const& cur_imm = cur_a.as<ExprImm>();
if (cur_imm.value() == false) {
return true;
}
}
else {
tmp *= cur_a;
}
}
args_ret.insert_dup(std::move(tmp));
return true;
});
if (args_ret.size() == 1) {
static_cast<Expr&>(*this) = std::move(args_ret[0]);
}
else {
set<ExprAdd>(std::move(ret));
}
}
| 27.252688 | 105 | 0.642336 |
2a7a17eb32aa76f1824c22d26b9978c1c654c6b4 | 1,152 | cpp | C++ | algospot/starforce/main.cpp | seirion/code | 3b8bf79764107255185061cec33decbc2235d03a | [
"Apache-2.0"
] | 13 | 2015-06-07T09:26:26.000Z | 2019-05-01T13:23:38.000Z | algospot/starforce/main.cpp | seirion/code | 3b8bf79764107255185061cec33decbc2235d03a | [
"Apache-2.0"
] | null | null | null | algospot/starforce/main.cpp | seirion/code | 3b8bf79764107255185061cec33decbc2235d03a | [
"Apache-2.0"
] | 4 | 2016-03-05T06:21:05.000Z | 2017-02-17T15:34:18.000Z | // http://algospot.com/judge/problem/read/STARFORCE
#include <cstdio>
#include <iostream>
using namespace std;
int n, m, s, best;
int in[200];
int pre[200][200]; // pre processed : or
void input() {
scanf("%d %d", &n, &m);
int i, j;
for (i = 0; i < n; i++) {
scanf("%d", &in[i]);
}
for (i = 0; i < n; i++) {
pre[i][i] = in[i];
for (j = i + 1; j < n; j++) {
pre[i][j] = pre[i][j-1] | in[j];
}
}
}
bool possible(int all, int start, int remain) {
if (remain == 0) return true;
for (int i = start; i <= n - remain; i++) {
if ((all & pre[start][i]) == all) {
return possible(all, i+1, remain-1);
}
}
return false;
}
int next(int v) {
unsigned int t = (v | (v - 1)) + 1;
return t | ((((t & -t) / (v & -v)) >> 1) - 1);
}
void solve() {
int now = 0xFFFF;
while (now > 0) {
if (possible(now, 0, m)) break;
now = next(now) & 0xFFFF;
}
printf("%d\n", __builtin_popcount(now));
}
int main() {
int num;
scanf("%d", &num);
for (int i = 0; i < num; i++) {input(); solve();}
return 0;
}
| 19.525424 | 53 | 0.454861 |
2a7cc699bef9f1b012901b82f1de0ee85c925214 | 2,241 | cpp | C++ | archives/problemset/acm.hdu.edu.cn/4727.cpp | BoleynSu/CP-CompetitiveProgramming | cc256bf402360fe0f689fdcdc4e898473a9594dd | [
"MIT"
] | 6 | 2019-03-23T21:06:25.000Z | 2021-06-27T05:22:41.000Z | archives/problemset/acm.hdu.edu.cn/4727.cpp | BoleynSu/CP-CompetitiveProgramming | cc256bf402360fe0f689fdcdc4e898473a9594dd | [
"MIT"
] | 1 | 2020-10-11T08:14:00.000Z | 2020-10-11T08:14:00.000Z | archives/problemset/acm.hdu.edu.cn/4727.cpp | BoleynSu/CP-CompetitiveProgramming | cc256bf402360fe0f689fdcdc4e898473a9594dd | [
"MIT"
] | 3 | 2019-03-23T21:06:31.000Z | 2021-10-24T01:44:01.000Z | #include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
using namespace std;
//const double eps=1e-8;
//struct P
//{
// double x,y;
// void in(){scanf("%lf%lf",&x,&y);}
//};
//double dis(P a,P b)
//{
// return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
//}
//int sgn(double x)
//{
// return (x>eps)-(x<-eps);
//}
//P a,b,c,T,p[6];
//int main()
//{
// int cas,i,j;
// scanf("%d",&cas);
// P cp;
// bool flag;
// pair<int,int>t;
// for(int k=1;k<=cas;k++)
// {
// a.in();
// b.in();
// c.in();
// T.in();
// double a1=b.x-a.x,b1=b.y-a.y,c1=(a1*a1+b1*b1)/2;
// double a2=c.x-a.x,b2=c.y-a.y,c2=(a2*a2+b2*b2)/2;
// double d=a1*b2-a2*b1;
// if(fabs(d)<1e-8)
// {
// p[0]=a;p[1]=b;p[2]=c;
// t=make_pair(0,1);
// for(i=0;i<3;i++)
// for(j=i+1;j<3;j++)
// if(dis(p[i],p[j])>dis(p[t.first],p[t.second]))
// t=make_pair(i,j);
// cp.x=(p[t.first].x+p[t.second].x)/2;
// cp.y=(p[t.first].y+p[t.second].y)/2;
// if(sgn(dis(T,cp)-dis(cp,a))<=0)flag=true;
// else flag=false;
// }
// else
// {
// cp.x=a.x+(c1*b2-c2*b1)/d;
// cp.y=a.y+(a1*c2-a2*c1)/d;
// printf("%f %f\n",dis(T,cp),dis(cp,a));
// if(sgn(dis(T,cp)-dis(cp,a))<=0)flag=true;
// else flag=false;
// }
// printf("Case #%d: ",k);
// if(flag)puts("Danger");
// else puts("Safe");
//
// }
//}
int a[129299],n;
int main()
{
int cas;
scanf("%d",&cas);
int k,i,ans;
for(k=1;k<=cas;k++)
{
scanf("%d",&n);
ans=-1;
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
if(i>1&&a[i]!=a[i-1]+1)ans=i;
}
if(ans==-1)ans=1;
printf("Case #%d: %d\n",k,ans);
}
}
//int main()
//{
// int T;
// scanf("%d",&T);
// for (int t=1;t<=T;t++)
// {
// int ans=0;
// printf("Case #%d: %d\n",t,ans);
// }
//}
| 23.34375 | 69 | 0.374386 |
2a81a4b4521f2e21d16f437712949fd2c3b8bc93 | 1,105 | cpp | C++ | src/erase_remove.cpp | ebayboy/cpp_demos | b01df202c0285bf232900662d336505520d5d24d | [
"Apache-2.0"
] | null | null | null | src/erase_remove.cpp | ebayboy/cpp_demos | b01df202c0285bf232900662d336505520d5d24d | [
"Apache-2.0"
] | null | null | null | src/erase_remove.cpp | ebayboy/cpp_demos | b01df202c0285bf232900662d336505520d5d24d | [
"Apache-2.0"
] | null | null | null | /*
erase && remove
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(int args, char **argv)
{
vector<int> v;
for (size_t i = 0; i < 10; i++)
{
v.push_back(i);
if (i == 5 || i == 8)
v.push_back(i);
}
for (auto &&i : v)
{
cout << "i:" << i << endl;
}
for (auto it = v.begin(); it != v.end(); it++)
{
if (*it == 5)
{
//test erase
v.erase(it--); //元素删除后迭代器需要退1,保证不丢掉重复的元素5
}
}
//erase删除后, v的元素减少
cout << "after erase size:" << v.size() << endl;
cout << "after remove show:================" << endl;
for (auto &&i : v)
{
cout << "i:" << i << endl;
}
auto it = std::remove(v.begin(),v.end(), 8);
if (it != v.end()) {
cout << "remove:" << *it << endl;
}
//remove后size没减少, 而是将删除的元素放到end后面
cout << "after remove: size:" << v.size() << endl;
cout << "end:" << *v.end() << endl;
for (auto &&i : v)
{
cout << "i:" << i << endl;
}
return 0;
}
| 18.416667 | 57 | 0.420814 |
2a83cb520267fb9b00cd17a3bf6acc4d462c2568 | 2,453 | cpp | C++ | examples/undocumented/libshogun/features_copy_subset_simple_features.cpp | srgnuclear/shogun | 33c04f77a642416376521b0cd1eed29b3256ac13 | [
"Ruby",
"MIT"
] | 1 | 2015-11-05T18:31:14.000Z | 2015-11-05T18:31:14.000Z | examples/undocumented/libshogun/features_copy_subset_simple_features.cpp | waderly/shogun | 9288b6fa38e001d63c32188f7f847dadea66e2ae | [
"Ruby",
"MIT"
] | null | null | null | examples/undocumented/libshogun/features_copy_subset_simple_features.cpp | waderly/shogun | 9288b6fa38e001d63c32188f7f847dadea66e2ae | [
"Ruby",
"MIT"
] | null | null | null | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2011-2012 Heiko Strathmann
* Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
*/
#include <shogun/base/init.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/features/Subset.h>
using namespace shogun;
void test()
{
SGMatrix<float64_t> data(3, 10);
CDenseFeatures<float64_t>* f=new CDenseFeatures<float64_t>(data);
SGVector<float64_t>::range_fill_vector(data.matrix, data.num_cols*data.num_rows, 1.0);
SGMatrix<float64_t>::display_matrix(data.matrix, data.num_rows, data.num_cols,
"original feature data");
index_t offset_subset=1;
SGVector<index_t> feature_subset(8);
SGVector<index_t>::range_fill_vector(feature_subset.vector, feature_subset.vlen,
offset_subset);
SGVector<index_t>::display_vector(feature_subset.vector, feature_subset.vlen,
"feature subset");
f->add_subset(feature_subset);
SG_SPRINT("feature vectors after setting subset on original data:\n");
for (index_t i=0; i<f->get_num_vectors(); ++i)
{
SGVector<float64_t> vec=f->get_feature_vector(i);
SG_SPRINT("%i: ", i);
SGVector<float64_t>::display_vector(vec.vector, vec.vlen);
f->free_feature_vector(vec, i);
}
index_t offset_copy=2;
SGVector<index_t> feature_copy_subset(4);
SGVector<index_t>::range_fill_vector(feature_copy_subset.vector,
feature_copy_subset.vlen, offset_copy);
SGVector<index_t>::display_vector(feature_copy_subset.vector, feature_copy_subset.vlen,
"indices that are to be copied");
CDenseFeatures<float64_t>* subset_copy=
(CDenseFeatures<float64_t>*)f->copy_subset(feature_copy_subset);
SGMatrix<float64_t> subset_copy_matrix=subset_copy->get_feature_matrix();
SGMatrix<float64_t>::display_matrix(subset_copy_matrix.matrix,
subset_copy_matrix.num_rows, subset_copy_matrix.num_cols,
"copy matrix");
index_t num_its=subset_copy_matrix.num_rows*subset_copy_matrix.num_cols;
for (index_t i=0; i<num_its; ++i)
{
index_t idx=i+(offset_copy+offset_subset)*subset_copy_matrix.num_rows;
ASSERT(subset_copy_matrix.matrix[i]==data.matrix[idx]);
}
SG_UNREF(f);
SG_UNREF(subset_copy);
}
int main(int argc, char **argv)
{
init_shogun_with_defaults();
test();
exit_shogun();
return 0;
}
| 31.050633 | 88 | 0.766001 |
2a8472d1cf692179f88f0bd648b65ffcadde02f4 | 532 | cc | C++ | 003-xoxoxo-tcp/xoxoxo.cc | gynvael/stream | 2d1a3f25b2f83241b39dab931d9ff03fca81d26e | [
"MIT"
] | 152 | 2016-02-04T10:40:46.000Z | 2022-03-03T18:25:54.000Z | 003-xoxoxo-tcp/xoxoxo.cc | gynvael/stream | 2d1a3f25b2f83241b39dab931d9ff03fca81d26e | [
"MIT"
] | 4 | 2016-03-11T23:49:46.000Z | 2017-06-16T18:58:53.000Z | 003-xoxoxo-tcp/xoxoxo.cc | gynvael/stream | 2d1a3f25b2f83241b39dab931d9ff03fca81d26e | [
"MIT"
] | 48 | 2016-01-31T19:13:36.000Z | 2021-09-03T19:50:17.000Z | #include <cstdio>
#include "NetSock.h"
void usage() {
printf("usage: xoxoxo <host> <port>\n");
}
int main(int argc, char **argv) {
if (argc != 3) {
usage();
return 1;
}
unsigned short port;
if (sscanf(argv[2], "%hu", &port) != 1) {
usage();
return 2;
}
const char *host = argv[1];
NetSock::InitNetworking();
NetSock s;
if (!s.Connect(host, port)) {
fprintf(stderr, "Could not connect!\n");
return 3;
}
s.Disconnect();
return 0;
}
| 14.777778 | 45 | 0.511278 |
2a84f22684d7b564d74896a34f15a6aa02daef67 | 4,930 | cpp | C++ | Libraries/libvitaboy/vbparse.cpp | daddesio/Niotso | 66ce47351427fa37c683f61003e0d3aa6b84e4f7 | [
"ISC"
] | 10 | 2017-04-28T08:09:25.000Z | 2022-03-28T11:08:18.000Z | Libraries/libvitaboy/vbparse.cpp | Fatbag/Niotso | 66ce47351427fa37c683f61003e0d3aa6b84e4f7 | [
"ISC"
] | null | null | null | Libraries/libvitaboy/vbparse.cpp | Fatbag/Niotso | 66ce47351427fa37c683f61003e0d3aa6b84e4f7 | [
"ISC"
] | 4 | 2015-06-23T11:06:34.000Z | 2017-01-17T03:50:08.000Z | /*
libvitaboy - Open source OpenGL TSO character animation library
vbparse.cpp - Copyright (c) 2012 Niotso Project <http://niotso.org/>
Author(s): Fatbag <X-Fi6@phppoll.org>
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 <stdio.h>
#include <strings.h>
#include <FileHandler.hpp>
#include "libvitaboy.hpp"
enum VBFileType {
VBFILE_ANIM,
VBFILE_APR,
VBFILE_BND,
VBFILE_COL,
VBFILE_HAG,
VBFILE_MESH,
VBFILE_OFT,
VBFILE_PO,
VBFILE_SKEL
};
int main(int argc, char *argv[]){
int type;
char * InFile;
if(argc == 1 || !strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")){
printf("Usage: vbparse [-t type] infile\n"
"Parse a TSO VitaBoy file.\n"
"\n"
"Supported types:\n"
" (*) ANIM - Animation\n"
" (*) APR - Appearance\n"
" (*) BND - Binding\n"
" (*) COL - Collection\n"
" (*) HAG - Hand group\n"
" (*) MESH - Mesh\n"
" (*) OFT - Outfit\n"
" (*) PO - Purchasable object\n"
" (*) SKEL - Skeleton\n"
"\n"
"Report bugs to <X-Fi6@phppoll.org>.\n"
"vbparse is maintained by the Niotso project.\n"
"Home page: <http://www.niotso.org/>");
return 0;
}
if(argc >= 4 && !strcmp(argv[1], "-t")){
if(!stricmp(argv[2], "anim")) type = 0;
else if(!stricmp(argv[2], "apr")) type = 1;
else if(!stricmp(argv[2], "bnd")) type = 2;
else if(!stricmp(argv[2], "col")) type = 3;
else if(!stricmp(argv[2], "hag")) type = 4;
else if(!stricmp(argv[2], "mesh")) type = 5;
else if(!stricmp(argv[2], "oft")) type = 6;
else if(!stricmp(argv[2], "po")) type = 7;
else if(!stricmp(argv[2], "skel")) type = 8;
else{
printf("%sUnrecognized type '%s'", "vbparse: Error: ", argv[2]);
return -1;
}
InFile = argv[3];
}else{
char * pos = strrchr(argv[1], '.') + 1;
if(!stricmp(pos, "anim")) type = 0;
else if(!stricmp(pos, "apr")) type = 1;
else if(!stricmp(pos, "bnd")) type = 2;
else if(!stricmp(pos, "col")) type = 3;
else if(!stricmp(pos, "hag")) type = 4;
else if(!stricmp(pos, "mesh")) type = 5;
else if(!stricmp(pos, "oft")) type = 6;
else if(!stricmp(pos, "po")) type = 7;
else if(!stricmp(pos, "skel")) type = 8;
else{
printf("%sUnrecognized type", "vbparse: Error: ");
return -1;
}
InFile = argv[1];
}
uint8_t *InData = File::ReadFile(InFile);
if(InData == NULL){
const char * Message;
switch(File::Error){
case FERR_NOT_FOUND:
Message = "%s does not exist.";
break;
case FERR_OPEN:
Message = "%s could not be opened for reading.";
break;
case FERR_BLANK:
Message = "%s is corrupt or invalid.";
break;
case FERR_MEMORY:
Message = "Memory for %s could not be allocated.";
break;
default:
Message = "%s could not be read.";
break;
}
printf(Message, InFile);
return -1;
}
VBFile.set(InData, File::FileSize);
switch(type){
case VBFILE_ANIM:
Animation_t Animation;
ReadAnimation(Animation);
break;
case VBFILE_APR:
Appearance_t Appearance;
ReadAppearance(Appearance);
break;
case VBFILE_BND:
Binding_t Binding;
ReadBinding(Binding);
break;
case VBFILE_COL:
Collection_t Collection;
ReadCollection(Collection);
break;
case VBFILE_HAG:
HandGroup_t HandGroup;
ReadHandGroup(HandGroup);
break;
case VBFILE_MESH:
Mesh_t Mesh;
ReadMesh(Mesh);
break;
case VBFILE_OFT:
Outfit_t Outfit;
ReadOutfit(Outfit);
break;
case VBFILE_PO:
PurchasableOutfit_t PurchasableOutfit;
ReadPurchasableOutfit(PurchasableOutfit);
break;
case VBFILE_SKEL:
Skeleton_t Skeleton;
ReadSkeleton(Skeleton);
}
return 0;
}
| 30.8125 | 76 | 0.558621 |
2a899caff1f02550a918d0971f15bf607f12f8d8 | 2,453 | cc | C++ | src/body.cc | wgtdkp/apollonia | 0e57af431818bc9a19e9952f4d4b2a294e1c9d8b | [
"MIT"
] | 126 | 2017-10-11T04:39:45.000Z | 2022-03-05T23:16:06.000Z | src/body.cc | FrostDescent/apollonia | 18f15102b1620d38de1b7de0939c9e93d8449f69 | [
"MIT"
] | 1 | 2020-11-08T15:01:28.000Z | 2020-11-08T15:01:28.000Z | src/body.cc | FrostDescent/apollonia | 18f15102b1620d38de1b7de0939c9e93d8449f69 | [
"MIT"
] | 24 | 2018-08-22T06:25:54.000Z | 2022-01-08T05:31:52.000Z | #include "body.h"
#include <algorithm>
namespace apollonia {
using std::abs;
void Body::set_mass(Float mass) {
mass_ = mass;
inv_mass_ = 1 / mass;
}
void Body::set_inertia(Float inertia) {
inertia_ = inertia;
inv_inertia_ = 1 / inertia;
}
bool Body::ShouldCollide(const Body& other) const {
return !(mass_ == kInf && other.mass_ == kInf);
}
void Body::ApplyImpulse(const Vec2& impulse, const Vec2& r) {
velocity_ += impulse * inv_mass_;
angular_velocity_ += inv_inertia_ * Cross(r, impulse);
}
void Body::Integrate(const Vec2& gravity, Float dt) {
if (mass_ == kInf) {
return;
}
velocity_ += (gravity + force_ * inv_mass_) * dt;
angular_velocity_ += (torque_ * inv_inertia_) * dt;
position_ += velocity_ * dt;
rotation_ = Mat22(angular_velocity_ * dt) * rotation_;
}
static Float PolygonArea(const std::vector<Vec2>& vertices) {
Float area = 0;
for (size_t i = 0; i < vertices.size(); ++i) {
auto j = (i+1) % vertices.size();
area += Cross(vertices[i], vertices[j]);
}
return area / 2;
}
static Vec2 PolygonCentroid(const std::vector<Vec2>& vertices) {
Vec2 gc {0, 0};
for (size_t i = 0; i < vertices.size(); ++i) {
auto j = (i+1) % vertices.size();
gc += (vertices[i] + vertices[j]) * Cross(vertices[i], vertices[j]);
}
return gc / 6 / PolygonArea(vertices);
}
static Float PolygonInertia(Float mass, const PolygonBody::VertexList& vertices) {
Float acc0 = 0, acc1 = 0;
for (size_t i = 0; i < vertices.size(); ++i) {
auto a = vertices[i], b = vertices[(i+1)%vertices.size()];
auto cross = abs(Cross(a, b));
acc0 += cross * (Dot(a, a) + Dot(b, b) + Dot(a, b));
acc1 += cross;
}
return mass * acc0 / 6 / acc1;
}
PolygonBody::PolygonBody(Float mass, const VertexList& vertices)
: Body(mass), vertices_(vertices) {
set_inertia(PolygonInertia(mass, vertices));
set_centroid(PolygonCentroid(vertices));
}
Float PolygonBody::FindMinSeparatingAxis(size_t& idx, const PolygonBody& other) const {
Float separation = -kInf;
for (size_t i = 0; i < this->Count(); ++i) {
auto va = this->LocalToWorld((*this)[i]);
auto normal = this->EdgeAt(i).Normal();
auto min_sep = kInf;
for (size_t j = 0; j < other.Count(); ++j) {
auto vb = other.LocalToWorld(other[j]);
min_sep = std::min(min_sep, Dot(vb - va, normal));
}
if (min_sep > separation) {
separation = min_sep;
idx = i;
}
}
return separation;
}
}
| 26.956044 | 87 | 0.630656 |
2a8c25a01728f4ae28a96fee151383affdcce969 | 6,100 | cpp | C++ | TricksterEngine/src/Rendering/Text/Internal/Font.cpp | Trickje/Trickster | ab73f15ec1b45676a20793ad6d4e9acfc2ba944e | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | TricksterEngine/src/Rendering/Text/Internal/Font.cpp | Trickje/Trickster | ab73f15ec1b45676a20793ad6d4e9acfc2ba944e | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | TricksterEngine/src/Rendering/Text/Internal/Font.cpp | Trickje/Trickster | ab73f15ec1b45676a20793ad6d4e9acfc2ba944e | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | #include "pch.h"
#include "Rendering/Text/Internal/Font.h"
#include "Core/Application.h"
#include "Rendering/ShaderManager.h"
#include "Rendering/Shader.h"
#include "Rendering/Window.h"
#include <glm/gtc/type_ptr.hpp>
using namespace TE;
#ifdef TRICKSTER_OPENGL
void Font::Initialize()
{
// configure VAO/VBO for texture quads
// -----------------------------------
glGenVertexArrays(1, &m_VAO);
glGenBuffers(1, &m_VBO);
glBindVertexArray(m_VAO);
glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
/*
* The size of each vertex
* Position: x, y, z = 3
* Color: r, g, b, a = 4
* TODO: implement batch rendering
*
*/
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 9, 0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 9, (const GLvoid*)(3 * sizeof(float)));
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 9, (const GLvoid*)(5 * sizeof(float)));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
void Font::LoadFromFile(const std::string& a_FileName)
{
FT_Error m_Error;
FT_Library m_Library;
FT_Face m_Face;
if (FT_Init_FreeType(&m_Library))
{
LOG_ERROR("[Font] " + a_FileName + " Could not init FreeType Library");
return;
}
if (FT_New_Face(m_Library, ("Resources/Fonts/" + a_FileName + ".ttf").c_str(), 0, &m_Face)) {
LOG_ERROR("[Font] " + a_FileName + " Failed to load font");
return;
}
// set size to load glyphs as
FT_Set_Pixel_Sizes(m_Face, 0, 48);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1); // disable byte-alignment restriction
FT_GlyphSlot g = m_Face->glyph;
int w = 0;
int h = 0;
for (int i = 0; i < 128; i++) {
if (FT_Load_Char(m_Face, i, FT_LOAD_RENDER)) {
fprintf(stderr, "Loading character %c failed!\n", i);
continue;
}
w += g->bitmap.width;
h = max(h, static_cast<int>(g->bitmap.rows));
}
/* you might as well save this value as it is needed later on */
atlas_width = static_cast<float>(w);
atlas_height = static_cast<float>(h);
glActiveTexture(GL_TEXTURE0);
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
int x = 0;
for (unsigned char c = 0; c < 128; c++) {
if (FT_Load_Char(m_Face, c, FT_LOAD_RENDER))
continue;
m_Characters[c].ax = g->advance.x >> 6;
m_Characters[c].ay = g->advance.y >> 6;
m_Characters[c].bw = g->bitmap.width;
m_Characters[c].bh = g->bitmap.rows;
m_Characters[c].bl = g->bitmap_left;
m_Characters[c].bt = g->bitmap_top;
m_Characters[c].tx = static_cast<float>(x) / static_cast<float>(w);
glTexSubImage2D(GL_TEXTURE_2D, 0, x, 0, g->bitmap.width, g->bitmap.rows, GL_RED, GL_UNSIGNED_BYTE, g->bitmap.buffer);
x += g->bitmap.width;
}
glBindTexture(GL_TEXTURE_2D, 0);
// destroy FreeType once we're finished
FT_Done_Face(m_Face);
FT_Done_FreeType(m_Library);
}
void Font::Render()
{
Shader* shader = ShaderManager::GetShader("BasicFont");
shader->Bind();
glm::mat4 projection = glm::ortho(0.0f, static_cast<float>(Application::Get()->GetWindow()->GetWidth()), 0.0f, static_cast<float>(Application::Get()->GetWindow()->GetHeight()));
// activate corresponding render state
glUniformMatrix4fv(shader->GetUniformLocation("projection"), 1, GL_FALSE, glm::value_ptr(projection));
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex);
glBindVertexArray(m_VAO);
glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
glBufferData(GL_ARRAY_BUFFER, coords.size() * 9 * sizeof(float), &coords[0], GL_DYNAMIC_DRAW);
glDrawArrays(GL_TRIANGLES, 0, coords.size());
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindTexture(GL_TEXTURE_2D, 0);
coords.clear();
}
bool Font::operator==(const Font& other)
{
return m_FileName == other.m_FileName;
}
void Font::AddVertexData(std::string text, float x, float y, float scale, glm::vec4 color)
{
// iterate through all characters
std::string::const_iterator c;
for (c = text.begin(); c != text.end(); c++)
{
Character* ch = &m_Characters[*c];
float x2 = x + ch->bl * scale;
float y2 = -y - ch->bt * scale;
float w = ch->bw * scale;
float h = ch->bh * scale;
/* Advance the cursor to the start of the next character */
x += ch->ax * scale;
y += ch->ay * scale;
float z = 0.f;
coords.push_back({ x2, -y2 , z, ch->tx, 0, color.r, color.g, color.b, color.a });
coords.push_back({ x2 + w, -y2 , z,ch->tx + ch->bw / atlas_width, 0 , color.r, color.g, color.b, color.a });
coords.push_back({ x2, -y2 - h, z, ch->tx, ch->bh / atlas_height, color.r, color.g, color.b, color.a }); //remember: each glyph occupies a different amount of vertical space
coords.push_back({ x2 + w, -y2 , z, ch->tx + ch->bw / atlas_width, 0 , color.r, color.g, color.b, color.a });
coords.push_back({ x2, -y2 - h, z, ch->tx, ch->bh / atlas_height , color.r, color.g, color.b, color.a });
coords.push_back({ x2 + w, -y2 - h, z, ch->tx + ch->bw / atlas_width, ch->bh / atlas_height , color.r, color.g, color.b, color.a });
}
}
#endif
#ifdef TRICKSTER_VULKAN
void Font::AddVertexData(std::string text, float x, float y, float scale, glm::vec4 color)
{
}
void Font::Initialize()
{
}
void Font::LoadFromFile(const std::string& a_FileName)
{
}
void Font::Render()
{
}
bool Font::operator==(const Font& other)
{
return true;
}
#endif
Font::Font()
{
Initialize();
}
Font::~Font()
{
}
| 28.240741 | 187 | 0.62623 |
2a9033e59bc54cb6063e2e3a1ef32b17cc82f547 | 2,105 | cpp | C++ | extras/cpp/main.cpp | skn123/DeslantImg | b7183ff31067e51d8dcba581c6241b15ceb87f28 | [
"MIT"
] | 115 | 2018-07-19T16:37:54.000Z | 2022-03-28T09:22:04.000Z | extras/cpp/main.cpp | skn123/DeslantImg | b7183ff31067e51d8dcba581c6241b15ceb87f28 | [
"MIT"
] | 5 | 2018-08-06T14:38:08.000Z | 2021-11-21T10:12:43.000Z | extras/cpp/main.cpp | skn123/DeslantImg | b7183ff31067e51d8dcba581c6241b15ceb87f28 | [
"MIT"
] | 36 | 2018-01-26T03:56:44.000Z | 2022-03-07T22:32:05.000Z | #ifdef USE_GPU
#include "DeslantImgGPU.hpp"
#else
#include "DeslantImgCPU.hpp"
#endif
#include <opencv2/imgcodecs.hpp>
#include <iostream>
int main(int argc, const char *argv[])
{
const cv::String opts =
"{help h usage ? | | print this message }"
"{@imagein |- | path name to read the input image from (or stdin) }"
"{@imageout |- | path name to write the output image to (or stdout) }"
"{lower_bound |-1.0 | lower bound of shear values }"
"{upper_bound |1.0 | upper bound of shear values }"
"{bg_color |255 | color to fill the gaps of the sheared image that is returned }"
;
cv::CommandLineParser parser(argc, argv, opts);
#ifdef USE_GPU
parser.about("DeslantImg GPU");
#else
parser.about("DeslantImg CPU");
#endif
if (parser.has("help"))
{
parser.printMessage();
return 0;
}
if (!parser.check())
{
parser.printErrors();
return 1;
}
cv::String inpath = parser.get<cv::String>("@imagein");
cv::String outpath = parser.get<cv::String>("@imageout");
float lower_bound = parser.get<float>("lower_bound");
float upper_bound = parser.get<float>("upper_bound");
int bg_color = parser.get<int>("bg_color");
#ifdef USE_GPU
htr::CLWrapper clWrapper; // setup OpenCL, the same instance should be used for all following calls to deslantImg
#endif
// load input image
cv::Mat img;
if (inpath == "-")
{
char c;
std::vector<char> data;
std::cin >> std::noskipws;
while (std::cin >> c)
data.push_back(c);
const cv::Mat rawimg(data);
img = cv::imdecode(rawimg, cv::IMREAD_GRAYSCALE);
}
else
img = cv::imread(inpath, cv::IMREAD_GRAYSCALE);
#ifdef USE_GPU
// deslant on GPU
const cv::Mat res = htr::deslantImg(img, bg_color, clWrapper);
#else
// deslant on CPU
cv::Mat res = htr::deslantImg(img, bg_color, lower_bound, upper_bound);
#endif
// write result to file
if (outpath == "-")
{
std::vector<unsigned char> data;
if (cv::imencode(".png", res, data))
{
std::string out(data.begin(), data.end());
std::cout << out;
}
else
return 1;
}
else
cv::imwrite(outpath, res);
return 0;
}
| 25.361446 | 114 | 0.651781 |
2a90974d03cbd0acc93682c3cb5ca024d5f5cc92 | 3,348 | cc | C++ | src/statement.cc | xukl/BASIC-Compiler | 3b0f752df5b9301aa116811729e362bfeaa05e58 | [
"MIT"
] | null | null | null | src/statement.cc | xukl/BASIC-Compiler | 3b0f752df5b9301aa116811729e362bfeaa05e58 | [
"MIT"
] | null | null | null | src/statement.cc | xukl/BASIC-Compiler | 3b0f752df5b9301aa116811729e362bfeaa05e58 | [
"MIT"
] | null | null | null | #include "statement.hpp"
#include <sstream>
#include <stack>
#include <memory>
#include <utility>
#include <typeinfo>
namespace statement
{
std::ostream &operator<< (std::ostream &os, const statement &x)
{
x.print(os);
return os;
}
std::ostream &operator<< (std::ostream &os, const assignment &x)
{
x.print(os);
return os;
}
program_type read_program(std::istream &is)
{
std::map<line_num, std::unique_ptr<statement>> ret;
line_num line;
std::stack<std::pair<line_num, std::string>> FOR_stack;
while (is >> line)
{
auto attemp_insert
= ret.insert(std::make_pair(line, std::unique_ptr<statement>()));
if (!attemp_insert.second)
throw "Line number repeated.";
std::string statement_type;
is >> statement_type;
std::unique_ptr<statement> sentence;
std::string sentence_str;
getline(is, sentence_str);
if (statement_type == "REM")
sentence = std::make_unique<REM>();
else if (statement_type == "LET")
sentence = std::make_unique<LET>(sentence_str);
else if (statement_type == "INPUT")
sentence = std::make_unique<INPUT>(sentence_str);
else if (statement_type == "EXIT")
sentence = std::make_unique<EXIT>(sentence_str);
else if (statement_type == "GOTO")
sentence = std::make_unique<GOTO>(sentence_str);
else if (statement_type == "IF")
sentence = std::make_unique<IF>(sentence_str);
else if (statement_type == "FOR")
{
FOR_stack.push(std::make_pair(line, sentence_str));
continue;
}
else if (statement_type == "END")
{
std::istringstream iss(sentence_str);
std::string for_expected;
iss >> for_expected;
if (for_expected != "FOR")
throw "Unknown token.";
char tmp;
if (iss >> tmp)
throw "Extra trailing characters.";
if (FOR_stack.empty())
throw "Unpaired \"END FOR\".";
auto &&FOR_info = FOR_stack.top();
const auto &str = FOR_info.second;
ret[FOR_info.first] = std::make_unique<FOR>(str, line);
sentence = std::make_unique<END_FOR>(FOR_info.first,
assignment(std::string(str, 0, str.find(';'))));
FOR_stack.pop();
}
else
throw "Unknown token.";
attemp_insert.first->second = std::move(sentence);
}
for (auto &[line, sent] : ret)
{
const auto &sent_type = typeid(*sent);
if (sent_type == typeid(IF))
{
line_num &target_line = static_cast<IF&>(*sent).line;
if (typeid(*ret[target_line]) == typeid(FOR))
{
line_num end_for_line =
static_cast<FOR&>(*ret[target_line]).end_for_line;
if (line >= target_line && line <= end_for_line)
target_line = end_for_line;
}
}
if (sent_type == typeid(GOTO))
{
line_num &target_line = static_cast<GOTO&>(*sent).line;
if (typeid(*ret[target_line]) == typeid(FOR))
{
line_num end_for_line =
static_cast<FOR&>(*ret[target_line]).end_for_line;
if (line >= target_line && line <= end_for_line)
target_line = end_for_line;
}
}
}
if (!is.eof())
throw "Error when reading program. Probably caused by missing line number.";
if (!FOR_stack.empty())
throw "Unpaired \"FOR\".";
if (ret.count(INT_MAX) != 0)
throw ":-( Line number too big.";
ret[additional_exit_line]
= std::make_unique<EXIT>(std::make_unique<expr::imm_num>(0));
return ret;
}
void print_program(std::ostream &os, const program_type &prog)
{
for (const auto &[line, sent] : prog)
os << '#' << line << ":\t" << *sent << std::endl;
}
}
| 28.615385 | 78 | 0.660992 |
2a914457d6f2022d1e593143d3b2c188989b1327 | 5,715 | cc | C++ | elements/analysis/aggcountervector.cc | timmytimj/fastclick | 260dfa7285e5fff3c916b8272249d6d393e61179 | [
"BSD-3-Clause-Clear"
] | 129 | 2015-10-08T14:38:35.000Z | 2022-03-06T14:54:44.000Z | elements/analysis/aggcountervector.cc | nic-bench/fastclick | 2812f0684050cec07e08f30d643ed121871cf25d | [
"BSD-3-Clause-Clear"
] | 241 | 2016-02-17T16:17:58.000Z | 2022-03-15T09:08:33.000Z | elements/analysis/aggcountervector.cc | nic-bench/fastclick | 2812f0684050cec07e08f30d643ed121871cf25d | [
"BSD-3-Clause-Clear"
] | 61 | 2015-12-17T01:46:58.000Z | 2022-02-07T22:25:19.000Z | /*
* aggcountervector.{cc,hh} -- count packets/bytes with given aggregate
*
* 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, subject to the conditions
* listed in the Click LICENSE file. These conditions include: you must
* preserve this copyright notice, and you cannot mention the copyright
* holders in advertising related to the Software without their permission.
* The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This
* notice is a summary of the Click LICENSE file; the license in that file is
* legally binding.
*/
#include <click/config.h>
#include "aggcountervector.hh"
#include <click/handlercall.hh>
#include <click/args.hh>
#include <click/error.hh>
#include <click/packet_anno.hh>
#include <click/integers.hh> // for first_bit_set
#include <click/router.hh>
CLICK_DECLS
AggregateCounterVector::AggregateCounterVector() : _epoch(0)
{
}
AggregateCounterVector::~AggregateCounterVector()
{
}
int
AggregateCounterVector::configure(Vector<String> &conf, ErrorHandler *errh)
{
bool bytes = false;
bool ip_bytes = false;
bool packet_count = true;
bool extra_length = true;
uint32_t freeze_nnz, stop_nnz;
uint32_t mask = (uint32_t)-1;
uint64_t freeze_count, stop_count;
bool mark = false;
String call_nnz, call_count;
if (Args(conf, this, errh)
.read_mp("MASK", mask)
.read("MARK", mark)
.read("BYTES", bytes)
.read("IP_BYTES", ip_bytes)
.read("MULTIPACKET", packet_count)
.read("EXTRA_LENGTH", extra_length)
.complete() < 0)
return -1;
_bytes = bytes;
_ip_bytes = ip_bytes;
_use_packet_count = packet_count;
_use_extra_length = extra_length;
_mask = mask;
_mark = mark;
_nodes.resize(mask + 1);
return 0;
}
int
AggregateCounterVector::initialize(ErrorHandler *errh)
{
_active = true;
return 0;
}
void
AggregateCounterVector::cleanup(CleanupStage)
{
}
inline bool
AggregateCounterVector::update_batch(PacketBatch *batch)
{
if (!_active)
return false;
uint32_t last_agg = 0;
Node *n = 0;
FOR_EACH_PACKET(batch,p) {
// AGGREGATE_ANNO is already in host byte order!
uint32_t agg = AGGREGATE_ANNO(p) & _mask;
if (agg == last_agg && n) {
} else {
bool outdated =false;
n = &find_node(last_agg,p,outdated);
if (outdated)
return true;
if (!n)
return false;
last_agg = agg;
}
uint32_t amount;
if (!_bytes)
amount = 1 + (_use_packet_count ? EXTRA_PACKETS_ANNO(p) : 0);
else {
amount = p->length() + (_use_extra_length ? EXTRA_LENGTH_ANNO(p) : 0);
if (_ip_bytes && p->has_network_header())
amount -= p->network_header_offset();
}
n->count += amount;
#if COUNT_FLOWS
n->add_flow(AGGREGATE_ANNO(p));
#endif
}
return true;
}
inline bool
AggregateCounterVector::update(Packet *p)
{
if (!_active)
return false;
// AGGREGATE_ANNO is already in host byte order!
uint32_t agg = AGGREGATE_ANNO(p) & _mask;
bool outdated = false;
Node &n = find_node(agg, p, outdated);
if (outdated)
return true;
uint32_t amount;
if (!_bytes)
amount = 1 + (_use_packet_count ? EXTRA_PACKETS_ANNO(p) : 0);
else {
amount = p->length() + (_use_extra_length ? EXTRA_LENGTH_ANNO(p) : 0);
if (_ip_bytes && p->has_network_header())
amount -= p->network_header_offset();
}
#if COUNT_FLOWS
n.add_flow(AGGREGATE_ANNO(p));
#endif
n.count += amount;
return true;
}
void
AggregateCounterVector::push(int port, Packet *p)
{
port = !update(p);
output(noutputs() == 1 ? 0 : port).push(p);
}
Packet *
AggregateCounterVector::pull(int)
{
Packet *p = input(0).pull();
if (p && _active)
update(p);
return p;
}
#if HAVE_BATCH
void
AggregateCounterVector::push_batch(int port, PacketBatch *batch)
{
auto fnt = [this,port](Packet*p){return !update(p);};
CLASSIFY_EACH_PACKET(2,fnt,batch,[this](int port, PacketBatch* batch){ output(0).push_batch(batch);});
}
PacketBatch *
AggregateCounterVector::pull_batch(int port,unsigned max)
{
PacketBatch *batch = input(0).pull_batch(max);
if (batch && _active) {
FOR_EACH_PACKET(batch,p) {
update(p);
}
}
return batch;
}
#endif
enum {
AC_ACTIVE, AC_STOP,
};
String
AggregateCounterVector::read_handler(Element *e, void *thunk)
{
AggregateCounterVector *ac = static_cast<AggregateCounterVector *>(e);
switch ((intptr_t)thunk) {
default:
return "<error>";
}
}
int
AggregateCounterVector::write_handler(const String &data, Element *e, void *thunk, ErrorHandler *errh)
{
AggregateCounterVector *ac = static_cast<AggregateCounterVector *>(e);
String s = cp_uncomment(data);
switch ((intptr_t)thunk) {
case AC_ACTIVE: {
bool val;
if (!BoolArg().parse(s, val))
return errh->error("type mismatch");
ac->_active = val;
return 0;
}
case AC_STOP:
ac->_active = false;
ac->router()->please_stop_driver();
return 0;
default:
return errh->error("internal error");
}
}
void
AggregateCounterVector::add_handlers()
{
add_data_handlers("active", Handler::f_read | Handler::f_checkbox, &_active);
add_write_handler("active", write_handler, AC_ACTIVE);
add_write_handler("stop", write_handler, AC_STOP, Handler::f_button);
}
ELEMENT_REQUIRES(userlevel int64)
EXPORT_ELEMENT(AggregateCounterVector)
ELEMENT_MT_SAFE(AggregateCounterVector)
CLICK_ENDDECLS
| 22.951807 | 106 | 0.665267 |
2a91841d2ecf5ba60689bdd71a926067f8f69011 | 12,043 | cpp | C++ | psx/_dump_/43/_dump_c_src_/diabpsx/source/inv.cpp | maoa3/scalpel | 2e7381b516cded28996d290438acc618d00b2aa7 | [
"Unlicense"
] | 15 | 2018-06-28T01:11:25.000Z | 2021-09-27T15:57:18.000Z | psx/_dump_/43/_dump_c_src_/diabpsx/source/inv.cpp | maoa3/scalpel | 2e7381b516cded28996d290438acc618d00b2aa7 | [
"Unlicense"
] | 7 | 2018-06-29T04:08:23.000Z | 2019-10-17T13:57:22.000Z | psx/_dump_/43/_dump_c_src_/diabpsx/source/inv.cpp | maoa3/scalpel | 2e7381b516cded28996d290438acc618d00b2aa7 | [
"Unlicense"
] | 7 | 2018-06-28T01:11:34.000Z | 2020-05-23T09:21:48.000Z | // C:\diabpsx\SOURCE\INV.CPP
#include "types.h"
// address: 0x801558DC
// line start: 434
// line end: 435
void FreeInvGFX__Fv() {
}
// address: 0x801558E4
// line start: 440
// line end: 447
void InvDrawSlot__Fiii(int X, int Y, int Frame) {
// register: 2
// size: 0x28
register struct POLY_FT4 *Ft4;
}
// address: 0x80155968
// line start: 452
// line end: 483
void InvDrawSlotBack__FiiiiUc(int X, int Y, int W, int H, int Flag) {
// register: 4
// size: 0x28
register struct POLY_FT4 *Ft4;
}
// address: 0x80155BBC
// line start: 489
// line end: 502
void InvDrawItem__FiiiUci(int ItemX, int ItemY, int ItemNo, unsigned char StatFlag, int TransFlag) {
// register: 3
// size: 0x28
register struct POLY_FT4 *Ft4;
// register: 4
// size: 0x6C
register struct TextDat *TData;
}
// address: 0x80155C8C
// line start: 507
// line end: 552
void InvDrawSlots__Fv() {
// register: 16
register int Bx;
// register: 17
register int By;
}
// address: 0x80155F64
// line start: 562
// line end: 564
void PrintStat__FiiPcUc(int Y, int Txt0, char *Txt1, unsigned char Col) {
}
// address: 0x80156030
// line start: 569
// line end: 720
void DrawInvStats__Fv() {
// address: 0xFFFFFFC8
// size: 0x10
auto struct Dialog InvBack;
// register: 18
register char c;
// address: 0xFFFFFFD8
// size: 0xA
auto char chrstr[10];
// register: 17
register long mind;
// register: 16
register long maxd;
// register: 16
register int hper;
// register: 16
register int ac;
}
// address: 0x80156B4C
// line start: 725
// line end: 732
void DrawInvBack__Fv() {
// address: 0xFFFFFFE8
// size: 0x10
auto struct Dialog InvBack;
}
// address: 0x80156BD4
// line start: 737
// line end: 840
void DrawInvCursor__Fv() {
// register: 6
register int ItemX;
// register: 8
register int ItemY;
// register: 4
register int LoopX;
// register: 5
register int LoopY;
// register: 4
// size: 0x28
register struct POLY_FT4 *Ft4;
// register: 4
// size: 0x6C
register struct TextDat *TData;
}
// address: 0x801570B0
// line start: 846
// line end: 877
void DrawInvMsg__Fv() {
// register: 2
// size: 0x28
register struct POLY_FT4 *Ft4;
// address: 0xFFFFFFD8
// size: 0x8
auto struct RECT InfoRect;
// register: 3
register int InfoX;
// register: 16
register int InfoY;
// address: 0xFFFFFFE0
// size: 0x10
auto struct Dialog InvBack;
}
// address: 0x80157278
// line start: 883
// line end: 914
void DrawInvUnique__Fv() {
// register: 19
// size: 0x6C
register struct TextDat *ThisDat;
// register: 10
// size: 0x28
register struct POLY_FT4 *Ft4;
// register: 17
register int x;
// register: 16
register int y;
// register: 18
register int flip;
}
// address: 0x8015739C
// line start: 931
// line end: 935
void DrawInv__Fv() {
}
// address: 0x801573DC
// line start: 942
// line end: 1046
void DrawInvTSK__FP4TASK(struct TASK *T) {
// register: 18
register int omp;
// register: 19
register int osel;
// register: 16
// size: 0xE0
register struct CBlocks *BgBlocks;
}
// address: 0x80157720
// line start: 1052
// line end: 1256
void DoThatDrawInv__Fv() {
// register: 16
register int Loop;
// register: 3
register int ii;
// register: 9
register int ItemX;
// register: 5
register int ItemY;
// register: 6
register int ItemNo;
}
// address: 0x80157EE8
// line start: 1261
// line end: 1308
unsigned char AutoPlace__FiiiiUc(int pnum, int ii, int sx, int sy, int saveflag) {
// register: 5
register int i;
// register: 11
register int j;
// register: 4
register int xx;
// register: 10
register int yy;
// register: 16
register unsigned char done;
}
// address: 0x80158208
// line start: 1313
// line end: 1377
unsigned char SpecialAutoPlace__FiiiiUc(int pnum, int ii, int sx, int sy, int saveflag) {
// register: 5
register int i;
// register: 11
register int j;
// register: 4
register int xx;
// register: 10
register int yy;
// register: 16
register unsigned char done;
}
// address: 0x801585A4
// line start: 1382
// line end: 1475
unsigned char GoldAutoPlace__Fi(int pnum) {
// register: 16
register int i;
// register: 19
register int ii;
// register: 10
register int xx;
// register: 8
register int yy;
// register: 3
register long gt;
// register: 6
register unsigned char done;
}
// address: 0x80158A74
// line start: 1480
// line end: 1507
unsigned char WeaponAutoPlace__Fi(int pnum) {
}
// address: 0x80158D00
// line start: 1513
// line end: 1519
int SwapItem__FP10ItemStructT0(struct ItemStruct *a, struct ItemStruct *b) {
// address: 0xFFFFFF68
// size: 0x98
auto struct ItemStruct h;
}
// address: 0x80158DFC
// line start: 1526
// line end: 1933
void CheckInvPaste__Fiii(int pnum, int mx, int my) {
// register: 21
register int r;
// register: 23
register int sx;
// register: 30
register int sy;
// register: 16
register int i;
// register: 9
register int j;
// register: 7
register int xx;
// register: 10
register int yy;
// register: 8
register int ii;
// register: 17
register unsigned char done;
// register: 17
register unsigned char done2h;
// register: 20
register int il;
// register: 22
register int cn;
// register: 2
register int it;
// register: 19
register int iv;
// register: 5
register int ig;
// register: 5
register long gt;
// address: 0xFFFFFED8
// size: 0x98
auto struct ItemStruct tempitem;
}
// address: 0x8015AAE8
// line start: 1975
// line end: 2091
void CheckInvCut__Fiii(int pnum, int mx, int my) {
// register: 18
register int r;
// register: 8
register int ii;
// register: 8
register int iv;
}
// address: 0x8015B598
// line start: 2116
// line end: 2137
void RemoveInvItem__Fii(int pnum, int iv) {
}
// address: 0x8015B840
// line start: 2145
// line end: 2149
void RemoveSpdBarItem__Fii(int pnum, int iv) {
}
// address: 0x8015B934
// line start: 2157
// line end: 2161
void CheckInvScrn__Fv() {
}
// address: 0x8015B9AC
// line start: 2175
// line end: 2184
void CheckItemStats__Fi(int pnum) {
// register: 4
// size: 0x23A8
register struct PlayerStruct *p;
}
// address: 0x8015BA30
// line start: 2190
// line end: 2202
void CheckBookLevel__Fi(int pnum) {
// register: 6
register int slvl;
}
// address: 0x8015BB64
// line start: 2208
// line end: 2266
void CheckQuestItem__Fi(int pnum) {
}
// address: 0x8015BF8C
// line start: 2276
// line end: 2335
void InvGetItem__Fii(int pnum, int ii) {
// register: 5
register int j;
// register: 4
register int jj;
}
// address: 0x8015C288
// line start: 2342
// line end: 2477
void AutoGetItem__Fii(int pnum, int ii) {
// register: 16
register int i;
// register: 2
register int g;
// register: 20
register int w;
// register: 21
register int h;
// register: 4
register int idx;
// register: 17
register unsigned char done;
{
{
// register: 5
register int j;
// register: 2
register int jj;
}
}
}
// address: 0x8015CCF8
// line start: 2521
// line end: 2535
int FindGetItem__FiUsi(int idx, unsigned short ci, int iseed) {
// register: 8
register int i;
// register: 7
register int ii;
}
// address: 0x8015CDAC
// line start: 2541
// line end: 2602
void SyncGetItem__FiiiUsi(int x, int y, int idx, unsigned short ci, int iseed) {
// register: 16
register int ii;
{
{
// register: 5
register int j;
// register: 4
register int jj;
}
}
}
// address: 0x8015CF38
// line start: 2617
// line end: 2639
unsigned char TryInvPut__Fv() {
{
{
}
}
}
// address: 0x8015D100
// line start: 2669
// line end: 2769
int InvPutItem__Fiii(int pnum, int x, int y) {
// register: 16
register int ii;
// register: 23
register unsigned char done;
{
// register: 21
register int d;
{
// register: 16
register int dy;
{
{
{
{
{
{
{
// register: 18
register int l;
{
{
// register: 19
register int j;
{
// register: 20
register int yy;
{
// register: 17
register int i;
{
// register: 16
register int xx;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
// address: 0x8015D5A8
// line start: 2781
// line end: 2885
int SyncPutItem__FiiiiUsiUciiiiiUl(int pnum, int x, int y, int idx, int icreateinfo, int iseed, int Id, int dur, int mdur, int ch, int mch, int ivalue, unsigned long ibuff) {
// register: 16
register int ii;
// register: 17
register int d;
// register: 16
register int dy;
{
{
{
{
{
{
// register: 21
register unsigned char done;
{
// register: 18
register int l;
{
{
// register: 20
register int j;
{
// register: 19
register int yy;
{
// register: 17
register int i;
{
// register: 16
register int xx;
}
}
}
}
}
}
}
}
}
}
}
}
}
// address: 0x8015DB04
// line start: 2890
// line end: 2999
char CheckInvHLight__Fv() {
// register: 16
register int r;
// register: 19
register char rv;
// register: 17
// size: 0x98
register struct ItemStruct *pi;
// register: 18
// size: 0x23A8
register struct PlayerStruct *p;
{
{
// register: 17
register int nGold;
}
}
}
// address: 0x8015DE4C
// line start: 3006
// line end: 3029
void RemoveScroll__Fi(int pnum) {
// register: 5
register int i;
}
// address: 0x8015E030
// line start: 3035
// line end: 3057
unsigned char UseScroll__Fv() {
// register: 5
register int i;
}
// address: 0x8015E298
// line start: 3064
// line end: 3071
void UseStaffCharge__FP12PlayerStruct(struct PlayerStruct *ptrplr) {
}
// address: 0x8015E300
// line start: 3079
// line end: 3087
unsigned char UseStaff__Fv() {
}
// address: 0x8015E3C0
// line start: 3138
// line end: 3152
void StartGoldDrop__Fv() {
}
// address: 0x8015E4BC
// line start: 3161
// line end: 3247
unsigned char UseInvItem__Fii(int pnum, int cii) {
// register: 18
register int c;
// register: 3
register int idata;
// register: 3
register int it;
// register: 17
// size: 0x98
register struct ItemStruct *Item;
// register: 19
register unsigned char speedlist;
}
// address: 0x8015E9E0
// line start: 3253
// line end: 3265
void DoTelekinesis__Fv() {
}
// address: 0x8015EB08
// line start: 3272
// line end: 3291
long CalculateGold__Fi(int pnum) {
// register: 6
register int i;
// register: 9
register long gold;
}
// address: 0x8015EC40
// line start: 3305
// line end: 3312
unsigned char DropItemBeforeTrig__Fv() {
}
// address: 0x8015EC98
// line start: 3428
// line end: 3506
void ControlInv__Fv() {
}
// address: 0x8015EFA4
// line start: 3512
// line end: 3521
void InvGetItemWH__Fi(int Pos) {
}
// address: 0x8015F098
// line start: 3527
// line end: 3546
void InvAlignObject__Fv() {
}
// address: 0x8015F24C
// line start: 3553
// line end: 3573
void InvSetItemCurs__Fv() {
// register: 6
register int ItemNo;
}
// address: 0x8015F3DC
// line start: 3580
// line end: 3675
void InvMoveCursLeft__Fv() {
// register: 5
register int ItemInc;
// register: 16
register int OldPos;
}
// address: 0x8015F584
// line start: 3681
// line end: 3784
void InvMoveCursRight__Fv() {
// register: 4
register int ItemInc;
// register: 16
register int OldPos;
}
// address: 0x8015F838
// line start: 3789
// line end: 3882
void InvMoveCursUp__Fv() {
// register: 4
register int ItemInc;
// register: 16
register int OldPos;
}
// address: 0x8015FA30
// line start: 3887
// line end: 3987
void InvMoveCursDown__Fv() {
// register: 17
register int ItemInc;
// register: 16
register int OldPos;
}
| 16.633978 | 174 | 0.630242 |
2a95e492aa69efa777e391e9c118fc572e339acd | 7,859 | cc | C++ | Replicator/Worker.cc | bjornd/couchbase-lite-core | 5da4cc825021bb90be591ae4ab835be201333a0a | [
"Apache-2.0"
] | null | null | null | Replicator/Worker.cc | bjornd/couchbase-lite-core | 5da4cc825021bb90be591ae4ab835be201333a0a | [
"Apache-2.0"
] | null | null | null | Replicator/Worker.cc | bjornd/couchbase-lite-core | 5da4cc825021bb90be591ae4ab835be201333a0a | [
"Apache-2.0"
] | null | null | null | //
// Worker.cc
//
// Copyright (c) 2017 Couchbase, Inc 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 "Worker.hh"
#include "Replicator.hh"
#include "ReplicatorTypes.hh"
#include "c4Private.h"
#include "Logging.hh"
#include "StringUtil.hh"
#include "PlatformCompat.hh"
#include "BLIP.hh"
#include <sstream>
#if defined(__clang__) && !defined(__ANDROID__)
#include <cxxabi.h>
#endif
using namespace std;
using namespace fleece;
using namespace fleeceapi;
using namespace litecore::blip;
namespace litecore {
LogDomain SyncLog("Sync");
}
namespace litecore { namespace repl {
LogDomain SyncBusyLog("SyncBusy", LogLevel::Warning);
static void writeRedacted(Dict dict, stringstream &s) {
s << "{";
int n = 0;
for (Dict::iterator i(dict); i; ++i) {
if (n++ > 0)
s << ", ";
slice key = i.keyString();
s << key << ":";
if (key == slice(C4STR(kC4ReplicatorAuthPassword))) {
s << "\"********\"";
} else if (i.value().asDict()) {
writeRedacted(i.value().asDict(), s);
} else {
alloc_slice json( i.value().toJSON5() );
s << json;
}
}
s << "}";
}
Worker::Options::operator string() const {
static const char* kModeNames[] = {"disabled", "passive", "one-shot", "continuous"};
stringstream s;
if (push != kC4Disabled)
s << "Push=" << kModeNames[push] << ", ";
if (pull != kC4Disabled)
s << "Pull=" << kModeNames[pull] << ", ";
s << "Options={";
writeRedacted(properties, s);
s << "}";
return s.str();
}
Worker::Worker(blip::Connection *connection,
Worker *parent,
const Options &options,
const char *namePrefix)
:Actor( string(namePrefix) + connection->name() )
,Logging(SyncLog)
,_connection(connection)
,_parent(parent)
,_options(options)
,_status{(connection->state() >= Connection::kConnected) ? kC4Idle : kC4Connecting}
,_loggingID(connection->name())
{ }
Worker::Worker(Worker *parent,
const char *namePrefix)
:Worker(parent->_connection, parent, parent->_options, namePrefix)
{
}
Worker::~Worker() {
if (_important)
logStats();
logDebug("deleting %s [%p]", actorName().c_str(), this);
}
void Worker::sendRequest(blip::MessageBuilder& builder, MessageProgressCallback callback) {
if (callback) {
increment(_pendingResponseCount);
builder.onProgress = asynchronize([=](MessageProgress progress) {
if (progress.state >= MessageProgress::kComplete)
decrement(_pendingResponseCount);
callback(progress);
});
} else {
if (!builder.noreply)
warn("Ignoring the response to a BLIP message!");
}
assert(_connection);
_connection->sendRequest(builder);
}
#pragma mark - ERRORS:
static const char* const kErrorDomainNames[] = {
nullptr, "LiteCore", "POSIX", nullptr, "SQLite", "Fleece", "Network", "WebSocket"};
blip::ErrorBuf Worker::c4ToBLIPError(C4Error err) {
//FIX: Map common errors to more standard domains
if (!err.code)
return { };
return {slice(kErrorDomainNames[err.domain]),
err.code,
alloc_slice(c4error_getMessage(err))};
}
C4Error Worker::blipToC4Error(const blip::Error &err) {
if (!err.domain)
return { };
C4ErrorDomain domain = LiteCoreDomain;
int code = kC4ErrorRemoteError;
string domainStr = err.domain.asString();
const char* domainCStr = domainStr.c_str();
for (uint32_t d = 0; d <= WebSocketDomain; d++) {
if (kErrorDomainNames[d] && strcmp(domainCStr, kErrorDomainNames[d]) == 0) {
domain = (C4ErrorDomain)d;
code = err.code;
break;
}
}
return c4error_make(domain, code, err.message);
}
void Worker::gotError(const MessageIn* msg) {
auto err = msg->getError();
logError("Got error response: %.*s %d '%.*s'",
SPLAT(err.domain), err.code, SPLAT(err.message));
onError(blipToC4Error(err));
}
void Worker::gotError(C4Error err) {
alloc_slice message = c4error_getMessage(err);
logError("Got LiteCore error: %.*s (%d/%d)", SPLAT(message), err.domain, err.code);
onError(err);
}
void Worker::caughtException(const std::exception &x) {
logError("Threw C++ exception: %s", x.what());
onError(c4error_make(LiteCoreDomain, kC4ErrorUnexpectedError, slice(x.what())));
}
void Worker::onError(C4Error err) {
_status.error = err;
_statusChanged = true;
}
void Worker::gotDocumentError(slice docID, C4Error error, bool pushing, bool transient) {
_parent->gotDocumentError(docID, error, pushing, transient);
}
void Worker::finishedDocument(slice docID, bool pushing) {
addProgress({0, 0, 1});
// if (_notifyAllDocuments) // experimental
// gotDocumentError(docID, {}, pushing, true);
}
#pragma mark - ACTIVITY / PROGRESS:
void Worker::setProgress(C4Progress p) {
addProgress(p - _status.progress);
}
void Worker::addProgress(C4Progress p) {
if (p.unitsCompleted || p.unitsTotal || p.documentCount) {
_status.progressDelta += p;
_status.progress += p;
_statusChanged = true;
}
}
Worker::ActivityLevel Worker::computeActivityLevel() const {
if (eventCount() > 1 || _pendingResponseCount > 0)
return kC4Busy;
else
return kC4Idle;
}
// Called after every event; updates busy status & detects when I'm done
void Worker::afterEvent() {
bool changed = _statusChanged;
_statusChanged = false;
if (changed && _important) {
logVerbose("progress +%llu/+%llu, %llu docs -- now %llu / %llu, %llu docs",
_status.progressDelta.unitsCompleted, _status.progressDelta.unitsTotal,
_status.progressDelta.documentCount,
_status.progress.unitsCompleted, _status.progress.unitsTotal,
_status.progress.documentCount);
}
auto newLevel = computeActivityLevel();
if (newLevel != _status.level) {
_status.level = newLevel;
changed = true;
if (_important) {
auto name = kC4ReplicatorActivityLevelNames[newLevel];
if (_important > 1)
log("now %-s", name);
else
logVerbose("now %-s", name);
}
}
if (changed)
changedStatus();
_status.progressDelta = {0, 0};
}
void Worker::changedStatus() {
if (_parent)
_parent->childChangedStatus(this, _status);
if (_status.level == kC4Stopped)
_parent = nullptr;
}
} }
| 29.882129 | 95 | 0.56992 |
2a9962ad8459dd796b9b7bb9f7d2e9a7ff9d9fc4 | 9,610 | cpp | C++ | engine/map/map.cpp | fcarreiro/genesis | 48b5c3bac888d999fb1ae17f1a864b59e2c85bc8 | [
"MIT"
] | null | null | null | engine/map/map.cpp | fcarreiro/genesis | 48b5c3bac888d999fb1ae17f1a864b59e2c85bc8 | [
"MIT"
] | null | null | null | engine/map/map.cpp | fcarreiro/genesis | 48b5c3bac888d999fb1ae17f1a864b59e2c85bc8 | [
"MIT"
] | null | null | null | #include "../precompiled/stdafx.h"
#include "../engine/base.h"
#include "../../common/utility/ext_xml.h"
#include "../../common/utility/ext_util.h"
//////////////////////////////////////////////////////////////////////////
// CMap default constructor & destructor
//////////////////////////////////////////////////////////////////////////
CMap::CMap()
{
// sub-modules
m_pSky = NULL;
m_pSea = NULL;
m_pLandscape = NULL;
// variables
m_fVisibility = 0.0f;
m_fFogDensity = 0.0f;
m_fBarAlpha = 0.0f;
}
CMap::~CMap()
{
// free data
Free();
}
//////////////////////////////////////////////////////////////////////////
// Free() : Unloads all map-related data from memmory
//////////////////////////////////////////////////////////////////////////
void CMap::Free()
{
// destroy sky
delete m_pSky;
m_pSky = NULL;
// destroy sea
delete m_pSea;
m_pSea = NULL;
// destroy landscape
delete m_pLandscape;
m_pLandscape = NULL;
// reset variables
m_fVisibility = 0.0f;
m_fFogDensity = 0.0f;
m_fBarAlpha = 0.0f;
m_Timer.Update();
m_strTitle.erase();
// free players list
m_Players.clear();
}
//////////////////////////////////////////////////////////////////////////
// Load() : Loads a map
//////////////////////////////////////////////////////////////////////////
bool CMap::Load(int iMap, TMapWarp iProcedence)
{
// format the string
std::ostringstream temp;
temp << "maps/map" << iMap << ".pak";
// load the map
return Load(temp.str(), iProcedence);
}
//////////////////////////////////////////////////////////////////////////
// Load() : Loads a map
//////////////////////////////////////////////////////////////////////////
bool CMap::Load(const std::string & strFile, TMapWarp iProcedence)
{
// temporary variables
xmlDocPtr doc;
xmlNodePtr node;
std::string strTemp;
// map info variables
std::string name;
std::string music;
int length;
int hm_length;
int shoreline;
int min_stars;
int max_stars;
float fog_density;
float visibility;
float scale;
CVector3 vDayBaseColor;
CVector3 vNightBaseColor;
CVector3 vDayBaseAmbient;
CVector3 vNightBaseAmbient;
// PHASE 0: free everything
Free();
// PHASE 1: open xml file
strTemp = strFile + "/settings.xml";
doc = ext::xml_parse_file(strTemp);
// check for document
if(!doc) return false;
// get root element and check for map
node = xmlDocGetRootElement(doc);
if(!node || xmlStrcmp(node->name, (const xmlChar *) "map"))
{
xmlFreeDoc(doc);
return false;
}
// get directly to first node
node = node->children->next;
// retrieve map settings
name = ext::xml_get_string(doc, node, "name");
music = ext::xml_get_string(doc, node, "music");
length = ext::xml_get_int(doc, node, "length");
hm_length = ext::xml_get_int(doc, node, "heightmap_length");
shoreline = ext::xml_get_int(doc, node, "shoreline");
min_stars = ext::xml_get_int(doc, node, "min_stars");
max_stars = ext::xml_get_int(doc, node, "max_stars");
fog_density = ext::xml_get_float(doc, node, "fog_density");
visibility = ext::xml_get_float(doc, node, "visibility");
scale = ext::xml_get_float(doc, node, "scale");
// retrieve sky settings
vDayBaseColor.x = ext::xml_get_prop_float(doc, node, "sky_day_color", "r");
vDayBaseColor.y = ext::xml_get_prop_float(doc, node, "sky_day_color", "g");
vDayBaseColor.z = ext::xml_get_prop_float(doc, node, "sky_day_color", "b");
vNightBaseColor.x = ext::xml_get_prop_float(doc, node, "sky_night_color", "r");
vNightBaseColor.y = ext::xml_get_prop_float(doc, node, "sky_night_color", "g");
vNightBaseColor.z = ext::xml_get_prop_float(doc, node, "sky_night_color", "b");
vDayBaseAmbient.x = ext::xml_get_prop_float(doc, node, "sky_day_ambient", "r");
vDayBaseAmbient.y = ext::xml_get_prop_float(doc, node, "sky_day_ambient", "g");
vDayBaseAmbient.z = ext::xml_get_prop_float(doc, node, "sky_day_ambient", "b");
vNightBaseAmbient.x = ext::xml_get_prop_float(doc, node, "sky_night_ambient", "r");
vNightBaseAmbient.y = ext::xml_get_prop_float(doc, node, "sky_night_ambient", "g");
vNightBaseAmbient.z = ext::xml_get_prop_float(doc, node, "sky_night_ambient", "b");
// free file
xmlFreeDoc(doc);
// PHASE 2: Sky allocation
m_pSky = new CSky();
if(!m_pSky) return false;
// place slightly under the player
CVector3 vCenter = CVector3(0.0f, 20.0f, 0.0f);
// create sky
m_pSky->Create(200, 200, 20,
min_stars, max_stars,
0.5f, vCenter,
vNightBaseColor, vDayBaseColor,
vNightBaseAmbient, vDayBaseAmbient);
// set null time (night)
m_pSky->SetDayTime(0.0f);
// PHASE 3: Landscape allocation
m_pLandscape = new CLandscape();
if(!m_pLandscape) return false;
// create landsape
strTemp = strFile + "/texture.tex";
std::string strHeightmap = strFile + "/heightmap.raw";
if(!m_pLandscape->Create(hm_length, scale,
strHeightmap.c_str(), strTemp.c_str())) return false;
// PHASE 5: create the sea
if(shoreline)
{
// allocate sea
m_pSea = new CSea();
if(!m_pSea) return false;
// create sea
if(!m_pSea->Create(length, shoreline * scale, m_pLandscape))
return false;
}
/*
// PHASE 6: player posistion
float py;
// where do we come from?
switch(iProcedence)
{
case FROM_NORTH:
py = m_pLandscape.HeightAt(vPosition.x, iMapLength - 300) + 2;
g_Player->SetPosition(vPosition.x, py, 300 - iMapLength);
break;
case FROM_SOUTH:
py = m_pLandscape.HeightAt(vPosition.x, 300) + 2;
g_Player->SetPosition(vPosition.x, py, -300);
break;
case FROM_EAST:
py = m_pLandscape.HeightAt(iMapLength - 300, -vPosition.z) + 2;
g_Player->SetPosition(iMapLength - 300, py, vPosition.z);
break;
case FROM_WEST:
py = m_pLandscape.HeightAt(300, -vPosition.z) + 2;
g_Player->SetPosition(300, py, vPosition.z);
break;
}
*/
// PHASE 7: set local values
m_strTitle = name;
m_fVisibility = visibility;
m_fFogDensity = fog_density;
// no errors
return true;
}
//////////////////////////////////////////////////////////////////////////
// Render() : Renders the map
//////////////////////////////////////////////////////////////////////////
void CMap::Render()
{
float fFogColor[4];
bool bUnderWater = false;
// set fog parameters
if(bUnderWater)
{
// set fog color
fFogColor[0] = 0.1f;
fFogColor[1] = 0.1f;
fFogColor[2] = 0.3f;
fFogColor[3] = 1.0f;
// set fog options
glFogf(GL_FOG_DENSITY, m_fFogDensity);
glFogf(GL_FOG_START, 50.0f);
glFogf(GL_FOG_END, 100.0f);
glFogfv(GL_FOG_COLOR, fFogColor);
glEnable(GL_FOG);
}
else
{
// set fog color
fFogColor[0] = 0.6f;
fFogColor[1] = 0.6f;
fFogColor[2] = 0.6f;
fFogColor[3] = 1.0f;
// set fog options
glFogf(GL_FOG_DENSITY, m_fFogDensity);
glFogf(GL_FOG_START, m_fVisibility * 200.0f);
glFogf(GL_FOG_END, 300.0f);
glFogfv(GL_FOG_COLOR, fFogColor);
}
glEnable(GL_FOG);
// set player's viewpoint
g_Player->Look();
// update frustum
g_Frustum->CalculateFrustum();
// render sky
m_pSky->Render(g_Player->GetPosition(), m_pSea ? m_pSea->GetShoreLine() : 0.0f,
CVector3(fFogColor[0], fFogColor[1], fFogColor[2]));
// render landscape
m_pLandscape->Render();
// render sea
if(m_pSea) m_pSea->Render();
// render bar with name
if(m_fBarAlpha >= 0.0f) RenderBar();
glDisable(GL_FOG);
}
//////////////////////////////////////////////////////////////////////////
// RenderBar() : Draws the bar with the map title
//////////////////////////////////////////////////////////////////////////
void CMap::RenderBar()
{
static CFont barFont("blackletter", 20, FONT_TEXTURE);
// calculate alpha
if(m_fBarAlpha < 1.0f)
{
m_fBarAlpha += 0.01f;
m_Timer.Update();
}
else
{
if(m_Timer.GetTimePassed() >= 5000) m_fBarAlpha -= 0.01f;
}
// get width & height
static const int iWidth = ext::get_option_int("screen_width");
static const int iHeight = ext::get_option_int("screen_height");
// overlay begin
g_OpenGL->OverlayBegin(iWidth, iHeight, true);
// enable blending
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// set alpha
glColor4f(0.0f, 0.0f, 0.0f, m_fBarAlpha);
// draw bar background
glBegin(GL_TRIANGLE_STRIP);
glVertex2i(iWidth, 35);
glVertex2i(0, 35);
glVertex2i(iWidth, 0);
glVertex2i(0, 0);
glEnd();
// set white
glColor4f(1.0f, 1.0f, 1.0f, m_fBarAlpha);
// draw map name
barFont.Print(10, 8, m_strTitle);
// disable blending
glDisable(GL_BLEND);
// overlay ending
g_OpenGL->OverlayEnd();
}
//////////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////////
void CMap::AddPlayer(unsigned long dwId, CPlayer *p)
{
// if we *DON'T* have the player
if(m_Players.find(dwId) == m_Players.end())
{
// add it
m_Players.insert(std::make_pair(dwId, p));
}
}
//////////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////////
void CMap::RemovePlayer(unsigned long dwId)
{
// if we *DO* have the player
if(m_Players.find(dwId) != m_Players.end())
{
// delete it
m_Players.erase(dwId);
}
}
//////////////////////////////////////////////////////////////////////////
// End
//////////////////////////////////////////////////////////////////////////
| 25.695187 | 85 | 0.564828 |
2a9a1a0019e9f62a8bdfc75fd23b1c9918074f88 | 2,690 | cpp | C++ | Source/main.cpp | gandreadis/graph-coloring | 23379dc6390a854757a9d659fda8941d699707c3 | [
"MIT"
] | 23 | 2019-02-28T21:52:28.000Z | 2022-03-16T11:21:55.000Z | Source/main.cpp | gandreadis/graph-coloring | 23379dc6390a854757a9d659fda8941d699707c3 | [
"MIT"
] | 7 | 2018-10-03T05:53:32.000Z | 2020-10-04T07:34:06.000Z | Source/main.cpp | gandreadis/graph-coloring | 23379dc6390a854757a9d659fda8941d699707c3 | [
"MIT"
] | 7 | 2019-07-31T07:17:55.000Z | 2022-02-04T15:54:56.000Z | #include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <gflags/gflags.h>
#include "../Header/parse.hpp"
#include "../Header/coloring_algorithm.hpp"
#include "../Header/dsatur.hpp"
#include "../Header/mcs.hpp"
#include "../Header/lmxrlf.hpp"
#include "../Header/hybrid_dsatur.hpp"
#include "../Header/hybrid_lmxrlf.hpp"
using std::cerr;
using std::endl;
using GraphColoring::Dsatur;
using GraphColoring::Mcs;
using GraphColoring::Lmxrlf;
using GraphColoring::HybridDsatur;
using GraphColoring::HybridLmxrlf;
using GraphColoring::GraphColor;
DEFINE_string(graph, "", "The path to the graph file to be colored");
DEFINE_string(algorithm, "mcs", "The algorithm to execute on chosen benchmark (dsatur, mcs, lmxrlf, hybrid dsatur, hybrid lmxrlf)");
DEFINE_string(format, "", "The format of the input graph to be parsed (matrix, list)");
GraphColor* parse_algorithm_flag(map<string,vector<string>> graph) {
if(FLAGS_algorithm == "dsatur") {
return new Dsatur(graph);
} else if(FLAGS_algorithm == "mcs") {
return new Mcs(graph);
} else if(FLAGS_algorithm == "lmxrlf") {
return new Lmxrlf(graph);
} else if(FLAGS_algorithm == "hybrid-dsatur") {
return new HybridDsatur(graph);
} else if(FLAGS_algorithm == "hybird-lmxrlf") {
return new HybridLmxrlf(graph);
}
return nullptr;
}
int main(int argc, char** argv) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
string banner = "This program attempts to color an input graph using one of the available coloring algorithms";
string usage = "\tUsage: ./color --graph=path_to_graph --format=(m[atrix]|l[ist]) [--algorithm=(dsatur|mcs|lmxrlf|hybrid-dsatur|hybrid-lmxrlf)]";
gflags::SetUsageMessage(banner + "\n" + usage);
if(FLAGS_graph == "") {
gflags::ShowUsageWithFlags(argv[0]);
return -1;
}
map<string,vector<string>> input_graph;
if(FLAGS_format == "matrix" || FLAGS_format == "m") {
input_graph = parse_edge_matrix(FLAGS_graph);
} else if(FLAGS_format == "list" || FLAGS_format == "l") {
input_graph = parse_edge_list(FLAGS_graph);
} else {
gflags::ShowUsageWithFlags(argv[0]);
return -1;
}
GraphColor *graph = parse_algorithm_flag(input_graph);
if(!graph) {
gflags::ShowUsageWithFlags(argv[0]);
return -1;
}
if(input_graph.size() == 0) {
cerr << "Stopping due to failure to parse input file" << endl;
return -2;
}
graph->color();
graph->print_chromatic();
if(!graph->is_valid()) {
cerr << "Graph coloring is invalid" << endl;
return -1;
}
return 0;
}
| 30.91954 | 149 | 0.656506 |
2a9aa099e30b5c5cf3dfc1440168e39eeb1f2bd9 | 9,750 | cc | C++ | tensorflow/compiler/xla/service/interpreter/executable_base.cc | Nyrio/tensorflow | c111a7e2f5a6ecd3a06d47c63ff552ee0373985d | [
"Apache-2.0"
] | null | null | null | tensorflow/compiler/xla/service/interpreter/executable_base.cc | Nyrio/tensorflow | c111a7e2f5a6ecd3a06d47c63ff552ee0373985d | [
"Apache-2.0"
] | null | null | null | tensorflow/compiler/xla/service/interpreter/executable_base.cc | Nyrio/tensorflow | c111a7e2f5a6ecd3a06d47c63ff552ee0373985d | [
"Apache-2.0"
] | null | null | null | /* Copyright 2020 The TensorFlow Authors. 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 "tensorflow/compiler/xla/service/interpreter/executable_base.h"
#include <type_traits>
#include <vector>
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/maybe_owning_device_memory.h"
#include "tensorflow/compiler/xla/service/shaped_buffer.h"
#include "tensorflow/compiler/xla/service/transfer_manager.h"
#include "tensorflow/compiler/xla/shape_tree.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/stream_executor/lib/statusor.h"
#include "tensorflow/stream_executor/platform.h"
#include "tensorflow/stream_executor/stream.h"
#include "tensorflow/stream_executor/stream_executor_pimpl.h"
namespace xla {
namespace interpreter {
InterpreterExecutableBase::InterpreterExecutableBase(
std::unique_ptr<HloModule> hlo_module)
: Executable(std::move(hlo_module), /*hlo_profile_printer_data=*/nullptr,
/*hlo_profile_index_map=*/nullptr) {}
StatusOr<ExecutionOutput> InterpreterExecutableBase::ExecuteAsyncOnStream(
const ServiceExecutableRunOptions* run_options,
std::vector<ExecutionInput> arguments,
HloExecutionProfile* hlo_execution_profile) {
se::Stream* stream = run_options->stream();
se::StreamExecutor* executor = stream->parent();
const se::Platform* platform = executor->platform();
// Convert the ShapeTree to a ShapedBuffer. We do this so we can call
// TransferManager methods below.
std::vector<ShapedBuffer> argument_buffers;
argument_buffers.reserve(arguments.size());
int device_ordinal = run_options->device_ordinal();
if (device_ordinal < 0) {
device_ordinal = 0;
}
for (auto& argument : arguments) {
const ShapeTree<MaybeOwningDeviceMemory>& buffers = argument.Buffers();
argument_buffers.push_back(ShapedBuffer(buffers.shape(),
/*device_ordinal=*/device_ordinal));
auto in_it = buffers.begin();
auto out_it = argument_buffers.back().buffers().begin();
for (; in_it != buffers.end(); ++in_it, ++out_it) {
out_it->second = in_it->second.AsDeviceMemoryBase();
}
}
VLOG(1) << "Execute " << module().name();
if (VLOG_IS_ON(2)) {
for (const auto& a : argument_buffers) {
VLOG(2) << "-- argument " << a;
}
}
uint64_t start_micros = tensorflow::Env::Default()->NowMicros();
const HloComputation* computation = module().entry_computation();
if (computation->num_parameters() != arguments.size()) {
return tensorflow::errors::Internal(
"Mismatch between argument count and graph parameter count.");
}
// Check that the args have the right shape.
for (int64_t i = 0; i < computation->num_parameters(); ++i) {
const auto& expected_shape = computation->parameter_instruction(i)->shape();
const auto& actual_shape = argument_buffers[i].on_device_shape();
bool shape_match = true;
if (expected_shape.is_dynamic()) {
if (!ShapeUtil::DynamicArrayShapeIsCompatible(actual_shape,
expected_shape)) {
shape_match = false;
}
} else if (!Shape::Equal().MinorToMajorOnlyInLayout()(expected_shape,
actual_shape)) {
shape_match = false;
}
if (!shape_match) {
return InvalidArgument(
"Shape mismatch on parameter %d. Expected %s, but was %s.", i,
ShapeUtil::HumanStringWithLayout(expected_shape),
ShapeUtil::HumanStringWithLayout(actual_shape));
}
}
TF_ASSIGN_OR_RETURN(TransferManager * transfer_manager,
TransferManager::GetForPlatform(platform));
// Transform the ShapedBuffer arguments into literals which the evaluator
// consumes.
std::vector<Literal> arg_literals;
const int64_t num_parameters = computation->num_parameters();
arg_literals.reserve(num_parameters);
for (int64_t p = 0; p < num_parameters; ++p) {
TF_ASSIGN_OR_RETURN(Literal arg_literal,
transfer_manager->TransferLiteralFromDevice(
run_options->stream(), argument_buffers[p]));
const auto& expected_shape = computation->parameter_instruction(p)->shape();
if (expected_shape.is_dynamic()) {
// Expand the input literal to expected shape.
arg_literal = arg_literal.ToBoundedDynamic(expected_shape);
}
arg_literals.push_back(std::move(arg_literal));
}
TF_ASSIGN_OR_RETURN(Literal result_literal,
Evaluate(run_options, *computation, arg_literals));
// Shrink the generated dynamic shape into static shape.
result_literal = result_literal.ToStatic();
// Transform the result literal back into a ShapedBuffer.
const HloInputOutputAliasConfig& alias_config =
hlo_module_ == nullptr ? HloInputOutputAliasConfig()
: hlo_module_->input_output_alias_config();
TF_ASSIGN_OR_RETURN(ExecutionOutput result,
AllocateOutputMemoryWithInputReuse(
result_literal.shape(), alias_config,
run_options->allocator(), &arguments, stream));
TF_RETURN_IF_ERROR(transfer_manager->TransferLiteralToDevice(
run_options->stream(), result_literal, result.Result()));
uint64_t end_micros = tensorflow::Env::Default()->NowMicros();
ExecutionProfile* profile = run_options->run_options().execution_profile();
if (profile) {
const double nanoseconds = (end_micros - start_micros) * 1000.0;
profile->set_compute_time_ns(std::max(nanoseconds, 1.0));
}
MarkToBeReleasedArguments(absl::MakeSpan(arguments), result);
return std::move(result);
}
StatusOr<ExecutionOutput>
InterpreterExecutableBase::AllocateOutputMemoryWithInputReuse(
const Shape& shape, const HloInputOutputAliasConfig& alias_config,
se::DeviceMemoryAllocator* allocator,
std::vector<ExecutionInput>* arguments, se::Stream* stream) {
TF_RETURN_IF_ERROR(alias_config.ForEachAliasWithStatus(
[&](const ShapeIndex& output_index,
std::optional<HloInputOutputAliasConfig::Alias> alias) {
if (alias && alias->must_alias()) {
VLOG(1) << alias->ToString();
const MaybeOwningDeviceMemory& original_input =
(*arguments)[alias->parameter_number].Buffers().element(
alias->parameter_index);
if (!original_input.HasOwnership()) {
return InvalidArgument(
"An input was configured to be must-alias at "
"compile time but not donated at runtime: %s",
alias->ToString());
}
}
return ::tensorflow::OkStatus();
}));
se::StreamExecutor* executor = stream->parent();
const se::Platform* platform = executor->platform();
TF_ASSIGN_OR_RETURN(TransferManager * transfer_manager,
TransferManager::GetForPlatform(platform));
ExecutionOutput result(shape, allocator, executor->device_ordinal());
for (auto& pair : result.MutableResult()->buffers()) {
const ShapeIndex& result_index = pair.first;
se::DeviceMemoryBase& result_buffer = pair.second;
int64_t allocation_bytes =
transfer_manager->GetByteSizeRequirement(ShapeUtil::GetSubshape(
result.Result().on_device_shape(), result_index));
if (!ShapeUtil::IndexIsValid(alias_config.shape(), result_index)) {
return InternalError("result_index is invalid: %s",
result_index.ToString());
}
std::optional<HloInputOutputAliasConfig::Alias> alias =
alias_config.GetAliasedParameter(result_index);
if (alias) {
TF_RET_CHECK(alias->parameter_number < arguments->size());
ExecutionInput& input = (*arguments)[alias->parameter_number];
MaybeOwningDeviceMemory* device_memory =
input.MutableBuffer(alias->parameter_index);
if (auto owning = device_memory->Release()) {
se::DeviceMemoryBase device_memory_base = owning->Release();
*device_memory = device_memory_base;
result_buffer = device_memory_base;
result.AddAliasedIndex(result_index);
} else {
VLOG(2) << "An input was not reused since it is not donated "
<< alias->ToString();
}
}
if (result_buffer.is_null()) {
const Shape& on_device_shape = result.Result().on_device_shape();
const Shape& on_device_subshape =
ShapeUtil::GetSubshape(on_device_shape, result_index);
TF_ASSIGN_OR_RETURN(
auto allocated_buffer,
allocator->Allocate(executor->device_ordinal(), allocation_bytes,
/*retry_on_failure=*/true,
on_device_subshape.layout().memory_space()));
result_buffer = allocated_buffer.Release();
}
TF_RET_CHECK(allocation_bytes == 0 || result_buffer != nullptr);
}
TF_RETURN_IF_ERROR(
transfer_manager->WriteTupleIndexTables(stream, result.Result()));
return std::move(result);
}
} // namespace interpreter
} // namespace xla
| 41.845494 | 80 | 0.679487 |
2a9aafba3c5d61dd0f6dbd47296f721c6961ab66 | 1,844 | cpp | C++ | Interactive/InpaintingIterationRecord.cpp | jingtangliao/ff | d308fe62045e241a4822bb855df97ee087420d9b | [
"Apache-2.0"
] | 39 | 2015-01-01T07:59:51.000Z | 2021-10-01T18:11:46.000Z | Interactive/InpaintingIterationRecord.cpp | jingtangliao/ff | d308fe62045e241a4822bb855df97ee087420d9b | [
"Apache-2.0"
] | 1 | 2019-04-24T09:56:15.000Z | 2019-04-24T14:45:46.000Z | Interactive/InpaintingIterationRecord.cpp | jingtangliao/ff | d308fe62045e241a4822bb855df97ee087420d9b | [
"Apache-2.0"
] | 18 | 2015-01-11T15:10:23.000Z | 2022-02-24T20:02:10.000Z | /*=========================================================================
*
* Copyright David Doria 2011 daviddoria@gmail.com
*
* 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.txt
*
* 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 "InpaintingIterationRecord.h"
InpaintingIterationRecord::InpaintingIterationRecord()
{
}
NamedITKImageCollection& InpaintingIterationRecord::GetImages()
{
return this->Images;
}
// void InpaintingIterationRecord::SetDisplayed(const unsigned int imageId, const bool displayed)
// {
// this->Display[imageId] = displayed;
// }
//
// bool InpaintingIterationRecord::IsDisplayed(const unsigned int imageId) const
// {
// return this->Display[imageId];
// }
void InpaintingIterationRecord::AddImage(const NamedITKImage& namedImage, const bool display)
{
this->Images.push_back(namedImage);
this->Display.push_back(display);
}
// NamedITKImage InpaintingIterationRecord::GetImage(const unsigned int imageId) const
// {
// return this->Images[imageId];
// }
//
// NamedITKImage InpaintingIterationRecord::GetImageByName(const std::string& imageName) const
// {
// return this->Images.FindImageByName(imageName);
// }
//
// unsigned int InpaintingIterationRecord::GetNumberOfImages() const
// {
// return this->Images.size();
// }
| 30.229508 | 97 | 0.677332 |
2a9aeaa398ef199bf8d61594d1cedc358518551e | 211 | hpp | C++ | Source/panels/spell_book.hpp | stefanmielke/devilutionX | 074f191be80db73b1158dd137f7bee4c767e48ce | [
"Unlicense"
] | 2 | 2022-01-14T06:10:31.000Z | 2022-02-28T23:30:26.000Z | Source/panels/spell_book.hpp | stefanmielke/devilutionX | 074f191be80db73b1158dd137f7bee4c767e48ce | [
"Unlicense"
] | 1 | 2022-01-31T07:44:04.000Z | 2022-01-31T07:44:04.000Z | Source/panels/spell_book.hpp | stefanmielke/devilutionX | 074f191be80db73b1158dd137f7bee4c767e48ce | [
"Unlicense"
] | 1 | 2021-10-31T01:32:43.000Z | 2021-10-31T01:32:43.000Z | #pragma once
#include "engine/surface.hpp"
namespace devilution {
void InitSpellBook();
void FreeSpellBook();
void CheckSBook();
void DrawSpellBook(const Surface &out);
} // namespace devilution
| 16.230769 | 40 | 0.71564 |
2a9bf2fa5a310f0f082537d85ead466e28527096 | 7,189 | cpp | C++ | libjnc/src/library.cpp | java-native-call/jnc | 5fd9a08142650f40b95c4ddc8bb7b8de9d89476a | [
"Apache-2.0"
] | 1 | 2022-01-17T10:17:22.000Z | 2022-01-17T10:17:22.000Z | libjnc/src/library.cpp | java-native-call/jnc | 5fd9a08142650f40b95c4ddc8bb7b8de9d89476a | [
"Apache-2.0"
] | 10 | 2019-06-01T14:16:50.000Z | 2020-10-13T05:08:39.000Z | libjnc/src/library.cpp | java-native-call/jnc | 5fd9a08142650f40b95c4ddc8bb7b8de9d89476a | [
"Apache-2.0"
] | 2 | 2019-06-08T07:03:28.000Z | 2022-01-13T23:50:53.000Z | #include "jnc.h"
/* GetStringChars is not guaranteed to be null terminated */
#define DO_WITH_STRING_16(env, jstring, name, length, stat, ret) \
do { \
jsize length = CALLJNI(env, GetStringLength, jstring); \
if (unlikely(CALLJNI(env, ExceptionCheck))) return ret; \
jchar* name = (jchar*) malloc((length + 1) * sizeof (jchar)); \
checkOutOfMemory(env, name, ret); \
CALLJNI(env, GetStringRegion, jstring, 0, length, (jchar*) name); \
if (unlikely(CALLJNI(env, ExceptionCheck))) return ret; \
name[length] = 0; \
stat; \
free(name); \
} while(false)
#define DO_WITH_STRING_UTF(env, jstring, name, length, stat, ret) \
do { \
jsize length = CALLJNI(env, GetStringUTFLength, jstring); \
jsize strLen_ = CALLJNI(env, GetStringLength, jstring); \
if (unlikely(CALLJNI(env, ExceptionCheck))) return ret; \
char *name = (char*) malloc(length + 1); \
checkOutOfMemory(env, name, ret); \
CALLJNI(env, GetStringUTFRegion, jstring, 0, strLen_, name); \
if (unlikely(CALLJNI(env, ExceptionCheck))) return ret; \
name[length] = 0; \
stat; \
free(name); \
} while(false)
#ifdef _WIN32
#include <windows.h>
#define RTLD_LAZY 0
/* and zero to avoid unused parameter */
#define JNC2RTLD(x) ((x) & 0)
#define dlopen(path, mode) (path ? LoadLibraryExW(path, nullptr, mode) : GetModuleHandleW(nullptr))
#define dlsym(hModule, symbol) GetProcAddress(hModule, symbol)
#define dlclose(module) !FreeLibrary(module)
/* assume wchar_t on windows is 2 byte, compile error when not */
#if WCHAR_MAX != UINT16_MAX
#error Unsupported wchar_t type
#else /* WCHAR_MAX != UINT16_MAX */
#define DO_WITH_PLATFORM_STRING DO_WITH_STRING_16
#define DLOPEN_PARAM_TYPE LPWSTR
#endif /* WCHAR_MAX != UINT16_MAX */
#define throwByNameA(key, sig, env, name, value) \
do { \
jclass jc_ = CALLJNI(env, FindClass, name); \
if (unlikely(CALLJNI(env, ExceptionCheck))) break; \
jmethodID _jm = CALLJNI(env, GetMethodID, jc_, "<init>", "(" sig ")V"); \
if (unlikely(CALLJNI(env, ExceptionCheck))) break; \
jvalue jv_; \
jv_.key = value; \
auto jo_ = reinterpret_cast<jthrowable> \
(CALLJNI(env, NewObjectA, jc_, _jm, &jv_)); \
if (unlikely(CALLJNI(env, ExceptionCheck))) break; \
CALLJNI(env, Throw, jo_); \
CALLJNI(env, DeleteLocalRef, jo_); \
} while(false)
#define throwByNameString(...) throwByNameA(l, "Ljava/lang/String;", __VA_ARGS__)
static void throwByLastError(JNIEnv * env, const char * type) {
DWORD dw = GetLastError();
LPWSTR lpMsgBuf = nullptr;
if (unlikely(!FormatMessageW(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPWSTR) & lpMsgBuf,
0, nullptr))) {
throwByName(env, OutOfMemory, nullptr);
return;
}
// trust system call return value
// assume lpMsgBuf is not nullptr
size_t len = wcslen(lpMsgBuf);
if (likely(len > 0 && lpMsgBuf[len - 1] == '\n'))--len;
if (likely(len > 0 && lpMsgBuf[len - 1] == '\r'))--len;
jstring string = CALLJNI(env, NewString, (jchar*) lpMsgBuf, len);
LocalFree(lpMsgBuf);
if (unlikely(CALLJNI(env, ExceptionCheck))) return;
throwByNameString(env, type, string);
}
#else /* _WIN32 */
#include <dlfcn.h>
#define RTLD(name) RTLD_##name
#define DEFAULT_RTLD (RTLD(LAZY) | RTLD(LOCAL))
#define JNC2RTLD(x) \
(x) ? ( \
((x) & JNC_RTLD(LAZY) ? RTLD(LAZY) : 0) | \
((x) & JNC_RTLD(NOW) ? RTLD(NOW) : 0) | \
((x) & JNC_RTLD(LOCAL) ? RTLD(LOCAL) : 0) | \
((x) & JNC_RTLD(GLOBAL) ? RTLD(GLOBAL) : 0) \
) : DEFAULT_RTLD
#define HMODULE void*
#define DO_WITH_PLATFORM_STRING DO_WITH_STRING_UTF
#define DLOPEN_PARAM_TYPE char*
#define throwByLastError(env, type) \
do { \
const char * _msg = dlerror(); \
if (!_msg) _msg = "unknown dl-error"; \
throwByName(env, type, _msg); \
} while(false)
#ifndef RTLD_NOW
#define RTLD_NOW 0
#endif /* RTLD_NOW */
#ifndef RTLD_LAZY
#define RTLD_LAZY 1
#endif /* RTLD_LAZY */
#endif /* _WIN32 */
/*
* Class: jnc_provider_NativeMethods
* Method: dlopen
* Signature: (Ljava/lang/String;I)J
*/
EXTERNC JNIEXPORT jlong JNICALL
Java_jnc_provider_NativeMethods_dlopen
(JNIEnv *env, jobject UNUSED(self), jstring path, jint mode) {
HMODULE ret = nullptr;
if (unlikely(nullptr == path)) {
#ifdef __BIONIC__
ret = RTLD_DEFAULT;
#else
ret = dlopen(nullptr, RTLD_LAZY);
#endif
} else {
DO_WITH_PLATFORM_STRING(env, path, buf, len, ret = dlopen((DLOPEN_PARAM_TYPE) (void*) buf, JNC2RTLD(mode)), 0);
}
if (unlikely(nullptr == ret)) {
throwByLastError(env, UnsatisfiedLink);
}
return p2j(ret);
}
/*
* Class: jnc_provider_NativeMethods
* Method: dlsym
* Signature: (JLjava/lang/String;)J
*/
EXTERNC JNIEXPORT jlong JNICALL
Java_jnc_provider_NativeMethods_dlsym
(JNIEnv *env, jobject UNUSED(self), jlong lhandle, jstring symbol) {
HMODULE hModule = j2p(lhandle, HMODULE);
checkNullPointer(env, hModule, 0);
checkNullPointer(env, symbol, 0);
jlong ret = 0;
// TODO charset on windows is not utf8, are all symbol characters ASCII??
DO_WITH_STRING_UTF(env, symbol, psymbol, len, ret = p2j(dlsym(hModule, psymbol)), 0);
if (unlikely(ret == 0)) {
throwByLastError(env, UnsatisfiedLink);
}
return ret;
}
/*
* Class: jnc_provider_NativeMethods
* Method: dlclose
* Signature: (J)V
*/
EXTERNC JNIEXPORT void JNICALL
Java_jnc_provider_NativeMethods_dlclose
(JNIEnv *env, jobject UNUSED(self), jlong lhandle) {
HMODULE hModule = j2p(lhandle, HMODULE);
checkNullPointer(env, hModule, /*void*/);
#ifdef _WIN32
if (unlikely(GetModuleHandleW(nullptr) == (hModule))) return;
#elif defined(__BIONIC__)
if (hModule == RTLD_DEFAULT) return;
#endif
if (unlikely(dlclose(hModule))) {
throwByLastError(env, UnknownError);
}
}
| 38.44385 | 119 | 0.553763 |
2a9d40e665f2116b536fe4cc3d176f4edcc1ec46 | 413 | cpp | C++ | Dataset/Leetcode/valid/48/348.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/valid/48/348.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/valid/48/348.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
void XXX(vector<vector<int>>& matrix) {
int m=matrix.size(),n=matrix[0].size();
for(int i=0;i<m/2;++i)
for(int j=0;j<n;++j)
{
swap(matrix[i][j],matrix[m-i-1][j]);
}
for(int i=0;i<m;++i)
for(int j=i+1;j<n;++j)
{
swap(matrix[i][j],matrix[j][i]);
}
}
};
| 22.944444 | 52 | 0.389831 |
2a9dfbd70b1bbcdbe68b98864c70517cf93dc2e7 | 10,703 | cpp | C++ | tests/src/library.cpp | kstenerud/c-compact-time | b128d1298af83c7d37e3d055b7742d668863a26a | [
"MIT"
] | 1 | 2019-09-30T16:54:46.000Z | 2019-09-30T16:54:46.000Z | tests/src/library.cpp | kstenerud/c-compact-time | b128d1298af83c7d37e3d055b7742d668863a26a | [
"MIT"
] | null | null | null | tests/src/library.cpp | kstenerud/c-compact-time | b128d1298af83c7d37e3d055b7742d668863a26a | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include <compact_time/compact_time.h>
// #define KSLog_LocalMinLevel KSLOG_LEVEL_TRACE
#include <kslog/kslog.h>
TEST(Library, version)
{
const char* expected = "1.0.0";
const char* actual = ct_version();
ASSERT_STREQ(expected, actual);
}
static void fill_date(ct_date* date, int year, int month, int day)
{
memset(date, 0, sizeof(*date));
date->year = year;
date->month = month;
date->day = day;
}
static void fill_time(ct_time* time, int hour, int minute, int second, int nanosecond)
{
memset(time, 0, sizeof(*time));
time->hour = hour;
time->minute = minute;
time->second = second;
time->nanosecond = nanosecond;
}
static void fill_timestamp(ct_timestamp* timestamp, int year, int month, int day, int hour, int minute, int second, int nanosecond)
{
memset(timestamp, 0, sizeof(*timestamp));
fill_date(×tamp->date, year, month, day);
fill_time(×tamp->time, hour, minute, second, nanosecond);
}
static void fill_timezone_utc(ct_timezone* timezone)
{
timezone->type = CT_TZ_ZERO;
}
static void fill_timezone_named(ct_timezone* timezone, const char* name)
{
timezone->type = CT_TZ_STRING;
strcpy(timezone->as_string, name);
}
static void fill_timezone_loc(ct_timezone* timezone, const int latitude, const int longitude)
{
timezone->type = CT_TZ_LATLONG;
timezone->latitude = latitude;
timezone->longitude = longitude;
}
#define ASSERT_TIMEZONE_EQ(ACTUAL, EXPECTED) \
ASSERT_EQ((EXPECTED).type, (ACTUAL).type); \
if((EXPECTED).type == CT_TZ_STRING) { \
ASSERT_STREQ((EXPECTED).as_string, (ACTUAL).as_string); \
} else if((EXPECTED).type == CT_TZ_LATLONG) { \
ASSERT_EQ((EXPECTED).latitude, (ACTUAL).latitude); \
ASSERT_EQ((EXPECTED).longitude, (ACTUAL).longitude); \
}
#define ASSERT_DATE_EQ(ACTUAL, EXPECTED) \
ASSERT_EQ(EXPECTED.year, ACTUAL.year); \
ASSERT_EQ(EXPECTED.month, ACTUAL.month); \
ASSERT_EQ(EXPECTED.day, ACTUAL.day)
#define ASSERT_TIME_EQ(ACTUAL, EXPECTED) \
ASSERT_EQ(EXPECTED.hour, ACTUAL.hour); \
ASSERT_EQ(EXPECTED.minute, ACTUAL.minute); \
ASSERT_EQ(EXPECTED.second, ACTUAL.second); \
ASSERT_EQ(EXPECTED.nanosecond, ACTUAL.nanosecond); \
ASSERT_TIMEZONE_EQ(EXPECTED.timezone, ACTUAL.timezone)
#define ASSERT_DATE_ENCODE_DECODE(EXPECTED_DATE, ACTUAL_DATE, ...) \
std::vector<uint8_t> expected = __VA_ARGS__; \
std::vector<uint8_t> actual(ct_date_encoded_size(&EXPECTED_DATE)); \
int bytes_encoded = ct_date_encode(&EXPECTED_DATE, actual.data(), actual.size()); \
ASSERT_EQ(expected, actual); \
ASSERT_EQ(bytes_encoded, expected.size()); \
ct_date ACTUAL_DATE; \
memset(&ACTUAL_DATE, 0, sizeof(ACTUAL_DATE)); \
int bytes_decoded = ct_date_decode(actual.data(), actual.size(), &ACTUAL_DATE); \
ASSERT_EQ(bytes_decoded, expected.size()); \
ASSERT_DATE_EQ(ACTUAL_DATE, EXPECTED_DATE)
#define ASSERT_TIME_ENCODE_DECODE(EXPECTED_TIME, ACTUAL_TIME, ...) \
std::vector<uint8_t> expected = __VA_ARGS__; \
std::vector<uint8_t> actual(ct_time_encoded_size(&EXPECTED_TIME)); \
int bytes_encoded = ct_time_encode(&EXPECTED_TIME, actual.data(), actual.size()); \
ASSERT_EQ(expected, actual); \
ASSERT_EQ(bytes_encoded, expected.size()); \
ct_time ACTUAL_TIME; \
memset(&ACTUAL_TIME, 0, sizeof(ACTUAL_TIME)); \
int bytes_decoded = ct_time_decode(actual.data(), actual.size(), &ACTUAL_TIME); \
ASSERT_EQ(bytes_decoded, expected.size()); \
ASSERT_TIME_EQ(ACTUAL_TIME, EXPECTED_TIME)
#define ASSERT_TIMESTAMP_ENCODE_DECODE(EXPECTED_TIMESTAMP, ACTUAL_TIMESTAMP, ...) \
std::vector<uint8_t> expected = __VA_ARGS__; \
std::vector<uint8_t> actual(ct_timestamp_encoded_size(&EXPECTED_TIMESTAMP)); \
int bytes_encoded = ct_timestamp_encode(&EXPECTED_TIMESTAMP, actual.data(), actual.size()); \
ASSERT_EQ(expected, actual); \
ASSERT_EQ(bytes_encoded, expected.size()); \
ct_timestamp ACTUAL_TIMESTAMP; \
memset(&ACTUAL_TIMESTAMP, 0, sizeof(ACTUAL_TIMESTAMP)); \
int bytes_decoded = ct_timestamp_decode(actual.data(), actual.size(), &ACTUAL_TIMESTAMP); \
ASSERT_EQ(bytes_decoded, expected.size()); \
ASSERT_DATE_EQ(ACTUAL_TIMESTAMP.date, EXPECTED_TIMESTAMP.date); \
ASSERT_TIME_EQ(ACTUAL_TIMESTAMP.time, EXPECTED_TIMESTAMP.time)
#define TEST_DATE(SIGN, YEAR, MONTH, DAY, ...) \
TEST(CDate, date_utc_ ## YEAR ## _ ## MONTH ## _ ## DAY) \
{ \
ct_date date; \
fill_date(&date, SIGN YEAR, MONTH, DAY); \
ASSERT_DATE_ENCODE_DECODE(date, actual_date, __VA_ARGS__); \
}
#define TEST_TIME_TZ_UTC(HOUR, MINUTE, SECOND, NANOSECOND, ...) \
TEST(CDate, time_utc_ ## HOUR ## _ ## MINUTE ## _ ## SECOND ## _ ## NANOSECOND) \
{ \
ct_time time; \
fill_time(&time, HOUR, MINUTE, SECOND, NANOSECOND); \
fill_timezone_utc(&time.timezone); \
ASSERT_TIME_ENCODE_DECODE(time, actual_time, __VA_ARGS__); \
}
#define TEST_TIME_TZ_NAMED(HOUR, MINUTE, SECOND, NANOSECOND, TZ, ...) \
TEST(CDate, time_named_ ## HOUR ## _ ## MINUTE ## _ ## SECOND ## _ ## NANOSECOND) \
{ \
ct_time time; \
fill_time(&time, HOUR, MINUTE, SECOND, NANOSECOND); \
fill_timezone_named(&time.timezone, TZ); \
ASSERT_TIME_ENCODE_DECODE(time, actual_time, __VA_ARGS__); \
ASSERT_STREQ(actual_time.timezone.as_string, TZ); \
}
#define TEST_TIME_TZ_LOC(HOUR, MINUTE, SECOND, NANOSECOND, LAT, LONG, ...) \
TEST(CDate, time_loc_ ## HOUR ## _ ## MINUTE ## _ ## SECOND ## _ ## NANOSECOND) \
{ \
ct_time time; \
fill_time(&time, HOUR, MINUTE, SECOND, NANOSECOND); \
fill_timezone_loc(&time.timezone, LAT, LONG); \
ASSERT_TIME_ENCODE_DECODE(time, actual_time, __VA_ARGS__); \
ASSERT_EQ(time.timezone.latitude, LAT); \
ASSERT_EQ(time.timezone.longitude, LONG); \
}
#define TEST_TIMESTAMP_TZ_UTC(SIGN, YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, NANOSECOND, ...) \
TEST(CDate, timestamp_utc_ ## YEAR ## _ ## MONTH ## _ ## DAY ## _ ## HOUR ## _ ## MINUTE ## _ ## SECOND ## _ ## NANOSECOND) \
{ \
ct_timestamp timestamp; \
fill_timestamp(×tamp, SIGN YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, NANOSECOND); \
fill_timezone_utc(×tamp.time.timezone); \
ASSERT_TIMESTAMP_ENCODE_DECODE(timestamp, actual_timestamp, __VA_ARGS__); \
}
#define TEST_TIMESTAMP_TZ_NAMED(SIGN, YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, NANOSECOND, TZ, ...) \
TEST(CDate, timestamp_named_ ## YEAR ## _ ## MONTH ## _ ## DAY ## _ ## HOUR ## _ ## MINUTE ## _ ## SECOND ## _ ## NANOSECOND) \
{ \
ct_timestamp timestamp; \
fill_timestamp(×tamp, SIGN YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, NANOSECOND); \
fill_timezone_named(×tamp.time.timezone, TZ); \
ASSERT_TIMESTAMP_ENCODE_DECODE(timestamp, actual_timestamp, __VA_ARGS__); \
ASSERT_STREQ(actual_timestamp.time.timezone.as_string, TZ); \
}
#define TEST_TIMESTAMP_TZ_LOC(SIGN, YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, NANOSECOND, LAT, LONG, ...) \
TEST(CDate, timestamp_loc_ ## YEAR ## _ ## MONTH ## _ ## DAY ## _ ## HOUR ## _ ## MINUTE ## _ ## SECOND ## _ ## NANOSECOND) \
{ \
ct_timestamp timestamp; \
fill_timestamp(×tamp, SIGN YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, NANOSECOND); \
fill_timezone_loc(×tamp.time.timezone, LAT, LONG); \
ASSERT_TIMESTAMP_ENCODE_DECODE(timestamp, actual_timestamp, __VA_ARGS__); \
ASSERT_EQ(timestamp.time.timezone.latitude, LAT); \
ASSERT_EQ(timestamp.time.timezone.longitude, LONG); \
}
// ----
// Date
// ----
TEST_DATE( , 2000,1,1, {0x21, 0x00, 0x00})
TEST_DATE(-, 2000,12,21, {0x95, 0x7d, 0x3f})
// ----
// Time
// ----
TEST_TIME_TZ_UTC(8, 41, 05, 999999999, {0x47, 0x69, 0xf1, 0x9f, 0xac, 0xb9, 0x03})
TEST_TIME_TZ_UTC(14, 18, 30, 43000000, {0x73, 0x92, 0xb7, 0x02})
TEST_TIME_TZ_UTC(23, 6, 55, 8000, {0xbd, 0xc6, 0x8d, 0x00, 0x00})
TEST_TIME_TZ_NAMED(10, 10, 10, 0, "S/Tokyo", {0x50, 0x8a, 0x02, 0x0e, 'S','/','T','o','k','y','o'})
TEST_TIME_TZ_LOC(7, 45, 0, 1000000, -3876, 2730, {0x3a, 0x2d, 0x10, 0x00, 0xb9, 0xe1, 0xaa, 0x0a})
TEST_TIME_TZ_LOC(7, 45, 0, 2000000, -9000, -18000, {0x3a, 0x2d, 0x20, 0x00, 0xb1, 0xb9, 0xb0, 0xb9})
TEST_TIME_TZ_LOC(7, 45, 0, 3000000, 9000, 18000, {0x3a, 0x2d, 0x30, 0x00, 0x51, 0x46, 0x50, 0x46})
// ---------
// Timestamp
// ---------
TEST_TIMESTAMP_TZ_NAMED( , 2000,1,1,0,0,0,0, "Europe/Berlin", {0x00, 0x00, 0x08, 0x01, 00, 0x1a, 'E','u','r','o','p','e','/','B','e','r','l','i','n'})
TEST_TIMESTAMP_TZ_NAMED( , 2020,8,30,15,33,14,19577323, "S/Singapore", {0x3b, 0xe1, 0xf3, 0xb8, 0x9e, 0xab, 0x12, 0x00, 0x50, 0x16, 'S', '/', 'S', 'i', 'n', 'g', 'a', 'p', 'o', 'r', 'e'})
TEST_TIMESTAMP_TZ_LOC( , 2000,1,1,1,0,0,0,100,200, {0x00, 0x40, 0x08, 0x01, 0x00, 0xc9, 0x00, 0xc8, 0x00})
TEST_TIMESTAMP_TZ_LOC( , 2000,1,1,2,0,0,0,-100,-200, {0x00, 0x80, 0x08, 0x01, 0x00, 0x39, 0xff, 0x38, 0xff})
TEST_TIMESTAMP_TZ_UTC( , 2000,1,1,0,0,0, 0, {0x00, 0x00, 0x08, 0x01, 0x01})
TEST_TIMESTAMP_TZ_UTC( , 2000,1,1,1,0,0, 0, {0x00, 0x40, 0x08, 0x01, 0x01})
TEST_TIMESTAMP_TZ_UTC( , 2000,1,1,0,1,0, 0, {0x00, 0x01, 0x08, 0x01, 0x01})
TEST_TIMESTAMP_TZ_UTC( , 2000,1,1,0,0,1, 0, {0x04, 0x00, 0x08, 0x01, 0x01})
TEST_TIMESTAMP_TZ_UTC( , 2000,1,1,0,0,0, 1000000, {0x01, 0x00, 0x08, 0x11, 0x00, 0x01})
TEST_TIMESTAMP_TZ_UTC( , 2000,1,1,0,0,0,999000000, {0x01, 0x00, 0x08, 0x71, 0x3e, 0x01})
TEST_TIMESTAMP_TZ_UTC( , 2000,1,1,0,0,0, 999000, {0x02, 0x00, 0x08, 0x71, 0x3e, 0x00, 0x01})
TEST_TIMESTAMP_TZ_UTC( , 2000,1,1,0,0,0, 999, {0x03, 0x00, 0x08, 0x71, 0x3e, 0x00, 0x00, 0x00, 0x01})
TEST_TIMESTAMP_TZ_UTC( , 2009,1,1,0,0,0, 0, {0x00, 0x00, 0x08, 0x01, 0x25})
TEST_TIMESTAMP_TZ_UTC( , 3009,1,1,0,0,0, 0, {0x00, 0x00, 0x08, 0x01, 0x9f, 0x45})
TEST_TIMESTAMP_TZ_UTC(-, 50000,1,1,0,0,0, 0, {0x00, 0x00, 0x08, 0xc1, 0xd8, 0x7f})
// -------------
// Spec Examples
// -------------
// June 24, 2019, 17:53:04.180
TEST_TIMESTAMP_TZ_UTC(, 2019,6,24,17,53,4,180000000, {0x11, 0x75, 0xc4, 0x46, 0x0b, 0x4d})
// January 7, 1998, 08:19:20, Europe/Rome
TEST_TIMESTAMP_TZ_NAMED(, 1998,1,7,8,19,20,0, "E/Rome", {0x50, 0x13, 0x3a, 0x01, 0x06, 0x0c, 'E', '/', 'R', 'o', 'm', 'e'})
// August 31, 3190, 00:54:47.394129, location 59.94, 10.71
TEST_TIMESTAMP_TZ_LOC(, 3190,8,31,0,54,47,394129000, 5994, 1071, {0xbe, 0x36, 0xf8, 0x18, 0x39, 0x60, 0xa5, 0x18, 0xd5, 0x2e, 0x2f, 0x04})
// ------------
// CBE Examples
// ------------
TEST_DATE( , 2051,10,22, {0x56, 0x01, 0x66})
TEST_TIME_TZ_NAMED(13, 15, 59, 529435422, "E/Berlin", {0x6e, 0xcf, 0xee, 0xb1, 0xe8, 0xf8, 0x01, 0x10, 'E', '/', 'B', 'e', 'r', 'l', 'i', 'n'})
TEST_TIMESTAMP_TZ_LOC( , 1985, 10, 26, 1, 22, 16, 0, 3399, -11793, {0x40, 0x56, 0xd0, 0x0a, 0x3a, 0x8f, 0x1a, 0xef, 0xd1})
| 42.472222 | 187 | 0.669812 |
2aa173d69c8bd5fad30c1658343077bad18134fb | 5,215 | cpp | C++ | src/dtkWidgets/dtkWidgetsTagCloudView.cpp | eti-nne/dtk | b5095c7a181e7497391a6a1fa0bb37e71dfa4b56 | [
"BSD-3-Clause"
] | null | null | null | src/dtkWidgets/dtkWidgetsTagCloudView.cpp | eti-nne/dtk | b5095c7a181e7497391a6a1fa0bb37e71dfa4b56 | [
"BSD-3-Clause"
] | null | null | null | src/dtkWidgets/dtkWidgetsTagCloudView.cpp | eti-nne/dtk | b5095c7a181e7497391a6a1fa0bb37e71dfa4b56 | [
"BSD-3-Clause"
] | null | null | null | /* dtkWidgetsTagCloudView.cpp ---
*
* Author: Julien Wintz
* Created: Mon Apr 15 14:39:34 2013 (+0200)
* Version:
* Last-Updated: Mon Apr 15 14:44:56 2013 (+0200)
* By: Julien Wintz
* Update #: 7
*/
/* Change Log:
*
*/
#include "dtkWidgetsTagCloudDesc.h"
#include "dtkWidgetsTagCloudList.h"
#include "dtkWidgetsTagCloudView.h"
class dtkWidgetsTagCloudViewPrivate
{
public:
QWidget *parent;
public:
QEasingCurve::Type type;
public:
bool vertical;
bool wrap;
bool active;
public:
int speed;
int now;
int next;
public:
QPoint pnow;
public:
dtkWidgetsTagCloudList *list;
dtkWidgetsTagCloudDesc *desc;
};
dtkWidgetsTagCloudView::dtkWidgetsTagCloudView(QWidget *parent) : QStackedWidget(parent), d(new dtkWidgetsTagCloudViewPrivate)
{
d->list = new dtkWidgetsTagCloudList(this);
d->desc = new dtkWidgetsTagCloudDesc(this);
if (parent != 0)
d->parent = parent;
else
d->parent = this;
d->vertical = false;
d->speed = 500;
d->type = QEasingCurve::OutBack;
d->now = 0;
d->next = 0;
d->wrap = false;
d->pnow = QPoint(0,0);
d->active = false;
this->addWidget(d->list);
this->addWidget(d->desc);
connect(d->list, SIGNAL(itemClicked(const QString&)), this, SLOT(onItemClicked(const QString&)));
connect(d->desc, SIGNAL(back()), this, SLOT(slideInPrev()));
}
dtkWidgetsTagCloudView::~dtkWidgetsTagCloudView(void)
{
delete d;
d = NULL;
}
dtkWidgetsTagCloudList *dtkWidgetsTagCloudView::list(void)
{
return d->list;
}
dtkWidgetsTagCloudDesc *dtkWidgetsTagCloudView::desc(void)
{
return d->desc;
}
void dtkWidgetsTagCloudView::setDark(void)
{
d->list->setDark();
}
void dtkWidgetsTagCloudView::onItemClicked(const QString& description)
{
d->desc->setDescription(description);
this->slideInNext();
}
void dtkWidgetsTagCloudView::setVerticalMode(bool vertical)
{
d->vertical = vertical;
}
void dtkWidgetsTagCloudView::setSpeed(int speed)
{
d->speed = speed;
}
void dtkWidgetsTagCloudView::setAnimation(QEasingCurve::Type type)
{
d->type = type;
}
void dtkWidgetsTagCloudView::setWrap(bool wrap)
{
d->wrap = wrap;
}
void dtkWidgetsTagCloudView::slideInNext(void)
{
int now = currentIndex();
if (d->wrap||(now<count()-1))
slideInIdx(now+1);
}
void dtkWidgetsTagCloudView::slideInPrev(void)
{
int now = currentIndex();
if (d->wrap||(now>0))
slideInIdx(now-1);
}
void dtkWidgetsTagCloudView::slideInIdx(int idx, Direction direction)
{
if (idx>count()-1) {
direction = d->vertical ? Top2Bottom : Right2Left;
idx = (idx)%count();
} else if (idx<0) {
direction = d->vertical ? Bottom2Top: Left2Right;
idx = (idx+count())%count();
}
slideInWgt(widget ( idx ),direction);
}
void dtkWidgetsTagCloudView::slideInWgt(QWidget *newwidget, Direction direction)
{
if (d->active)
return;
else
d->active = true;
Direction directionhint;
int now = currentIndex();
int next = indexOf(newwidget);
if (now==next) {
d->active = false;
return;
}
else if (now<next){
directionhint = d->vertical ? Top2Bottom : Right2Left;
}
else {
directionhint = d->vertical ? Bottom2Top : Left2Right;
}
if (direction == Automatic) {
direction = directionhint;
}
int offsetx = frameRect().width();
int offsety = frameRect().height();
widget(next)->setGeometry ( 0, 0, offsetx, offsety );
if (direction==Bottom2Top) {
offsetx = 0;
offsety = -offsety;
}
else if (direction==Top2Bottom) {
offsetx = 0;
}
else if (direction==Right2Left) {
offsetx = -offsetx;
offsety = 0;
}
else if (direction==Left2Right) {
offsety = 0;
}
QPoint pnext = widget(next)->pos();
QPoint pnow = widget(now)->pos();
d->pnow = pnow;
widget(next)->move(pnext.x()-offsetx,pnext.y()-offsety);
widget(next)->show();
widget(next)->raise();
QPropertyAnimation *animnow = new QPropertyAnimation(widget(now), "pos");
animnow->setDuration(d->speed);
animnow->setEasingCurve(d->type);
animnow->setStartValue(QPoint(pnow.x(), pnow.y()));
animnow->setEndValue(QPoint(offsetx+pnow.x(), offsety+pnow.y()));
QPropertyAnimation *animnext = new QPropertyAnimation(widget(next), "pos");
animnext->setDuration(d->speed);
animnext->setEasingCurve(d->type);
animnext->setStartValue(QPoint(-offsetx+pnext.x(), offsety+pnext.y()));
animnext->setEndValue(QPoint(pnext.x(), pnext.y()));
QParallelAnimationGroup *animgroup = new QParallelAnimationGroup;
animgroup->addAnimation(animnow);
animgroup->addAnimation(animnext);
QObject::connect(animgroup, SIGNAL(finished()),this,SLOT(animationDoneSlot()));
d->next = next;
d->now = now;
d->active = true;
animgroup->start();
}
void dtkWidgetsTagCloudView::animationDoneSlot(void)
{
setCurrentIndex(d->next);
widget(d->now)->hide();
widget(d->now)->move(d->pnow);
d->active = false;
emit animationFinished();
}
| 22.286325 | 126 | 0.635858 |
2aa2010afd6be7798a9d1041d28c63f6924839fd | 1,777 | hpp | C++ | include/veriblock/entities/popdata.hpp | overcookedpanda/alt-integration-cpp | 7932e79a77d9514ca0e0354636e77fba1845d707 | [
"MIT"
] | null | null | null | include/veriblock/entities/popdata.hpp | overcookedpanda/alt-integration-cpp | 7932e79a77d9514ca0e0354636e77fba1845d707 | [
"MIT"
] | null | null | null | include/veriblock/entities/popdata.hpp | overcookedpanda/alt-integration-cpp | 7932e79a77d9514ca0e0354636e77fba1845d707 | [
"MIT"
] | null | null | null | // Copyright (c) 2019-2020 Xenios SEZC
// https://www.veriblock.org
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef ALT_INTEGRATION_INCLUDE_VERIBLOCK_ENTITIES_ALT_POP_TRANSACTION_HPP_
#define ALT_INTEGRATION_INCLUDE_VERIBLOCK_ENTITIES_ALT_POP_TRANSACTION_HPP_
#include <stdint.h>
#include <vector>
#include "veriblock/entities/atv.hpp"
#include "veriblock/entities/vtb.hpp"
#include "veriblock/serde.hpp"
#include "veriblock/slice.hpp"
namespace altintegration {
struct PopData {
int32_t version{};
std::vector<VbkBlock> vbk_context;
bool hasAtv{false};
ATV atv{};
std::vector<VTB> vtbs{};
/**
* Read VBK data from the stream and convert it to PopData
* @param stream data stream to read from
* @return PopData
*/
static PopData fromVbkEncoding(ReadStream& stream);
/**
* Read VBK data from the raw byte representation and convert it to PopData
* @param string data bytes to read from
* @return PopData
*/
static PopData fromVbkEncoding(Slice<const uint8_t> bytes);
/**
* Convert PopData to data stream using Vbk byte format
* @param stream data stream to write into
*/
void toVbkEncoding(WriteStream& stream) const;
/**
* Convert PopData to raw bytes data using Vbk byte format
* @return bytes data
*/
std::vector<uint8_t> toVbkEncoding() const;
/**
* Return true if contains endorsement data
* @return true if contains endorsement data
*/
bool containsEndorsements() const;
friend bool operator==(const PopData& a, const PopData& b) {
// clang-format off
return a.toVbkEncoding() == b.toVbkEncoding();
// clang-format on
}
};
} // namespace altintegration
#endif
| 25.385714 | 77 | 0.720878 |
2aa48b48ffb0b7acd42535b935e6941388b394ba | 700 | cpp | C++ | cpp/utility_declval.cpp | rpuntaie/c-examples | 385b3c792e5b39f81a187870100ed6401520a404 | [
"MIT"
] | null | null | null | cpp/utility_declval.cpp | rpuntaie/c-examples | 385b3c792e5b39f81a187870100ed6401520a404 | [
"MIT"
] | null | null | null | cpp/utility_declval.cpp | rpuntaie/c-examples | 385b3c792e5b39f81a187870100ed6401520a404 | [
"MIT"
] | null | null | null | /*
g++ --std=c++20 -pthread -o ../_build/cpp/utility_declval.exe ./cpp/utility_declval.cpp && (cd ../_build/cpp/;./utility_declval.exe)
https://en.cppreference.com/w/cpp/utility/declval
*/
#include <utility>
#include <iostream>
struct Default { int foo() const { return 1; } };
struct NonDefault
{
NonDefault() = delete;
int foo() const { return 1; }
};
int main()
{
decltype(Default().foo()) n1 = 1; // type of n1 is int
// decltype(NonDefault().foo()) n2 = n1; // error: no default constructor
decltype(std::declval<NonDefault>().foo()) n2 = n1; // type of n2 is int
std::cout << "n1 = " << n1 << '\n'
<< "n2 = " << n2 << '\n';
}
| 31.818182 | 132 | 0.568571 |
2aa9c6bd380b1487f674bc761d7efc628e018703 | 7,631 | cpp | C++ | UnitTests/CommandBuffer/src/CommandBuffer.cpp | Gpinchon/OCRA | 341bb07facc616f1f8a27350054d1e86f022d7c6 | [
"Apache-2.0"
] | null | null | null | UnitTests/CommandBuffer/src/CommandBuffer.cpp | Gpinchon/OCRA | 341bb07facc616f1f8a27350054d1e86f022d7c6 | [
"Apache-2.0"
] | null | null | null | UnitTests/CommandBuffer/src/CommandBuffer.cpp | Gpinchon/OCRA | 341bb07facc616f1f8a27350054d1e86f022d7c6 | [
"Apache-2.0"
] | null | null | null | #include <Instance.hpp>
#include <PhysicalDevice.hpp>
#include <Device.hpp>
#include <Queue/Queue.hpp>
#include <Queue/Fence.hpp>
#include <Queue/Semaphore.hpp>
#include <Command/Pool.hpp>
#include <Command/Buffer.hpp>
#include <Memory.hpp>
#include <Buffer.hpp>
#include <Common.hpp>
#include <future>
#include <iostream>
#define FENCE_VERSION
#define CHUNK_SIZE 256
#define SENTENCE0 std::string("Hello World !")
#define SENTENCE1 std::string("All your base are belong to us")
#define SWAP_NBR 1
using namespace OCRA;
#ifdef FENCE_VERSION
static inline void SubmitCommandBuffer(const Device::Handle& a_Device, const Queue::Handle& a_Queue, const Command::Buffer::Handle& a_CommandBuffer)
{
auto fence = Queue::Fence::Create(a_Device);
Queue::SubmitInfo submitInfo;
for (auto i = 0u; i < 1; ++i)
submitInfo.commandBuffers.push_back(a_CommandBuffer);
std::cout << "========== Command Buffer submit ==========\n";
//test multithreaded submit
std::async([a_Queue, submitInfo, fence] {
VerboseTimer("Queue Submission");
Queue::Submit(a_Queue, { submitInfo }, fence);
});
//make sure GPU is done
{
VerboseTimer bufferCopiesTimer("Buffer Copies");
Queue::Fence::WaitFor(a_Device, fence, std::chrono::nanoseconds(15000000));
}
//test for function time itself
{
auto timer = Timer();
int waitNbr = 100000;
for (auto i = 0; i < waitNbr; ++i)
Queue::Fence::WaitFor(a_Device, fence, std::chrono::nanoseconds(15000000));
std::cout << "Already signaled Fence mean wait time : " << timer.Elapsed().count() / double(waitNbr) << " nanoseconds\n";
}
std::cout << "===========================================\n";
std::cout << "\n";
}
#else //FENCE_VERSION
static inline void SubmitCommandBuffer(const Device::Handle& a_Device, const Queue::Handle& a_Queue, const Command::Buffer::Handle& a_CommandBuffer)
{
Queue::Semaphore::Info semaphoreInfo;
semaphoreInfo.type = Queue::Semaphore::Type::Timeline;
semaphoreInfo.initialValue = 0;
Queue::Semaphore::Handle semaphore = Queue::Semaphore::Create(a_Device, semaphoreInfo);
Queue::TimelineSemaphoreSubmitInfo timelineValues;
timelineValues.waitSemaphoreValues.push_back(1);
timelineValues.signalSemaphoreValues.push_back(2);
Queue::SubmitInfo submitInfo;
for (auto i = 0u; i < SWAP_NBR; ++i)
submitInfo.commandBuffers.push_back(a_CommandBuffer);
submitInfo.waitSemaphores.push_back(semaphore);
submitInfo.signalSemaphores.push_back(semaphore);
submitInfo.timelineSemaphoreValues = timelineValues;
std::cout << "========== Command Buffer submit ==========\n";
//test multithreaded submit
std::async([a_Queue, submitInfo] {
VerboseTimer("Queue Submission");
Queue::Submit(a_Queue, { submitInfo });
});
Queue::Semaphore::Signal(a_Device, semaphore, 1);
//make sure GPU is done
{
VerboseTimer bufferCopiesTimer("Buffer Copies");
Queue::Semaphore::Wait(a_Device, { semaphore }, { 2 }, std::chrono::nanoseconds(15000000));
}
std::cout << "===========================================\n";
std::cout << "\n";
}
#endif
static inline void RecordSwapCommandBuffer(
const Command::Buffer::Handle& a_CommandBuffer,
const Buffer::Handle& a_Buffer0,
const Buffer::Handle& a_Buffer1,
const Buffer::Handle& a_BufferT)
{
Command::Buffer::BeginInfo bufferbeginInfo;
bufferbeginInfo.flags = Command::Buffer::UsageFlagBits::None;
Command::Buffer::Begin(a_CommandBuffer, bufferbeginInfo);
{
Command::BufferCopyRegion copyRegions;
copyRegions.size = CHUNK_SIZE;
Command::CopyBuffer(a_CommandBuffer, a_Buffer0, a_BufferT, { copyRegions });
Command::CopyBuffer(a_CommandBuffer, a_Buffer1, a_Buffer0, { copyRegions });
Command::CopyBuffer(a_CommandBuffer, a_BufferT, a_Buffer1, { copyRegions });
}
Command::Buffer::End(a_CommandBuffer);
}
int main()
{
const auto instance = CreateInstance("Test_CommandBuffer");
const auto physicalDevice = Instance::EnumeratePhysicalDevices(instance).front();
const auto device = CreateDevice(physicalDevice);
const auto queueFamily = FindQueueFamily(physicalDevice, PhysicalDevice::QueueFlagsBits::Transfer);
const auto queue = Device::GetQueue(device, queueFamily, 0); //Get first available queue
const auto memory = AllocateMemory(physicalDevice, device, CHUNK_SIZE * 3, PhysicalDevice::MemoryPropertyFlagBits::HostVisible | PhysicalDevice::MemoryPropertyFlagBits::HostCached);
const auto commandPool = CreateCommandPool(device, queueFamily);
const auto commandBuffer = CreateCommandBuffer(device, commandPool, Command::Pool::AllocateInfo::Level::Primary);
//create test buffers
Buffer::Info bufferInfo;
bufferInfo.size = CHUNK_SIZE;
bufferInfo.usage = Buffer::UsageFlagBits::TransferDst | Buffer::UsageFlagBits::TransferSrc;
const auto buffer0 = Buffer::Create(device, bufferInfo);
const auto buffer1 = Buffer::Create(device, bufferInfo);
const auto bufferT = Buffer::Create(device, bufferInfo);
Buffer::BindMemory(device, buffer0, memory, CHUNK_SIZE * 0);
Buffer::BindMemory(device, buffer1, memory, CHUNK_SIZE * 1);
Buffer::BindMemory(device, bufferT, memory, CHUNK_SIZE * 2);
//write some value to the buffer0
{
Memory::MappedRange mappedRange;
mappedRange.memory = memory;
mappedRange.offset = CHUNK_SIZE * 0;
mappedRange.length = CHUNK_SIZE;
auto bufferPtr = Memory::Map(device, mappedRange);
memcpy(bufferPtr, SENTENCE0.c_str(), SENTENCE0.size());
Memory::Unmap(device, memory);
}
//write some value to the buffer1
{
Memory::MappedRange mappedRange;
mappedRange.memory = memory;
mappedRange.offset = CHUNK_SIZE * 1;
mappedRange.length = CHUNK_SIZE;
auto bufferPtr = Memory::Map(device, mappedRange);
memcpy(bufferPtr, SENTENCE1.c_str(), SENTENCE1.size());
Memory::Unmap(device, memory);
}
RecordSwapCommandBuffer(commandBuffer, buffer0, buffer1, bufferT);
SubmitCommandBuffer(device, queue, commandBuffer);
std::cout << "========== Sentences to swap ==========\n";
std::cout << " Sentence 0 : " << SENTENCE0 << "\n";
std::cout << " Sentence 1 : " << SENTENCE1 << "\n";
std::cout << "=======================================\n";
std::cout << "\n";
std::cout << "===== Check if sentences were swapped =====\n";
int success = 0;
{
Memory::MappedRange mappedRange;
mappedRange.memory = memory;
mappedRange.offset = CHUNK_SIZE * 0;
mappedRange.length = CHUNK_SIZE;
std::string buffer0String = (char*)Memory::Map(device, mappedRange);
success += buffer0String == SENTENCE1 ? 0 : 1;
std::cout << " Buffer 0 value : " << buffer0String << "\n";
Memory::Unmap(device, memory);
}
{
Memory::MappedRange mappedRange;
mappedRange.memory = memory;
mappedRange.offset = CHUNK_SIZE * 1;
mappedRange.length = CHUNK_SIZE;
std::string buffer1String = (char*)Memory::Map(device, mappedRange);
success += buffer1String == SENTENCE0 ? 0 : 1;
std::cout << " Buffer 1 value : " << buffer1String << "\n";
Memory::Unmap(device, memory);
}
std::cout << " " << (success == 0 ? "***** Great success ! *****" : "XXXXX Failure will not be tolerated. XXXXX") << "\n";
std::cout << "===========================================\n";
return success;
} | 42.394444 | 185 | 0.653781 |
2aada408721b2630a046925c15f9e820d8849fe7 | 2,813 | hpp | C++ | PlanetaMatchMakerServer/library/minimal_serializer/type_traits.hpp | InstytutXR/PlanetaMatchMaker | 4bf7503c031aea467c191c3a0d14c6dd58354f99 | [
"MIT"
] | 6 | 2019-08-15T09:48:55.000Z | 2021-07-25T14:40:59.000Z | PlanetaMatchMakerServer/library/minimal_serializer/type_traits.hpp | InstytutXR/PlanetaMatchMaker | 4bf7503c031aea467c191c3a0d14c6dd58354f99 | [
"MIT"
] | 43 | 2019-12-25T14:54:52.000Z | 2022-02-24T17:22:48.000Z | PlanetaMatchMakerServer/library/minimal_serializer/type_traits.hpp | InstytutXR/PlanetaMatchMaker | 4bf7503c031aea467c191c3a0d14c6dd58354f99 | [
"MIT"
] | 2 | 2020-05-06T20:14:44.000Z | 2020-06-02T21:21:10.000Z | /*
The MIT License (MIT)
Copyright (c) 2019 Cdec
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include <type_traits>
#include <memory>
#include <boost/tti/has_member_function.hpp>
namespace minimal_serializer {
class serializer;
// Remove const, volatile and reference
template <typename T>
using remove_cvref_t = std::remove_cv_t<std::remove_reference_t<T>>;
BOOST_TTI_HAS_MEMBER_FUNCTION(on_serialize)
template <typename T>
constexpr bool has_member_on_serialize_v = has_member_function_on_serialize<T, void, boost::mpl::vector<serializer&>
, boost::function_types::non_cv>::value;
struct has_global_on_serialize_impl {
template <class T>
static auto check(T&& x) -> decltype(on_serialize(std::declval<T&>(), std::declval<serializer&>()), std::true_type());
template <class T>
static std::false_type check(...);
};
template <class T>
constexpr bool has_global_on_serialize_v
= decltype(has_global_on_serialize_impl::check<T>(std::declval<T>()))::value;
template <class T>
constexpr bool is_serializable_v = has_global_on_serialize_v<T> && std::is_trivial_v<T>;
struct is_fixed_array_container_impl {
template <class T>
static auto check(T&& x) -> decltype(x.operator[](std::declval<size_t>()), x.max_size(), std::true_type{});
template <class T>
static auto check(...)->std::false_type;
};
template <class T>
struct is_fixed_array_container final : decltype(is_fixed_array_container_impl::check<T>(std::declval<T>())) {};
template <class T>
constexpr bool is_fixed_array_container_v = is_fixed_array_container<T>::value;
template <typename T>
struct is_shared_ptr : std::false_type {};
template <typename T>
struct is_shared_ptr<std::shared_ptr<T>> : std::true_type {};
template <typename T>
constexpr bool is_shared_ptr_v = is_shared_ptr<T>::value;
}
| 40.768116 | 460 | 0.766086 |
2aaecd0f7cb573a49029330dd55990710e46610b | 1,559 | cpp | C++ | src/cfiddle/resources/libcfiddle/cfiddle.cpp | NVSL/fiddle | 5edffa92caa0894057a449ad5accb23af748e657 | [
"MIT"
] | 2 | 2022-01-22T06:12:52.000Z | 2022-01-24T07:29:44.000Z | src/cfiddle/resources/libcfiddle/cfiddle.cpp | NVSL/cfiddle | 5edffa92caa0894057a449ad5accb23af748e657 | [
"MIT"
] | null | null | null | src/cfiddle/resources/libcfiddle/cfiddle.cpp | NVSL/cfiddle | 5edffa92caa0894057a449ad5accb23af748e657 | [
"MIT"
] | null | null | null | #include"cfiddle.hpp"
#include<sstream>
#include<string>
#include<fstream>
#include"DataSet.hpp"
#include"PerfCounter.hpp"
#include"walltime.h"
double start_time = 0.0;
DataSet * get_dataset();
extern "C"
void write_stats(char * filename) {
//std::cerr << "Writing to " << filename << "\n";
std::ofstream out(filename);
get_dataset()->write_csv(out);
out.close();
}
extern "C"
void clear_stats() {
get_dataset()->clear();
}
extern "C"
void clear_perf_counters() {
get_perf_counter()->clear();
}
extern "C"
void add_perf_counter(char * perf_counter_spec) {
get_perf_counter()->add_counter(perf_counter_spec);
}
extern "C"
bool are_perf_counters_available() {
return get_perf_counter()->performance_counters_enabled();
}
extern "C"
void start_measurement(const char *tag)
{
get_dataset()->start_new_row();
if (tag) {
get_dataset()->set("tag", tag);
}
start_time = wall_time();
get_perf_counter()->start();
}
extern "C"
void end_measurement()
{
double end_time = wall_time();
auto perf_counter = get_perf_counter();
auto dataset = get_dataset();
perf_counter->stop();
dataset->set("ET", end_time - start_time);
for(auto & v: perf_counter->get_counters()) {
dataset->set(v.name, v.value);
}
}
extern "C"
void restart_measurement(const char *tag)
{
end_measurement();
start_measurement(tag);
}
DataSet *get_dataset() {
static DataSet *ds = new DataSet();
return ds;
}
PerfCounter *get_perf_counter() {
static PerfCounter *pc = new PerfCounter();
return pc;
}
void __attribute__ ((constructor)) my_init(void) {
}
| 17.131868 | 59 | 0.702373 |
2aaf1393cc24731b2409395aefa6e0433686823d | 15,716 | cpp | C++ | mergeBathy/Error_Estimator/Bathy_Grid.cpp | Sammie-Jo/MergeBathy_Repos-MergeBathy_CPP | 9996f5ee40e40e892ce5eb77dc4bb67930af4005 | [
"CC0-1.0"
] | 4 | 2017-05-04T15:50:48.000Z | 2020-07-30T03:52:07.000Z | mergeBathy/Error_Estimator/Bathy_Grid.cpp | Sammie-Jo/MergeBathy_Repos-MergeBathy_CPP | 9996f5ee40e40e892ce5eb77dc4bb67930af4005 | [
"CC0-1.0"
] | null | null | null | mergeBathy/Error_Estimator/Bathy_Grid.cpp | Sammie-Jo/MergeBathy_Repos-MergeBathy_CPP | 9996f5ee40e40e892ce5eb77dc4bb67930af4005 | [
"CC0-1.0"
] | 2 | 2017-01-11T09:53:26.000Z | 2020-07-30T03:52:09.000Z | /**********************************************************************
* CC0 License
**********************************************************************
* MergeBathy - Tool to combine one or more bathymetric data files onto a single input grid.
* Written in 2015 by Samantha J.Zambo(samantha.zambo@gmail.com) while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by Todd Holland while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by Nathaniel Plant while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by Kevin Duvieilh while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by Paul Elmore while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by Will Avera while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by Brian Bourgeois while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by A.Louise Perkins while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by David Lalejini while employed by the U.S.Naval Research Laboratory.
* To the extent possible under law, the author(s) and the U.S.Naval Research Laboratory have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide.This software is distributed without any warranty.
* You should have received a copy of the CC0 Public Domain Dedication along with this software.If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
**********************************************************************/
#include "Bathy_Grid.h"
#include "GradientGrid.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include <list>
#include <math.h>
#include <list>
#include <vector>
#include "../grid.h"
#include "pointList.h"
#include "sHullDelaunay.h"
void Bathy_Grid::clear()
{
if(ptl != NULL)
{
delete ptl;
ptl = NULL;
}
if(tin != NULL)
{
delete tin;
tin = NULL;
}
size_t sz = interpGrids.size();
for(size_t i = 0; i < sz; ++i){
delete interpGrids[i];
interpGrids[i] = NULL;
}
interpGrids.clear();
ensemble_X.clear();//sam added 12/28/15 don't know why it wasnt already here
ensemble_Y.clear();//sam added 12/28/15 don't know why it wasnt already here
ensemble_Z.clear();//sam added 12/28/15 don't know why it wasnt already here
ensemble_H.clear();//sam added 12/28/15 don't know why it wasnt already here
ensemble_V.clear();//sam added 12/28/15 don't know why it wasnt already here
ensemble_U.clear();//sam added 12/28/15 don't know why it wasnt already here
ensemble_U2.clear();
ensemble_U3.clear();
ensemble_U4.clear();
ensemble_U5.clear();
}
void InterpGrid::clear()
{
if(ptlSurface != NULL)
{
delete ptlSurface;
ptlSurface = NULL;
}
if(grads != NULL)
{
delete grads;
grads = NULL;
}
triangles.clear();
e.clear();
e2.clear();
e3.clear();
e4.clear();
e5.clear();
z.clear();
s.clear();
//For Raster/Bag Interpolation SJZ
z0.clear();
e0.clear();
zK.clear();
eK.clear();
nei.clear();
rei.clear();
}
void Bathy_Grid::Construct_TinRaster(vector<double> *xInit, vector<double> *yInit, vector<double> *zInit, vector<double> *eInit)
{
//Each BathyGrid object gets its own copy.
ptl = new PointList();
ptl->setFromVectorsRaster(*xInit, *yInit, *zInit, *eInit/*, *z0Init, *e0Init, *zKInit, *eKInit*/);
tin = new SHullDelaunay();
std::cout << "Initializing triangle for Raster Conversion." << std::endl;
tin->insert(*ptl);
std::cout << "Done Converting to Raster." << std::endl;
}
void Bathy_Grid::Construct_TinRaster(vector<double> *xInit, vector<double> *yInit, vector<double> *zInit, vector<double> *eInit, vector<double> *neiInit, vector<double> *reiInit, vector<double> *z0Init, vector<double> *e0Init, vector<double> *zKInit, vector<double> *eKInit)
{
//Each BathyGrid object gets its own copy.
ptl = new PointList();
ptl->setFromVectorsRaster(*xInit, *yInit, *zInit, *eInit, *neiInit, *reiInit, *z0Init, *e0Init, *zKInit, *eKInit);
tin = new SHullDelaunay();
std::cout << "Initializing triangle for Raster Conversion." << std::endl;
tin->insert(*ptl);
std::cout << "Done Converting to Raster." << std::endl;
}
//void InterpGrid::estimateRaster(vector<double> *xSurf, vector<double> *ySurf, vector<double> *zSurf, const double& sH, const double& alpha, const double& deltaMin, SHullDelaunay* tin, string interpMethod)
//{
// ptlSurface = new PointList();
// ptlSurface->setFromVectors(*xSurf, *ySurf, *zSurf, tin->getOffsetX(), tin->getOffsetY());
//
// grads = new GradientGrid();
//
// //triangles = vector<Triangle>();
// triangles.reserve(ptlSurface->size());
//
// //Compute Gradients if depths are known.
// if(ptlSurface->getAvgZ() != 0.00)
// (*grads).calc_GradientGrid(*xSurf, *ySurf, *zSurf);
// //Compute Depths and Gradients
// else
// {
// this->scaleFactor = sH;
// this->alpha = alpha;
// this->deltaMin = deltaMin;
// vector<Point> pVec(tin->determinePingLocationInTriangle(*ptlSurface, sH, alpha, deltaMin,*grads, triangles, interpMethod));
//
// e.reserve(pVec.size());
// z.reserve(pVec.size());
// //s.reserve(pVec.size());
//
// for (int i = 0; i < (int) pVec.size(); i++)
// {
// e.push_back(pVec[i].u);
// z.push_back(pVec[i].z);
// //s.push_back(pVec[i].s);
// }
// }
//}
void Bathy_Grid::Construct_Tin(vector<double> *xInit, vector<double> *yInit, vector<double> *zInit, vector<double> *hInit, vector<double> *vInit)
{
//Each BathyGrid object gets its own copy.
ptl = new PointList();
ptl->setFromVectors(*xInit, *yInit, *zInit, *hInit, *vInit);
tin = new SHullDelaunay();
//std::cout << "Initializing triangle for error computation" << std::endl;
tin->insert(*ptl);
//std::cout << "Done initializing" << std::endl;
}
void InterpGrid::estimate(vector<double> *xSurf, vector<double> *ySurf, vector<double> *zSurf, const double& sH, const double& alpha, const double& deltaMin, SHullDelaunay* tin, string depthInterpMethod, string errorInterpMethod, string extrapMethod)
{
ptlSurface = new PointList();
ptlSurface->setFromVectors(*xSurf, *ySurf, *zSurf, tin->getOffsetX(), tin->getOffsetY());
grads = new GradientGrid();
//triangles = vector<Triangle>();
triangles.reserve(ptlSurface->size());
//Compute Gradients before-hand if depths are known.
//This catches if we pre-splined.
if(ptlSurface->getAvgZ() != 0.00)
(*grads).calc_GradientGrid(*xSurf, *ySurf, *zSurf);
//Compute Depths, Gradients, and uncertainties
this->scaleFactor = sH;
this->alpha = alpha;
this->deltaMin = deltaMin;
vector<Point> pVec(tin->determinePingLocationInTriangle(*ptlSurface, sH, alpha, deltaMin,*grads, triangles, depthInterpMethod, errorInterpMethod, extrapMethod));
e.reserve(pVec.size());
e2.reserve(pVec.size());
e3.reserve(pVec.size());
e4.reserve(pVec.size());
e5.reserve(pVec.size());
z.reserve(pVec.size());
s.reserve(pVec.size());
nei.reserve(pVec.size());
rei.reserve(pVec.size());
z0.reserve(pVec.size());
e0.reserve(pVec.size());
eK.reserve(pVec.size());
eK.reserve(pVec.size());
for (int i = 0; i < (int) pVec.size(); i++)
{
e.push_back(pVec[i].u);
e2.push_back(pVec[i].u2);
e3.push_back(pVec[i].u3);
e4.push_back(pVec[i].u4);
e5.push_back(pVec[i].u5);
z.push_back(pVec[i].z);
s.push_back(pVec[i].s);
// e.push_back(pVec[i].e);
nei.push_back(pVec[i].nei);
rei.push_back(pVec[i].rei);
z0.push_back(pVec[i].z0);
e0.push_back(pVec[i].e0);
zK.push_back(pVec[i].zK);
eK.push_back(pVec[i].eK);
}
}
//void InterpGrid::estimate(vector<double> *xSurf, vector<double> *ySurf, vector<double> *zSurf,vector<double> *eSurf,vector<double> *hSurf,vector<double> *vSurf, vector<double> *nmseiSurf,vector<double> *reiSurf,const double& sH, const double& alpha, const double& deltaMin, SHullDelaunay* tin, string interpMethod)
//{
// ptlSurface = new PointList();
// ptlSurface->setFromVectors(*xSurf, *ySurf, *zSurf, tin->getOffsetX(), tin->getOffsetY());
//
// grads = new GradientGrid();
//
// //triangles = vector<Triangle>();
// triangles.reserve(ptlSurface->size());
//
// //Compute Gradients if depths are known.
// if(ptlSurface->getAvgZ() != 0.00)
// (*grads).calc_GradientGrid(*xSurf, *ySurf, *zSurf);
// //Compute Depths and Gradients
// else
// {
// this->scaleFactor = sH;
// this->alpha = alpha;
// this->deltaMin = deltaMin;
// vector<Point> pVec(tin->determinePingLocationInTriangle(*ptlSurface, sH, alpha, deltaMin,*grads, triangles, interpMethod));
//
// e.reserve(pVec.size());
// e2.reserve(pVec.size());
// e3.reserve(pVec.size());
// e4.reserve(pVec.size());
// e5.reserve(pVec.size());
// z.reserve(pVec.size());
// s.reserve(pVec.size());
//
// for (int i = 0; i < (int) pVec.size(); i++)
// {
// e.push_back(pVec[i].u);
// e2.push_back(pVec[i].u2);
// e3.push_back(pVec[i].u3);
// e4.push_back(pVec[i].u4);
// e5.push_back(pVec[i].u5);
// z.push_back(pVec[i].z);
// s.push_back(pVec[i].s);
// }
// }
//}
bool Bathy_Grid::ensemble()
{
//This assumes that the correct grid is MBZ
//and the extra leading rows in GMT need to
//be ignored for calculations. These rows
//are in the beginning and provide extra lats for 1 extra lon.
//**This is believed to be fixed;verify before removing! SJZ 12/28/15.
int i, k, j, diff = 0;
double temp = 0;//,n,h;
InterpGrid *kInd;
int cnt = (const int)interpGrids.size();//3;// {MBZ,GMT,ALG} //
double sigma = 0, sigma2 = 0, sigma3 = 0, sigma4 = 0, sigma5 = 0;
vector<int> row, js, jsInit;
vector<int> xcols, yrows;
row.reserve(cnt);
xcols.reserve(cnt); //# rows (x) in each grid
yrows.reserve(cnt); //#cols (y) in each grid
js.reserve(cnt);
jsInit.reserve(cnt); //last index pos at in the set of uniq. new starting index
vector<InterpGrid*>::iterator it = interpGrids.begin();
vector<InterpGrid*>::iterator kIt;
k = (const int)(*it)->e.size();
vector<double> sortGrid1;
vector<double> sortGrid2;
vector<double> sortGrid3;
//find the max grid in order to know the number of extra rows to skip in GMT beginning
for(it = interpGrids.begin()++; it != interpGrids.end(); it++)
{
j = (const int)(*it)->e.size();
if(j < k)
{
k = j;
diff = k - j;
kInd = *&*it;
kIt = it;
}
//xcols and yrows are indices starting at 0. Add +1 to get dimensions.
xcols.push_back((const int)(((*it)->ptlSurface->getPositions().back().x
- (*it)->ptlSurface->getPositions().front().x)/(*it)->deltaMin)+1);
yrows.push_back((const int)(abs(((*it)->ptlSurface->getPositions().back().y
- (*it)->ptlSurface->getPositions().front().y)/(*it)->deltaMin))+1);
js.push_back((const int)(*it)->e.size()-1);
jsInit.push_back((const int)(*it)->e.size()-1);//beginning row index
}
vector<Point> mbzItXY;
vector<Point> algItXY;
vector<Point> gmtItXY;
int mbzflag = 0;
int masterGrid = 0;;
for(it = interpGrids.begin(); it != interpGrids.end(); it++)
{
switch((*it)->gtype)
{
case ALGSpline:
if(!mbzflag)
masterGrid = 1; //because there is only GMT then ALG
algItXY = (*it)->ptlSurface->getPositions();
break;
case GMT:
gmtItXY = (*it)->ptlSurface->getPositions();
break;//sorted by y min to max
case MBZ:
mbzflag = 1;
masterGrid = MBZ; //should be 0
mbzItXY = (*it)->ptlSurface->getPositions();
break;
}
}
it = interpGrids.begin();
ensemble_H.reserve(k);
ensemble_V.reserve(k);
ensemble_U.reserve(k);
ensemble_U2.reserve(k);
ensemble_U3.reserve(k);
ensemble_U4.reserve(k);
ensemble_U5.reserve(k);
vector<int> js2;
int j2;
js2.reserve(cnt);
int counter = 0;
int counter1 = 0, counter2 = 0;
int counter3 = 0, counter4 = 0;
js[0] = 0; //last visited index
jsInit[0] = 0; //index at beginning of current row visited
js2.assign(js.begin(),js.end());
//i = MBZ, k = GMT, j = same x,y loc in both
for(i =0; i < k; i++)
{
for(it = interpGrids.begin(); it != interpGrids.end(); it++)
{
switch((*it)->gtype)
{
case ALGSpline:
//ALGSpline j should be the same x,y as MBZ
//counter = 2;
j = xcols[counter]*(counter3)+counter4;
js[counter] = j;
counter3++;
if(counter3==abs(yrows[masterGrid]))
{
counter3=0;
counter4++;
}
if(counter4==xcols[masterGrid])
counter4=0;
break; //sorted by y max to min
case GMT:
//GMT j should be the same x,y as MBZ
//counter = 1;
j = xcols[counter]*(abs(yrows[counter])-counter1)-(xcols[counter]-counter2);
js[counter] = j;
counter1++;
if(counter1==abs(yrows[masterGrid]))
{
counter1=0;
counter2++;
}
if(counter2==xcols[masterGrid])
counter2=0;
break;//sorted by y min to max
case MBZ:
//j index is always i since MBZ is assumed to be correct.
//counter = 0;
j = i;
js[counter] = j;
break;//sorted by x min to max
}
if(mbzflag)
{
if(counter==ALGSpline){//2
if(! (mbzItXY[js[masterGrid]].x == algItXY[js[ALGSpline]].x && mbzItXY[js[masterGrid]].y == algItXY[js[ALGSpline]].y))
{
std::cout<< "Error: ALG and MBZ X, Y locations do not align!" << std::endl;
return false;
}
}
if(counter==GMT){//1
if(! (mbzItXY[js[masterGrid]].x == gmtItXY[js[GMT]].x && mbzItXY[js[masterGrid]].y == gmtItXY[js[GMT]].y))
{
std::cout<< "Error: GMT and MBZ X, Y locations do not align!" << std::endl;
return false;
}
}
}
else
{
if(counter==masterGrid){
if(! (algItXY[js[masterGrid]].x == gmtItXY[js[counter-1]].x && algItXY[js[masterGrid]].y == gmtItXY[js[counter-1]].y))
{
std::cout<< "Error: ALG and GMT X, Y locations do not align!" << std::endl;
return false;
}
}
}
sigma += (*it)->e[j];
sigma2 += (*it)->e2[j];
sigma3 += (*it)->e3[j];
sigma4 += (*it)->e4[j];
sigma5 += (*it)->e5[j];
counter++;
}
if(mbzflag)
{
ensemble_X.push_back(mbzItXY[js[masterGrid]].x);
ensemble_Y.push_back(mbzItXY[js[masterGrid]].y);
ensemble_Z.push_back(mbzItXY[js[masterGrid]].z);
}
else
{
ensemble_X.push_back(algItXY[js[masterGrid]].x);
ensemble_Y.push_back(algItXY[js[masterGrid]].y);
ensemble_Z.push_back(algItXY[js[masterGrid]].z);
}
ensemble_U.push_back(sigma/cnt);
ensemble_U2.push_back(sigma2/cnt);
ensemble_U3.push_back(sigma3/cnt);
ensemble_U4.push_back(sigma4/cnt);
ensemble_U5.push_back(sigma5/cnt);
//SJZ
temp = sqrt(pow(ensemble_U[i],2)/2);
ensemble_H.push_back(temp);
ensemble_V.push_back(temp);
sigma = 0, sigma2 = 0, sigma3 = 0, sigma4 = 0, sigma5 = 0; counter = 0;
}
//printensemble("../Output_Files/ensemble_Test.txt");
return true;
}
void Bathy_Grid::printensemble(string z_OutputFileName)
{
std::ofstream outFile;
//vector<InterpGrid*>::iterator it = interpGrids.begin();
//vector<Point> ps;
outFile.open(z_OutputFileName.c_str());
outFile.precision(6);
outFile.setf(std::ios::fixed, std::ios::floatfield);
std::cout << "Writing file to " << z_OutputFileName.c_str() << std::endl;
if (outFile.is_open())
{
//it = interpGrids.begin();
//ps=(*it)->ptlSurface->getPositions();
for(int i = 0; i < (int) ensemble_X.size(); i++){
outFile << ensemble_X[i] << "\t" << ensemble_Y[i] << "\t" << ensemble_Z[i]
<< "\t" << ensemble_U[i] << "\t" << ensemble_U2[i]
<< "\t" << ensemble_U3[i]<< "\t" << ensemble_U4[i]
<< "\t" << ensemble_U5[i] << std::endl;
}
}
outFile.close();
}
void Bathy_Grid::addToList( InterpGrid* g)
{
interpGrids.push_back(&*g);
}
//Get the first interpGrid of type g
InterpGrid* Bathy_Grid::getGrid(GridType g)
{
vector<InterpGrid*>::iterator it;
for(it = interpGrids.begin(); it != interpGrids.end(); it++)
if((*it)->gtype == g) return *it;
}
//Get all interpGrids
vector<InterpGrid*> Bathy_Grid::getGrids()
{
return interpGrids;
} | 31.62173 | 316 | 0.65042 |
2ab0701e04a3d9f65ebe3b2ea06ed955efcc6494 | 713 | cpp | C++ | src/ck/core/customstream.cpp | opala-studios/ck | dff23ff3912de114ef0c7ca57da6506f0a9bee51 | [
"Zlib"
] | 23 | 2020-02-23T23:20:22.000Z | 2021-12-30T16:09:23.000Z | src/ck/core/customstream.cpp | opala-studios/ck | dff23ff3912de114ef0c7ca57da6506f0a9bee51 | [
"Zlib"
] | 3 | 2020-03-17T05:50:40.000Z | 2020-10-12T18:18:44.000Z | src/ck/core/customstream.cpp | opala-studios/ck | dff23ff3912de114ef0c7ca57da6506f0a9bee51 | [
"Zlib"
] | 10 | 2020-03-02T15:07:32.000Z | 2022-01-29T03:34:55.000Z | #include "ck/core/customstream.h"
namespace Cki
{
CustomStream::CustomStream(CkCustomFile* file) :
m_file(file)
{}
CustomStream::~CustomStream()
{
delete m_file;
}
bool CustomStream::isValid() const
{
return m_file->isValid();
}
int CustomStream::read(void* buf, int bytes)
{
return m_file->read(buf, bytes);
}
int CustomStream::write(const void* buf, int bytes)
{
return 0;
}
int CustomStream::getSize() const
{
return m_file->getSize();
}
int CustomStream::getPos() const
{
return m_file->getPos();
}
void CustomStream::setPos(int pos)
{
m_file->setPos(pos);
}
void CustomStream::close()
{
if (m_file)
{
delete m_file;
m_file = NULL;
}
}
}
| 12.963636 | 51 | 0.645161 |
2ab7d255232ba4334fef0c3c8039f8ab4d62b85e | 23,760 | cc | C++ | pmlc/dialect/pxa/analysis/strides.cc | IsolatedMy/plaidml | 34538a9224e770fd79151105399d8d7ea08678c0 | [
"Apache-2.0"
] | null | null | null | pmlc/dialect/pxa/analysis/strides.cc | IsolatedMy/plaidml | 34538a9224e770fd79151105399d8d7ea08678c0 | [
"Apache-2.0"
] | 65 | 2020-08-24T07:41:09.000Z | 2021-07-19T09:13:49.000Z | pmlc/dialect/pxa/analysis/strides.cc | Flex-plaidml-team/plaidml | 1070411a87b3eb3d94674d4d041ed904be3e7d87 | [
"Apache-2.0"
] | null | null | null | // Copyright 2020, Intel Corporation
#include "pmlc/dialect/pxa/analysis/strides.h"
#include <algorithm>
#include <map>
#include <numeric>
#include <string>
#include <utility>
#include <vector>
#include "mlir/Dialect/Affine/IR/AffineValueMap.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/Support/DebugStringHelper.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/FormatVariadic.h"
#include "pmlc/dialect/pxa/analysis/affine_expr.h"
#include "pmlc/util/bilp/ilp_solver.h"
#include "pmlc/util/logging.h"
#include "pmlc/util/util.h"
using namespace mlir; // NOLINT
namespace pmlc::dialect::pxa {
const char *kBlockAndArgFormat = "^bb{0}:%arg{1}";
static std::string getUniqueName(Block *ref, BlockArgument arg) {
unsigned reverseDepth = 0;
while (arg.getOwner() != ref) {
ref = ref->getParentOp()->getBlock();
reverseDepth++;
}
return llvm::formatv(kBlockAndArgFormat, reverseDepth, arg.getArgNumber())
.str();
}
// Generally useful helper function
int64_t getIVStep(BlockArgument arg) {
// Check the kind of loop we are part of, and dispatch.
Operation *baseOp = arg.getOwner()->getParentOp();
size_t idx = arg.getArgNumber();
if (auto op = dyn_cast<AffineParallelOp>(baseOp)) {
auto steps = op.getSteps();
return steps[idx];
}
if (auto op = dyn_cast<AffineForOp>(baseOp)) {
return op.getStep();
}
llvm_unreachable("Get IV Step on non-IV");
}
static Optional<StrideInfo> flatten(MemRefType memRefType,
ArrayRef<StrideInfo> dimensional) {
assert(memRefType.getRank() == static_cast<int64_t>(dimensional.size()) &&
"memRef and dimensional rank mismatch");
// Get the memRef strides/offsets, and fail early if there is an issue.
int64_t offset;
SmallVector<int64_t, 4> strides;
if (failed(getStridesAndOffset(memRefType, strides, offset)))
return None;
// Fail if anything is dynamic.
if (ShapedType::isDynamicStrideOrOffset(offset) ||
llvm::any_of(strides, ShapedType::isDynamicStrideOrOffset))
return None;
StrideInfo flat{offset};
for (size_t i = 0; i < strides.size(); i++) {
flat += dimensional[i] * strides[i];
}
return flat;
}
// Multiply the offset and all strides by a constant.
StrideInfo &StrideInfo::operator*=(int64_t factor) {
offset *= factor;
if (factor == 0) {
strides.clear();
} else {
for (auto &kvp : strides) {
kvp.second *= factor;
}
}
return *this;
}
// StrideInfo addition operation.
StrideInfo &StrideInfo::operator+=(const StrideInfo &rhs) {
offset += rhs.offset;
for (const auto &kvp : rhs.strides) {
strides[kvp.first] += kvp.second;
}
// Remove entries with 0 for stride
for (auto &kvp : llvm::make_early_inc_range(strides)) {
if (kvp.second == 0) {
// DenseMap never resizes during erase, so iterators stay valid.
strides.erase(kvp.first);
}
}
return *this;
}
static BoundaryRegion getBoundaryRegion(Block *x, Block *y) {
while (x != y) {
Operation *parentOp = y->getParentOp();
if (!parentOp) {
return BoundaryRegion::Interior;
}
y = parentOp->getBlock();
if (!y) {
return BoundaryRegion::Interior;
}
}
return BoundaryRegion::Exterior;
}
StrideInfo StrideInfo::outer(BlockArgumentBoundaryFn fn) {
StrideInfo ret;
ret.offset = offset;
for (const auto &kvp : strides) {
if (fn(kvp.first) == BoundaryRegion::Exterior) {
ret.strides.insert(kvp);
}
}
return ret;
}
StrideInfo StrideInfo::inner(BlockArgumentBoundaryFn fn) {
StrideInfo ret;
ret.offset = 0;
for (const auto &kvp : strides) {
if (fn(kvp.first) == BoundaryRegion::Interior) {
ret.strides.insert(kvp);
}
}
return ret;
}
StrideInfo StrideInfo::outer(Block *block) {
return outer([block](BlockArgument arg) {
return getBoundaryRegion(arg.getOwner(), block);
});
}
StrideInfo StrideInfo::inner(Block *block) {
return inner([block](BlockArgument arg) {
return getBoundaryRegion(arg.getOwner(), block);
});
}
StrideRange StrideInfo::range() const {
StrideRange ret(offset);
for (const auto &kvp : strides) {
ret += StrideRange(kvp.first) * kvp.second;
}
return ret;
}
AffineValueExpr StrideInfo::toValueExpr(MLIRContext *ctx) const {
typedef std::pair<unsigned, unsigned> nestedArgNumber;
std::map<nestedArgNumber, BlockArgument> ordered;
for (auto kvp : strides) {
unsigned loopDepth = 0;
auto parent = kvp.first.getOwner()->getParentOp();
while (!dyn_cast<FuncOp>(parent)) {
loopDepth++;
parent = parent->getParentOp();
}
ordered.emplace(nestedArgNumber(loopDepth, kvp.first.getArgNumber()),
kvp.first);
}
auto tot = AffineValueExpr(ctx, offset);
for (auto item : llvm::enumerate(ordered)) {
auto blockArg = item.value().second;
Operation *baseOp = blockArg.getOwner()->getParentOp();
AffineValueExpr idx(blockArg);
if (auto op = dyn_cast<AffineParallelOp>(baseOp)) {
idx = idx - AffineValueExpr(op.getLowerBoundsValueMap(),
blockArg.getArgNumber());
} else if (auto op = dyn_cast<AffineForOp>(baseOp)) {
auto map = op.getLowerBoundMap();
idx = idx - AffineValueExpr(map.getResult(0), op.getLowerBoundOperands());
} else {
llvm_unreachable("Invalid op type in toValueMap");
}
int64_t step = getIVStep(blockArg);
auto si = strides.find(blockArg);
assert(si != strides.end());
assert(si->second % step == 0 && "Stride not divisible by step");
tot = tot + idx * (si->second / step);
}
return tot;
}
void StrideInfo::print(raw_ostream &os, Block *relative) const {
std::map<std::string, unsigned> ordered;
std::map<Block *, unsigned> blockIds;
for (auto kvp : strides) {
if (relative) {
ordered.emplace(getUniqueName(relative, kvp.first), kvp.second);
} else {
auto itNew = blockIds.emplace(kvp.first.getOwner(), blockIds.size());
ordered.emplace(llvm::formatv(kBlockAndArgFormat, itNew.first->second,
kvp.first.getArgNumber()),
kvp.second);
}
}
os << offset;
if (ordered.size()) {
os << ":[";
for (auto item : llvm::enumerate(ordered)) {
if (item.index())
os << ", ";
os << item.value().first << "=" << item.value().second;
}
os << ']';
}
}
std::ostream &operator<<(std::ostream &os, const StrideInfo &x) {
os << debugString(x);
return os;
}
AffineValueMap convertToValueMap(MLIRContext *ctx, ArrayRef<StrideInfo> dims) {
SmallVector<AffineValueExpr, 4> exprs;
for (const auto &si : dims) {
exprs.push_back(si.toValueExpr(ctx));
}
return jointValueMap(ctx, exprs);
}
static Optional<StrideInfo> computeStrideInfo(AffineParallelOp op,
BlockArgument arg) {
// Start at the lower bound, fail early if lower bound fails.
size_t idx = arg.getArgNumber();
auto out = computeStrideInfo(op.lowerBoundsMap().getResult(idx),
op.getLowerBoundsOperands());
if (!out)
return out;
// Otherwise add current index's contribution.
auto steps = op.getSteps();
out->strides[arg] += steps[idx];
return out;
}
static Optional<StrideInfo> computeStrideInfo(AffineForOp op,
BlockArgument arg) {
// Get lower bound
auto map = op.getLowerBoundMap();
// If it's not a simple lower bound, give up.
if (map.getNumResults() != 1)
return None;
// Compute the effect of the lower bound, fail early if needed.
auto out = computeStrideInfo(op.getLowerBoundMap().getResult(0),
op.getLowerBoundOperands());
if (!out)
return None;
// Otherwise add current index's contribution.
out->strides[arg] += op.getStep();
return out;
}
Optional<StrideInfo> computeStrideInfo(Value expr) {
// First, check for a block argument.
if (auto arg = expr.dyn_cast<BlockArgument>()) {
// Check the kind of loop we are part of, and dispatch.
Operation *baseOp = arg.getOwner()->getParentOp();
if (auto op = dyn_cast<AffineParallelOp>(baseOp))
return computeStrideInfo(op, arg);
if (auto op = dyn_cast<AffineForOp>(baseOp))
return computeStrideInfo(op, arg);
// Is this an assertable condition?
return None;
}
// Try for the affine apply case
if (auto op = dyn_cast_or_null<AffineApplyOp>(expr.getDefiningOp()))
return computeStrideInfo(op.getAffineMap().getResult(0),
op.getMapOperands());
IVLOG(1, "Failed stride info: op = " << debugString(expr));
return None;
}
Optional<StrideInfo> computeStrideInfo(AffineExpr expr, ValueRange args) {
// If we are a constant affine expression, it's a simple offset.
if (auto cexpr = expr.dyn_cast<AffineConstantExpr>())
return StrideInfo(cexpr.getValue());
// If we are a dim, it's just a Value.
if (auto dexpr = expr.dyn_cast<AffineDimExpr>())
return computeStrideInfo(args[dexpr.getPosition()]);
// Check the various binary ops.
if (auto bexpr = expr.dyn_cast<AffineBinaryOpExpr>()) {
if (bexpr.getKind() == AffineExprKind::Mul) {
// For multiplies, RHS should always be constant of symbolic, and symbols
// fail, so we cast to constant and give up if it doesn't work
auto rhs = bexpr.getRHS().dyn_cast<AffineConstantExpr>();
if (!rhs)
return None;
// Now compute the LHS via recursion
auto lhs = computeStrideInfo(bexpr.getLHS(), args);
if (!lhs)
return None;
// Multiply by the multiplier and return
*lhs *= rhs.getValue();
return lhs;
}
if (bexpr.getKind() == AffineExprKind::Add) {
// For add, we compute both sides and add them (presuming they both return
// valid outputs).
auto lhs = computeStrideInfo(bexpr.getLHS(), args);
if (!lhs)
return None;
auto rhs = computeStrideInfo(bexpr.getRHS(), args);
if (!rhs)
return None;
*lhs += *rhs;
return lhs;
}
}
// Fail for all other cases.
return None;
}
LogicalResult computeMultiDimStrideInfo(AffineMap map, ValueRange args,
SmallVectorImpl<StrideInfo> &results) {
for (auto expr : map.getResults()) {
auto dimStride = computeStrideInfo(expr, args);
if (!dimStride) {
return failure();
}
results.push_back(*dimStride);
}
return success();
}
LogicalResult computeMultiDimStrideInfo(const AffineValueMap &valueMap,
SmallVectorImpl<StrideInfo> &out) {
return computeMultiDimStrideInfo(valueMap.getAffineMap(),
valueMap.getOperands(), out);
}
Optional<StrideInfo> computeStrideInfo(MemRefType memRefType, AffineMap map,
ValueRange values) {
// Verify the in/out dimensions make sense.
assert(map.getNumResults() == memRefType.getRank());
assert(map.getNumInputs() == values.size());
// Get the memRef strides/offsets, and fail early if there is an issue.
int64_t memRefOffset;
SmallVector<int64_t, 4> memRefStrides;
if (failed(getStridesAndOffset(memRefType, memRefStrides, memRefOffset)))
return None;
// Fail if anything is dynamic.
if (ShapedType::isDynamicStrideOrOffset(memRefOffset))
return None;
for (size_t i = 0; i < memRefStrides.size(); i++) {
if (ShapedType::isDynamicStrideOrOffset(memRefStrides[i]))
return None;
}
StrideInfo out(memRefOffset);
for (size_t i = 0; i < map.getNumResults(); i++) {
// Collect the output for each dimension of the memRef.
auto perDim = computeStrideInfo(map.getResult(i), values);
// Fail if needed
if (!perDim)
return None;
// Otherwise multiply by memRef stride and add in
*perDim *= memRefStrides[i];
out += *perDim;
}
// Return the accumulated results
return out;
}
Optional<StrideInfo> computeStrideInfo(PxaLoadOp op) {
return computeStrideInfo(op.getMemRefType(), op.getAffineMap(),
op.getMapOperands());
}
Optional<StrideInfo> computeStrideInfo(PxaReduceOp op) {
return computeStrideInfo(op.getMemRefType(), op.getAffineMap(),
op.getMapOperands());
}
Optional<StrideInfo> computeStrideInfo(PxaVectorLoadOp op) {
return computeStrideInfo(op.getMemRefType(), op.getAffineMap(),
op.getMapOperands());
}
Optional<StrideInfo> computeStrideInfo(PxaVectorReduceOp op) {
return computeStrideInfo(op.getMemRefType(), op.getAffineMap(),
op.getMapOperands());
}
Optional<RelativeAccessPattern>
computeRelativeAccess(Value memref, ArrayRef<StrideRange> internalRanges,
const AffineValueMap &valueMap, Block *block) {
return computeRelativeAccess(
memref, internalRanges, valueMap, [block](BlockArgument arg) {
return getBoundaryRegion(arg.getOwner(), block);
});
}
Optional<RelativeAccessPattern>
computeRelativeAccess(Value memref, ArrayRef<StrideRange> internalRanges,
const AffineValueMap &valueMap,
BlockArgumentBoundaryFn fn) {
SmallVector<StrideInfo> strides;
if (failed(computeMultiDimStrideInfo(valueMap, strides)))
return None;
RelativeAccessPattern ret(memref);
for (auto it : llvm::zip(strides, internalRanges)) {
StrideInfo &si = std::get<0>(it);
const StrideRange &internalRange = std::get<1>(it);
ret.outer.push_back(si.outer(fn));
StrideInfo inner = si.inner(fn);
ret.inner.push_back(inner);
StrideRange range = inner.range() + internalRange;
if (!range.valid || range.minVal != 0)
return None;
ret.innerRanges.push_back(range);
ret.wholeInnerCount.push_back(range.maxVal - range.minVal + 1);
ret.innerCount.push_back(range.count());
}
return ret;
}
Optional<RelativeAccessPattern>
computeRelativeAccess(Operation *op, BlockArgumentBoundaryFn fn) {
ArrayRef<int64_t> vecSize;
Value memref;
SmallVector<StrideInfo> strides;
LogicalResult ok =
TypeSwitch<Operation *, LogicalResult>(op)
.Case<PxaLoadOp>([&](auto op) {
memref = op.memref();
return computeMultiDimStrideInfo(op.getAffineMap(),
op.getMapOperands(), strides);
})
.Case<PxaReduceOp>([&](auto op) {
memref = op.memref();
return computeMultiDimStrideInfo(op.getAffineMap(),
op.getMapOperands(), strides);
})
.Case<PxaVectorLoadOp>([&](auto op) {
memref = op.memref();
vecSize = op.getVectorType().getShape();
return computeMultiDimStrideInfo(op.getAffineMap(),
op.getMapOperands(), strides);
})
.Case<PxaVectorReduceOp>([&](auto op) {
memref = op.memref();
vecSize = op.getVectorType().getShape();
return computeMultiDimStrideInfo(op.getAffineMap(),
op.getMapOperands(), strides);
})
.Default([](auto op) { return failure(); });
if (failed(ok)) {
return None;
}
RelativeAccessPattern ret(memref);
for (size_t i = 0; i < strides.size(); i++) {
auto outer = strides[i].outer(fn);
ret.outer.push_back(outer);
auto inner = strides[i].inner(fn);
ret.inner.push_back(inner);
StrideRange range = inner.range();
if (i + vecSize.size() >= strides.size()) {
int64_t vecVal = vecSize[i + vecSize.size() - strides.size()];
if (vecVal > 1) {
StrideRange vecRange(0, vecVal - 1, 1);
range += vecRange;
}
}
if (!range.valid || range.minVal != 0) {
return None;
}
ret.innerRanges.push_back(range);
ret.wholeInnerCount.push_back(range.maxVal - range.minVal + 1);
ret.innerCount.push_back(range.count());
}
return ret;
}
Optional<RelativeAccessPattern> computeRelativeAccess(Operation *op,
Block *block) {
return computeRelativeAccess(op, [block](BlockArgument arg) {
return getBoundaryRegion(arg.getOwner(), block);
});
}
MemRefType RelativeAccessPattern::getMemRefType() const {
return memRef.getType().cast<MemRefType>();
}
SmallVector<int64_t, 4> RelativeAccessPattern::innerStride() const {
SmallVector<int64_t, 4> ret;
for (const StrideRange &range : innerRanges) {
ret.push_back(range.stride ? range.stride : 1);
}
return ret;
}
int64_t RelativeAccessPattern::totalInnerCount() const {
int64_t ret = 1;
for (auto range : innerRanges) {
ret *= range.count();
}
return ret;
}
int64_t RelativeAccessPattern::totalInnerBytes() const {
auto eltSize = llvm::divideCeil(getMemRefType().getElementTypeBitWidth(), 8);
return totalInnerCount() * eltSize;
}
Optional<StrideInfo> RelativeAccessPattern::flatOuter() const {
return flatten(getMemRefType(), outer);
}
Optional<StrideInfo> RelativeAccessPattern::flatInner() const {
return flatten(getMemRefType(), inner);
}
LogicalResult
RelativeAccessPattern::unionMerge(const RelativeAccessPattern &rhs) {
if (innerRanges.size() != rhs.innerRanges.size()) {
return failure();
}
for (unsigned i = 0; i < outer.size(); i++) {
if (outer[i] != rhs.outer[i]) {
return failure();
}
}
inner.clear();
innerCount.clear();
for (unsigned i = 0; i < innerRanges.size(); i++) {
innerRanges[i].unionEquals(rhs.innerRanges[i]);
innerCount.push_back(innerRanges[i].count());
}
return success();
}
// Use ILP to find out if two different iterations of the outer indexes (in
// allOuter) ever alias. To do this, we make a system with two copies of all
// the variable (outer + inner indexes) called _a and _b. Then we constrain the
// total effect of _a and the total effect of _b to be the same (i.e. both
// index sets access the same memory location). We also contrain the indexes to
// their appropriate ranges. Then we see if we can ever get the _a and _b
// version of any of the outer indexes to differ at all (by minimimizing oi_a -
// oi_b). If it's possible for them the differ, then (since _a + _b are
// symmetric), the minimum of the difference will be < 0.
bool RelativeAccessPattern::outerAlias(DenseSet<BlockArgument> allOuter) const {
using Poly = util::math::Polynomial<util::math::Rational>;
using RangeCons = util::math::RangeConstraint;
util::bilp::ILPSolver solver;
// We track each index as we add it, and make a string version since the
// Polynomial logic uses string names for variables.
DenseMap<BlockArgument, std::string> baToStr;
// The collection of constraints, this ends up including:
// 1) Range constraints for two copies (a + b).
// 2) Contraints requiring all dimensions of the access to be the same for
// both the a access and the b access.
std::vector<RangeCons> constraints;
// The collection of things to minimize. Here it's the differences of _a and
// _b for all outer indexes
std::vector<Poly> toMin;
// A lambda to convert a block arg to x<i>_a - x<i>_b for some unique i. If
// we haven't seen the block arg before, we add it to the map, along with
// range constraints for the _a and _b versions.
auto toDiff = [&](BlockArgument arg) {
std::string &str = baToStr[arg];
if (str.empty()) {
str = llvm::formatv("x{0}", baToStr.size());
StrideRange range(arg);
constraints.emplace_back(str + "_a", range.maxVal + 1);
constraints.emplace_back(str + "_b", range.maxVal + 1);
}
return Poly(str + "_a") - Poly(str + "_b");
};
// Add entries for all the outer indexes.
for (BlockArgument arg : allOuter) {
Poly diff = toDiff(arg);
toMin.emplace_back(diff);
}
// Go over each dimension of the access.
for (size_t i = 0; i < outer.size(); i++) {
// Compute the difference between the a + b versions of the access for this
// dimension of the access.
Poly totDiff;
for (const auto &kvp : outer[i].strides) {
Poly diff = toDiff(kvp.first);
totDiff += diff * kvp.second;
}
for (const auto &kvp : inner[i].strides) {
Poly diff = toDiff(kvp.first);
totDiff += diff * kvp.second;
}
// Constrain this diff to be the range [0, 1) in integers, i.e. constrain it
// to be exactly 0.
constraints.emplace_back(totDiff, 1);
}
IVLOG(3, "Doing a batch solve!");
IVLOG(3, "Constraints: " << constraints);
IVLOG(3, "toMin: " << toMin);
// Do the actual ILP solve.
auto res = solver.batch_solve(constraints, toMin);
// If any of the results have a minimum that is not exactly 0, it means the _a
// and _b version of that index can have two differnt values while still
// accessing the same point in the tensor. AKA we have hit an outer alias.
for (const auto &kvp : res) {
IVLOG(3, "obj_val = " << kvp.second.obj_val);
if (kvp.second.obj_val < 0) {
return true;
}
}
// Otherwise, all is well.
return false;
}
bool hasPerfectAliasing(const RelativeAccessPattern &aRap,
RelativeAccessPattern bRap,
const DenseMap<BlockArgument, BlockArgument> &bToA) {
IVLOG(3, "hasPerfectAliasing");
DenseSet<BlockArgument> allOuter;
for (const auto &kvp : bToA) {
allOuter.insert(kvp.second);
}
if (aRap.outerAlias(allOuter)) {
IVLOG(3, "outerAlias");
return false;
}
for (auto &si : bRap.outer) {
StrideInfo translated(si.offset);
for (const auto &kvp : si.strides) {
translated.strides[bToA.find(kvp.first)->second] = kvp.second;
}
si = translated;
}
if (aRap.outer.size() != bRap.outer.size()) {
IVLOG(3, "size mismatch: " << aRap.outer.size()
<< " != " << bRap.outer.size());
return false;
}
IVLOG(3, "aRap.innerCount: " << aRap.innerCount);
IVLOG(3, "bRap.innerCount: " << bRap.innerCount);
for (size_t i = 0; i < aRap.outer.size(); i++) {
const StrideInfo &aOuter = aRap.outer[i];
const StrideInfo &bOuter = bRap.outer[i];
const int64_t aInnerCount = aRap.innerCount[i];
const int64_t bInnerCount = bRap.innerCount[i];
if (aOuter != bOuter) {
IVLOG(3, "aOuter != bOuter");
return false;
}
if (aInnerCount != bInnerCount) {
IVLOG(3, "aInnerCount: " << aInnerCount
<< " != bInnerCount: " << bInnerCount);
return false;
}
}
return true;
}
double computeCacheMiss(double cacheElems,
SmallVector<int64_t, 4> tileDimensions,
SmallVector<int64_t, 4> tensorStrides) {
// Start with one cache line
double cacheLines = 1.0;
// Current accumulated maximum value
int64_t maxVal = 0;
// For each dimension (in sorted order)
assert(tileDimensions.size() == tensorStrides.size());
for (size_t i = tileDimensions.size(); i > 0; i--) {
// Compute gap per step
int64_t gap = std::abs(tensorStrides[i - 1]) - maxVal;
// Multiply current cache hits by size
cacheLines *= static_cast<double>(tileDimensions[i - 1]);
// Compute probability that cache line is shared across gap
double probShared = 0.0; // Assume it's never shared
if (cacheElems != 0.0 && gap < cacheElems) {
probShared = 1.0 - (gap / cacheElems);
}
// Subtract shared elements
cacheLines -= probShared * static_cast<double>(tileDimensions[i - 1] - 1);
// Update maxVal
maxVal += std::abs(tensorStrides[i - 1]) * (tileDimensions[i - 1] - 1);
}
return cacheLines;
}
} // namespace pmlc::dialect::pxa
| 32.151556 | 80 | 0.642971 |
2ababea0ef23519b966cf9c4d85576fa04565f94 | 3,055 | cpp | C++ | projects/InjectDLL/features/launch_no_deceleration.cpp | Mawex/wotw-client | 19cd13a5cfab0b504d5f1aa3da6eb11e631bd9ca | [
"MIT"
] | null | null | null | projects/InjectDLL/features/launch_no_deceleration.cpp | Mawex/wotw-client | 19cd13a5cfab0b504d5f1aa3da6eb11e631bd9ca | [
"MIT"
] | null | null | null | projects/InjectDLL/features/launch_no_deceleration.cpp | Mawex/wotw-client | 19cd13a5cfab0b504d5f1aa3da6eb11e631bd9ca | [
"MIT"
] | null | null | null | #include <dll_main.h>
#include <Il2CppModLoader/il2cpp_helpers.h>
#include <Il2CppModLoader/interception_macros.h>
using namespace modloader;
INJECT_C_DLLEXPORT bool in_menu();
namespace
{
constexpr float NO_AIR_DECELERATION_DURATION = 0.2f;
constexpr float NO_AIR_DECELERATION_RESET_DURATION = 0.2f;
float aim_timer = 0.0f;
float reset_timer = 0.0f;
STATIC_IL2CPP_BINDING(Game, UI, bool, get_MainMenuVisible, ());
STATIC_IL2CPP_BINDING(Game, UI, bool, get_WorldMapVisible, ());
STATIC_IL2CPP_BINDING(Game, UI, bool, get_ShardShopVisible, ());
STATIC_IL2CPP_BINDING(Game, UI, bool, IsInventoryVisible, ());
STATIC_IL2CPP_BINDING(, TimeUtility, float, get_deltaTime, ());
bool is_aiming_launch(app::CharacterAirNoDeceleration* this_ptr)
{
if (!in_menu())
{
if (aim_timer >= 0.0f)
aim_timer -= TimeUtility::get_deltaTime();
if (reset_timer >= 0.0f)
reset_timer -= TimeUtility::get_deltaTime();
}
auto* sein = get_sein();
auto* wrapper = sein->fields.Abilities->fields.ChargeJumpWrapper;
if (wrapper->fields.HasState && wrapper->fields.State->fields.m_state == app::SeinChargeJump_State__Enum_Aiming)
{
aim_timer = NO_AIR_DECELERATION_DURATION;
if (reset_timer > 0.0f)
this_ptr->fields.m_noDeceleration = true;
}
return aim_timer > 0.0f;
}
IL2CPP_INTERCEPT(, CharacterAirNoDeceleration, void, UpdateCharacterState, (app::CharacterAirNoDeceleration* this_ptr)) {
auto* platform_behaviour = this_ptr->fields.PlatformBehaviour;
auto* platform_movement = platform_behaviour->fields.PlatformMovement;
if (!il2cpp::invoke<app::Boolean__Boxed>(platform_movement, "get_IsSuspended")->fields)
{
if (il2cpp::invoke<app::Boolean__Boxed>(platform_movement, "get_IsOnGround")->fields)
this_ptr->fields.m_noDeceleration = false;
if (0.00000000 <= il2cpp::invoke<app::Single__Boxed>(platform_movement, "get_LocalSpeedY")->fields &&
platform_movement->fields._.Ceiling->fields.IsOn)
this_ptr->fields.m_noDeceleration = false;
auto* left_right_movement = platform_behaviour->fields.LeftRightMovement;
if (!left_right_movement->fields.m_settings->fields.LockInput &&
!is_aiming_launch(this_ptr) &&
left_right_movement->fields.m_horizontalInput != 0.0)
{
if (this_ptr->fields.m_noDeceleration)
reset_timer = NO_AIR_DECELERATION_RESET_DURATION;
this_ptr->fields.m_noDeceleration = false;
}
}
}
}
INJECT_C_DLLEXPORT bool in_menu()
{
return il2cpp::get_class<app::UI__Class>("Game", "UI")->static_fields->m_sMenu->fields.m_equipmentWhellVisible
|| UI::get_MainMenuVisible()
|| UI::get_WorldMapVisible()
|| UI::get_ShardShopVisible()
|| UI::IsInventoryVisible();
}
| 39.166667 | 125 | 0.656301 |
2abeb9fd1d1143367447899d45b6634125850eb3 | 903 | hpp | C++ | server/src/static_controller.hpp | R0nd/beefweb | d61e03eef97e089f36847ac34bba4ec59c1bb5cd | [
"MIT"
] | 148 | 2017-08-25T13:32:05.000Z | 2022-03-17T18:40:49.000Z | server/src/static_controller.hpp | R0nd/beefweb | d61e03eef97e089f36847ac34bba4ec59c1bb5cd | [
"MIT"
] | 160 | 2017-08-16T19:58:53.000Z | 2022-02-26T09:57:38.000Z | server/src/static_controller.hpp | R0nd/beefweb | d61e03eef97e089f36847ac34bba4ec59c1bb5cd | [
"MIT"
] | 24 | 2018-05-23T18:59:47.000Z | 2022-03-23T17:25:01.000Z | #pragma once
#include "controller.hpp"
#include "settings.hpp"
namespace msrv {
class Router;
class ContentTypeMap;
class WorkQueue;
class StaticController : public ControllerBase
{
public:
StaticController(
Request* request,
const Path& targetDir,
const ContentTypeMap& contentTypes);
~StaticController();
ResponsePtr getFile();
static void defineRoutes(
Router* router,
WorkQueue* workQueue,
SettingsDataPtr settings,
const ContentTypeMap& contentTypes);
static void defineRoutes(
Router* router,
WorkQueue* workQueue,
const std::string& urlPrefix,
const std::string& targetDir,
const ContentTypeMap& contentTypes);
private:
std::string getNormalizedPath();
ResponsePtr redirectToDirectory();
const Path& targetDir_;
const ContentTypeMap& contentTypes_;
};
}
| 20.066667 | 46 | 0.679956 |
2abf210d52a35dc06f0affc7c10b492d6f89479f | 291 | cpp | C++ | predavanje1/operatori3.cpp | Miillky/algoritmi_i_strukture_podataka | b5813f4b897a1370b6f46782bf5ecd474d0d7e20 | [
"MIT"
] | null | null | null | predavanje1/operatori3.cpp | Miillky/algoritmi_i_strukture_podataka | b5813f4b897a1370b6f46782bf5ecd474d0d7e20 | [
"MIT"
] | null | null | null | predavanje1/operatori3.cpp | Miillky/algoritmi_i_strukture_podataka | b5813f4b897a1370b6f46782bf5ecd474d0d7e20 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main()
{
int a = 3;
if (int b = 2; a > b) // javlja warning - init-statement in selection statements only available with -std=c++1z or -std=gnu++1z
{
cout << a << endl;
cout << b << endl;
}
cout << a << endl;
} | 24.25 | 131 | 0.549828 |
2abfff4018ad1033983ed6c1d115a1c39441d92c | 948 | cpp | C++ | lib/matrix/MatrixOperators.cpp | frndmg/simplex-method | 0fe509d43ac794344b5d95f7e4faacd0dd444d56 | [
"MIT"
] | 2 | 2019-11-25T20:54:56.000Z | 2019-11-25T20:55:20.000Z | lib/matrix/MatrixOperators.cpp | frndmg/simplex-method | 0fe509d43ac794344b5d95f7e4faacd0dd444d56 | [
"MIT"
] | null | null | null | lib/matrix/MatrixOperators.cpp | frndmg/simplex-method | 0fe509d43ac794344b5d95f7e4faacd0dd444d56 | [
"MIT"
] | 1 | 2019-11-25T23:14:18.000Z | 2019-11-25T23:14:18.000Z | #include "Matrix.hpp"
Matrix Matrix::operator+ () const {
return *this;
}
Matrix Matrix::operator- () const {
return operator*(-1.);
}
Matrix Matrix::operator+ (const real_t &scalar) const {
Matrix A = *this;
for(size_t y = 0; y < A.Height(); ++y)
A[y] = A[y] + scalar;
return A;
}
Matrix Matrix::operator- (const real_t &scalar) const {
return operator+ (-scalar);
}
Matrix Matrix::operator* (const real_t &scalar) const {
Matrix A = *this;
for(size_t y = 0; y < A.Height(); ++y)
A[y] = A[y] * scalar;
return A;
}
Matrix Matrix::operator/ (const real_t &scalar) const {
ASSERT_DOMAIN(scalar != 0.);
return operator* (1 / scalar);
}
Matrix Matrix::operator+ (const Matrix &B) const {
Matrix A = *this;
ASSERT_DOMAIN(A.Width() == B.Width() && A.Height() == B.Height());
for(size_t y = 0; y < Height(); ++y)
A[y] = A[y] + B[y];
return A;
}
Matrix Matrix::operator- (const Matrix &B) const {
return operator+ (-B);
}
| 19.346939 | 67 | 0.619198 |
2ac265cf382f478e608bd8422b037015ab3bcd7e | 1,949 | hpp | C++ | include/crab/cfg/cfg_operators.hpp | LinerSu/crab | 8f3516f4b4765f4a093bb3c3a94ac2daa174130c | [
"Apache-2.0"
] | null | null | null | include/crab/cfg/cfg_operators.hpp | LinerSu/crab | 8f3516f4b4765f4a093bb3c3a94ac2daa174130c | [
"Apache-2.0"
] | null | null | null | include/crab/cfg/cfg_operators.hpp | LinerSu/crab | 8f3516f4b4765f4a093bb3c3a94ac2daa174130c | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <crab/support/debug.hpp>
#include <crab/support/os.hpp>
namespace crab {
namespace cfg {
// To group together statements over integers or real
typedef enum {
BINOP_ADD,
BINOP_SUB,
BINOP_MUL,
BINOP_SDIV,
BINOP_UDIV,
BINOP_SREM,
BINOP_UREM,
BINOP_AND,
BINOP_OR,
BINOP_XOR,
BINOP_SHL,
BINOP_LSHR,
BINOP_ASHR,
} binary_operation_t;
typedef enum { BINOP_BAND, BINOP_BOR, BINOP_BXOR } bool_binary_operation_t;
typedef enum { CAST_TRUNC, CAST_SEXT, CAST_ZEXT } cast_operation_t;
inline crab::crab_os &operator<<(crab::crab_os &o, binary_operation_t op) {
switch (op) {
case BINOP_ADD:
o << "+";
break;
case BINOP_SUB:
o << "-";
break;
case BINOP_MUL:
o << "*";
break;
case BINOP_SDIV:
o << "/";
break;
case BINOP_UDIV:
o << "/_u";
break;
case BINOP_SREM:
o << "%";
break;
case BINOP_UREM:
o << "%_u";
break;
case BINOP_AND:
o << "&";
break;
case BINOP_OR:
o << "|";
break;
case BINOP_XOR:
o << "^";
break;
case BINOP_SHL:
o << "<<";
break;
case BINOP_LSHR:
o << ">>_l";
break;
case BINOP_ASHR:
o << ">>_r";
break;
default:
CRAB_ERROR("unexpected binary operation ", op);
}
return o;
}
inline crab::crab_os &operator<<(crab::crab_os &o, bool_binary_operation_t op) {
switch (op) {
case BINOP_BAND:
o << "&";
break;
case BINOP_BOR:
o << "|";
break;
case BINOP_BXOR:
o << "^";
break;
default:
CRAB_ERROR("unexpected boolean binary operation ", op);
}
return o;
}
inline crab::crab_os &operator<<(crab::crab_os &o, cast_operation_t op) {
switch (op) {
case CAST_TRUNC:
o << "trunc";
break;
case CAST_SEXT:
o << "sext";
break;
case CAST_ZEXT:
o << "zext";
break;
default:
CRAB_ERROR("unexpected cast operation", op);
}
return o;
}
} // end namespace cfg
} // end namespace crab
| 17.247788 | 80 | 0.601847 |
2ac7289f2839f679932b31c3de3b0e50c2d56a5a | 1,735 | cpp | C++ | rrMFC/Dlg_Property/PropertySheet/PropertyPage1.cpp | afoolsbag/rrCnCxx | 1e673bd4edac43d8406a0c726138cba194d17f48 | [
"Unlicense"
] | 2 | 2019-03-20T01:14:10.000Z | 2021-12-08T15:39:32.000Z | rrMFC/Dlg_Property/PropertySheet/PropertyPage1.cpp | afoolsbag/rrCnCxx | 1e673bd4edac43d8406a0c726138cba194d17f48 | [
"Unlicense"
] | null | null | null | rrMFC/Dlg_Property/PropertySheet/PropertyPage1.cpp | afoolsbag/rrCnCxx | 1e673bd4edac43d8406a0c726138cba194d17f48 | [
"Unlicense"
] | null | null | null | /// \copyright The Unlicense
#include "stdafx.h"
#include "PropertyPage1.h"
#include "PropertySheet.rc.h"
#include "rrwindows/rrwindows.h"
namespace rrMFC {
namespace Test {
const UINT PropertyPage1::IDD {IDD_PROPERTY_PAGE_1};
#// Constructors
PropertyPage1::
PropertyPage1()
: CPropertyPage(IDD)
{
DcMeth();
}
PropertyPage1::
~PropertyPage1()
{
DcMeth();
}
#// Operations
VOID PropertyPage1::
ReadFrom(CONST Configurations &configs)
{
DcMeth();
#ifdef M
# error Macro name conflicts.
#endif/*M*/
#define M(prop) (prop = configs.prop)
M(ServiceIpaddr);
M(ServiceIpport);
#undef M
}
VOID PropertyPage1::
WriteTo(Configurations *CONST pConfigs) CONST
{
DcMeth();
#ifdef M
# error Macro name conflicts.
#endif/*M*/
#define M(prop) (pConfigs->prop = prop)
M(ServiceIpaddr);
M(ServiceIpport);
#undef M
}
#// Overridables
BOOL PropertyPage1::
OnInitDialog()
{
CPropertyPage::OnInitDialog();
DcMeth();
return TRUE;
}
BOOL PropertyPage1::
OnWndMsg(UINT message, WPARAM wParam, LPARAM lParam, LRESULT *pResult)
{
DcWndMsg();
return CPropertyPage::OnWndMsg(message, wParam, lParam, pResult);
}
VOID PropertyPage1::
DoDataExchange(CDataExchange *pDX)
{
CPropertyPage::DoDataExchange(pDX);
DcMeth();
DDX_IPAddress(pDX, IDC_SERVICE_IPADDR, ServiceIpaddr);
DDX_Text(pDX, IDC_SERVICE_IPPORT, ServiceIpport);
DDV_MinMaxUInt(pDX, ServiceIpport, 0, 65535);
}
VOID PropertyPage1::
OnOK()
{
DcMeth();
CPropertyPage::OnOK();
}
VOID PropertyPage1::
OnCancel()
{
DcMeth();
CPropertyPage::OnCancel();
}
BOOL PropertyPage1::
OnApply()
{
DcMeth();
return CPropertyPage::OnApply();
}
#// Message Handlers
}//namespace Test
}//namespace rrMFC
| 15.772727 | 70 | 0.695677 |
2ac9d9b284c80fb4fcb117ac935242dc593aea35 | 1,825 | hpp | C++ | src/include/Geometry/HalfedgeMeshBuilder/MeshBuilderBase.hpp | timow-gh/Geometry | 6b46b107355cd76fbb9c3a86db23dc891e868a3b | [
"Apache-2.0"
] | null | null | null | src/include/Geometry/HalfedgeMeshBuilder/MeshBuilderBase.hpp | timow-gh/Geometry | 6b46b107355cd76fbb9c3a86db23dc891e868a3b | [
"Apache-2.0"
] | null | null | null | src/include/Geometry/HalfedgeMeshBuilder/MeshBuilderBase.hpp | timow-gh/Geometry | 6b46b107355cd76fbb9c3a86db23dc891e868a3b | [
"Apache-2.0"
] | null | null | null | #ifndef GEOMETRY_MESHBUILDERBASE_HPP
#define GEOMETRY_MESHBUILDERBASE_HPP
#include <Core/Types/TVector.hpp>
#include <Geometry/HalfedgeMesh/HalfedgeMesh.hpp>
#include <Geometry/HalfedgeMeshBuilder/MeshTriangleAdder.hpp>
#include <LinAl/LinearAlgebra.hpp>
namespace Geometry
{
template <typename T, typename Derived>
class MeshBuilderBase {
protected:
LinAl::HMatrix<double_t> m_transformation = {{1, 0, 0, 0},
{0, 1, 0, 0},
{0, 0, 1, 0},
{0, 0, 0, 1}};
std::unique_ptr<HalfedgeMesh<T>>
buildTriangleHeMesh(const LinAl::Vec3Vector<T>& points,
const Core::TVector<uint32_t>& triangleIndices) const
{
auto heMesh = std::make_unique<HalfedgeMesh<T>>();
MeshTriangleAdder<T> meshTriangleAdder{*heMesh};
std::size_t size = triangleIndices.size();
for (std::size_t i{2}; i < size; i += 3)
{
LinAl::VecArray<T, 3, 3> trianglePoints;
for (std::size_t j{0}; j < 3; ++j)
{
const std::size_t idx = triangleIndices[i - j];
const LinAl::Vec3<T>& point = points[idx];
LinAl::HVec<T> tPoint =
m_transformation * LinAl::HVec<T>{point[0], point[1], point[2], 1.0};
trianglePoints[j] = LinAl::Vec3<T>{tPoint[0], tPoint[1], tPoint[2]};
}
meshTriangleAdder(Triangle<T, 3>(trianglePoints));
}
return heMesh;
}
Derived& setTransformation(const LinAl::HMatrix<T>& transformation)
{
m_transformation = transformation;
return *static_cast<Derived*>(this);
}
};
} // namespace Geometry
#endif // GEOMETRY_MESHBUILDERBASE_HPP
| 35.096154 | 89 | 0.564384 |
2acc8f0b59ee05dd822e63465b79e6daa6a48a67 | 6,856 | cpp | C++ | main.cpp | deepomicslab/SpecHap | 194ded31c6b3fdfada593bd248082bf1945530b9 | [
"MIT"
] | 7 | 2021-02-17T09:24:39.000Z | 2021-12-23T07:47:38.000Z | main.cpp | deepomicslab/SpecHap | 194ded31c6b3fdfada593bd248082bf1945530b9 | [
"MIT"
] | 3 | 2021-04-30T19:36:57.000Z | 2022-03-24T02:32:17.000Z | main.cpp | deepomicslab/SpecHap | 194ded31c6b3fdfada593bd248082bf1945530b9 | [
"MIT"
] | 3 | 2021-09-06T07:20:06.000Z | 2021-11-24T05:21:19.000Z | #include <iostream>
#include "phaser.h"
#include "results.h"
#include "type.h"
bool HYBRID = false;
bool NEW_FORMAT = false;
bool KEEP_PS = false;
int WINDOW_SIZE = 200;
int WINDOW_OVERLAP = 60;
int BASE_OFFSET = 33;
int MAX_BARCODE_SPANNING = 60000;
int MAX_HIC_INSERTION= 40000000;
int RECURSIVE_LIMIT = 15;
int OPERATION = MODE_PE;
enum optionIndex
{
UNKNOWN, HELP, VCF, FRAGMENT, OUT, TENX, HIC, _WINDOW_SIZE, COVERAGE, _RECURSIVE_LIMIT, NANOPORE, PACBIO, NOSORT,
_MAX_BARCODE_SPANNING_LENGTH, _WINDOW_OVERLAP, STATS, _NEWFORMAT, USESECONDARY, _KEEP_PHASING_INFO, _BASEOFFSET, _HYBRID
};
struct Arg : public option::Arg
{
static void printError(const char *msg1, const option::Option &opt, const char *msg2)
{
std::cerr << "SpecHap: " << msg1 << opt.desc->longopt << msg2 << std::endl;
}
static option::ArgStatus Unknown(const option::Option &option, bool msg)
{
if (msg) printError("Unknown option '", option, "'\n");
return option::ARG_ILLEGAL;
}
static option::ArgStatus Required(const option::Option &option, bool msg)
{
if (option.arg != nullptr)
return option::ARG_OK;
if (msg) printError("Option '", option, "' requires an argument\n");
return option::ARG_ILLEGAL;
}
static option::ArgStatus Numeric(const option::Option &option, bool msg)
{
char *endptr = nullptr;
if (option.arg != nullptr && strtol(option.arg, &endptr, 10))
;
if (endptr != option.arg && *endptr == 0)
return option::ARG_OK;
return option::ARG_IGNORE;
}
};
const option::Descriptor usage[] =
{
{UNKNOWN, 0, "", "", Arg::Unknown, "Usage: "},
{HELP, 0, "h", "help", Arg::None, "\t--help\tPrint this message and exit."},
{VCF, 0, "v", "vcf", Arg::Required, "\t-v <arg>,\t--vcf=<arg>\tSorted Heterozygous VCF File, gzipped, tbi or csi index required."},
{FRAGMENT, 0, "f", "frag", Arg::Required, "\t-f <arg>,\t--frag=<arg>\tFragment File Generated by ExtractHairs, sort by SNP position is required."},
{STATS, 0, "s", "frag_stat", Arg::Required, "\t-s <arg>,\t--frag_stat=<arg>\tFragment file statistic, in bed format, required for 10x."},
{OUT, 0, "o", "out", Arg::Required, "\t-o <arg>,\t--out=<arg>\tOutput VCF File."},
{_WINDOW_SIZE, 0, "", "window_size", Arg::Numeric, "\t-w [<arg>],\t--window_size [<arg>]\tPhasing Window Size, default=250."},
{_WINDOW_OVERLAP, 0, "", "window_overlap", Arg::Numeric, "\t-O [<arg>],\t--window_overlap [<arg>]\tOverlap length between consecutive phasing window, default=60."},
{TENX, 0, "T", "tenx", Arg::None, "\t-T,\t--tenx\tSpecified for 10X data."},
{HIC, 0, "H", "hic", Arg::None, "\t-H,\t--hic\tSpecified for HiC data."},
{PACBIO, 0, "P", "pacbio", Arg::None, "\t-P,\t--pacbio\tSpecified for Pacbio data."},
{NANOPORE, 0, "N", "nanopore", Arg::None, "\t-N,\t--nanopore\tSpecified for Nanopore data."},
{_HYBRID, 0, "", "hybrid", Arg::None, "\t--hybrid\tSpecified for hybrid data type."},
{_NEWFORMAT, 0, "", "new_format", Arg::None, "\t--new_format\tSpecified when using new_format with extractHair"},
{_BASEOFFSET, 0, "", "base_offset", Arg::Numeric, "\t--base_offset\tQuality of set for read base, default is 33."},
{_KEEP_PHASING_INFO,0, "", "keep_phasing_info", Arg::None, "\t--keep_phasing_info\tSpecified when trying to keep previous phasing info"},
{0, 0, 0, 0, 0, 0 }
};
//TODO: messegign system
int main(int argc, char *argv[])
{
argc -= (argc > 0);argv += (argc > 0);
option::Stats stats(usage, argc, argv);
std::vector<option::Option> options(stats.options_max);
std::vector<option::Option> buffer(stats.buffer_max);
option::Parser parse(usage, argc, argv, &options[0], &buffer[0]);
if (parse.error())
exit(1);
if (options[HELP] || argc == 0)
{
int columns = getenv("COLUMNS") ? atoi(getenv("COLUMNS")) : 80;
option::printUsage(std::cout, usage);
exit(1);
}
if (options[VCF].arg == nullptr)
{
std::cerr << "SpecHap: Error. Missing VCF file, check the usage of specHap.\n";
option::printUsage(std::cout, usage);
exit(1);
}
if (options[FRAGMENT].arg == nullptr)
{
std::cerr << "SpecHap: Error. Missing Fragment file, check the usage of specHap.\n";
option::printUsage(std::cout, usage);
exit(1);
}
if (options[OUT].arg == nullptr)
{
std::cerr << "SpecHap: Error. Missing output file name, check the usage of specHap.\n";
option::printUsage(std::cout, usage);
exit(1);
}
if (options[TENX] && options[HIC])
{
std::cerr << "SpecHap: Error. Operation mode 10X and HiC are specified at the same time.\n";
exit(1);
}
if (options[TENX] && options[STATS].arg == nullptr)
{
std::cerr << "SpecHap: Error, require bed formatted fragment status file in 10X mode.\n";
exit(1);
}
if (options[_NEWFORMAT])
NEW_FORMAT = true;
if (options[_BASEOFFSET].arg != nullptr)
BASE_OFFSET = int(atoi(options[_BASEOFFSET].arg));
if (options[_KEEP_PHASING_INFO])
KEEP_PS = true;
if (options[_WINDOW_OVERLAP].arg != nullptr)
WINDOW_OVERLAP = int(atoi(options[_WINDOW_OVERLAP].arg));
if (options[_WINDOW_SIZE].arg != nullptr)
WINDOW_SIZE = int(atoi(options[_WINDOW_SIZE].arg));
std::string fnbed;
if (options[TENX])
{
OPERATION = MODE_10X;
fnbed = options[STATS].arg;
}
else if (options[HIC])
OPERATION = MODE_HIC;
else if (options[PACBIO])
OPERATION = MODE_PACBIO;
else if (options[NANOPORE])
OPERATION = MODE_NANOPORE;
if (options[_HYBRID]) //hybrid mode, using pacbio/oxford nanopore, ngs and hic.
{
HYBRID = true;
OPERATION = MODE_HYBRID;
}
std::string invcf = options[VCF].arg;
std::string out = options[OUT].arg;
std::string frag = options[FRAGMENT].arg;
Phaser *phaser = new Phaser(invcf, out, frag, fnbed);
phaser->phasing();
delete phaser;
return 0;
} | 40.809524 | 192 | 0.553384 |
2acdb257016405c6b7cea49c82cc62ea4fa18a86 | 6,326 | cpp | C++ | Lab02_03c.cpp | xinyizou/school-projects | 10adc544faf45446ef99d8e1a74acbe16c88c7b5 | [
"MIT"
] | 1 | 2020-01-21T00:46:48.000Z | 2020-01-21T00:46:48.000Z | Lab02_03c.cpp | xinyizou/school-projects | 10adc544faf45446ef99d8e1a74acbe16c88c7b5 | [
"MIT"
] | null | null | null | Lab02_03c.cpp | xinyizou/school-projects | 10adc544faf45446ef99d8e1a74acbe16c88c7b5 | [
"MIT"
] | null | null | null | //
// Student name: Xinyi Zou
// Student number: 20765197
//
// SYDE 121 Lab: Lab Assignment #1 Exercise #3
// Filename: lab02_03c
//
// I hereby declare that this code, submitted for credit for the course
// SYDE121, is a product of my own efforts. This coded solution has
// not been plagiarized from other sources and has not been knowingly
// plagiarized by others.
//
// Project: calculating sum of consecutive numbers
// Purpose: verifying the correctness of programs created by comparing program results with manual computation
// Due date: Friday, September 21, 2018
// Evaluation of program
//
// First number: 1
// Last number: 100
// Program output: The sum of 1 to 100 is 5050
// Manual calculation: (100 / 2) * (2 * 1 + (100 - 1) * 1) = 5050
//
// First number: 1
// Last number: 3000
// Program output: The sum of 1 to 3000 is 4501500
// Manual calculation: (3000 / 2) * (2 * 1 + (3000 - 1) * 1) = 4501500
//
// First number: 5
// Last number: 10000
// Program output: The sum of 1 to 10000 is 50004990
// Manual calculation: (9996 / 2) * (2 * 5 + (9996 - 1) * 1) = 50004990
//
//
// Since the program's outputted values and manually calculated values are the same, the program is correct
#include <iostream>
using namespace std;
int main()
{
// INPUT: finite arithmetic series defined by starting number, ending number, and interval
// OUTPUT: sum of arithmetic series
// calculate as per the formula: sum = (n / 2) * (2 * a + (n - 1) * d
// where n is number of integers to be added, a is the first number, and d is the difference between each number
// declare variables
int first_num;
int last_num;
const int INTERVAL = 1;
int sum;
double num_of_int; // must be double to accommodate cases where num_of_int / 2 is not a whole number since int / int will return an integer value that will cut off decimal values
//initialize variables with appropriate values given in the question
first_num = 1;
last_num = 100;
// calculate variable value using given formulas
num_of_int = last_num - first_num + 1;
sum = (num_of_int / 2) * (2 * first_num + (num_of_int - 1) * INTERVAL);
// output result to user
cout << "The sum of " << first_num << " to " << last_num << " is " << sum << endl;
// repeat with each consequent arithmetic series
first_num = 1;
last_num = 3000;
num_of_int = last_num - first_num + 1;
sum = (num_of_int / 2) * (2 * first_num + (num_of_int - 1) * INTERVAL);
cout << "The sum of " << first_num << " to " << last_num << " is " << sum << endl;
first_num = 5;
last_num = 10000;
num_of_int = last_num - first_num + 1;
sum = (num_of_int / 2) * (2 * first_num + (num_of_int - 1) * INTERVAL);
cout << "The sum of " << first_num << " to " << last_num << " is " << sum << endl;
//terminate
return 0;
}
// Limits
// The input limits for this function are the limits of the int variable
// As previously determined, an integer can take any value between (but not
// including) -2147483649 and 2147483647
//
// Example:
// First number: -2147483648
// Last number: 2147483649
// Program output: The sum of -2147483648 to 2147483647 is 0
// Manual calculation: (4294967298 / 2) * (2 * -2147483648 + (4294967298 - 1) * 1) = -2147483649
//
// This error in calculation can be attributed to the overloading of the variables,
// as seen, the values initiated into the variable is not fully outputted (2147483649 became 2147483647)
// nor is the final sum correct.
//
// Therefore, when any of the inputted values exceeds the allowable limit for the
// integer variable, the program is not correct.
//
// Similarly, since the value of the resulting sum is also stored in an integer its
// value must also be between (but not including) -2147483649 and 2147483647
//
// Example:
// First number: -2147483647
// Last number: -2147483646
// Program output: The sum of -2147483647 to -2147483646 with an interval of 1 is 3
// Manual calculation: (2 / 2) * (2 * -2147483647 + (2 - 1) * 1) = -4294967293
//
// Once the sum has exceeded the limits of the int variable, the program is no longer correct.
//
// This also makes sense given the expressible limit of an integer variable is -2147483648 to 2147483647 [1]
// Source [1]: corob-msft. 2016. "Data Type Ranges | Microsoft Doc". Available from
// https://github.com/mozillascience/code-research-object/issues/12
//
//
// Decimals
//
// First number: 42.42
// Last number: 84.42
// Program output: The sum of 42 to 84 with an interval of 1 is 2646
//
// As seen above, when a non-integer value is inputted into the int variable, the
// decimal values are cut off to make an integer, meaning the program is incorrect. This could be corrected by changing the variable type to from int to double.
//
//
// Therefore, this program is only correct when all integer variables (inputs and outputs) have an integer value between (but not including) -2147483649 and 2147483647.
#include <iostream>
using namespace std;
int main()
{
// INPUT: user inputs starting number, ending number, and interval
// OUTPUT: sum of numbers from starting number to ending number
// calculate as per the formula: sum = (n / 2) * (2 * a + (n - 1) * d
// where n is number of integers to be added, a is the first number, and d is the difference between each number
// declare variables
int first_num;
int last_num;
const int INTERVAL = 1;
int sum;
double num_of_int; // must be double to accommodate cases where num_of_int / 2 is not a whole number since int / int will return an integer value that will cut off decimal values
// ask user for input and initialize variables
cout << "Enter the starting value: " << endl;
cin >> first_num;
cout << "Enter the ending value: " << endl;
cin >> last_num;
// initialize variable with a formula
num_of_int = last_num - first_num + 1;
sum = (num_of_int / 2) * (2 * first_num + (num_of_int - 1) * INTERVAL);
// output result to user
cout << "The sum of " << first_num << " to " << last_num << " is " << sum << endl;
// terminate
return 0;
}
| 37.654762 | 188 | 0.659026 |
2ad3ff62c9f8e0a981f7abfdf613bdbb11baf678 | 2,997 | cpp | C++ | herramientas.cpp | AdrianN17/PosPolygon | db6bdef524c4712488bdfc1161ce29bb9c84e46f | [
"MIT"
] | 1 | 2019-10-11T03:37:35.000Z | 2019-10-11T03:37:35.000Z | herramientas.cpp | AdrianN17/PosPolygon | db6bdef524c4712488bdfc1161ce29bb9c84e46f | [
"MIT"
] | null | null | null | herramientas.cpp | AdrianN17/PosPolygon | db6bdef524c4712488bdfc1161ce29bb9c84e46f | [
"MIT"
] | null | null | null | #include "herramientas.h"
#include "ui_herramientas.h"
herramientas::herramientas(QWidget *parent) :
QWidget(parent),
ui(new Ui::herramientas)
{
const int max=450;
ui->setupUi(this);
ui->txt_centrox->setValidator( new QIntValidator(0, max, this) );
ui->txt_centroy->setValidator( new QIntValidator(0, max, this) );
ui->txt_puntox->setValidator( new QIntValidator(0, max, this) );
ui->txt_puntoy->setValidator( new QIntValidator(0, max, this) );
}
herramientas::~herramientas()
{
delete ui;
}
void herramientas::editar_centros(QVector2D centro)
{
float x= centro.x();
float y= centro.y();
ui->txt_centrox->setText(QString::number(x));
ui->txt_centroy->setText(QString::number(y));
}
void herramientas::on_btn_guardar_centro_clicked()
{
float x = ui->txt_centrox->text().toDouble();
float y = ui->txt_centroy->text().toDouble();
emit enviar_centros(QVector2D(x,y));
}
void herramientas::on_btn_reiniciar_centro_clicked()
{
emit pedir_centro();
}
void herramientas::cambiar_spinner_max(int count)
{
if(count>=0)
{
this->ui->spinner->setMaximum(count);
if(!ui->spinner->isEnabled())
{
cambiar_estado_puntos(true);
emit pedir_punto_posicion(0);
}
}
else
{
cambiar_estado_puntos(false);
limpieza_campos();
}
}
void herramientas::cambiar_estado_puntos(bool enable)
{
ui->spinner->setEnabled(enable);
ui->txt_puntox->setEnabled(enable);
ui->txt_puntoy->setEnabled(enable);
ui->btn_guardar_punto->setEnabled(enable);
ui->btn_eliminar_punto->setEnabled(enable);
}
void herramientas::on_spinner_valueChanged(int arg1)
{
emit pedir_punto_posicion(arg1);
}
void herramientas::dar_puntos_texto(QVector2D punto)
{
float x= punto.x();
float y= punto.y();
ui->txt_puntox->setText(QString::number(x));
ui->txt_puntoy->setText(QString::number(y));
}
void herramientas::on_btn_guardar_punto_clicked()
{
int index = ui->spinner->value();
float x = ui->txt_puntox->text().toFloat();
float y = ui->txt_puntoy->text().toFloat();
QVector2D data = QVector2D(x,y);
emit editar_punto(index,data);
}
void herramientas::on_rb1_clicked()
{
emit editar_tipo(0);
}
void herramientas::on_rb2_clicked()
{
emit editar_tipo(1);
}
void herramientas::on_btn_eliminar_punto_clicked()
{
qDebug()<<ui->spinner->maximum();
if(ui->spinner->maximum()==0)
{
emit enviar_eliminar_punto(ui->spinner->value());
}
else
{
emit enviar_eliminar_punto(ui->spinner->value());
emit pedir_punto_posicion(0);
ui->spinner->setValue(0);
}
}
void herramientas::on_btn_limpiar_clicked()
{
emit enviar_limpieza();
}
void herramientas::limpieza_campos()
{
cambiar_estado_puntos(false);
ui->txt_centrox->setText("");
ui->txt_centroy->setText("");
ui->txt_puntox->setText("");
ui->txt_puntoy->setText("");
}
| 19.717105 | 69 | 0.658659 |
2ad5e71ed708caeab1e5aa79f61f9bf9fd376894 | 1,802 | hpp | C++ | misc/bit_operation.hpp | hly1204/library | b62c47a8f20623c1f1edd892b980714e8587f40e | [
"Unlicense"
] | 7 | 2021-07-20T15:25:00.000Z | 2022-03-13T11:58:25.000Z | misc/bit_operation.hpp | hly1204/library | b62c47a8f20623c1f1edd892b980714e8587f40e | [
"Unlicense"
] | 10 | 2021-03-11T16:08:22.000Z | 2022-03-13T08:40:36.000Z | misc/bit_operation.hpp | hly1204/library | b62c47a8f20623c1f1edd892b980714e8587f40e | [
"Unlicense"
] | null | null | null | #ifndef BIT_OPERATION_HEADER_HPP
#define BIT_OPERATION_HEADER_HPP
/**
* @brief bit operations
*
*/
#include <cassert>
#include <cstdint>
#include "deBruijn_sequence.hpp"
namespace lib {
/**
* @brief 在二进制最高的 1 后面填充满 1
* @param x
* @return std::uint32_t
*/
std::uint32_t fill_one_after_msb(std::uint32_t x) {
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
return x | x >> 16;
}
std::uint64_t fill_one_after_msb(std::uint64_t x) {
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x | x >> 32;
}
/**
* @brief 计算 x 的二进制表示中 least significant 1-bit 的索引加一
* @param x
* @return int 若 x=0 则返回 0 。
*/
int ffs(std::uint32_t x) { return x == 0 ? 0 : deBruijn_log2(x & ~(x - 1)) + 1; }
int ffs(std::uint64_t x) { return x == 0 ? 0 : deBruijn_log2(x & ~(x - 1)) + 1; }
/**
* @brief 计算 x 的二进制表示中从 most significant bit 位置开始有多少个 0
* @param x
* @return int 若 x=0 则未定义。
*
*/
int clz(std::uint32_t x) {
assert(x != 0);
return 31 - deBruijn_log2(fill_one_after_msb(x >> 1) + 1);
}
int clz(std::uint64_t x) {
assert(x != 0);
return 63 - deBruijn_log2(fill_one_after_msb(x >> 1) + 1);
}
/**
* @brief 计算 x 的二进制表示中从 least significant bit 位置开始有多少个 0
* @param x
* @return int 若 x=0 则返回未定义
*/
int ctz(std::uint32_t x) {
assert(x != 0);
return deBruijn_log2(x & ~(x - 1));
}
int ctz(std::uint64_t x) {
assert(x != 0);
return deBruijn_log2(x & ~(x - 1));
}
/**
* @brief 计算 x 的二进制表示中 1 的个数
* @param x
* @return int
*/
int popcount(std::uint32_t x) {
int cnt = 0;
while (x) ++cnt, x &= x - 1;
return cnt;
}
int popcount(std::uint64_t x) {
int cnt = 0;
while (x) ++cnt, x &= x - 1;
return cnt;
}
} // namespace lib
#endif | 18.57732 | 82 | 0.546615 |
2ad5fbbb2684206d87b47e0f76ddc9b0da67b001 | 2,845 | cpp | C++ | godgame2/Sphere.cpp | magnificus/godgame | cafb36830263d95516eb014f432319cabf50bda7 | [
"Unlicense"
] | 5 | 2017-10-31T17:36:13.000Z | 2021-11-05T21:01:04.000Z | godgame2/Sphere.cpp | magnificus/godgame | cafb36830263d95516eb014f432319cabf50bda7 | [
"Unlicense"
] | null | null | null | godgame2/Sphere.cpp | magnificus/godgame | cafb36830263d95516eb014f432319cabf50bda7 | [
"Unlicense"
] | null | null | null | #include "Sphere.h"
#include "math.h"
#include <map>
#include <array>
struct Triangle
{
unsigned int vertex[3];
};
using TriangleList = std::vector<Triangle>;
using VertexList = std::vector<glm::vec3>;
using NormalList = std::vector<glm::vec3>;
#define Index unsigned int
namespace icosahedron
{
const float X = .525731112119133606f;
const float Z = .850650808352039932f;
const float N = 0.f;
static const VertexList vertices =
{
{ -X,N,Z },{ X,N,Z },{ -X,N,-Z },{ X,N,-Z },
{ N,Z,X },{ N,Z,-X },{ N,-Z,X },{ N,-Z,-X },
{ Z,X,N },{ -Z,X, N },{ Z,-X,N },{ -Z,-X, N }
};
static const std::vector<Triangle> triangles =
{
{ 0,4,1 },{ 0,9,4 },{ 9,5,4 },{ 4,5,8 },{ 4,8,1 },
{ 8,10,1 },{ 8,3,10 },{ 5,3,8 },{ 5,2,3 },{ 2,7,3 },
{ 7,10,3 },{ 7,6,10 },{ 7,11,6 },{ 11,0,6 },{ 0,1,6 },
{ 6,1,10 },{ 9,0,11 },{ 9,11,2 },{ 9,2,5 },{ 7,2,11 }
};
}
using Lookup = std::map<std::pair<Index, Index>, Index>;
Index vertex_for_edge(Lookup& lookup,
VertexList& vertices, Index first, Index second)
{
Lookup::key_type key(first, second);
if (key.first>key.second)
std::swap(key.first, key.second);
auto inserted = lookup.insert({ key, vertices.size() });
if (inserted.second)
{
auto& edge0 = vertices[first];
auto& edge1 = vertices[second];
auto point = normalize(edge0 + edge1);
vertices.push_back(point);
}
return inserted.first->second;
}
TriangleList subdivide(VertexList& vertices,
TriangleList triangles)
{
Lookup lookup;
TriangleList result;
for (auto&& each : triangles)
{
std::array<Index, 3> mid;
for (int edge = 0; edge<3; ++edge)
{
mid[edge] = vertex_for_edge(lookup, vertices,
each.vertex[edge], each.vertex[(edge + 1) % 3]);
}
result.push_back({ each.vertex[0], mid[0], mid[2] });
result.push_back({ each.vertex[1], mid[1], mid[0] });
result.push_back({ each.vertex[2], mid[2], mid[1] });
result.push_back({ mid[0], mid[1], mid[2] });
}
return result;
}
struct IndexedMesh {
VertexList vertList;
TriangleList triList;
};
//using IndexedMesh = std::pair<VertexList, TriangleList>;
IndexedMesh make_icosphere(int subdivisions)
{
VertexList vertices = icosahedron::vertices;
TriangleList triangles = icosahedron::triangles;
for (int i = 0; i<subdivisions; ++i)
{
triangles = subdivide(vertices, triangles);
}
return{ vertices, triangles };
}
Sphere::Sphere(Shader *s) : Model(s)
{
IndexedMesh mesh = make_icosphere(2);
vertices = mesh.vertList;
//normals = mesh.vertList;
for (glm::vec3 t : mesh.vertList) {
normals.push_back(t);
}
for (Triangle t : mesh.triList) {
for (int i = 2; i >= 0; i--)
indicies.push_back(t.vertex[i]);
}
//for (int i = 0; i < vertices.size(); i++) {
// glm::vec3 vert = vertices[i];
//}
}
| 23.708333 | 59 | 0.599297 |
2adb800c632a7ae555e16819d86333554fafdb11 | 5,691 | cpp | C++ | PostLib/GMeshImport.cpp | chunkeey/FEBioStudio | f342d4ac2bc3581db792373c4265454109af92b3 | [
"MIT"
] | 27 | 2020-06-25T06:34:52.000Z | 2022-03-11T08:58:57.000Z | PostLib/GMeshImport.cpp | chunkeey/FEBioStudio | f342d4ac2bc3581db792373c4265454109af92b3 | [
"MIT"
] | 42 | 2020-06-15T18:40:57.000Z | 2022-03-24T05:38:54.000Z | PostLib/GMeshImport.cpp | chunkeey/FEBioStudio | f342d4ac2bc3581db792373c4265454109af92b3 | [
"MIT"
] | 12 | 2020-06-27T13:58:57.000Z | 2022-03-24T05:39:10.000Z | /*This file is part of the FEBio Studio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio-Studio.txt for details.
Copyright (c) 2020 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
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 "stdafx.h"
#include "GMeshImport.h"
#include <FSCore/color.h>
#include "FEPostModel.h"
#include "FEPostMesh.h"
using namespace Post;
GMeshImport::GMeshImport(FEPostModel* fem) : FEFileReader(fem)
{
}
GMeshImport::~GMeshImport(void)
{
}
bool GMeshImport::Load(const char* szfile)
{
// open the file
if (Open(szfile, "rt") == false) return false;
bool bret = true;
char szline[256] = {0};
while (fgets(szline, 255, m_fp))
{
if (strncmp(szline, "$Nodes" , 6) == 0) bret = ReadNodes();
else if (strncmp(szline, "$Elements" , 9) == 0) bret = ReadElements();
if (bret == false) return false;
}
// close the file
Close();
return BuildMesh(*m_fem);
}
bool GMeshImport::ReadNodes()
{
m_Node.clear();
char szline[256] = {0};
fgets(szline, 255, m_fp);
int nodes = 0;
int nread = sscanf(szline, "%d", &nodes);
if (nread != 1) return errf("Error while reading Nodes section");
m_Node.resize(nodes);
// read the nodes
for (int i=0; i<nodes; ++i)
{
vec3f& r = m_Node[i].r;
fgets(szline, 255, m_fp);
int nread = sscanf(szline, "%*d %g %g %g", &r.x, &r.y, &r.z);
if (nread != 3) return errf("Error while reading Nodes section");
}
// read the end of the mesh format
fgets(szline, 255, m_fp);
if (strncmp(szline, "$EndNodes", 9) != 0) return errf("Failed finding EndNodes");
return true;
}
bool GMeshImport::ReadElements()
{
m_Elem.clear();
char szline[256] = {0};
fgets(szline, 255, m_fp);
int elems = 0;
int nread = sscanf(szline, "%d", &elems);
if (nread != 1) return errf("Error while reading Element section");
m_Elem.reserve(elems);
// read the elements
ELEM el;
int n[13];
for (int i=0; i<elems; ++i)
{
fgets(szline, 255, m_fp);
sscanf(szline,"%d%d%d%d%d%d%d%d%d%d%d%d%d",n,n+1,n+2,n+3,n+4,n+5,n+6,n+7,n+8,n+9,n+10,n+11,n+12);
switch (n[1])
{
case 4: // tetrahedron
el.ntype = FE_TET4;
el.node[0] = n[ 3 + n[2] ] - 1;
el.node[1] = n[ 3 + n[2] + 1] - 1;
el.node[2] = n[ 3 + n[2] + 2] - 1;
el.node[3] = n[ 3 + n[2] + 3] - 1;
m_Elem.push_back(el);
break;
case 5:
el.ntype = FE_HEX8;
el.node[0] = n[ 3 + n[2] ] - 1;
el.node[1] = n[ 3 + n[2] + 1] - 1;
el.node[2] = n[ 3 + n[2] + 2] - 1;
el.node[3] = n[ 3 + n[2] + 3] - 1;
el.node[4] = n[ 3 + n[2] + 4] - 1;
el.node[5] = n[ 3 + n[2] + 5] - 1;
el.node[6] = n[ 3 + n[2] + 6] - 1;
el.node[7] = n[ 3 + n[2] + 7] - 1;
m_Elem.push_back(el);
break;
case 6:
el.ntype = FE_PENTA6;
el.node[0] = n[ 3 + n[2] ] - 1;
el.node[1] = n[ 3 + n[2] + 1] - 1;
el.node[2] = n[ 3 + n[2] + 2] - 1;
el.node[3] = n[ 3 + n[2] + 3] - 1;
el.node[4] = n[ 3 + n[2] + 4] - 1;
el.node[5] = n[ 3 + n[2] + 5] - 1;
m_Elem.push_back(el);
break;
}
}
// read the end of the mesh format
fgets(szline, 255, m_fp);
if (strncmp(szline, "$EndElements", 12) != 0) return errf("Failed finding EndElements");
return true;
}
bool GMeshImport::BuildMesh(FEPostModel& fem)
{
int i;
int nodes = (int)m_Node.size();
int elems = (int)m_Elem.size();
if (nodes == 0) return errf("FATAL ERROR: No nodal data defined in file.");
if (elems == 0) return errf("FATAL ERROR: No element data defined in file.");
// clear the model
fem.Clear();
// add a materials
FEMaterial mat;
fem.AddMaterial(mat);
// build the mesh
FEPostMesh* pm = new FEPostMesh;
pm->Create(nodes, elems);
// create nodes
for (i=0; i<nodes; ++i)
{
FENode& n = pm->Node(i);
NODE& node = m_Node[i];
n.r.x = node.r.x;
n.r.y = node.r.y;
n.r.z = node.r.z;
}
// create elements
for (i=0; i<elems; ++i)
{
FEElement& el = static_cast<FEElement&>(pm->ElementRef(i));
ELEM& E = m_Elem[i];
el.m_MatID = 0;
switch (E.ntype)
{
case FE_TET4 : el.SetType(FE_TET4); break;
case FE_HEX8 : el.SetType(FE_HEX8); break;
case FE_PENTA6: el.SetType(FE_PENTA6); break;
default:
assert(false);
return false;
}
el.m_node[0] = E.node[0];
el.m_node[1] = E.node[1];
el.m_node[2] = E.node[2];
el.m_node[3] = E.node[3];
el.m_node[4] = E.node[4];
el.m_node[5] = E.node[5];
el.m_node[6] = E.node[6];
el.m_node[7] = E.node[7];
}
// update the mesh
fem.AddMesh(pm);
pm->BuildMesh();
fem.UpdateBoundingBox();
// we need a single state
FEState* ps = new FEState(0.f, &fem, fem.GetFEMesh(0));
fem.AddState(ps);
// clean up
m_Node.clear();
m_Elem.clear();
// we're good!
return true;
}
| 25.070485 | 99 | 0.628712 |
2adca25a6559cdf343d960f039d6d2b4feb0ddfa | 4,219 | cpp | C++ | SDK/PUBG_SoundOptionWidget_functions.cpp | realrespecter/PUBG-FULL-SDK | 5e2b0f103c74c95d2329c4c9dfbfab48aa0da737 | [
"MIT"
] | 7 | 2019-03-06T11:04:52.000Z | 2019-07-10T20:00:51.000Z | SDK/PUBG_SoundOptionWidget_functions.cpp | realrespecter/PUBG-FULL-SDK | 5e2b0f103c74c95d2329c4c9dfbfab48aa0da737 | [
"MIT"
] | null | null | null | SDK/PUBG_SoundOptionWidget_functions.cpp | realrespecter/PUBG-FULL-SDK | 5e2b0f103c74c95d2329c4c9dfbfab48aa0da737 | [
"MIT"
] | 10 | 2019-03-06T11:53:46.000Z | 2021-02-18T14:01:11.000Z | // PUBG FULL SDK - Generated By Respecter (5.3.4.11 [06/03/2019]) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "PUBG_SoundOptionWidget_parameters.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function SoundOptionWidget.SoundOptionWidget_C.IsEnable_VoiceSetting
// ()
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
bool USoundOptionWidget_C::IsEnable_VoiceSetting()
{
static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.IsEnable_VoiceSetting");
USoundOptionWidget_C_IsEnable_VoiceSetting_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function SoundOptionWidget.SoundOptionWidget_C.IsKeyUp
// (Event)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
bool USoundOptionWidget_C::IsKeyUp()
{
static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.IsKeyUp");
USoundOptionWidget_C_IsKeyUp_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function SoundOptionWidget.SoundOptionWidget_C.IsChanged
// (Event)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
bool USoundOptionWidget_C::IsChanged()
{
static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.IsChanged");
USoundOptionWidget_C_IsChanged_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function SoundOptionWidget.SoundOptionWidget_C.OnApply
// (Event)
void USoundOptionWidget_C::OnApply()
{
static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.OnApply");
USoundOptionWidget_C_OnApply_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function SoundOptionWidget.SoundOptionWidget_C.OnDefault
// (Event)
void USoundOptionWidget_C::OnDefault()
{
static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.OnDefault");
USoundOptionWidget_C_OnDefault_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function SoundOptionWidget.SoundOptionWidget_C.OnReset
// (Event)
void USoundOptionWidget_C::OnReset()
{
static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.OnReset");
USoundOptionWidget_C_OnReset_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function SoundOptionWidget.SoundOptionWidget_C.Construct
// (BlueprintCosmetic, Event)
void USoundOptionWidget_C::Construct()
{
static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.Construct");
USoundOptionWidget_C_Construct_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function SoundOptionWidget.SoundOptionWidget_C.ExecuteUbergraph_SoundOptionWidget
// ()
// Parameters:
// int* EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void USoundOptionWidget_C::ExecuteUbergraph_SoundOptionWidget(int* EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.ExecuteUbergraph_SoundOptionWidget");
USoundOptionWidget_C_ExecuteUbergraph_SoundOptionWidget_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 24.672515 | 134 | 0.726475 |
2ae8821c883a13bc5a2b3fae0f8a9d88ca472eea | 808 | hh | C++ | include/muensterTPCRunAction.hh | l-althueser/MuensterTPC-Simulation | 7a086ab330cd5905f3c78c324936cdc36951e9bd | [
"BSD-2-Clause"
] | null | null | null | include/muensterTPCRunAction.hh | l-althueser/MuensterTPC-Simulation | 7a086ab330cd5905f3c78c324936cdc36951e9bd | [
"BSD-2-Clause"
] | 2 | 2017-01-24T21:18:46.000Z | 2017-01-27T13:24:48.000Z | include/muensterTPCRunAction.hh | l-althueser/MuensterTPC-Simulation | 7a086ab330cd5905f3c78c324936cdc36951e9bd | [
"BSD-2-Clause"
] | 4 | 2017-04-28T12:18:58.000Z | 2019-04-10T21:15:00.000Z | /******************************************************************
* muensterTPCsim
*
* Simulations of the Muenster TPC
*
* @author Lutz Althüser
* @date 2015-04-14
*
* @update 2015-11-02 - added comments
*
* @comment
******************************************************************/
#ifndef __muensterTPCPRUNACTION_H__
#define __muensterTPCPRUNACTION_H__
#include <G4UserRunAction.hh>
class G4Run;
class muensterTPCAnalysisManager;
class muensterTPCRunAction: public G4UserRunAction {
public:
muensterTPCRunAction(muensterTPCAnalysisManager *pAnalysisManager=0);
~muensterTPCRunAction();
public:
void BeginOfRunAction(const G4Run *pRun);
void EndOfRunAction(const G4Run *pRun);
private:
muensterTPCAnalysisManager *m_pAnalysisManager;
};
#endif // __muensterTPCPRUNACTION_H__
| 21.837838 | 70 | 0.65099 |
2aeaf60025deb5b258232b5f76df3ed43b233b3d | 5,403 | cpp | C++ | 2_Package/imu/dev_bmp085.cpp | HANDS-FREE/OpenRE | fbd4cfa7a12bb43679db23422e79da69aaef1fce | [
"BSD-2-Clause"
] | 56 | 2016-08-13T11:26:51.000Z | 2022-02-17T08:45:40.000Z | 2_Package/imu/dev_bmp085.cpp | HANDS-FREE/OpenRE | fbd4cfa7a12bb43679db23422e79da69aaef1fce | [
"BSD-2-Clause"
] | 3 | 2017-03-04T11:55:26.000Z | 2018-05-03T08:34:52.000Z | 2_Package/imu/dev_bmp085.cpp | HANDS-FREE/OpenRE | fbd4cfa7a12bb43679db23422e79da69aaef1fce | [
"BSD-2-Clause"
] | 51 | 2016-08-15T14:00:44.000Z | 2022-02-17T08:45:41.000Z | /***********************************************************************************************************************
* Copyright (c) Hands Free Team. All rights reserved.
* Contact: QQ Exchange Group -- 521037187
*
* LICENSING TERMS:
* The Hands Free is licensed generally under a permissive 3-clause BSD license.
* Contributions are requiredto be made under the same license.
*
* History:
* <author> <time> <version> <desc>
* mawenke 2015.10.1 V1.0 creat this file
* chenyingbing 2015.12.1 V1.6 update
* Description: 本文件封装了IMU中 气压计模块bmp085的驱动代码
*
***********************************************************************************************************************/
#include "dev_bmp085.h"
#include "math.h"
#define BMP085_ADDRESS 0xee
#define OSS 0
BMP085 bmp085;
void BMP085::readBuffer(void)
{
}
void BMP085::writeByte(unsigned char reg_address,unsigned char reg_data)
{
Board::getInstance()->iicDeviceWriteByte(IIC_IMU , BMP085_ADDRESS, reg_address, reg_data);
}
unsigned char BMP085::readByte(unsigned char reg_address)
{
return(Board::getInstance()->iicDeviceReadByte(IIC_IMU , BMP085_ADDRESS, reg_address));
}
/***********************************************************************************************************************
*
*
*
***********************************************************************************************************************/
//滑动平均滤波 算术平均滤波算法 输入最近采样值,返回最近NUM个值的平均值 NUM < 30
#define AAF_NUM_MAX 30
template<typename TYPE> TYPE Arithmetic_Average_F ( TYPE new_value , unsigned short int NUM)
{
static TYPE value_buf[AAF_NUM_MAX];
static unsigned short int count;
TYPE SUM;
unsigned short int i;
value_buf[count] = new_value;
count++;
if(count >= NUM) count=0; //滑动更新窗口
for ( i=0;i<NUM;i++)
{
SUM += value_buf[i];
}
return SUM/NUM;
}
unsigned char BMP085::checkDeviceState(void)
{
device_state = 1;
return device_state;
}
/***********************************************************************************************************************
* Function: void BMP085::deviceInit(void)
*
* Scope: public
*
* Description:
*
* Arguments:
*
* Return:
*
* Cpu_Time:
*
* History:
* mawenke 2015.10.1 V1.0 creat
***********************************************************************************************************************/
unsigned char BMP085::deviceInit(void)
{
ac1 = readByte(0xAA);
ac1 = (ac1<<8)|readByte(0xAB);
ac2 = readByte(0xAC);
ac2 = (ac2<<8)| readByte(0xAD);
ac3 = readByte(0xAE);
ac3 = (ac3<<8)| readByte(0xAF);
ac4 = readByte(0xB0);
ac4 = (ac4<<8)| readByte(0xB1);
ac5 = readByte(0xB2);
ac5 = (ac5<<8)| readByte(0xB3);
ac6 = readByte(0xB4);
ac6 = (ac6<<8)| readByte(0xB5);
b1 = readByte(0xB6);
b1 = (b1<<8)| readByte(0xB7);
b2 = readByte(0xB8);
b2 = (b2<<8)| readByte(0xB9);
mb = readByte(0xBA);
mb = (mb<<8)| readByte(0xBB);
mc = readByte(0xBC);
mc = (mc<<8)| readByte(0xBD);
md = readByte(0xBE);
md = (md<<8)| readByte(0xBF);
writeByte(0xF4,0x2E); //选择了BMP085模块,写入读温度指令
checkDeviceState();
return device_state;
}
/***********************************************************************************************************************
* Function: void BMP085::dataUpdate(void)
*
* Scope: private
*
* Description: 处理BMP的数据 循环调用 建议5ms 运行一次(200hz) 气压和温度更新速度各为100hz
*
* Arguments:
*
* Return:
*
* Cpu_Time: stm32f1(140 us) stm32f4+nofpu(unknow us) stm32f4+fpu(unknow us)
*
* History:
* mawenke 2015.10.1 V1.0 creat
***********************************************************************************************************************/
void BMP085::dataUpdate(void)
{
if(data_update_i == 0)
{
data_update_i = 1;
ut = ( readByte(0xF6) <<8 ) | readByte(0xF7); //读取数据低八位
writeByte(0xF4,0x34); //选择了BMP085模块,写入读气压指令
}
else
{
data_update_i = 0;
up = ( readByte(0xF6) <<8 ) | readByte(0xF7);
up &= 0x0000FFFF;
writeByte(0xF4,0x2E); //选择了BMP085模块,写入读温度指令
//以下为温补代码
x1 = ((int)ut - ac6) * ac5 >> 15;
x2 = ((int) mc << 11) / (x1 + md);
b5 = x1 + x2;
temperature = (b5 + 8) >> 4;
temperature = temperature/10 ;
b6 = b5 - 4000;
x1 = (b2 * (b6 * b6 >> 12)) >> 11;
x2 = ac2 * b6 >> 11;
x3 = x1 + x2;
b3 = (((int)ac1 * 4 + x3) + 2)/4;
x1 = ac3 * b6 >> 13;
x2 = (b1 * (b6 * b6 >> 12)) >> 16;
x3 = ((x1 + x2) + 2) >> 2;
b4 = (ac4 * (unsigned int) (x3 + 32768)) >> 15;
b7 = ((unsigned int) up - b3) * (50000 >> OSS);
if( b7 < 0x80000000)
p = (b7 * 2) / b4 ;
else
p = (b7 / b4) * 2;
x1 = (p >> 8) * (p >> 8);
x1 = (x1 * 3038) >> 16;
x2 = (-7357 * p) >> 16;
pressure = p + ((x1 + x2 + 3791) >> 4);
//以下为计算海拔的代码
altitude = (float)44330.0 * (1 - pow( (float)( pressure / (float)101325 ) , (float)0.1903 ) );
//altitude = Arithmetic_Average_F ( altitude , 10);
}
}
| 29.850829 | 121 | 0.446604 |
2af1887a721bdeb858258afbb3e4d04e60fb56d6 | 2,977 | cpp | C++ | TDEngine2/source/core/CConfigFileEngineCoreBuilder.cpp | bnoazx005/TDEngine2 | 93ebfecf8af791ff5ecd4f57525a6935e34cd05c | [
"Apache-2.0"
] | 1 | 2019-07-15T01:14:15.000Z | 2019-07-15T01:14:15.000Z | TDEngine2/source/core/CConfigFileEngineCoreBuilder.cpp | bnoazx005/TDEngine2 | 93ebfecf8af791ff5ecd4f57525a6935e34cd05c | [
"Apache-2.0"
] | 76 | 2018-10-27T16:59:36.000Z | 2022-03-30T17:40:39.000Z | TDEngine2/source/core/CConfigFileEngineCoreBuilder.cpp | bnoazx005/TDEngine2 | 93ebfecf8af791ff5ecd4f57525a6935e34cd05c | [
"Apache-2.0"
] | 1 | 2019-07-29T02:02:08.000Z | 2019-07-29T02:02:08.000Z | #include "../../include/core/CConfigFileEngineCoreBuilder.h"
#include "../../include/core/IFileSystem.h"
#include "../../include/platform/CConfigFileReader.h"
#include <memory>
#include <thread>
#include <functional>
namespace TDEngine2
{
CConfigFileEngineCoreBuilder::CConfigFileEngineCoreBuilder() :
CBaseEngineCoreBuilder()
{
}
/*!
\brief The method initialized the builder's object
\param[in] A callback to a factory's function of IEngineCore's objects
\return RC_OK if everything went ok, or some other code, which describes an error
*/
E_RESULT_CODE CConfigFileEngineCoreBuilder::Init(TCreateEngineCoreCallback pEngineCoreFactoryCallback, const std::string& configFilename)
{
if (mIsInitialized)
{
return RC_OK;
}
if (!pEngineCoreFactoryCallback || configFilename.empty())
{
return RC_INVALID_ARGS;
}
E_RESULT_CODE result = RC_OK;
mConfigFilename = configFilename;
mpEngineCoreInstance = pEngineCoreFactoryCallback(result);
if (result != RC_OK)
{
return result;
}
mIsInitialized = true;
return RC_OK;
}
TResult<TEngineSettings> CConfigFileEngineCoreBuilder::_readConfigurationFile(IFileSystem* pFileSystem, const std::string& configFilename)
{
TFileEntryId configFileHandle = pFileSystem->Open<IConfigFileReader>(configFilename, false).Get();
IConfigFileReader* pConfigFileReader = pFileSystem->Get<IConfigFileReader>(configFileHandle);
TEngineSettings settings;
settings.mApplicationName = pConfigFileReader->GetString("main", "name", "Default App");
settings.mWindowWidth = pConfigFileReader->GetInt("main", "width", 640);
settings.mWindowHeight = pConfigFileReader->GetInt("main", "height", 480);
settings.mFlags = pConfigFileReader->GetInt("main", "flags", 0x0);
settings.mMaxNumOfWorkerThreads = pConfigFileReader->GetInt("main", "max-num-worker-threads", std::thread::hardware_concurrency() - 1);
settings.mTotalPreallocatedMemorySize = pConfigFileReader->GetInt("memory", "total-preallocated-memory-size", DefaultGlobalMemoryBlockSize);
settings.mGraphicsContextType = StringToGraphicsContextType(pConfigFileReader->GetString("graphics", "context-type", "unknown"));
settings.mAudioContextType = E_AUDIO_CONTEXT_API_TYPE::FMOD;
pConfigFileReader->Close();
return Wrench::TOkValue<TEngineSettings>(settings);
}
TEngineSettings CConfigFileEngineCoreBuilder::_initEngineSettings()
{
if (auto readConfigResult = _readConfigurationFile(mpFileSystemInstance, mConfigFilename))
{
return (mEngineSettings = readConfigResult.Get());
}
TDE2_ASSERT(false);
return mEngineSettings;
}
TDE2_API IEngineCoreBuilder* CreateConfigFileEngineCoreBuilder(TCreateEngineCoreCallback pEngineCoreFactoryCallback, const std::string& configFilename, E_RESULT_CODE& result)
{
return CREATE_IMPL(IEngineCoreBuilder, CConfigFileEngineCoreBuilder, result, pEngineCoreFactoryCallback, configFilename);
}
} | 32.358696 | 175 | 0.762177 |
2af323f0acf239b7f37307f9ff8a65783bd92f7a | 710 | cpp | C++ | Codechef/VisitTheCities.cpp | MartinAparicioPons/Competitive-Programming | 58151df0ed08a5e4e605abefdd69fef1ecc10fa0 | [
"Apache-2.0"
] | 1 | 2019-09-29T03:58:35.000Z | 2019-09-29T03:58:35.000Z | Codechef/VisitTheCities.cpp | MartinAparicioPons/Competitive-Programming | 58151df0ed08a5e4e605abefdd69fef1ecc10fa0 | [
"Apache-2.0"
] | null | null | null | Codechef/VisitTheCities.cpp | MartinAparicioPons/Competitive-Programming | 58151df0ed08a5e4e605abefdd69fef1ecc10fa0 | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 10010;
int n, P, Pi;
vector<int> E[MAXN];
bool vis[MAXN];
void dfs(int u, int p){
if(vis[u]) return;
vis[u] = true;
if(p > P){
P = p;
Pi = u;
}
for(int i = 0; i < E[u].size(); i++){
dfs(E[u][i], p + 1);
}
}
int main(){
ios_base::sync_with_stdio(0);
int T, i, u, v;
cin >> T;
while(T--){
cin >> n;
if(n <= 0){
cout << 0 << endl;
continue;
}
for(i = 0; i <= n; i++){
E[i].clear();
}
for(i = 0; i < n-1; i++){
cin >> u >> v;
E[u].push_back(v);
E[v].push_back(u);
}
memset(vis, 0, sizeof vis);
P = 0;
dfs(1, 0);
memset(vis, 0, sizeof vis);
P = 0;
dfs(Pi, 0);
cout << P << endl;
}
}
| 14.2 | 38 | 0.476056 |
2af50f0fe6ae885ca83997d8da58c9840370afa1 | 3,521 | hpp | C++ | src/simple_graph/algorithm/bellman_ford.hpp | sfod/simple-graph | b07ac266296f44238ee02f7cc1042f079f4eac9d | [
"MIT"
] | 1 | 2016-01-25T09:54:38.000Z | 2016-01-25T09:54:38.000Z | src/simple_graph/algorithm/bellman_ford.hpp | sfod/simple-graph | b07ac266296f44238ee02f7cc1042f079f4eac9d | [
"MIT"
] | 1 | 2019-04-08T10:40:00.000Z | 2019-04-08T10:40:00.000Z | src/simple_graph/algorithm/bellman_ford.hpp | sfod/simple-graph | b07ac266296f44238ee02f7cc1042f079f4eac9d | [
"MIT"
] | null | null | null | #pragma once
#include <algorithm>
#include <cassert>
#include <set>
#include <vector>
#include "simple_graph/graph.hpp"
namespace simple_graph {
template<typename W>
bool check_distance(const W &d, const W &w)
{
return !((d > 0) && (w > 0) && (std::numeric_limits<W>::max() - d < w));
}
template<bool Dir, typename V, typename E, typename W>
bool bellman_ford(const Graph<Dir, V, E, W> &g, vertex_index_t start_idx, vertex_index_t goal_idx,
std::vector<vertex_index_t> *path)
{
// TODO add utility function to check passed vertex indices
if ((start_idx < 0) || (goal_idx < 0)) {
return false;
}
std::vector<W> distance(g.vertex_num(), std::numeric_limits<W>::max());
std::vector<vertex_index_t> predecessor(g.vertex_num(), -1);
distance[start_idx] = 0;
auto fg = const_cast<Graph<Dir, V, E, W>*>(&g);
std::vector<Edge<E, W>> asc_edges;
std::vector<Edge<E, W>> desc_edges;
for (const auto &edge : fg->edges()) {
if (Dir) {
if (edge.idx1() < edge.idx2()) {
asc_edges.push_back(edge);
}
else {
desc_edges.push_back(edge);
}
}
else {
asc_edges.push_back(edge);
desc_edges.push_back(edge);
}
}
std::sort(asc_edges.begin(), asc_edges.end(), [](const Edge<E, W> &a, const Edge<E, W> &b) {
vertex_index_t a_idx = std::min(a.idx1(), a.idx2());
vertex_index_t b_idx = std::min(b.idx1(), b.idx2());
return a_idx < b_idx;
});
std::sort(desc_edges.begin(), desc_edges.end(), [](const Edge<E, W> &a, const Edge<E, W> &b) {
vertex_index_t a_idx = std::max(a.idx1(), a.idx2());
vertex_index_t b_idx = std::max(b.idx1(), b.idx2());
return b_idx < a_idx;
});
for (size_t i = 0; i < g.vertex_num(); ++i) {
bool changed = false;
for (const auto &edge : asc_edges) {
std::pair<vertex_index_t, vertex_index_t> e = std::minmax(edge.idx1(), edge.idx2());
if (check_distance(distance[e.first], edge.weight())
&& (distance[e.first] + edge.weight() < distance[e.second])) {
distance[e.second] = distance[e.first] + edge.weight();
predecessor[e.second] = e.first;
changed = true;
}
}
for (const auto &edge : desc_edges) {
std::pair<vertex_index_t, vertex_index_t> e = std::minmax(edge.idx1(), edge.idx2());
if (check_distance(distance[e.second], edge.weight())
&& (distance[e.second] + edge.weight() < distance[e.first])) {
distance[e.first] = distance[e.second] + edge.weight();
predecessor[e.first] = e.second;
changed = true;
}
}
if (!changed) {
break;
}
}
for (const auto &edge : fg->edges()) {
if (check_distance(distance[edge.idx1()], edge.weight())
&& (distance[edge.idx1()] + edge.weight() < distance[edge.idx2()])) {
return false;
}
}
if (distance[goal_idx] == std::numeric_limits<W>::max()) {
return false;
}
vertex_index_t idx = goal_idx;
while (idx != start_idx) {
path->push_back(idx);
idx = predecessor[idx];
assert(idx != static_cast<vertex_index_t>(-1));
}
path->push_back(idx);
std::reverse(path->begin(), path->end());
return true;
}
} // simple_graph
| 32.302752 | 98 | 0.545016 |
2af5fb5321452a0e61ee7a8063da3a949c424301 | 5,338 | cc | C++ | tensorflow_graphics/rendering/opengl/egl_offscreen_context.cc | Liang813/graphics | 71ab1775228a0a292427551350cbb62bfa8bd01a | [
"Apache-2.0"
] | 2,759 | 2019-01-08T10:40:34.000Z | 2022-03-28T13:49:37.000Z | tensorflow_graphics/rendering/opengl/egl_offscreen_context.cc | Liang813/graphics | 71ab1775228a0a292427551350cbb62bfa8bd01a | [
"Apache-2.0"
] | 262 | 2019-04-28T12:25:49.000Z | 2022-03-24T19:35:15.000Z | tensorflow_graphics/rendering/opengl/egl_offscreen_context.cc | Liang813/graphics | 71ab1775228a0a292427551350cbb62bfa8bd01a | [
"Apache-2.0"
] | 380 | 2019-05-09T00:14:45.000Z | 2022-03-31T12:48:25.000Z | /* Copyright 2020 The TensorFlow Authors
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 "egl_offscreen_context.h"
#include <EGL/egl.h>
#include "egl_util.h"
#include "macros.h"
#include "cleanup.h"
#include "tensorflow/core/lib/core/status.h"
EGLOffscreenContext::EGLOffscreenContext(EGLContext context, EGLDisplay display,
EGLSurface pixel_buffer_surface)
: context_(context),
display_(display),
pixel_buffer_surface_(pixel_buffer_surface) {}
EGLOffscreenContext::~EGLOffscreenContext() { TF_CHECK_OK(Destroy()); }
tensorflow::Status EGLOffscreenContext::Create(
std::unique_ptr<EGLOffscreenContext>* egl_offscreen_context) {
constexpr std::array<int, 13> kDefaultConfigurationAttributes = {
EGL_SURFACE_TYPE,
EGL_PBUFFER_BIT,
EGL_RENDERABLE_TYPE,
EGL_OPENGL_ES2_BIT,
EGL_BLUE_SIZE,
8,
EGL_GREEN_SIZE,
8,
EGL_RED_SIZE,
8,
EGL_DEPTH_SIZE,
24,
EGL_NONE // The array must be terminated with that value.
};
constexpr std::array<int, 3> kDefaultContextAttributes = {
EGL_CONTEXT_CLIENT_VERSION,
2,
EGL_NONE,
};
return Create(0, 0, EGL_OPENGL_API, kDefaultConfigurationAttributes.data(),
kDefaultContextAttributes.data(), egl_offscreen_context);
}
tensorflow::Status EGLOffscreenContext::Create(
const int pixel_buffer_width, const int pixel_buffer_height,
const EGLenum rendering_api, const EGLint* configuration_attributes,
const EGLint* context_attributes,
std::unique_ptr<EGLOffscreenContext>* egl_offscreen_context) {
// Create an EGL display at device index 0.
EGLDisplay display;
display = CreateInitializedEGLDisplay();
if (display == EGL_NO_DISPLAY) return TFG_INTERNAL_ERROR("EGL_NO_DISPLAY");
auto initialize_cleanup =
MakeCleanup([display]() { TerminateInitializedEGLDisplay(display); });
// Set the current rendering API.
EGLBoolean success;
success = eglBindAPI(rendering_api);
if (success == false) return TFG_INTERNAL_ERROR("eglBindAPI");
// Build a frame buffer configuration.
EGLConfig frame_buffer_configuration;
EGLint returned_num_configs;
const EGLint kRequestedNumConfigs = 1;
TFG_RETURN_IF_EGL_ERROR(
success = eglChooseConfig(display, configuration_attributes,
&frame_buffer_configuration,
kRequestedNumConfigs, &returned_num_configs));
if (!success || returned_num_configs != kRequestedNumConfigs)
return TFG_INTERNAL_ERROR("returned_num_configs != kRequestedNumConfigs");
// Create a pixel buffer surface.
EGLint pixel_buffer_attributes[] = {
EGL_WIDTH, pixel_buffer_width, EGL_HEIGHT, pixel_buffer_height, EGL_NONE,
};
EGLSurface pixel_buffer_surface;
TFG_RETURN_IF_EGL_ERROR(
pixel_buffer_surface = eglCreatePbufferSurface(
display, frame_buffer_configuration, pixel_buffer_attributes));
auto surface_cleanup = MakeCleanup([display, pixel_buffer_surface]() {
eglDestroySurface(display, pixel_buffer_surface);
});
// Create the EGL rendering context.
EGLContext context;
TFG_RETURN_IF_EGL_ERROR(
context = eglCreateContext(display, frame_buffer_configuration,
EGL_NO_CONTEXT, context_attributes));
if (context == EGL_NO_CONTEXT) return TFG_INTERNAL_ERROR("EGL_NO_CONTEXT");
initialize_cleanup.release();
surface_cleanup.release();
*egl_offscreen_context = std::unique_ptr<EGLOffscreenContext>(
new EGLOffscreenContext(context, display, pixel_buffer_surface));
return tensorflow::Status::OK();
}
tensorflow::Status EGLOffscreenContext::Destroy() {
TF_RETURN_IF_ERROR(Release());
if (eglDestroyContext(display_, context_) == false) {
return TFG_INTERNAL_ERROR("an error occured in eglDestroyContext.");
}
if (eglDestroySurface(display_, pixel_buffer_surface_) == false) {
return TFG_INTERNAL_ERROR("an error occured in eglDestroySurface.");
}
if (TerminateInitializedEGLDisplay(display_) == false) {
return TFG_INTERNAL_ERROR(
"an error occured in TerminateInitializedEGLDisplay.");
}
return tensorflow::Status::OK();
}
tensorflow::Status EGLOffscreenContext::MakeCurrent() const {
TFG_RETURN_IF_EGL_ERROR(eglMakeCurrent(display_, pixel_buffer_surface_,
pixel_buffer_surface_, context_));
return tensorflow::Status::OK();
}
tensorflow::Status EGLOffscreenContext::Release() {
if (context_ != EGL_NO_CONTEXT && context_ == eglGetCurrentContext()) {
TFG_RETURN_IF_EGL_ERROR(eglMakeCurrent(display_, EGL_NO_SURFACE,
EGL_NO_SURFACE, EGL_NO_CONTEXT));
}
return tensorflow::Status::OK();
}
| 36.561644 | 80 | 0.716373 |
2af686437eda8ab8178fd1a9174f42768e3f51d5 | 4,200 | cc | C++ | testing/gsgts_test.cc | shgalus/shg | 0318d0126cf12c3236183447d130969c468a02fa | [
"MIT"
] | 9 | 2015-05-21T04:14:50.000Z | 2021-05-31T17:15:15.000Z | testing/gsgts_test.cc | shgalus/shg | 0318d0126cf12c3236183447d130969c468a02fa | [
"MIT"
] | 1 | 2015-05-21T05:31:04.000Z | 2015-05-21T05:31:04.000Z | testing/gsgts_test.cc | shgalus/shg | 0318d0126cf12c3236183447d130969c468a02fa | [
"MIT"
] | 2 | 2015-05-21T04:14:44.000Z | 2020-08-18T12:35:22.000Z | #include <shg/gsgts.h>
#include <shg/mzt.h>
#include <shg/utils.h>
#include "testing.h"
namespace SHG::Testing {
BOOST_AUTO_TEST_SUITE(gsgts_test)
BOOST_AUTO_TEST_CASE(basic_test) {
const std::vector<double> result1{
-0.1853455, -0.1532896, -0.1108232, -0.2036469, -0.1754326,
-0.1098344, -0.1704000, -0.1704131, -0.1563406, -0.1918795,
-0.0037222, 0.0975940, 0.0355298, -0.0634263, 0.0374293,
0.0977770, 0.0736954, 0.2835564, 0.2788326, 0.2212461,
0.1910693, 0.1717203, 0.1263446, 0.0584663, -0.1037948,
-0.2123793, -0.3292821, -0.2957615, -0.0796072, -0.0078135,
0.1049731, -0.1195140, 0.0005337, -0.0356647, 0.2934005,
0.2276349, 0.4457550, 0.4160869, 0.4105583, 0.1995325,
0.0474566, 0.1518003, 0.2249002, 0.1612962, 0.1916418,
0.1283362, 0.0949260, 0.1025253, 0.1695968, 0.3228145,
0.0881576, 0.2352667, 0.2379230, 0.0875150, -0.1102473,
-0.2148395, -0.0491461, -0.1555136, -0.0795668, 0.0525286,
0.0295757, 0.2391820, 0.1089352, 0.2395681, 0.1216882,
0.2793094, 0.3333728, 0.1691596, -0.0416942, 0.1816499,
0.4151612, 0.2889556, 0.2731870, 0.3562827, 0.1409797,
0.1811236, 0.1518109, 0.0900939, 0.1209136, 0.0668564,
0.1764099, 0.2728195, 0.2470544, 0.1540218, 0.0997584,
0.1230065, -0.0144507, 0.1192095, 0.1224003, 0.1762245,
0.1806781, 0.1696920, -0.0684979, -0.1765898, -0.1535255,
-0.0453403, -0.0492510, 0.0043458, 0.0749827, 0.0774716,
0.1105852, 0.1633152, 0.3711041, 0.3320104, 0.3874592,
0.2527283, 0.0685019, 0.0296893, -0.1128779, -0.1337343,
-0.0479861, -0.0095436, -0.0649834, -0.0609462, -0.1011171,
-0.1103539, -0.0297745, 0.0183672, 0.1219624, 0.3562367,
0.4008174, 0.4294983, 0.2980393, 0.1350898, -0.0283490,
-0.0908774, -0.0056641, -0.0478976, 0.1339543};
const std::vector<double> result2{
-0.6316450, -0.5236583, -0.6450972, -0.6190345, -0.5010952,
-0.9558759, -0.1537523, 0.4321690, -0.2066403, 0.1795031,
0.6131393, 1.3266019, 0.8642400, 0.7363808, 0.3988882,
-0.6462101, -1.5355407, -1.0049679, 0.3972050, -0.2645621,
-0.3155533, 0.8387987, 1.5328002, 2.0032490, 0.8197588,
0.0549526, 0.9641574, 0.4819636, 0.5519046, 0.0725050,
1.2768633, 0.4071369, 1.3226040, -0.3431683, -0.7920558,
-0.6202403, -0.2992066, 0.3171086, 0.8226870, 0.5258867,
1.0262011, 1.1781231, -0.4041209, 1.4476297, 1.2358308,
1.1499674, 0.5927083, 0.4290790, 0.2877266, 0.2509648,
1.2343851, 0.6633968, 0.4232300, -0.0151701, 0.4706398,
0.6900624, 0.8829870, -0.7137435, -0.7393445, -0.2582170,
0.0220044, 0.3048083, 0.4480417, 1.4495389, 1.7003893,
0.8326820, -0.1140906, -0.6896338, -0.2440786, -0.1348664,
-0.4987745, -0.4856796, -0.1759956, 0.7788311, 1.9449494,
1.6053352, 0.3524270, -0.6395870, -0.1899812, -0.0128994};
const GSGTS::Cosine_transform ct{nullptr};
const GSGTS::Real_transform rt{nullptr};
const double eps = 5e-8;
const std::vector<double> acf1 = acfar1(1.0 / 64.0, 0.8, 129);
const std::vector<double> acf2 = acfar1(0.5, 0.6, 80);
std::vector<double>::size_type i;
MZT mzt;
auto normal = [&mzt]() { return mzt.normal(); };
std::vector<double> X;
mzt = MZT();
X.resize(acf1.size());
GSGTS gsgts1(acf1, ct);
gsgts1.generate(X, normal, rt);
BOOST_CHECK(X.size() == acf1.size());
BOOST_REQUIRE(X.size() == result1.size());
for (i = 0; i < X.size(); i++)
BOOST_CHECK(faeq(X[i], result1[i], eps));
mzt = MZT();
X.resize(acf2.size());
GSGTS gsgts2(acf2, ct);
gsgts2.generate(X, normal, rt);
BOOST_CHECK(X.size() == acf2.size());
BOOST_REQUIRE(X.size() == result2.size());
for (i = 0; i < X.size(); i++)
BOOST_CHECK(faeq(X[i], result2[i], eps));
}
BOOST_AUTO_TEST_SUITE_END()
} // namespace SHG::Testing
| 48.275862 | 70 | 0.584524 |
2af7a6ae39d191373e3196cf3e77ea0da3ed2cd8 | 3,925 | cpp | C++ | kernels/gact-raw/gact.cpp | YC-Vertex/GeneSAK | 10fcd2fc3d9c3df1f391dc277b8d5840abf3034c | [
"MIT"
] | 4 | 2021-09-13T14:41:06.000Z | 2021-12-25T03:31:56.000Z | kernels/gact-raw/gact.cpp | YC-Vertex/GeneSAK | 10fcd2fc3d9c3df1f391dc277b8d5840abf3034c | [
"MIT"
] | null | null | null | kernels/gact-raw/gact.cpp | YC-Vertex/GeneSAK | 10fcd2fc3d9c3df1f391dc277b8d5840abf3034c | [
"MIT"
] | 1 | 2021-09-16T06:56:41.000Z | 2021-09-16T06:56:41.000Z | #include <string>
#include "gact.h"
inline int64_t max(int64_t a, int64_t b) {
return a > b ? a : b;
}
inline void setDefaultParams(AlignTask *task) {
task->params["TILE_SIZE"] = 128;
task->params["OVERLAP_SIZE"] = 32;
}
AlignTileRet alignTile(std::string ref, std::string qry, bool first, int maxTBLen) {
int dp[ref.length()][qry.length()];
int tb[ref.length()][qry.length()];
int maxval = 0;
MatchPos maxpos = {0, 0};
AlignTileRet ret;
ret.refTBStr = "";
ret.qryTBStr = "";
for (int i = 0; i < ref.length(); ++i) {
for (int j = 0; j < qry.length(); ++j) {
if (i == 0 || j == 0) {
dp[i][j] = 0;
tb[i][j] = 0;
tb[i][j] |= (i > 0) ? 0b10 : 0;
tb[i][j] |= (j > 0) ? 0b01 : 0;
continue;
}
int u = dp[i][j-1] - 1; // insertion
int l = dp[i-1][j] - 1; // deletion
int ul = dp[i-1][j-1] + (ref[i] == qry[j] ? 1 : -1); // match / subst
if (ul >= u && ul >= l) {
dp[i][j] = ul;
tb[i][j] = 0b11;
}
else if (l >= ul && l >= u) {
dp[i][j] = l;
tb[i][j] = 0b10;
}
else {
dp[i][j] = u;
tb[i][j] = 0b01;
}
if (dp[i][j] > maxval) {
maxval = dp[i][j];
maxpos = {uint64_t(i), uint64_t(j)};
}
}
}
if (first) {
return {maxpos, "", ""};
}
int i = ref.length() - 1;
int j = qry.length() - 1;
while (maxTBLen != 0 && i >= 0 && j >= 0 && !(i == 0 && j == 0)) {
bool im1 = false;
bool jm1 = false;
if (tb[i][j] & 0b10) {
ret.refTBStr = ref[i] + ret.refTBStr;
im1 = true;
}
else {
ret.refTBStr = '-' + ret.refTBStr;
}
if (tb[i][j] & 0b01) {
ret.qryTBStr = qry[j] + ret.qryTBStr;
jm1 = true;
}
else {
ret.qryTBStr = '-' + ret.qryTBStr;
}
if (im1) --i;
if (jm1) --j;
--maxTBLen;
}
ret.offset = {(uint64_t)i, (uint64_t) j};
return ret;
}
GACTRet gact(AlignTask *task, std::string ref, std::string qry, MatchPos initPos) {
if (task->params.find("TILE_SIZE") == task->params.end()) {
setDefaultParams(task);
}
int T = task->params["TILE_SIZE"];
int O = task->params["OVERLAP_SIZE"];
int icurr = initPos.refPos + (qry.length() - 1 - initPos.qryPos);
int jcurr = qry.length() - 1;
bool first = true;
MatchPos optPos;
while (icurr > 0 && jcurr > 0) {
int istart = max(0, icurr - T);
int jstart = max(0, jcurr - T);
std::string refSubStr = ref.substr(istart, icurr - istart + 1);
std::string qrySubStr = qry.substr(jstart, jcurr - jstart + 1);
AlignTileRet ret = alignTile(refSubStr, qrySubStr, first, T - O);
#ifdef __DEBUG__
if (first) {
std::cout << "optPos = ("
<< ret.offset.refPos << ", "
<< ret.offset.qryPos << ")"
<< std::endl << std::endl;
}
else {
std::cout << "Ref[" << istart << ":" << icurr << "] <-> "
<< "Qry[" << jstart << ":" << jcurr << "]:"
<< std::endl;
std::cout << ret.refTBStr << std::endl
<< ret.qryTBStr << std::endl << std::endl;
}
#endif // __DEBUG__
icurr = istart + ret.offset.refPos;
jcurr = jstart + ret.offset.qryPos;
if (first) {
optPos = {(uint64_t)icurr, (uint64_t)jcurr};
first = false;
continue;
}
if (icurr == 0 || jcurr == 0)
break;
}
return optPos;
} | 26.52027 | 84 | 0.421656 |
2afdf7b06a66366ec7c1cbf55fb56779ea03d8f0 | 9,465 | cpp | C++ | pure_pursuit_core/test/GeometryTest.cpp | Idate96/se2_navigation | 0fabe002742add5e4d716776b13704aa9c1aa339 | [
"BSD-3-Clause"
] | 216 | 2020-04-14T22:32:45.000Z | 2022-03-30T17:56:12.000Z | pure_pursuit_core/test/GeometryTest.cpp | Idate96/se2_navigation | 0fabe002742add5e4d716776b13704aa9c1aa339 | [
"BSD-3-Clause"
] | 5 | 2020-09-23T08:41:38.000Z | 2021-11-11T09:58:00.000Z | pure_pursuit_core/test/GeometryTest.cpp | Idate96/se2_navigation | 0fabe002742add5e4d716776b13704aa9c1aa339 | [
"BSD-3-Clause"
] | 56 | 2020-04-29T00:26:20.000Z | 2022-03-30T17:27:55.000Z | /*
* GeometryTest.cpp
*
* Created on: Mar 19, 2020
* Author: jelavice
*/
#include <gtest/gtest.h>
// Math
#include <cmath>
#include "test_helpers.hpp"
#include "pure_pursuit_core/math.hpp"
namespace ppt = pure_pursuit_test;
namespace pp = pure_pursuit;
using SolutionCase = pp::Intersection::SolutionCase;
template<typename T>
int toInt(T t)
{
return static_cast<int>(t);
}
constexpr unsigned int numCasesPerTest = 2000;
TEST(Geoemtry, CircleValid)
{
const int seed = ppt::seedRndGenerator();
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
const auto circle = ppt::createRandomCircle();
EXPECT_GE(circle.r_, 0.0);
EXPECT_LE(std::fabs(circle.center_.x()), ppt::testPlaneWidth);
EXPECT_LE(std::fabs(circle.center_.y()), ppt::testPlaneWidth);
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, CircleValid failed with seed: " << seed << std::endl;
}
}
TEST(Geoemtry, PointOutsideCircle)
{
const int seed = ppt::seedRndGenerator();
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
const auto circle = ppt::createRandomCircle();
const auto point = ppt::createRandomPointOutside(circle);
const double d = (circle.center_ - point).norm();
EXPECT_GT(d, circle.r_);
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, PointOutsideCircle failed with seed: " << seed << std::endl;
}
}
TEST(Geoemtry, PointInsideCircle)
{
const int seed = ppt::seedRndGenerator();
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
const auto circle = ppt::createRandomCircle();
const auto point = ppt::createRandomPointInside(circle);
const double d = (circle.center_ - point).norm();
EXPECT_LT(d, circle.r_);
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, PointInsideCircle failed with seed: " << seed << std::endl;
}
}
TEST(Geoemtry, PerpendicularVector)
{
const int seed = ppt::seedRndGenerator();
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
ppt::Line l;
l.p1_ = ppt::createRandomPoint();
l.p2_ = ppt::createRandomPoint();
const auto v = ppt::createUnitVectorPerpendicularToLine(l);
EXPECT_NEAR(v.norm(), 1.0, 1e-5);
ppt::Vector v_hat = l.p2_ - l.p1_;
v_hat.normalize();
EXPECT_NEAR(v.transpose() * v_hat, 0.0, 1e-5);
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, PerpendicularVector failed with seed: " << seed << std::endl;
}
}
TEST(Geometry, CircleIntersection_0)
{
const int seed = ppt::seedRndGenerator();
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
const auto circle = ppt::createRandomCircle();
const auto line = ppt::createRandomLineWithoutIntersection(circle);
EXPECT_GT((line.p1_ - circle.center_).norm(), circle.r_);
EXPECT_GT((line.p2_ - circle.center_).norm(), circle.r_);
pp::Intersection intersection;
pp::computeIntersection(line, circle, &intersection);
EXPECT_EQ(toInt(intersection.solutionCase_), toInt(SolutionCase::NO_SOLUTION));
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, CircleIntersection_0 failed with seed: " << seed << std::endl;
}
}
TEST(Geometry, CircleIntersection_1)
{
const int seed = 558104554; //ppt::seedRndGenerator();
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
const auto circle = ppt::createRandomCircle();
const auto line = ppt::createRandomLineWitOneIntersection(circle);
const bool atLeastOnePointAtcircleRadiusDistance = pp::isClose(
(line.p1_ - circle.center_).norm(), circle.r_)
|| pp::isClose((line.p2_ - circle.center_).norm(), circle.r_);
EXPECT_TRUE(atLeastOnePointAtcircleRadiusDistance);
pp::Intersection intersection;
pp::computeIntersection(line, circle, &intersection);
EXPECT_EQ(toInt(intersection.solutionCase_), toInt(SolutionCase::ONE_SOLUTION));
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, CircleIntersection_1 failed with seed: " << seed << std::endl;
}
}
TEST(Geometry, CircleIntersection_2)
{
const int seed = ppt::seedRndGenerator();
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
const auto circle = ppt::createRandomCircle();
const auto line = ppt::createRandomLineWithTwoIntersections(circle);
pp::Intersection intersection;
pp::computeIntersection(line, circle, &intersection);
EXPECT_EQ(toInt(intersection.solutionCase_), toInt(SolutionCase::TWO_SOLUTIONS));
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, CircleIntersection_2 failed with seed: " << seed << std::endl;
}
}
TEST(Geometry, DesiredHeadingForward)
{
using DrivingDirection = pp::DrivingDirection;
const int seed = ppt::seedRndGenerator();
std::uniform_real_distribution<double> yawDist(-M_PI, M_PI);
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
const double desiredYaw = yawDist(ppt::rndGenerator);
ppt::Vector desiredHeading = computeDesiredHeadingVector(desiredYaw, DrivingDirection::FWD);
desiredHeading.normalize();
ppt::Vector headingGroundTruth(std::cos(desiredYaw), std::sin(desiredYaw));
EXPECT_NEAR(headingGroundTruth.transpose() * desiredHeading, 1.0, 1e-5);
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, DesiredHeadingForward failed with seed: " << seed << std::endl;
}
}
TEST(Geometry, DesiredHeadingReverse)
{
using DrivingDirection = pp::DrivingDirection;
const int seed = ppt::seedRndGenerator();
std::uniform_real_distribution<double> yawDist(-M_PI, M_PI);
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
const double desiredYaw = yawDist(ppt::rndGenerator);
ppt::Vector desiredHeading = computeDesiredHeadingVector(desiredYaw, DrivingDirection::BCK);
desiredHeading.normalize();
const ppt::Vector headingGroundTruth(std::cos(desiredYaw), std::sin(desiredYaw));
EXPECT_NEAR(headingGroundTruth.transpose() * desiredHeading, -1.0, 1e-5);
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, DesiredHeadingReverse failed with seed: " << seed << std::endl;
}
}
TEST(Geometry, IsPastLastPoint)
{
using PathPoint = pp::PathPoint;
const int seed = ppt::seedRndGenerator();
pp::PathSegment segment;
segment.point_.resize(1);
EXPECT_THROW(pp::isPastLastPoint(segment, ppt::createRandomPoint()), std::runtime_error);
segment.point_.resize(2);
EXPECT_NO_THROW(pp::isPastLastPoint(segment, ppt::createRandomPoint()));
segment.point_ = {PathPoint(-1.0,0.0), PathPoint(0.0,0.0)};
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
const PathPoint queryPoint(ppt::createRandomPoint());
if (queryPoint.position_.x() > 0.0){
EXPECT_TRUE(pp::isPastLastPoint(segment, queryPoint.position_));
} else {
EXPECT_FALSE(pp::isPastLastPoint(segment, queryPoint.position_));
}
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, IsPastLastPoint failed with seed: " << seed << std::endl;
}
}
TEST(Geometry, CoarseWaypoints1)
{
/* this test addresses the ISSUE #3
* https://github.com/leggedrobotics/se2_navigation/issues/3
*/
using namespace pp;
RobotState robotState;
robotState.pose_ = RobotPose(-7.52288223073, 0.383239928729, 0.5042049);
PathSegment pathSegment;
pathSegment.drivingDirection_ = DrivingDirection::FWD;
pathSegment.point_.push_back(PathPoint(-9.64970568409, 0.036127697624)); // 0
pathSegment.point_.push_back(PathPoint(-6.11220568409, 2.16112769762)); // 1
pathSegment.point_.push_back(PathPoint(0.0, 5.0)); // 2
pathSegment.point_.push_back(PathPoint(6.11220568409, 2.16112769762)); // 3
pathSegment.point_.push_back(PathPoint(9.64970568409, 0.036127697624)); // 4
pathSegment.point_.push_back(PathPoint(13.9358333817, -2.53857798646)); // 5
const double lookaheadDistance = 2.5;
appendPointAlongFinalApproachDirection(5.0 * lookaheadDistance, &pathSegment);
unsigned int closerPointId=0, fartherPointId=0;
const Point anchorPoint(-7.08510279935,0.624795656177 );
findIdsOfTwoPointsDefiningALine(robotState, pathSegment, anchorPoint, 0, lookaheadDistance, &closerPointId, &fartherPointId);
EXPECT_EQ(closerPointId,1);
EXPECT_EQ(fartherPointId,2);
}
TEST(Geometry, CoarseWaypoints2)
{
/* this test addresses the ISSUE #3
* https://github.com/leggedrobotics/se2_navigation/issues/3
*/
using namespace pp;
RobotState robotState;
robotState.pose_ = RobotPose(2.25228492629, 4.33692721322, -0.2410715);
PathSegment pathSegment;
pathSegment.drivingDirection_ = DrivingDirection::FWD;
pathSegment.point_.push_back(PathPoint(-9.64970568409, 0.036127697624)); // 0
pathSegment.point_.push_back(PathPoint(-6.11220568409, 2.16112769762)); // 1
pathSegment.point_.push_back(PathPoint(0.0, 5.0)); // 2
pathSegment.point_.push_back(PathPoint(6.11220568409, 2.16112769762)); // 3
pathSegment.point_.push_back(PathPoint(9.64970568409, 0.036127697624)); // 4
pathSegment.point_.push_back(PathPoint(13.9358333817, -2.53857798646)); // 5
const double lookaheadDistance = 2.5;
appendPointAlongFinalApproachDirection(5.0 * lookaheadDistance, &pathSegment);
unsigned int closerPointId=0, fartherPointId=0;
const Point anchorPoint(2.737826287315, 4.21755558031 );
findIdsOfTwoPointsDefiningALine(robotState, pathSegment, anchorPoint, 0, lookaheadDistance, &closerPointId, &fartherPointId);
EXPECT_EQ(closerPointId,2);
EXPECT_EQ(fartherPointId,3);
}
| 36.686047 | 127 | 0.709773 |
63021073c1c0f32186c24ec364ce2c943ccf648c | 1,712 | cpp | C++ | src/web/tests/test_libaeon_web/test_url_encoding.cpp | aeon-engine/libaeon | e42b39e621dcd0a0fba05e1c166fc688288fb69b | [
"BSD-2-Clause"
] | 7 | 2017-02-19T16:22:16.000Z | 2021-03-02T05:47:39.000Z | src/web/tests/test_libaeon_web/test_url_encoding.cpp | aeon-engine/libaeon | e42b39e621dcd0a0fba05e1c166fc688288fb69b | [
"BSD-2-Clause"
] | 61 | 2017-05-29T06:11:17.000Z | 2021-03-28T21:51:44.000Z | src/web/tests/test_libaeon_web/test_url_encoding.cpp | aeon-engine/libaeon | e42b39e621dcd0a0fba05e1c166fc688288fb69b | [
"BSD-2-Clause"
] | 2 | 2017-05-28T17:17:40.000Z | 2017-07-14T21:45:16.000Z | // Distributed under the BSD 2-Clause License - Copyright 2012-2021 Robin Degen
#include <aeon/web/http/url_encoding.h>
#include <aeon/web/http/validators.h>
#include <gtest/gtest.h>
#include <random>
using namespace aeon;
TEST(test_url_encoding, encode_regular_string)
{
const std::u8string test_str = u8"ThisIsATestString123";
ASSERT_EQ(test_str, web::http::url_encode(test_str));
}
TEST(test_url_encoding, encode_spaces)
{
const std::u8string test_str = u8"This Is A Test String 123";
const std::u8string expected_str = u8"This%20Is%20A%20Test%20String%20123";
ASSERT_EQ(expected_str, web::http::url_encode(test_str));
}
static auto generate_random_string(const int length) -> std::u8string
{
std::u8string str;
str.reserve(length);
std::random_device r;
std::default_random_engine e1(r());
std::uniform_int_distribution<unsigned long> uniform_dist;
int offset = 0;
auto random_value = uniform_dist(e1);
for (auto i = 0; i < length; ++i)
{
if (offset == sizeof(unsigned long))
{
random_value = uniform_dist(e1);
i = 0;
}
str += static_cast<char>((random_value >> (i * 8)) & 0xFF);
++offset;
}
return str;
}
TEST(test_url_encoding, encode_decode_random)
{
for (auto i = 0; i < 100; ++i)
{
for (auto j = 5; j < 20; ++j)
{
const auto str = generate_random_string(j);
const auto str_encoded = web::http::url_encode(str);
ASSERT_TRUE(web::http::detail::validate_uri(str_encoded));
const auto str_decoded = web::http::url_decode(str_encoded);
ASSERT_EQ(str, str_decoded);
}
}
}
| 25.939394 | 79 | 0.638435 |
6304a393a27ce668de2d43bd5d1b5530919ee665 | 326 | hpp | C++ | DoremiEngine/AI/Include/Interface/SubModule/AStarSubModule.hpp | meraz/doremi | 452d08ebd10db50d9563c1cf97699571889ab18f | [
"MIT"
] | 1 | 2020-03-23T15:42:05.000Z | 2020-03-23T15:42:05.000Z | DoremiEngine/AI/Include/Interface/SubModule/AStarSubModule.hpp | Meraz/ssp15 | 452d08ebd10db50d9563c1cf97699571889ab18f | [
"MIT"
] | null | null | null | DoremiEngine/AI/Include/Interface/SubModule/AStarSubModule.hpp | Meraz/ssp15 | 452d08ebd10db50d9563c1cf97699571889ab18f | [
"MIT"
] | 1 | 2020-03-23T15:42:06.000Z | 2020-03-23T15:42:06.000Z | #pragma once
namespace DoremiEngine
{
namespace AI
{
/**
TODOKO docs
*/
class MapGrid;
class AStarSubModule
{
public:
virtual void GetPath(int p_startPos, const MapGrid& p_map) = 0;
virtual MapGrid* BuildMapGrid() = 0;
};
}
}
| 18.111111 | 75 | 0.506135 |
630642a798f5254c0a521c6019c0031bcdbc86d9 | 5,515 | cpp | C++ | src/ui/Style.cpp | CedricGuillemet/gemoni | 76ca371d509791dd9d560d3f9f701f96e209ca5e | [
"MIT"
] | null | null | null | src/ui/Style.cpp | CedricGuillemet/gemoni | 76ca371d509791dd9d560d3f9f701f96e209ca5e | [
"MIT"
] | null | null | null | src/ui/Style.cpp | CedricGuillemet/gemoni | 76ca371d509791dd9d560d3f9f701f96e209ca5e | [
"MIT"
] | null | null | null | #include "imgui.h"
#include "IconsFontAwesome5.h"
void SetStyle()
{
ImGuiStyle& st = ImGui::GetStyle();
st.FrameBorderSize = 1.0f;
st.FramePadding = ImVec2(4.0f, 2.0f);
st.ItemSpacing = ImVec2(8.0f, 2.0f);
st.WindowBorderSize = 1.0f;
st.TabBorderSize = 1.0f;
st.WindowRounding = 1.0f;
st.ChildRounding = 1.0f;
st.FrameRounding = 1.0f;
st.ScrollbarRounding = 1.0f;
st.GrabRounding = 1.0f;
st.TabRounding = 1.0f;
// Setup style
ImVec4* colors = ImGui::GetStyle().Colors;
colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 0.95f);
colors[ImGuiCol_TextDisabled] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f);
colors[ImGuiCol_WindowBg] = ImVec4(0.13f, 0.12f, 0.12f, 1.00f);
colors[ImGuiCol_ChildBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.00f);
colors[ImGuiCol_PopupBg] = ImVec4(0.05f, 0.05f, 0.05f, 0.94f);
colors[ImGuiCol_Border] = ImVec4(0.53f, 0.53f, 0.53f, 0.46f);
colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
colors[ImGuiCol_FrameBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.85f);
colors[ImGuiCol_FrameBgHovered] = ImVec4(0.22f, 0.22f, 0.22f, 0.40f);
colors[ImGuiCol_FrameBgActive] = ImVec4(0.16f, 0.16f, 0.16f, 0.53f);
colors[ImGuiCol_TitleBg] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);
colors[ImGuiCol_TitleBgActive] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);
colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.00f, 0.00f, 0.00f, 0.51f);
colors[ImGuiCol_MenuBarBg] = ImVec4(0.12f, 0.12f, 0.12f, 1.00f);
colors[ImGuiCol_ScrollbarBg] = ImVec4(0.02f, 0.02f, 0.02f, 0.53f);
colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f);
colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.41f, 0.41f, 0.41f, 1.00f);
colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.48f, 0.48f, 0.48f, 1.00f);
colors[ImGuiCol_CheckMark] = ImVec4(0.79f, 0.79f, 0.79f, 1.00f);
colors[ImGuiCol_SliderGrab] = ImVec4(0.48f, 0.47f, 0.47f, 0.91f);
colors[ImGuiCol_SliderGrabActive] = ImVec4(0.56f, 0.55f, 0.55f, 0.62f);
colors[ImGuiCol_Button] = ImVec4(0.50f, 0.50f, 0.50f, 0.63f);
colors[ImGuiCol_ButtonHovered] = ImVec4(0.67f, 0.67f, 0.68f, 0.63f);
colors[ImGuiCol_ButtonActive] = ImVec4(0.26f, 0.26f, 0.26f, 0.63f);
colors[ImGuiCol_Header] = ImVec4(0.54f, 0.54f, 0.54f, 0.58f);
colors[ImGuiCol_HeaderHovered] = ImVec4(0.64f, 0.65f, 0.65f, 0.80f);
colors[ImGuiCol_HeaderActive] = ImVec4(0.25f, 0.25f, 0.25f, 0.80f);
colors[ImGuiCol_Separator] = ImVec4(0.58f, 0.58f, 0.58f, 0.50f);
colors[ImGuiCol_SeparatorHovered] = ImVec4(0.81f, 0.81f, 0.81f, 0.64f);
colors[ImGuiCol_SeparatorActive] = ImVec4(0.81f, 0.81f, 0.81f, 0.64f);
colors[ImGuiCol_ResizeGrip] = ImVec4(0.87f, 0.87f, 0.87f, 0.53f);
colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.87f, 0.87f, 0.87f, 0.74f);
colors[ImGuiCol_ResizeGripActive] = ImVec4(0.87f, 0.87f, 0.87f, 0.74f);
colors[ImGuiCol_Tab] = ImVec4(0.01f, 0.01f, 0.01f, 0.86f);
colors[ImGuiCol_TabHovered] = ImVec4(0.29f, 0.29f, 0.79f, 1.00f);
colors[ImGuiCol_TabActive] = ImVec4(0.31f, 0.31f, 0.91f, 1.00f);
colors[ImGuiCol_TabUnfocused] = ImVec4(0.02f, 0.02f, 0.02f, 1.00f);
colors[ImGuiCol_TabUnfocusedActive] = ImVec4(0.19f, 0.19f, 0.19f, 1.00f);
colors[ImGuiCol_DockingPreview] = ImVec4(0.38f, 0.48f, 0.60f, 1.00f);
colors[ImGuiCol_DockingEmptyBg] = ImVec4(0.20f, 0.20f, 0.20f, 1.00f);
colors[ImGuiCol_PlotLines] = ImVec4(0.61f, 0.61f, 0.61f, 1.00f);
colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.68f, 0.68f, 0.68f, 1.00f);
colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.77f, 0.33f, 1.00f);
colors[ImGuiCol_PlotHistogramHovered] = ImVec4(0.87f, 0.55f, 0.08f, 1.00f);
colors[ImGuiCol_TextSelectedBg] = ImVec4(0.47f, 0.60f, 0.76f, 0.47f);
colors[ImGuiCol_DragDropTarget] = ImVec4(0.58f, 0.58f, 0.58f, 0.90f);
colors[ImGuiCol_NavHighlight] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f);
colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f);
colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f);
colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.35f);
}
//extern ImGui::MarkdownConfig mdConfig;
ImFont* smallAF, * bigAF, * mediumAF;
void InitFonts()
{
ImGuiIO& io = ImGui::GetIO();
io.Fonts->Clear();
static const ImWchar icons_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 };
ImFontConfig icons_config;
icons_config.MergeMode = true;
icons_config.PixelSnapH = true;
float fontSize_ = 16.f;
static const char* defaultFontPath = "Fonts/OpenSans-SemiBold.ttf";
io.Fonts->AddFontFromFileTTF(defaultFontPath, fontSize_);
smallAF = io.Fonts->AddFontFromFileTTF("Fonts/" FONT_ICON_FILE_NAME_FAS, fontSize_, &icons_config, icons_ranges);
mediumAF = io.Fonts->AddFontFromFileTTF(defaultFontPath, 20.f);
io.Fonts->AddFontFromFileTTF("Fonts/" FONT_ICON_FILE_NAME_FAS, 20.f, &icons_config, icons_ranges);
bigAF = io.Fonts->AddFontFromFileTTF(defaultFontPath, 24.f);
io.Fonts->AddFontFromFileTTF("Fonts/" FONT_ICON_FILE_NAME_FAS, 24.f, &icons_config, icons_ranges);
/*
// Bold headings H2 and H3
mdConfig.headingFormats[1].font = io.Fonts->AddFontFromFileTTF("Stock/Fonts/OpenSans-ExtraBold.ttf", fontSize_);
mdConfig.headingFormats[2].font = mdConfig.headingFormats[1].font;
// bold heading H1
float fontSizeH1 = fontSize_ * 1.2f;
mdConfig.headingFormats[0].font = io.Fonts->AddFontFromFileTTF("Stock/Fonts/OpenSans-ExtraBold.ttf", fontSizeH1);
*/
}
| 51.542056 | 117 | 0.688123 |
deb89d9db31f248c546602d7996ccbd4f783a53d | 269 | cpp | C++ | examples/algos/subset-xor-maximization/example-1.cpp | parth-07/dragon | 2e771d698398303c8ae6d603d28bc3acfa116181 | [
"MIT"
] | 1 | 2021-02-24T17:51:32.000Z | 2021-02-24T17:51:32.000Z | examples/algos/subset-xor-maximization/example-1.cpp | parth-07/dragon | 2e771d698398303c8ae6d603d28bc3acfa116181 | [
"MIT"
] | 1 | 2021-02-24T17:57:04.000Z | 2021-05-17T11:09:40.000Z | examples/algos/subset-xor-maximization/example-1.cpp | parth-07/ds-and-algos | 2e771d698398303c8ae6d603d28bc3acfa116181 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include "dragon/algos/subset-xor-maximization.hpp"
int main() {
std::vector<int> v{48, 32, 31};
std::cout<<dragon::maximum_subset_xor_value(v)<<"\n";
std::cout<<dragon::maximum_subset_xor_value(v.begin(), v.end())<<"\n";
}
| 26.9 | 72 | 0.680297 |
deba72bc62b66ae33e4534d7a1553b5ece28dbbd | 465 | cpp | C++ | cpp codes/ThreeDigitArmstrongNumber.cpp | umesh-negi/Hacktoberfest2020 | eaa0455ed1f111d9019dacf1cce19d7679009725 | [
"MIT"
] | null | null | null | cpp codes/ThreeDigitArmstrongNumber.cpp | umesh-negi/Hacktoberfest2020 | eaa0455ed1f111d9019dacf1cce19d7679009725 | [
"MIT"
] | null | null | null | cpp codes/ThreeDigitArmstrongNumber.cpp | umesh-negi/Hacktoberfest2020 | eaa0455ed1f111d9019dacf1cce19d7679009725 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n,r,sum=0,temp;
cout<<"Enter a three digit positive integer: ";
cin>>n;
temp=n;
while(n>0)
{
r=n%10;
sum=sum+(r*r*r);
n=n/10;
}
if(temp==sum)
cout<<temp<<" is an Armstrong Number."<<endl;
else
cout<<temp<<" is not an Armstrong Number."<<endl;
return 0;
}
| 22.142857 | 60 | 0.443011 |
debd512b89d62a5af5f86ed64acef38fef6159ba | 176 | cpp | C++ | shared/qstd.cpp | Guilyx/Pendu | 6ccd6a5a566d900d73422f70a99aec05f9e3ce10 | [
"BSD-3-Clause"
] | null | null | null | shared/qstd.cpp | Guilyx/Pendu | 6ccd6a5a566d900d73422f70a99aec05f9e3ce10 | [
"BSD-3-Clause"
] | null | null | null | shared/qstd.cpp | Guilyx/Pendu | 6ccd6a5a566d900d73422f70a99aec05f9e3ce10 | [
"BSD-3-Clause"
] | null | null | null | #include "qstd.h"
QTextStream qstd::cin(stdin,QIODevice::ReadOnly);
QTextStream qstd::cout(stdout,QIODevice::WriteOnly);
QTextStream qstd::cerr(stderr, QIODevice::WriteOnly);
| 29.333333 | 53 | 0.784091 |
debe935fde02f6f2ba3a1451dc340f8fed2236e2 | 1,070 | cc | C++ | app/node/node_modules/httpsync/src/curl.cc | syntaxerrors/Stories | c24e3f5ac37c0e3467d385bdd4ba02fe4d0a5eb8 | [
"MIT"
] | 1 | 2020-05-24T19:36:54.000Z | 2020-05-24T19:36:54.000Z | node_modules/httpsync/src/curl.cc | jeremyfa/node-cocos2d-coffee-autocomplete | 4eac201d43bdd08ded26fea8916e9bf4ca73f88e | [
"MIT",
"Unlicense"
] | null | null | null | node_modules/httpsync/src/curl.cc | jeremyfa/node-cocos2d-coffee-autocomplete | 4eac201d43bdd08ded26fea8916e9bf4ca73f88e | [
"MIT",
"Unlicense"
] | null | null | null | #include "./curl.h"
void NodeCurl::Init(Handle<Object> target) {
target->Set(String::NewSymbol("request"),
FunctionTemplate::New(request)->GetFunction());
target->Set(String::NewSymbol("get"),
FunctionTemplate::New(get)->GetFunction());
}
// curl.request (options);
Handle<Value> NodeCurl::request(const Arguments& args) {
HandleScope scope;
if (args.Length() != 1 || !args[0]->IsObject()) {
return THROW_BAD_ARGS;
}
return Request::New(Handle<Object>::Cast(args[0]));
}
// curl.get (options | url);
Handle<Value> NodeCurl::get (const Arguments& args) {
HandleScope scope;
if (args.Length() != 1 || (!args[0]->IsObject() && !args[0]->IsString())) {
return THROW_BAD_ARGS;
}
Handle<Object> options = Object::New();
if (args[0]->IsString()) {
options->Set(String::NewSymbol("url"), args[0]);
options->Set(String::NewSymbol("method"), String::New("GET"));
} else {
options = Handle<Object>::Cast(args[0]);
options->Set(String::NewSymbol("method"), String::New("GET"));
}
return Request::New (options);
}
| 26.097561 | 77 | 0.639252 |
dec07522838bb529579d678c2d24200377ab029c | 604 | cpp | C++ | example/asyncdeamon.cpp | apppur/canna | bdcce4f16be56da40445fec79959b6bc90003573 | [
"MIT"
] | null | null | null | example/asyncdeamon.cpp | apppur/canna | bdcce4f16be56da40445fec79959b6bc90003573 | [
"MIT"
] | null | null | null | example/asyncdeamon.cpp | apppur/canna | bdcce4f16be56da40445fec79959b6bc90003573 | [
"MIT"
] | null | null | null | #include <thread>
#include <functional>
#include <stdio.h>
#include <memory>
#include "asyncclient.h"
#include "asyncserver.h"
int main(int argc, char** argv)
{
asyncclient async1;
asyncclient async2;
asyncclient async3;
asyncserver server;
std::thread t1(std::bind(&asyncclient::start, &async1));
std::thread t2(std::bind(&asyncclient::start, &async2));
std::thread t3(std::bind(&asyncclient::start, &async3));
std::thread t4(std::bind(&asyncserver::run, &server));
t1.detach();
t2.detach();
t3.detach();
t4.detach();
getchar();
return 0;
}
| 20.133333 | 60 | 0.642384 |
dec2f325f34c51e9af008d0a401b695be3e82249 | 442 | cpp | C++ | algorithms/cpp/deleteNodeInALinkedList/test.cpp | mzlogin/LeetCode | b0ccb0f84eafe60ff355e4ab81bde2f39c043035 | [
"MIT"
] | 2 | 2017-03-27T17:20:28.000Z | 2018-06-07T15:15:54.000Z | algorithms/cpp/deleteNodeInALinkedList/test.cpp | mzlogin/LeetCode | b0ccb0f84eafe60ff355e4ab81bde2f39c043035 | [
"MIT"
] | 2 | 2015-12-13T02:58:29.000Z | 2016-09-15T00:00:22.000Z | algorithms/cpp/deleteNodeInALinkedList/test.cpp | mzlogin/LeetCode | b0ccb0f84eafe60ff355e4ab81bde2f39c043035 | [
"MIT"
] | null | null | null | #include "../catch.h"
#include "../mylist.h"
#include "solution.h"
TEST_CASE("Delete Node In a Linked List", "deleteNodeInALinkedList") {
Solution sln;
const int len = 4;
int nums[len] = {1,2,3,4};
ListNode* root = createList(nums, len);
ListNode* p = root->next->next;
sln.deleteNode(p);
CHECK(getListValueAt(root, 2) == 4);
p = root->next;
sln.deleteNode(p);
CHECK(getListValueAt(root, 1) == 4);
}
| 24.555556 | 70 | 0.615385 |
dec60f7023fc0c5f3a3f7e986d258647535c871b | 499 | cc | C++ | leetcode/src/balaced_binary_tree.cc | plusplus7/solutions | 31233c13ee2bd0da6a907a24adbaf5b49ebf843c | [
"CC0-1.0"
] | 5 | 2016-04-29T07:14:23.000Z | 2020-01-07T04:56:11.000Z | leetcode/src/balaced_binary_tree.cc | plusplus7/solutions | 31233c13ee2bd0da6a907a24adbaf5b49ebf843c | [
"CC0-1.0"
] | null | null | null | leetcode/src/balaced_binary_tree.cc | plusplus7/solutions | 31233c13ee2bd0da6a907a24adbaf5b49ebf843c | [
"CC0-1.0"
] | 1 | 2016-04-29T07:14:32.000Z | 2016-04-29T07:14:32.000Z | #include <iostream>
using namespace std;
class Solution {
public:
int dfs(TreeNode *node) {
if (node == NULL)
return 0;
return max(dfs(node->left, dep+1), dfs(node->right, dep+1))+1;
}
bool isBalanced(TreeNode *root) {
if (root == NULL)
return true;
if (abs(dfs(node->left)-dfs(node->right)) > 1)
return false;
else
return isBalanced(root->left) == true && isBalanced(root->right) == true;
}
};
| 26.263158 | 85 | 0.537074 |
decdd07a00f33af05ff4c749316d9b1956486241 | 2,237 | cpp | C++ | tests/common_test/tests/mask_tests/circle_mask_tests.cpp | JulianBiancardi/Wolfenstein-Taller1 | 28e72ce8438264919586785aa09ce9b0a5de222b | [
"MIT"
] | 1 | 2021-04-23T19:57:40.000Z | 2021-04-23T19:57:40.000Z | tests/common_test/tests/mask_tests/circle_mask_tests.cpp | JulianBiancardi/Wolfenstein-Taller1 | 28e72ce8438264919586785aa09ce9b0a5de222b | [
"MIT"
] | null | null | null | tests/common_test/tests/mask_tests/circle_mask_tests.cpp | JulianBiancardi/Wolfenstein-Taller1 | 28e72ce8438264919586785aa09ce9b0a5de222b | [
"MIT"
] | null | null | null | #include "circle_mask_tests.h"
#include "../../main/collisions/circle_mask.h"
#include "../../main/utils/point.h"
#include "../tests_setup.h"
int static creation_test();
int static center_test();
int static interior_test();
int static border_test();
int static exterior_test();
void circle_mask_tests() {
begin_tests("CIRCLE MASK");
print_test("La máscara circular se crea correctamente", creation_test,
NO_ERROR);
print_test("La máscara circular ocupa su centro", center_test, NO_ERROR);
print_test(
"La máscara circular ocupa puntos dentro de su circunferencia límite",
interior_test, NO_ERROR);
print_test("La máscara circular ocupa puntos en su circunferencia límite",
border_test, NO_ERROR);
print_test("La máscara circular no ocupa puntos fuera de su circunferencia",
exterior_test, NO_ERROR);
end_tests();
}
int static creation_test() {
Point center(0, 0);
CircleMask mask(1, center);
return NO_ERROR;
}
int static center_test() {
Point center(0, 0);
CircleMask mask(1, center);
Point center_p(0, 0);
if (!mask.occupies(center_p)) {
return ERROR;
}
return NO_ERROR;
}
int static interior_test() {
Point center(0, 0);
CircleMask mask(1, center);
Point p1(-0.1, 0.5);
Point p2(-0.6, -0.79);
Point p3(0.8, 0.0);
Point p4(0, 0.3);
Point p5(-0.2, 0.2);
if (!mask.occupies(p1)) {
return ERROR;
}
if (!mask.occupies(p2)) {
return ERROR;
}
if (!mask.occupies(p3)) {
return ERROR;
}
if (!mask.occupies(p4)) {
return ERROR;
}
if (!mask.occupies(p5)) {
return ERROR;
}
return NO_ERROR;
}
int static border_test() {
Point center(0, 0);
CircleMask mask(1, center);
Point p1(0, 1);
Point p2(0, -1);
Point p3(1, 0);
Point p4(-1, 0);
if (!mask.occupies(p1) || !mask.occupies(p2) || !mask.occupies(p3) ||
!mask.occupies(p4)) {
return ERROR;
}
return NO_ERROR;
}
int static exterior_test() {
Point center(0, 0);
CircleMask mask(1, center);
Point p1(0, 2);
Point p2(0, 1.1);
Point p3(1, 1);
Point p4(0, -1.5);
if (mask.occupies(p1) || mask.occupies(p2) || mask.occupies(p3) ||
mask.occupies(p4)) {
return ERROR;
}
return NO_ERROR;
}
| 21.103774 | 78 | 0.640143 |
dece96829fe573ed8b4ad39e4772d59a7b19567a | 1,179 | hpp | C++ | FFmpegServer/FFmpegYAGuiDroidCapture_PacketQueue/include/Buffer/BufferData.hpp | aalekhm/OpenFF | 9df23a21727f29a871f7239ccf15e3100ae9780e | [
"MIT"
] | null | null | null | FFmpegServer/FFmpegYAGuiDroidCapture_PacketQueue/include/Buffer/BufferData.hpp | aalekhm/OpenFF | 9df23a21727f29a871f7239ccf15e3100ae9780e | [
"MIT"
] | null | null | null | FFmpegServer/FFmpegYAGuiDroidCapture_PacketQueue/include/Buffer/BufferData.hpp | aalekhm/OpenFF | 9df23a21727f29a871f7239ccf15e3100ae9780e | [
"MIT"
] | null | null | null | #pragma once
#include "Common/Defines.h"
#include "Common/RandomAccessFile.h"
class BufferData
{
public:
BufferData()
: m_iBufferSize(-1)
, m_pBuffer(nullptr)
{ }
BufferData(size_t iBufferSize)
{
setSize(iBufferSize);
}
void operator=(BufferData& pBufferData)
{
cleanup();
setSize(pBufferData.m_iBufferSize);
memcpy_s(m_pBuffer, m_iBufferSize, pBufferData.m_pBuffer, pBufferData.m_iBufferSize);
}
void setSize(size_t iBufferSize)
{
if (iBufferSize != m_iBufferSize)
{
cleanup();
}
m_iBufferSize = iBufferSize;
m_pBuffer = (uint8_t*)std::malloc(iBufferSize);
}
virtual ~BufferData()
{
cleanup();
}
void cleanup()
{
m_iBufferSize = -1;
if (m_pBuffer != nullptr)
{
std::free(m_pBuffer);
m_pBuffer = nullptr;
}
}
void saveToDisk(std::string sFileName)
{
RandomAccessFile* raf = new RandomAccessFile();
if (raf->openForWrite(sFileName.c_str()))
{
LOG_CONSOLE("Saving buffer to disk! size = " << m_iBufferSize);
raf->write((char*)m_pBuffer, 0, m_iBufferSize);
raf->close();
}
}
uint8_t* m_pBuffer;
size_t m_iBufferSize;
protected:
private:
};
| 17.338235 | 88 | 0.65564 |
ded00ab6f7ed575fdcb08faaef40996cf6db9fbf | 7,069 | cpp | C++ | libs/dev/Math/MathEngineTest/Matrix_Constructor.cpp | Norseman055/immaterial-engine | 6aca0fad64f5b2b9fe6eb351528a79a39dc94625 | [
"MIT"
] | null | null | null | libs/dev/Math/MathEngineTest/Matrix_Constructor.cpp | Norseman055/immaterial-engine | 6aca0fad64f5b2b9fe6eb351528a79a39dc94625 | [
"MIT"
] | null | null | null | libs/dev/Math/MathEngineTest/Matrix_Constructor.cpp | Norseman055/immaterial-engine | 6aca0fad64f5b2b9fe6eb351528a79a39dc94625 | [
"MIT"
] | null | null | null | //---------------------------------------------------------------------------
// HEADER FILES:
//---------------------------------------------------------------------------
#include "UnitTest.h"
#include "MathEngine.h"
#define eq Util::isEqual
#define MATH_TOLERANCE 0.0001f
//---------------------------------------------------------------------------
// TESTS:
//---------------------------------------------------------------------------
TEST( Matrix_default_constructor, matix_tests )
{
Matrix M;
CHECK( M[m0] == 0.0f );
CHECK( M[m1] == 0.0f );
CHECK( M[m2] == 0.0f );
CHECK( M[m3] == 0.0f );
CHECK( M[m4] == 0.0f );
CHECK( M[m5] == 0.0f );
CHECK( M[m6] == 0.0f );
CHECK( M[m7] == 0.0f );
CHECK( M[m8] == 0.0f );
CHECK( M[m9] == 0.0f );
CHECK( M[m10] == 0.0f );
CHECK( M[m11] == 0.0f );
CHECK( M[m12] == 0.0f );
CHECK( M[m13] == 0.0f );
CHECK( M[m14] == 0.0f );
CHECK( M[m15] == 0.0f );
}
TEST( Matrix_vector_constructor, matix_tests )
{
Vect V0(1.0f,2.0f,3.0f,4.0f);
Vect V1(7.0f,6.0f,5.0f,3.0f);
Vect V2(-4.0f,-2.0f,-1.0f,-4.0f);
Vect V3(9.0f,-7.0f,-2.0f,5.0f);
CHECK( V0[x] == 1.0f );
CHECK( V0[y] == 2.0f );
CHECK( V0[z] == 3.0f );
CHECK( V0[w] == 4.0f );
CHECK( V1[x] == 7.0f );
CHECK( V1[y] == 6.0f );
CHECK( V1[z] == 5.0f );
CHECK( V1[w] == 3.0f );
CHECK( V2[x] == -4.0f );
CHECK( V2[y] == -2.0f );
CHECK( V2[z] == -1.0f );
CHECK( V2[w] == -4.0f );
CHECK( V3[x] == 9.0f );
CHECK( V3[y] == -7.0f );
CHECK( V3[z] == -2.0f );
CHECK( V3[w] == 5.0f );
Matrix M(V0,V1,V2,V3);
CHECK( M[m0] == 1.0f );
CHECK( M[m1] == 2.0f );
CHECK( M[m2] == 3.0f );
CHECK( M[m3] == 4.0f );
CHECK( M[m4] == 7.0f );
CHECK( M[m5] == 6.0f );
CHECK( M[m6] == 5.0f );
CHECK( M[m7] == 3.0f );
CHECK( M[m8] == -4.0f );
CHECK( M[m9] == -2.0f );
CHECK( M[m10] == -1.0f );
CHECK( M[m11] == -4.0f );
CHECK( M[m12] == 9.0f );
CHECK( M[m13] == -7.0f );
CHECK( M[m14] == -2.0f );
CHECK( M[m15] == 5.0f );
}
TEST( Matrix_copy_constructor, matix_tests )
{
Vect V0(1.0f,2.0f,3.0f,4.0f);
Vect V1(7.0f,6.0f,5.0f,3.0f);
Vect V2(-4.0f,-2.0f,-1.0f,-4.0f);
Vect V3(9.0f,-7.0f,-2.0f,5.0f);
CHECK( V0[x] == 1.0f );
CHECK( V0[y] == 2.0f );
CHECK( V0[z] == 3.0f );
CHECK( V0[w] == 4.0f );
CHECK( V1[x] == 7.0f );
CHECK( V1[y] == 6.0f );
CHECK( V1[z] == 5.0f );
CHECK( V1[w] == 3.0f );
CHECK( V2[x] == -4.0f );
CHECK( V2[y] == -2.0f );
CHECK( V2[z] == -1.0f );
CHECK( V2[w] == -4.0f );
CHECK( V3[x] == 9.0f );
CHECK( V3[y] == -7.0f );
CHECK( V3[z] == -2.0f );
CHECK( V3[w] == 5.0f );
Matrix M(V0,V1,V2,V3);
Matrix N( M );
CHECK( N[m0] == 1.0f );
CHECK( N[m1] == 2.0f );
CHECK( N[m2] == 3.0f );
CHECK( N[m3] == 4.0f );
CHECK( N[m4] == 7.0f );
CHECK( N[m5] == 6.0f );
CHECK( N[m6] == 5.0f );
CHECK( N[m7] == 3.0f );
CHECK( N[m8] == -4.0f );
CHECK( N[m9] == -2.0f );
CHECK( N[m10] == -1.0f );
CHECK( N[m11] == -4.0f );
CHECK( N[m12] == 9.0f );
CHECK( N[m13] == -7.0f );
CHECK( N[m14] == -2.0f );
CHECK( N[m15] == 5.0f );
CHECK( M[m0] == 1.0f );
CHECK( M[m1] == 2.0f );
CHECK( M[m2] == 3.0f );
CHECK( M[m3] == 4.0f );
CHECK( M[m4] == 7.0f );
CHECK( M[m5] == 6.0f );
CHECK( M[m6] == 5.0f );
CHECK( M[m7] == 3.0f );
CHECK( M[m8] == -4.0f );
CHECK( M[m9] == -2.0f );
CHECK( M[m10] == -1.0f );
CHECK( M[m11] == -4.0f );
CHECK( M[m12] == 9.0f );
CHECK( M[m13] == -7.0f );
CHECK( M[m14] == -2.0f );
CHECK( M[m15] == 5.0f );
}
TEST( Destructor_constuctor, matrix_tests )
{
Vect V0(1.0f,2.0f,3.0f,4.0f);
Vect V1(7.0f,6.0f,5.0f,3.0f);
Vect V2(-4.0f,-2.0f,-1.0f,-4.0f);
Vect V3(9.0f,-7.0f,-2.0f,5.0f);
Matrix M(V0,V1,V2,V3);
Matrix *pM = &M;
pM->~Matrix();
CHECK(1);
}
TEST( MatrixRotAxisAngle, matrix_tests )
{
// Axis and Angle Type Constructor:
Vect v11( 2.0f, 53.0f, 24.0f);
Matrix m54( ROT_AXIS_ANGLE, v11, MATH_PI3 );
// => Vect v11( 2.0f, 53.0f, 24.0f); \n"););
// => Matrix m54(ROT_AXIS_ANGLE, v11, MATH_PI3 );\n"););
CHECK( eq(m54[m0], 0.5005f, MATH_TOLERANCE) );
CHECK( eq(m54[m1], 0.3726f, MATH_TOLERANCE) );
CHECK( eq(m54[m2],-0.7813f, MATH_TOLERANCE) );
CHECK( m54[m3] == 0.0f );
CHECK( eq(m54[m4],-0.3413f, MATH_TOLERANCE) );
CHECK( eq(m54[m5], 0.9144f, MATH_TOLERANCE) );
CHECK( eq(m54[m6], 0.2174f, MATH_TOLERANCE) );
CHECK( (m54[m7] == 0.0f) );
CHECK( eq(m54[m8], 0.7955f, MATH_TOLERANCE) );
CHECK( eq(m54[m9], 0.1579f, MATH_TOLERANCE) );
CHECK( eq(m54[m10], 0.5849f, MATH_TOLERANCE) );
CHECK( (m54[m11] == 0.0f) );
CHECK( (m54[m12] == 0.0f) );
CHECK( (m54[m13] == 0.0f) );
CHECK( (m54[m14] == 0.0f) );
CHECK( (m54[m15] == 1.0f) );
}
TEST( MatrixRotOrient, matrix_tests )
{
// Orientation Type Constructor:
Vect v15( 2.0f, 53.0f, 24.0f);
Vect v16( 0.0f, -24.0f, 53.0f);
Matrix m56(ROT_ORIENT, v15, v16 );
CHECK( eq(m56[m0],-0.9994f, MATH_TOLERANCE) );
CHECK( eq(m56[m1], 0.0313f, MATH_TOLERANCE) );
CHECK( eq(m56[m2], 0.0142f, MATH_TOLERANCE) );
CHECK( (m56[m3] == 0.0f) );
CHECK( eq(m56[m4], 0.0000f, MATH_TOLERANCE) );
CHECK( eq(m56[m5],-0.4125f, MATH_TOLERANCE) );
CHECK( eq(m56[m6], 0.9110f, MATH_TOLERANCE) );
CHECK( (m56[m7] == 0.0f) );
CHECK( eq(m56[m8], 0.0344f, MATH_TOLERANCE) );
CHECK( eq(m56[m9], 0.9104f, MATH_TOLERANCE) );
CHECK( eq(m56[m10], 0.4123f, MATH_TOLERANCE) );
CHECK( (m56[m11] == 0.0f) );
CHECK( (m56[m12] == 0.0f) );
CHECK( (m56[m13] == 0.0f) );
CHECK( (m56[m14] == 0.0f) );
CHECK( (m56[m15] == 1.0f) );
}
TEST( MatrixRotInverseOrient, matrix_tests)
{
// Orientation Type Constructor:
Vect v17( 2.0f, 53.0f, 24.0f);
Vect v18( 0.0f, -24.0f, 53.0f);
Matrix m57(ROT_INVERSE_ORIENT, v17, v18 );
CHECK( eq(m57[m0],-0.9994f, MATH_TOLERANCE) );
CHECK( eq(m57[m1], 0.0000f, MATH_TOLERANCE) );
CHECK( eq(m57[m2], 0.0344f, MATH_TOLERANCE) );
CHECK( (m57[m3] == 0.0f) );
CHECK( eq(m57[m4], 0.0313f, MATH_TOLERANCE) );
CHECK( eq(m57[m5],-0.4125f, MATH_TOLERANCE) );
CHECK( eq(m57[m6], 0.9104f, MATH_TOLERANCE) );
CHECK( (m57[m7] == 0.0f) );
CHECK( eq(m57[m8], 0.0142f, MATH_TOLERANCE) );
CHECK( eq(m57[m9], 0.9110f, MATH_TOLERANCE) );
CHECK( eq(m57[m10], 0.4123f, MATH_TOLERANCE) );
CHECK( (m57[m11] == 0.0f) );
CHECK( (m57[m12] == 0.0f) );
CHECK( (m57[m13] == 0.0f) );
CHECK( (m57[m14] == 0.0f) );
CHECK( (m57[m15] == 1.0f) );
}
TEST( MatrixQuaternion, matrix_tests)
{
// Quaternion Type Constructor:
Matrix Rxyz1(ROT_XYZ, MATH_PI3, MATH_5PI8, MATH_PI4 );
Quat Qxyz1(Rxyz1);
Matrix Mxyz1( Qxyz1 );
CHECK( eq(Mxyz1[m0],-0.2705f,MATH_TOLERANCE) );
CHECK( eq(Mxyz1[m1],-0.2705f,MATH_TOLERANCE) );
CHECK( eq(Mxyz1[m2],-0.9238f,MATH_TOLERANCE) );
CHECK( (Mxyz1[m3] == 0.0f) );
CHECK( eq(Mxyz1[m4], 0.2122f,MATH_TOLERANCE) );
CHECK( eq(Mxyz1[m5], 0.9193f,MATH_TOLERANCE) );
CHECK( eq(Mxyz1[m6],-0.3314f,MATH_TOLERANCE) );
CHECK( (Mxyz1[m7] == 0.0f) );
CHECK( eq(Mxyz1[m8], 0.9390f,MATH_TOLERANCE) );
CHECK( eq(Mxyz1[m9],-0.2857f,MATH_TOLERANCE) );
CHECK( eq(Mxyz1[m10],-0.1913f,MATH_TOLERANCE) );
CHECK( (Mxyz1[m11] == 0.0f) );
CHECK( (Mxyz1[m12] == 0.0f) );
CHECK( (Mxyz1[m13] == 0.0f) );
CHECK( (Mxyz1[m14] == 0.0f) );
CHECK( (Mxyz1[m15] == 1.0f) );
} | 26.776515 | 77 | 0.530485 |
ded12ff193fedcafbc3acfc7a1a1a355ddaec06d | 1,170 | cpp | C++ | nodes/DataLoggerNode/DataLoggerProcess.cpp | dgitz/eROS | 0ff4b5dda5f3d445784d43745597bb5c31d1997c | [
"MIT"
] | 2 | 2016-11-28T13:01:12.000Z | 2021-03-26T22:02:02.000Z | nodes/DataLoggerNode/DataLoggerProcess.cpp | dgitz/eROS | 0ff4b5dda5f3d445784d43745597bb5c31d1997c | [
"MIT"
] | 46 | 2016-10-24T13:34:48.000Z | 2019-11-14T23:47:22.000Z | nodes/DataLoggerNode/DataLoggerProcess.cpp | dgitz/eros | 0ff4b5dda5f3d445784d43745597bb5c31d1997c | [
"MIT"
] | 2 | 2021-07-20T10:11:45.000Z | 2021-08-10T11:31:41.000Z | #include <eros/DataLogger/DataLoggerProcess.h>
using namespace eros;
using namespace eros_nodes;
DataLoggerProcess::DataLoggerProcess()
: log_directory(""),
log_directory_available(false),
logfile_duration(-1.0),
logging_enabled(false),
snapshot_mode(true) {
}
DataLoggerProcess::~DataLoggerProcess() {
}
Diagnostic::DiagnosticDefinition DataLoggerProcess::finish_initialization() {
Diagnostic::DiagnosticDefinition diag;
return diag;
}
void DataLoggerProcess::reset() {
}
Diagnostic::DiagnosticDefinition DataLoggerProcess::update(double t_dt, double t_ros_time) {
Diagnostic::DiagnosticDefinition diag = base_update(t_dt, t_ros_time);
ready_to_arm.ready_to_arm = true;
ready_to_arm.diag = convert(diag);
return diag;
}
std::vector<Diagnostic::DiagnosticDefinition> DataLoggerProcess::new_commandmsg(eros::command msg) {
(void)msg; // Not used yet.
std::vector<Diagnostic::DiagnosticDefinition> diag_list;
return diag_list;
}
std::vector<Diagnostic::DiagnosticDefinition> DataLoggerProcess::check_programvariables() {
std::vector<Diagnostic::DiagnosticDefinition> diag_list;
return diag_list;
}
| 33.428571 | 100 | 0.761538 |
ded73d86410b8acca4b20373f5b8e439c0127133 | 841 | cc | C++ | libconfluo/src/compression/confluo_encoder.cc | Mu-L/confluo | e9b8621e99f56b1adf5675c4296c006d89e6e582 | [
"Apache-2.0"
] | 1,398 | 2018-12-05T19:13:15.000Z | 2022-03-29T08:26:03.000Z | libconfluo/src/compression/confluo_encoder.cc | Mu-L/confluo | e9b8621e99f56b1adf5675c4296c006d89e6e582 | [
"Apache-2.0"
] | 53 | 2018-10-21T03:28:25.000Z | 2021-03-16T03:50:54.000Z | libconfluo/src/compression/confluo_encoder.cc | Mu-L/confluo | e9b8621e99f56b1adf5675c4296c006d89e6e582 | [
"Apache-2.0"
] | 208 | 2018-10-28T03:05:46.000Z | 2022-02-06T06:16:37.000Z | #include "compression/confluo_encoder.h"
namespace confluo {
namespace compression {
unique_byte_array confluo_encoder::encode(void *ptr, size_t size, uint8_t encoding) {
switch (encoding) {
case encoding_type::D_UNENCODED: {
return unique_byte_array(reinterpret_cast<uint8_t *>(ptr), size, no_op_delete);
}
case encoding_type::D_ELIAS_GAMMA: {
uint64_t *casted = reinterpret_cast<uint64_t *>(ptr);
size_t array_len = size / sizeof(uint64_t);
return delta_encoder::encode<uint64_t>(casted, array_len);
}
case encoding_type::D_LZ4: {
uint8_t *casted = reinterpret_cast<uint8_t *>(ptr);
return lz4_encoder<>::encode(casted, size);
}
default : {
THROW(illegal_state_exception, "Invalid encoding type!");
}
}
}
void confluo_encoder::no_op_delete(uint8_t *) {}
}
} | 29 | 85 | 0.6956 |
ded97349fac892fd74f4c924f410dd860981d4da | 19,721 | inl | C++ | ivp/havana/havok/hk_math/vector_fpu/vector_fpu.inl | DannyParker0001/Kisak-Strike | 99ed85927336fe3aff2efd9b9382b2b32eb1d05d | [
"Unlicense"
] | 252 | 2020-12-16T15:34:43.000Z | 2022-03-31T23:21:37.000Z | ivp/havana/havok/hk_math/vector_fpu/vector_fpu.inl | DannyParker0001/Kisak-Strike | 99ed85927336fe3aff2efd9b9382b2b32eb1d05d | [
"Unlicense"
] | 23 | 2020-12-20T18:02:54.000Z | 2022-03-28T16:58:32.000Z | ivp/havana/havok/hk_math/vector_fpu/vector_fpu.inl | DannyParker0001/Kisak-Strike | 99ed85927336fe3aff2efd9b9382b2b32eb1d05d | [
"Unlicense"
] | 42 | 2020-12-19T04:32:33.000Z | 2022-03-30T06:00:28.000Z |
inline void hk_VecFPU::fpu_add_multiple_row(hk_real *target_adress,hk_real *source_adress,hk_real factor,int size,hk_bool adress_aligned) {
if(adress_aligned==HK_FALSE) {
//we have to calculate the block size and shift adresses to lower aligned adresses
long result_adress = long(source_adress) & hk_VecFPU_MEM_MASK_FLOAT;
target_adress = (hk_real *)( long (target_adress) & hk_VecFPU_MEM_MASK_FLOAT);
size += (long(source_adress)-result_adress)>>hk_VecFPU_MEMSHIFT_FLOAT;
source_adress=(hk_real *)result_adress;
}
#if defined(IVP_USE_PS2_VU0)
asm __volatile__("
mfc1 $8,%3
qmtc2 $8,vf5 # vf5.x factor
1:
lqc2 vf4,0x0(%1) # vf4 *source
vmulx.xyzw vf6,vf4,vf5 # vf6 *source * factor
lqc2 vf4,0x0(%0)
addi %0, 0x10
vadd.xyzw vf6,vf4,vf6 # vf6 = *dest + factor * *source
addi %2,-4
addi %1, 0x10
sqc2 vf6,-0x10(%0)
bgtz %2,1b
nop
"
: /* no output */
: "r" (target_adress), "r" (source_adress) , "r" (size), "f" (factor)
: "$8" , "memory");
#else
#if 0
# if defined(IVP_WILLAMETTE)
;
__m128d factor128=_mm_set1_pd(factor);
for(int i=size;i>0;i-=hk_VecFPU_SIZE_FLOAT) {
__m128d source_d=_mm_load_pd(source_adress);
__m128d prod_d=_mm_mul_pd(factor128,source_d);
__m128d target_d=_mm_load_pd(target_adress);
target_d=_mm_add_pd(prod_d,target_d);
_mm_store_pd(target_adress,target_d);
target_adress+=hk_VecFPU_SIZE_FLOAT;
source_adress+=hk_VecFPU_SIZE_FLOAT;
}
#endif
#endif
for(int i=size;i>0;i-=hk_VecFPU_SIZE_FLOAT) {
# if hk_VecFPU_SIZE_FLOAT == 2
hk_real a = source_adress[0] * factor;
hk_real b = source_adress[1] * factor;
a += target_adress[0];
b += target_adress[1];
target_adress[0] = a;
target_adress[1] = b;
# elif hk_VecFPU_SIZE_FLOAT == 4
hk_real a = source_adress[0] * factor;
hk_real b = source_adress[1] * factor;
hk_real c = source_adress[2] * factor;
hk_real d = source_adress[3] * factor;
a += target_adress[0];
b += target_adress[1];
c += target_adress[2];
d += target_adress[3];
target_adress[0] = a;
target_adress[1] = b;
target_adress[2] = c;
target_adress[3] = d;
# else
shit
# endif
target_adress+=hk_VecFPU_SIZE_FLOAT;
source_adress+=hk_VecFPU_SIZE_FLOAT;
}
#endif
}
inline hk_real hk_VecFPU::fpu_large_dot_product(hk_real *base_a, hk_real *base_b, int size, hk_bool adress_aligned) {
if(adress_aligned==HK_FALSE) {
//we have to calculate the block size and shift adresses to lower aligned adresses
long result_adress = long(base_a) & hk_VecFPU_MEM_MASK_FLOAT;
base_b = (hk_real *)( long (base_b) & hk_VecFPU_MEM_MASK_FLOAT);
size += (long(base_a)-result_adress)>>hk_VecFPU_MEMSHIFT_FLOAT; // because start changed
base_a=(hk_real *)result_adress;
}
# if defined(IVP_WILLAMETTE)
IVP_IF_WILLAMETTE_OPT(IVP_Environment_Manager::get_environment_manager()->ivp_willamette_optimization) {
__m128d sum128 =_mm_set1_pd(0.0f);
int i;
for(i=size;i>=hk_VecFPU_SIZE_FLOAT; i-= hk_VecFPU_SIZE_FLOAT) {
__m128d mult1=_mm_load_pd(base_a);
__m128d mult2=_mm_load_pd(base_b);
__m128d prod =_mm_mul_pd(mult1,mult2);
sum128 =_mm_add_pd(prod,sum128);
base_a += hk_VecFPU_SIZE_FLOAT;
base_b += hk_VecFPU_SIZE_FLOAT;
}
__m128d dummy,low,high;
low=sum128;
dummy=sum128;
//_mm_shuffle_pd(sum128,sum128,1); //swap high and low
sum128=_mm_unpackhi_pd(sum128,dummy);
high=sum128;
__m128d sum64=_mm_add_sd(low,high);
__m128d res=sum64;
//_mm_shuffle_pd(sum64,sum64,1);
hk_real result_sum;
_mm_store_sd(&result_sum,res);
for(;i>=0;i--) {
result_sum += base_a[i] * base_b[i];
}
return result_sum;
} else {
hk_real sum=0.0f;
for(int i=size-1;i>=0;i--) {
sum += base_a[i] * base_b[i];
}
return sum;
}
#else
hk_real sum=0.0f;
for(int i=size-1;i>=0;i--) {
sum += base_a[i] * base_b[i];
}
return sum;
#endif
}
inline void hk_VecFPU::fpu_multiply_row(hk_real *target_adress,hk_real factor,int size,hk_bool adress_aligned) {
if(adress_aligned==HK_FALSE) {
//we have to calculate the block size and shift adresses to lower aligned adresses
long adress,result_adress;
adress=(long)target_adress;
result_adress=adress & hk_VecFPU_MEM_MASK_FLOAT;
size+=(adress-result_adress)>>hk_VecFPU_MEMSHIFT_FLOAT;
target_adress=(hk_real *)result_adress;
}
#if 0
#ifdef IVP_WILLAMETTE
__m128d factor128=_mm_set1_pd(factor);
int i;
for(i=size;i>0;i-=hk_VecFPU_SIZE_FLOAT) {
__m128d target_d=_mm_load_pd(target_adress);
target_d=_mm_mul_pd(factor128,target_d);
_mm_store_pd(target_adress,target_d);
target_adress+=hk_VecFPU_SIZE_FLOAT;
}
#endif
#endif
int i;
for(i=size;i>0;i-=hk_VecFPU_SIZE_FLOAT) {
# if hk_VecFPU_SIZE_FLOAT == 2
hk_real a = target_adress[0] * factor;
hk_real b = target_adress[1] * factor;
target_adress[0] = a;
target_adress[1] = b;
# elif hk_VecFPU_SIZE_FLOAT == 4
hk_real a = target_adress[0] * factor;
hk_real b = target_adress[1] * factor;
hk_real c = target_adress[2] * factor;
hk_real d = target_adress[3] * factor;
target_adress[0] = a;
target_adress[1] = b;
target_adress[2] = c;
target_adress[3] = d;
# else
shit
# endif
target_adress+=hk_VecFPU_SIZE_FLOAT;
}
}
// #+# sparc says rui, optimize for non vector units ( hk_VecFPU_SIZE_FLOAT = 4 )
inline void hk_VecFPU::fpu_exchange_rows(hk_real *target_adress1,hk_real *target_adress2,int size,hk_bool adress_aligned) {
if(adress_aligned==HK_FALSE) {
//we have to calculate the block size and shift adresses to lower aligned adresses
long adress,result_adress;
adress=(long)target_adress1;
result_adress=adress & hk_VecFPU_MEM_MASK_FLOAT;
size+=(adress-result_adress)>>hk_VecFPU_MEMSHIFT_FLOAT;
target_adress1=(hk_real *)result_adress;
adress=(long)target_adress2;
adress=adress & hk_VecFPU_MEM_MASK_FLOAT;
target_adress2=(hk_real *)adress;
}
#if 0
int i;
for(i=size;i>0;i-=hk_VecFPU_SIZE_FLOAT) {
__m128d a_d=_mm_load_pd(target_adress1);
__m128d b_d=_mm_load_pd(target_adress2);
_mm_store_pd(target_adress1,b_d);
_mm_store_pd(target_adress2,a_d);
target_adress1+=hk_VecFPU_SIZE_FLOAT;
target_adress2+=hk_VecFPU_SIZE_FLOAT;
}
#endif
int i;
for(i=size;i>0;i-=hk_VecFPU_SIZE_FLOAT) {
hk_real h;
# if hk_VecFPU_SIZE_FLOAT == 2
h=target_adress1[0]; target_adress1[0]=target_adress2[0]; target_adress2[0]=h;
h=target_adress1[1]; target_adress1[1]=target_adress2[1]; target_adress2[1]=h;
# elif hk_VecFPU_SIZE_FLOAT == 4
h=target_adress1[0]; target_adress1[0]=target_adress2[0]; target_adress2[0]=h;
h=target_adress1[1]; target_adress1[1]=target_adress2[1]; target_adress2[1]=h;
h=target_adress1[2]; target_adress1[2]=target_adress2[2]; target_adress2[2]=h;
h=target_adress1[3]; target_adress1[3]=target_adress2[3]; target_adress2[3]=h;
# else
shit
# endif
target_adress1+=hk_VecFPU_SIZE_FLOAT;
target_adress2+=hk_VecFPU_SIZE_FLOAT;
}
}
inline void hk_VecFPU::fpu_copy_rows(hk_real *target_adress,hk_real *source_adress,int size,hk_bool adress_aligned) {
if(adress_aligned==HK_FALSE) {
//we have to calculate the block size and shift adresses to lower aligned adresses
long adress,result_adress;
adress=(long)source_adress;
result_adress=adress & hk_VecFPU_MEM_MASK_FLOAT;
size+=(adress-result_adress)>>hk_VecFPU_MEMSHIFT_FLOAT;
source_adress=(hk_real *)result_adress;
adress=(long)target_adress;
adress=adress & hk_VecFPU_MEM_MASK_FLOAT;
target_adress=(hk_real *)adress;
}
#if 0
int i;
for(i=size-1;i>=0;i-=hk_VecFPU_SIZE_FLOAT) {
__m128d target_d=_mm_load_pd(source_adress);
_mm_store_pd(target_adress,target_d);
target_adress+=hk_VecFPU_SIZE_FLOAT;
source_adress+=hk_VecFPU_SIZE_FLOAT;
}
}
#endif
int i;
for(i=size-1;i>=0;i-=hk_VecFPU_SIZE_FLOAT) {
int j;
for(j=0;j<hk_VecFPU_SIZE_FLOAT;j++) {
target_adress[j] = source_adress[j];
}
target_adress+=hk_VecFPU_SIZE_FLOAT;
source_adress+=hk_VecFPU_SIZE_FLOAT;
}
}
inline void hk_VecFPU::fpu_set_row_to_zero(hk_real *target_adress,int size,hk_bool adress_aligned) {
if(adress_aligned==HK_FALSE) {
long adress,result_adress;
adress=(long)target_adress;
result_adress=adress & hk_VecFPU_MEM_MASK_FLOAT;
size+=(adress-result_adress)>>hk_VecFPU_MEMSHIFT_FLOAT;
target_adress=(hk_real *)result_adress;
}
#if 0
__m128d zero128=_mm_set1_pd(0.0f);
int i;
for(i=size-1;i>=0;i-=hk_VecFPU_SIZE_FLOAT) {
_mm_store_pd(target_adress,zero128);
target_adress+=hk_VecFPU_SIZE_FLOAT;
}
}
#endif
int i;
for(i=size-1;i>=0;i-=hk_VecFPU_SIZE_FLOAT) {
int j;
for(j=0;j<hk_VecFPU_SIZE_FLOAT;j++) {
target_adress[j] = 0.0f;
}
target_adress+=hk_VecFPU_SIZE_FLOAT;
}
}
inline int hk_VecFPU::calc_aligned_row_len(int unaligned_len,hk_real *dummy_type) { //dummy type is used for overloading
return (unaligned_len+hk_VecFPU_SIZE_FLOAT-1)&hk_VecFPU_MASK_FLOAT;
}
//----------------------------------------------------------------------------------------------------------------------
inline void hk_VecFPU::fpu_add_multiple_row(hk_double *target_adress,hk_double *source_adress,hk_double factor,int size,hk_bool adress_aligned) {
if(adress_aligned==HK_FALSE) {
//we have to calculate the block size and shift adresses to lower aligned adresses
long result_adress = long(source_adress) & hk_VecFPU_MEM_MASK_DOUBLE;
target_adress = (hk_double *)( long (target_adress) & hk_VecFPU_MEM_MASK_DOUBLE);
size += (long(source_adress)-result_adress)>>hk_VecFPU_MEMSHIFT_DOUBLE;
source_adress=(hk_double *)result_adress;
}
#if defined(IVP_USE_PS2_VU0)
asm __volatile__("
mfc1 $8,%3
qmtc2 $8,vf5 # vf5.x factor
1:
lqc2 vf4,0x0(%1) # vf4 *source
vmulx.xyzw vf6,vf4,vf5 # vf6 *source * factor
lqc2 vf4,0x0(%0)
addi %0, 0x10
vadd.xyzw vf6,vf4,vf6 # vf6 = *dest + factor * *source
addi %2,-4
addi %1, 0x10
sqc2 vf6,-0x10(%0)
bgtz %2,1b
nop
"
: /* no output */
: "r" (target_adress), "r" (source_adress) , "r" (size), "f" (factor)
: "$8" , "memory");
#else
if(0) {
# if defined(IVP_WILLAMETTE)
;
__m128d factor128=_mm_set1_pd(factor);
for(int i=size;i>0;i-=hk_VecFPU_SIZE_DOUBLE) {
__m128d source_d=_mm_load_pd(source_adress);
__m128d prod_d=_mm_mul_pd(factor128,source_d);
__m128d target_d=_mm_load_pd(target_adress);
target_d=_mm_add_pd(prod_d,target_d);
_mm_store_pd(target_adress,target_d);
target_adress+=hk_VecFPU_SIZE_DOUBLE;
source_adress+=hk_VecFPU_SIZE_DOUBLE;
}
#endif
} else {
for(int i=size;i>0;i-=hk_VecFPU_SIZE_DOUBLE) {
# if hk_VecFPU_SIZE_DOUBLE == 2
hk_double a = source_adress[0] * factor;
hk_double b = source_adress[1] * factor;
a += target_adress[0];
b += target_adress[1];
target_adress[0] = a;
target_adress[1] = b;
# elif hk_VecFPU_SIZE_DOUBLE == 4
hk_double a = source_adress[0] * factor;
hk_double b = source_adress[1] * factor;
hk_double c = source_adress[2] * factor;
hk_double d = source_adress[3] * factor;
a += target_adress[0];
b += target_adress[1];
c += target_adress[2];
d += target_adress[3];
target_adress[0] = a;
target_adress[1] = b;
target_adress[2] = c;
target_adress[3] = d;
# else
shit
# endif
target_adress+=hk_VecFPU_SIZE_DOUBLE;
source_adress+=hk_VecFPU_SIZE_DOUBLE;
}
}
#endif
}
inline hk_double hk_VecFPU::fpu_large_dot_product(hk_double *base_a, hk_double *base_b, int size, hk_bool adress_aligned) {
if(adress_aligned==HK_FALSE) {
//we have to calculate the block size and shift adresses to lower aligned adresses
long result_adress = long(base_a) & hk_VecFPU_MEM_MASK_DOUBLE;
base_b = (hk_double *)( long (base_b) & hk_VecFPU_MEM_MASK_DOUBLE);
size += (long(base_a)-result_adress)>>hk_VecFPU_MEMSHIFT_DOUBLE; // because start changed
base_a=(hk_double *)result_adress;
}
# if defined(IVP_WILLAMETTE)
if(0) {
__m128d sum128 =_mm_set1_pd(0.0);
int i;
for(i=size;i>=hk_VecFPU_SIZE_DOUBLE; i-= hk_VecFPU_SIZE_DOUBLE) {
__m128d mult1=_mm_load_pd(base_a);
__m128d mult2=_mm_load_pd(base_b);
__m128d prod =_mm_mul_pd(mult1,mult2);
sum128 =_mm_add_pd(prod,sum128);
base_a += hk_VecFPU_SIZE_DOUBLE;
base_b += hk_VecFPU_SIZE_DOUBLE;
}
__m128d dummy,low,high;
low=sum128;
dummy=sum128;
//_mm_shuffle_pd(sum128,sum128,1); //swap high and low
sum128=_mm_unpackhi_pd(sum128,dummy);
high=sum128;
__m128d sum64=_mm_add_sd(low,high);
__m128d res=sum64;
//_mm_shuffle_pd(sum64,sum64,1);
hk_double result_sum;
_mm_store_sd(&result_sum,res);
for(;i>=0;i--) {
result_sum += base_a[i] * base_b[i];
}
return result_sum;
} else {
hk_double sum=0.0;
for(int i=size-1;i>=0;i--) {
sum += base_a[i] * base_b[i];
}
return sum;
}
#else
hk_double sum=0.0;
for(int i=size-1;i>=0;i--) {
sum += base_a[i] * base_b[i];
}
return sum;
#endif
}
inline void hk_VecFPU::fpu_multiply_row(hk_double *target_adress,hk_double factor,int size,hk_bool adress_aligned) {
if(adress_aligned==HK_FALSE) {
//we have to calculate the block size and shift adresses to lower aligned adresses
long adress,result_adress;
adress=(long)target_adress;
result_adress=adress & hk_VecFPU_MEM_MASK_DOUBLE;
size+=(adress-result_adress)>>hk_VecFPU_MEMSHIFT_DOUBLE;
target_adress=(hk_double *)result_adress;
}
if(0) {
#ifdef IVP_WILLAMETTE
__m128d factor128=_mm_set1_pd(factor);
int i;
for(i=size;i>0;i-=hk_VecFPU_SIZE_DOUBLE) {
__m128d target_d=_mm_load_pd(target_adress);
target_d=_mm_mul_pd(factor128,target_d);
_mm_store_pd(target_adress,target_d);
target_adress+=hk_VecFPU_SIZE_DOUBLE;
}
#endif
} else {
int i;
for(i=size;i>0;i-=hk_VecFPU_SIZE_DOUBLE) {
# if hk_VecFPU_SIZE_DOUBLE == 2
hk_double a = target_adress[0] * factor;
hk_double b = target_adress[1] * factor;
target_adress[0] = a;
target_adress[1] = b;
# elif hk_VecFPU_SIZE_DOUBLE == 4
hk_double a = target_adress[0] * factor;
hk_double b = target_adress[1] * factor;
hk_double c = target_adress[2] * factor;
hk_double d = target_adress[3] * factor;
target_adress[0] = a;
target_adress[1] = b;
target_adress[2] = c;
target_adress[3] = d;
# else
shit
# endif
target_adress+=hk_VecFPU_SIZE_DOUBLE;
}
}
}
// #+# sparc says rui, optimize for non vector units ( hk_VecFPU_SIZE_DOUBLE = 4 )
inline void hk_VecFPU::fpu_exchange_rows(hk_double *target_adress1,hk_double *target_adress2,int size,hk_bool adress_aligned) {
if(adress_aligned==HK_FALSE) {
//we have to calculate the block size and shift adresses to lower aligned adresses
long adress,result_adress;
adress=(long)target_adress1;
result_adress=adress & hk_VecFPU_MEM_MASK_DOUBLE;
size+=(adress-result_adress)>>hk_VecFPU_MEMSHIFT_DOUBLE;
target_adress1=(hk_double *)result_adress;
adress=(long)target_adress2;
adress=adress & hk_VecFPU_MEM_MASK_DOUBLE;
target_adress2=(hk_double *)adress;
}
if(0) {
#ifdef IVP_WILLAMETTE
int i;
for(i=size;i>0;i-=hk_VecFPU_SIZE_DOUBLE) {
__m128d a_d=_mm_load_pd(target_adress1);
__m128d b_d=_mm_load_pd(target_adress2);
_mm_store_pd(target_adress1,b_d);
_mm_store_pd(target_adress2,a_d);
target_adress1+=hk_VecFPU_SIZE_DOUBLE;
target_adress2+=hk_VecFPU_SIZE_DOUBLE;
}
#endif
} else {
int i;
for(i=size;i>0;i-=hk_VecFPU_SIZE_DOUBLE) {
hk_double h;
# if hk_VecFPU_SIZE_DOUBLE == 2
h=target_adress1[0]; target_adress1[0]=target_adress2[0]; target_adress2[0]=h;
h=target_adress1[1]; target_adress1[1]=target_adress2[1]; target_adress2[1]=h;
# elif hk_VecFPU_SIZE_DOUBLE == 4
h=target_adress1[0]; target_adress1[0]=target_adress2[0]; target_adress2[0]=h;
h=target_adress1[1]; target_adress1[1]=target_adress2[1]; target_adress2[1]=h;
h=target_adress1[2]; target_adress1[2]=target_adress2[2]; target_adress2[2]=h;
h=target_adress1[3]; target_adress1[3]=target_adress2[3]; target_adress2[3]=h;
# else
shit
# endif
target_adress1+=hk_VecFPU_SIZE_DOUBLE;
target_adress2+=hk_VecFPU_SIZE_DOUBLE;
}
}
}
inline void hk_VecFPU::fpu_copy_rows(hk_double *target_adress,hk_double *source_adress,int size,hk_bool adress_aligned) {
if(adress_aligned==HK_FALSE) {
//we have to calculate the block size and shift adresses to lower aligned adresses
long adress,result_adress;
adress=(long)source_adress;
result_adress=adress & hk_VecFPU_MEM_MASK_DOUBLE;
size+=(adress-result_adress)>>hk_VecFPU_MEMSHIFT_DOUBLE;
source_adress=(hk_double *)result_adress;
adress=(long)target_adress;
adress=adress & hk_VecFPU_MEM_MASK_DOUBLE;
target_adress=(hk_double *)adress;
}
#ifdef HK_WILLAMETTE
int i;
for(i=size-1;i>=0;i-=hk_VecFPU_SIZE_DOUBLE) {
__m128d target_d=_mm_load_pd(source_adress);
_mm_store_pd(target_adress,target_d);
target_adress+=hk_VecFPU_SIZE_DOUBLE;
source_adress+=hk_VecFPU_SIZE_DOUBLE;
}
#else
int i;
for(i=size-1;i>=0;i-=hk_VecFPU_SIZE_DOUBLE) {
int j;
for(j=0;j<hk_VecFPU_SIZE_DOUBLE;j++) {
target_adress[j] = source_adress[j];
}
target_adress+=hk_VecFPU_SIZE_DOUBLE;
source_adress+=hk_VecFPU_SIZE_DOUBLE;
}
#endif
}
inline void hk_VecFPU::fpu_set_row_to_zero(hk_double *target_adress,int size,hk_bool adress_aligned) {
if(adress_aligned==HK_FALSE) {
long adress,result_adress;
adress=(long)target_adress;
result_adress=adress & hk_VecFPU_MEM_MASK_DOUBLE;
size+=(adress-result_adress)>>hk_VecFPU_MEMSHIFT_DOUBLE;
target_adress=(hk_double *)result_adress;
}
if(0) {
#ifdef IVP_WILLAMETTE
__m128d zero128=_mm_set1_pd(0.0f);
int i;
for(i=size-1;i>=0;i-=hk_VecFPU_SIZE_DOUBLE) {
_mm_store_pd(target_adress,zero128);
target_adress+=hk_VecFPU_SIZE_DOUBLE;
}
#endif
} else {
int i;
for(i=size-1;i>=0;i-=hk_VecFPU_SIZE_DOUBLE) {
int j;
for(j=0;j<hk_VecFPU_SIZE_DOUBLE;j++) {
target_adress[j] = 0.0f;
}
target_adress+=hk_VecFPU_SIZE_DOUBLE;
}
}
}
inline int hk_VecFPU::calc_aligned_row_len(int unaligned_len,hk_double *dummy_type) { //dummy type is used for overloading
return (unaligned_len+hk_VecFPU_SIZE_DOUBLE-1)&hk_VecFPU_MASK_DOUBLE;
}
| 32.923205 | 146 | 0.66092 |
dedc9bea22e4d12bc1c587ec698d2444e590a3be | 4,793 | cpp | C++ | SimSpark/rcssserver3d/plugin/soccer/gamestateperceptor/gamestateperceptor.cpp | IllyasvielEin/Robocup3dInstaller | 12e91d9372dd08a92feebf98e916c98bc2242ff4 | [
"MIT"
] | null | null | null | SimSpark/rcssserver3d/plugin/soccer/gamestateperceptor/gamestateperceptor.cpp | IllyasvielEin/Robocup3dInstaller | 12e91d9372dd08a92feebf98e916c98bc2242ff4 | [
"MIT"
] | null | null | null | SimSpark/rcssserver3d/plugin/soccer/gamestateperceptor/gamestateperceptor.cpp | IllyasvielEin/Robocup3dInstaller | 12e91d9372dd08a92feebf98e916c98bc2242ff4 | [
"MIT"
] | null | null | null | /* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*-
this file is part of rcssserver3D
Fri May 9 2003
Copyright (C) 2002,2003 Koblenz University
Copyright (C) 2003 RoboCup Soccer Server 3D Maintenance Group
$Id$
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "gamestateperceptor.h"
#include <zeitgeist/logserver/logserver.h>
#include <soccerbase/soccerbase.h>
#include <agentstate/agentstate.h>
#include <gamestateaspect/gamestateaspect.h>
using namespace zeitgeist;
using namespace oxygen;
using namespace boost;
using namespace std;
GameStatePerceptor::GameStatePerceptor() : oxygen::Perceptor()
{
mFirstPercept = true;
mReportScore = true;
}
GameStatePerceptor::~GameStatePerceptor()
{
}
void
GameStatePerceptor::InsertSoccerParam(Predicate& predicate, const std::string& name)
{
float value;
if (! SoccerBase::GetSoccerVar(*this,name,value))
{
return;
}
ParameterList& element = predicate.parameter.AddList();
element.AddValue(name);
element.AddValue(value);
}
void
GameStatePerceptor::InsertInitialPercept(Predicate& predicate)
{
// uniform number
ParameterList& unumElement = predicate.parameter.AddList();
unumElement.AddValue(string("unum"));
unumElement.AddValue(mAgentState->GetUniformNumber());
// team index
std::string team;
switch (mAgentState->GetTeamIndex())
{
case TI_NONE :
team = "none";
break;
case TI_LEFT :
team = "left";
break;
case TI_RIGHT :
team = "right";
break;
}
ParameterList& teamElement = predicate.parameter.AddList();
teamElement.AddValue(string("team"));
teamElement.AddValue(team);
// soccer variables
// field geometry parameter
// InsertSoccerParam(predicate,"FieldLength");
// InsertSoccerParam(predicate,"FieldWidth");
// InsertSoccerParam(predicate,"FieldHeight");
// InsertSoccerParam(predicate,"GoalWidth");
// InsertSoccerParam(predicate,"GoalDepth");
// InsertSoccerParam(predicate,"GoalHeight");
// InsertSoccerParam(predicate,"BorderSize");
// // agent parameter
// InsertSoccerParam(predicate,"AgentMass");
// InsertSoccerParam(predicate,"AgentRadius");
// InsertSoccerParam(predicate,"AgentMaxSpeed");
// // ball parameter
// InsertSoccerParam(predicate,"BallRadius");
// InsertSoccerParam(predicate,"BallMass");
}
bool
GameStatePerceptor::Percept(boost::shared_ptr<PredicateList> predList)
{
if (
(mGameState.get() == 0) ||
(mAgentState.get() == 0)
)
{
return false;
}
Predicate& predicate = predList->AddPredicate();
predicate.name = "GS";
predicate.parameter.Clear();
// with the first GameState percept after the player is assigned
// to a team it receives info about it's team and unum assignment
// along with outher soccer parameters
if (
(mFirstPercept) &&
(mAgentState->GetTeamIndex() != TI_NONE)
)
{
mFirstPercept = false;
InsertInitialPercept(predicate);
}
if (mReportScore) {
// score left
ParameterList& slElement = predicate.parameter.AddList();
slElement.AddValue(string("sl"));
slElement.AddValue(mGameState->GetScore(TI_LEFT));
// score right
ParameterList& srElement = predicate.parameter.AddList();
srElement.AddValue(string("sr"));
srElement.AddValue(mGameState->GetScore(TI_RIGHT));
}
// time
ParameterList& timeElement = predicate.parameter.AddList();
timeElement.AddValue(string("t"));
timeElement.AddValue(mGameState->GetTime());
// playmode
ParameterList& pmElement = predicate.parameter.AddList();
pmElement.AddValue(string("pm"));
pmElement.AddValue(SoccerBase::PlayMode2Str(mGameState->GetPlayMode()));
return true;
}
void
GameStatePerceptor::OnLink()
{
SoccerBase::GetGameState(*this,mGameState);
SoccerBase::GetAgentState(*this,mAgentState);
SoccerBase::GetSoccerVar(*this,"ReportScore",mReportScore);
}
void
GameStatePerceptor::OnUnlink()
{
mGameState.reset();
mAgentState.reset();
}
| 28.194118 | 84 | 0.685583 |
dedd51ee810c8f039746f6cede22295f7057ad54 | 2,838 | cc | C++ | content/browser/renderer_host/pepper/browser_ppapi_host_impl.cc | junmin-zhu/chromium-rivertrail | eb1a57aca71fe68d96e48af8998dcfbe45171ee1 | [
"BSD-3-Clause"
] | 5 | 2018-03-10T13:08:42.000Z | 2021-07-26T15:02:11.000Z | content/browser/renderer_host/pepper/browser_ppapi_host_impl.cc | quisquous/chromium | b25660e05cddc9d0c3053b3514f07037acc69a10 | [
"BSD-3-Clause"
] | 1 | 2015-07-21T08:02:01.000Z | 2015-07-21T08:02:01.000Z | content/browser/renderer_host/pepper/browser_ppapi_host_impl.cc | jianglong0156/chromium.src | d496dfeebb0f282468827654c2b3769b3378c087 | [
"BSD-3-Clause"
] | 6 | 2016-11-14T10:13:35.000Z | 2021-01-23T15:29:53.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/pepper/browser_ppapi_host_impl.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_view_host.h"
#include "ipc/ipc_message_macros.h"
namespace content {
BrowserPpapiHostImpl::BrowserPpapiHostImpl(
IPC::Sender* sender,
const ppapi::PpapiPermissions& permissions)
: ppapi_host_(sender, permissions),
plugin_process_handle_(base::kNullProcessHandle) {
ppapi_host_.AddHostFactoryFilter(scoped_ptr<ppapi::host::HostFactory>(
new ContentBrowserPepperHostFactory(this)));
}
BrowserPpapiHostImpl::~BrowserPpapiHostImpl() {
}
bool BrowserPpapiHostImpl::OnMessageReceived(const IPC::Message& msg) {
/* TODO(brettw) when we add messages, here, the code should look like this:
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(BrowserPpapiHostImpl, msg)
// Add necessary message handlers here.
IPC_MESSAGE_UNHANDLED(handled = ppapi_host_.OnMessageReceived(msg))
IPC_END_MESSAGE_MAP();
return handled;
*/
return ppapi_host_.OnMessageReceived(msg);
}
ppapi::host::PpapiHost* BrowserPpapiHostImpl::GetPpapiHost() {
return &ppapi_host_;
}
base::ProcessHandle BrowserPpapiHostImpl::GetPluginProcessHandle() const {
// Handle should previously have been set before use.
DCHECK(plugin_process_handle_ != base::kNullProcessHandle);
return plugin_process_handle_;
}
bool BrowserPpapiHostImpl::IsValidInstance(PP_Instance instance) const {
return instance_to_view_.find(instance) != instance_to_view_.end();
}
bool BrowserPpapiHostImpl::GetRenderViewIDsForInstance(
PP_Instance instance,
int* render_process_id,
int* render_view_id) const {
InstanceToViewMap::const_iterator found = instance_to_view_.find(instance);
if (found == instance_to_view_.end()) {
*render_process_id = 0;
*render_view_id = 0;
return false;
}
*render_process_id = found->second.process_id;
*render_view_id = found->second.view_id;
return true;
}
void BrowserPpapiHostImpl::AddInstanceForView(PP_Instance instance,
int render_process_id,
int render_view_id) {
DCHECK(instance_to_view_.find(instance) == instance_to_view_.end());
RenderViewIDs ids;
ids.process_id = render_process_id;
ids.view_id = render_view_id;
instance_to_view_[instance] = ids;
}
void BrowserPpapiHostImpl::DeleteInstanceForView(PP_Instance instance) {
InstanceToViewMap::iterator found = instance_to_view_.find(instance);
if (found == instance_to_view_.end()) {
NOTREACHED();
return;
}
instance_to_view_.erase(found);
}
} // namespace content
| 32.25 | 77 | 0.744891 |
dee02e61c6026421062ff37899f6387291f3d3c8 | 325 | cpp | C++ | mutations_aliens/main.cpp | aymeebonvarlet/projet_mutation_aliens | a1885d77d9ef197395c7f9545d96105fdac47018 | [
"Apache-2.0"
] | null | null | null | mutations_aliens/main.cpp | aymeebonvarlet/projet_mutation_aliens | a1885d77d9ef197395c7f9545d96105fdac47018 | [
"Apache-2.0"
] | null | null | null | mutations_aliens/main.cpp | aymeebonvarlet/projet_mutation_aliens | a1885d77d9ef197395c7f9545d96105fdac47018 | [
"Apache-2.0"
] | null | null | null | #include "mainwindow.h"
#include "qstd.h"
using namespace qstd;
#include <QApplication>
#include "evolutionnary_process.h"
int main(int argc, char *argv[])
{
Evolutionnary_process evo;
evo.init();
cout<<evo.toString()<<endl;
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
| 19.117647 | 34 | 0.664615 |
dee0c4a6231b74e6f1b2d9129bdf422fd8e12380 | 616 | cpp | C++ | 08_pass-by-reference/src/main.cpp | JuliusDiestra/cpp-sandbox | 6fa3bcb2a284e58136168e1952a8a54621232621 | [
"MIT"
] | null | null | null | 08_pass-by-reference/src/main.cpp | JuliusDiestra/cpp-sandbox | 6fa3bcb2a284e58136168e1952a8a54621232621 | [
"MIT"
] | null | null | null | 08_pass-by-reference/src/main.cpp | JuliusDiestra/cpp-sandbox | 6fa3bcb2a284e58136168e1952a8a54621232621 | [
"MIT"
] | null | null | null | #include "vehicle.hpp"
#include "controller.hpp"
int main(int argc, char *argv[]) {
// Create vehicle object
Vehicle vehicle;
vehicle.SetVelocity(20);
vehicle.SetAcceleration(30);
std::cout << "### Vehicle Object ###" << std::endl;
std::cout << "velocity:" << vehicle.GetVelocity() << std::endl;
std::cout << "acceleration:" << vehicle.GetAcceleration() << std::endl;
Controller controller(vehicle);
controller.ChangeVehicleVelocity(40);
std::cout << "### Vehicle Object ###" << std::endl;
std::cout << "velocity:" << vehicle.GetVelocity() << std::endl;
return 0;
}
| 32.421053 | 75 | 0.625 |
dee0f6e51b0bf08f7f3b1b3f4ce0dede9913d9f2 | 2,898 | cpp | C++ | Source/Extensions/PGUI/PGUI.Screen.cpp | wipe2238/foc | 87f083e4d12178244953857ee89da488b31d0a9b | [
"MIT"
] | 2 | 2018-12-14T23:06:21.000Z | 2021-07-29T03:10:38.000Z | Source/Extensions/PGUI/PGUI.Screen.cpp | wipe2238/foc | 87f083e4d12178244953857ee89da488b31d0a9b | [
"MIT"
] | 1 | 2020-08-25T10:38:00.000Z | 2020-08-25T10:38:00.000Z | Source/Extensions/PGUI/PGUI.Screen.cpp | wipe2238/foc | 87f083e4d12178244953857ee89da488b31d0a9b | [
"MIT"
] | null | null | null | #include <App.h>
#include <Defines.Public.h>
#include <GameOptions.h>
#include <Ini.h>
#include "PGUI.Core.h"
#include "PGUI.Screen.h"
PGUI::Screen::Screen( PGUI::Core* gui, uint width /* = 0 */, uint height /* = 0 */, int left /* = 0 */, int top /* = 0 */ ) : PGUI::Element( gui, width, height, left, top ),
// public
IsMovable( true ),
Layer( 0 ),
ScreenData( nullptr ),
// protected
DrawLayer( 0 )
{}
PGUI::Screen::~Screen()
{
if( GUI->Debug )
App.WriteLogF( _FUNC_, "\n" );
}
uint PGUI::Screen::GetID()
{
return GUI->GetScreenID( this );
}
bool PGUI::Screen::LoadSettings( Ini* ini, const std::string& section )
{
if( !ini )
{
// if (Debug)
App.WriteLogF( _FUNC_, " WARNING : ini is null\n", section.c_str() );
return false;
}
if( ini->IsSection( section ) )
{
// if (Debug)
App.WriteLogF( _FUNC_, " WARNING : section<%s> not found\n", section.c_str() );
return false;
}
return true;
}
void PGUI::Screen::AutoSize()
{
uint16 width = 0, height = 0;
for( auto it = Elements.begin(), end = Elements.end(); it != end; ++it )
{
PGUI::Element* element = it->second;
if( !element )
continue;
uint16 w = element->GetWidth() + element->GetLeft( true );
uint16 h = element->GetHeight() + element->GetTop( true );
width = std::max( width, w );
height = std::max( height, h );
}
if( GUI->Debug )
App.WriteLogF( _FUNC_, " = %ux%u\n", width, height );
SetSize( width, height );
}
void PGUI::Screen::MouseMove( int16 fromX, int16 fromY, int16 toX, int16 toY )
{
if( !IsMouseEnabled )
return;
if( IsMovable && MousePressed && MouseButton == MOUSE_CLICK_LEFT )
{
int16 oldLeft = 0, oldTop = 0;
GetPosition( oldLeft, oldTop, true );
int newLeft = oldLeft + (toX - fromX);
int newTop = oldTop + (toY - fromY);
bool reset = false;
if( newLeft < 0 )
{
newLeft = 0;
reset = true;
}
if( newTop < 0 )
{
newTop = 0;
reset = true;
}
uint16 width = 0, height = 0;
GetSize( width, height );
if( newLeft + width > GUI->GetScreenWidth() )
{
newLeft = GUI->GetScreenWidth() - width;
reset = true;
}
if( newTop + height > GUI->GetScreenHeight() )
{
newTop = GUI->GetScreenHeight() - height;
reset = true;
}
if( reset )
{
// TODO cursor goes crazy here
// GameOpt.MouseX = fromX;
// GameOpt.MouseY = fromY;
}
if( oldLeft != newLeft || oldTop != newTop )
SetPosition( newLeft, newTop );
}
PGUI::Element::MouseMove( fromX, fromY, toX, toY );
}
| 22.640625 | 173 | 0.515528 |
dee106f0ef1f044ea3ecd0fcbb3d197955f98a5f | 668 | cpp | C++ | problems/lazyloading/submissions/accepted/lel.cpp | stoman/CompetitiveProgramming | 0000b64369b50e31c6f48939e837bdf6cece8ce4 | [
"MIT"
] | 2 | 2020-12-22T13:21:25.000Z | 2021-12-12T22:26:26.000Z | problems/lazyloading/submissions/accepted/lel.cpp | stoman/CompetitiveProgramming | 0000b64369b50e31c6f48939e837bdf6cece8ce4 | [
"MIT"
] | null | null | null | problems/lazyloading/submissions/accepted/lel.cpp | stoman/CompetitiveProgramming | 0000b64369b50e31c6f48939e837bdf6cece8ce4 | [
"MIT"
] | null | null | null | #include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#define MAXN 105
using namespace std;
int t, n, ans, lo, hi, maxim, how;
int w[MAXN];
int main( ) {
scanf( "%d", &t );
for ( int T = 0; T < t; ++T ) {
scanf( "%d", &n );
for ( int i = 1; i <= n; ++i ) {
scanf( "%d", &w[i] );
}
sort( w+1, w+n+1 );
ans = 0;
lo = 1;
hi = n;
ans = 0;
while ( lo <= hi ) {
maxim = w[hi];
how = 1;
while ( lo < hi ) {
if ( maxim * how >= 50 ) {
break;
}
++lo;
++how;
}
if ( maxim * how >= 50 ) {
++ans;
}
--hi;
}
printf( "Case #%d: %d\n", T+1, ans );
}
return 0;
}
| 11.133333 | 39 | 0.42515 |
dee18f7be43af0742ef1a141d1cc2b540d142fa3 | 9,745 | hh | C++ | nodecursor.hh | cp-profiler/cp-profiler-deprecated- | ec163bde5c3a5bd9cc428b8fa8fd6ef713e0247a | [
"MIT-feh"
] | 1 | 2021-05-06T04:41:37.000Z | 2021-05-06T04:41:37.000Z | nodecursor.hh | cp-profiler/cp-profiler-deprecated- | ec163bde5c3a5bd9cc428b8fa8fd6ef713e0247a | [
"MIT-feh"
] | null | null | null | nodecursor.hh | cp-profiler/cp-profiler-deprecated- | ec163bde5c3a5bd9cc428b8fa8fd6ef713e0247a | [
"MIT-feh"
] | 1 | 2021-05-06T04:41:39.000Z | 2021-05-06T04:41:39.000Z | /* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Guido Tack <tack@gecode.org>
*
* Copyright:
* Guido Tack, 2006
*
* Last modified:
* $Date$ by $Author$
* $Revision$
*
* This file is part of Gecode, the generic constraint
* development environment:
* http://www.gecode.org
*
* 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 GECODE_GIST_NODECURSOR_HH
#define GECODE_GIST_NODECURSOR_HH
#include "nodecursor_base.hh"
#include <vector>
#include <QTextStream>
class TreeCanvas;
class Execution;
class VisualNode;
/// \brief A cursor that marks failed subtrees as hidden
class HideFailedCursor : public NodeCursor {
private:
bool onlyDirty;
public:
/// Constructor
HideFailedCursor(VisualNode* theNode,
const NodeAllocator& na,
bool onlyDirtyNodes);
/// \name Cursor interface
//@{
/// Test if the cursor may move to the first child node
bool mayMoveDownwards(void) const;
/// Process node
void processCurrentNode(void);
//@}
};
/// \brief A cursor that marks all nodes in the tree as not hidden
class UnhideAllCursor : public NodeCursor {
public:
/// Constructor
UnhideAllCursor(VisualNode* theNode,
const NodeAllocator& na);
/// \name Cursor interface
//@{
/// Process node
void processCurrentNode(void);
//@}
};
/// \brief A cursor that marks all nodes in the tree as not selected
class UnselectAllCursor : public NodeCursor {
public:
/// Constructor
UnselectAllCursor(VisualNode* theNode,
const NodeAllocator& na);
/// \name Cursor interface
//@{
/// Process node
void processCurrentNode(void);
//@}
};
/// \brief A cursor that marks ancestor nodes in the tree as not hidden
class UnhideAncestorsCursor : public NodeCursor {
public:
/// Constructor
UnhideAncestorsCursor(VisualNode* theNode,
const NodeAllocator& na);
/// \name Cursor interface
//@{
/// Test if the cursor may move to the parent node
bool mayMoveUpwards(void) const;
/// Process node
void processCurrentNode(void);
//@}
};
/// \brief A cursor that marks all nodes in the tree as hidden
class HideAllCursor : public NodeCursor {
public:
/// Constructor
HideAllCursor(VisualNode* theNode,
const NodeAllocator& na);
/// \name Cursor interface
//@{
/// Process node
void processCurrentNode(void);
//@}
};
/// \brief A cursor that finds the next solution
class NextSolCursor : public NodeCursor {
private:
/// Whether to search backwards
bool back;
/// Whether the current node is not a solution
bool notOnSol(void) const;
public:
/// Constructor
NextSolCursor(VisualNode* theNode, bool backwards,
const NodeAllocator& na);
/// \name Cursor interface
//@{
/// Do nothing
void processCurrentNode(void);
/// Test if the cursor may move to the parent node
bool mayMoveUpwards(void) const;
/// Test if cursor may move to the first child node
bool mayMoveDownwards(void) const;
/// Move cursor to the first child node
void moveDownwards(void);
/// Test if cursor may move to the first sibling
bool mayMoveSidewards(void) const;
/// Move cursor to the first sibling
void moveSidewards(void);
//@}
};
/// \brief A cursor that finds the next leaf
class NextLeafCursor : public NodeCursor {
private:
/// Whether to search backwards
bool back;
/// Whether the current node is not a leaf
bool notOnLeaf(void) const;
public:
/// Constructor
NextLeafCursor(VisualNode* theNode, bool backwards,
const NodeAllocator& na);
/// \name Cursor interface
//@{
/// Do nothing
void processCurrentNode(void);
/// Test if the cursor may move to the parent node
bool mayMoveUpwards(void) const;
/// Test if cursor may move to the first child node
bool mayMoveDownwards(void) const;
/// Move cursor to the first child node
void moveDownwards(void);
/// Test if cursor may move to the first sibling
bool mayMoveSidewards(void) const;
/// Move cursor to the first sibling
void moveSidewards(void);
//@}
};
/// \brief A cursor that finds the next pentagon
class NextPentagonCursor : public NodeCursor {
private:
/// Whether to search backwards
bool back;
/// Whether the current node is not a pentagon
bool notOnPentagon(void) const;
public:
/// Constructor
NextPentagonCursor(VisualNode* theNode, bool backwards,
const NodeAllocator& na);
/// \name Cursor interface
//@{
/// Do nothing
void processCurrentNode(void);
/// Test if the cursor may move to the parent node
bool mayMoveUpwards(void) const;
/// Test if cursor may move to the first child node
bool mayMoveDownwards(void) const;
/// Move cursor to the first child node
void moveDownwards(void);
/// Test if cursor may move to the first sibling
bool mayMoveSidewards(void) const;
/// Move cursor to the first sibling
void moveSidewards(void);
//@}
};
/// \brief A cursor that collects statistics
class StatCursor : public NodeCursor {
private:
/// Current depth
int curDepth;
public:
/// Depth of the search tree
int depth;
/// Number of failed nodes
int failed;
/// Number of solved nodes
int solved;
/// Number of choice nodes
int choice;
/// Number of open nodes
int open;
/// Constructor
StatCursor(VisualNode* theNode,
const NodeAllocator& na);
/// \name Cursor interface
//@{
/// Collect statistics
void processCurrentNode(void);
/// Move cursor to the first child node
void moveDownwards(void);
/// Move cursor to the parent node
void moveUpwards(void);
//@}
};
class HighlightCursor : public NodeCursor {
public:
// Constructor
HighlightCursor(VisualNode* startNode, const NodeAllocator& na);
// Highlight all the nodes below
void processCurrentNode(void);
};
class UnhighlightCursor : public NodeCursor {
public:
// Constructor
UnhighlightCursor(VisualNode* root, const NodeAllocator& na);
// Unhighlight all the nodes below
void processCurrentNode(void);
};
class CountSolvedCursor : public NodeCursor {
public:
CountSolvedCursor(VisualNode* startNode, const NodeAllocator& na, int &count);
// Count solved leaves and store the nubmer in count variable
void processCurrentNode(void);
private:
int &_count;
};
class GetIndexesCursor : public NodeCursor {
public:
// Constructor
GetIndexesCursor(VisualNode* startNode, const NodeAllocator& na,
std::vector<int>& node_gids);
// Populate node_gids vector with gid of nodes
void processCurrentNode(void);
private:
const NodeAllocator& _na;
std::vector<int>& _node_gids;
};
/// Hide subtrees that are not highlighted
class HideNotHighlightedCursor : public NodeCursor {
protected:
QHash<VisualNode*,bool> onHighlightPath;
public:
/// Constructor
HideNotHighlightedCursor(VisualNode* startNode, const NodeAllocator& na);
/// Process node
void processCurrentNode(void);
/// Test if cursor may move to the first child node
bool mayMoveDownwards(void) const;
};
/// \brief A cursor that labels branches
class BranchLabelCursor : public NodeCursor {
private:
/// The node allocator
NodeAllocator& _na;
/// Current TreeCanvas instance (extract labels from data)
TreeCanvas& _tc;
/// Whether to clear labels
bool _clear;
public:
/// Constructor
BranchLabelCursor(VisualNode* theNode, bool clear,
NodeAllocator& na, TreeCanvas& tc);
/// \name Cursor interface
//@{
void processCurrentNode(void);
//@}
};
class SubtreeCountCursor : public NodeCursor {
public:
std::vector<int> stack;
int threshold;
SubtreeCountCursor(VisualNode *theNode,
int _threshold,
const NodeAllocator& na);
void processCurrentNode(void);
void moveSidewards(void);
void moveUpwards(void);
void moveDownwards(void);
};
class SearchLogCursor : public NodeCursor {
private:
QTextStream& _out;
/// The node allocator
const NodeAllocator& _na;
/// TODO(maxim): should have a reference to the execution here
const Execution& _execution;
public:
SearchLogCursor(VisualNode *theNode,
QTextStream& outputStream,
const NodeAllocator& na,
const Execution& execution);
void processCurrentNode(void);
};
#include "nodecursor.hpp"
#endif
| 28.328488 | 80 | 0.677783 |
dee63efa3f0c22e5bb79cef4e943cfc3e049ed24 | 2,316 | hpp | C++ | src/Modules/ModuleBuilder.hpp | pawel-jarosz/nastya-lisp | 813a58523b741e00c8c27980fe658b546e9ff38c | [
"MIT"
] | 1 | 2021-03-12T13:39:17.000Z | 2021-03-12T13:39:17.000Z | src/Modules/ModuleBuilder.hpp | pawel-jarosz/nastya-lisp | 813a58523b741e00c8c27980fe658b546e9ff38c | [
"MIT"
] | null | null | null | src/Modules/ModuleBuilder.hpp | pawel-jarosz/nastya-lisp | 813a58523b741e00c8c27980fe658b546e9ff38c | [
"MIT"
] | null | null | null | //
// Created by caedus on 30.01.2021.
//
#pragma once
#include "Modules/Module.hpp"
#include "Runtime/Interface/IEvaluatorFactory.hpp"
#include "Modules/Interface/IModuleBuilder.hpp"
#include <algorithm>
namespace nastya::modules {
template<typename EvaluatorFactory, typename... OtherFactories>
class ModuleBuilder : public ModuleBuilder<OtherFactories...> {
public:
explicit ModuleBuilder(std::string moduleName);
std::unique_ptr<IModule> build() override;
};
template<typename EvaluatorFactory>
class ModuleBuilder<EvaluatorFactory> : public IModuleBuilder {
public:
explicit ModuleBuilder(std::string moduleName);
std::unique_ptr<IModule> build() override;
std::vector<std::unique_ptr<runtime::IEvaluatorFactory>>& getFactories() {
return m_factories;
}
protected:
std::unique_ptr<Module> m_module;
std::string m_module_name;
std::vector<std::unique_ptr<runtime::IEvaluatorFactory>> m_factories;
};
template<typename EvaluatorFactory, typename... OtherFactory>
std::unique_ptr<IModule> ModuleBuilder<EvaluatorFactory, OtherFactory...>::build() {
return ModuleBuilder<OtherFactory...>::build();
}
template<typename EvaluatorFactory, typename... OtherFactories>
ModuleBuilder<EvaluatorFactory, OtherFactories...>::ModuleBuilder(std::string moduleName)
: ModuleBuilder<OtherFactories...>(std::move(moduleName)) {
std::unique_ptr<runtime::IEvaluatorFactory> factory(new EvaluatorFactory);
ModuleBuilder<OtherFactories...>::getFactories().emplace_back(std::move(factory));
}
template<typename EvaluatorFactory>
ModuleBuilder<EvaluatorFactory>::ModuleBuilder(std::string moduleName)
: m_module{new Module{moduleName}}
, m_module_name(std::move(moduleName))
, m_factories{}
{
std::unique_ptr<runtime::IEvaluatorFactory> factory(new EvaluatorFactory);
m_factories.emplace_back(std::move(factory));
}
template<typename EvaluatorFactory>
std::unique_ptr<IModule> ModuleBuilder<EvaluatorFactory>::build()
{
using Factory = std::unique_ptr<runtime::IEvaluatorFactory>;
std::for_each(m_factories.begin(), m_factories.end(), [&](const Factory& factory) {
m_module->registerFunction(factory->create());
});
auto new_module = std::make_unique<Module>(m_module_name);
m_module.swap(new_module);
return new_module;
}
} | 33.085714 | 89 | 0.756045 |
dee7db73453cfe5478fcf165793c973eaba126fc | 2,150 | cpp | C++ | src/DescentGame/src/Main.cpp | poseidn/KungFoo | 35fa33bd5a9abb40ecf485db2fc038ca52c48a2d | [
"CC-BY-3.0",
"CC0-1.0",
"CC-BY-4.0"
] | 7 | 2016-01-28T14:28:10.000Z | 2021-09-03T17:33:37.000Z | src/DescentGame/src/Main.cpp | poseidn/KungFoo | 35fa33bd5a9abb40ecf485db2fc038ca52c48a2d | [
"CC-BY-3.0",
"CC0-1.0",
"CC-BY-4.0"
] | 1 | 2016-03-19T11:34:36.000Z | 2016-03-24T21:35:06.000Z | src/DescentGame/src/Main.cpp | poseidn/KungFoo | 35fa33bd5a9abb40ecf485db2fc038ca52c48a2d | [
"CC-BY-3.0",
"CC0-1.0",
"CC-BY-4.0"
] | 3 | 2016-03-10T14:23:40.000Z | 2019-03-17T16:21:21.000Z | /*
Copyright (C) 2016 Thomas Hauth. All Rights Reserved.
* Written by Thomas Hauth (Thomas.Hauth@web.de)
This file is part of Kung Foo Barracuda.
Kung Foo Barracuda is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Kung Foo Barracuda is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Kung Foo Barracuda. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <vector>
#include <boost/program_options.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <DescentLogic/src/DescentFramework.h>
//#include "CommandLineOptions.h"
// set via the build system, if a profile is needed
#ifdef USE_PROFILER
#include <gperftools/profiler.h>
#endif
namespace po = boost::program_options;
// use ./DescentGame --fullscreen --resolution 1366x768
// on the notebook for the total fun
int main(int argc, const char* argv[]) {
SDLInterfaceInitData sdlInitData;
std::vector < std::string > opts;
for (int i = 0; i < argc; i++) {
opts.push_back(std::string(argv[i]));
}
// running fullscreen is default
sdlInitData.Fullscreen = false;
bool runDemoMode = false;
bool muted = false;
bool forwardScroll = false;
bool withIntro = false;
/*
if (commandline::handleCommandLine(sdlInitData, opts, runDemoMode, muted, forwardScroll, withIntro)
== false)
return 0;*/
DescentFramework f(false, runDemoMode, muted, forwardScroll, withIntro, true);
f.initRenderEngine(sdlInitData);
// todo: make this a lot nicer, by templating the FW class
#ifdef USE_PROFILER
ProfilerStart("GameLoop.perf");
#endif
f.execute();
#ifdef USE_PROFILER
ProfilerStop();
#endif
// done globally here for all used SDL systems;
SDL_Quit();
return 0;
}
| 26.54321 | 100 | 0.751628 |
dee83e605a1f575e4a2d710a5a6cb28e33523456 | 5,810 | cpp | C++ | patch/specific/drawbars.cpp | Tonyx97/TombMP | 7eb2d265df2fe7312b7ed07dd5943736340b921c | [
"MIT"
] | 3 | 2021-10-10T11:12:03.000Z | 2021-11-04T16:46:57.000Z | patch/specific/drawbars.cpp | Tonyx97/TombMP | 7eb2d265df2fe7312b7ed07dd5943736340b921c | [
"MIT"
] | null | null | null | patch/specific/drawbars.cpp | Tonyx97/TombMP | 7eb2d265df2fe7312b7ed07dd5943736340b921c | [
"MIT"
] | null | null | null | #include "standard.h"
#include "directx.h"
#include "global.h"
#include "hwrender.h"
#include "output.h"
#include <main.h>
#include <game/inventry.h>
#include <3dsystem/hwinsert.h>
#define HealthBarX 8
#define HealthBarY 6
#define HealthBarW 100
#define AirBarX (game_setup.dump_width-110)
#define AirBarY 6
#define AirBarW 100
#define DASHBAR_X (game_setup.dump_width-110)
#define DASHBAR_Y 6
void S_DrawDashBar(int percent)
{
HWR_EnableZBuffer(true, true);
g_blue_effect = false;
int x = DASHBAR_X,
y = DASHBAR_Y,
w = (percent * HealthBarW) / 100,
z = phd_znear + 50;
auto colour = (char)inv_colours[C_BLACK];
InsertLine(x - 2, y + 1, x + HealthBarW + 1, y + 1, z, colour);
InsertLine(x - 2, y + 2, x + HealthBarW + 1, y + 2, z, colour);
InsertLine(x - 2, y + 3, x + HealthBarW + 1, y + 3, z, colour);
InsertLine(x - 2, y + 4, x + HealthBarW + 1, y + 4, z, colour);
InsertLine(x - 2, y + 5, x + HealthBarW + 1, y + 5, z, colour);
InsertLine(x - 2, y + 6, x + HealthBarW + 1, y + 6, z, colour);
InsertLine(x - 2, y + 7, x + HealthBarW + 1, y + 7, z, colour);
z = phd_znear + 40;
colour = (char)inv_colours[C_GREY];
InsertLine(x - 2, y + 8, x + HealthBarW + 2, y + 8, z, colour);
InsertLine(x + HealthBarW + 2, y, x + HealthBarW + 2, y + 8, z, colour);
z = phd_znear + 30;
colour = (char)inv_colours[C_WHITE];
InsertLine(x - 2, y, x + HealthBarW + 2, y, z, colour);
InsertLine(x - 2, y + 8, x - 2, y, z, colour);
if (w)
{
colour = (char)inv_colours[C_DARKGREEN];
InsertLine(x, y + 2, x + w, y + 2, z, colour);
InsertLine(x, y + 3, x + w, y + 3, z, colour);
InsertLine(x, y + 4, x + w, y + 4, z, colour);
InsertLine(x, y + 5, x + w, y + 5, z, colour);
InsertLine(x, y + 6, x + w, y + 6, z, colour);
}
}
void S_DrawHealthBar(int percent, bool poisoned)
{
HWR_EnableZBuffer(true, true);
g_blue_effect = false;
int x = HealthBarX,
y = HealthBarY,
w = (percent * HealthBarW) / 100,
z = phd_znear + 50;
auto colour = (char)inv_colours[C_BLACK];
InsertLine(x - 2, y + 1, x + HealthBarW + 1, y + 1, z, colour);
InsertLine(x - 2, y + 2, x + HealthBarW + 1, y + 2, z, colour);
InsertLine(x - 2, y + 3, x + HealthBarW + 1, y + 3, z, colour);
InsertLine(x - 2, y + 4, x + HealthBarW + 1, y + 4, z, colour);
InsertLine(x - 2, y + 5, x + HealthBarW + 1, y + 5, z, colour);
InsertLine(x - 2, y + 6, x + HealthBarW + 1, y + 6, z, colour);
InsertLine(x - 2, y + 7, x + HealthBarW + 1, y + 7, z, colour);
z = phd_znear + 40;
colour = (char)inv_colours[C_GREY];
InsertLine(x - 2, y + 8, x + HealthBarW + 2, y + 8, z, colour);
InsertLine(x + HealthBarW + 2, y, x + HealthBarW + 2, y + 8, z, colour);
z = phd_znear + 30;
colour = (char)inv_colours[C_WHITE];
InsertLine(x - 2, y, x + HealthBarW + 2, y, z, colour);
InsertLine(x - 2, y + 8, x - 2, y, z, colour);
if (w)
{
z = phd_znear + 20;
colour = (char)inv_colours[poisoned ? C_YELLOW : C_RED];
InsertLine(x, y + 2, x + w, y + 2, z, colour);
InsertLine(x, y + 3, x + w, y + 3, z, colour);
InsertLine(x, y + 4, x + w, y + 4, z, colour);
InsertLine(x, y + 5, x + w, y + 5, z, colour);
InsertLine(x, y + 6, x + w, y + 6, z, colour);
}
}
void S_DrawHealthBar3D(int32_t wx, int32_t wy, int32_t wz, int percent, bool poisoned)
{
HWR_EnableZBuffer(true, true);
g_blue_effect = false;
long result[XYZ];
long scr[XYZ];
mCalcPoint(wx, wy, wz, &result[0]);
ProjectPCoord(result[_X], result[_Y], result[_Z], scr, f_centerx, f_centery, phd_persp);
int x = scr[_X] - HealthBarW / 2,
y = scr[_Y],
w = (percent * HealthBarW) / 100,
z = phd_znear + 50;
auto colour = (char)inv_colours[C_BLACK];
InsertLine(x - 2, y + 1, x + HealthBarW + 1, y + 1, z, colour);
InsertLine(x - 2, y + 2, x + HealthBarW + 1, y + 2, z, colour);
InsertLine(x - 2, y + 3, x + HealthBarW + 1, y + 3, z, colour);
InsertLine(x - 2, y + 4, x + HealthBarW + 1, y + 4, z, colour);
InsertLine(x - 2, y + 5, x + HealthBarW + 1, y + 5, z, colour);
InsertLine(x - 2, y + 6, x + HealthBarW + 1, y + 6, z, colour);
InsertLine(x - 2, y + 7, x + HealthBarW + 1, y + 7, z, colour);
if (w)
{
z = phd_znear + 40;
colour = (char)inv_colours[poisoned ? C_YELLOW : C_RED];
InsertLine(x, y + 2, x + w, y + 2, z, colour);
InsertLine(x, y + 3, x + w, y + 3, z, colour);
InsertLine(x, y + 4, x + w, y + 4, z, colour);
InsertLine(x, y + 5, x + w, y + 5, z, colour);
InsertLine(x, y + 6, x + w, y + 6, z, colour);
}
}
void S_DrawAirBar(int percent)
{
HWR_EnableZBuffer(true, true);
g_blue_effect = false;
int x = AirBarX,
y = AirBarY,
w = (percent * AirBarW) / 100,
z = phd_znear + 50;
auto colour = (char)inv_colours[C_BLACK];
InsertLine(x - 2, y + 1, x + AirBarW + 1, y + 1, z, colour);
InsertLine(x - 2, y + 2, x + AirBarW + 1, y + 2, z, colour);
InsertLine(x - 2, y + 3, x + AirBarW + 1, y + 3, z, colour);
InsertLine(x - 2, y + 4, x + AirBarW + 1, y + 4, z, colour);
InsertLine(x - 2, y + 5, x + AirBarW + 1, y + 5, z, colour);
InsertLine(x - 2, y + 6, x + AirBarW + 1, y + 6, z, colour);
InsertLine(x - 2, y + 7, x + AirBarW + 1, y + 7, z, colour);
z = phd_znear + 40;
colour = (char)inv_colours[C_GREY];
InsertLine(x - 2, y + 8, x + AirBarW + 2, y + 8, z, colour);
InsertLine(x + AirBarW + 2, y, x + AirBarW + 2, y + 8, z, colour);
z = phd_znear + 30;
colour = (char)inv_colours[C_WHITE];
InsertLine(x - 2, y, x + AirBarW + 2, y, z, colour);
InsertLine(x - 2, y + 8, x - 2, y, z, colour);
if (percent > 0)
{
z = phd_znear + 20;
colour = (char)inv_colours[C_WHITE];
InsertLine(x, y + 3, x + w, y + 3, z, colour);
colour = (char)inv_colours[C_BLUE];
InsertLine(x, y + 2, x + w, y + 2, z, colour);
InsertLine(x, y + 4, x + w, y + 4, z, colour);
InsertLine(x, y + 5, x + w, y + 5, z, colour);
InsertLine(x, y + 6, x + w, y + 6, z, colour);
}
} | 30.904255 | 89 | 0.58537 |