blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
e22a6da3857016ac5558a80c420bbe406ed51983
2351872312e3b5e38e4f625715ee5dfee4392302
/$P@/SPA/UnitTesting/TestParent.h
48987eeade11b6711b50ae7bbedc2f49acb86c45
[]
no_license
allanckw/32Ol_32oII_intelli-spa
737c4dae974cd08cf98ad414b4da847bdc19af62
e6929f146275ae2127a58584c65de7a1d83ce8a5
refs/heads/master
2020-05-07T13:18:03.290332
2013-04-25T14:20:07
2013-04-25T14:20:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
384
h
TestParent.h
#pragma once // Note 1 #include <cppunit/extensions/HelperMacros.h> class TestParent: public CPPUNIT_NS::TestFixture // Note 2 { CPPUNIT_TEST_SUITE(TestParent); // Note 3 CPPUNIT_TEST(testInsertAndRetrieveParent); CPPUNIT_TEST_SUITE_END(); public: void setUp(); void tearDown(); // method to test the assigning and retrieval of procs void testInsertAndRetrieveParent(); };
5fae218db8f0e1f4acac42de28e340dbc83f9d08
8e62c3eb35302aaa79e4a602ddfbb93489e09660
/mindspore/ccsrc/device/gpu/gpu_kernel_runtime.cc
dc4487ccee1501e021ec61079b766053a89f1ace
[ "Apache-2.0", "IJG", "Zlib", "LGPL-2.1-only", "MIT", "BSD-3-Clause", "BSD-3-Clause-Open-MPI", "GPL-2.0-only", "BSL-1.0", "MPL-2.0", "MPL-2.0-no-copyleft-exception", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-public-domain", "AGPL-3.0-only", "LicenseRef-scancode-unknown-license-reference", "MPL-1.1", "Unlicense", "BSD-2-Clause", "MPL-1.0", "Libpng" ]
permissive
ythlml/mindspore
a7faa28fa401372c73798c6b0ad186fa10386b09
028ae212624164044cfaa84f347fc502cb7fcb0f
refs/heads/master
2022-09-09T20:28:34.554927
2020-05-24T06:19:23
2020-05-24T06:19:23
266,301,148
7
0
Apache-2.0
2020-05-23T09:09:49
2020-05-23T09:09:48
null
UTF-8
C++
false
false
16,042
cc
gpu_kernel_runtime.cc
/** * Copyright 2019 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "device/gpu/gpu_kernel_runtime.h" #include "device/gpu/gpu_device_address.h" #include "device/gpu/cuda_driver.h" #include "device/gpu/gpu_buffer_mgr.h" #include "device/gpu/gpu_device_manager.h" #include "device/gpu/gpu_memory_allocator.h" #include "device/gpu/distribution/collective_init.h" #include "utils/convert_utils.h" #include "utils/context/ms_context.h" #include "device/kernel_runtime_manager.h" #include "device/gpu/gpu_common.h" #include "common/utils.h" #include "device/gpu/gpu_memory_manager.h" #include "kernel/common_utils.h" namespace mindspore { namespace device { namespace gpu { bool GPUKernelRuntime::SyncStream() { return GPUDeviceManager::GetInstance().SyncStream(stream_); } bool GPUKernelRuntime::Init() { if (device_init_ == true) { return true; } auto ret = InitDevice(); if (!ret) { MS_LOG(ERROR) << "InitDevice error."; return ret; } mem_manager_ = std::make_shared<GPUMemoryManager>(); MS_EXCEPTION_IF_NULL(mem_manager_); mem_manager_->MallocDeviceMemory(); const void *collective_handle_ = CollectiveInitializer::instance().collective_handle(); bool collective_inited = CollectiveInitializer::instance().collective_inited(); if (collective_inited && collective_handle_ != nullptr) { auto init_nccl_comm_funcptr = reinterpret_cast<InitNCCLComm>(dlsym(const_cast<void *>(collective_handle_), "InitNCCLComm")); MS_EXCEPTION_IF_NULL(init_nccl_comm_funcptr); (*init_nccl_comm_funcptr)(); } device_init_ = true; return ret; } DeviceAddressPtr GPUKernelRuntime::CreateDeviceAddress(void *device_ptr, size_t device_size, const string &format, TypeId type_id) { return std::make_shared<GPUDeviceAddress>(device_ptr, device_size, format, type_id); } bool GPUKernelRuntime::InitDevice() { if (GPUDeviceManager::GetInstance().device_count() <= 0) { MS_LOG(ERROR) << "No GPU device found."; return false; } const void *collective_handle_ = CollectiveInitializer::instance().collective_handle(); bool collective_inited = CollectiveInitializer::instance().collective_inited(); if (collective_inited && collective_handle_ != nullptr) { auto get_local_rank_funcptr = reinterpret_cast<GetLocalRankId>(dlsym(const_cast<void *>(collective_handle_), "local_rank_id")); MS_EXCEPTION_IF_NULL(get_local_rank_funcptr); device_id_ = IntToUint((*get_local_rank_funcptr)()); } if (!GPUDeviceManager::GetInstance().is_device_id_init()) { if (!GPUDeviceManager::GetInstance().set_cur_device_id(device_id_)) { MS_LOG(ERROR) << "Failed to set current device to " << SizeToInt(device_id_); return false; } } GPUDeviceManager::GetInstance().InitDevice(); stream_ = GPUDeviceManager::GetInstance().default_stream(); if (stream_ == nullptr) { MS_LOG(ERROR) << "No default CUDA stream found."; return false; } return true; } void GPUKernelRuntime::ReleaseDeviceRes() { // For dataset mode. if (GpuBufferMgr::GetInstance().IsInit()) { if (!GpuBufferMgr::GetInstance().IsClosed()) { if (!GpuBufferMgr::GetInstance().CloseNotify()) { MS_LOG(EXCEPTION) << "Could not close gpu data queue."; } } CHECK_OP_RET_WITH_EXCEPT(GpuBufferMgr::GetInstance().Destroy(), "Could not destroy gpu data queue."); } GPUDeviceManager::GetInstance().ReleaseDevice(); if (mem_manager_ != nullptr) { mem_manager_->FreeDeviceMemory(); } kernel::KernelMeta::GetInstance()->RemoveKernelCache(); } void GPUKernelRuntime::AssignMemory(session::KernelGraph *graph) { auto context_ptr = MsContext::GetInstance(); MS_EXCEPTION_IF_NULL(context_ptr); MS_EXCEPTION_IF_NULL(mem_manager_); mem_manager_->ResetDynamicMemory(); AssignStaticMemoryInput(graph); AssignStaticMemoryValueNode(graph); bool is_enable_dynamic_mem = context_ptr->enable_dynamic_mem_pool(); if (is_enable_dynamic_mem) { // Use the dynamic memory pool. InitKernelRefCount(graph); InitKernelOutputAddress(graph); } else { AssignDynamicMemory(graph); } } bool GPUKernelRuntime::Run(session::KernelGraph *graph) { bool ret; auto context_ptr = MsContext::GetInstance(); MS_EXCEPTION_IF_NULL(context_ptr); bool is_enable_dynamic_mem = context_ptr->enable_dynamic_mem_pool(); bool is_enable_pynative_infer = context_ptr->enable_pynative_infer(); struct timeval start_time, end_time; (void)gettimeofday(&start_time, nullptr); if (is_enable_dynamic_mem && !is_enable_pynative_infer) { ret = LaunchKernelDynamic(graph); } else { ret = LaunchKernel(graph); } (void)gettimeofday(&end_time, nullptr); const uint64_t kUSecondInSecond = 1000000; uint64_t cost = kUSecondInSecond * static_cast<uint64_t>(end_time.tv_sec - start_time.tv_sec); cost += static_cast<uint64_t>(end_time.tv_usec - start_time.tv_usec); MS_LOG(DEBUG) << "kernel runtime run graph in " << cost << " us"; return ret; } void GPUKernelRuntime::InitKernelRefCount(const session::KernelGraph *graph) { MS_EXCEPTION_IF_NULL(graph); MemReuseUtilPtr mem_reuse_util_ptr = std::make_shared<memreuse::MemReuseUtil>(); MS_EXCEPTION_IF_NULL(mem_reuse_util_ptr); // Init the kernel reference count. if (!mem_reuse_util_ptr->InitDynamicKernelRef(graph)) { MS_LOG(EXCEPTION) << "Init kernel reference count failed"; } mem_reuse_util_ptr->SetKernelDefMap(); mem_reuse_util_ptr->SetReuseRefCount(); // Can't free the device address of graph output, so set the reference count of graph output specially. mem_reuse_util_ptr->SetGraphOutputRefCount(); auto graph_id = graph->graph_id(); mem_reuse_util_map_[graph_id] = mem_reuse_util_ptr; } void GPUKernelRuntime::InitKernelOutputAddress(const session::KernelGraph *graph) { MS_EXCEPTION_IF_NULL(graph); auto &kernels = graph->execution_order(); for (const auto &kernel : kernels) { auto kernel_mod = AnfAlgo::GetKernelMod(kernel); MS_EXCEPTION_IF_NULL(kernel_mod); auto output_sizes = kernel_mod->GetOutputSizeList(); for (size_t i = 0; i < output_sizes.size(); ++i) { if (AnfAlgo::OutputAddrExist(kernel, i)) { continue; } std::string output_format = AnfAlgo::GetOutputFormat(kernel, i); auto output_type = AnfAlgo::GetOutputDeviceDataType(kernel, i); auto device_address = CreateDeviceAddress(nullptr, output_sizes[i], output_format, output_type); AnfAlgo::SetOutputAddr(device_address, i, kernel.get()); } } } bool GPUKernelRuntime::LaunchKernelDynamic(const session::KernelGraph *graph) { MS_EXCEPTION_IF_NULL(graph); auto graph_id = graph->graph_id(); auto mem_reuse_util_ptr = mem_reuse_util_map_[graph_id]; MS_EXCEPTION_IF_NULL(mem_reuse_util_ptr); // Reset the reference count. mem_reuse_util_ptr->ResetDynamicUsedRefCount(); // The inputs and outputs memory of communication kernel need be continuous, so separate processing. AllocCommunicationOpDynamicRes(graph); auto &kernels = graph->execution_order(); for (const auto &kernel : kernels) { auto kernel_mod = AnfAlgo::GetKernelMod(kernel); MS_EXCEPTION_IF_NULL(kernel_mod); AddressPtrList kernel_inputs; AddressPtrList kernel_workspaces; AddressPtrList kernel_outputs; AllocKernelDynamicRes(*kernel_mod, kernel, &kernel_inputs, &kernel_workspaces, &kernel_outputs); if (!kernel_mod->Launch(kernel_inputs, kernel_workspaces, kernel_outputs, stream_)) { MS_LOG(ERROR) << "Launch kernel failed."; return false; } FreeKernelDynamicRes(kernel, kernel_workspaces, graph_id); } if (!SyncStream()) { MS_LOG(ERROR) << "SyncStream failed."; return false; } return true; } void GPUKernelRuntime::AllocKernelDynamicRes(const mindspore::kernel::KernelMod &kernel_mod, const mindspore::AnfNodePtr &kernel, AddressPtrList *kernel_inputs, AddressPtrList *kernel_workspaces, AddressPtrList *kernel_outputs) { MS_EXCEPTION_IF_NULL(kernel); MS_EXCEPTION_IF_NULL(kernel_inputs); MS_EXCEPTION_IF_NULL(kernel_workspaces); MS_EXCEPTION_IF_NULL(kernel_outputs); MS_EXCEPTION_IF_NULL(mem_manager_); for (size_t i = 0; i < AnfAlgo::GetInputTensorNum(kernel); ++i) { auto device_address = AnfAlgo::GetPrevNodeOutputAddr(kernel, i); MS_EXCEPTION_IF_NULL(device_address); MS_EXCEPTION_IF_NULL(device_address->ptr_); kernel::AddressPtr input = std::make_shared<kernel::Address>(); MS_EXCEPTION_IF_NULL(input); input->addr = device_address->ptr_; input->size = device_address->size_; kernel_inputs->emplace_back(input); } auto output_sizes = kernel_mod.GetOutputSizeList(); for (size_t i = 0; i < output_sizes.size(); ++i) { auto device_address = AnfAlgo::GetMutableOutputAddr(kernel, i); MS_EXCEPTION_IF_NULL(device_address); if (device_address->ptr_ == nullptr) { auto ret = mem_manager_->MallocMemFromMemPool(device_address, output_sizes[i]); if (!ret) { MS_LOG(EXCEPTION) << "Malloc device memory failed."; } } kernel::AddressPtr output = std::make_shared<kernel::Address>(); MS_EXCEPTION_IF_NULL(output); output->addr = device_address->ptr_; output->size = output_sizes[i]; kernel_outputs->emplace_back(output); } auto workspace_sizes = kernel_mod.GetWorkspaceSizeList(); for (size_t i = 0; i < workspace_sizes.size(); ++i) { if (workspace_sizes[i] == 0) { kernel_workspaces->emplace_back(nullptr); continue; } auto device_ptr = mem_manager_->MallocMemFromMemPool(workspace_sizes[i]); if (!device_ptr) { MS_LOG(EXCEPTION) << "Malloc device memory failed."; } kernel::AddressPtr workspace = std::make_shared<kernel::Address>(); MS_EXCEPTION_IF_NULL(workspace); workspace->addr = device_ptr; workspace->size = workspace_sizes[i]; kernel_workspaces->emplace_back(workspace); } } void GPUKernelRuntime::AllocCommunicationOpDynamicRes(const session::KernelGraph *graph) { MS_EXCEPTION_IF_NULL(graph); auto &kernels = graph->execution_order(); for (auto &kernel : kernels) { MS_EXCEPTION_IF_NULL(kernel); if (AnfAlgo::IsCommunicationOp(kernel)) { AllocCommunicationOpInputDynamicRes(kernel); AllocCommunicationOpOutputDynamicRes(kernel); } } } void GPUKernelRuntime::AllocCommunicationOpInputDynamicRes(const mindspore::AnfNodePtr &kernel) { MS_EXCEPTION_IF_NULL(kernel); MS_EXCEPTION_IF_NULL(mem_manager_); bool is_need_alloc_memory = false; bool is_need_free_memory = false; size_t total_size = 0; std::vector<size_t> size_list; DeviceAddressPtrList addr_list; for (size_t i = 0; i < AnfAlgo::GetInputTensorNum(kernel); ++i) { auto device_address = AnfAlgo::GetPrevNodeMutableOutputAddr(kernel, i); MS_EXCEPTION_IF_NULL(device_address); if (device_address->ptr_ == nullptr) { is_need_alloc_memory = true; } else { is_need_free_memory = true; } total_size += device_address->size_; size_list.emplace_back(device_address->size_); addr_list.emplace_back(device_address); } AllocCommunicationOpMemory(is_need_alloc_memory, is_need_free_memory, addr_list, total_size, size_list); } void GPUKernelRuntime::AllocCommunicationOpOutputDynamicRes(const mindspore::AnfNodePtr &kernel) { MS_EXCEPTION_IF_NULL(kernel); MS_EXCEPTION_IF_NULL(mem_manager_); bool is_need_alloc_memory = false; bool is_need_free_memory = false; size_t total_size = 0; std::vector<size_t> size_list; DeviceAddressPtrList addr_list; auto kernel_mod = AnfAlgo::GetKernelMod(kernel); MS_EXCEPTION_IF_NULL(kernel_mod); auto output_sizes = kernel_mod->GetOutputSizeList(); for (size_t i = 0; i < output_sizes.size(); ++i) { auto device_address = AnfAlgo::GetMutableOutputAddr(kernel, i); MS_EXCEPTION_IF_NULL(device_address); if (device_address->ptr_ == nullptr) { is_need_alloc_memory = true; } else { is_need_free_memory = true; } total_size += output_sizes[i]; size_list.emplace_back(output_sizes[i]); addr_list.emplace_back(device_address); } AllocCommunicationOpMemory(is_need_alloc_memory, is_need_free_memory, addr_list, total_size, size_list); } void GPUKernelRuntime::AllocCommunicationOpMemory(bool is_need_alloc_memory, bool is_need_free_memory, const DeviceAddressPtrList addr_list, size_t total_size, std::vector<size_t> size_list) { if (!is_need_alloc_memory) { return; } if (is_need_free_memory) { for (const auto &iter : addr_list) { MS_EXCEPTION_IF_NULL(iter); // Free the inputs/outputs of communication kernel which are not released. if (iter->ptr_ != nullptr) { mem_manager_->FreeMemFromMemPool(iter); } } } auto ret = mem_manager_->MallocContinuousMemFromMemPool(addr_list, total_size, size_list); if (!ret) { MS_LOG(EXCEPTION) << "Malloc device memory failed."; } } void GPUKernelRuntime::FreeKernelDynamicRes(const mindspore::AnfNodePtr &kernel, const AddressPtrList &kernel_workspaces, uint32_t graph_id) { MS_EXCEPTION_IF_NULL(kernel); MS_EXCEPTION_IF_NULL(mem_manager_); auto mem_reuse_util_ptr = mem_reuse_util_map_[graph_id]; MS_EXCEPTION_IF_NULL(mem_reuse_util_ptr); auto cnode = kernel->cast<CNodePtr>(); MS_EXCEPTION_IF_NULL(cnode); if (AnfAlgo::GetCNodeName(kernel) == kAllReduceOpName) { return; } // Free the input of kernel by reference count. for (size_t i = 0; i < AnfAlgo::GetInputTensorNum(kernel); ++i) { auto kernel_ref_count_ptr = mem_reuse_util_ptr->GetKernelInputRef(cnode, i); if (kernel_ref_count_ptr == nullptr) { continue; } kernel_ref_count_ptr->ref_count_dynamic_use_--; if (kernel_ref_count_ptr->ref_count_dynamic_use_ < 0) { MS_LOG(EXCEPTION) << "Check dynamic reference count failed."; } if (kernel_ref_count_ptr->ref_count_dynamic_use_ == 0) { auto device_address = AnfAlgo::GetPrevNodeMutableOutputAddr(kernel, i); mem_manager_->FreeMemFromMemPool(device_address); } } // Free the output of kernel, if output has no reference. for (size_t i = 0; i < AnfAlgo::GetOutputTensorNum(kernel); ++i) { auto kernel_ref_count_ptr = mem_reuse_util_ptr->GetRef(cnode, i); if (kernel_ref_count_ptr == nullptr) { continue; } if (kernel_ref_count_ptr->ref_count_dynamic_use_ == 0) { auto device_address = AnfAlgo::GetMutableOutputAddr(kernel, i); mem_manager_->FreeMemFromMemPool(device_address); } } // Free the workspace of kernel. for (size_t i = 0; i < kernel_workspaces.size(); ++i) { auto workspace = kernel_workspaces[i]; if (workspace != nullptr) { MS_EXCEPTION_IF_NULL(workspace->addr); mem_manager_->FreeMemFromMemPool(workspace->addr); workspace->addr = nullptr; } } } } // namespace gpu } // namespace device } // namespace mindspore
cd81dbc40a688a28e3becdddc7d17885347c0a16
91b268d73d27dd5b6b1329b1de57d4d65d6ca743
/algorithms/longest_common_substring/main.cpp
31a32bb731382cf043436d3087b97b839c3f9432
[]
no_license
allisonkundrik/examples
e5b2772e07d0ea1251bbcae1905109873d4e80cc
f6fe125e6ab9118127ba771ecf16e740c8ca7ea1
refs/heads/master
2020-05-16T19:14:27.915885
2016-07-28T20:08:46
2016-07-28T20:08:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,075
cpp
main.cpp
/* * File: main.cpp * Author: peter * * Created on March 9, 2014, 12:53 AM * http://stackoverflow.com/questions/22276500/overlapping-of-keyword-and-comparison-word/22276831#22276831 */ #include <string> std::string longestCommonSubstr( std::string& s, std::string& in) { size_t s_s = s.size(); size_t in_s = in.size(); if ( ( s_s == 0) || ( in_s == 0)) return std::string(); size_t common_s = std::min( s_s, in_s); for ( size_t i = common_s; i > 0; i--) { size_t pos_beg = 0; size_t pos_end = i; while ( pos_end < s_s + 1) { std::string searched = s.substr( pos_beg, pos_end); size_t found = in.find( searched); if ( found != std::string::npos) return searched; ++pos_beg; ++pos_end; } } return std::string(); } /* * */ int main(int argc, char** argv) { std::string me( "face"); std::string ymey( "efftarcc"); std::string res = longestCommonSubstr( me, ymey); if ( !res.empty()) { // found } return 0; }
40a7e55ae55c538e7918322e58f7d208cd91d05c
d1cf7ad235c3c4ce7e154fc3651bb94496276388
/src/Input.h
fe8525f4742835f466f06a1e0d3386cef63a92dd
[]
no_license
ArcoMul/Rrenderer
fd5b9714eef0f52b46b690b78f40ad9e8491a0ee
d4239fe3f7a34e5c8e0682da3d949556c73e83c4
refs/heads/master
2020-06-03T21:00:50.182052
2015-02-04T21:45:30
2015-02-04T21:45:30
26,933,969
0
0
null
null
null
null
UTF-8
C++
false
false
598
h
Input.h
#pragma once #include "Rrenderer.h" #include "Vector3.h" namespace Rr { class RRENDERER_API Input { public: Input(); ~Input(); bool isPressed(int key); void setPressed(int key, bool pressed); bool keysDown[100]; static const int KEY_W = 87; static const int KEY_A = 65; static const int KEY_S = 83; static const int KEY_D = 68; static const int KEY_SPACE = 32; static const int KEY_SHIFT = 340; void setMousePosition(double x, double y); Vector3 getMousePosition(); Vector3 getMousePositionDelta(); Vector3 mousePosition; Vector3 mousePositionDelta; }; }
7985821457a03d472800b70d120ac9017a8a294b
4e21668ee4107d7899fe4e0375272b803a8f5fc8
/Upper/main.cpp
012ca97ecc581341d8888d1247add316f83edbf5
[]
no_license
SoapLi/57StepMotor-ctrl
7544d600d68aeb49911c54b9295fe421f2605b3d
c3e9e1b9beb6dee7c5f19bd337c543b406a12940
refs/heads/master
2022-12-10T00:01:01.112388
2020-09-08T16:06:15
2020-09-08T16:06:15
293,859,878
0
0
null
null
null
null
UTF-8
C++
false
false
827
cpp
main.cpp
#include <QApplication> #include "datamenu.h" #include "GloableData/gloabledata.h" #include <macro_define.h> #include <QTextStream> #include <QByteArray> #include <QDebug> #include <QString> #include <QTableWidget> #include "qtablewidget.h" #include <QWidget> //#include <QtGui/QApplication> #include <QTableWidget> #include <QTableWidgetItem> #include <QDebug> #include <QSplashScreen> #include <QDateTime> #include <QMessageBox> #include <QFileDialog> #include <QSettings> #include "qt_windows.h" #include <QVariant> #include <QDebug> #include <QScrollBar> #include <QSettings> #include<stdio.h> #include<windows.h> #include<string.h> #include<conio.h> #include <QtXml> #include "tools.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); DataMenu dataMenu; dataMenu.show(); return a.exec(); }
370fca9f54d10868862bc78561a540452ee09450
a92b18defb50c5d1118a11bc364f17b148312028
/src/prod/test/FabricTest/ITestStoreService.h
1b008f0be86766af2c710f8d700b49253ac81883
[ "MIT" ]
permissive
KDSBest/service-fabric
34694e150fde662286e25f048fb763c97606382e
fe61c45b15a30fb089ad891c68c893b3a976e404
refs/heads/master
2023-01-28T23:19:25.040275
2020-11-30T11:11:58
2020-11-30T11:11:58
301,365,601
1
0
MIT
2020-11-30T11:11:59
2020-10-05T10:05:53
null
UTF-8
C++
false
false
5,510
h
ITestStoreService.h
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #pragma once using namespace Store; namespace FabricTest { struct ITestStoreService { public: virtual ~ITestStoreService() { }; virtual Common::ErrorCode Put( __int64 key, std::wstring const& value, FABRIC_SEQUENCE_NUMBER currentVersion, std::wstring serviceName, FABRIC_SEQUENCE_NUMBER & newVersion, ULONGLONG & dataLossVersion) = 0; virtual Common::ErrorCode Get( __int64 key, std::wstring serviceName, std::wstring & value, FABRIC_SEQUENCE_NUMBER & version, ULONGLONG & dataLossVersion) = 0; virtual Common::ErrorCode GetAll( std::wstring serviceName, vector<std::pair<__int64,std::wstring>> & kvpairs) { UNREFERENCED_PARAMETER(serviceName); UNREFERENCED_PARAMETER(kvpairs); return Common::ErrorCodeValue::NotImplemented; } virtual Common::ErrorCode GetKeys( std::wstring serviceName, __int64 first, __int64 last, vector<__int64> & keys) { UNREFERENCED_PARAMETER(serviceName); UNREFERENCED_PARAMETER(first); UNREFERENCED_PARAMETER(last); UNREFERENCED_PARAMETER(keys); return Common::ErrorCodeValue::NotImplemented; } virtual Common::ErrorCode Delete( __int64, FABRIC_SEQUENCE_NUMBER, std::wstring, FABRIC_SEQUENCE_NUMBER &, ULONGLONG &) { return Common::ErrorCodeValue::NotImplemented; } virtual Common::ComPointer<IFabricStatefulServicePartition> const& GetPartition() const = 0; virtual std::wstring const & GetPartitionId() const = 0; virtual std::wstring const & GetServiceLocation() const = 0; virtual bool IsStandby() const = 0; virtual std::wstring const & GetServiceName() const = 0; virtual Federation::NodeId const & GetNodeId() const = 0; virtual void SetSecondaryPumpEnabled(bool value) = 0; virtual void ReportFault(::FABRIC_FAULT_TYPE faultType) const = 0; virtual void ReportLoad(ULONG metricCount, ::FABRIC_LOAD_METRIC const *metrics) const = 0; virtual void ReportMoveCost(::FABRIC_MOVE_COST moveCost) const = 0; virtual Common::ErrorCode ReportPartitionHealth( ::FABRIC_HEALTH_INFORMATION const *healthInfo, ::FABRIC_HEALTH_REPORT_SEND_OPTIONS const * sendOptions) const = 0; virtual Common::ErrorCode ReportReplicaHealth( ::FABRIC_HEALTH_INFORMATION const *healthInfo, ::FABRIC_HEALTH_REPORT_SEND_OPTIONS const * sendOptions) const = 0; virtual FABRIC_SERVICE_PARTITION_ACCESS_STATUS GetWriteStatus() const = 0; virtual FABRIC_SERVICE_PARTITION_ACCESS_STATUS GetReadStatus() const = 0; virtual Common::ErrorCode Backup(std::wstring const & dir) = 0; virtual Common::ErrorCode Restore(std::wstring const & dir) = 0; virtual Common::AsyncOperationSPtr BeginBackup( __in std::wstring const & backupDir, __in StoreBackupOption::Enum backupOption, __in Api::IStorePostBackupHandlerPtr const & postBackupHandler, __in Common::AsyncCallback const & callback, __in Common::AsyncOperationSPtr const & parent) = 0; virtual Common::ErrorCode EndBackup( __in Common::AsyncOperationSPtr const & operation) = 0; virtual Common::AsyncOperationSPtr BeginRestore( __in std::wstring const & backupDir, __in Common::AsyncCallback const & callback, __in Common::AsyncOperationSPtr const & parent) = 0; virtual Common::ErrorCode EndRestore( __in Common::AsyncOperationSPtr const & operation) = 0; virtual Common::ErrorCode CompressionTest(std::vector<std::wstring> const & params) = 0; virtual Common::ErrorCode getCurrentStoreTime(int64 & currentStoreTime) = 0; virtual Common::ErrorCode RequestCheckpoint() { return Common::ErrorCodeValue::NotImplemented; } virtual Common::ErrorCode GetReplicationQueueCounters( __out FABRIC_INTERNAL_REPLICATION_QUEUE_COUNTERS & counter) { UNREFERENCED_PARAMETER(counter); return Common::ErrorCodeValue::NotImplemented; } virtual Common::ErrorCode GetReplicatorQueryResult(__out ServiceModel::ReplicatorStatusQueryResultSPtr & result) { UNREFERENCED_PARAMETER(result); return Common::ErrorCodeValue::NotImplemented; } virtual NTSTATUS GetPeriodicCheckpointAndTruncationTimestamps( __out LONG64 & lastPeriodicCheckpoint, __out LONG64 & lastPeriodicTruncation) { lastPeriodicCheckpoint = 0; lastPeriodicTruncation = 0; return STATUS_NOT_IMPLEMENTED; } }; typedef std::shared_ptr<ITestStoreService> ITestStoreServiceSPtr; typedef std::weak_ptr<ITestStoreService> ITestStoreServiceWPtr; };
e98b5c8611b0be328a088c8b2cc774f1f1f321cd
052f25db8b52e1de600625905caae9dd79433841
/client/global.h
6b94a71cca10ccd2fd3fe75356b486e476e9884a
[]
no_license
laurentiudodoloi/rc-resources
a9e4232ea34ca42f324256a843b96623886d61ae
719da517dcd9b21e4a36cd3696451320ddd2ab8c
refs/heads/master
2022-03-27T03:24:11.664601
2020-01-18T07:40:29
2020-01-18T07:40:29
234,174,206
0
0
null
null
null
null
UTF-8
C++
false
false
383
h
global.h
#ifndef GLOBAL_H #define GLOBAL_H #include "file.h" #include <string> #include "mainwindow.h" #include <list> class Global { public: static File currentFile; static std::string tempText; static MainWindow *window; static std::list<std::string> fileList; Global(); static bool isFileSelected(); static void selectFile(File file); }; #endif // GLOBAL_H
6a44e5149a401ce37ee5bbc465b57e32c138cb1f
f95dd759587fe0fe53c4f1c29d8b2181e52c1ece
/src/ossimGui/GatherImageViewProjTransVisitor.cpp
497cc6ed1de6477309e2550208cc64e26e2d3c16
[ "MIT" ]
permissive
ossimlabs/ossim-gui
2b547a604885f9b5af458d528a90055538430bec
746840ec731aef50056a626ae1ffd8e5a280fede
refs/heads/dev
2022-11-03T08:16:29.890146
2022-10-19T14:19:38
2022-10-19T14:19:38
42,268,337
4
1
MIT
2019-04-07T02:45:14
2015-09-10T20:14:20
C++
UTF-8
C++
false
false
1,375
cpp
GatherImageViewProjTransVisitor.cpp
#include <ossimGui/GatherImageViewProjTransVisitor.h> #include <ossim/imaging/ossimImageRenderer.h> #include <ossim/imaging/ossimImageHandler.h> void ossimGui::GatherImageViewProjTransVisitor::visit(ossimObject* obj) { if(!hasVisited(obj)) { ossimImageRenderer* renderer = dynamic_cast<ossimImageRenderer*>(obj); if(renderer) { ossimImageViewProjectionTransform* ivpt = dynamic_cast<ossimImageViewProjectionTransform*>(renderer->getImageViewTransform()); if(ivpt) { m_transformList.push_back(new IvtGeomTransform(ivpt, ivpt->getImageGeometry()) ); } else { ossimImageViewAffineTransform* ivat = dynamic_cast<ossimImageViewAffineTransform*>(renderer->getImageViewTransform()); if(ivat&&renderer->getInput()) { ossimTypeNameVisitor v("ossimImageHandler", true); renderer->accept(v); ossimImageHandler* handler = v.getObjectAs<ossimImageHandler>(0); if(handler) { ossimRefPtr<ossimImageGeometry> geom = handler->getImageGeometry(); if(geom.valid()) { m_transformList.push_back(new IvtGeomTransform(ivat, geom.get()) ); } } } } } ossimVisitor::visit(obj); } }
5716b18e3798a25cebd2950c41554ca9fdae39fd
9aad1dfbbfa5e9650987950a601ee511bfb8a0a2
/FrameBuffer.h
16c3f796db2e23ea3568872c8861f6c2b9206536
[]
no_license
HummaWhite/SoftRaster
0a7755b310cfb2f5744e137957399654bc888b38
04a478c9aa14b1d309c1f846c90ab31aa8fd936f
refs/heads/master
2023-02-03T03:37:36.446985
2020-12-16T15:20:47
2020-12-16T15:20:47
280,191,203
0
0
null
null
null
null
UTF-8
C++
false
false
565
h
FrameBuffer.h
#ifndef FRAMEBUFFER_H #define FRAMEBUFFER_H #include "Buffer.h" template<typename T> struct FrameBuffer: Buffer<T> { FrameBuffer() {} FrameBuffer(int w, int h) { init(w, h); } ~FrameBuffer() {} void init(int w, int h) { Buffer<T>::init(w * h); width = w, height = h; } void release() { Buffer<T>::release(); width = height = 0; } void resize(int w, int h) { Buffer<T>::resize(w * h); init(w, h); } T& operator () (int i, int j) { return (*((Buffer<T>*)this)) [j * width + i]; } int width = 0; int height = 0; }; #endif
78e24b3f50533400b080fbf98bc551f630408d0b
4955e3dfffae9ce5d25bd4ea66fc3d822deb1ad6
/src/luv_tty.cc
2452fc3664a524c0b4bf72d8c37da8afbe462183
[]
no_license
bmeck/candor.io
412e79226b6f523b284ed2796bd4f4ccda595cdc
91cbef1fb46ba8ba07b3d817c347f7b0935043af
refs/heads/master
2023-07-11T19:44:27.882148
2012-03-29T07:12:28
2012-03-29T07:12:28
3,863,517
1
0
null
null
null
null
UTF-8
C++
false
false
1,258
cc
luv_tty.cc
#include "luv_stream.h" // uv_stream_prototype #include "luv_tty.h" #include "luv.h" #include "candor.h" #include "uv.h" #include <assert.h> // assert using namespace candor; static Value* luv_create_tty(uint32_t argc, Value* argv[]) { assert(argc > 0); int fd = argv[0]->ToNumber()->IntegralValue(); UVData* data = new UVData(sizeof(uv_tty_t), uv_tty_prototype()); uv_tty_init(uv_default_loop(), (uv_tty_t*)data->handle, fd, argc > 1 ? argv[1]->ToBoolean()->IsTrue() : fd == 0); return *data->obj; } static Value* luv_tty_set_mode(uint32_t argc, Value* argv[]) { assert(argc == 2); Object* obj = argv[0]->As<Object>(); uv_tty_t* handle = UVData::ObjectTo<uv_tty_t>(obj); int status = uv_tty_set_mode(handle, argv[1]->As<Boolean>()->IsTrue()); return Number::NewIntegral(status); } static Handle<Object> module; Object* uv_tty_module() { if (!module.IsEmpty()) return *module; module.Wrap(Object::New()); module->Set("create", Function::New(luv_create_tty)); return *module; } static Handle<Object> prototype; Object* uv_tty_prototype() { if (!prototype.IsEmpty()) return *prototype; prototype.Wrap(uv_stream_prototype()->Clone()); prototype->Set("setMode", Function::New(luv_tty_set_mode)); return *prototype; }
b23a3d5fac118ef23513f49c12515ecf8d736735
fead51e991d0dfa23d7a29cb0c5170e571407d4b
/src/test.cpp
e338d605c0dfb66342f7ff6ead7526d617c67442
[]
no_license
froly/catch-skeleton
f94f72aebdfac7a2774957fc76fdcd24bc107f28
d7e60fd08568bdac5a9d03f2e6c10ab860508a1c
refs/heads/master
2021-03-08T19:35:52.122622
2016-05-24T23:28:30
2016-05-24T23:43:57
59,615,879
0
0
null
null
null
null
UTF-8
C++
false
false
213
cpp
test.cpp
#ifdef CATCH_TEST #define CATCH_CONFIG_MAIN #include <Catch/single_include/catch.hpp> #endif #include "test.hpp" #ifdef CATCH_TEST TEST_CASE("TEST") { REQUIRE(1); } #else int main() { return 0; } #endif
aa9b64f13a28c40a8a415862e79f52371729c66d
25a9b6ee2479520c19971a644dc471b66139a1d9
/API/source/example.cpp
619f7fa756c3912c842f06294b7fd84b66d229ef
[ "MIT" ]
permissive
GrzegorzSalzburg/DroneApi
88e014eb71813cc23f2daedbea674f317e029edb
c05ebaabb760b5d099422cde54e743e08fa548f5
refs/heads/master
2022-11-09T19:16:07.931292
2020-06-15T12:25:04
2020-06-15T12:25:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,290
cpp
example.cpp
#include <iostream> #include <unistd.h> #include "Dr3D_gnuplot_api.hh" #include "Prostopadloscian.hh" #include "Powierzchnia.hh" #include "Dno.hh" #include "Graniastoslup.hh" #include "Dron.hh" #include "Przeszkoda_Pret.hh" #include "Przeszkod_Plaszczyzna.hh" #include "Przeszkoda_Prostopadloscienna.hh" using drawNS::APIGnuPlot3D; using drawNS::Point3D; using std::cout; using std::endl; using std::vector; using namespace std; void wait4key() { do { std::cout << "\n Press a key to continue..." << std::endl; } while (std::cin.get() != '\n'); } int main() { std::shared_ptr<drawNS::Draw3DAPI> api(new APIGnuPlot3D(-60, 60, -60, 60, -60, 60, 0)); //włacza gnuplota, pojawia się scena [-5,5] x [-5,5] x [-5,5] odświeżana co 1000 ms std::vector<std::shared_ptr<Przeszkoda>> tab; tab.push_back(make_shared<Przeszkoda_Plaszczyzna>(0, 10, 10, api)); tab.push_back(make_shared<Przeszkoda_Pret>(0, 10, 0, api)); tab.push_back(make_shared<Przeszkoda_Prostopadloscian>(20, 20, 10, api)); for (int i = 0; i < tab.size(); i++) { tab[i]->ruch(rand() % 30 + 20, rand() % 360); tab[i]->rysuj(); } Powierzchnia po(api); Dno d(api); d.rysuj(); po.rysuj(); Dron dron(api); dron.start(); char opcja; while (1) { cout << "wybierz opcje:" << endl; cout << "p - przesuniecie" << endl; cout << "o - obrot" << endl; cout << "k - koniec" << endl; std::cin >> opcja; switch (opcja) { case 'p': { cout << "Podaj przesuniecie" << endl; double przesu; cin >> przesu; cout << "Podaj kat" << endl; double kat; cin >> kat; int i; for (int k = 0; k < przesu; k++) { tab[2]->kolizja(dron); for ( i = 0; i < tab.size() && !tab[i]->kolizja(dron); i++); if(i>2) i=0; if( tab[i]->kolizja(dron)) { break; } dron.przesun_(kat); } break; } case 'o': { std::cout << "Podaj kat" << std::endl; double k; std::cin >> k; if(k>0) for (int i = 0; i < k; i++) { dron.obrot(); } else for (int i = 0; i < -k; i++) { dron.obrot_ujem(); } break; } case 'k': { return 1; break; } } } }
da3bdfa6a1609de6da62566e22f66d19261bb466
5673ea0c12cf8798a66e3fb9a798b260cea55c67
/Code/ARIAELEC/mainwindow.h
d0dbb4d4fd95f2b247b54fc44ba868dc2f202932
[]
no_license
mohammadVatandoost/Oscilloscope-Digital
49127b62d77f90386f54ca06468fdb4653e9eb76
aaa42847f329042861b49e679f7e4cd19c671c83
refs/heads/master
2021-08-15T22:42:28.834682
2017-11-18T13:28:14
2017-11-18T13:28:14
111,195,719
2
0
null
null
null
null
UTF-8
C++
false
false
2,048
h
mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <qwidget.h> #include "plot.h" #include "plot2.h" #include "knob.h" #include "knob2.h" #include "wheelbox.h" #include "wheelbox2.h" #include <qwt_scale_engine.h> #include <qlabel.h> #include <qlayout.h> #include <QtMath> #include <QtCore> #include <QPixmap> #include <QLabel> #include <QtCore> #include <QtSerialPort/QSerialPortInfo> #include <QtSerialPort/QSerialPort> #include <QtSerialPort/qserialport.h> #include <QtSerialPort/QtSerialPort> #include <QtSerialPort/qserialportglobal.h> #include <QTextEdit> #include <qtextedit.h> #include <QDebug> #include <time.h> #include "QMessageBox" #include <QProgressBar> #include <qprogressbar.h> #include "samplingthread.h" #include "samplingthread2.h" #include <time.h> #include <QIcon> class Plot; class Plot2; class Knob; class Knob2; class WheelBox; class WheelBox2; namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); void start(); float temp0,temp1; QSerialPort *serial; QString come_port; QByteArray recieve; QPixmap *mypix; QIcon *icon; float voltage[3],current[2]; QString checkbox[5]; float test[1000]; int k = 0; int l=0; int p=0; int b = 0 ; int s =0 ; int flag_test=0; float last_value2 = 0; float last_value = 0; QTimer *dataTimer; QString text_edit; // double signalInterval() const; SamplingThread *samplingThread; SamplingThread2 *samplingThread_1; Q_SIGNALS: // void signalIntervalChanged( double ); float getVoltage1(float); float getVoltage2(float); private: Ui::MainWindow *ui; WheelBox *d_intervalWheel; WheelBox2 *d_intervalWheel_2; Plot *d_plot; Plot2 *d_plot_2; private slots: void on_pushButton_clicked(); void on_pushButton_2_clicked(); void on_pushButton_3_clicked(); void machineState(); void realtimeDataSlot(); }; #endif // MAINWINDOW_H
f74594f964deba4d488dc955f6f73e6297037097
7f32c053f44b7968a833802a0df281f665e4add4
/Header/CheckoutPtr.h
85ad38f83762d2cd84e2919a8cbe8904533d1ad5
[ "MIT" ]
permissive
fc3156/GitDemo
37b9c5065e8ea6da89fcc124870b5e52c97c16fa
713edc64111686ea6dc38fcdae0aadafce359a37
refs/heads/master
2020-05-31T05:30:30.725267
2019-10-15T06:17:55
2019-10-15T06:17:55
190,120,208
0
0
null
null
null
null
UTF-8
C++
false
false
777
h
CheckoutPtr.h
// // Created by fc0310 on 2019/5/16. // #ifndef LEARNVSC_CHECKOUTPTR_H #define LEARNVSC_CHECKOUTPTR_H #include <queue> #include <memory> #include "Customer.h" using PCustomer=std::unique_ptr<Customer>; class Checkout{ private: std::queue<PCustomer> customers; public: void add(PCustomer&& customer){ customers.push(std::move(customer)); } size_t qlength() const{return customers.size();}\ void time_increment(){ if(customers.front()->time_decrement().done()){ customers.pop(); } } bool operator<(const Checkout& other) const {return qlength()<other.qlength();} bool operator>(const Checkout& other) const {return qlength()>other.qlength();} }; #endif //LEARNVSC_CHECKOUTPTR_H
f737570a94ea8722ebf74fcb6a85e6eac17e4218
52101a66ad4106b1644fa2c201ffd9a8862aebb4
/Views/ConsoleInputOutput.h
fe18f0607f4402c99a1faaf5f3346bdd7d67ac0a
[]
no_license
celloist/Rogue
168a7b403b8bb557013afa0e8a201d0f6ccc4d2d
a3c9fe797777ea0bce953dba6ff31e521735f4d8
refs/heads/master
2020-12-14T04:14:32.601862
2016-03-23T13:17:45
2016-03-23T13:17:45
42,726,158
0
0
null
2016-03-23T13:17:47
2015-09-18T14:09:57
C++
UTF-8
C++
false
false
285
h
ConsoleInputOutput.h
// // Created by alhric on 30-Oct-15. // #ifndef ROGUE_CONSOLEINPUT_H #define ROGUE_CONSOLEINPUT_H #include <iostream> using namespace std; class ConsoleInputOutput { public: string askInput(string question); void display(string output); }; #endif //ROGUE_CONSOLEINPUT_H
dfc42bfb2743d3bb417e5647b63708022b48668d
8dd8a28c60935d7e367b088955119b04efc7cbb4
/rosmon_core/src/log_event.h
403f258c110415f046062158ae4d81723d548f35
[ "BSD-3-Clause" ]
permissive
rapyuta-robotics/rosmon
62abd8abd4edffdb693143b099108509618ad2df
b724a3e2a8d8d5bdb5b4370448dff16d5a3fc461
refs/heads/rr-devel
2021-08-18T15:48:48.555016
2021-07-16T05:18:43
2021-07-19T08:20:23
151,363,103
2
1
NOASSERTION
2021-07-19T09:02:58
2018-10-03T05:02:22
C++
UTF-8
C++
false
false
984
h
log_event.h
// Log event with metadata // Author: Max Schwarz <max.schwarz@ais.uni-bonn.de> #ifndef ROSMON_LOG_EVENT_H #define ROSMON_LOG_EVENT_H #include <string> namespace rosmon { struct LogEvent { public: enum class Type { /** * Raw messages from monitored nodes. These are self-coded using * ANSI escape codes. */ Raw, Info, Warning, Error }; enum class Channel { NotApplicable, Stdout, Stderr }; LogEvent(std::string source, std::string message, Type type = Type::Raw) : source{std::move(source)}, message{std::move(message)}, type{type} {} std::string source; std::string message; Type type; bool muted = false; Channel channel = Channel::NotApplicable; bool showStdout = true; }; inline std::string toString(LogEvent::Type type) { switch(type) { case LogEvent::Type::Info: return " INFO"; case LogEvent::Type::Warning: return " WARN"; case LogEvent::Type::Error: return "ERROR"; default: return "DEBUG"; } } } #endif
d385f0f2856f4d078948294d4ff275dad6106d83
21eb94c2c7e8b601926d0f87925703e29ba61cea
/dmf_control_board_rpc/Arduino/dmf_control_board_rpc/FeedbackController.cpp
d1baa827536b174b380358eb347f4bbc364b9287
[]
no_license
wheeler-microfluidics/dmf_control_board_rpc
05b323423a9ae56c3c1eab6d6d765a9183c7ad7e
73d5824e0a9b5a70ca99eaf5f5a8babc2aa087b1
refs/heads/master
2021-05-16T02:50:44.883759
2017-07-20T14:30:14
2017-07-20T14:30:14
19,990,949
0
0
null
null
null
null
UTF-8
C++
false
false
16,991
cpp
FeedbackController.cpp
#if defined(AVR) || defined(__SAM3X8E__) #include "FeedbackController.h" #include "AdvancedADC.h" #include "DMFControlBoard.h" uint8_t FeedbackController::series_resistor_indices_[NUMBER_OF_ADC_CHANNELS]; uint8_t FeedbackController::saturated_[NUMBER_OF_ADC_CHANNELS]; uint8_t FeedbackController::post_saturation_ignore_[NUMBER_OF_ADC_CHANNELS]; uint16_t FeedbackController::max_value_[NUMBER_OF_ADC_CHANNELS]; uint16_t FeedbackController::min_value_[NUMBER_OF_ADC_CHANNELS]; uint32_t FeedbackController::sum2_[NUMBER_OF_ADC_CHANNELS]; uint16_t FeedbackController::n_samples_per_window_; DMFControlBoard* FeedbackController::parent_; bool FeedbackController::rms_; const uint8_t FeedbackController::CHANNELS[] = { FeedbackController::HV_CHANNEL, FeedbackController::FB_CHANNEL }; void FeedbackController::begin(DMFControlBoard* parent) { parent_ = parent; // set the default sampling rate AdvancedADC.setSamplingRate(45e3); // Versions > 1.2 use the built in 5V AREF (default) #if ___HARDWARE_MAJOR_VERSION___ == 1 && ___HARDWARE_MINOR_VERSION___ < 3 analogReference(EXTERNAL); #endif #if ___HARDWARE_MAJOR_VERSION___ == 1 pinMode(HV_SERIES_RESISTOR_0_, OUTPUT); pinMode(FB_SERIES_RESISTOR_0_, OUTPUT); pinMode(FB_SERIES_RESISTOR_1_, OUTPUT); pinMode(FB_SERIES_RESISTOR_2_, OUTPUT); #else pinMode(HV_SERIES_RESISTOR_0_, OUTPUT); pinMode(HV_SERIES_RESISTOR_1_, OUTPUT); pinMode(FB_SERIES_RESISTOR_0_, OUTPUT); pinMode(FB_SERIES_RESISTOR_1_, OUTPUT); pinMode(FB_SERIES_RESISTOR_2_, OUTPUT); pinMode(FB_SERIES_RESISTOR_3_, OUTPUT); #endif AdvancedADC.setPrescaler(3); // turn on smalles series resistors set_series_resistor_index(0, 0); set_series_resistor_index(1, 0); } uint8_t FeedbackController::set_series_resistor_index( const uint8_t channel_index, const uint8_t index) { uint8_t return_code = DMFControlBoard::RETURN_OK; if (channel_index==0) { switch(index) { case 0: digitalWrite(HV_SERIES_RESISTOR_0_, HIGH); #if ___HARDWARE_MAJOR_VERSION___ == 2 digitalWrite(HV_SERIES_RESISTOR_1_, LOW); #endif break; case 1: digitalWrite(HV_SERIES_RESISTOR_0_, LOW); #if ___HARDWARE_MAJOR_VERSION___ == 2 digitalWrite(HV_SERIES_RESISTOR_1_, HIGH); #endif break; #if ___HARDWARE_MAJOR_VERSION___ == 2 case 2: digitalWrite(HV_SERIES_RESISTOR_0_, LOW); digitalWrite(HV_SERIES_RESISTOR_1_, LOW); break; #endif default: return_code = DMFControlBoard::RETURN_BAD_INDEX; break; } if (return_code==DMFControlBoard::RETURN_OK) { series_resistor_indices_[channel_index] = index; } } else if (channel_index==1) { switch(index) { case 0: digitalWrite(FB_SERIES_RESISTOR_0_, HIGH); digitalWrite(FB_SERIES_RESISTOR_1_, LOW); digitalWrite(FB_SERIES_RESISTOR_2_, LOW); #if ___HARDWARE_MAJOR_VERSION___ == 2 digitalWrite(FB_SERIES_RESISTOR_3_, LOW); #endif break; case 1: digitalWrite(FB_SERIES_RESISTOR_0_, LOW); digitalWrite(FB_SERIES_RESISTOR_1_, HIGH); digitalWrite(FB_SERIES_RESISTOR_2_, LOW); #if ___HARDWARE_MAJOR_VERSION___ == 2 digitalWrite(FB_SERIES_RESISTOR_3_, LOW); #endif break; case 2: digitalWrite(FB_SERIES_RESISTOR_0_, LOW); digitalWrite(FB_SERIES_RESISTOR_1_, LOW); digitalWrite(FB_SERIES_RESISTOR_2_, HIGH); #if ___HARDWARE_MAJOR_VERSION___ == 2 digitalWrite(FB_SERIES_RESISTOR_3_, LOW); #endif break; case 3: digitalWrite(FB_SERIES_RESISTOR_0_, LOW); digitalWrite(FB_SERIES_RESISTOR_1_, LOW); digitalWrite(FB_SERIES_RESISTOR_2_, LOW); #if ___HARDWARE_MAJOR_VERSION___ == 2 digitalWrite(FB_SERIES_RESISTOR_3_, HIGH); #endif break; #if ___HARDWARE_MAJOR_VERSION___ == 2 case 4: digitalWrite(FB_SERIES_RESISTOR_0_, LOW); digitalWrite(FB_SERIES_RESISTOR_1_, LOW); digitalWrite(FB_SERIES_RESISTOR_2_, LOW); digitalWrite(FB_SERIES_RESISTOR_3_, LOW); break; #endif default: return_code = DMFControlBoard::RETURN_BAD_INDEX; break; } if (return_code==DMFControlBoard::RETURN_OK) { series_resistor_indices_[channel_index] = index; } } else { // bad channel_index return_code = DMFControlBoard::RETURN_BAD_INDEX; } return return_code; } // update buffer with new reading and increment to next channel_index void FeedbackController::interleaved_callback(uint8_t channel_index, uint16_t value) { // check if we've exceeded the saturation threshold if (value > SATURATION_THRESHOLD_HIGH || value < SATURATION_THRESHOLD_LOW) { if (post_saturation_ignore_[channel_index] == 0) { saturated_[channel_index] = saturated_[channel_index] + 1; // The ADC is saturated, so use a smaller resistor if (series_resistor_indices_[channel_index] > 0) { set_series_resistor_index(channel_index, series_resistor_indices_[channel_index] - 1); } post_saturation_ignore_[channel_index] = N_IGNORE_POST_SATURATION; } else { post_saturation_ignore_[channel_index] -= 1; } } else { if (rms_) { // update rms int32_t v = (int32_t)value-511; sum2_[channel_index] += v*v; } else { // update peak-to-peak if (value > max_value_[channel_index]) { max_value_[channel_index] = value; } else if (value < min_value_[channel_index]) { min_value_[channel_index] = value; } } } } void FeedbackController::hv_channel_callback(uint8_t channel_index, uint16_t value) { interleaved_callback(HV_CHANNEL_INDEX, value); } void FeedbackController::fb_channel_callback(uint8_t channel_index, uint16_t value) { interleaved_callback(FB_CHANNEL_INDEX, value); } uint16_t FeedbackController::measure_impedance(uint16_t n_samples_per_window, uint16_t n_sampling_windows, float delay_between_windows_ms, bool interleave_samples, bool rms) { // # `measure_impedance` # // // ## Pins ## // // - Analog pin `0` is connected to _high-voltage (HV)_ signal. // - Analog pin `1` is connected to _feedback (FB)_ signal. // // ## Analog input measurement circuit ## // // // $R_fixed$ // $V_in$ |-------/\/\/\------------\--------\--------\--------\ // | | | | // / / / / // $R_min$ \ $R_1$ \ $R_2$ \ $R_3$ \ // / / / / // \ \ \ \ // | | | | // o o o o // / / / / // / / / / // o o o o // | | | | // | | | | // --- --- --- --- // - - - - // // Based on the amplitude of $V_in$, we need to select an appropriate // resistor to activate, such that we divide the input voltage to within // 0-5V, since this is the range that Arduino ADC can handle. // // Collect samples over a set of windows of a set duration (number of // samples * sampling rate), and an optional delay between sampling windows. // // Only collect enough sampling windows to fill the maximum payload length. // // Each sampling window contains: // // - High-voltage amplitude. // - High-voltage resistor index. // - Feedback amplitude. // - Feedback resistor index. // save the number of samples per window and rms flag n_samples_per_window_ = n_samples_per_window; rms_ = rms; // record the current series resistors (so we can restore the current state // after this measurement) uint8_t original_hv_index = series_resistor_indices_[HV_CHANNEL_INDEX]; uint8_t original_fb_index = series_resistor_indices_[FB_CHANNEL_INDEX]; // enable the largest series resistors FeedbackReading reading; reading.hv_resistor_index = parent_->config_settings_.n_series_resistors(HV_CHANNEL_INDEX) - 1; reading.fb_resistor_index = parent_->config_settings_.n_series_resistors(FB_CHANNEL_INDEX) - 1; set_series_resistor_index(HV_CHANNEL_INDEX, reading.hv_resistor_index); set_series_resistor_index(FB_CHANNEL_INDEX, reading.fb_resistor_index); // Sample the following voltage signals: // // - Incoming high-voltage signal from the amplifier. // - Incoming feedback signal from the DMF device. // // For each signal, take `n` samples to find the corresponding peak-to-peak // voltage. While sampling, automatically select the largest feedback // resistor that _does not saturate_ the input _analog-to-digital converter // (ADC)_. This provides the highest resolution measurements. // // __NB__ In the case where the signal saturates the lowest resistor, mark // the measurement as saturated/invalid. if (interleave_samples) { AdvancedADC.setBufferLen(n_samples_per_window_); AdvancedADC.setChannels((uint8_t*)CHANNELS, NUMBER_OF_ADC_CHANNELS); AdvancedADC.registerCallback(&interleaved_callback); } else { AdvancedADC.setBufferLen(n_samples_per_window_/2); } // Calculate the transfer function for each high-voltage attenuator. Do this // once prior to starting measurements because these floating point // calculations are computationally intensive. float a_conv = parent_->aref() / 1023.0; float transfer_function[ sizeof(parent_->config_settings_.A0_series_resistance)/sizeof(float)]; for (uint8_t i=0; i < sizeof(transfer_function)/sizeof(float); i++) { float R = parent_->config_settings_.series_resistance(HV_CHANNEL, i); float C = parent_->config_settings_.series_capacitance(HV_CHANNEL, i); #if ___HARDWARE_MAJOR_VERSION___ == 1 transfer_function[i] = a_conv * sqrt(pow(10e6 / R + 1, 2) + pow(10e6 * C * 2 * M_PI * parent_->waveform_frequency(), 2)); #else // #if ___HARDWARE_MAJOR_VERSION___ == 1 transfer_function[i] = a_conv * sqrt(pow(10e6 / R, 2) + pow(10e6 * C * 2 * M_PI * parent_->waveform_frequency(), 2)); #endif // #if ___HARDWARE_MAJOR_VERSION___ == 1 } for (uint16_t i = 0; i < n_sampling_windows; i++) { // set both channels to the unsaturated state saturated_[HV_CHANNEL_INDEX] = 0; saturated_[FB_CHANNEL_INDEX] = 0; post_saturation_ignore_[HV_CHANNEL_INDEX] = 0; post_saturation_ignore_[FB_CHANNEL_INDEX] = 0; if (rms_) { // initialize sum2 buffer sum2_[HV_CHANNEL_INDEX] = 0; sum2_[FB_CHANNEL_INDEX] = 0; } else { // initialize max/min buffers min_value_[HV_CHANNEL_INDEX] = 1023; max_value_[HV_CHANNEL_INDEX] = 0; min_value_[FB_CHANNEL_INDEX] = 1023; max_value_[FB_CHANNEL_INDEX] = 0; } // Sample for `sampling_window_ms` milliseconds if (interleave_samples) { AdvancedADC.begin(); while(!AdvancedADC.finished()); } else { AdvancedADC.setChannel(HV_CHANNEL); AdvancedADC.registerCallback(&hv_channel_callback); AdvancedADC.begin(); while(!AdvancedADC.finished()); AdvancedADC.setChannel(FB_CHANNEL); AdvancedADC.registerCallback(&fb_channel_callback); AdvancedADC.begin(); while(!AdvancedADC.finished()); } // start measuring the time after our sampling window completeds long delta_t_start = micros(); float hv_rms, fb_rms; uint16_t &hv_pk_pk = reading.hv_pk_pk; uint16_t &fb_pk_pk = reading.fb_pk_pk; // calculate the rms voltage for each channel if (rms_) { hv_rms = sqrt((float)sum2_[HV_CHANNEL_INDEX] * 2.0 / (float)(n_samples_per_window_)); fb_rms = sqrt((float)sum2_[FB_CHANNEL_INDEX] * 2.0 / (float)(n_samples_per_window_)); hv_pk_pk = (hv_rms * 64.0 * 2.0 * sqrt(2)); fb_pk_pk = (fb_rms * 64.0 * 2.0 * sqrt(2)); } else { // use peak-to-peak measurements hv_pk_pk = 64 * (max_value_[HV_CHANNEL_INDEX] - min_value_[HV_CHANNEL_INDEX]); fb_pk_pk = 64 * (max_value_[FB_CHANNEL_INDEX] - min_value_[FB_CHANNEL_INDEX]); hv_rms = hv_pk_pk / sqrt(2) / (2 * 64); fb_rms = fb_pk_pk / sqrt(2) / (2 * 64); } // update the resistor indices if (saturated_[HV_CHANNEL_INDEX] > 0) { reading.hv_resistor_index = -saturated_[HV_CHANNEL_INDEX]; } else { reading.hv_resistor_index = series_resistor_indices_[HV_CHANNEL_INDEX]; } if (saturated_[FB_CHANNEL_INDEX] > 0) { reading.fb_resistor_index = -saturated_[FB_CHANNEL_INDEX]; } else { reading.fb_resistor_index = series_resistor_indices_[FB_CHANNEL_INDEX]; } // Based on the most-recent measurement of the incoming high-voltage // signal, adjust the gain correction factor we apply to waveform // amplitude changes to compensate for deviations from our model of the // gain of the amplifier. Only adjust gain if the last reading did not // saturate the ADC. if (parent_->auto_adjust_amplifier_gain() && saturated_[HV_CHANNEL_INDEX] == 0 && parent_->waveform_voltage() > 0) { // calculate the actuation voltage float measured_voltage = hv_rms * transfer_function[reading.hv_resistor_index]; float target_voltage; #if ___HARDWARE_MAJOR_VERSION___ == 1 float V_fb; if (saturated_[FB_CHANNEL_INDEX] > 0) { V_fb = 0; } else { V_fb = fb_rms * a_conv; } target_voltage = parent_->waveform_voltage() + V_fb; #else // #if ___HARDWARE_MAJOR_VERSION___ == 1 target_voltage = parent_->waveform_voltage(); #endif // #if ___HARDWARE_MAJOR_VERSION___ == 1 / #else // If we're outside of the voltage tolerance, update the gain and // voltage. if (abs(measured_voltage - target_voltage) > parent_->config_settings_.voltage_tolerance) { float gain = (parent_->amplifier_gain() * measured_voltage / target_voltage); // Enforce minimum gain of 1 because if gain goes to zero, it cannot // be adjusted further. if (gain < 1) { gain = 1; } parent_->set_amplifier_gain(gain); } } // if the voltage on either channel is too low (< ~5% of the available // range), increase the series resistor index one step if (hv_pk_pk < (64*1023L)/20) { set_series_resistor_index(HV_CHANNEL_INDEX, series_resistor_indices_[HV_CHANNEL_INDEX] + 1); } if (fb_pk_pk < (64*1023L)/20) { set_series_resistor_index(FB_CHANNEL_INDEX, series_resistor_indices_[FB_CHANNEL_INDEX] + 1); } // Serialize measurements to the return buffer. parent_->on_feedback_measure(reading); // There is a new request available on the serial port. Stop what we're // doing so we can service the new request. if (Serial.available() > 0) { break; } // if there is a delay between windows, wait until it has elapsed while( (micros() - delta_t_start) < delay_between_windows_ms*1000) {} } // Set the resistors back to their original states. set_series_resistor_index(HV_CHANNEL_INDEX, original_hv_index); set_series_resistor_index(FB_CHANNEL_INDEX, original_fb_index); // Return the number of samples that we measured _(i.e, the number of values // available in the result buffers)_. return n_sampling_windows; } #endif // defined(AVR) || defined(__SAM3X8E__)
3dea6e71afcb66c66721adcb74d72f9a9e67e418
b367fe5f0c2c50846b002b59472c50453e1629bc
/xbox_leak_may_2020/xbox trunk/xbox/private/vc7addon/vs/src/vc/ide/pkgs/projbld/ui_dll/src/exehierarchy.cpp
f8df167f3631bed59ea889cda87a50f0fecf55a7
[]
no_license
sgzwiz/xbox_leak_may_2020
11b441502a659c8da8a1aa199f89f6236dd59325
fd00b4b3b2abb1ea6ef9ac64b755419741a3af00
refs/heads/master
2022-12-23T16:14:54.706755
2020-09-27T18:24:48
2020-09-27T18:24:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,354
cpp
exehierarchy.cpp
//--------------------------------------------------------------------------- // Microsoft Visual InterDev // // Microsoft Confidential // Copyright 1994 - 1997 Microsoft Corporation. All Rights Reserved. // // WebArchy.cpp : Implementation of CIswsApp and DLL registration. //--------------------------------------------------------------------------- #include "stdafx.h" #include "ExeHierarchy.h" #include "..\resdll\gpcmd.h" #include "VsCoCreate.h" #include "context.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif BOOL g_bCommandLineDBG = FALSE; HRESULT CExeHierarchy::Initialize( LPCOLESTR pszFilename, LPCOLESTR pszArgs ) { wchar_t drive[_MAX_PATH]; // Should these be _MAX_DRIVE, _MAX_DIR and _MAX_FNAME? wchar_t path[_MAX_PATH]; wchar_t name[_MAX_PATH]; wchar_t ext[_MAX_EXT]; _wsplitpath( pszFilename, drive, path, name, ext ); m_bstrFullPath = pszFilename; m_bstrName = name; m_bstrName.Append(ext); m_pParentHierarchy = NULL; m_dwParentHierarchyItemID = VSITEMID_NIL; // To emulate VC6 behavior, we want to see if this .EXE has an BSC file associated with it. If it does we want it loaded. wchar_t bscpath[_MAX_PATH]; _wmakepath(bscpath, drive, path, name, L"bsc"); if (GetFileAttributesW(bscpath) != -1) { //Try to open the .bsc CComPtr<IVsUIShellOpenDocument> spOpenDoc; BOOL bIsOpen = FALSE; if (SUCCEEDED(ExternalQueryService(SID_SVsUIShellOpenDocument, IID_IVsUIShellOpenDocument,reinterpret_cast<void **>(&spOpenDoc))) && SUCCEEDED(spOpenDoc->IsDocumentOpen(NULL, NULL, bscpath, GUID_NULL, 0, NULL, NULL, NULL, &bIsOpen))) { // We are not checking the return value because we are not going to do anything with it anyways. if (!bIsOpen) spOpenDoc->OpenDocumentViaProject(bscpath, LOGVIEWID_Primary, NULL, NULL, NULL, NULL); } } return CExeConfig::CreateInstance(&m_pConfig, pszFilename, pszArgs, this); } // _Project STDMETHODIMP CExeHierarchy::get_Name(BSTR FAR* pbstrName) { wchar_t drive[_MAX_PATH]; wchar_t path[_MAX_PATH]; wchar_t name[_MAX_PATH]; wchar_t ext[_MAX_EXT]; _wsplitpath( m_bstrFullPath, drive, path, name, ext ); CComBSTR bstrName = name; *pbstrName = bstrName.Detach(); return S_OK; } STDMETHODIMP CExeHierarchy::get_FileName( BSTR *pbstrPath ) { return get_FullName(pbstrPath); } STDMETHODIMP CExeHierarchy::get_IsDirty(VARIANT_BOOL FAR* lpfReturn) { CHECK_POINTER_VALID(lpfReturn) *lpfReturn = VARIANT_FALSE; return S_OK; } STDMETHODIMP CExeHierarchy::get_DTE(DTE FAR* FAR* lppaReturn) { CHECK_POINTER_VALID(lppaReturn) return ExternalQueryService(SID_SDTE, IID__DTE, (void **)lppaReturn); } STDMETHODIMP CExeHierarchy::get_Kind(BSTR FAR* lpbstrFileName) { CHECK_POINTER_VALID(lpbstrFileName); CComBSTR bstr = L"{F1C25864-3097-11D2-A5C5-00C04F7968B4}"; // should be guid ? *lpbstrFileName = bstr.Detach(); return S_OK; } STDMETHODIMP CExeHierarchy::get_FullName(BSTR *pbstrPath) { CHECK_POINTER_VALID(pbstrPath); return m_bstrFullPath.CopyTo( pbstrPath ); } STDMETHODIMP CExeHierarchy::get_Saved(VARIANT_BOOL *lpfReturn) { CHECK_POINTER_VALID(lpfReturn) *lpfReturn = VARIANT_TRUE; return S_OK; } STDMETHODIMP CExeHierarchy::get_ConfigurationManager(ConfigurationManager **ppConfigurationManager) { CHECK_POINTER_VALID(ppConfigurationManager); HRESULT hr = S_OK; CComPtr<IVsExtensibility> pExtService; CComPtr<IVsCfgProvider> pCfgProvider; hr = ExternalQueryService(SID_SVsExtensibility, IID_IVsExtensibility, (LPVOID*)&pExtService); RETURN_ON_FAIL_OR_NULL(hr, pExtService); CComPtr<IVsHierarchy> spHier = VCQI_cast<IVsHierarchy>(this); return pExtService->GetConfigMgr(spHier, VSITEMID_ROOT, ppConfigurationManager); } STDMETHODIMP CExeHierarchy::get_ParentProjectItem(ProjectItem ** ppProjectItem) { CHECK_POINTER_VALID(ppProjectItem); *ppProjectItem = NULL; return NOERROR; } // IVsHierarchy STDMETHODIMP CExeHierarchy::SetSite(IServiceProvider *pSP) { m_pServiceProvider = pSP; return S_OK; } STDMETHODIMP CExeHierarchy::GetSite(IServiceProvider **ppSP) { CHECK_POINTER_NULL(ppSP); return m_pServiceProvider.CopyTo(ppSP); } STDMETHODIMP CExeHierarchy::QueryClose(BOOL *pfCanClose) { CHECK_POINTER_NULL(pfCanClose); *pfCanClose = TRUE; return S_OK; } STDMETHODIMP CExeHierarchy::GetGuidProperty(VSITEMID itemid, VSHPROPID propid, GUID *pguid) { CHECK_POINTER_NULL(pguid); return E_FAIL; } STDMETHODIMP CExeHierarchy::SetGuidProperty( /* [in] */ VSITEMID itemid, /* [in] */ VSHPROPID propid, /* [in] */ REFGUID guid) { return E_FAIL; } STDMETHODIMP CExeHierarchy::ParseCanonicalName( /* [in] */ LPCOLESTR pszName, /* [out] */ VSITEMID *pitemid) { CHECK_POINTER_NULL(pitemid); return E_NOTIMPL; // CExeHierarchy::ParseCanonicalName } STDMETHODIMP CExeHierarchy::GetCanonicalName( /* [in] */ VSITEMID itemid, /* [out] */ BSTR *ppszName) { CHECK_POINTER_NULL(ppszName); if(itemid != VSITEMID_ROOT) return E_FAIL; return m_bstrFullPath.CopyTo( ppszName ); }; STDMETHODIMP CExeHierarchy::GetProperty( VSITEMID itemid, /* [in] */ VSHPROPID propid, /* [out] */ VARIANT *pvar) { CHECK_POINTER_NULL(pvar); switch(propid) { case VSHPROPID_Caption: case VSHPROPID_Name: { V_VT(pvar) = VT_BSTR; return m_bstrName.CopyTo( &V_BSTR(pvar) ); } case VSHPROPID_Expandable: case VSHPROPID_ExpandByDefault: { V_VT(pvar) = VT_BOOL; V_BOOL(pvar) = VARIANT_FALSE; return S_OK; } case VSHPROPID_AltHierarchy: { V_VT(pvar) = VT_I4; V_UI4(pvar) = NULL; return E_FAIL; } case VSHPROPID_SortPriority: { V_VT(pvar) = VT_BOOL; V_UI4(pvar) = VARIANT_FALSE; return E_FAIL; } case VSHPROPID_ParentHierarchy: { pvar->vt = VT_UNKNOWN; if( !m_pParentHierarchy ) return E_FAIL; pvar->punkVal = m_pParentHierarchy; if (pvar->punkVal) pvar->punkVal->AddRef(); return S_OK; } case VSHPROPID_ParentHierarchyItemid: { pvar->vt = VT_INT_PTR; if( m_dwParentHierarchyItemID == VSITEMID_NIL ) { V_INT_PTR(pvar) = VSITEMID_ROOT; return S_OK; } V_INT_PTR(pvar) = m_dwParentHierarchyItemID; return S_OK; } case VSHPROPID_Parent: { V_VT(pvar) = VT_INT_PTR; V_INT_PTR(pvar) = VSITEMID_NIL; return S_OK; } case VSHPROPID_Root: { V_VT(pvar) = VT_INT_PTR; V_INT_PTR(pvar) = VSITEMID_ROOT; return S_OK; } case VSHPROPID_BrowseObject: case VSHPROPID_ExtObject: { VariantInit(pvar); if(SUCCEEDED(QueryInterface(IID_IDispatch, (void **)&V_DISPATCH(pvar)))) { V_VT(pvar) = VT_DISPATCH; return S_OK; } return E_FAIL; } case VSHPROPID_ItemDocCookie: case VSHPROPID_ImplantHierarchy: case VSHPROPID_FirstVisibleChild: case VSHPROPID_NextVisibleSibling: case VSHPROPID_IsHiddenItem: case VSHPROPID_IsNonMemberItem: case VSHPROPID_OpenFolderIconIndex: case VSHPROPID_SelContainer: case VSHPROPID_EditLabel: return E_NOTIMPL; // CExeHierarchy::GetProperty, several properties that don't need to be impl case VSHPROPID_UserContext: { V_VT(pvar) = VT_UNKNOWN; IVsUserContext *pUserCtx = NULL; CComPtr<IVsMonitorUserContext> pmuc; if (SUCCEEDED(ExternalQueryService(SID_SVsMonitorUserContext, IID_IVsMonitorUserContext, (void **)&pmuc))) { pmuc->CreateEmptyContext(&pUserCtx); if(pUserCtx) { pUserCtx->AddAttribute(VSUC_Usage_Filter, L"PRODUCT", L"VC"); pUserCtx->AddAttribute(VSUC_Usage_Filter, L"ITEM", L"EXE"); V_UNKNOWN(pvar) = pUserCtx; return S_OK; } } return E_FAIL; } case VSHPROPID_IconImgList: V_VT(pvar) = VT_INT_PTR; V_INT_PTR(pvar) = reinterpret_cast<INT_PTR>(GetBuildPkg()->m_hImageList); return S_OK; case VSHPROPID_IconIndex: V_VT(pvar) = VT_I4; V_I4(pvar) = BMP_PROJNODE; return S_OK; case VSHPROPID_StateIconIndex: V_VT(pvar) = VT_I4; V_I4(pvar) = STATEICON_NONE; return S_OK; case VSHPROPID_HandlesOwnReload: { V_VT(pvar) = VT_BOOL; V_BOOL(pvar) = VARIANT_TRUE; return S_OK; } default: break; } return E_UNEXPECTED; } STDMETHODIMP CExeHierarchy::SetProperty(VSITEMID itemid, VSHPROPID propid, /* [in] */ VARIANT var) { switch( propid ) { case VSHPROPID_ParentHierarchy: if( var.vt != VT_UNKNOWN ) RETURN_INVALID(); m_pParentHierarchy = var.punkVal; return S_OK; case VSHPROPID_ParentHierarchyItemid: if( var.vt != VT_I4 ) RETURN_INVALID(); m_dwParentHierarchyItemID = var.lVal; return S_OK; default: return S_OK; } } // IVsUIHierarchy STDMETHODIMP CExeHierarchy::QueryStatusCommand( VSITEMID itemid, const GUID * pguidCmdGroup, ULONG cCmds, OLECMD prgCmds[], OLECMDTEXT *pCmdText) { return S_OK; } HRESULT CExeHierarchy::ExecCommand( VSITEMID itemid, const GUID * pguidCmdGroup, DWORD nCmdID, DWORD nCmdexecopt, VARIANT *pvaIn, VARIANT *pvaOut) { if(*pguidCmdGroup == GUID_VsUIHierarchyWindowCmds) { HRESULT hr; switch(nCmdID) { case UIHWCMDID_RightClick: { CComPtr<IOleComponentUIManager> pOleComponentUImanager; hr = ExternalQueryService(SID_OleComponentUIManager, __uuidof(IOleComponentUIManager), (void**)&pOleComponentUImanager); if (SUCCEEDED(hr) && pOleComponentUImanager) { CComQIPtr<IOleInPlaceComponentUIManager> pComponentUImanager = pOleComponentUImanager; if (pComponentUImanager) pComponentUImanager->UpdateUI(0, FALSE, 0); POINTS pnts; ULONG ulPts = V_UI4(pvaIn); memcpy((void*)&pnts, &ulPts, sizeof(POINTS)); CComPtr<IOleCommandTarget> spTarget = VCQI_cast<IOleCommandTarget>(this); hr = pOleComponentUImanager->ShowContextMenu( 0, guidVCGrpId, IDMX_VC_EXEPROJECT, pnts, spTarget); } break; } // case UIHWCMDID_DoubleClick: // case UIHWCMDID_EnterKey: default: hr = OLECMDERR_E_NOTSUPPORTED; break; } return hr; } return OLECMDERR_E_UNKNOWNGROUP; } STDMETHODIMP CExeHierarchy::AdviseHierarchyEvents( /* [in] */ IVsHierarchyEvents *pEventSink, /* [out] */ VSCOOKIE *pdwCookie) { CHECK_POINTER_NULL(pdwCookie); *pdwCookie = 1; return S_OK; }; // IVsHierarchyDeleteHandler STDMETHODIMP CExeHierarchy::QueryDeleteItem( /* [in] */ VSDELETEITEMOPERATION dwDelItemOp, /* [in] */ VSITEMID itemid, /* [retval][out] */ BOOL __RPC_FAR *pfCanDelete) { CHECK_POINTER_NULL(pfCanDelete); if (dwDelItemOp != DELITEMOP_RemoveFromProject) // support remove only, not delete { *pfCanDelete = FALSE; return S_OK; } // yes, we can be deleted *pfCanDelete = TRUE; return S_OK; } STDMETHODIMP CExeHierarchy::DeleteItem( /* [in] */ VSDELETEITEMOPERATION dwDelItemOp, /* [in] */ VSITEMID itemid) { if (dwDelItemOp != DELITEMOP_RemoveFromProject) // support remove only, not delete return E_UNEXPECTED; // cause the solution to shut down the project CComPtr<IVsSolution> pSolution; HRESULT hr = GetBuildPkg()->GetIVsSolution( &pSolution ); VSASSERT( SUCCEEDED( hr ), "QueryService for solution failed! Note that you can't do a QueryService for that in a secondary thread..." ); RETURN_ON_FAIL(hr); // remove project from solution CComPtr<IVsHierarchy> spHier = VCQI_cast<IVsHierarchy>(this); return pSolution->CloseSolutionElement( SLNSAVEOPT_PromptSave, spHier, 0 ); } // IOleCommandTarget STDMETHODIMP CExeHierarchy::QueryStatus(const GUID *pguidCmdGroup, ULONG cCmds, OLECMD prgCmds[], OLECMDTEXT *pCmdText) { return OLECMDERR_E_UNKNOWNGROUP; } STDMETHODIMP CExeHierarchy::Exec(const GUID *pguidCmdGroup, DWORD nCmdID, DWORD nCmdexecopt, VARIANT *pvaIn, VARIANT *pvaOut) { return OLECMDERR_E_UNKNOWNGROUP; } // IVsCfgProvider STDMETHODIMP CExeHierarchy::GetCfgs(ULONG celt, IVsCfg *rgpcfg[], ULONG *pcActual, VSCFGFLAGS *prgfFlags) { CHECK_ZOMBIE(m_pConfig, IDS_ERR_CFG_ZOMBIE); if (celt == 0) { CHECK_POINTER_NULL(pcActual); *pcActual = 1; return S_OK; } CHECK_POINTER_NULL(rgpcfg); if (pcActual) *pcActual = 1; return m_pConfig->QueryInterface(IID_IVsCfg, (void**)rgpcfg); } // IVsProjectCfgProvider STDMETHODIMP CExeHierarchy::get_UsesIndependentConfigurations(BOOL *pfUsesIndependentConfigurations ) { CHECK_POINTER_NULL(pfUsesIndependentConfigurations); *pfUsesIndependentConfigurations = FALSE; return S_FALSE; }; HRESULT CExeConfig::CreateInstance(IVsDebuggableProjectCfg ** ppCfg, LPCOLESTR pszFilename, LPCOLESTR pszArgs, CExeHierarchy* pArchy) { CComObject<CExeConfig> *pCfg = NULL; HRESULT hr = CComObject<CExeConfig>::CreateInstance(&pCfg); if (SUCCEEDED(hr)) { pCfg->Initialize( pszFilename, pszArgs, pArchy ); hr = pCfg->QueryInterface(__uuidof(IVsDebuggableProjectCfg), (void**)ppCfg ); } return hr; } HRESULT CExeConfig::Initialize( LPCOLESTR pszFilename, LPCOLESTR pszArgs, CExeHierarchy* pArchy ) { CComPtr<VCDebugSettings> pDebug; HRESULT hr = VsLoaderCoCreateInstance<VCDebugSettings>(CLSID__VCDebugSettings, &pDebug); // HRESULT hr = pDebug.CoCreateInstance(CLSID_VCDebugSettings); if(SUCCEEDED(hr) && pDebug) { m_pDbgSettings = pDebug; wchar_t drive[_MAX_PATH]; wchar_t path[_MAX_PATH]; wchar_t name[_MAX_PATH]; wchar_t ext[_MAX_EXT]; _wsplitpath( pszFilename, drive, path, name, ext ); CComBSTR bstrFullPath = pszFilename; CComBSTR bstrName = name; bstrName.Append(ext); CStringW strDir; if( g_bCommandLineDBG == TRUE ) { GetCurrentDirectoryW(MAX_PATH, strDir.GetBuffer(MAX_PATH)); strDir.ReleaseBuffer(); g_bCommandLineDBG = FALSE; } else { strDir = drive; strDir += path; } CComBSTR bstrDir = strDir; CComBSTR bstrArgs = pszArgs; pDebug->put_Command(bstrFullPath); pDebug->put_WorkingDirectory(bstrDir); pDebug->put_CommandArguments(bstrArgs); m_pArchy = pArchy; } return hr; } // IVsCfg STDMETHODIMP CExeConfig::get_DisplayName(BSTR *pbstrDisplayName) { CHECK_POINTER_NULL(pbstrDisplayName); CComBSTR bstrCfg = L"Debug"; return bstrCfg.CopyTo(pbstrDisplayName); } STDMETHODIMP CExeConfig::get_IsDebugOnly(BOOL *pfIsDebugOnly ) { CHECK_POINTER_NULL(pfIsDebugOnly); *pfIsDebugOnly = TRUE; return S_OK; }; STDMETHODIMP CExeConfig::get_IsReleaseOnly(BOOL *pfIsRetailOnly) { CHECK_POINTER_NULL(pfIsRetailOnly); *pfIsRetailOnly = FALSE; return S_FALSE; }; // IVsProjectCfg STDMETHODIMP CExeConfig::get_ProjectCfgProvider(/* [out] */ IVsProjectCfgProvider **ppIVsProjectCfgProvider) { CHECK_POINTER_NULL(ppIVsProjectCfgProvider); *ppIVsProjectCfgProvider = NULL; CHECK_POINTER_NULL(m_pArchy); return m_pArchy->QueryInterface(IID_IVsProjectCfgProvider, (void**)ppIVsProjectCfgProvider ); } STDMETHODIMP CExeConfig::get_CanonicalName(/* [out] */ BSTR *pbstrCanonicalName) { CHECK_POINTER_NULL(pbstrCanonicalName); CComBSTR bstrCfg = L"Debug"; return bstrCfg.CopyTo(pbstrCanonicalName); } STDMETHODIMP CExeConfig::get_IsRetailOnly(BOOL *pfIsRetailOnly) { CHECK_POINTER_NULL(pfIsRetailOnly); *pfIsRetailOnly = FALSE; return S_FALSE; }; STDMETHODIMP CExeConfig::get_IsPackaged(BOOL *pfIsPackaged) { CHECK_POINTER_NULL(pfIsPackaged); *pfIsPackaged = FALSE; return S_FALSE; }; STDMETHODIMP CExeConfig::get_IsSpecifyingOutputSupported(BOOL *pfIsSpecifyingOutputSupported) { CHECK_POINTER_NULL(pfIsSpecifyingOutputSupported); *pfIsSpecifyingOutputSupported = FALSE; return S_FALSE; }; STDMETHODIMP CExeConfig::get_TargetCodePage( /* [out] */ UINT *puiTargetCodePage) { CHECK_POINTER_NULL(puiTargetCodePage); *puiTargetCodePage = 1200; return S_OK; } // IVsDebuggableProjectCfg STDMETHODIMP CExeConfig::DebugLaunch(/* [in] */ VSDBGLAUNCHFLAGS grfLaunch) { CComPtr<IVsDebugger> pVsDebugger; HRESULT hr = ExternalQueryService(IID_IVsDebugger, IID_IVsDebugger, (void **)&pVsDebugger); if (SUCCEEDED(hr) && pVsDebugger) { VSASSERT(hr==S_OK, "Must have gotten some form of warning/success!"); VsDebugTargetInfo dbgi[2]; ZeroMemory( dbgi, 2 * sizeof(VsDebugTargetInfo) ); DWORD dwNumTargets = 2; CHECK_ZOMBIE(m_pDbgSettings, IDS_ERR_CFG_ZOMBIE); hr = m_pDbgSettings->CanGetDebugTargetInfo(NULL); if (hr != S_OK) { CComQIPtr<VCDebugSettings> pDbgSettingsPublic = m_pDbgSettings; hr = GetBuildPkg()->GetDebugCommandLines(pDbgSettingsPublic, NULL); } if (hr == S_OK) hr = m_pDbgSettings->GetDebugTargetInfo( grfLaunch, dbgi, &dwNumTargets ); if (hr==S_OK) { hr = pVsDebugger->LaunchDebugTargets(dwNumTargets, dbgi); // free up the structures for (DWORD i = 0; i < dwNumTargets; i++) { SysFreeString(dbgi[i].bstrRemoteMachine); SysFreeString(dbgi[i].bstrMdmRegisteredName); SysFreeString(dbgi[i].bstrExe); SysFreeString(dbgi[i].bstrArg); SysFreeString(dbgi[i].bstrCurDir); SysFreeString(dbgi[i].bstrEnv); CoTaskMemFree(dbgi[i].pClsidList); } } if (FAILED(hr)) { // do something reasonable here. } } return hr; } STDMETHODIMP CExeConfig::QueryDebugLaunch(/* [in] */ VSDBGLAUNCHFLAGS grfLaunch, /* [out] */ BOOL *pfCanLaunch) { CHECK_POINTER_NULL(pfCanLaunch); *pfCanLaunch = TRUE; return S_OK; } // ISpecifyPropertyPages STDMETHODIMP CExeConfig::GetPages(/* [out] */ CAUUID *pPages) { CHECK_POINTER_NULL(pPages); // number of tool pages plus number of 'extra' pages pPages->pElems = (GUID*) CoTaskMemAlloc(sizeof(CLSID)); RETURN_ON_NULL2(pPages->pElems, E_OUTOFMEMORY); pPages->pElems[0] = __uuidof(DebugSettingsPage); pPages->cElems = 1; return S_OK; } // IVcCfg STDMETHODIMP CExeConfig::get_Object( IDispatch **ppConfig) { CHECK_POINTER_NULL(ppConfig); return m_pDbgSettings->QueryInterface(IID_IDispatch, (void **) ppConfig); } // STDMETHODIMP CExeConfig::ReadUserOptions(IStream *pStream, LPCOLESTR pszKey) { CHECK_READ_POINTER_NULL(pStream); CComBSTR bstrName; HRESULT hr; //Read in the settings header hr = bstrName.ReadFromStream(pStream); RETURN_ON_FAIL(hr); //Check to see if this is the debug settings if (bstrName == L"DebugSettings") { //Load settings CHECK_ZOMBIE(m_pDbgSettings, IDS_ERR_CFG_ZOMBIE); hr = m_pDbgSettings->ReadFromStream(pStream); RETURN_ON_FAIL(hr); } return hr; } STDMETHODIMP CExeConfig::WriteUserOptions(IStream *pStream, LPCOLESTR pszKey) { CHECK_READ_POINTER_NULL(pStream); CHECK_ZOMBIE(m_pDbgSettings, IDS_ERR_CFG_ZOMBIE); //Write out the debug settings header CComBSTR bstrName = L"DebugSettings"; HRESULT hr; hr = bstrName.WriteToStream(pStream); RETURN_ON_FAIL(hr); //Save to stream hr = m_pDbgSettings->WriteToStream(pStream); RETURN_ON_FAIL(hr); return hr; } // IPersist STDMETHODIMP CExeHierarchy::GetClassID( CLSID *pClassID) { CHECK_POINTER_NULL(pClassID); *pClassID = IID_IExeHierarchy; return S_OK; } // IPersistFileFormat STDMETHODIMP CExeHierarchy::IsDirty(BOOL *pfIsDirty) { CHECK_POINTER_NULL(pfIsDirty); *pfIsDirty = FALSE; return S_FALSE; }; STDMETHODIMP CExeHierarchy::ReadUserOptions(IStream *pStream, LPCOLESTR pszKey) { CHECK_READ_POINTER_NULL(pStream); CComQIPtr<IVsPersistSolutionOpts> pOpts = m_pConfig; CHECK_ZOMBIE(pOpts, IDS_ERR_CFG_ZOMBIE); return pOpts->ReadUserOptions(pStream, pszKey); } STDMETHODIMP CExeHierarchy::WriteUserOptions(IStream *pStream, LPCOLESTR pszKey) { CHECK_READ_POINTER_NULL(pStream); CComQIPtr<IVsPersistSolutionOpts> pOpts = m_pConfig; CHECK_ZOMBIE(pOpts, IDS_ERR_CFG_ZOMBIE); return pOpts->WriteUserOptions(pStream, pszKey); } STDMETHODIMP CExeHierarchy::GetCurFile( /* [out] */ LPOLESTR __RPC_FAR *ppszFilename, /* [out] */ DWORD __RPC_FAR *pnFormatIndex) { CHECK_POINTER_NULL(ppszFilename); DWORD dwLen = (DWORD)(ocslen(m_bstrFullPath) + sizeof(OLECHAR)); *ppszFilename = (LPOLESTR)::CoTaskMemAlloc(dwLen * sizeof(OLECHAR)); if (NULL == *ppszFilename) return E_OUTOFMEMORY; ocscpy(*ppszFilename, m_bstrFullPath); return S_OK; }; // IVsPerPropertyBrowsing STDMETHODIMP CExeHierarchy::HideProperty(DISPID dispid, BOOL *pfHide) { *pfHide = FALSE; switch( dispid ) { case DISPID_VALUE: case 209: *pfHide = FALSE; break; default: *pfHide = TRUE; break; } return S_OK; } // IVsPerPropertyBrowsing STDMETHODIMP CExeHierarchy::IsPropertyReadOnly( DISPID dispid, BOOL *fReadOnly) { *fReadOnly = TRUE; return S_OK; } STDMETHODIMP CExeHierarchy::GetLocalizedPropertyInfo(DISPID dispid, LCID localeID, BSTR *pbstrName, BSTR *pbstrDesc) { CHECK_POINTER_NULL(pbstrName); *pbstrName = NULL; CHECK_POINTER_NULL(pbstrDesc); *pbstrDesc = NULL; CComBSTR bstrName; CComBSTR bstrDesc; switch( dispid ) { case DISPID_VALUE: { if (!bstrName.LoadString(IDS_EXE_PROJ_NAME_LBL)) bstrName = ( L"Name" ); *pbstrName = bstrName.Detach(); if (!bstrDesc.LoadString(IDS_EXE_PROJ_NAME_DESC)) bstrDesc = ( L"The Name of the exe to debug" ); break; } case 209: { if (!bstrName.LoadString(IDS_EXE_PROJ_PATH_LBL)) bstrName = ( L"Full Path" ); if (!bstrDesc.LoadString(IDS_EXE_PROJ_PATH_DESC)) bstrDesc = ( L"The Full Path to the exe to debug" ); break; } default: break; } if (bstrName) *pbstrName = bstrName.Detach(); if (bstrDesc) *pbstrDesc = bstrDesc.Detach(); return S_OK; } STDMETHODIMP CExeHierarchy::GetClassName(BSTR* pbstrClassName) { CHECK_POINTER_NULL(pbstrClassName); CComBSTR bstrClassName; bstrClassName.LoadString(IDS_PROJ_PROPERTIES); *pbstrClassName = bstrClassName.Detach(); if (*pbstrClassName) return S_OK; else return E_OUTOFMEMORY; } // IPersist STDMETHODIMP CCrashDumpHierarchy::GetClassID( CLSID *pClassID) { CHECK_POINTER_NULL(pClassID); *pClassID = IID_ICrashDumpHierarchy; return S_OK; }
20de72c0deb94561e5fbdd091a71efcf5ed8bfb8
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_15346.cpp
858641b33a839f28e181d01c0e064c8cb0b57ec8
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
309
cpp
Kitware_CMake_repos_basic_block_block_15346.cpp
{ if (value == NULL || !(value[0] >= '0' && value[0] <= '9') || value[1] != '\0') { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Illegal value `%s'", value); return (ARCHIVE_FAILED); } zip->opt_compression_level = value[0] - '0'; return (ARCHIVE_OK); }
17697beece77d6f741914510174272cdd7773487
f6f323c895e18433159627bd61efccf63a5fe12f
/vertex_cover_two.cpp
7f6950a2d6fe8651194fbfd956a93c10e58d5c7c
[]
no_license
Adarsh-kumar/Competitive_coding_practice
200d869d072b97daa5e900b0c35b91e1da128247
88bb368b107b35eb5e9c40a683a3e41fbe16b469
refs/heads/master
2020-03-30T14:03:30.177798
2018-10-02T18:09:40
2018-10-02T18:09:40
151,299,363
0
0
null
null
null
null
UTF-8
C++
false
false
784
cpp
vertex_cover_two.cpp
#include<bits/stdc++.h> using namespace std; vector<int> adj[100005]; int count1=0; int count2=0; int col[100005]; bool check_bipartite(int s) { queue<int> q; q.push(s); col[s]=1; count1++; while(!q.empty()) { int u=q.front(); q.pop(); for(int v:adj[u]) { if(col[v]==-1) { col[v]=1-col[u]; q.push(v); if(col[v]==1) count1++; else count2++; } else if(col[v]==col[u]) return 0; } } return 1; } int main() { int n,m; cin>>n>>m; memset(col,-1,sizeof(col)); for(int i=0;i<m;i++) { int u,v; cin>>u>>v; adj[u].push_back(v); adj[v].push_back(u); } if(!check_bipartite(1)) cout<<-1<<endl; else { cout<<count1<<endl; for(int i=1;i<=n;i++) { if(col[i]==1) cout<<i<<" "; } cout<<endl; cout<<count2<<endl; for(int i=1;i<=n;i++) { if(col[i]==0) cout<<i<<" "; } } return 0; }
1ab41f42a370ed6cb6b0602219de3d38bb0c453c
cff962dad386e37f98d59e586515a7bd4b3571f9
/dist/alure/src/context.h
58aed01dd9730d62cf31d54b59e8115a1c4cef04
[ "MIT", "Zlib" ]
permissive
snada/openal-alure-sandbox
d3cdf8a408f8f9bdda519887258fe80d42d19ced
de0870068e013bec1306af21927e39b9578af420
refs/heads/master
2021-08-24T01:56:01.281073
2017-12-07T14:58:44
2017-12-07T14:58:44
111,256,887
4
0
null
null
null
null
UTF-8
C++
false
false
10,326
h
context.h
#ifndef CONTEXT_H #define CONTEXT_H #include <condition_variable> #include <unordered_map> #include <stdexcept> #include <thread> #include <mutex> #include <stack> #include <queue> #include <set> #include "main.h" #include "device.h" #include "source.h" #define F_PI (3.14159265358979323846f) namespace alure { enum class AL { EXT_EFX, EXT_FLOAT32, EXT_MCFORMATS, EXT_BFORMAT, EXT_MULAW, EXT_MULAW_MCFORMATS, EXT_MULAW_BFORMAT, SOFT_loop_points, SOFT_source_latency, SOFT_source_resampler, SOFT_source_spatialize, EXT_disconnect, EXT_SOURCE_RADIUS, EXT_STEREO_ANGLES, EXTENSION_MAX }; // Batches OpenAL updates while the object is alive, if batching isn't already // in progress. class Batcher { ALCcontext *mContext; public: Batcher(ALCcontext *context) : mContext(context) { } Batcher(Batcher&& rhs) : mContext(rhs.mContext) { rhs.mContext = nullptr; } Batcher(const Batcher&) = delete; ~Batcher() { if(mContext) alcProcessContext(mContext); } Batcher& operator=(Batcher&&) = delete; Batcher& operator=(const Batcher&) = delete; }; class ListenerImpl { ContextImpl *const mContext; public: ListenerImpl(ContextImpl *ctx) : mContext(ctx) { } void setGain(ALfloat gain); void set3DParameters(const Vector3 &position, const Vector3 &velocity, const std::pair<Vector3,Vector3> &orientation); void setPosition(const Vector3 &position); void setPosition(const ALfloat *pos); void setVelocity(const Vector3 &velocity); void setVelocity(const ALfloat *vel); void setOrientation(const std::pair<Vector3,Vector3> &orientation); void setOrientation(const ALfloat *at, const ALfloat *up); void setOrientation(const ALfloat *ori); void setMetersPerUnit(ALfloat m_u); }; using DecoderOrExceptT = std::variant<SharedPtr<Decoder>,std::exception_ptr>; using BufferOrExceptT = std::variant<Buffer,std::exception_ptr>; class ContextImpl { static ContextImpl *sCurrentCtx; static thread_local ContextImpl *sThreadCurrentCtx; public: static void MakeCurrent(ContextImpl *context); static ContextImpl *GetCurrent() { auto thrd_ctx = sThreadCurrentCtx; return thrd_ctx ? thrd_ctx : sCurrentCtx; } static void MakeThreadCurrent(ContextImpl *context); static ContextImpl *GetThreadCurrent() { return sThreadCurrentCtx; } static std::atomic<uint64_t> sContextSetCount; mutable uint64_t mContextSetCounter{std::numeric_limits<uint64_t>::max()}; private: ListenerImpl mListener; ALCcontext *mContext{nullptr}; Vector<ALuint> mSourceIds; struct PendingBuffer { BufferImpl *mBuffer; SharedFuture<Buffer> mFuture; }; struct PendingSource { SourceImpl *mSource; SharedFuture<Buffer> mFuture; }; DeviceImpl &mDevice; Vector<PendingBuffer> mFutureBuffers; Vector<UniquePtr<BufferImpl>> mBuffers; Vector<UniquePtr<SourceGroupImpl>> mSourceGroups; Vector<UniquePtr<AuxiliaryEffectSlotImpl>> mEffectSlots; Vector<UniquePtr<EffectImpl>> mEffects; std::deque<SourceImpl> mAllSources; Vector<SourceImpl*> mFreeSources; Vector<PendingSource> mPendingSources; Vector<SourceImpl*> mFadingSources; Vector<SourceBufferUpdateEntry> mPlaySources; Vector<SourceStreamUpdateEntry> mStreamSources; Vector<SourceImpl*> mStreamingSources; std::mutex mSourceStreamMutex; std::atomic<std::chrono::milliseconds> mWakeInterval{std::chrono::milliseconds::zero()}; std::mutex mWakeMutex; std::condition_variable mWakeThread; SharedPtr<MessageHandler> mMessage; struct PendingPromise { BufferImpl *mBuffer; SharedPtr<Decoder> mDecoder; ALenum mFormat; ALuint mFrames; Promise<Buffer> mPromise; std::atomic<PendingPromise*> mNext; }; std::atomic<PendingPromise*> mPendingCurrent{nullptr}; PendingPromise *mPendingTail{nullptr}; PendingPromise *mPendingHead{nullptr}; std::atomic<bool> mQuitThread{false}; std::thread mThread; void backgroundProc(); size_t mRefs{0}; Vector<String> mResamplers; Bitfield<static_cast<size_t>(AL::EXTENSION_MAX)> mHasExt; std::once_flag mSetExts; void setupExts(); DecoderOrExceptT findDecoder(StringView name); BufferOrExceptT doCreateBuffer(StringView name, Vector<UniquePtr<BufferImpl>>::iterator iter, SharedPtr<Decoder> decoder); BufferOrExceptT doCreateBufferAsync(StringView name, Vector<UniquePtr<BufferImpl>>::iterator iter, SharedPtr<Decoder> decoder, Promise<Buffer> promise); bool mIsConnected : 1; bool mIsBatching : 1; public: ContextImpl(DeviceImpl &device, ArrayView<AttributePair> attrs); ~ContextImpl(); ALCcontext *getALCcontext() const { return mContext; } long addRef() { return ++mRefs; } long decRef() { return --mRefs; } bool hasExtension(AL ext) const { return mHasExt[static_cast<size_t>(ext)]; } LPALGETSTRINGISOFT alGetStringiSOFT{nullptr}; LPALGETSOURCEI64VSOFT alGetSourcei64vSOFT{nullptr}; LPALGETSOURCEDVSOFT alGetSourcedvSOFT{nullptr}; LPALGENEFFECTS alGenEffects{nullptr}; LPALDELETEEFFECTS alDeleteEffects{nullptr}; LPALISEFFECT alIsEffect{nullptr}; LPALEFFECTI alEffecti{nullptr}; LPALEFFECTIV alEffectiv{nullptr}; LPALEFFECTF alEffectf{nullptr}; LPALEFFECTFV alEffectfv{nullptr}; LPALGETEFFECTI alGetEffecti{nullptr}; LPALGETEFFECTIV alGetEffectiv{nullptr}; LPALGETEFFECTF alGetEffectf{nullptr}; LPALGETEFFECTFV alGetEffectfv{nullptr}; LPALGENFILTERS alGenFilters{nullptr}; LPALDELETEFILTERS alDeleteFilters{nullptr}; LPALISFILTER alIsFilter{nullptr}; LPALFILTERI alFilteri{nullptr}; LPALFILTERIV alFilteriv{nullptr}; LPALFILTERF alFilterf{nullptr}; LPALFILTERFV alFilterfv{nullptr}; LPALGETFILTERI alGetFilteri{nullptr}; LPALGETFILTERIV alGetFilteriv{nullptr}; LPALGETFILTERF alGetFilterf{nullptr}; LPALGETFILTERFV alGetFilterfv{nullptr}; LPALGENAUXILIARYEFFECTSLOTS alGenAuxiliaryEffectSlots{nullptr}; LPALDELETEAUXILIARYEFFECTSLOTS alDeleteAuxiliaryEffectSlots{nullptr}; LPALISAUXILIARYEFFECTSLOT alIsAuxiliaryEffectSlot{nullptr}; LPALAUXILIARYEFFECTSLOTI alAuxiliaryEffectSloti{nullptr}; LPALAUXILIARYEFFECTSLOTIV alAuxiliaryEffectSlotiv{nullptr}; LPALAUXILIARYEFFECTSLOTF alAuxiliaryEffectSlotf{nullptr}; LPALAUXILIARYEFFECTSLOTFV alAuxiliaryEffectSlotfv{nullptr}; LPALGETAUXILIARYEFFECTSLOTI alGetAuxiliaryEffectSloti{nullptr}; LPALGETAUXILIARYEFFECTSLOTIV alGetAuxiliaryEffectSlotiv{nullptr}; LPALGETAUXILIARYEFFECTSLOTF alGetAuxiliaryEffectSlotf{nullptr}; LPALGETAUXILIARYEFFECTSLOTFV alGetAuxiliaryEffectSlotfv{nullptr}; ALuint getSourceId(ALuint maxprio); void insertSourceId(ALuint id) { mSourceIds.push_back(id); } void addPendingSource(SourceImpl *source, SharedFuture<Buffer> future); void removePendingSource(SourceImpl *source); bool isPendingSource(const SourceImpl *source) const; void addFadingSource(SourceImpl *source); void removeFadingSource(SourceImpl *source); void addPlayingSource(SourceImpl *source, ALuint id); void addPlayingSource(SourceImpl *source); void removePlayingSource(SourceImpl *source); void addStream(SourceImpl *source); void removeStream(SourceImpl *source); void removeStreamNoLock(SourceImpl *source); void freeSource(SourceImpl *source) { mFreeSources.push_back(source); } void freeSourceGroup(SourceGroupImpl *group); void freeEffectSlot(AuxiliaryEffectSlotImpl *slot); void freeEffect(EffectImpl *effect); Batcher getBatcher() { if(mIsBatching) return Batcher(nullptr); alcSuspendContext(mContext); return Batcher(mContext); } std::unique_lock<std::mutex> getSourceStreamLock() { return std::unique_lock<std::mutex>(mSourceStreamMutex); } template<typename R, typename... Args> void send(R MessageHandler::* func, Args&&... args) { if(mMessage.get()) (mMessage.get()->*func)(std::forward<Args>(args)...); } Device getDevice() { return Device(&mDevice); } void destroy(); void startBatch(); void endBatch(); Listener getListener() { return Listener(&mListener); } SharedPtr<MessageHandler> setMessageHandler(SharedPtr<MessageHandler>&& handler); SharedPtr<MessageHandler> getMessageHandler() const { return mMessage; } void setAsyncWakeInterval(std::chrono::milliseconds interval); std::chrono::milliseconds getAsyncWakeInterval() const { return mWakeInterval.load(); } SharedPtr<Decoder> createDecoder(StringView name); bool isSupported(ChannelConfig channels, SampleType type) const; ArrayView<String> getAvailableResamplers(); ALsizei getDefaultResamplerIndex() const; Buffer getBuffer(StringView name); SharedFuture<Buffer> getBufferAsync(StringView name); void precacheBuffersAsync(ArrayView<StringView> names); Buffer createBufferFrom(StringView name, SharedPtr<Decoder>&& decoder); SharedFuture<Buffer> createBufferAsyncFrom(StringView name, SharedPtr<Decoder>&& decoder); Buffer findBuffer(StringView name); SharedFuture<Buffer> findBufferAsync(StringView name); void removeBuffer(StringView name); void removeBuffer(Buffer buffer) { removeBuffer(buffer.getName()); } Source createSource(); AuxiliaryEffectSlot createAuxiliaryEffectSlot(); Effect createEffect(); SourceGroup createSourceGroup(); void setDopplerFactor(ALfloat factor); void setSpeedOfSound(ALfloat speed); void setDistanceModel(DistanceModel model); void update(); }; inline void CheckContext(const ContextImpl &ctx) { auto count = ContextImpl::sContextSetCount.load(std::memory_order_acquire); if(UNLIKELY(count != ctx.mContextSetCounter)) { if(UNLIKELY(&ctx != ContextImpl::GetCurrent())) throw std::runtime_error("Called context is not current"); ctx.mContextSetCounter = count; } } inline void CheckContexts(const ContextImpl &ctx0, const ContextImpl &ctx1) { if(UNLIKELY(&ctx0 != &ctx1)) throw std::runtime_error("Mismatched object contexts"); } } // namespace alure #endif /* CONTEXT_H */
1108ab8b58f08fe230598f0f74ebf3f6d76a7852
b7373c9a097c409f8f9f60068cb1d47670c37be5
/src/RtbDict.cpp
7651c3c32da597b068bf782e8e228ceb8ab8cbe2
[]
no_license
SericWong/adtrident
6e2d71eade8ee0f928c623ff7e63ec0ad44220d0
e9101b528ba0d4f29ee8fa53949514154184f3e6
refs/heads/master
2021-01-12T19:59:55.750156
2016-01-03T16:07:18
2016-01-03T16:07:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,416
cpp
RtbDict.cpp
#include "RtbDict.h" #define REG_DICT(dictname, dict) \ do { \ if (xbuiltin::Manager::instance().register_dict(dictname, (dict)) < 0) { \ WRITE_LOG(UL_LOG_FATAL, "register dict[%s] failed.", dictname); \ return -1; \ } \ } while (0) #define REG_PLUGIN(dict, plugin) \ do { \ if ((dict)->register_plugin((plugin)) < 0) { \ WRITE_LOG(UL_LOG_FATAL, "register plugin failed."); \ return -1; \ } \ } while (0) namespace ad { namespace rtb { int RtbDict::register_plugin() { return 0; } int RtbDict::register_dict() { if (register_plugin() < 0) { return -1; } try { REG_DICT("phrase_business", &phrase_business_dict); REG_DICT("business_ad", &business_ad_dict); REG_DICT("stop_word", &stop_word_dict); REG_DICT("user_info", &user_info_dict); REG_DICT("plan_info", &plan_info_dict); REG_DICT("unit_info", &unit_info_dict); REG_DICT("idea_info", &idea_info_dict); REG_DICT("unit_idea", &unit_idea_dict); //REG_DICT("black_list_info", &black_list_info_dict); } catch (bsl::Exception& e) { WRITE_LOG(UL_LOG_FATAL, "failed to register dict. [%s]", e.what()); return -1; } catch (...) { WRITE_LOG(UL_LOG_FATAL, "Expection: failed to register dict."); return -1; } return 0; } } } /* vim: set ts=4 sw=4 sts=4 tw=100 et: */
8d2a393c64116aa15365c9c26216836eba2738e0
c76dc04ab30acb663990aeff842436f2d4d1fcb5
/media/blink/video_frame_compositor.h
02b6077f9605ff25029cfb08da5adefc8c3808e6
[ "BSD-3-Clause" ]
permissive
tongxingwy/chromium-1
1352c851a18a26645d69741ed6fc540fabcc862e
9e3ebd26fa69a2e2fdf5d5f53300bbf1e2f72b8c
refs/heads/master
2021-01-21T03:09:12.806702
2015-04-30T17:32:56
2015-04-30T17:33:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,255
h
video_frame_compositor.h
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MEDIA_BLINK_VIDEO_FRAME_COMPOSITOR_H_ #define MEDIA_BLINK_VIDEO_FRAME_COMPOSITOR_H_ #include "base/callback.h" #include "base/memory/ref_counted.h" #include "base/single_thread_task_runner.h" #include "base/synchronization/lock.h" #include "cc/layers/video_frame_provider.h" #include "media/base/media_export.h" #include "media/base/video_renderer_sink.h" #include "ui/gfx/geometry/size.h" namespace media { class VideoFrame; // VideoFrameCompositor acts as a bridge between the media and cc layers for // rendering video frames. I.e. a media::VideoRenderer will talk to this class // from the media side, while a cc::VideoFrameProvider::Client will talk to it // from the cc side. // // This class is responsible for requesting new frames from a video renderer in // response to requests from the VFP::Client. Since the VFP::Client may stop // issuing requests in response to visibility changes it is also responsible for // ensuring the "freshness" of the current frame for programmatic frame // requests; e.g., Canvas.drawImage() requests // // This class is also responsible for detecting frames dropped by the compositor // after rendering and signaling that information to a RenderCallback. It // detects frames not dropped by verifying each GetCurrentFrame() is followed // by a PutCurrentFrame() before the next UpdateCurrentFrame() call. // // VideoRenderSink::RenderCallback implementations must call Start() and Stop() // once new frames are expected or are no longer expected to be ready; this data // is relayed to the compositor to avoid extraneous callbacks. // // VideoFrameCompositor must live on the same thread as the compositor, though // it may be constructed on any thread. class MEDIA_EXPORT VideoFrameCompositor : public VideoRendererSink, NON_EXPORTED_BASE(public cc::VideoFrameProvider) { public: // |compositor_task_runner| is the task runner on which this class will live, // though it may be constructed on any thread. // // |natural_size_changed_cb| is run with the new natural size of the video // frame whenever a change in natural size is detected. It is not called the // first time UpdateCurrentFrame() is called. Run on the same thread as the // caller of UpdateCurrentFrame(). // // |opacity_changed_cb| is run when a change in opacity is detected. It *is* // called the first time UpdateCurrentFrame() is called. Run on the same // thread as the caller of UpdateCurrentFrame(). // // TODO(dalecurtis): Investigate the inconsistency between the callbacks with // respect to why we don't call |natural_size_changed_cb| on the first frame. // I suspect it was for historical reasons that no longer make sense. VideoFrameCompositor( const scoped_refptr<base::SingleThreadTaskRunner>& compositor_task_runner, const base::Callback<void(gfx::Size)>& natural_size_changed_cb, const base::Callback<void(bool)>& opacity_changed_cb); // Destruction must happen on the compositor thread; Stop() must have been // called before destruction starts. ~VideoFrameCompositor() override; // Returns |current_frame_| if it was refreshed recently; otherwise, if // |callback_| is available, requests a new frame and returns that one. // // This is required for programmatic frame requests where the compositor may // have stopped issuing UpdateCurrentFrame() callbacks in response to // visibility changes in the output layer. scoped_refptr<VideoFrame> GetCurrentFrameAndUpdateIfStale(); // cc::VideoFrameProvider implementation. These methods must be called on the // |compositor_task_runner_|. void SetVideoFrameProviderClient( cc::VideoFrameProvider::Client* client) override; bool UpdateCurrentFrame(base::TimeTicks deadline_min, base::TimeTicks deadline_max) override; scoped_refptr<VideoFrame> GetCurrentFrame() override; void PutCurrentFrame() override; // VideoRendererSink implementation. These methods must be called from the // same thread (typically the media thread). void Start(RenderCallback* callback) override; void Stop() override; void PaintFrameUsingOldRenderingPath( const scoped_refptr<VideoFrame>& frame) override; private: // Called on the compositor thread to start or stop rendering if rendering was // previously started or stopped before we had a |callback_|. void OnRendererStateUpdate(); scoped_refptr<base::SingleThreadTaskRunner> compositor_task_runner_; // These callbacks are executed on the compositor thread. base::Callback<void(gfx::Size)> natural_size_changed_cb_; base::Callback<void(bool)> opacity_changed_cb_; // These values are only set and read on the compositor thread. cc::VideoFrameProvider::Client* client_; scoped_refptr<VideoFrame> current_frame_; // These values are updated and read from the media and compositor threads. base::Lock lock_; bool rendering_; VideoRendererSink::RenderCallback* callback_; DISALLOW_COPY_AND_ASSIGN(VideoFrameCompositor); }; } // namespace media #endif // MEDIA_BLINK_VIDEO_FRAME_COMPOSITOR_H_
b256f8ec0e32b740f97a81e3fb9d73460acc6e5b
6ca74d0492333aa61d02056e476b0376249c734e
/Minimum Platforms/min_platforms.cpp
e2aae11e1696a94eb223529334992acbc2f8dc64
[]
no_license
Jitendra2027/Geeksforgeeks-11-weeks-DSA-With-Cpp-
829be56ea1a4a7c14520c9a9153b9b2df60ea077
62ef0fc658d56ab0be272788406f3786a1ffcb1a
refs/heads/main
2023-07-27T13:12:24.833784
2021-09-07T13:11:14
2021-09-07T13:11:14
388,146,051
0
0
null
null
null
null
UTF-8
C++
false
false
718
cpp
min_platforms.cpp
#include<bits/stdc++.h> using namespace std; int min_platforms(int arr[],int dep[],int n) { sort(arr,arr+n); sort(dep,dep+n); int i=1,j=0; int platform=1,result=1; while(i<n && j<n) { if(arr[i]<=dep[j]) { platform++; i++; } else { platform--; j++; } if(platform>result) result=platform; } return result; } int main() { int arr[]={ 900, 940, 950, 1100, 1500, 1800}; int dep[]={ 910, 1200, 1120, 1130, 1900, 2000}; int n=sizeof(arr)/sizeof(arr[0]); int result=min_platforms(arr,dep,n); cout<<"Minimum platforms required are: "<<result; return 0; }
b29609438aed7013946be78b07deba07a924bef0
3be9bb691024e276bffa63d05653e512d666cfa9
/Receiver/widget.cpp
497b41cd3be99691a4159637786a5a7ebe080c7b
[]
no_license
ruanshihai/S3C6410-VMS
83ba7356847fb1f921b02ef79c561a8ac774eea2
c825f18b64f63e8a2432b5f96af251f462c3da9e
refs/heads/master
2020-06-05T09:40:17.543941
2015-06-18T05:41:42
2015-06-18T05:41:42
37,639,528
0
0
null
null
null
null
UTF-8
C++
false
false
9,407
cpp
widget.cpp
#include <QMessageBox> #include <stdio.h> #include <unistd.h> #include <sys/ioctl.h> #include <fcntl.h> #include <linux/fs.h> #include <errno.h> #include <fcntl.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <linux/fb.h> #include <linux/kd.h> #include <time.h> #include <jpeglib.h> #include "widget.h" #include "ui_widget.h" #include "s3c-jpeg/JPGApi.h" #include "Common/performance.h" #include "rgb5652yuv422.h" #define LOG_FILE_NAME "/tmp/jpeghw.log" static int _debug = 1; static void _log2file(const char* fmt, va_list vl) { FILE* file_out; file_out = fopen(LOG_FILE_NAME,"a+"); if (file_out == NULL) { return; } vfprintf(file_out, fmt, vl); fclose(file_out); } static void log2file(const char *fmt, ...) { if (_debug) { va_list vl; va_start(vl, fmt); _log2file(fmt, vl); va_end(vl); } } ////////////////////////////////////////////////// struct _FBInfo; typedef struct _FBInfo FBInfo; struct _FBInfo { int fd; unsigned char *bits; struct fb_fix_screeninfo fi; struct fb_var_screeninfo vi; }; #define fb_width(fb) ((fb)->vi.xres) #define fb_height(fb) ((fb)->vi.yres) #define fb_bpp(fb) ((fb)->vi.bits_per_pixel>>3) #define fb_size(fb) ((fb)->vi.xres * (fb)->vi.yres * fb_bpp(fb)) #define FB_FILENAME "/dev/fb1" #define PICTURN_PATH "/tmp/" static int fb_open(FBInfo* fb, const char* fbfilename) { fb->fd = open(fbfilename, O_RDWR); if (fb->fd < 0) { fprintf(stderr, "can't open %s\n", fbfilename); return -1; } if (ioctl(fb->fd, FBIOGET_FSCREENINFO, &fb->fi) < 0) goto fail; if (ioctl(fb->fd, FBIOGET_VSCREENINFO, &fb->vi) < 0) goto fail; fb->bits = (unsigned char*) mmap(0, fb_size(fb), PROT_READ | PROT_WRITE, MAP_SHARED, fb->fd, 0); if (fb->bits == MAP_FAILED) goto fail; return 0; fail: printf("%s is not a framebuffer.\n", fbfilename); close(fb->fd); return -1; } static void fb_close(FBInfo* fb) { munmap(fb->bits, fb_size(fb)); close(fb->fd); return; } void makeExifParam(ExifFileInfo *exifFileInfo) { strcpy(exifFileInfo->Make,"Samsung SYS.LSI make");; strcpy(exifFileInfo->Model,"Samsung 2007 model"); strcpy(exifFileInfo->Version,"version 1.0.2.0"); strcpy(exifFileInfo->DateTime,"2007:05:16 12:32:54"); strcpy(exifFileInfo->CopyRight,"Samsung Electronics@2007:All rights reserved"); exifFileInfo->Height = 320; exifFileInfo->Width = 240; exifFileInfo->Orientation = 1; // top-left exifFileInfo->ColorSpace = 1; exifFileInfo->Process = 1; exifFileInfo->Flash = 0; exifFileInfo->FocalLengthNum = 1; exifFileInfo->FocalLengthDen = 4; exifFileInfo->ExposureTimeNum = 1; exifFileInfo->ExposureTimeDen = 20; exifFileInfo->FNumberNum = 1; exifFileInfo->FNumberDen = 35; exifFileInfo->ApertureFNumber = 1; exifFileInfo->SubjectDistanceNum = -20; exifFileInfo->SubjectDistanceDen = -7; exifFileInfo->CCDWidth = 1; exifFileInfo->ExposureBiasNum = -16; exifFileInfo->ExposureBiasDen = -2; exifFileInfo->WhiteBalance = 6; exifFileInfo->MeteringMode = 3; exifFileInfo->ExposureProgram = 1; exifFileInfo->ISOSpeedRatings[0] = 1; exifFileInfo->ISOSpeedRatings[1] = 2; exifFileInfo->FocalPlaneXResolutionNum = 65; exifFileInfo->FocalPlaneXResolutionDen = 66; exifFileInfo->FocalPlaneYResolutionNum = 70; exifFileInfo->FocalPlaneYResolutionDen = 71; exifFileInfo->FocalPlaneResolutionUnit = 3; exifFileInfo->XResolutionNum = 48; exifFileInfo->XResolutionDen = 20; exifFileInfo->YResolutionNum = 48; exifFileInfo->YResolutionDen = 20; exifFileInfo->RUnit = 2; exifFileInfo->BrightnessNum = -7; exifFileInfo->BrightnessDen = 1; strcpy(exifFileInfo->UserComments,"Usercomments"); } static int rgb5652jpeg(void *rgb565Buffer , int width , int height , char* outFilename) { void *InBuf; void *OutBuf; long jpegSize = 0; FILE* fp; int ret = 0; JPEG_ERRORTYPE result; ExifFileInfo ExifInfo; long inBufferSize; log2file("rgb5652jpeg %d,%d\n", width, height); memset(&ExifInfo, 0x00, sizeof(ExifFileInfo)); makeExifParam(&ExifInfo); ExifInfo.Width = width; ExifInfo.Height = height; int jpegEncodeHandle = SsbSipJPEGEncodeInit(); if (jpegEncodeHandle < 0) { log2file("SsbSipJPEGDecodeInit failed!\n"); return -1; } if (SsbSipJPEGSetConfig(JPEG_SET_SAMPING_MODE, JPG_422) != JPEG_OK) { log2file("SsbSipJPEGSetConfig failed!\n" ); ret = -1; goto ENCODE_ERROR; } if (SsbSipJPEGSetConfig(JPEG_SET_ENCODE_WIDTH, width) != JPEG_OK) { log2file("SsbSipJPEGSetConfig failed!\n" ); ret = -1; goto ENCODE_ERROR; } if (SsbSipJPEGSetConfig(JPEG_SET_ENCODE_HEIGHT, height) != JPEG_OK) { log2file("SsbSipJPEGSetConfig failed!\n"); ret = -1; goto ENCODE_ERROR; } if (SsbSipJPEGSetConfig(JPEG_SET_ENCODE_QUALITY, JPG_QUALITY_LEVEL_1) != JPEG_OK) { log2file("SsbSipJPEGSetConfig failed!\n"); ret = -1; goto ENCODE_ERROR; } inBufferSize = width*height*2; InBuf = SsbSipJPEGGetEncodeInBuf(jpegEncodeHandle, inBufferSize); if (InBuf == NULL) { log2file("SsbSipJPEGGetEncodeInBuf failed\n"); ret = -1; goto ENCODE_ERROR; } Rgb565ToYuv422((unsigned char*)rgb565Buffer, width, height, (unsigned char*)InBuf); /* fp2 = fopen("/test_320_240.yuv", "rb"); if(fp2 == NULL){ ret = -1; goto ENCODE_ERROR; } fseek(fp2, 0, SEEK_END); fileSize = ftell(fp2); fseek(fp2, 0, SEEK_SET); log2file("inBufferSize = %ld, fileSize = %ld\n", inBufferSize, fileSize); fread(InBuf, 1, fileSize, fp2); fclose(fp2); */ result = SsbSipJPEGEncodeExe(jpegEncodeHandle, &ExifInfo, JPEG_USE_HW_SCALER); if (result != JPEG_OK){ log2file("SsbSipJPEGEncodeExe failed!\n"); ret = -1; goto ENCODE_ERROR; } OutBuf = SsbSipJPEGGetEncodeOutBuf(jpegEncodeHandle, &jpegSize); if(OutBuf == NULL){ log2file("SsbSipJPEGGetEncodeOutBuf failed!\n"); ret = -1; goto ENCODE_ERROR; } fp = fopen(outFilename, "wb+"); if(fp == NULL) { log2file("open %s file failed!\n", outFilename); ret = -1; goto ENCODE_ERROR; } fwrite(OutBuf, 1, jpegSize, fp); fclose(fp); ENCODE_ERROR: SsbSipJPEGEncodeDeInit(jpegEncodeHandle); return ret; } Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); } Widget::~Widget() { delete ui; } void Widget::on_SnapButton_clicked() { FBInfo fb; int i,j; memset(&fb, 0x00, sizeof(fb)); if (fb_open(&fb, FB_FILENAME) == 0) { char filename[255]; char timeStr[255]; time_t lt; lt=time(NULL); strcpy(filename, PICTURN_PATH); strcpy(timeStr, asctime(localtime(&lt))); i = strlen(filename); for (j = 0; j<strlen(timeStr) && i<sizeof(filename); j++) { if (timeStr[j]>='0' && timeStr[j]<='9') { filename[i++] = timeStr[j]; } } filename[i]='\0'; strcat(filename, ".jpg"); if ( rgb5652jpeg(fb.bits , fb_width(&fb) , fb_height(&fb) , filename) == 0) { //QMessageBox::information(this, "Snap", QString("Successed! The picturn has been save to %1.").arg(filename)); /* QPixmap pixmap(filename); static QLabel* label = new QLabel(0); label->setPixmap(pixmap); label->showMaximized(); */ } else { QMessageBox::information(this, "Snap", "Error!"); } fb_close(&fb); } else { QMessageBox::information(this, "Snap", "Error!"); } } extern bool is_recording; extern bool receive_enable; extern FILE* encoded_fp; void Widget::on_StopButton_clicked() { is_recording = false; receive_enable = !receive_enable; } void Widget::on_RecordButton_clicked() { if (!is_recording) { char filename[255]; char timeStr[255]; time_t lt; lt=time(NULL); strcpy(filename, PICTURN_PATH); strcpy(timeStr, asctime(localtime(&lt))); int i = strlen(filename); for (int j = 0; j<strlen(timeStr) && i<sizeof(filename); j++) { if (timeStr[j]>='0' && timeStr[j]<='9') { filename[i++] = timeStr[j]; } } filename[i]='\0'; strcat(filename, ".h264"); encoded_fp = fopen(filename, "wb+"); } else { fclose(encoded_fp); } is_recording = !is_recording; } void Widget::on_PlaybackButton_clicked() { }
ff31b01c792940a9b13420ced0de0dff554501d7
5ea09a949bdcf7ef5c3ea504fb14751f57d3f328
/Homework04/Circle.h
5cc69e924f74bb195a78d6ce8c4bd4e6f9e5a7e6
[]
no_license
staatsty/CSE_335
0e4600e7748b8a42c057fa2f64947bc4c080aaf7
53d32188869a3a58a4b259b974f217ac7df5f588
refs/heads/master
2020-04-01T05:48:08.654789
2018-10-13T22:45:26
2018-10-13T22:45:26
152,920,091
0
0
null
null
null
null
UTF-8
C++
false
false
785
h
Circle.h
/* * File: Circle.h * Author: Tyler Staats * * Created on January 22, 2018, 3:15 PM */ #ifndef CIRCLE_H #define CIRCLE_H #include <string> #include <iostream> #include <iomanip> using namespace std; /* * This class is called Circle * This class is derived from the Shape base class * Uses the same variables as shape with and added radius variable */ class Circle: public Shape{ public: float radius; //radius of circle const float pi = 3.1415926535897; //const pi used to find area Circle(int a, int b, string c, float d):Shape(a,b,c),radius(d){ //ctor ofCircle } float computeArea() {return pi * (radius * radius);}//uses virtual function to compute area of Circle }; #endif /* CIRCLE_H */
cd09b92772d8662ebc5b3760c7136f3f5af3e983
2aa20455bc11aa7a94da704ab3770a6231ddfc38
/LintCode/searchRange.cpp
0e993a8e1cf8e6f12eead86e15706eb4b1109c93
[]
no_license
zhonghuawu/workspace
852485eafe399f9fd2d88083c35312b309ad18a5
a283b18bea3e63b5cb674acfbf2f30d0108f40d8
refs/heads/master
2020-12-29T02:42:31.283317
2015-03-10T20:09:04
2017-02-17T12:16:51
46,476,002
0
0
null
null
null
null
UTF-8
C++
false
false
935
cpp
searchRange.cpp
#include <iostream> #include <vector> using namespace std; class TreeNode { public : int val; TreeNode* left,* right; TreeNode(int val) { this->val = val; this->left = this->right = NULL; } }; class Solution { public : vector<int> searchRange(TreeNode* root, int k1, int k2) { vector<int> result; search(root,k1,k2,result); return result; } void search(TreeNode* root, int k1, int k2, vector<int>& result){ if(root!=NULL){ search(root->left,k1,k2,result); if(root->val>= k1 && root->val<=k2) result.push_back(root->val); search(root->right,k1,k2,result); } } }; int main(){ TreeNode root(20); root.left = new TreeNode(8); root.right = new TreeNode(22); root.left->left = new TreeNode(4); root.left->right = new TreeNode(12); vector<int> result = Solution().searchRange(&root,10,22); for(vector<int>::iterator it = result.begin();it!=result.end();it++) cout << *it << " "; cout << endl; }
48987d31673615cfb99a0ed2361094f52b1fc7b8
bbcda48854d6890ad029d5973e011d4784d248d2
/trunk/win/BumpTop Settings/include/wxWidgets/wx/mac/classic/control.h
6bfeae08432ed86f3ae8f68b1712b035ea6b7892
[ "LGPL-2.0-or-later", "WxWindows-exception-3.1", "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
dyzmapl/BumpTop
9c396f876e6a9ace1099b3b32e45612a388943ff
1329ea41411c7368516b942d19add694af3d602f
refs/heads/master
2020-12-20T22:42:55.100473
2020-01-25T21:00:08
2020-01-25T21:00:08
236,229,087
0
0
Apache-2.0
2020-01-25T20:58:59
2020-01-25T20:58:58
null
UTF-8
C++
false
false
3,976
h
control.h
///////////////////////////////////////////////////////////////////////////// // Name: control.h // Purpose: wxControl class // Author: Stefan Csomor // Modified by: // Created: 1998-01-01 // RCS-ID: $Id: control.h 36891 2006-01-16 14:59:55Z MR $ // Copyright: (c) Stefan Csomor // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #ifndef _WX_CONTROL_H_ #define _WX_CONTROL_H_ WXDLLEXPORT_DATA(extern const wxChar) wxControlNameStr[]; // General item class class WXDLLEXPORT wxControl : public wxControlBase { DECLARE_ABSTRACT_CLASS(wxControl) public: wxControl(); wxControl(wxWindow *parent, wxWindowID id, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = 0, const wxValidator& validator = wxDefaultValidator, const wxString& name = wxControlNameStr) { Create(parent, id, pos, size, style, validator, name); } bool Create(wxWindow *parent, wxWindowID id, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = 0, const wxValidator& validator = wxDefaultValidator, const wxString& name = wxControlNameStr); virtual ~wxControl(); // Simulates an event virtual void Command(wxCommandEvent& event) { ProcessCommand(event); } // implementation from now on // -------------------------- // Calls the callback and appropriate event handlers bool ProcessCommand(wxCommandEvent& event); virtual void SetLabel(const wxString& title) ; wxList& GetSubcontrols() { return m_subControls; } void OnEraseBackground(wxEraseEvent& event); virtual bool Enable(bool enable = TRUE) ; virtual bool Show(bool show = TRUE) ; virtual void DoSetWindowVariant( wxWindowVariant variant ) ; virtual void MacRedrawControl () ; virtual void MacHandleControlClick( WXWidget control , wxInt16 controlpart , bool mouseStillDown ) ; virtual void MacPreControlCreate( wxWindow *parent, wxWindowID id, wxString label , const wxPoint& pos, const wxSize& size, long style, const wxValidator& validator, const wxString& name , WXRECTPTR outBounds , unsigned char* maclabel ) ; virtual void MacPostControlCreate() ; virtual void MacAdjustControlRect() ; virtual WXWidget MacGetContainerForEmbedding() ; virtual void MacSuperChangedPosition() ; virtual void MacSuperEnabled( bool enabled ) ; virtual void MacSuperShown( bool show ) ; virtual bool MacCanFocus() const ; virtual void MacUpdateDimensions() ; void* MacGetControlAction() { return m_macControlAction ; } virtual void DoSetSize(int x, int y,int width, int height,int sizeFlags = wxSIZE_AUTO ) ; void OnKeyDown( wxKeyEvent &event ) ; void OnMouseEvent( wxMouseEvent &event ) ; void OnPaint(wxPaintEvent& event) ; virtual void Refresh(bool eraseBack = TRUE, const wxRect *rect = NULL) ; WXWidget GetMacControl() { return m_macControl ;} protected: // For controls like radiobuttons which are really composite WXWidget m_macControl ; void* m_macControlAction ; bool m_macControlIsShown ; wxList m_subControls; int m_macHorizontalBorder ; int m_macVerticalBorder ; virtual wxSize DoGetBestSize() const; private: DECLARE_EVENT_TABLE() }; wxControl *wxFindControlFromMacControl(WXWidget inControl ) ; void wxAssociateControlWithMacControl(WXWidget inControl, wxControl *control) ; void wxRemoveMacControlAssociation(wxControl *control) ; #endif // _WX_CONTROL_H_
1c2abb9d105ea101007937c7eda2b42efd355539
9b4c00dc79a073ea26a0221e1f24464e4eb70b5c
/20x4/TB CODE/SerLCD_testbed_v01/SerLCD_testbed_v01.ino
44aec6644d97efc3a9f75ac0e695b8331e72a03d
[]
no_license
lewispg228/Serial_LCD_testbeds
95f8a897dd75dfa6a26f7227ad4fffdecaa2e7f4
5b25c64f0f43cb0a214ecae06eb5e2fe04d3f234
refs/heads/master
2020-07-19T18:15:17.178728
2020-04-27T22:23:47
2020-04-27T22:23:47
73,756,164
0
0
null
null
null
null
UTF-8
C++
false
false
15,857
ino
SerLCD_testbed_v01.ino
/* SerLCD testbed code. Flying Jalapeno (VCC (aka LOGIC): 3.3V, V1:3.3V, V2: RAW (5-7V)) 2 capsense pads: Pretest & Power, TEST Select Mega2560 from the boards list Test procedure: * USER PRESS "PRETEST & POWER" BUTTON * pretest for shorts to GND on VIN and 3.3V rails * power up with V2 (jumpered to RAW 7V input source) * power up V1 (used to power the programming lines switch IC) * * USER ENGAGE PROGRAMMING (via batch file or stand alone Pi_grammer) * Load bootloader/firmware combined hex * * USER VERIFY SPLASH SCREEN * * USER PRESS "TEST" BUTTON * Test voltage output is 3.3V * Set contrast via serial * Test Serial * Test I2C * Test SPI * Test backlight(s) via Serial * Leave LCD in ideal user state (contrast set, backlight on) * * */ #define STATUS_LED 13 #define PGM_SWITCH_EN 30 #define PT_CTRL_PIN 3 #define PT_READ_PIN A6 #define DTR_FJ 2 #define CS_PIN 53 // Display size. The same testbed code goes onto both versions of the testing hardware, // and the following two definitions change the messages sent during testing. // Define one of these two following variables as a "1" and the other as a "0". #define DISPLAY_SIZE_16X2 0 #define DISPLAY_SIZE_20X4 1 #define DISPLAY_ADDRESS1 0x72 //This is the default address of the Serial1 #include <FlyingJalapeno.h> FlyingJalapeno FJ(STATUS_LED, 3.3); //Blink status msgs on pin 13 #include <Wire.h> #include <SPI.h> #include <CapacitiveSensor.h> CapacitiveSensor cs_1 = CapacitiveSensor(47, 45); CapacitiveSensor cs_2 = CapacitiveSensor(31, 46); int failures = 0; //Number of failures by the main test routine boolean targetPowered = false; //Keeps track of whether power supplies are energized long preTestButton = 0; //Cap sense values for two main test buttons long testButton = 0; void setup() { pinMode(STATUS_LED, OUTPUT); pinMode(PT_CTRL_PIN, OUTPUT); digitalWrite(PT_CTRL_PIN, LOW); pinMode(DTR_FJ, INPUT); pinMode(18, INPUT); // TX1, connected to RXI on product pinMode(19, INPUT); // RX1, connected to TXO on product FJ.enablePCA(); //Enable the I2C buffer Serial.begin(9600); Serial.println("Serial Enabled LCD Testbed\n\r"); } void loop() { preTestButton = cs_1.capacitiveSensor(30); testButton = cs_2.capacitiveSensor(30); //Serial.print(preTestButton); //Serial.print("\t"); //Serial.println(testButton); //Is user pressing PreTest button? if (preTestButton > 5000) { FJ.dot(); //Blink status LED to indicate button press if (targetPowered == true) { power_down(); //Power down the test jig } else { //Check v2 for shorts to ground. Note, V1 is being used to power the switching programming lines IC // also a third pretest for 3.3V output boolean PT_VIN = FJ.powerTest(2); boolean PT_33V = FJ.PreTest_Custom(PT_CTRL_PIN, PT_READ_PIN); if (PT_VIN == true && PT_33V == true) { FJ.setV2(true, 5); // note, this is connected to RAW source via jumper on FJ // supply 5V to programming lines swittcher IC. Note, this is the only portion of the tested using this power supply, so we can just leave it on 100% of the time. FJ.setV1(true, 3.3); //Turn on power supply 1 to 3.3V pinMode(PGM_SWITCH_EN, OUTPUT); digitalWrite(PGM_SWITCH_EN, HIGH); // enable switch for initial programming. We will want to disable this when we move to other testing. Serial.println("Pre-test PASS, powering up...\n\r"); targetPowered = true; digitalWrite(LED_PT_PASS, HIGH); digitalWrite(LED_PT_FAIL, LOW); delay(500); // debounce touching } else { //Power supply test failed failures++; FJ.setV2(false, 5); //Turn off power supply 2 if (PT_VIN == false) Serial.println("Jumper on Power Input Rail (FJ V2, aka board VIN)\n\r"); if (PT_33V == false) Serial.println("Jumper on 3.3V Rail (board VCC)\n\r"); targetPowered = false; digitalWrite(LED_PT_FAIL, HIGH); digitalWrite(LED_PT_PASS, LOW); delay(500); // debounce touching } } } else if (testButton > 5000 && targetPowered == true) { //Begin main test FJ.dot(); digitalWrite(PGM_SWITCH_EN, LOW); // DISable switch for programming. pinMode(PGM_SWITCH_EN, INPUT); failures = 0; // reset for testing a second time digitalWrite(LED_PASS, LOW); digitalWrite(LED_FAIL, LOW); //contrast_test(); test(); //Run main test code if (failures == 0) { digitalWrite(LED_FAIL, HIGH); // accidentally swapped PASS and FAIL LEDs on hardware design } else { digitalWrite(LED_PASS, HIGH); // accidentally swapped PASS and FAIL LEDs on hardware design } } } void test() { test_VCC(); //contrast_test(); // just here temporarily to make sure this is working set_contrast_via_serial(10); serial_test(); //backlight_test_loop(); delay(200); I2C_test(); delay(200); if(failures == 0) SPI_test(); delay(200); if(failures == 0) { backlight_rgb_upfades(500); } } // This is an example of testing a 3.3V output from the board sent to A2. // This was originally used on the ESP32 dev board testbed. void test_VCC() { Serial.println("testing 3.3V output on board VCC"); // THIS IS SPLIT WITH A PRETEST CIRCUIT // This means that we need to write the PT_CTRL pin LOW, in order to get a split "closer" to 50%. pinMode(PT_CTRL_PIN, OUTPUT); digitalWrite(PT_CTRL_PIN, LOW); //pin = pin to test //correct_val = what we expect. //allowance_percent = allowed window for overage. 0.1 = 10% //debug = print debug statements boolean result = FJ.verifyVoltage(A6, 1.7, 10, true); // 3.3V split by two 10Ks in the PT circuit if (result == true) Serial.println("test success!"); else { Serial.println("test failure (should read near 1.7 V)"); failures++; } } void power_down() { Serial.println("powering down target"); Serial1.end(); Wire.end(); SPI.end(); digitalWrite(CS_PIN, LOW); FJ.disableRegulator1(); FJ.disableRegulator2(); digitalWrite(PGM_SWITCH_EN, LOW); // DISable switch for programming. pinMode(PGM_SWITCH_EN, INPUT); targetPowered = false; //Turn off all LEDs digitalWrite(LED_PT_PASS, LOW); digitalWrite(LED_PT_FAIL, LOW); digitalWrite(LED_PASS, LOW); digitalWrite(LED_FAIL, LOW); failures = 0; delay(500); // debounce touching } void contrast_test() { byte contrast = 0; //Will roll over at 255 Serial1.begin(9600); while(1) { Serial.print("Contrast: "); Serial.println(contrast); set_contrast_via_serial(contrast); Serial1.write('|'); //Setting character Serial1.write('-'); //Clear display Serial1.print("Contrast: "); Serial1.print(contrast); contrast += 10; delay(2000); //Hang out for a bit } } void set_contrast_via_serial(int contrast) { Serial1.begin(9600); // Note, this is only here because I can't get the RED or BLUE backlight to work right now, and I want to test com lines. Serial.println("Green brightness: 29"); // debug Serial1.write('|'); //Put LCD into setting mode Serial1.write(158 + 29); //Set green backlight amount to 0% delay(100); //Send contrast setting Serial1.write('|'); //Put LCD into setting mode Serial1.write(24); //Send contrast command (24 aka "ctrl-x") Serial1.write(contrast); // "10" contrast setting (0-255) seems to look perfect on my test jig in my office. delay(100); } void serial_test() { Serial1.write('|'); //Setting character Serial1.write('-'); //Clear display if(DISPLAY_SIZE_20X4) Serial1.print("Serial "); else if(DISPLAY_SIZE_16X2) Serial1.print("Serial "); // shorter amount of "spaces" - makes total length of characters 16 delay(100); } boolean ping_I2C() { #include <Wire.h> Wire.begin(); boolean result = FJ.verify_i2c_device(DISPLAY_ADDRESS1); if(result == false) failures++; return result; } void I2C_test() { FJ.enablePCA(); if(ping_I2C() == true) { Wire.beginTransmission(DISPLAY_ADDRESS1); // transmit to device #1 if(DISPLAY_SIZE_20X4) Wire.print("I2C "); else if(DISPLAY_SIZE_16X2) Wire.print("I2C "); // shorter amount of "spaces" - makes total length of characters 13 - note, we need room for "SPI" Wire.endTransmission(); //Stop I2C transmission } else { Serial.print("I2C ping FAILURE"); } Wire.end(); FJ.disablePCA(); } void SPI_test() { pinMode(CS_PIN, OUTPUT); digitalWrite(CS_PIN, HIGH); //By default, don't be selecting Serial1 SPI.begin(); //Start SPI communication //SPI.beginTransaction(SPISettings(100000, MSBFIRST, SPI_MODE0)); SPI.setClockDivider(SPI_CLOCK_DIV64); //Slow down the master a bit //Send the clear display command to the display - this forces the cursor to return to the beginning of the display //digitalWrite(CS_PIN, LOW); //Drive the CS pin low to select Serial1 //SPI.transfer('|'); //Put LCD into setting mode //SPI.transfer('-'); //Send clear display command //digitalWrite(CS_PIN, HIGH); //Release the CS pin to de-select Serial1 char tempString[50]; //Needs to be large enough to hold the entire string with up to 5 digits if(DISPLAY_SIZE_20X4) sprintf(tempString, "SPI "); else if(DISPLAY_SIZE_16X2) sprintf(tempString, "SPI"); // just fit in in the last 3 spots in the bottom row. The total row will display "I2C SPI" spiSendString(tempString); } //Sends a string over SPI void spiSendString(char* data) { digitalWrite(CS_PIN, LOW); //Drive the CS pin low to select Serial1 for(byte x = 0 ; data[x] != '\0' ; x++) //Send chars until we hit the end of the string SPI.transfer(data[x]); digitalWrite(CS_PIN, HIGH); //Release the CS pin to de-select Serial1 } void backlight_test_RGB(int delay_var) { //Serial1.begin(9600); //Begin communication with Serial1 Serial1.write('|'); //Put LCD into setting mode Serial1.write(158 + 0); //Set green backlight amount to 0% delay(100); Serial1.write('|'); //Put LCD into setting mode Serial1.write(188 + 0); //Set blue backlight amount to 0% delay(100); Serial1.write('|'); //Put LCD into setting mode Serial1.write(128); //Set white/red backlight amount to 0% delay(100); ///////////////////////RED Serial1.write('|'); //Put LCD into setting mode Serial1.write(128 + 29); //Set white/red backlight amount to 100% delay(delay_var); Serial1.write('|'); //Put LCD into setting mode Serial1.write(128); //Set white/red backlight amount to 0% ///////////////////////GREEN Serial1.write('|'); //Put LCD into setting mode Serial1.write(158 + 29); //Set green backlight amount to 100% delay(delay_var); Serial1.write('|'); //Put LCD into setting mode Serial1.write(158 + 0); //Set green backlight amount to 0% ///////////////////////BLUE Serial1.write('|'); //Put LCD into setting mode Serial1.write(188 + 29); //Set blue backlight amount to 100% delay(delay_var); Serial1.write('|'); //Put LCD into setting mode Serial1.write(188 + 0); //Set blue backlight amount to 0% ///////////////////////WHITE Serial1.write('|'); //Put LCD into setting mode Serial1.write(128 + 29); //Set white/red backlight amount to 100% Serial1.write(158 + 29); //Set green backlight amount to 100% Serial1.write(188 + 29); //Set blue backlight amount to 100% delay(delay_var); Serial1.write('|'); //Put LCD into setting mode Serial1.write(128); //Set white/red backlight amount to 0% Serial1.write(158 + 0); //Set green backlight amount to 0% Serial1.write(188 + 0); //Set blue backlight amount to 0% } void backlight_rgb_upfades(int delay_var) { int brightness[3] = {0,15,29}; //Serial1.begin(9600); //Begin communication with Serial1 // ALL OFF Serial1.write('|'); //Put LCD into setting mode Serial1.write(158 + 0); //Set green backlight amount to 0% delay(delay_var); Serial1.write('|'); //Put LCD into setting mode Serial1.write(188 + 0); //Set blue backlight amount to 0% delay(delay_var); Serial1.write('|'); //Put LCD into setting mode Serial1.write(128); //Set white/red backlight amount to 0% delay(delay_var); // RED UPFADE for( int i = 0 ; i <= 2 ; i++) { Serial.print("brightness: "); // debug Serial.println(brightness[i]); // debug Serial1.write('|'); //Put LCD into setting mode Serial1.write(128 + brightness[i]); //Set white/red backlight amount to 0% delay(delay_var); } Serial1.write('|'); //Put LCD into setting mode Serial1.write(128); //Set white/red backlight amount to 0% delay(delay_var); // GREEN UPFADE for( int i = 0 ; i <= 2 ; i++) { Serial.print("brightness: "); // debug Serial.println(brightness[i]); // debug Serial1.write('|'); //Put LCD into setting mode Serial1.write(158 + brightness[i]); //Set green backlight amount to 0% delay(delay_var); } Serial1.write('|'); //Put LCD into setting mode Serial1.write(158 + 0); //Set green backlight amount to 0% delay(delay_var); // BLUE UPFADE for( int i = 0 ; i <= 2 ; i++) { ///////////////////////RED Serial.print("brightness: "); // debug Serial.println(brightness[i]); // debug Serial1.write('|'); //Put LCD into setting mode Serial1.write(188 + brightness[i]); //Set blue backlight amount to 0% delay(delay_var); } Serial1.write('|'); //Put LCD into setting mode Serial1.write(188 + 0); //Set blue backlight amount to 0% delay(delay_var); } void backlight_test_monochrome() { //Serial1.begin(9600); //Begin communication with Serial1 Serial1.write('|'); //Put LCD into setting mode Serial1.write(128 + 29); //Set white/red backlight amount to 0% delay(2000); Serial1.write('|'); //Put LCD into setting mode Serial1.write(128 + 15); //Set white/red backlight amount to 51% delay(2000); Serial1.write('|'); //Put LCD into setting mode Serial1.write(128); //Set white/red backlight amount to 100% } // Note, this is only here because I can't get the RED or BLUE backlight to work right now, and I want to test com lines. void backlight_test_loop() { int BL128 = 0; int BL158 = 0; int BL188 = 0; while(1) { Serial1.begin(9600); if(Serial.available() > 0) { char input = Serial.read(); switch (input) { case '1': BL128 -= 1; Serial1.write('|'); //Put LCD into setting mode Serial1.write(128 + BL128); //Set green backlight amount to 0% delay(100); break; case '4': BL128 += 1; Serial1.write('|'); //Put LCD into setting mode Serial1.write(128 + BL128); //Set green backlight amount to 0% delay(100); break; case '2': BL158 -= 1; Serial1.write('|'); //Put LCD into setting mode Serial1.write(158 + BL158); //Set green backlight amount to 0% delay(100); break; case '5': BL158 += 1; Serial1.write('|'); //Put LCD into setting mode Serial1.write(158 + BL158); //Set green backlight amount to 0% delay(100); break; case '3': BL188 -= 1; Serial1.write('|'); //Put LCD into setting mode Serial1.write(188 + BL188); //Set green backlight amount to 0% delay(100); break; case '6': BL188 += 1; Serial1.write('|'); //Put LCD into setting mode Serial1.write(188 + BL188); //Set green backlight amount to 0% delay(100); break; } Serial.println(BL128); Serial.println(BL158); Serial.println(BL188); } } }
6a12bf72bfbf98744b3ba5554b3afe0b1aa2c228
091afb7001e86146209397ea362da70ffd63a916
/inst/include/nt2/signal/include/functions/db2mag.hpp
4b1cb850e2771e8bdc0b45e0f9afa1f8f9e14051
[]
no_license
RcppCore/RcppNT2
f156b58c08863243f259d1e609c9a7a8cf669990
cd7e548daa2d679b6ccebe19744b9a36f1e9139c
refs/heads/master
2021-01-10T16:15:16.861239
2016-02-02T22:18:25
2016-02-02T22:18:25
50,460,545
15
1
null
2019-11-15T22:08:50
2016-01-26T21:29:34
C++
UTF-8
C++
false
false
217
hpp
db2mag.hpp
#ifndef NT2_SIGNAL_INCLUDE_FUNCTIONS_DB2MAG_HPP_INCLUDED #define NT2_SIGNAL_INCLUDE_FUNCTIONS_DB2MAG_HPP_INCLUDED #include <nt2/signal/functions/db2mag.hpp> #include <nt2/signal/functions/generic/db2mag.hpp> #endif
9359653ff016118c0a68d0dc1221ba9af3a3341b
28dba754ddf8211d754dd4a6b0704bbedb2bd373
/CodeTemplate/Geometry/PointsAndPolygon.cpp
dfa24d633428163a4d22cbc07df9c6aabb80d1fb
[]
no_license
zjsxzy/algo
599354679bd72ef20c724bb50b42fce65ceab76f
a84494969952f981bfdc38003f7269e5c80a142e
refs/heads/master
2023-08-31T17:00:53.393421
2023-08-19T14:20:31
2023-08-19T14:20:31
10,140,040
0
1
null
null
null
null
UTF-8
C++
false
false
17,443
cpp
PointsAndPolygon.cpp
#define maxn 10010 #define M_PI 3.14159265358979323846 /* pi */ double my_sqrt(double d) {return sqrt(max(d, 0.0));} double my_acos(double d) {return acos(d<-1?-1:d>1?1:d);} #define sqr(v) ((v)*(v)) const double eps = 1E-6; int sig(double d) { return (d>eps) - (d<-eps); } struct Point { double x, y; Point(double x, double y) : x(x), y(y) {} Point() {} Point operator - (const Point & p) const { return Point(x-p.x, y-p.y); } Point operator + (const Point & p) const { return Point(x+p.x, y+p.y); } Point operator * (double d) const { return Point(x*d, y*d); } /*double operator * (const Point &b) const { return x * b.y - y * b.x; }*/ bool operator == (const Point & p) const { return sig(x-p.x)==0 && sig(y-p.y)==0; } bool operator < (const Point & p) const { return sig(x-p.x)!=0 ? x<p.x : sig(y-p.y)<0; } Point resize(double d) { d /= my_sqrt(sqr(x)+sqr(y)); return Point(x*d, y*d); } Point left90() { return Point(-y, x); } Point rotate(double radian) { //逆时针转 double c = cos(radian), s = sin(radian); return Point(x*c-y*s, y*c+x*s); } double mod() { return my_sqrt(sqr(x)+sqr(y)); } void output() { printf("x = %.2f, y = %.2f\n", x, y); } }; double cross(const Point & o, const Point & a, const Point & b) { return (a.x-o.x)*(b.y-o.y) - (b.x-o.x)*(a.y-o.y); } double dot(Point o, Point a, Point b) { return (a.x-o.x)*(b.x-o.x) + (a.y-o.y)*(b.y-o.y); } double dis(Point a, Point b) { return my_sqrt(sqr(a.x-b.x) + sqr(a.y-b.y)); } int lineCross(Point a, Point b, Point c, Point d, Point &p) { double s1, s2; s1=cross(a,b,c); s2=cross(a,b,d); if(sig(s1)==0 && sig(s2)==0) return 2; if(sig(s2-s1)==0) return 0; p.x = (c.x*s2-d.x*s1)/(s2-s1); p.y = (c.y*s2-d.y*s1)/(s2-s1); return 1; } double area(Point * p, int n) { double res = 0; p[n] = p[0]; for(int i = 0; i < n; i ++) { // res += p[i].x*p[i+1].y - p[i+1].x*p[i].y; res += cross(p[0], p[i], p[i+1]); } return res / 2; } Point massCenter(Point *ps, int n) { Point ans = Point(0, 0); double sum_area = area(ps, n); if (sig(sum_area) == 0) return ans; ps[n] = ps[0]; Point ori = Point(0, 0); for (int i = 0; i < n; i++) { ans = ans + (ps[i] + ps[i + 1]) * (ps[i].x * ps[i + 1].y - ps[i + 1].x * ps[i].y); } return Point(ans.x / sum_area / 6., ans.y / sum_area / 6.); } //在ax+by+c=0直线上找两个点p1、p2,并且使得向量(p1,p2)的左面为ax+by+c<0一面 //返回ax+by+c是否为一直线,即a^2+b^2 != 0 bool axis(double a, double b, double c, Point & p1, Point & p2) { double d = a*a+b*b; if(sig(d) > 0) { p1 = Point(-a*c/d, -b*c/d); p2 = p1 + Point(-b, a); return true; } return false; } //下面是新的基本操作 //返回点o到直线ab的距离,res保存o在ab上的投影 double pointToLine(Point o, Point a, Point b, Point & res) { double d = dis(a, b); double s = cross(a, b, o) / d; res = o + (a-b).left90()*(s/d); return fabs(s); } //oa围绕o点,逆时针转到ob,所转的角度。返回值在(-pi, pi]之间 double angle(Point o, Point a, Point b) { double cr = cross(o, a, b); double dt = dot(o, a, b); if(sig(cr)==0) cr = 0; if(sig(dt)==0) dt = 0; return atan2(cr, dt); } /** * a1a2逆时针绕点转到b1b2,绕的点为p,转的角度为ang (-pi, pi] * 返回:可以转true,不可以转false 当且仅当两向量平行且同向时无解! * assume |a1a2| = |b1b2| */ bool angle(Point a1, Point a2, Point b1, Point b2, Point & p, double & ang) { Point vecA = a2-a1, vecB = b2-b1; if(sig(vecA.mod()-vecB.mod()) != 0) return false; double cr = vecA.x*vecB.y-vecA.y*vecB.x; double dt = vecA.x*vecB.x+vecA.y*vecB.y; if(sig(cr)==0) cr = 0; if(sig(dt)==0) dt = 0; ang = atan2(cr, dt); if(sig(cr)==0) { if(sig(dt)>=0) return false; p = (a1+b1) * 0.5; return true; } Point m1 = (a1+b1)*0.5, m2 = (a2+b2)*0.5; if(1!=lineCross(m1, m1+(a1-b1).left90(), m2, m2+(a2-b2).left90(), p))//中垂线交点 lineCross(a1, a2, b1, b2, p); //中垂线平行,现在assume 八字型 return true; } //判断p是否在线段ab上,在端点处也返回true bool onSeg(Point p, Point a, Point b) { return sig(cross(p, a, b))==0 && sig(dot(p, a, b))<=0; } //---------上面是基本函数----------- //---------下面是新函数----------- //判断一个多边形是否是凸多边形,初始为瞬时针、逆时针均可! bool isConvex(Point * ps, int n) { bool s[3] = {1, 1, 1}; ps[n] = ps[0]; ps[n+1] = ps[1]; for(int i = 0; i < n && (s[0] | s[2]); i ++) { s[ 1+sig(cross(ps[i+1], ps[i+2], ps[i])) ] = 0; } return (s[0] | s[2]); //允许三点共线 return (s[1] && s[0] | s[2]); //不允许三点共线, 要用这个for的条件最好也改... } //0不在里面 2在里面 1边上 int inside_convex(Point * ps, int n, Point q) { bool s[3] = {1, 1, 1}; ps[n] = ps[0]; for(int i = 0; i < n && (s[0] | s[2]); i ++) { s[ 1+sig(cross(ps[i+1], q, ps[i])) ] = 0; } if(s[0] | s[2]) return s[1]+1; //里面或者边上 return 0; } /** * 判断点是否在凸多边形内O(n)初始化,log(n)效率,assume多边形为convex并且没有三点共线 * 教程:http://hi.baidu.com/aekdycoin/blog/item/7abf85026f0d7e85d43f7cfe.html * 题目:http://acm.sgu.ru/problem.php?contest=0&problem=253 */ Point ps[maxn]; double ang[maxn]; int n; void init() { if(area(ps, n) < 0) reverse(ps, ps+n); rotate(ps, min_element(ps, ps+n), ps+n); for(int i = 1; i < n; i ++) { ang[i] = atan2(ps[i].y-ps[0].y, ps[i].x-ps[0].x); } ang[0] = -M_PI/2; } bool dcmp(double a, double b) { return sig(a-b) < 0; } //0 外 2 内 1 边上 int judge(Point p) { if(onSeg(p, ps[0], ps[1]) || onSeg(p, ps[0], ps[n-1])) return 1; int idx = lower_bound(ang, ang+n, atan2(p.y-ps[0].y, p.x-ps[0].x), dcmp) - ang; if(idx <= 1 || idx == n) return 0; //外面! return 1 + sig(cross(ps[idx-1], ps[idx], p)); } /*sgu 253,快速判断点是否在凸多边形内 int main() { int m, k; while(scanf("%d%d%d", &n, &m, &k) != EOF) { for(int i = 0; i < n; i ++) scanf("%lf%lf", &ps[i].x, &ps[i].y); init(); int sum = 0; Point p; while(m --) { scanf("%lf%lf", &p.x, &p.y); if(judge(p)) sum ++; } if(sum >= k) { printf("YES\n"); } else { printf("NO\n"); } } return 0; } */ /** * 判断点p是否在任意多边形ps中 * 0外,1内,2边上 */ int inPolygon(Point * ps, int n, Point p) { int cnt = 0; ps[n] = ps[0]; for(int i = 0; i < n; i ++) { if(onSeg(p, ps[i], ps[i+1])) return 2; int k = sig( cross(ps[i], ps[i+1], p) ); int d1 = sig( ps[i+0].y-p.y ); int d2 = sig( ps[i+1].y-p.y ); if(k>0 && d1<=0 && d2>0) cnt ++; if(k<0 && d2<=0 && d1>0) cnt --; } return cnt != 0; } //多边形切割 //用直线ab切割多边形p,切割后的在向量(a,b)的左侧,并原地保存切割结果 //如果退化为一个点,也会返回去, 此时n为1 void polygon_cut(Point * p, int & n, Point a, Point b) { static Point pp[maxn]; int m = 0; p[n] = p[0]; for(int i = 0; i < n; i ++) { if(sig(cross(a, b, p[i])) > 0) pp[m ++] = p[i]; if(sig(cross(a, b, p[i])) != sig(cross(a, b, p[i+1]))) lineCross(a, b, p[i], p[i+1], pp[m ++]); } n = 0; for(int i = 0; i < m; i ++) if(!i || !(pp[i]==pp[i-1])) p[n ++] = pp[i]; while(n>1 && p[n-1]==p[0]) n --; } //多边形求核,类似于zzy的calCore const double BOUND = 10000000.0; bool calCore(Point * p, int & n) { static Point pp[maxn]; if(sig(area(p, n)) >= 0) copy(p, p+n, pp); else reverse_copy(p, p+n, pp); pp[n] = pp[0]; int nn = n; //pp,nn init over! p[0] = Point(-BOUND, -BOUND); p[1] = Point(BOUND, -BOUND); p[2] = Point(BOUND, BOUND); p[3] = Point(-BOUND, BOUND); n = 4; //p, n init over! for(int i = 0; i < nn && n; i ++) polygon_cut(p, n, pp[i], pp[i+1]); return n != 0; } /**求最近点对,分两个版本: * 1. 【版本1】:将靠近中心线的点按照y进行排序,每次递归都进行sort操作。。【类似吉大】 * 算法效率n^n logn,但是实际效果可能更好一些! * 2. 【版本2】:将所有的点按照y进行归并排序,每次递归进行inplace_merge操作。【类似上交】 * 算法效率nlogn,但是纯的nlogn,实际效果不一定最好。。。 * 3. 【求集合间的最近点对】 *类似poj3714,如果有两个点集,求点集间的最短距离,只需给Point加id域,且在close0的倒数第二行: * res = min(res, dis(psy[i], psy[j])); *的前面加一个if语句就可以了,比如 * if(psy[i].id^psy[j].id) * res = min(res, dis(psy[i], psy[j])); *并且用【版本2】的模板速度会快一点!!! */ bool cmp_x(const Point & a, const Point & b) {return a.x<b.x;} bool cmp_y(const Point & a, const Point & b) {return a.y<b.y;} //【版本1】:将靠近中心线的点按照y进行排序,每次递归都进行sort操作。。【类似吉大】 //算法效率n^n logn,但是实际效果可能更好一些! double close0(Point * ps, int l, int r) { static Point psy[maxn]; if(r-l <= 1) return 1E100; int m = (l + r) / 2, i; double res = 1E100; for(i = m; i >= l && sig(ps[i].x-ps[m].x)==0; i --); res = min(res, close0(ps, l, i+1)); for(i = m; i < r && sig(ps[i].x-ps[m].x)==0; i ++); res = min(res, close0(ps, i, r)); int len = 0; for(i = m; i>= l && sig(ps[m].x-res-ps[i].x)<0; i --) psy[len ++] = ps[i]; for(i = m+1; i < r && sig(ps[m].x+res-ps[i].x)>0; i ++) psy[len ++] = ps[i]; sort(psy, psy+len, cmp_y); for(int i = 0; i < len; i ++) for(int j = i+1; j<len && psy[j].y<psy[i].y+res; j ++) res = min(res, dis(psy[i], psy[j])); return res; } double close(Point * ps, int n) { sort(ps, ps+n, cmp_x); return close0(ps, 0, n); } //【版本2】:将所有的点按照y进行归并排序,每次递归进行inplace_merge操作。【类似上交】 //算法效率nlogn,但是纯的nlogn,实际效果不一定最好。。。 double close0_(Point * ps, int l, int r) { static Point psy[maxn]; if(r-l <= 1) return 1E300; int m = (l + r) / 2; double midX = ps[m].x; double res = min( close0_(ps, l, m), close0_(ps, m, r) ); inplace_merge(ps+l, ps+m, ps+r, cmp_y); double x1 = midX-res, x2 = midX+res; int len = 0; for(int i = l; i < r; i ++) if(sig(x1-ps[i].x)<0 && sig(ps[i].x-x2)<0) psy[len ++] = ps[i]; for(int i = 0; i < len; i ++) for(int j = i+1; j<len && psy[j].y<psy[i].y + res; j ++) res = min(res, dis(psy[i], psy[j])); return res; } double close_(Point * ps, int n) { sort(ps, ps+n, cmp_x); return close0_(ps, 0, n); } /** * 下面开始【【【【【【旋转卡壳】】】】】】】!!! * 旋转卡壳全集教程:http://blog.csdn.net/ACMaker/archive/2008/10/29/3176910.aspx */ /** * 求凸多边形直径!注意传入凸多边形! */ double diam(Point *p, int n) { if(area(p, n)<0) reverse(p, p+n); p[n] = p[0]; double res = 0; for(int i = 0, j = 1; i < n; i ++) { while(sig(cross(p[i], p[i+1], p[j])-cross(p[i], p[i+1], p[(j+1)%n])) < 0) j = (j+1)%n; res = max(res, dis(p[i], p[j])); res = max(res, dis(p[i+1], p[j])); } return res; } //计算两个凸多边形间最近,最远距离,assume两个凸多边形分离 //返回o到线段ab的最短距离 double minDis(Point o, Point a, Point b) { if (a == b) return dis(o, a); if(sig(dot(b, a, o))<0) return dis(o, b); if(sig(dot(a, b, o))<0) return dis(o, a); return fabs(cross(o, a, b)/dis(a, b)); } //计算从curAng逆时针转到ab的角 double calRotate(Point a, Point b, double curAng) { double x = fmod(atan2(b.y-a.y, b.x-a.x)-curAng, M_PI*2); if(x<0) x += M_PI*2; if(x>1.9*M_PI) x = 0; //in case x is nearly 2*M_PI if(x >= 1.01*M_PI) while(1); return x; } //求凸多边形间最小距离,断言P和Q分离 //传入P、Q:凸多边形。n、m:P和Q的顶点个数 //如果P和Q非逆时针,则reverse! //题目:POJ-3608 //教程:http://blog.csdn.net/ACMaker/archive/2008/10/29/3178696.aspx double mind2p(Point *P, int n, Point *Q, int m) { if(area(P, n) < 0) reverse(P, P+n); //需要逆时针的 if(area(Q, m) < 0) reverse(Q, Q+m); int p0 = min_element(P, P+n)-P, q0 = max_element(Q, Q+m)-Q; double res = dis(P[p0], Q[q0]); double ang = -M_PI/2, rotateP, rotateQ; int pi, pj, qi, qj, totP, totQ, val; for(pi=p0, qi=q0, totP=0, totQ=0; totP<n && totQ<m; ) { pj = (pi+1) % n; qj = (qi+1) % m; rotateP = calRotate(P[pi], P[pj], ang); rotateQ = calRotate(Q[qi], Q[qj], ang+M_PI); val = sig(rotateP - rotateQ); ang += min(rotateP, rotateQ); if(val == -1) res = min(res, minDis(Q[qi], P[pi], P[pj])); else if(val==1) res = min(res, minDis(P[pi], Q[qi], Q[qj])); else { res = min(res, minDis(P[pi], Q[qi], Q[qj])); res = min(res, minDis(P[pj], Q[qi], Q[qj])); res = min(res, minDis(Q[qi], P[pi], P[pj])); res = min(res, minDis(Q[qj], P[pi], P[pj])); } if(val != 1) pi=pj, totP ++; if(val != -1) qi=qj, totQ ++; } return res; } //求凸多边形间最大距离,断言P和Q分离 //传入P、Q:凸多边形。n、m:P和Q的顶点个数 //如果P和Q非逆时针,则reverse! //教程:http://blog.csdn.net/ACMaker/archive/2008/10/29/3178794.aspx double maxd2p(Point *P, int n, Point *Q, int m) { //【【【待测】】】.......!!! if(area(P, n) < 0) reverse(P, P+n); //需要逆时针的 if(area(Q, m) < 0) reverse(Q, Q+m); int p0 = min_element(P, P+n)-P, q0 = max_element(Q, Q+m)-Q; double res = dis(P[p0], Q[q0]); double ang = -M_PI/2, rotateP, rotateQ; int pi, pj, qi, qj, totP, totQ, val; for(pi=p0, qi=q0, totP=0, totQ=0; totP<n && totQ<m; ) { pj = (pi+1) % n; qj = (qi+1) % m; rotateP = calRotate(P[pi], P[pj], ang); rotateQ = calRotate(Q[qi], Q[qj], ang+M_PI); val = sig(rotateP - rotateQ); ang += min(rotateP, rotateQ); if(val == -1) res = max(res, max(dis(Q[qi], P[pi]), dis(Q[qi], P[pj]))); else if(val==1) res = max(res, max(dis(P[pi], Q[qi]), dis(P[pi], Q[qj]))); else { res = max(res, dis(P[pi], Q[qi])); res = max(res, dis(P[pi], Q[qj])); res = max(res, dis(P[pj], Q[qi])); res = max(res, dis(P[pj], Q[qj])); } if(val != 1) pi=pj, totP ++; if(val != -1) qi=qj, totQ ++; } return res; } /** //poj3608 Point P[maxn], Q[maxn]; int n, m; int main() { while(scanf("%d%d", &n, &m), n||m) { for(int i = 0; i < n; i ++) scanf("%lf%lf", &P[i].x, &P[i].y); for(int i = 0; i < m; i ++) scanf("%lf%lf", &Q[i].x, &Q[i].y); printf("%.5f\n", mind2p(P, n, Q, m)); } return 0; } */ /** * 计算凸多边形的最小外接矩形面积 * 如果要计算点集的最小外接矩形,先求凸包 * 点集的最小面积/周长外接矩形,UVA10173 * 教程:http://blog.csdn.net/ACMaker/archive/2008/10/30/3188123.aspx */ /** * graham求凸包-水平序,结果是按照瞬时针给出的 */ int graham(Point*p, int n, int*ch) { #define push(x) ch[len ++]=x #define pop() len -- sort(p, p+n); int len = 0, len0 = 1, i; for(i = 0; i < n; i ++) { while(len > len0 && sig(cross(p[ch[len-1]], p[ch[len-2]], p[i]))<=0) pop(); push(i); } len0 = len; for(i = n-2; i >= 0; i --) { while(len > len0 && sig(cross(p[ch[len-1]], p[ch[len-2]], p[i]))<=0) pop(); push(i); } return len-1; } bool cmp2(const Point &a, const Point &b) { return sig(a.y-b.y)!=0 ? a.y<b.y : sig(a.x-b.x)>0; } //计算凸多边形的最小外接矩形面积 double minRect0(Point *p, int n) { if(n<=2) return 0; if(area(p, n) < 0) reverse(p, p+n); int ai = min_element(p, p+n) -p; int bi = min_element(p, p+n, cmp2)-p; int ci = max_element(p, p+n) -p; int di = max_element(p, p+n, cmp2)-p; int aj, bj, cj, dj; double res = 1E100, ang = -M_PI/2; double ra, rb, rc, rd, r, s, c, ac, bd; while(ang < M_PI * 0.51) { aj=(ai+1)%n; ra = calRotate(p[ai], p[aj], ang); bj=(bi+1)%n; rb = calRotate(p[bi], p[bj], ang+0.5*M_PI); cj=(ci+1)%n; rc = calRotate(p[ci], p[cj], ang+1.0*M_PI); dj=(di+1)%n; rd = calRotate(p[di], p[dj], ang+1.5*M_PI); r = min(min(ra,rb), min(rc,rd)); ang += r; s = sin(ang), c = cos(ang); ac = -s*(p[ci].x-p[ai].x) + c*(p[ci].y-p[ai].y); bd = c*(p[di].x-p[bi].x) + s*(p[di].y-p[bi].y); res = min(res, fabs(ac*bd)); //改为(fabs(ac)+fabs(bd))*2就是求最小周长外接矩形 if(sig(ra-r)==0) ai=aj; if(sig(rb-r)==0) bi=bj; if(sig(rc-r)==0) ci=cj; if(sig(rd-r)==0) di=dj; } return res==1E100 ? 0 : res; } //计算点集的最小外接举行面积,底层调用minRect0 double minRect(Point *p, int n) { static Point q[maxn]; static int ch[maxn]; int len = graham(p, n, ch); for(int i = 0; i < len; i ++) q[i] = p[ch[len-1-i]]; return minRect0(q, len); } /* //UVA10173 Point P[maxn]; int n; int main() { while(scanf("%d", &n), n) { for(int i = 0; i < n; i ++) scanf("%lf%lf", &P[i].x, &P[i].y); printf("%.4f\n", minRect(P, n)); } return 0; } */ /** * 计算最多共线的点的个数(必须是整点,不能有重点,效率n^2),不能有重点!! */ typedef pair<int,int> T; int gcd(int a, int b) { for(int t; t=b; b=a%b, a=t); return a; } int calNumLine(T *ts, int n) { static T tmp[maxn]; int res = 0; int i, j, k; for(i = 0; i < n; i ++) { for(j = 0; j < i; j ++) { int dx = ts[j].first - ts[i].first; int dy = ts[j].second-ts[i].second; int g = gcd(dx, dy); dx /= g; dy /= g; if(dx<0) dx=-dx,dy=-dy; tmp[j] = T(dx, dy); } sort(tmp, tmp+j); for(j = 0; j < i; j = k) { for(k = j; k<i && tmp[k]==tmp[j]; k ++); res = max(res, k-j); } } return res+1; } int main() { return 0; }
c201ba5c63def4ac06fb41e6fd6dc6a43b102e6e
cd922461c50f6c86dd660f2bca7ee68afb3ee1ea
/test/integ/ImmutableSubcomponentAnalyzerTest.cpp
b57d4d3ce3d4eadde7fd5f25bd205702e9468894
[ "BSD-3-Clause", "LicenseRef-scancode-unknown" ]
permissive
alanyee/redex
0376b5091eee42d6817b9b28dc5c5bb5598889bb
35d261274571b1515e0eaec278cb8ecd79006559
refs/heads/master
2020-04-10T23:06:09.842130
2018-03-07T23:03:41
2018-03-07T23:03:41
124,304,844
0
0
BSD-3-Clause
2018-03-07T22:59:47
2018-03-07T22:59:47
null
UTF-8
C++
false
false
3,305
cpp
ImmutableSubcomponentAnalyzerTest.cpp
/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include <gmock/gmock.h> #include <gtest/gtest.h> #include <boost/algorithm/string/predicate.hpp> #include "DexClass.h" #include "DexLoader.h" #include "DexStore.h" #include "DexUtil.h" #include "IRCode.h" #include "IRInstruction.h" #include "IROpcode.h" #include "ImmutableSubcomponentAnalyzer.h" #include "JarLoader.h" #include "RedexContext.h" std::vector<std::vector<std::string>> expected_paths = { // First call to `check` {"p0.getA()", "p0.getA().getB()", "p0.getA().getC()", "p0.getB().getD()", "p0.getA().getB().getD().getE()"}, // Second call to `check` {"p1.getA()", "p1.getB()", "p1.getA().getC()", "p1.getB().getD()", "p1.getB().getD().getE()"}, // Third call to `check` {"?", "?", "?", "?", "?"}}; void validate_arguments(size_t occurrence, IRInstruction* insn, const ImmutableSubcomponentAnalyzer& analyzer) { std::vector<std::string> args; for (size_t i = 0; i < 5; ++i) { auto path_opt = analyzer.get_access_path(insn->src(i), insn); args.push_back(path_opt ? path_opt->to_string() : "?"); } EXPECT_THAT(args, ::testing::ElementsAreArray(expected_paths[occurrence])); } bool is_immutable_getter(DexMethodRef* method) { return boost::algorithm::starts_with(method->get_name()->str(), "get"); } TEST(ImmutableSubcomponentAnalyzerTest, accessPaths) { g_redex = new RedexContext(); std::vector<DexStore> stores; DexMetadata dm; dm.set_id("classes"); DexStore root_store(dm); const char* dexfile = std::getenv("dexfile"); ASSERT_NE(nullptr, dexfile); root_store.add_classes(load_classes_from_dex(dexfile)); stores.emplace_back(std::move(root_store)); const char* android_sdk = std::getenv("ANDROID_SDK"); ASSERT_NE(nullptr, android_sdk); const char* android_target = std::getenv("android_target"); ASSERT_NE(nullptr, android_target); std::string android_version(android_target); ASSERT_NE("NotFound", android_version); std::string sdk_jar = std::string(android_sdk) + "/platforms/" + android_version + "/android.jar"; ASSERT_TRUE(load_jar_file(sdk_jar.c_str())); DexStoreClassesIterator it(stores); Scope scope = build_class_scope(it); for (const auto& cls : scope) { if (cls->get_name()->str() == "Lcom/facebook/redextest/ImmutableSubcomponentAnalyzer;") { for (const auto& method : cls->get_dmethods()) { if (method->get_name()->str() == "test") { ImmutableSubcomponentAnalyzer analyzer(method, is_immutable_getter); size_t check_occurrence = 0; for (auto& mie : InstructionIterable(method->get_code())) { IRInstruction* insn = mie.insn; if (insn->opcode() == OPCODE_INVOKE_STATIC && insn->get_method()->get_name()->str() == "check") { validate_arguments(check_occurrence++, insn, analyzer); } } } } } } delete g_redex; }
aac3af57cfa9e693b1244bbd69eac54fed4e02b2
bc8a89a4911fc31c1ae50944889f5a81c0e4832f
/10222.cpp
a551c40d801502e50ba14a6a15362dd5c44e985d
[]
no_license
thierrychou/uva_online_judge
44616c1368176b16871a3cecbaff8c220e53680e
8a8a1493dec163c46a816785c66cfc65af6abc65
refs/heads/master
2023-03-28T12:12:10.499713
2021-03-21T12:23:33
2021-03-21T12:23:33
349,991,527
0
0
null
null
null
null
UTF-8
C++
false
false
1,597
cpp
10222.cpp
#include <cstdio> int main() { char c; char keymap[256]; keymap['\n'] = '\n'; keymap['\t'] = '\t'; keymap[' '] = ' '; keymap['\''] = 'l'; keymap[','] = 'n'; keymap['.'] = 'm'; keymap['/'] = ','; keymap[';'] = 'k'; keymap['['] = 'o'; keymap['\\'] = ';'; keymap[']'] = 'p'; keymap['a'] = ';'; keymap['b'] = 'c'; keymap['c'] = 'z'; keymap['d'] = 'a'; keymap['e'] = 'q'; keymap['f'] = 's'; keymap['g'] = 'd'; keymap['h'] = 'f'; keymap['i'] = 'y'; keymap['j'] = 'g'; keymap['k'] = 'h'; keymap['l'] = 'j'; keymap['m'] = 'b'; keymap['n'] = 'v'; keymap['o'] = 'u'; keymap['p'] = 'i'; keymap['q'] = '{'; keymap['r'] = 'w'; keymap['s'] = '`'; keymap['t'] = 'e'; keymap['u'] = 't'; keymap['v'] = 'x'; keymap['w'] = '}'; keymap['x'] = '/'; keymap['y'] = 'r'; keymap['z'] = '.'; keymap['A'] = ';'; keymap['B'] = 'c'; keymap['C'] = 'z'; keymap['D'] = 'a'; keymap['E'] = 'q'; keymap['F'] = 's'; keymap['G'] = 'd'; keymap['H'] = 'f'; keymap['I'] = 'y'; keymap['J'] = 'g'; keymap['K'] = 'h'; keymap['L'] = 'j'; keymap['M'] = 'b'; keymap['N'] = 'v'; keymap['O'] = 'u'; keymap['P'] = 'i'; keymap['Q'] = '{'; keymap['R'] = 'w'; keymap['S'] = '`'; keymap['T'] = 'e'; keymap['U'] = 't'; keymap['V'] = 'x'; keymap['W'] = '}'; keymap['X'] = '/'; keymap['Y'] = 'r'; keymap['Z'] = '.'; while((c=getchar())!=EOF) { putchar(keymap[c]); } }
5c1df618e5bcc76e031e0bcc8d43792f01f47998
dbce306854ea709f7544be3ddf24c0cd83daab87
/src/glpk/param.h
d50b64db3a3fc12c69486a881217adc47cd6a006
[]
no_license
jackiepurdue/ilp-spr-distance
c2f1aae6411d080e0ea3f1fe8e92f03e13293166
724ec50b9e60626007e2d853a829be8078fb99b3
refs/heads/master
2020-09-08T21:55:55.295609
2019-11-12T15:35:39
2019-11-12T15:35:39
221,251,175
0
0
null
null
null
null
UTF-8
C++
false
false
297
h
param.h
#include <memory> #ifndef CSPR_PARAM_H #define CSPR_PARAM_H class param { public: param(std::string tree1, std::string tree2, int param, bool verbose); int solve(int param); void formulate(); void delete_problem(); private: struct impl; std::shared_ptr<impl> _internals; }; #endif
adce38f4232b1a6ec3a2b809081b6463c89e45bc
9254fc558d175f76558be210c65a2e819753cb9e
/include/urbi/object/fwd.hh
544a60db15026eb6cf1765e842009877a8c2aa01
[]
permissive
urbiforge/urbi
ee36996e87c25dd0a75199d580ac13442ba3032c
d6c6091a28e79b935b4f6573225486238e3c7d47
refs/heads/master
2023-08-22T04:15:36.358115
2023-08-10T13:24:17
2023-08-10T13:24:17
56,369,573
18
5
BSD-3-Clause
2023-08-10T12:43:43
2016-04-16T06:38:50
C++
UTF-8
C++
false
false
4,360
hh
fwd.hh
/* * Copyright (C) 2007-2012, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /** ** \file object/fwd.hh ** \brief Forward declarations of all node-classes of OBJECT ** (needed by the visitors) */ #ifndef OBJECT_FWD_HH # define OBJECT_FWD_HH # include <libport/fwd.hh> # include <libport/intrusive-ptr.hh> # include <libport/reserved-vector.hh> # include <libport/vector.hh> # include <urbi/export.hh> namespace urbi { namespace object { // rObject & objects_type. class Object; typedef libport::intrusive_ptr<Object> rObject; static const unsigned objects_type_floor = 8; typedef libport::FlooredAllocator<rObject, objects_type_floor> objects_type_allocator; typedef libport::Constructor<rObject> objects_type_constructor; typedef libport::FlooredExponentialCapacity<objects_type_floor> objects_type_capacity; typedef libport::Vector<rObject, objects_type_allocator, objects_type_constructor, objects_type_capacity> objects_type; # define APPLY_ON_ALL_OBJECTS(Macro) \ Macro(Barrier); \ Macro(Code); \ Macro(Date); \ Macro(Dictionary); \ Macro(Directory); \ Macro(Duration); \ Macro(Event); \ Macro(EventHandler); \ Macro(Executable); \ Macro(File); \ Macro(Finalizable); \ Macro(Float); \ Macro(FormatInfo); \ Macro(Formatter); \ Macro(FunctionProfile); \ Macro(Hash); \ Macro(InputStream); \ Macro(IoService); \ Macro(Job); \ Macro(List); \ Macro(Lobby); \ Macro(Location); \ Macro(Logger); \ Macro(Matrix); \ Macro(OutputStream); \ Macro(Path); \ Macro(Position); \ Macro(Primitive); \ Macro(Process); \ Macro(Profile); \ Macro(Regexp); \ Macro(Semaphore); \ Macro(Server); \ Macro(Socket); \ Macro(Slot); \ Macro(Stream); \ Macro(String); \ Macro(Subscription); \ Macro(Tag); \ Macro(UConnection); \ Macro(UValue); \ Macro(Vector); class Slot; typedef libport::intrusive_ptr<Slot> rSlot; # define FWD_DECL(Class) \ class Class; \ typedef libport::intrusive_ptr<Class> r ## Class \ APPLY_ON_ALL_OBJECTS(FWD_DECL); # undef FWD_DECL extern URBI_SDK_API rObject false_class; extern URBI_SDK_API rObject nil_class; extern URBI_SDK_API rObject true_class; extern URBI_SDK_API rObject void_class; template <typename T> rObject to_urbi(const T&); // From cxx-primitive. template<typename M> rPrimitive primitive(M f); template<typename M> rPrimitive primitive(rPrimitive extend, M f); /// Stack of Urbi tags, to control execution. typedef std::vector<object::rTag> tag_stack_type; } // namespace object } namespace object { // Temporary merge until everything is moved in the urbi namespace. using namespace urbi::object; } #endif // !OBJECT_FWD_HH
955450942654eadfa9a66a4d2846e7c4c11bb6a9
804c6a3aa11ed1b723d65e5f2ff24190554dbce4
/rwindow.h
d92fd1ba05f041776048fd0c113829cd650cd5f2
[]
no_license
Kretikus/qtrogue
fe38141350305c382fc339d40be1ed5e48516d20
718669bdb63f94bd8cdad30aeca4bfe5cc49cf80
refs/heads/master
2018-12-29T17:54:58.857605
2012-08-06T11:47:38
2012-08-06T11:47:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
277
h
rwindow.h
#include "currentmap.h" #include <QVector> #include <QWidget> class RWidget : public QWidget { Q_OBJECT public: RWidget(QWidget* parent); protected: void paintEvent(QPaintEvent * event); void keyReleaseEvent(QKeyEvent *); QString currentText_; CurrentMap map_; };
d11c87e3bca9fce42d4ad64782ee97af9be74a22
91c49abf81011a221703afee257b6d6d11f2fb4d
/ai/perceptron/include/perceptron.hpp
f3c05f76dcca20cd3cd6b49c4fbb378687e4bb85
[]
no_license
milesand/UniversityCodes
017660e742cd6cc03f19900545d5a97b48c92dc6
3cad638ae9f6bc72fe25281b8f3aff0ebbac4fdb
refs/heads/master
2022-12-01T09:28:34.107805
2020-08-13T07:43:48
2020-08-13T07:43:48
287,214,623
0
0
null
null
null
null
UTF-8
C++
false
false
2,791
hpp
perceptron.hpp
#ifndef PERCEPTRON_H #define PERCEPTRON_H #include <cstddef> #include <array> // Perceptron with compile-time defined number of incoming connections. template <std::size_t N> class StaticPerceptron { public: // fields are public because the assignment requires these to be changed // and just having them public is easier than formal setters. // Threshold of this perceptron. float threshold; // Weights to be applied to input. std::array<float, N> weights; // Constructor. First N values in the given iterator will be used as weight // for this perceptron. User must make sure these values are accessible. // Failing to do so may result in an undefined behavior. template <typename Iterator> StaticPerceptron(float threshold, Iterator weights); // Run the numbers using the input iterator as incoming connection. // First N values in the given iterator will be accessed; user must make // sure these values are accessible. Failing to do so may result in an // undefined behavior. template<typename Iterator> float run(Iterator inputs); }; // Template stuff needs to live in header file! // I thought I'd put implementations in a separate file and #include it here, // but VSCode doesn't seem to like that very much. template <std::size_t N> template <typename Iterator> StaticPerceptron<N>::StaticPerceptron(float threshold, Iterator weights): threshold(threshold) { if (N == 0) { return; } // Advance iterator only (N-1) times. We only require N values to be // accessible from the iterator; that would imply 'can be advanced (N-1) // times', but probably not 'can be advanced N times'. Well, I'm not really // sure that's a problem, but still. auto iter = this->weights.begin(); auto end = this->weights.end(); *iter = *weights; for (++iter; iter != end; ++iter) { ++weights; *iter = *weights; } } template <std::size_t N> template <typename Iterator> float StaticPerceptron<N>::run(Iterator inputs) { float acc = -this->threshold; if (N != 0) { auto iter = this->weights.begin(); auto end = this->weights.end(); acc += (*iter) * (*inputs); for (++iter; iter != end; ++iter) { ++inputs; acc += (*iter) * (*inputs); } } // Activation function here. This might work better as a separate function // but I don't think there's a way to effectively hide this 'implementation // detail' in C++ that way. Making it a private static function member of // StaticPerceptron<N> might work, but I think that generates N different // copies of this exactly same snippet... Hmm. if (acc >= 0.0) { return 1.0; } return 0.0; } #endif
db751022e1aa5d839f08d31da159fd5fbea2e74b
8f021f68cd0949afa8d119582c0b419b014919d8
/URIOJ/uri2534.cpp
7e62f05c84e216b0e304198e7c620fdce16b73da
[]
no_license
Jonatankk/codigos
b9c8426c2f33b5142460a84337480b147169b3e6
233ae668bdf6cdd12dbc9ef243fb4ccdab49c933
refs/heads/master
2022-07-22T11:09:27.271029
2020-05-09T20:57:42
2020-05-09T20:57:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
382
cpp
uri2534.cpp
/* * Leonardo Deliyannis Constantin * URI 2534 - Exame Geral */ #include <stdio.h> #include <algorithm> bool cmp(int a, int b){ return a > b; } int main(){ int N, Q, i, v[112]; while(scanf("%d %d", &N, &Q) != EOF){ for(i = 0; i < N; i++){ scanf("%d", v+i); } std::sort(v, v+N, cmp); while(Q--){ scanf("%d", &i); printf("%d\n", v[i-1]); } } return 0; }
39a638b375c976f8e2c28e44471587d7ff253b27
f3376c06cf12367f2cb50ae2b1d1b41cdaef9e3e
/MyProjectA/Source/MyProject/EmitPickup.cpp
1aff2bc74985a6acc69a3b29a85d8ecbe0d4b82a
[]
no_license
bam1a/2097A2
256ce534d487c4ddceca2e45ffc158505dce8b73
4d19921bfc247acfa84234932161151cff464de5
refs/heads/master
2022-03-20T08:10:47.287234
2019-11-08T11:02:54
2019-11-08T11:02:54
149,250,282
0
0
null
null
null
null
UTF-8
C++
false
false
530
cpp
EmitPickup.cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "EmitPickup.h" #include "MyProject.h" #include "Net/UnrealNetwork.h" AEmitPickup::AEmitPickup() { // //Super::APickup(); pickupName = "default emit pickup"; pickupDisplayText = "default pickup display text"; } void AEmitPickup::BeginPlay() { Super::BeginPlay(); //pickupName = "default emit pickup"; //pickupDisplayText = "default pickup display text"; } void AEmitPickup::EmitExplosion_Implementation() { emitExplosionBP(); }
9d7730c75a2bc550c27658e74b26cd5fc1dc5319
8481b904e1ed3b25f5daa982a3d0cafff5a8d201
/C++/SJTU/sjtu 4012.cpp
b16c133fd3f9787ff9e44001c8084c7dcf6159f8
[]
no_license
lwher/Algorithm-exercise
e4ac914b90b6e4098ab5236cc936a58f437c2e06
2d545af90f7051bf20db0a7a51b8cd0588902bfa
refs/heads/master
2021-01-17T17:39:33.019131
2017-09-12T09:58:54
2017-09-12T09:58:54
70,559,619
1
2
null
null
null
null
UTF-8
C++
false
false
578
cpp
sjtu 4012.cpp
#include<iostream> #include<map> #include<queue> #include<cmath> #include<vector> #include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; struct node{ int v; node(int p=0){ v=p; } bool operator <(const node &b) const{ return v>b.v; } }; int n,ans; priority_queue<node> q; int main(){ int num; scanf("%d",&n); for(int i=1;i<=n;i++){ scanf("%d",&num); q.push(node(num)); } node A,B; for(int i=1;i<n;i++){ A=q.top();q.pop(); B=q.top();q.pop(); ans+=A.v+B.v; q.push(node(A.v+B.v)); } cout<<ans<<endl; return 0; }
17505d1a474cb28711e271af8e6d4805c88de05e
73e8f0b24c7a6c3bae304bc3aa71683ffe3964d7
/Training/basic_data_types.cpp
ec309c22c5d1f5e7c2c29989e5ea171e0d87666d
[]
no_license
norioz/training
bf59a3af43ec7dfd60e9ba4c36500e2d26690db7
bea3267e2ebfec4264f10a7e0b361e1d123aa64d
refs/heads/master
2020-03-24T21:59:59.366596
2018-11-27T02:51:21
2018-11-27T02:51:21
143,061,491
0
1
null
2018-08-24T02:56:11
2018-07-31T20:03:46
C++
UTF-8
C++
false
false
675
cpp
basic_data_types.cpp
#define _CRT_SECURE_NO_WARNINGS #include <cstdio> #include "basic_data_types.h" // Input // Input consists of the following space-separated values: int, long, char, // float, and double, respectively. // // Output Format // Print each element on a new line in the same order it was received as input. // Note that the floating point value should be correct up to 3 decimal places // and the double to 9 decimal places. int hackerrank::basic_data_types () { int a = -1; long b = -1L; char c = '\0'; float d = 0.0F; double e = 0.0; scanf("%d %ld %c %f %lf", &a, &b, &c, &d, &e); printf("%d\n%ld\n%c\n%f\n%lf\n", a, b, c, d, e); return 0; }
f9791a82d0289a228d06f7a473a24d5064352502
7121aaa6b2bfb0b9562c51d74a2d35805a25a4f5
/embedded/embedded.h
f5ccada2f810f5d5f8483a364c0c599aab8be1e3
[]
no_license
mongodb/mongo-snippets
0648e6211769623f518630142ff123296a78dca1
86abccb35fa43fb093169021f600c488b25d050d
refs/heads/master
2023-08-17T05:49:36.281014
2023-04-01T01:19:49
2023-04-01T01:19:49
147,843
192
57
null
2023-04-10T15:08:56
2009-03-10T22:09:11
C++
UTF-8
C++
false
false
1,250
h
embedded.h
/** embedded.h embedded todos: _ power management: there are some places in the code where it does not go completely idle, but rather almost idle, when there are no db requests coming in. this is not good on battery device. this is not too hard to change. _ --dur should be on automatically for embedded (when dur is ready) _ elegant/automatic handling of broken database files _ lots of cleanup in embedded.cpp */ namespace mongo { /** call at program startup. under normal circumstances returns fairly quickly after starting a thread. typically command line is inapplicable for embedded. however for dev/qa purposes it is still here. */ int initEmbeddedMongo(int argc, char* argv[]); /** call to shutdown with datafiles closed cleanly */ void endEmbeddedMongo(); /** include the normal mongodb client/ libraries to use this. The direct client is allocated with new and should be freed with the delete operator when you are done (or placed in a scoped ptr). DBDirectClient's can also be directly instantiated, but then you pull in a lot of extra header files... */ class DBClientBase; DBClientBase * makeDirectClient(); }
f664674748a0ecdb15c9711f842b647192ad7c78
6aa4ce39f7e5761f920872ab3dd5fa6cfb8e7c7f
/src/lcd/nextion_hmi/StateFiles.cpp
b8487aed903054444fbc15f3d8100ff4459caee7
[]
no_license
eskeyaar/MKA-firmware
2068feb3525873b22af2020300cfcbd1e588ca89
c1d01a81c2ede9a72a0e1282a6c858e3aa0e5251
refs/heads/master
2022-04-15T19:22:58.187596
2020-03-18T10:42:25
2020-03-18T10:42:25
null
0
0
null
null
null
null
ISO-8859-7
C++
false
false
8,291
cpp
StateFiles.cpp
/* * StateFiles.cpp * * Created on: 7 θών. 2018 γ. * Author: Azarov */ #include "../../../MK4duo.h" #if ENABLED(NEXTION_HMI) #include "StateFiles.h" namespace { ///////////// Nextion components ////////// //Page NexObject _page = NexObject(PAGE_FILES, 0, "files"); //Buttons NexObject _tFName0 = NexObject(PAGE_FILES, 21, "f0"); NexObject _tFName1 = NexObject(PAGE_FILES, 22, "f1"); NexObject _tFName2 = NexObject(PAGE_FILES, 23, "f2"); NexObject _tFName3 = NexObject(PAGE_FILES, 24, "f3"); NexObject _tFName4 = NexObject(PAGE_FILES, 25, "f4"); NexObject _tFName5 = NexObject(PAGE_FILES, 26, "f5"); NexObject _tFName6 = NexObject(PAGE_FILES, 27, "f6"); NexObject _tFIcon0 = NexObject(PAGE_FILES, 10, "i0"); NexObject _tFIcon1 = NexObject(PAGE_FILES, 12, "i1"); NexObject _tFIcon2 = NexObject(PAGE_FILES, 14, "i2"); NexObject _tFIcon3 = NexObject(PAGE_FILES, 28, "i3"); NexObject _tFIcon4 = NexObject(PAGE_FILES, 29, "i4"); NexObject _tFIcon5 = NexObject(PAGE_FILES, 30, "i5"); NexObject _tFIcon6 = NexObject(PAGE_FILES, 31, "i6"); NexObject _bFUp = NexObject(PAGE_FILES, 32, "up"); NexObject _bFDown = NexObject(PAGE_FILES, 33, "dn"); NexObject _tLoading = NexObject(PAGE_FILES, 34, "tL"); NexObject _bFUpIcon = NexObject(PAGE_FILES, 17, "pUP"); NexObject _bFDownIcon = NexObject(PAGE_FILES, 18, "pDN"); NexObject _bFilesCancel = NexObject(PAGE_FILES, 9, "cc"); NexObject *_listenList[] = { &_tFName0, &_tFName1, &_tFName2, &_tFName3, &_tFName4, &_tFName5, &_tFName6, &_bFUp, &_bFDown, &_bFilesCancel, NULL }; uint32_t _listPosition = 0; bool _insideDir = false; void Files_PopulateFileRow(uint32_t row, bool isDir, const char* filename) { NexObject* rowText; NexObject* rowIcon; switch(row) { case 0 : rowText = &_tFName0; rowIcon = &_tFIcon0; break; case 1 : rowText = &_tFName1; rowIcon = &_tFIcon1; break; case 2 : rowText = &_tFName2; rowIcon = &_tFIcon2; break; case 3 : rowText = &_tFName3; rowIcon = &_tFIcon3; break; case 4 : rowText = &_tFName4; rowIcon = &_tFIcon4; break; case 5 : rowText = &_tFName5; rowIcon = &_tFIcon5; break; case 6 : rowText = &_tFName6; rowIcon = &_tFIcon6; break; } if (isDir) { rowIcon->setPic(NEX_ICON_FILE_FOLDER); rowText->attachPush(StateFiles::FFolder_Push, rowText); } else { rowIcon->setPic(NEX_ICON_FILE_BLANK); if (filename == "") { rowText->detachPush(); } else { rowText->attachPush(StateFiles::FFile_Push, rowText); } } rowText->setText(filename); } void Files_PopulateFileList(uint32_t number) { uint16_t fileCnt = card.getnrfilenames(); uint32_t i = number; card.getWorkDirName(); uint8_t start_row = 0; //serial_print(card.fileName); //serial_print("\n>>>>>>>>>>>>\n"); if (card.fileName[0] != '/') { _tFName0.setText(".."); _tFIcon0.setPic(NEX_ICON_FILE_BACK); _tFName0.attachPush(StateFiles::FFolderUp_Push); start_row = 1; _insideDir = true; } else { _insideDir = false; } for (uint8_t row = start_row; row < 7; row++) { if (i < fileCnt) { #if ENABLED(SDCARD_SORT_ALPHA) card.getfilename_sorted(i); #else card.getfilename(i); #endif Files_PopulateFileRow(row, card.filenameIsDir, card.fileName); } else { Files_PopulateFileRow(row, false, ""); } i++; } if (number>0) _bFUpIcon.setPic(NEX_ICON_FILES_UP); else _bFUpIcon.setPic(NEX_ICON_FILES_UP_GREY); if ((number + (_insideDir ? 6 : 7)) <fileCnt) _bFDownIcon.setPic(NEX_ICON_FILES_DOWN); else _bFDownIcon.setPic(NEX_ICON_FILES_DOWN_GREY); } } void StateFiles::FUp_Push(void* ptr) { if (_listPosition>0) { _listPosition -= _insideDir ? 6 : 7; if (_listPosition<0) _listPosition=0; Files_PopulateFileList(_listPosition); } } void StateFiles::FDown_Push(void* ptr) { uint16_t fileCnt = card.getnrfilenames(); if ((_listPosition + (_insideDir ? 6 : 7)) <fileCnt) { _listPosition += _insideDir ? 6 : 7; Files_PopulateFileList(_listPosition); } } void StateFiles::FFile_Push(void* ptr) { ZERO(NextionHMI::buffer); if (ptr == &_tFName0) _tFName0.getText(NextionHMI::buffer, sizeof(NextionHMI::buffer)); else if (ptr == &_tFName1) _tFName1.getText(NextionHMI::buffer, sizeof(NextionHMI::buffer)); else if (ptr == &_tFName2) _tFName2.getText(NextionHMI::buffer, sizeof(NextionHMI::buffer)); else if (ptr == &_tFName3) _tFName3.getText(NextionHMI::buffer, sizeof(NextionHMI::buffer)); else if (ptr == &_tFName4) _tFName4.getText(NextionHMI::buffer, sizeof(NextionHMI::buffer)); else if (ptr == &_tFName5) _tFName5.getText(NextionHMI::buffer, sizeof(NextionHMI::buffer)); else if (ptr == &_tFName6) _tFName6.getText(NextionHMI::buffer, sizeof(NextionHMI::buffer)); if (strlen(NextionHMI::buffer)>50) { StateMessage::ActivatePGM_M(MESSAGE_WARNING, NEX_ICON_WARNING, MSG_WARNING, MSG_LONG_FILENAME, 1, PSTR(MSG_OK), StateMessage::ReturnToLastState, 0, 0); return; } if (card.isFileOpen()) card.closeFile(); card.selectFile(NextionHMI::buffer); StateFileinfo::Activate(); } void StateFiles::FFolder_Push(void* ptr) { ZERO(NextionHMI::buffer); // serial_print(ptr); // serial_print("\n+++\n"); if (ptr == &_tFName0) _tFName0.getText(NextionHMI::buffer, sizeof(NextionHMI::buffer)); else if (ptr == &_tFName1) _tFName1.getText(NextionHMI::buffer, sizeof(NextionHMI::buffer)); else if (ptr == &_tFName2) _tFName2.getText(NextionHMI::buffer, sizeof(NextionHMI::buffer)); else if (ptr == &_tFName3) _tFName3.getText(NextionHMI::buffer, sizeof(NextionHMI::buffer)); else if (ptr == &_tFName4) _tFName4.getText(NextionHMI::buffer, sizeof(NextionHMI::buffer)); else if (ptr == &_tFName5) _tFName5.getText(NextionHMI::buffer, sizeof(NextionHMI::buffer)); else if (ptr == &_tFName6) _tFName6.getText(NextionHMI::buffer, sizeof(NextionHMI::buffer)); if (strlen(NextionHMI::buffer)>50) { StateMessage::ActivatePGM_M(MESSAGE_WARNING, NEX_ICON_WARNING, MSG_WARNING, MSG_LONG_FILENAME, 1, PSTR(MSG_OK), StateMessage::ReturnToLastState, 0, 0); return; } _tLoading.SetVisibility(true); card.chdir(NextionHMI::buffer); _listPosition = 0; Files_PopulateFileList(_listPosition); _tLoading.SetVisibility(false); } void StateFiles::FFolderUp_Push(void* ptr) { card.updir(); _listPosition = 0; _tLoading.SetVisibility(true); Files_PopulateFileList(_listPosition); _tLoading.SetVisibility(false); } void StateFiles::FilesCancel_Push(void* ptr) { StateStatus::Activate(); } void StateFiles::Init() { _bFilesCancel.attachPush(FilesCancel_Push); _bFUp.attachPush(FUp_Push); _bFDown.attachPush(FDown_Push); } void StateFiles::Activate() { _listPosition = 0; _insideDir = false; //StateMessage::ActivatePGM(0, NEX_ICON_FILES, PSTR(MSG_READING_SD), PSTR(MSG_READING_SD), 0, "", 0, "", 0, 0); NextionHMI::ActivateState(PAGE_FILES); _page.show(); card.mount(); if (card.cardOK) { Files_PopulateFileList(_listPosition); _tLoading.SetVisibility(false); } else { StateMessage::ActivatePGM(MESSAGE_DIALOG, NEX_ICON_WARNING, PSTR(MSG_ERROR), PSTR(MSG_NO_SD), 1, PSTR(MSG_BACK), FilesCancel_Push, "", 0, 0); //if (!card.cardOK) //StateStatus::Activate(); //else // Files_PopulateFileList(_listPosition); } //NextionHMI::headerText.setTextPGM(PSTR(WELCOME_MSG)); } void StateFiles::TouchUpdate() { nexLoop(_listenList); } #endif
4e9dab138ab57677c64a5d6b999bb0fbd90e8bf8
4032d24a4191f8ef2e7997f74e4d5c440f50dae2
/nesterj/nes/mapper/085.cpp
82be2eba439b68567c248d452bbe25ae61e6a890
[]
no_license
PSP-Archive/NesterJ-Plus-RM
606461ad32881734927426abeecdcfe61773595f
a651249d963f29360f09f5b7cd8b4923a0982cb2
refs/heads/main
2023-05-27T03:26:54.064093
2021-06-05T01:01:00
2021-06-05T01:01:00
373,992,047
3
2
null
null
null
null
UTF-8
C++
false
false
4,096
cpp
085.cpp
///////////////////////////////////////////////////////////////////// // Mapper 85 void NES_mapper85_Init() { g_NESmapper.Reset = NES_mapper85_Reset; g_NESmapper.MemoryWrite = NES_mapper85_MemoryWrite; g_NESmapper.HSync = NES_mapper85_HSync; } void NES_mapper85_Reset() { // Init ExSound NES_APU_SelectExSound(2); // set CPU bank pointers g_NESmapper.set_CPU_banks4(0,1,g_NESmapper.num_8k_ROM_banks-2,g_NESmapper.num_8k_ROM_banks-1); // set PPU bank pointers if(g_NESmapper.num_1k_VROM_banks) { g_NESmapper.set_PPU_banks8(0,1,2,3,4,5,6,7); } else { g_NESmapper.set_VRAM_bank(0, 0); g_NESmapper.set_VRAM_bank(1, 0); g_NESmapper.set_VRAM_bank(2, 0); g_NESmapper.set_VRAM_bank(3, 0); g_NESmapper.set_VRAM_bank(4, 0); g_NESmapper.set_VRAM_bank(5, 0); g_NESmapper.set_VRAM_bank(6, 0); g_NESmapper.set_VRAM_bank(7, 0); } g_NESmapper.Mapper85.patch = 0; if(NES_crc32() == 0x33CE3FF0) // lagurange g_NESmapper.Mapper85.patch = 1; g_NESmapper.Mapper85.irq_enabled = 0; g_NESmapper.Mapper85.irq_counter = 0; g_NESmapper.Mapper85.irq_latch = 0; } void NES_mapper85_MemoryWrite(uint32 addr, uint8 data) { switch(addr & 0xF038) { case 0x8000: { g_NESmapper.set_CPU_bank4(data); } break; case 0x8008: case 0x8010: { g_NESmapper.set_CPU_bank5(data); } break; case 0x9000: { g_NESmapper.set_CPU_bank6(data); } break; case 0x9010: case 0x9030: { NES_APU_ExWrite(addr, data); } break; case 0xA000: { if(g_NESmapper.num_1k_VROM_banks) { g_NESmapper.set_PPU_bank0(data); } else { g_NESmapper.set_VRAM_bank(0, data); } } break; case 0xA008: case 0xA010: { if(g_NESmapper.num_1k_VROM_banks) { g_NESmapper.set_PPU_bank1(data); } else { g_NESmapper.set_VRAM_bank(1, data); } } break; case 0xB000: { if(g_NESmapper.num_1k_VROM_banks) { g_NESmapper.set_PPU_bank2(data); } else { g_NESmapper.set_VRAM_bank(2, data); } } break; case 0xB008: case 0xB010: { if(g_NESmapper.num_1k_VROM_banks) { g_NESmapper.set_PPU_bank3(data); } else { g_NESmapper.set_VRAM_bank(3, data); } } break; case 0xC000: { if(g_NESmapper.num_1k_VROM_banks) { g_NESmapper.set_PPU_bank4(data); } else { g_NESmapper.set_VRAM_bank(4, data); } } break; case 0xC008: case 0xC010: { if(g_NESmapper.num_1k_VROM_banks) { g_NESmapper.set_PPU_bank5(data); } else { g_NESmapper.set_VRAM_bank(5, data); } } break; case 0xD000: { if(g_NESmapper.num_1k_VROM_banks) { g_NESmapper.set_PPU_bank6(data); } else { g_NESmapper.set_VRAM_bank(6, data); } } break; case 0xD008: case 0xD010: { if(g_NESmapper.num_1k_VROM_banks) { g_NESmapper.set_PPU_bank7(data); } else { g_NESmapper.set_VRAM_bank(7, data); } } break; case 0xE000: { data &= 0x03; if(data == 0x00) { g_NESmapper.set_mirroring2(NES_PPU_MIRROR_VERT); } else if(data == 0x01) { g_NESmapper.set_mirroring2(NES_PPU_MIRROR_HORIZ); } else if(data == 0x02) { g_NESmapper.set_mirroring(0,0,0,0); } else { g_NESmapper.set_mirroring(1,1,1,1); } } break; case 0xE008: case 0xE010: { g_NESmapper.Mapper85.irq_latch = data; } break; case 0xF000: { g_NESmapper.Mapper85.irq_enabled = data & 0x03; if(g_NESmapper.Mapper85.irq_enabled & 0x02) { g_NESmapper.Mapper85.irq_counter = g_NESmapper.Mapper85.irq_latch; } } break; case 0xF008: case 0xF010: { g_NESmapper.Mapper85.irq_enabled = (g_NESmapper.Mapper85.irq_enabled & 0x01) * 3; } break; } } void NES_mapper85_HSync(uint32 scanline) { if(g_NESmapper.Mapper85.irq_enabled & 0x02) { if(g_NESmapper.Mapper85.irq_counter == (g_NESmapper.Mapper85.patch?0:0xFF)) { NES6502_DoIRQ(); g_NESmapper.Mapper85.irq_counter = g_NESmapper.Mapper85.irq_latch; } else { g_NESmapper.Mapper85.irq_counter++; } } } /////////////////////////////////////////////////////////////////////
96a3dab4a82e72bf7eb22e4d5750c18a81a7dfc6
518c1ea218366df02c9d04c08a9944742a94339a
/codeforces/Codeforces Round #270/D.cpp
dc57222ac7127f008de0e253151627e16bc5dc74
[]
no_license
jhonber/Programming-Contest
5b670d0e96263926e5d467c7b7c2434328c53c83
c2aa60acd3ac55f9e58a610ac037b31f52236ad4
refs/heads/master
2021-01-24T12:52:39.569485
2020-03-13T01:24:32
2020-03-13T01:24:32
16,530,134
6
1
null
null
null
null
UTF-8
C++
false
false
3,264
cpp
D.cpp
// http://codeforces.com/contest/472/problem/D #include<bits/stdc++.h> using namespace std; #define __ ios_base::sync_with_stdio(0); cin.tie(0); #define endl '\n' #define foreach(it, x) for (__typeof (x).begin() it = (x).begin(); it != (x).end(); ++it) #define all(x) x.begin(),x.end() #define D(x) cout << #x " = " << (x) << endl; template <class T> string toStr(const T &x) { stringstream s; s << x; return s.str(); } template <class T> int toInt(const T &x) { stringstream s; s << x; int r; s >> r; return r; } int dx[8] = {-1,-1,-1,0,1,1, 1, 0}; int dy[8] = {-1, 0, 1,1,1,0,-1,-1}; const int mx = 100100; struct edge { int start, end, weight; edge(){} edge(int start, int end, int weight) : start(start), end(end), weight(weight) {} bool operator < (const edge &that) const { // Change < by > to find maximum spanning tree return weight < that.weight; } }; /** Begin union find * Complexity: O(m log n) where m is the number of the operation * and n are the number of objects, in practice is almost O(m) **/ int p[mx]; void init_set (int &n) { for (int i = 0; i <= n; ++i) p[i] = i; } int find_set (int x) { return p[x] == x ? p[x] : p[x] = find_set(p[x]); } void join (int x, int y) { p[find_set(x)] = find_set(y); } /** End union find **/ /** e is a vector with all edges of the graph * return graph of MST **/ void krustal (vector<edge> &e, int &n, vector< vector<edge> > &G) { sort(e.begin(), e.end()); init_set(n); for (int i = 0 ; i < e.size(); ++i) { int u = e[i].start; int v = e[i].end; int w = e[i].weight; if (find_set(u) != find_set(v)) { join(u, v); G[u].push_back(edge(u, v, w)); G[v].push_back(edge(v, u, w)); } } } void dfs (int init, int i, int d, vector<int> &visited, vector< vector<edge> > &G, vector< vector<int> > &mat) { if (!visited[i]) { visited[i] = true; for (int j = 0; j < G[i].size(); ++j) { int cur = G[i][j].end; if (visited[cur]) continue; int cost = d + G[i][j].weight; mat[init][cur] = cost; dfs (init, cur, cost, visited, G, mat); } } } bool check (vector< vector<int> > &mat, int &n, vector< vector<edge> > &G) { vector< vector<int> > mat2 (n, vector<int> (n)); vector<int> visited(n); for (int i = 0; i < n; ++i) { for (int x = 0; x < n; ++x) visited[x] = 0; dfs (i, i, 0, visited, G, mat2); } int zeros = 0; for (int i = 0; i < n; ++i) { for (int j = i; j < n; ++j) { if (!mat[i][j]) zeros ++; if (mat[i][j] != mat[j][i] || mat[i][j] != mat2[i][j]) return false; } } n ++; if (zeros == (n * (n - 1)) / 2) return false; return true; } int main() { int n; scanf("%d", &n); vector< vector<int> > mat(n, vector<int> (n)); vector<edge> v; edge e; int ind = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { scanf("%d", &mat[i][j]); if (i < j) { e.weight = mat[i][j]; e.start = i; e.end = j; v.push_back(e); } } } vector< vector<edge> > G(n); krustal(v, n, G); if (n == 1 && !mat[0][0]) { cout << "YES"; return 0; } if (!check(mat, n, G)) cout << "NO"; else cout << "YES"; return 0; }
9a1538d66327c8a05b77d037e14afa217bc28e4c
40e704c0ca0691437cd92f13f13c5650d52ddeae
/ReadFile.cpp
ac36643618d749942f080c8563a660d82e583c3d
[]
no_license
bradpurvis/scaryrex
2dfeebae933783f9fbec72a05d397e801a518cfa
22e57c07c9c5db19824b6c4b6e0618be597e9360
refs/heads/master
2020-07-04T18:16:03.595108
2019-08-14T15:23:04
2019-08-14T15:23:04
202,370,224
0
0
null
null
null
null
UTF-8
C++
false
false
579
cpp
ReadFile.cpp
//Brad Purvis //COP2000.053 //read file #include "pch.h" #include <iostream> #include <string> #include <fstream> using namespace std; int main() { string dayofweek; ifstream myinputfile; myinputfile.open("Weekdays.txt"); if (!myinputfile) //file did not open { cout << "File did not open" << endl; return 10; } //loop thru file reading data records cout << "Reading data records\n\n"; while (myinputfile >> dayofweek) cout << dayofweek << endl; cout << "\nFinished reading records\n"; myinputfile.close(); return 0; }
0675ca369037f13166111ea801e5b03bfc30899b
691792c9c88c9d2b0f6d1cafc07604f719f06693
/5543.cpp
672f5f4a3f6bfd3e409ac868a8908e0baa033cda
[]
no_license
Do-ho/BaekJoon_Online_Judge
3d4221c1798bcccbfb5689f2cae22ecb1bcadc68
57488470b61951303253e864d6d262f13ef1ec18
refs/heads/master
2022-05-27T17:34:08.109927
2020-05-01T14:15:57
2020-05-01T14:15:57
260,465,662
1
0
null
null
null
null
UTF-8
C++
false
false
351
cpp
5543.cpp
#include <iostream> using namespace std; int main() { int menu[5], hamburger=2000, drink=2000; for(int i=0; i<5; i++) { cin >> menu[i]; if(i<3) { if(hamburger>menu[i]) hamburger = menu[i]; } else { if(drink>menu[i]) drink = menu[i]; } } cout << hamburger + drink - 50; }
ccb79cbaa8dc201211e46993a42d9fe6156084c8
06c9bb3dbce266df4b17e7dfab6ad251ace8d06a
/cateditdialog.cpp
b841b97d18006068803821c8227ab8627fe63a53
[]
no_license
demanxd/Dialogue_Compositor
72c83485846cb7cf5d94ca230fd8b9fc591b3cd7
53a7953d9c0af33246c227c433ed31b584329c82
refs/heads/master
2023-01-04T11:39:27.800801
2020-10-25T20:51:42
2020-10-25T20:51:42
307,192,268
0
0
null
null
null
null
UTF-8
C++
false
false
2,375
cpp
cateditdialog.cpp
#include "delegate.h" #include "cateditdialog.h" #include "ui_cateditdialog.h" CatEditDialog::CatEditDialog(QWidget *parent) { QVBoxLayout *layout = new QVBoxLayout(this); listView = new QListView(this); Delegate *myDelegate = new Delegate(this); myModel = new QStringListModel(this); listView->setModel(myModel); listView->setItemDelegate(myDelegate); appendButton = new QPushButton("Append", this); deleteButton = new QPushButton("Delete", this); layout->addWidget(listView); layout->addWidget(appendButton); layout->addWidget(deleteButton); setLayout(layout); connect(myDelegate, SIGNAL(closeEditor(QWidget*)), this, SLOT(checkUniqueItem(QWidget*))); //связываем сигнал закрытия редактора со слотом проверки connect(this, SIGNAL(tryToWriteItem(bool)), myDelegate, SLOT(setUnique(bool))); //для передачи в делегат булевой переменной connect(appendButton, SIGNAL(clicked()), this, SLOT(addItem())); connect(deleteButton, SIGNAL(clicked()), this, SLOT(removeItem())); listView->setCurrentIndex(myModel->index(0)); } CatEditDialog::~CatEditDialog() { } bool CatEditDialog::isUnique(QString &text, QAbstractItemView *view) { //метод, проверяющий уникальность элемента int item = view->currentIndex().row(); QStringListModel* model = static_cast<QStringListModel*>(view->model()); for (int i=0; i<model->rowCount(); i++) { if (i != item) if (model->data(model->index(i), Qt::DisplayRole).toString() == text) return false; } return true; } void CatEditDialog::removeItem() { QModelIndex index = listView->currentIndex(); myModel->removeRow(index.row()); listView->setCurrentIndex(index.row() != myModel->rowCount() ? index : myModel->index(index.row()-1)); } void CatEditDialog::addItem() { QModelIndex index = listView->currentIndex(); int i=myModel->rowCount(); myModel->insertRow(i); myModel->setData(myModel->index(i), QString("Iptem%1").arg(i)); listView->setCurrentIndex(myModel->index(myModel->rowCount()-1)); } void CatEditDialog::checkUniqueItem(QWidget *editor) { qDebug() << "CLOSE EDITOR"; QString text = static_cast<QLineEdit*>(editor)->text(); emit tryToWriteItem(isUnique(text, listView)); //сигнал делегату, isUnique(text, catView) - результат проверки }
8aced40d5a4931bc6a1f10381e907ae647ef7b80
4de159aea4b1eb5a527a3011275be57c4bb8d28f
/src/deps/newton/dgPhysics/dgCollisionUserMesh.cpp
52fc1c4ea22ee7c7fafc152a0e9ea118cd3c4747
[ "MIT", "LicenseRef-scancode-free-unknown" ]
permissive
tanis2000/binocle-c
27691ec089a4b75acc451ef6abc4767cb06a6fdd
cd3dbacdd5cb94bfce489b9ee2f07e218c645e29
refs/heads/master
2023-09-04T20:39:34.331172
2023-08-29T13:22:12
2023-08-29T13:22:12
192,515,187
132
8
MIT
2023-05-09T14:39:31
2019-06-18T10:07:33
C
UTF-8
C++
false
false
11,264
cpp
dgCollisionUserMesh.cpp
/* Copyright (c) <2003-2019> <Julio Jerez, Newton Game Dynamics> * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. */ #include "dgPhysicsStdafx.h" #include "dgBody.h" #include "dgWorld.h" #include "dgCollisionUserMesh.h" dgCollisionUserMesh::dgCollisionUserMesh(dgWorld* const world, const dgVector& boxP0, const dgVector& boxP1, const dgUserMeshCreation& data) :dgCollisionMesh (world, m_userMesh) { m_rtti |= dgCollisionUserMesh_RTTI; m_userData = data.m_userData; m_getInfoCallback = data.m_getInfoCallback; m_faceInAABBCalback = data.m_faceInAABBCallback; m_rayHitCallback = data.m_rayHitCallback; m_collideCallback = data.m_collideCallback; m_destroyCallback = data.m_destroyCallback; m_serializeCallback = data.m_serializeCallback; m_getAABBOvelapTestCallback = data.m_getAABBOvelapTestCallback; SetCollisionBBox(boxP0, boxP1); } dgCollisionUserMesh::dgCollisionUserMesh (dgWorld* const world, dgDeserialize deserialization, void* const userData, dgInt32 revisionNumber) :dgCollisionMesh (world, deserialization, userData, revisionNumber) { dgAssert (0); m_rtti |= dgCollisionUserMesh_RTTI; /* dgAABBPolygonSoup::Deserialize (deserialization, userData); dgVector p0; dgVector p1; GetAABB (p0, p1); SetCollisionBBox(p0, p1); */ } dgCollisionUserMesh::~dgCollisionUserMesh(void) { if (m_destroyCallback) { m_destroyCallback (m_userData); } } void dgCollisionUserMesh::Serialize(dgSerialize callback, void* const userData) const { SerializeLow(callback, userData); if (m_serializeCallback) { m_serializeCallback (m_userData, callback, userData); } } void dgCollisionUserMesh::GetVertexListIndexList (const dgVector& p0, const dgVector& p1, dgMeshVertexListIndexList &data) const { if (m_faceInAABBCalback) { return m_faceInAABBCalback (m_userData, &p0[0], &p1[0], (const dgFloat32**) &data.m_veterxArray, &data.m_vertexCount, &data.m_vertexStrideInBytes, data.m_indexList, data.m_maxIndexCount, data.m_userDataList); } else { data.m_triangleCount = 0; } } void dgCollisionUserMesh::GetCollisionInfo(dgCollisionInfo* const info) const { dgCollision::GetCollisionInfo(info); if (m_getInfoCallback) { m_getInfoCallback (m_userData, info); } } bool dgCollisionUserMesh::AABBOvelapTest (const dgVector& boxP0, const dgVector& boxP1) const { return (m_getAABBOvelapTestCallback && m_getAABBOvelapTestCallback (m_userData, boxP0, boxP1)) ? true : false; } dgFloat32 dgCollisionUserMesh::RayCast (const dgVector& localP0, const dgVector& localP1, dgFloat32 maxT, dgContactPoint& contactOut, const dgBody* const body, void* const userData, OnRayPrecastAction preFilter) const { dgFloat32 param = dgFloat32 (1.2f); if (m_rayHitCallback) { dgCollisionMeshRayHitDesc data; data.m_localP0 = localP0; data.m_localP1 = localP1; data.m_userId = body->m_collision->GetUserDataID(); data.m_userData = m_userData; data.m_altenateUserData = userData; if (body) { data.m_matrix = body->m_collision->GetGlobalMatrix(); } dgFloat32 t = m_rayHitCallback (data); if ((t < dgFloat32 (1.0f)) && (t > dgFloat32 (0.0f))) { param = t; contactOut.m_normal = data.m_normal; // contactOut.m_userId = data.m_userId; contactOut.m_shapeId0 = dgInt64 (data.m_userId); } } return param; } dgVector dgCollisionUserMesh::SupportVertex (const dgVector& dir, dgInt32* const vertexIndex) const { dgAssert (0); return dgVector::m_zero; } dgVector dgCollisionUserMesh::SupportVertexSpecial (const dgVector& dir, dgFloat32 skinThickness, dgInt32* const vertexIndex) const { dgAssert(0); return dgVector::m_zero; } void dgCollisionUserMesh::GetCollidingFacesContinue(dgPolygonMeshDesc* const data) const { data->m_me = this; data->m_faceCount = 0; data->m_userData = m_userData; data->m_separationDistance = dgFloat32(0.0f); dgFastRayTest ray(dgVector(dgFloat32(0.0f)), data->m_boxDistanceTravelInMeshSpace); m_collideCallback(&data->m_p0, &ray); dgInt32 faceCount0 = 0; dgInt32 faceIndexCount0 = 0; dgInt32 faceIndexCount1 = 0; dgInt32 stride = data->m_vertexStrideInBytes / sizeof(dgFloat32); dgFloat32* const vertex = data->m_vertex; dgInt32* const address = data->m_meshData.m_globalFaceIndexStart; dgFloat32* const hitDistance = data->m_meshData.m_globalHitDistance; const dgInt32* const srcIndices = data->m_faceVertexIndex; dgInt32* const dstIndices = data->m_globalFaceVertexIndex; dgInt32* const faceIndexCountArray = data->m_faceIndexCount; for (dgInt32 i = 0; (i < data->m_faceCount) && (faceIndexCount0 < (DG_MAX_COLLIDING_INDICES - 32)); i++) { dgInt32 indexCount = faceIndexCountArray[i]; const dgInt32* const indexArray = &srcIndices[faceIndexCount1]; dgInt32 normalIndex = data->GetNormalIndex(indexArray, indexCount); dgVector faceNormal(&vertex[normalIndex * stride]); faceNormal = faceNormal & dgVector::m_triplexMask; dgFloat32 dist = data->PolygonBoxRayDistance(faceNormal, indexCount, indexArray, stride, vertex, ray); const dgInt32 faceIndexCount = data->GetFaceIndexCount(indexCount); if (dist < dgFloat32(1.0f)) { hitDistance[faceCount0] = dist; address[faceCount0] = faceIndexCount0; faceIndexCountArray[faceCount0] = indexCount; memcpy(&dstIndices[faceIndexCount0], indexArray, faceIndexCount * sizeof(dgInt32)); faceCount0++; faceIndexCount0 += faceIndexCount; } faceIndexCount1 += faceIndexCount; } data->m_faceCount = 0; if (faceCount0) { data->m_faceCount = faceCount0; data->m_faceIndexStart = address; data->m_hitDistance = hitDistance; data->m_faceVertexIndex = dstIndices; if (GetDebugCollisionCallback()) { dgTriplex triplex[32]; //const dgMatrix& matrix = data->m_polySoupInstance->GetGlobalMatrix(); const dgVector scale = data->m_polySoupInstance->GetScale(); dgMatrix matrix(data->m_polySoupInstance->GetLocalMatrix() * data->m_polySoupBody->GetMatrix()); for (dgInt32 i = 0; i < data->m_faceCount; i++) { dgInt32 base = address[i]; dgInt32 indexCount = faceIndexCountArray[i]; const dgInt32* const vertexFaceIndex = &data->m_faceVertexIndex[base]; for (dgInt32 j = 0; j < indexCount; j++) { dgInt32 index = vertexFaceIndex[j]; dgVector q(&vertex[index * stride]); q = q & dgVector::m_triplexMask; //dgVector p(matrix.TransformVector(scale * dgVector(&vertex[index * stride]))); dgVector p(matrix.TransformVector(scale * q)); triplex[j].m_x = p.m_x; triplex[j].m_y = p.m_y; triplex[j].m_z = p.m_z; } dgInt32 faceId = data->GetFaceId(vertexFaceIndex, indexCount); GetDebugCollisionCallback() (data->m_polySoupBody, data->m_objBody, faceId, indexCount, &triplex[0].m_x, sizeof(dgTriplex)); } } } } void dgCollisionUserMesh::GetCollidingFacesDescrete(dgPolygonMeshDesc* const data) const { data->m_me = this; data->m_faceCount = 0; data->m_userData = m_userData; data->m_separationDistance = dgFloat32(0.0f); m_collideCallback(&data->m_p0, NULL); dgInt32 faceCount0 = 0; dgInt32 faceIndexCount0 = 0; dgInt32 faceIndexCount1 = 0; dgInt32 stride = data->m_vertexStrideInBytes / sizeof(dgFloat32); dgFloat32* const vertex = data->m_vertex; dgInt32* const address = data->m_meshData.m_globalFaceIndexStart; dgFloat32* const hitDistance = data->m_meshData.m_globalHitDistance; const dgInt32* const srcIndices = data->m_faceVertexIndex; dgInt32* const dstIndices = data->m_globalFaceVertexIndex; dgInt32* const faceIndexCountArray = data->m_faceIndexCount; for (dgInt32 i = 0; (i < data->m_faceCount) && (faceIndexCount0 < (DG_MAX_COLLIDING_INDICES - 32)); i++) { dgInt32 indexCount = faceIndexCountArray[i]; const dgInt32* const indexArray = &srcIndices[faceIndexCount1]; dgInt32 normalIndex = data->GetNormalIndex(indexArray, indexCount); dgVector faceNormal(&vertex[normalIndex * stride]); faceNormal = faceNormal & dgVector::m_triplexMask; dgFloat32 dist = data->PolygonBoxDistance(faceNormal, indexCount, indexArray, stride, vertex); const dgInt32 faceIndexCount = data->GetFaceIndexCount(indexCount); if (dist > dgFloat32(0.0f)) { hitDistance[faceCount0] = dist; address[faceCount0] = faceIndexCount0; faceIndexCountArray[faceCount0] = indexCount; memcpy(&dstIndices[faceIndexCount0], indexArray, faceIndexCount * sizeof(dgInt32)); faceCount0++; faceIndexCount0 += faceIndexCount; } faceIndexCount1 += faceIndexCount; } data->m_faceCount = 0; if (faceCount0) { data->m_faceCount = faceCount0; data->m_faceIndexStart = address; data->m_hitDistance = hitDistance; data->m_faceVertexIndex = dstIndices; if (GetDebugCollisionCallback()) { dgTriplex triplex[32]; //const dgMatrix& matrix = data->m_polySoupInstance->GetGlobalMatrix(); const dgVector scale = data->m_polySoupInstance->GetScale(); dgMatrix matrix(data->m_polySoupInstance->GetLocalMatrix() * data->m_polySoupBody->GetMatrix()); for (dgInt32 i = 0; i < data->m_faceCount; i++) { dgInt32 base = address[i]; dgInt32 indexCount = faceIndexCountArray[i]; const dgInt32* const vertexFaceIndex = &data->m_faceVertexIndex[base]; for (dgInt32 j = 0; j < indexCount; j++) { dgInt32 index = vertexFaceIndex[j]; dgVector q(&vertex[index * stride]); q = q & dgVector::m_triplexMask; //dgVector p(matrix.TransformVector(scale * dgVector(&vertex[index * stride]))); dgVector p(matrix.TransformVector(scale * q)); triplex[j].m_x = p.m_x; triplex[j].m_y = p.m_y; triplex[j].m_z = p.m_z; } dgInt32 faceId = data->GetFaceId(vertexFaceIndex, indexCount); GetDebugCollisionCallback() (data->m_polySoupBody, data->m_objBody, faceId, indexCount, &triplex[0].m_x, sizeof(dgTriplex)); } } } } void dgCollisionUserMesh::GetCollidingFaces (dgPolygonMeshDesc* const data) const { if (m_collideCallback) { if (data->m_doContinuesCollisionTest) { GetCollidingFacesContinue(data); } else { GetCollidingFacesDescrete(data); } } } void dgCollisionUserMesh::DebugCollision (const dgMatrix& matrixPtr, dgCollision::OnDebugCollisionMeshCallback callback, void* const userData) const { /* dgCollisionUserMeshShowPolyContext context; context.m_matrix = matrixPtr; context.m_userData = userData;; context.m_callback = callback; dgVector p0 (dgFloat32 (-1.0e20f), dgFloat32 (-1.0e20f), dgFloat32 (-1.0e20f), dgFloat32 (0.0f)); dgVector p1 (dgFloat32 ( 1.0e20f), dgFloat32 ( 1.0e20f), dgFloat32 ( 1.0e20f), dgFloat32 (0.0f)); ForAllSectors (p0, p1, ShowDebugPolygon, &context); */ }
be77fbcc4d556453dfe00b031d3813ea86cfe1f6
76382e22455dc10da2c85068d93bcb139a062f26
/src/net/NetSocket.h
7cbbbd8d3c65b1f32f051cf641ee5342d06d6bac
[ "Apache-2.0" ]
permissive
levyhoo/netwb
14522217f88d0e5fcbe044230f6a9a9be69529e5
2d00398ca5b8cd69e94e986822b98733b3780d57
refs/heads/master
2016-08-06T05:19:22.670597
2015-08-26T09:48:18
2015-08-26T09:48:18
40,540,732
0
0
null
null
null
null
UTF-8
C++
false
false
6,615
h
NetSocket.h
#ifndef _ISocket_2013_5_28_h__ #define _ISocket_2013_5_28_h__ #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> #include "net/ProxyInfo.h" #include <net/NetCommon.h> namespace net { class DLL_EXPORT_NET NetSocket : public boost::enable_shared_from_this<NetSocket> { public: static SocketPtr makeComonSocket(net::StrandPtr strand); static SocketPtr makeSslSocket(net::StrandPtr strand, boost::asio::ssl::context& context); virtual void cancel(boost::system::error_code& error) = 0; virtual void close(boost::system::error_code& error) = 0; virtual boost::system::error_code shutdown(const boost::asio::socket_base::shutdown_type what, boost::system::error_code& ec) = 0; virtual void async_read_some(void* p, size_t len, const boost::function<void (const boost::system::error_code& error, size_t)>& callback) = 0; virtual void async_write(void* p, size_t len, const boost::function<void (const boost::system::error_code& error, size_t)>& callback) = 0; virtual void async_connect(const ProxyInfo& proxy, string serverIp, int port, const boost::function<void (const boost::system::error_code& error)>& callback) = 0; virtual void connect(const ProxyInfo& proxy, string serverIp, int port, boost::system::error_code& error) = 0; virtual void write(void* p, size_t len) = 0; virtual boost::asio::ip::tcp::endpoint local_endpoint() = 0; virtual boost::asio::ip::tcp::endpoint remote_endpoint() = 0; virtual boost::asio::ip::tcp::socket& getSocket() = 0; virtual size_t read_some(void* p, size_t len, boost::system::error_code& error) = 0; protected: private: }; template <typename SocketType> class TSocket : public NetSocket { typedef boost::shared_ptr<SocketType> SocketTypePtr; public: TSocket(){}; virtual ~TSocket(){}; virtual void cancel(boost::system::error_code& error) { getSocket().cancel(error); }; virtual void close(boost::system::error_code& error) { getSocket().close(error); }; virtual boost::system::error_code shutdown(const boost::asio::socket_base::shutdown_type what, boost::system::error_code& ec) { return getSocket().shutdown(what, ec); }; virtual void async_read_some(void* p, size_t len, const boost::function<void (const boost::system::error_code& error, size_t)>& callback) { m_socket->async_read_some(boost::asio::buffer(p, len), callback); }; virtual void async_write(void* p, size_t len, const boost::function<void (const boost::system::error_code& error, size_t)>& callback) { boost::asio::async_write(*m_socket, boost::asio::buffer(p, len), callback); }; virtual void write(void* p, size_t len) { boost::asio::write(*m_socket, boost::asio::buffer(p, len)); }; virtual boost::asio::ip::tcp::endpoint local_endpoint() { return getSocket().local_endpoint(); }; virtual boost::asio::ip::tcp::endpoint remote_endpoint() { return getSocket().remote_endpoint(); }; virtual size_t read_some(void* p, size_t len, boost::system::error_code& error) { return m_socket->read_some(boost::asio::buffer(p, len), error); }; protected: SocketTypePtr m_socket; }; class DLL_EXPORT_NET CommonSocket : public TSocket<boost::asio::ip::tcp::socket> { public: CommonSocket(net::StrandPtr strand) { m_socket = boost::shared_ptr<boost::asio::ip::tcp::socket>(new boost::asio::ip::tcp::socket(strand->get_io_service())); m_resolver = boost::shared_ptr<boost::asio::ip::tcp::resolver>(new boost::asio::ip::tcp::resolver(strand->get_io_service())); }; ~CommonSocket(){ if (NULL != m_socket) { boost::system::error_code error; m_socket->close(error); } }; virtual boost::asio::ip::tcp::socket& getSocket() { return *m_socket; }; virtual void async_connect(const ProxyInfo& proxy, string serverIp, int port, const boost::function<void (const boost::system::error_code& error)>& callback) ; virtual void connect(const ProxyInfo& proxy, string serverIp, int port, boost::system::error_code& error) ; protected: void on_resolve_handler(const boost::system::error_code& error, boost::asio::ip::tcp::resolver::iterator iter, const boost::function<void (const boost::system::error_code& error)>& callback); private: boost::shared_ptr<boost::asio::ip::tcp::resolver> m_resolver; }; typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> ssl_socket; class DLL_EXPORT_NET SSLSocket: public TSocket<ssl_socket> { public: SSLSocket(net::StrandPtr strand, boost::asio::ssl::context& context) { m_socket = boost::shared_ptr<ssl_socket>(new ssl_socket(strand->get_io_service(), context)); }; ~SSLSocket(){ if (NULL != m_socket) { boost::system::error_code error; close(error); } }; virtual boost::asio::ip::tcp::socket& getSocket() { return m_socket->next_layer(); }; virtual void async_connect(const ProxyInfo& proxy, string serverIp, int port, const boost::function<void (const boost::system::error_code& error)>& callback) ; virtual void connect(const ProxyInfo& proxy, string serverIp, int port, boost::system::error_code& error) ; boost::shared_ptr<ssl_socket> getSSL() { return m_socket; }; protected: void doAfterConnect(const boost::function<void (const boost::system::error_code& error)>& callback); void handleConnect(const boost::system::error_code& error, const boost::function<void (const boost::system::error_code& error)>& callback); void handleShake(const boost::system::error_code& error, const boost::function<void (const boost::system::error_code& error)>& callback); private: }; void onResolveConnect(boost::asio::ip::tcp::socket& socket, boost::asio::ip::tcp::resolver::iterator& endpoint_iterator, const boost::system::error_code& error, const boost::function<void (const boost::system::error_code& error)>& callback); } #endif // ISocket_h__
a142cd6ec18140589821f08b8cda665c9ae09ca4
a07d4ef7d9edc7d1cc43dfd7b612f5f0161b7bd7
/include/quickmsg/quickmsg_java.hpp
816617ed0f1cca3d2779b221bc5c00bffcac07b1
[]
no_license
jlowenz/quickmsg
753d5dc219457885ffa403fa89a59894329e2f6e
ba1acaef6f0865655130bcf983c2cfdb4ba7fe46
refs/heads/master
2020-12-24T05:53:16.168451
2018-09-19T19:13:09
2018-09-19T19:13:09
32,294,359
4
7
null
2018-09-19T19:13:10
2015-03-16T01:34:10
C++
UTF-8
C++
false
false
212
hpp
quickmsg_java.hpp
#ifndef JAVA_QUICKMSG_HPP #define JAVA_QUICKMSG_HPP #include <jni.h> struct java_cb_data { JNIEnv* env; jobject obj; bool init_thread; java_cb_data() : env(NULL), init_thread(false) {} }; #endif
9611fb7121342466317a6ed383fae49cd84e6d28
72135b4340c4ae0d922b3ddff5e0c0c32b39cb70
/oceandemo/Camera.h
7a9a118840502f53489dcd676de6fb088be6fd3d
[]
no_license
rioki/oceandemo
ab03bdff58ed0d69a75a33612ae07de9fd6978ef
2cfa76b379f609a8c6f34980062658ba99f79714
refs/heads/master
2020-06-03T10:58:06.036550
2014-12-17T19:19:46
2014-12-17T19:19:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
762
h
Camera.h
#ifndef _OD_CAMERA_H_ #define _OD_CAMERA_H_ #include <rgm/rgm.h> #include "Entity.h" namespace od { class Shader; class Camera : public Entity { public: Camera(); ~Camera(); void set_fov(float value); float get_fov() const; void set_aspect(float value); float get_aspect() const; void set_near(float value); float get_near() const; void set_far(float value); float get_far() const; rgm::mat4 get_projection() const; rgm::mat4 get_view() const; void setup(const Shader& shader) const; private: float fov; float aspect; float near; float far; }; } #endif
f20bffe5e75d14e93f30ebc4bf0fea09f1645fa9
ab253052e141e9f6e5dcd6c031315bc311ed86dc
/ShaderBasics/Scene.h
6e25c5da724269f913d802969ec9219d8c267159
[]
no_license
0xdeadcat-uni-stuff/cg_sem6_sha12_lab
4f592da9e5316048fb34d6a53ee0602d70959969
cc9209ae50b4406abca42c39cb490ef656724c97
refs/heads/master
2023-03-30T00:00:07.916699
2021-03-19T17:02:57
2021-03-19T17:02:57
348,511,465
0
0
null
null
null
null
UTF-8
C++
false
false
1,807
h
Scene.h
#pragma once #include <gl/glew.h> #include <ctime> #include <chrono> #include "FragmentShader.h" #include "VertexShader.h" #include "SphereGPUProgram.h" template <class GProgram, class VGenerator> class Scene { private: std::chrono::system_clock::time_point t; std::chrono::system_clock::time_point tBegin; bool first = true; void updateTimers(); void updateGLState(); protected: float dT; float wT; GProgram program; VGenerator vGenerator; virtual void drawVertieces() = 0; virtual void addShaders() = 0; virtual void initializeScene() = 0; virtual void update() = 0; public: void init(); void frame(void); Scene(); ~Scene(); }; template <class GProgram, class VGenerator> void Scene<GProgram, VGenerator>::updateTimers() { std::chrono::system_clock::time_point tCurr = std::chrono::system_clock::now(); if (first) { t = tCurr; tBegin = tCurr; first = false; return; } wT = (float)std::chrono::duration_cast<std::chrono::microseconds>(tCurr - tBegin).count() / 1000000; dT = (float)std::chrono::duration_cast<std::chrono::microseconds>(tCurr - t).count() / 1000000; t = tCurr; } template <class GProgram, class VGenerator> void Scene<GProgram, VGenerator>::updateGLState() { glutSwapBuffers(); glutPostRedisplay(); } template <class GProgram, class VGenerator> void Scene<GProgram, VGenerator>::init() { GLenum err = glewInit(); addShaders(); program.linkShaders(); program.bindVertieces(vGenerator, dT, wT); initializeScene(); } template <class GProgram, class VGenerator> void Scene<GProgram, VGenerator>::frame(void) { updateTimers(); update(); drawVertieces(); updateGLState(); } template <class GProgram, class VGenerator> Scene<GProgram, VGenerator>::Scene() { } template <class GProgram, class VGenerator> Scene<GProgram, VGenerator>::~Scene() { }
a9fc024958121cf75e2087bc02b7b9f5ed7a296a
165be8367f5753b03fae11430b1c3ebf48aa834a
/source/geometry/GeometryComputer.hpp
be1165a963e3465c8b576bc182f1a7874b5df37b
[ "Apache-2.0" ]
permissive
alibaba/MNN
f21b31e3c62d9ba1070c2e4e931fd9220611307c
c442ff39ec9a6a99c28bddd465d8074a7b5c1cca
refs/heads/master
2023-09-01T18:26:42.533902
2023-08-22T11:16:44
2023-08-22T11:16:44
181,436,799
8,383
1,789
null
2023-09-07T02:01:43
2019-04-15T07:40:18
C++
UTF-8
C++
false
false
3,393
hpp
GeometryComputer.hpp
// // GeometryComputer.hpp // MNN // // Created by MNN on 2020/04/01. // Copyright © 2018, Alibaba Group Holding Limited // #ifndef GeometryComputer_hpp #define GeometryComputer_hpp #include <map> #include <vector> #include "MNN_generated.h" #include "core/Command.hpp" #include "core/TensorUtils.hpp" #include "core/Backend.hpp" namespace MNN { class GeometryComputer { public: virtual ~GeometryComputer() { // Do nothing } class MNN_PUBLIC Context { public: Context(std::shared_ptr<Backend> allocBackend, MNNForwardType type = MNN_FORWARD_CPU, BackendConfig::PrecisionMode precision = BackendConfig::Precision_Normal); ~Context(); void clear(); void setBackend(Backend* backend); void getRasterCacheCreateRecursive(Tensor* src, CommandBuffer& cmd); // If has cache, return. Otherwise create cache const std::vector<std::shared_ptr<Tensor>>& searchConst(const Op* op); std::shared_ptr<Tensor> allocConst(const Op* key, const std::vector<int>& shape, halide_type_t type, Tensor::DimensionType dimType = Tensor::TENSORFLOW); bool allocTensor(Tensor* tenosr); inline MNNForwardType forwardType() const { return mForwardType; } inline BackendConfig::PrecisionMode precisionType() const { return mPrecision; } void pushCache(const CommandBuffer& buffer); std::shared_ptr<BufferStorage> mRasterOp; private: void getRasterCacheCreate(Tensor* src, CommandBuffer& cmd); std::map<const Op*, std::vector<std::shared_ptr<Tensor>>> mConstTensors; std::vector<std::shared_ptr<Tensor>> mEmpty; std::vector<std::shared_ptr<Tensor>> mTempConstTensors; std::shared_ptr<Backend> mBackend; MNNForwardType mForwardType; BackendConfig::PrecisionMode mPrecision; std::vector<SharedPtr<Command>> mRasterCmdCache; }; static void init(); MNN_PUBLIC static const GeometryComputer* search(int opType, Runtime::CompilerType compType); static void registerGeometryComputer(std::shared_ptr<GeometryComputer> comp, std::vector<int> type, Runtime::CompilerType compType = Runtime::Compiler_Geometry); virtual bool onCompute(const Op* op, const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs, Context& context, CommandBuffer& cmd) const = 0; virtual bool onRecompute(const Op* op, const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs, Context& context, CommandBuffer& cmd) const { return false; } }; class DefaultGeometryComputer : public GeometryComputer { public: DefaultGeometryComputer() { // Do nothing } virtual bool onRecompute(const Op* op, const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs, Context& context, CommandBuffer& cmd) const override; virtual bool onCompute(const Op* op, const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs, Context& context, CommandBuffer& cmd) const override; }; void registerGeometryOps(); #define REGISTER_GEOMETRY(f, c) \ extern void ___##f##__##c##__() { \ c(); \ } } // namespace MNN #endif
4ae6861e7375295aaba6e79c6bb09db9b76fa127
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/printscan/print/drivers/usermode/unidrv2/vector/hpgl2col/render/realize.cpp
bb014cbf3a0d96494909a70dac2b24c5fe307d54
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
43,194
cpp
realize.cpp
/////////////////////////////////////////////////////////// // // // Copyright (c) 1999-2001 Microsoft Corporation // All rights reserved. // // Module Name: // // realize.cpp // // Abstract: // // Implementation of Pen and Brush realization. // // Environment: // // Windows 2000 Unidrv driver // // Revision History: // ///////////////////////////////////////////////////// #include "hpgl2col.h" //Precompiled header file #define NT_SCREEN_RES 96 #define ULONG_MSB1 (0x80000000) //ULONG with first bit 1 // //Function Declaration // BOOL BGetNup( IN PDEVOBJ pdevobj, OUT LAYOUT * pLayoutNup ); ///////////////////////////////////////////////////////////////////////////// // BGetBitmapInfo // // Routine Description: // This function is used by raster.c and RealizeBrush. This is one of the // competing implementations to answer the question: what are the details // of the given bitmap? We automatically map 16bpp and 32bpp to 24bpp since // the xlateobj will actually convert the pixels when we output them. // // Arguments: // // sizlSrc - [in] dimensions of the bitmap // iBitmapFormat - the OS-defined bitmap format // pPCLPattern - [out] a structure which carries bitmap info to the caller // pulsrcBpp - [out] source bpp // puldestBpp - [out] destination bpp // // Return Value: // // TRUE if successful, FALSE if there is an error ///////////////////////////////////////////////////////////////////////////// BOOL BGetBitmapInfo( SIZEL *sizlSrc, ULONG iBitmapFormat, PCLPATTERN *pPCLPattern, PULONG pulsrcBpp, PULONG puldestBpp ) { ULONG ulWidth; // source width in pixels ULONG ulHeight; // source height in pixels ENTERING(BGetBitmapInfo); if(!pPCLPattern || !pulsrcBpp || !puldestBpp) return FALSE; ulWidth = sizlSrc->cx; ulHeight = sizlSrc->cy; pPCLPattern->iBitmapFormat = iBitmapFormat; switch ( iBitmapFormat ) { case BMF_1BPP: pPCLPattern->colorMappingEnum = HP_eIndexedPixel; *pulsrcBpp = 1; *puldestBpp = 1; break; case BMF_4BPP: pPCLPattern->colorMappingEnum = HP_eIndexedPixel; *pulsrcBpp = 4; *puldestBpp = 4; break; case BMF_4RLE: ERR(("BMF_4RLE is not supported yet\n")); return FALSE; case BMF_8RLE: case BMF_8BPP: pPCLPattern->colorMappingEnum = HP_eIndexedPixel; *pulsrcBpp = 8; *puldestBpp = 8; break; case BMF_16BPP: pPCLPattern->colorMappingEnum = HP_eDirectPixel; *pulsrcBpp = 16; *puldestBpp = 24; break; case BMF_24BPP: pPCLPattern->colorMappingEnum = HP_eDirectPixel; *pulsrcBpp = 24; *puldestBpp = 24; break; case BMF_32BPP: pPCLPattern->colorMappingEnum = HP_eDirectPixel; *pulsrcBpp = 32; *puldestBpp = 24; break; default: ERR(("BGetBitmapInfo -- Unsupported Bitmap type\n")); return FALSE; } EXITING(BGetBitmapInfo); return TRUE; } ///////////////////////////////////////////////////////////////////////////// // CheckXlateObj // // Routine Description: // This function check the XLATEOBJ provided and determined the translate // method. // // Arguments: // // pxlo - XLATEOBJ provided by the engine // srcBpp - Source bits per pixel // // Return Value: // // SCFlags with SC_XXXX to identify the translation method and accel. ///////////////////////////////////////////////////////////////////////////// DWORD CheckXlateObj( XLATEOBJ *pxlo, DWORD srcBpp) { DWORD Ret; // // Only set the SC_XXX if has xlate object and source is 16bpp or greater // if ( (pxlo) && (srcBpp >= 16) ) { DWORD Dst[4]; // the result of Ret is as follows: // for 1,4,8 BPP ==> always 0 // for 16 BPP ==> always SC_XLATE // for 24, 32 BPP ==> 1. ( SC_XLATE | SC_IDENTITY ) if the translation result is the same // 2. (SC_XLATE | SC_SWAP_RB) if translation result has swapped RGB value // 3. SC_XLATE otherwise switch (srcBpp) { case 24: case 32: Ret = SC_XLATE; // // Translate all 4 bytes from the DWORD // Dst[0] = XLATEOBJ_iXlate(pxlo, 0x000000FF); Dst[1] = XLATEOBJ_iXlate(pxlo, 0x0000FF00); Dst[2] = XLATEOBJ_iXlate(pxlo, 0x00FF0000); Dst[3] = XLATEOBJ_iXlate(pxlo, 0xFF000000); // Verbose(("XlateDst: %08lx:%08lx:%08lx:%08lx\n", // Dst[0], Dst[1], Dst[2], Dst[3])); if ((Dst[0] == 0x000000FF) && (Dst[1] == 0x0000FF00) && (Dst[2] == 0x00FF0000) && (Dst[3] == 0x00000000)) { // // If translate result is same (4th byte will be zero) then // we done with it except if 32bpp then we have to skip one // source byte for every 3 bytes // Ret |= SC_IDENTITY; } else if ((Dst[0] == 0x00FF0000) && (Dst[1] == 0x0000FF00) && (Dst[2] == 0x000000FF) && (Dst[3] == 0x00000000)) { // // Simply swap the R and B component // Ret |= SC_SWAP_RB; } break; case 16: Ret = SC_XLATE; break; } // end of switch } // end of if ( (pxlo) && (srcBpp >= 16) ) else Ret = 0; return(Ret); } ///////////////////////////////////////////////////////////////////////////// // XlateColor // // Routine Description: // This function will translate source color to our device RGB color space by // using pxlo with SCFlags. // // This function is called from raster.c and RealizeBrush // // Arguments: // // pbSrc - Pointer to the source color must 16/24/32 bpp (include bitfields) // pbDst - Translated device RGB buffer // pxlo - XLATEOBJ provided by the engine // SCFlags - The SOURCE COLOR flags, the flags is returned by CheckXlateObj // srcBpp - Bits per pixel of the source provided by the pbSrc // destBpp - Bits per pixel of the destination provided by the pbDst // cPels - Total Source pixels to be translated // // Return Value: // // None. ///////////////////////////////////////////////////////////////////////////// VOID XlateColor( LPBYTE pbSrc, LPBYTE pbDst, XLATEOBJ *pxlo, DWORD SCFlags, DWORD srcBpp, DWORD destBpp, DWORD cPels ) { ULONG srcColor; DW4B dw4b; //JM //dz DW4B dw4b; UINT SrcInc; LPBYTE pbTmpSrc = pbSrc; // avoid address of pbSrc getting changing when this rouitin terminates LPBYTE pbTmpDst = pbDst; // avoid address of pbDst getting changing when this rouitin terminates ASSERT( srcBpp == 16 || srcBpp == 24 || srcBpp == 32 ); SrcInc = (UINT)(srcBpp >> 3); if (SCFlags & SC_SWAP_RB) // for 24, 32 bpp only { // // Just swap first byte with third byte, and skip the source by // the SrcBpp // while (cPels--) { // dw4b.b4[0] = *(pbTmpSrc + 2); // dw4b.b4[1] = *(pbTmpSrc + 1); // dw4b.b4[2] = *(pbTmpSrc + 0); { *pbTmpDst++ = *(pbTmpSrc + 2); *pbTmpDst++ = *(pbTmpSrc + 1); *pbTmpDst++ = *pbTmpSrc; } pbTmpSrc += SrcInc; } } else if (SCFlags & SC_IDENTITY) // for 24, 32BPP with no change of value after translation { // // If no color translate for 32bpp is needed then we need to // remove 4th byte from the source // while (cPels--) { { *pbTmpDst++ = *pbTmpSrc; *pbTmpDst++ = *(pbTmpSrc+1); *pbTmpDst++ = *(pbTmpSrc+2); } pbTmpSrc += SrcInc;; } } //JM #if 0 else { // // At here only engine know how to translate 16, 24, 32 bpp color from the // source to our RGB format. (may be bitfields) // while (cPels--) { switch ( srcBpp ) { case 16: // // Translate every WORD (16 bits) to a 3 bytes RGB by calling engine // srcColor = *((PWORD)pbTmpSrc); break; case 24: srcColor = ((ULONG) pbTmpSrc[0]) | ((ULONG) pbTmpSrc[1] << 8) | ((ULONG) pbTmpSrc[2] << 16); break; case 32: srcColor = *((PULONG)pbTmpSrc); break; } dw4b.dw = XLATEOBJ_iXlate(pxlo, srcColor); pbTmpSrc += SrcInc; if (destBpp == 8) *pbTmpDst++ = RgbToGray(dw4b.b4[0], dw4b.b4[1], dw4b.b4[2]); else // 24 bits { *pbTmpDst++ = dw4b.b4[0]; *pbTmpDst++ = dw4b.b4[1]; *pbTmpDst++ = dw4b.b4[2]; } } // end of while (cPels--) } // JM #endif } ///////////////////////////////////////////////////////////////////////////// // StretchPCLPattern // // Routine Description: // This function copies the given pattern and stretches it by a factor of // 2. // // Arguments: // // pPattern - [out] destination pattern // psoPattern - [in] source pattern // // Return Value: // // BOOL: TRUE if successful, else FALSE. ///////////////////////////////////////////////////////////////////////////// BOOL StretchPCLPattern(PPCLPATTERN pPattern, SURFOBJ *psoPattern) { PBYTE pSrcRow; PBYTE pDstRow; int r, c; WORD w; BOOL bDupRow; int bit; if (!pPattern || !psoPattern) return FALSE; // // HACK ALERT!!! The bDupRow is a cheap toggle which allows me to write out // each row twice. When it's true rewrite the same source row to the next // target row. When it's false go on to the next row. Be sure to toggle it // on each row! // bDupRow = TRUE; pSrcRow = (PBYTE) psoPattern->pvScan0; pDstRow = pPattern->pBits; for (r = 0; r < psoPattern->sizlBitmap.cy; r++) { for (c = 0; c < psoPattern->sizlBitmap.cx; c++) { switch (psoPattern->iBitmapFormat) { case BMF_1BPP: w = 0; if (pSrcRow[0] != 0) // optimization: don't bother with 0 { for (bit = 7; bit >= 0; bit--) { w <<= 2; if (pSrcRow[c] & (0x01 << bit)) { w |= 0x0003; } } } pDstRow[(c * 2) + 0] = HIBYTE(w); pDstRow[(c * 2) + 1] = LOBYTE(w); break; case BMF_8BPP: pDstRow[(c * 2) + 0] = pSrcRow[c]; pDstRow[(c * 2) + 1] = pSrcRow[c]; break; default: // not supported! return FALSE; } } if (bDupRow) { r--; // don't count row--we want to dup it. } else { pSrcRow += psoPattern->lDelta; // only increment if we've already dup'ed } pDstRow += pPattern->lDelta; bDupRow = !bDupRow; } return TRUE; } ///////////////////////////////////////////////////////////////////////////// // HPGLRealizeBrush // // Routine Description: // Implementation of DDI entry point DrvRealizeBrush. // Please refer to DDK documentation for more details. // // Arguments: // // pbo - BRUSHOBJ to be realized // psoTarget - Defines the surface for which the brush is to be realized // psoPattern - Defines the pattern for the brush // psoMask - Transparency mask for the brush // pxlo - Defines the interpretration of colors in the pattern // iHatch - Specifies whether psoPattern is one of the hatch brushes // // Return Value: // // TRUE if successful, FALSE if there is an error ///////////////////////////////////////////////////////////////////////////// BOOL HPGLRealizeBrush( BRUSHOBJ *pbo, SURFOBJ *psoTarget, SURFOBJ *psoPattern, SURFOBJ *psoMask, XLATEOBJ *pxlo, ULONG iHatch ) { PBRUSHINFO pBrush; POEMPDEV poempdev; PDEVOBJ pdevobj; BRUSHTYPE BType = eBrushTypeNULL; ULONG ulFlags = 0; LAYOUT LayoutNup = ONE_UP; //default. BOOL retVal; TERSE(("HPGLRealizeBrush() entry.\r\n")); UNREFERENCED_PARAMETER(psoMask); pdevobj = (PDEVOBJ)psoTarget->dhpdev; ASSERT(VALID_PDEVOBJ(pdevobj)); poempdev = (POEMPDEV)pdevobj->pdevOEM; REQUIRE_VALID_DATA( (poempdev && pbo && psoTarget && psoPattern && pxlo), return FALSE ); DWORD *pdwColorTable = NULL; DWORD dwForeColor, dwBackColor, dwPatternID; if (pxlo) pdwColorTable = GET_COLOR_TABLE(pxlo); if (pdwColorTable) { // dwForeColor = pdwColorTable[0]; // dwBackColor = pdwColorTable[1]; dwForeColor = pdwColorTable[1]; dwBackColor = pdwColorTable[0]; } else { dwForeColor = BRUSHOBJ_ulGetBrushColor(pbo); dwBackColor = 0xFFFFFF; } // // Sometimes RealizeBrush gets called // with both the members of pxlo having the same color. In that case, instead // of downloading the pattern that GDI gives us, we can create a gray scale pattern // associated with that color. // (Used only for Monochrome Printers) // Q. Why is the new method better. Now we have to create a pattern too, // instead of just using one that GDI gave us. // A. In HPGL (monochrome) we cannot download the palette for the pattern. Pen 1 // is hardcoded to be black while Pen 0 is white. There is no way we can change // it. So if the pattern consists of 1's and 0's but both 1 and 0 represent the // the same color, monochrome printer will fail. 1's will appear as black and // 0's as white. In the new method, the color will be converted to a gray scale // pattern. // if ( !BIsColorPrinter(pdevobj) && (dwForeColor == dwBackColor) ) { pbo->iSolidColor = (ULONG)dwForeColor; } // // iHatch as received from GDI does not match the iHatch as expected // by PCL language. There are 2 major differences // 1. GDI's hatch pattern numbers start from 0 while those of PCL // start from 1. So we need to add 1 to GDI's iHatch. This is // done somewhere else in the code. // 2. // IN GDI : iHatch = 2 (2+1=3 for PCL)indicates forward diagnol // iHatch = 3 (3+1=4 for PCL)= backward diagnol // In PCL : iHatch = 3 = backward diagnol (lower left to top right) // iHatch = 4 = forward diagnol. (lower right to top left) // As can be seen above, the iHatch numbers for iHatch=2 and 3 should // be interchanged. // // Another interesting thing is that for n-up, the hatch brushes are not // rotated. i.e. A vertical line in a normal page (parallel to long edge) // still appears as vertical line on 2-up. i.e. it remains parallel to // long edge of the page. But on 2-up, since the image is rototated 90 degree // the line should now be drawn parallel to the short edge of the plane. // So lets do this adjustment here. // if ( BGetNup(pdevobj, &LayoutNup) && ( LayoutNup == TWO_UP || LayoutNup == SIX_UP ) ) { // // There are 6 types of hatch brushes (lets say 3 pairs) // a. HS_HORIZONTAL, HS_VERTICAL, // b. HS_FDIAGONAL, HS_BDIAGONAL // c. HS_CROSS, HS_DIAGCROSS // Only HS_HORIZONTAL, HS_VERTICAL needs to be interchanged. // HS_CROSS and HS_DIAGCROSS are same in any orientation. // HS_FDIAGONAL, HS_BDIAGONAL should be inverted but since GDI already // gives it inverted (in respect to PCL language, see point 2 above) // we dont need to invert it here. // if ( iHatch == HS_HORIZONTAL ) { iHatch = HS_VERTICAL; } else if ( iHatch == HS_VERTICAL ) { iHatch = HS_HORIZONTAL; } } else { if ( iHatch == HS_FDIAGONAL) //iHatch == 2 { iHatch = HS_BDIAGONAL; } else if ( iHatch == HS_BDIAGONAL) //iHatch == 3 { iHatch = HS_FDIAGONAL; } } // // Hack!!: If you do not want to support Hatch Brushes, simply set // iHatch a value greater than HS_DDI_MAX. // Then instead of using iHatch, we will use pboPattern. // (for further details look at the documentation of DrvRealizeBrush). // We can also selectively ignore iHatch for color or monochrome // printers or for any other conditions. // if (iHatch < HS_DDI_MAX) { if ( (dwBackColor != RGB_WHITE) || (!BIsColorPrinter(pdevobj) && dwForeColor != RGB_BLACK ) ) { // // Ignore iHatch if // a) If the background color is non-white. (Irrespective of whether // printer is color or monochrome. // b) If the printer is monochrome, then if the color of the HatchBrush // is non-black. (Because the limitation of PCL/HPGL does not // allow a dither pattern to be associated with a Hatch Brush. // By making Most Significant bit 1, we give a special meaning to HatchBrush. // We say, "Ok, it is a Hatch Brush but the MSB 1 indicates it needs // some special processing. // For functions that dont understand this special format, they think // the value of iHatch is greater than HS_DDI_MAX (HS_DDI_MAX = 6). // So they think this is not a hatch brush. That is exactly what we // want them to think. // iHatch |= ULONG_MSB1; //Make the first bit 1. } } else { // // Just so that iHatch does not have a random value. // iHatch = HS_DDI_MAX; } // // Check if there is the brush available. // If the return value is S_FALSE: means brush not available, so // it needs to be created. The new brush that we download should // get the value dwPatternID. // A value of S_OK means a brush that matches the pattern // has been created earlier, dwPatternID gives that pattern number. // For color printers, the brush consists of a pattern and a palette. // for mono, it is only the pattern since palette is understood to // be black and white. // So for color, the fact that pattern matches is half the job done, // a palette still needs to be created. We could have cached palettes // too, just like patterns, but that i will do in the next revision // of HP-GL/2. Now i dont have time. // LRESULT LResult = poempdev->pBrushCache->ReturnPatternID(pbo, iHatch, dwForeColor, psoPattern, BIsColorPrinter(pdevobj), poempdev->bStick, &dwPatternID, &BType); // // If S_OK is returned and the brush type is pattern and // the printer is a color printer, then we dont have to download // the pattern but still have to download the palette (as explained above). // if ( (LResult == S_OK) && (BType == eBrushTypePattern) && //Probably I dont need to do this. //hatch might also need palette. BIsColorPrinter(pdevobj) ) { retVal = BCreateNewBrush ( pbo, psoTarget, psoPattern, pxlo, iHatch, dwForeColor, dwPatternID); if ( retVal) { ((PBRUSHINFO)(pbo->pvRbrush))->ulFlags = VALID_PALETTE; } } else if (S_FALSE == LResult) { retVal = BCreateNewBrush ( pbo, psoTarget, psoPattern, pxlo, iHatch, dwForeColor, dwPatternID); if ( retVal && (BType == eBrushTypePattern) ) { if ( BIsColorPrinter(pdevobj) ) { ((PBRUSHINFO)(pbo->pvRbrush))->ulFlags = VALID_PATTERN | VALID_PALETTE; } else { ((PBRUSHINFO)(pbo->pvRbrush))->ulFlags = VALID_PATTERN; } } } else if (S_OK == LResult) { // // Do not need to download pattern. // Just pass ID or iHatch to the caller of BRUSHOBJ_pvGetRbrush; // if ( !(pBrush = (PBRUSHINFO)BRUSHOBJ_pvAllocRbrush(pbo, sizeof(BRUSHINFO)) ) ) { retVal = FALSE; } else { pBrush->Brush.iHatch = iHatch; pBrush->Brush.pPattern = NULL; pBrush->dwPatternID = dwPatternID; pBrush->bNeedToDownload = FALSE; pBrush->ulFlags = 0; //not to look at pattern or palette. Just ID is enough. retVal = TRUE; } } else { ERR(("BrushCach.ReturnPatternID failed.\n")); return FALSE; } return retVal; } /*++ Routine Description: Creates a New Brush. It allocates space using BRUSHOBJ_pvAllocBrush, populates it with appropriate values (depending on the type of brush). Note: The memory allocated here is released by GDI, so this function does not have to worry about releasing it. Arguments: pbo - The pointer to BRUSHOBJ psoTarget - The destination surface. psoPattern - The source surface. This has the brush. pxlo - The color translation table. iHatch - This is iHatch. The meaning of this iHatch is slightly different from the iHatch that we get in DrvRealizeBrush. In DrvRealizeBrush, if iHatch is less than HS_DDI_MAX, then this is one of the Hatch Brushes. In this function, it means the same. But in addition if iHatch's most significant bit is 1, then psoPattern should be used for realizing the brush, instead of iHatch. If this is the case, then this function does not scale the psoPattern as it does for normal non-iHatch brushes. dwForeColor - The foreground color of Hatch Brush. dwPatternId - The ID to be given to the brush when it is downloaded. This is also the id with which the pattern's information is stored in the brush cache. Return Value: TRUE if function succeeds. FALSE otherwise. Author: hsingh --*/ BOOL BCreateNewBrush ( IN BRUSHOBJ *pbo, IN SURFOBJ *psoTarget, IN SURFOBJ *psoPattern, IN XLATEOBJ *pxlo, IN LONG iHatch, IN DWORD dwForeColor, IN DWORD dwPatternID) { BOOL bProxyDataUsed = FALSE; BOOL bReverseImage = FALSE; BOOL bRetVal = TRUE; PDEVOBJ pdevobj = NULL; HPGL2BRUSH HPGL2Brush; BOOL bExpandImage; RASTER_DATA srcImage; PALETTE srcPalette; PRASTER_DATA pSrcImage = &srcImage; PPALETTE pSrcPalette = NULL; PPATTERN_DATA pDstPattern = NULL; PRASTER_DATA pDstImage = NULL; PPALETTE pDstPalette = NULL; POEMPDEV poempdev; PBRUSHINFO pBrush = NULL; BOOL bDownloadAsHPGL = FALSE; //i.e. by default download as PCL EIMTYPE eImType = kUNKNOWN; // // Valid input parameters // REQUIRE_VALID_DATA( (pbo && psoTarget && psoPattern && pxlo), return FALSE ); pdevobj = (PDEVOBJ)psoTarget->dhpdev; REQUIRE_VALID_DATA( pdevobj, return FALSE ); poempdev = (POEMPDEV)pdevobj->pdevOEM; REQUIRE_VALID_DATA( poempdev, return FALSE ); // // When ReturnPatternID was called, the metadata regarding the new brush was // in the brush cache. i.e. the type of brush. The actual contents of brush were not // stored. Here, we get that metadata and depending on that, we procede. // if (S_OK != poempdev->pBrushCache->GetHPGL2BRUSH(dwPatternID, &HPGL2Brush)) { // // This failure is fatal, cos the cache has to have the metadata stored. // return FALSE; } // // Now the new brush has to be created. How it is created depends on // 1. Whether the printer is color or monochrome and // 2. What is the type of the brush i.e. Patter, Solid or Hatch. // if (HPGL2Brush.BType == eBrushTypePattern) { SURFOBJ *psoHT = NULL; HBITMAP hBmpHT = NULL; ULONG ulDeviceRes = HPGL_GetDeviceResolution(pdevobj); DWORD dwBrushExpansionFactor = 1; //Initialize to 1 i.e. no expansion. DWORD dwBrushCompressionFactor = 1; //Initialize to 1 i.e. dont compress VERBOSE(("RealizeBrush: eBrushTypePattern.\n")); // // In case we are doing n-up, we have to compress the brush // accordingly. // if ( (dwBrushCompressionFactor = poempdev->ulNupCompr) == 0) { WARNING(("N-up with value zero recieved. . Assuming nup to be 1 and continuing.\n")); dwBrushCompressionFactor = 1; } if ( ( iHatch & ULONG_MSB1 ) && ( (iHatch & (ULONG_MSB1-1)) < HS_DDI_MAX) ) { // // If the MSB of iHatch is 1, // eImType = kHATCHBRUSHPATTERN; } // // Logic behind dwBrushExpansionFactor. // GDI does not scale brushes in accordance with printer resolution. // So the driver has to do the job. Postscript assumes that GDI patterns // are meant for 150 dpi printer (this assumption may fail if an app // scales patterns according to printer resolution but I dont know // of any such app). So when printing to 600 dpi there are 2 ways of handling // this problem 1) Scale the pattern in the driver so that printer does not // have to do anything or 2) Have the printer do the scaling. // When pattern is downloaded as HPGL, we have to go with option 1 since // there is no way to tell HPGL the pattern dpi. i.e. When printing to // 600 dpi printer in HPGL mode the pattern has to be scaled 4 times. // When pattern is downloaded as PCL we are in a little bit better position. // PCL expects the pattern to be correct for 300 dpi. If we are printing // to 600 dpi printer, the printer automatically scales up the pattern. // // NOTE : if eImType == kHATCHBRUSHPATTERN, we do not scale the brush. // if (ulDeviceRes >= DPI_600 && eImType != kHATCHBRUSHPATTERN) { // // For 600 dpi, we need the atleast double the size of the // brush. We may need to quadruple it if we are printing as HPGL. // That will be checked a little down in the code. // dwBrushExpansionFactor = 2; } // // Now the Brush type is pattern. We have to take out the information // of the pattern that is stored in psoPattern and put it into // pBrush->Brush.pPattern. // Color printers can handle the color data from the image easily. // But monochrome printers need a 1bpp image. If the image is // not 1bpp and we are printing to monochrome printers, the image // has to be halftoned to monochrome. // What happens if the image is 1bpp, but it is not black and white. // Do we still have to halftone? hmmm, Yes and No. // Ideally, we should. If there are two patterns that are exactly // the same but the color is different, if we dont halftone them, // they will print exactly the same. This is not correct. But // when I tried to halftone, the output was horrible, so we // are better off without it. // But in one case, output of halftoning is acceptable. // Thats when the psoPattern represent a hatch brush. // Note : in this case, the hatch brush is not scaled. // Whatever GDI gives us, we just print it. // if ( BIsColorPrinter (pdevobj) || ( psoPattern->iBitmapFormat == BMF_1BPP && eImType != kHATCHBRUSHPATTERN ) ) { // // Get the source image data from the surface object // if (!InitRasterDataFromSURFOBJ(&srcImage, psoPattern, FALSE)) { bRetVal = FALSE; } } else { // // For monochrome, we need to halftone the brush. // The halftoned image is stored in psoHT. // if ( !bCreateHTImage(&srcImage, psoTarget, // psoDst, psoPattern, // psoSrc, &psoHT, &hBmpHT, pxlo, iHatch) ) { bRetVal = FALSE; } } // // For color printers some special processing is required depending on // the pxlo. // // // Get the source palette data from the translate object // If a direct image is passed in we will create a proxy of that image which // is translated to an indexed palette. Don't forget to clean up! // // ASSERT(pxlo->cEntries <= MAX_PALETTE_ENTRIES); if ( bRetVal && BIsColorPrinter (pdevobj) ) { if ((!InitPaletteFromXLATEOBJ(&srcPalette, pxlo)) || (srcPalette.cEntries == 0) || (srcImage.eColorMap == HP_eDirectPixel)) { bProxyDataUsed = TRUE; pSrcPalette = CreateIndexedPaletteFromImage(&srcImage); pSrcImage = CreateIndexedImageFromDirect(&srcImage, pSrcPalette); TranslatePalette(pSrcPalette, pSrcImage, pxlo); } else { bProxyDataUsed = FALSE; pSrcImage = &srcImage; pSrcPalette = &srcPalette; } if (pSrcImage == NULL || pSrcPalette == NULL) { bRetVal = FALSE; } } // // Now we have all the information we need (the image, the palette etc...) // Now // 1. allocate space for the brush (=image) using BRUSHOBJ_pvAllocRbrush. // 2. Initialize the header values (i.e. type of image, its size, its location // in memory). // 3. Then copy the image from pSrcImage to the brush. // // // CreateCompatiblePatternBrush does 1 and 2 and returns the pointer to // the memory it allocated. // if ( bRetVal) { // // Lets decide here whether to download the pattern as HPGL or PCL. // PCL patterns are generally smaller, so the output file size is small. // But it may take a cost to switch the printer from HPGL to PCL mode // // If the pattern represents a hatch brush, then we download // as HPGL and dont scale it. The way PCL downloading is implemented // now, patterns are scaled to 300dpi. The firmware is told that pattern is // is at 300dpi, so it expands it to 600dpi. But in this case, we dont // want hatch brush to be scaled. So we download as HPGL. // I could also change the PCL downloading so that it does not scale. // but that will mean testing lots of stuff. I am afraid to do it at // this late stage. // ERenderLanguage eRendLang = eUNKNOWN; if ( eImType == kHATCHBRUSHPATTERN ) { bDownloadAsHPGL = TRUE; } else if (BWhichLangToDwnldBrush(pdevobj, pSrcImage, &eRendLang) ) { if ( eRendLang == eHPGL ) { bDownloadAsHPGL = TRUE; // // The exact same pattern downloaded as HPGL appears smaller // on paper than when it is downloaded as HPGL. So it has // to be expanded // dwBrushExpansionFactor *= 2; } } // else if BWhichLangToDwnldBrush fails or eRendLang != HPGL, then we // we download as PCL. // // Now lets do the calculation to find out how much to expand // the brush. Either the brush is expanded, or left just like it is. // It is not compressed. // dwBrushExpansionFactor /= dwBrushCompressionFactor; if ( dwBrushExpansionFactor < 1 ) { dwBrushExpansionFactor = 1; } if ( (pBrush = CreateCompatiblePatternBrush(pbo, pSrcImage, pSrcPalette, dwBrushExpansionFactor, psoPattern->iUniq, iHatch) ) ) { // // Retrieve the interesting parts of the brush into convenience variables // pDstPattern = (PPATTERN_DATA)pBrush->Brush.pPattern; pDstImage = &pDstPattern->image; pDstPalette = &pDstPattern->palette; pDstPattern->eRendLang = bDownloadAsHPGL ? eHPGL : ePCL; } else { bRetVal = FALSE; } } // // The palette is associated only with color printers. // Monochrome printers accept only 1bpp images, and the palette consists // only of white color. So we dont explicitly need to have a // a palette for them. We could choose to have one to specify whether // a bit set to 1 is black or white and viceversa. In RGB format, // GDI gives us image in which 1 is white and 0 is black. We know this // so no need for palette. // For color printers printing 1bpp images, we will still want to have // a palette, because the 1bpp does not definitely mean black and white. // Could be red and white or any 2 colors. // if ( bRetVal && BIsColorPrinter(pdevobj) && !CopyPalette(pDstPalette, pSrcPalette)) { bRetVal = FALSE; } if ( bRetVal ) { // // Monochrome printers accept 1 as black and 0 white, which is the reverse // of the format GDI gives. So we might need to reverse the image before // copying it into brush. Make sure by looking at pxlo. // if ( !BIsColorPrinter (pdevobj) ) { // // First check if pxlo has any color information. If the image // is monochrome && pxlo is empty, then the image // needs to be inverted (This was found by using DTH5_LET.XLS printing // through Excel 5). If pxlo has no color information, // BImageNeedsInversion returns FALSE (i.e. image should not be // inverted). This is reverse of what we want. // Note : BImageNeedsInversion() is used for some other code paths // in which empty pxlo means inversion not required. But in the case // of monochrome brush, empty pxlo means image needs inverted. // if ( (pxlo == NULL ) || (pxlo->pulXlate == NULL ) || BImageNeedsInversion(pdevobj, (ULONG)pSrcImage->colorDepth , pxlo) ) { bReverseImage = TRUE; } } if (dwBrushExpansionFactor > 1) { if (!StretchCopyImage(pDstImage, pSrcImage, pxlo, dwBrushExpansionFactor, bReverseImage)) { bRetVal = FALSE; } } else { if (!CopyRasterImage(pDstImage, pSrcImage, pxlo, bReverseImage)) { bRetVal = FALSE; } } } // // Free the shadows surface created in call to bCreateHTImage. // if ( hBmpHT != NULL ) { DELETE_SURFOBJ(&psoHT, &hBmpHT); } } else if (HPGL2Brush.BType == eBrushTypeSolid || HPGL2Brush.BType == eBrushTypeHatch) { VERBOSE(("RealizeBrush: eBrushTypeSolid or eBrushTypeHatch.\n")); // // Hatch Brushes also have color. So Hatch Brushes are // SolidBrushes + HatchInfo // if ( (pBrush = (PBRUSHINFO)BRUSHOBJ_pvAllocRbrush(pbo, sizeof(BRUSHINFO))) ) { ZeroMemory(pBrush, sizeof(BRUSHINFO) ); pbo->pvRbrush = pBrush; } else { bRetVal = FALSE; } // // Initially I was realizing brush here (for monochrome printers). // But now all solid brush // realization takes place in CreateAndDwnldSolidBrushForMono() // if ( bRetVal && HPGL2Brush.BType == eBrushTypeHatch) { pBrush->Brush.iHatch = iHatch; } } else { ERR(("HPGLRealizeBrush : Unknown Brush Type: Cannot RealizeBrush\n")); bRetVal = FALSE; } if ( bRetVal ) { pBrush->dwPatternID = dwPatternID; pBrush->bNeedToDownload = TRUE; (pBrush->Brush).dwRGBColor = dwForeColor; bRetVal = TRUE; } if (bProxyDataUsed) { if ( pSrcImage ) { MemFree(pSrcImage); pSrcImage = NULL; } if ( pSrcPalette ) { MemFree(pSrcPalette); pSrcPalette = NULL; } } return bRetVal; } BOOL BWhichLangToDwnldBrush( IN PDEVOBJ pdevobj, IN PRASTER_DATA pSrcImage, OUT ERenderLanguage *eRendLang) { if ( !pdevobj || !pSrcImage || !eRendLang) { return FALSE; } // // Download as PCL only if // 1) Image is 1bpp or 8bpp. // - PCL downloading can only handle 1 or 8bpp (see PCL manual) // 2) Its size is bigger than 8*8. // - I have not done any tests to see which is the size where downloading // as PCL becomes better than HPGL. But conventional wisdom states that // the bigger the size, the more the benefit, so lets go for 8*8 now. // if ( (pSrcImage->colorDepth == 1 || pSrcImage->colorDepth == 8) && pSrcImage->size.cx * pSrcImage->size.cy > 64 ) { *eRendLang = ePCL; } else { *eRendLang = eHPGL; } return TRUE; } /*++ Routine Name ULGetNup Routine Description: Gets the n=up value from the unidrv's devmode. Arguments: pdevobj - The pointer to this device's PDEVOBJ pLayout - The buffer that will receive the n-up number. LAYOUT is defined in usermode\inc\devmode.h as an enum. Return Value: TRUE if function succeeds. FALSE otherwise. Author: hsingh --*/ BOOL BGetNup( IN PDEVOBJ pdevobj, OUT LAYOUT * pLayoutNup ) { REQUIRE_VALID_DATA(pdevobj && pLayoutNup, return FALSE); if ( ((PDEV *)pdevobj)->pdmPrivate ) { *pLayoutNup = ((PDEV *)pdevobj)->pdmPrivate->iLayout; return TRUE; } return FALSE; }
660df015e9aa6425a629183e19dec7eda496f18a
5ff0b928d9e93667c8f6c6c9796c3af015b87f81
/Boss (Code)/Game/GameLuaBindings/KeyboardBind.h
b458e30e296bb145c20177d548d470cfc1e6bd4f
[]
no_license
DodgeeSoftware/Boss-Project-MinGW-w64
1820671b8ba07c101de678269dc718646b962730
6b3bdfc576e67f557657273d2464b68b1e9569b2
refs/heads/master
2022-03-29T12:42:44.349220
2019-11-17T21:11:40
2019-11-17T21:11:40
222,312,722
1
0
null
null
null
null
UTF-8
C++
false
false
12,691
h
KeyboardBind.h
#ifndef __KEYBOARDBIND_H #define __KEYBOARDBIND_H // C/C++ Includes #include <string> // Lua extern "C" { #include "lua.h" #include "lualib.h" #include "lauxlib.h" } // LuaBridge #include <LuaBridge/LuaBridge.h> // GamePad #include "Keyboard.h" namespace LuaBinding { static void KeyboardBind(lua_State* pLuaState) { luabridge::getGlobalNamespace(pLuaState) // Keyboard Class .beginClass<Keyboard>("Keyboard") // TODO: Implement me .addConstructor <void (*)(void)>() .addFunction("isKeyPressed", (bool (Keyboard::*)(int)) &Keyboard::isKeyPressed) .addFunction("isKeyToggled", (bool (Keyboard::*)(int)) &Keyboard::isKeyToggled) .endClass(); // Globals luabridge::push(pLuaState, -1); lua_setglobal(pLuaState, "GLFW_KEY_UNKNOWN"); luabridge::push(pLuaState, 32); lua_setglobal(pLuaState, "GLFW_KEY_SPACE"); luabridge::push(pLuaState, 39); lua_setglobal(pLuaState, "GLFW_KEY_APOSTROPHE"); luabridge::push(pLuaState, 44); lua_setglobal(pLuaState, "GLFW_KEY_COMMA"); luabridge::push(pLuaState, 45); lua_setglobal(pLuaState, "GLFW_KEY_MINUS"); luabridge::push(pLuaState, 46); lua_setglobal(pLuaState, "GLFW_KEY_PERIOD"); luabridge::push(pLuaState, 47); lua_setglobal(pLuaState, "GLFW_KEY_SLASH"); luabridge::push(pLuaState, 48); lua_setglobal(pLuaState, "GLFW_KEY_0"); luabridge::push(pLuaState, 49); lua_setglobal(pLuaState, "GLFW_KEY_1"); luabridge::push(pLuaState, 50); lua_setglobal(pLuaState, "GLFW_KEY_2"); luabridge::push(pLuaState, 51); lua_setglobal(pLuaState, "GLFW_KEY_3"); luabridge::push(pLuaState, 52); lua_setglobal(pLuaState, "GLFW_KEY_4"); luabridge::push(pLuaState, 53); lua_setglobal(pLuaState, "GLFW_KEY_5"); luabridge::push(pLuaState, 54); lua_setglobal(pLuaState, "GLFW_KEY_6"); luabridge::push(pLuaState, 55); lua_setglobal(pLuaState, "GLFW_KEY_7"); luabridge::push(pLuaState, 56); lua_setglobal(pLuaState, "GLFW_KEY_8"); luabridge::push(pLuaState, 57); lua_setglobal(pLuaState, "GLFW_KEY_9"); luabridge::push(pLuaState, 59); lua_setglobal(pLuaState, "GLFW_KEY_SEMICOLON"); luabridge::push(pLuaState, 61); lua_setglobal(pLuaState, "GLFW_KEY_EQUAL"); luabridge::push(pLuaState, 65); lua_setglobal(pLuaState, "GLFW_KEY_A"); luabridge::push(pLuaState, 66); lua_setglobal(pLuaState, "GLFW_KEY_B"); luabridge::push(pLuaState, 67); lua_setglobal(pLuaState, "GLFW_KEY_C"); luabridge::push(pLuaState, 68); lua_setglobal(pLuaState, "GLFW_KEY_D"); luabridge::push(pLuaState, 69); lua_setglobal(pLuaState, "GLFW_KEY_E"); luabridge::push(pLuaState, 70); lua_setglobal(pLuaState, "GLFW_KEY_F"); luabridge::push(pLuaState, 71); lua_setglobal(pLuaState, "GLFW_KEY_G"); luabridge::push(pLuaState, 72); lua_setglobal(pLuaState, "GLFW_KEY_H"); luabridge::push(pLuaState, 73); lua_setglobal(pLuaState, "GLFW_KEY_I"); luabridge::push(pLuaState, 74); lua_setglobal(pLuaState, "GLFW_KEY_J"); luabridge::push(pLuaState, 75); lua_setglobal(pLuaState, "GLFW_KEY_K"); luabridge::push(pLuaState, 76); lua_setglobal(pLuaState, "GLFW_KEY_L"); luabridge::push(pLuaState, 77); lua_setglobal(pLuaState, "GLFW_KEY_M"); luabridge::push(pLuaState, 78); lua_setglobal(pLuaState, "GLFW_KEY_N"); luabridge::push(pLuaState, 79); lua_setglobal(pLuaState, "GLFW_KEY_O"); luabridge::push(pLuaState, 80); lua_setglobal(pLuaState, "GLFW_KEY_P"); luabridge::push(pLuaState, 81); lua_setglobal(pLuaState, "GLFW_KEY_Q"); luabridge::push(pLuaState, 82); lua_setglobal(pLuaState, "GLFW_KEY_R"); luabridge::push(pLuaState, 83); lua_setglobal(pLuaState, "GLFW_KEY_S"); luabridge::push(pLuaState, 84); lua_setglobal(pLuaState, "GLFW_KEY_T"); luabridge::push(pLuaState, 85); lua_setglobal(pLuaState, "GLFW_KEY_U"); luabridge::push(pLuaState, 86); lua_setglobal(pLuaState, "GLFW_KEY_V"); luabridge::push(pLuaState, 87); lua_setglobal(pLuaState, "GLFW_KEY_W"); luabridge::push(pLuaState, 88); lua_setglobal(pLuaState, "GLFW_KEY_X"); luabridge::push(pLuaState, 89); lua_setglobal(pLuaState, "GLFW_KEY_Y"); luabridge::push(pLuaState, 90); lua_setglobal(pLuaState, "GLFW_KEY_Z"); luabridge::push(pLuaState, 91); lua_setglobal(pLuaState, "GLFW_KEY_LEFT_BRACKET"); luabridge::push(pLuaState, 92); lua_setglobal(pLuaState, "GLFW_KEY_BACKSLASH"); luabridge::push(pLuaState, 93); lua_setglobal(pLuaState, "GLFW_KEY_RIGHT_BRACKET"); luabridge::push(pLuaState, 96); lua_setglobal(pLuaState, "GLFW_KEY_GRAVE_ACCENT"); luabridge::push(pLuaState, 161); lua_setglobal(pLuaState, "GLFW_KEY_WORLD_1"); luabridge::push(pLuaState, 162); lua_setglobal(pLuaState, "GLFW_KEY_WORLD_2"); luabridge::push(pLuaState, 256); lua_setglobal(pLuaState, "GLFW_KEY_ESCAPE"); luabridge::push(pLuaState, 257); lua_setglobal(pLuaState, "GLFW_KEY_ENTER"); luabridge::push(pLuaState, 258); lua_setglobal(pLuaState, "GLFW_KEY_TAB"); luabridge::push(pLuaState, 259); lua_setglobal(pLuaState, "GLFW_KEY_BACKSPACE"); luabridge::push(pLuaState, 260); lua_setglobal(pLuaState, "GLFW_KEY_INSERT"); luabridge::push(pLuaState, 261); lua_setglobal(pLuaState, "GLFW_KEY_DELETE"); luabridge::push(pLuaState, 262); lua_setglobal(pLuaState, "GLFW_KEY_RIGHT"); luabridge::push(pLuaState, 263); lua_setglobal(pLuaState, "GLFW_KEY_LEFT"); luabridge::push(pLuaState, 264); lua_setglobal(pLuaState, "GLFW_KEY_DOWN"); luabridge::push(pLuaState, 265); lua_setglobal(pLuaState, "GLFW_KEY_UP"); luabridge::push(pLuaState, 266); lua_setglobal(pLuaState, "GLFW_KEY_PAGE_UP"); luabridge::push(pLuaState, 267); lua_setglobal(pLuaState, "GLFW_KEY_PAGE_DOWN"); luabridge::push(pLuaState, 268); lua_setglobal(pLuaState, "GLFW_KEY_HOME"); luabridge::push(pLuaState, 269); lua_setglobal(pLuaState, "GLFW_KEY_END"); luabridge::push(pLuaState, 280); lua_setglobal(pLuaState, "GLFW_KEY_CAPS_LOCK"); luabridge::push(pLuaState, 281); lua_setglobal(pLuaState, "GLFW_KEY_SCROLL_LOCK"); luabridge::push(pLuaState, 282); lua_setglobal(pLuaState, "GLFW_KEY_NUM_LOCK"); luabridge::push(pLuaState, 283); lua_setglobal(pLuaState, "GLFW_KEY_PRINT_SCREEN"); luabridge::push(pLuaState, 284); lua_setglobal(pLuaState, "GLFW_KEY_PAUSE"); luabridge::push(pLuaState, 290); lua_setglobal(pLuaState, "GLFW_KEY_F1"); luabridge::push(pLuaState, 291); lua_setglobal(pLuaState, "GLFW_KEY_F2"); luabridge::push(pLuaState, 292); lua_setglobal(pLuaState, "GLFW_KEY_F3"); luabridge::push(pLuaState, 293); lua_setglobal(pLuaState, "GLFW_KEY_F4"); luabridge::push(pLuaState, 294); lua_setglobal(pLuaState, "GLFW_KEY_F5"); luabridge::push(pLuaState, 295); lua_setglobal(pLuaState, "GLFW_KEY_F6"); luabridge::push(pLuaState, 296); lua_setglobal(pLuaState, "GLFW_KEY_F7"); luabridge::push(pLuaState, 297); lua_setglobal(pLuaState, "GLFW_KEY_F8"); luabridge::push(pLuaState, 298); lua_setglobal(pLuaState, "GLFW_KEY_F9"); luabridge::push(pLuaState, 299); lua_setglobal(pLuaState, "GLFW_KEY_F10"); luabridge::push(pLuaState, 300); lua_setglobal(pLuaState, "GLFW_KEY_F11"); luabridge::push(pLuaState, 301); lua_setglobal(pLuaState, "GLFW_KEY_F12"); luabridge::push(pLuaState, 302); lua_setglobal(pLuaState, "GLFW_KEY_F13"); luabridge::push(pLuaState, 303); lua_setglobal(pLuaState, "GLFW_KEY_F14"); luabridge::push(pLuaState, 304); lua_setglobal(pLuaState, "GLFW_KEY_F15"); luabridge::push(pLuaState, 305); lua_setglobal(pLuaState, "GLFW_KEY_F16"); luabridge::push(pLuaState, 306); lua_setglobal(pLuaState, "GLFW_KEY_F17"); luabridge::push(pLuaState, 307); lua_setglobal(pLuaState, "GLFW_KEY_F18"); luabridge::push(pLuaState, 308); lua_setglobal(pLuaState, "GLFW_KEY_F19"); luabridge::push(pLuaState, 309); lua_setglobal(pLuaState, "GLFW_KEY_F20"); luabridge::push(pLuaState, 310); lua_setglobal(pLuaState, "GLFW_KEY_F21"); luabridge::push(pLuaState, 311); lua_setglobal(pLuaState, "GLFW_KEY_F22"); luabridge::push(pLuaState, 312); lua_setglobal(pLuaState, "GLFW_KEY_F23"); luabridge::push(pLuaState, 313); lua_setglobal(pLuaState, "GLFW_KEY_F24"); luabridge::push(pLuaState, 314); lua_setglobal(pLuaState, "GLFW_KEY_F25"); luabridge::push(pLuaState, 320); lua_setglobal(pLuaState, "GLFW_KEY_KP_0"); luabridge::push(pLuaState, 321); lua_setglobal(pLuaState, "GLFW_KEY_KP_1"); luabridge::push(pLuaState, 322); lua_setglobal(pLuaState, "GLFW_KEY_KP_2"); luabridge::push(pLuaState, 323); lua_setglobal(pLuaState, "GLFW_KEY_KP_3"); luabridge::push(pLuaState, 324); lua_setglobal(pLuaState, "GLFW_KEY_KP_4"); luabridge::push(pLuaState, 325); lua_setglobal(pLuaState, "GLFW_KEY_KP_5"); luabridge::push(pLuaState, 326); lua_setglobal(pLuaState, "GLFW_KEY_KP_6"); luabridge::push(pLuaState, 327); lua_setglobal(pLuaState, "GLFW_KEY_KP_7"); luabridge::push(pLuaState, 328); lua_setglobal(pLuaState, "GLFW_KEY_KP_8"); luabridge::push(pLuaState, 329); lua_setglobal(pLuaState, "GLFW_KEY_KP_9"); luabridge::push(pLuaState, 330); lua_setglobal(pLuaState, "GLFW_KEY_KP_DECIMAL"); luabridge::push(pLuaState, 331); lua_setglobal(pLuaState, "GLFW_KEY_KP_DIVIDE"); luabridge::push(pLuaState, 332); lua_setglobal(pLuaState, "GLFW_KEY_KP_MULTIPLY"); luabridge::push(pLuaState, 333); lua_setglobal(pLuaState, "GLFW_KEY_KP_SUBTRACT"); luabridge::push(pLuaState, 334); lua_setglobal(pLuaState, "GLFW_KEY_KP_ADD"); luabridge::push(pLuaState, 335); lua_setglobal(pLuaState, "GLFW_KEY_KP_ENTER"); luabridge::push(pLuaState, 336); lua_setglobal(pLuaState, "GLFW_KEY_KP_EQUAL"); luabridge::push(pLuaState, 340); lua_setglobal(pLuaState, "GLFW_KEY_LEFT_SHIFT"); luabridge::push(pLuaState, 341); lua_setglobal(pLuaState, "GLFW_KEY_LEFT_CONTROL"); luabridge::push(pLuaState, 342); lua_setglobal(pLuaState, "GLFW_KEY_LEFT_ALT"); luabridge::push(pLuaState, 343); lua_setglobal(pLuaState, "GLFW_KEY_LEFT_SUPER"); luabridge::push(pLuaState, 344); lua_setglobal(pLuaState, "GLFW_KEY_RIGHT_SHIFT"); luabridge::push(pLuaState, 345); lua_setglobal(pLuaState, "GLFW_KEY_RIGHT_CONTROL"); luabridge::push(pLuaState, 346); lua_setglobal(pLuaState, "GLFW_KEY_RIGHT_ALT"); luabridge::push(pLuaState, 347); lua_setglobal(pLuaState, "GLFW_KEY_RIGHT_SUPER"); luabridge::push(pLuaState, 348); lua_setglobal(pLuaState, "GLFW_KEY_MENU"); luabridge::push(pLuaState, GLFW_KEY_MENU); lua_setglobal(pLuaState, "GLFW_KEY_MENU"); luabridge::push(pLuaState, 0x1); lua_setglobal(pLuaState, "GLFW_MOD_SHIFT"); luabridge::push(pLuaState, 0x2); lua_setglobal(pLuaState, "GLFW_MOD_CONTROL"); luabridge::push(pLuaState, 0x4); lua_setglobal(pLuaState, "GLFW_MOD_ALT"); luabridge::push(pLuaState, 0x8); lua_setglobal(pLuaState, "GLFW_MOD_ALT"); luabridge::push(pLuaState, 0); lua_setglobal(pLuaState, "GLFW_RELEASE"); luabridge::push(pLuaState, 1); lua_setglobal(pLuaState, "GLFW_PRESS"); luabridge::push(pLuaState, 2); lua_setglobal(pLuaState, "GLFW_REPEAT"); } } #endif // __KEYBOARDBIND_H
dc862d215257ef2fce9f89378da17e45cdbd31dd
c464b71b7936f4e0ddf9246992134a864dd02d64
/solidMechanicsTutorials/icoFsiElasticNonLinULSolidFoam/HronTurekFsi/fluid/0.2/solid/V0
96a1965260cd586bb965a2410181af79374deff0
[]
no_license
simuBT/foamyLatte
c11e69cb2e890e32e43e506934ccc31b40c4dc20
8f5263edb1b2ae92656ffb38437cc032eb8e4a53
refs/heads/master
2021-01-18T05:28:49.236551
2013-10-11T04:38:23
2013-10-11T04:38:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,892
V0
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM Extend Project: Open source CFD | | \\ / O peration | Version: 1.6-ext | | \\ / A nd | Web: www.extend-project.de | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField::DimensionedInternalField; location "0.2"; object V0; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 3 0 0 0 0 0]; value nonuniform List<scalar> 328 ( 2.53334e-07 2.53329e-07 2.53333e-07 2.53338e-07 2.71705e-07 2.71698e-07 2.71701e-07 2.71709e-07 2.91403e-07 2.91398e-07 2.91401e-07 2.91408e-07 3.12529e-07 3.12527e-07 3.12529e-07 3.12536e-07 3.35187e-07 3.35187e-07 3.35189e-07 3.35196e-07 3.59489e-07 3.5949e-07 3.59492e-07 3.59498e-07 3.85552e-07 3.85555e-07 3.85557e-07 3.85563e-07 4.13506e-07 4.1351e-07 4.13512e-07 4.13518e-07 4.43487e-07 4.43492e-07 4.43494e-07 4.435e-07 4.75641e-07 4.75647e-07 4.75649e-07 4.75655e-07 5.10127e-07 5.10133e-07 5.10136e-07 5.10143e-07 5.47114e-07 5.4712e-07 5.47123e-07 5.4713e-07 5.86782e-07 5.86789e-07 5.86792e-07 5.868e-07 6.29326e-07 6.29334e-07 6.29338e-07 6.29346e-07 6.74955e-07 6.74964e-07 6.74967e-07 6.74976e-07 7.23892e-07 7.23901e-07 7.23905e-07 7.23915e-07 7.76377e-07 7.76388e-07 7.76392e-07 7.76402e-07 8.32668e-07 8.32679e-07 8.32684e-07 8.32695e-07 8.9304e-07 8.93052e-07 8.93057e-07 8.93069e-07 9.57789e-07 9.57802e-07 9.57807e-07 9.5782e-07 1.02723e-06 1.02725e-06 1.02725e-06 1.02727e-06 1.10171e-06 1.10173e-06 1.10173e-06 1.10175e-06 1.26865e-06 1.26866e-06 1.26867e-06 1.26869e-06 1.26865e-06 1.26866e-06 1.26867e-06 1.26869e-06 1.26865e-06 1.26866e-06 1.26867e-06 1.26869e-06 1.26865e-06 1.26866e-06 1.26867e-06 1.26869e-06 1.26865e-06 1.26866e-06 1.26867e-06 1.26869e-06 1.26865e-06 1.26866e-06 1.26867e-06 1.26868e-06 1.26864e-06 1.26866e-06 1.26867e-06 1.26868e-06 1.26864e-06 1.26866e-06 1.26867e-06 1.26868e-06 1.26864e-06 1.26866e-06 1.26867e-06 1.26868e-06 1.26864e-06 1.26866e-06 1.26867e-06 1.26868e-06 1.26864e-06 1.26866e-06 1.26867e-06 1.26868e-06 1.26864e-06 1.26866e-06 1.26867e-06 1.26868e-06 1.26864e-06 1.26866e-06 1.26867e-06 1.26868e-06 1.26864e-06 1.26866e-06 1.26867e-06 1.26868e-06 1.26864e-06 1.26866e-06 1.26866e-06 1.26868e-06 1.26864e-06 1.26866e-06 1.26866e-06 1.26868e-06 1.26864e-06 1.26866e-06 1.26866e-06 1.26868e-06 1.26864e-06 1.26866e-06 1.26866e-06 1.26868e-06 1.26865e-06 1.26866e-06 1.26866e-06 1.26868e-06 1.26865e-06 1.26866e-06 1.26866e-06 1.26868e-06 1.26865e-06 1.26866e-06 1.26866e-06 1.26868e-06 1.26865e-06 1.26866e-06 1.26866e-06 1.26868e-06 1.26865e-06 1.26866e-06 1.26866e-06 1.26868e-06 1.26865e-06 1.26866e-06 1.26866e-06 1.26868e-06 1.26865e-06 1.26866e-06 1.26866e-06 1.26868e-06 1.26865e-06 1.26866e-06 1.26866e-06 1.26868e-06 1.26865e-06 1.26866e-06 1.26866e-06 1.26868e-06 1.26865e-06 1.26866e-06 1.26866e-06 1.26868e-06 1.26865e-06 1.26866e-06 1.26866e-06 1.26868e-06 1.26865e-06 1.26866e-06 1.26866e-06 1.26867e-06 1.26865e-06 1.26866e-06 1.26866e-06 1.26867e-06 1.26865e-06 1.26866e-06 1.26867e-06 1.26867e-06 1.26865e-06 1.26866e-06 1.26867e-06 1.26867e-06 1.26865e-06 1.26866e-06 1.26867e-06 1.26867e-06 1.26865e-06 1.26866e-06 1.26867e-06 1.26867e-06 1.26865e-06 1.26866e-06 1.26867e-06 1.26867e-06 1.26866e-06 1.26866e-06 1.26867e-06 1.26867e-06 1.26866e-06 1.26866e-06 1.26867e-06 1.26867e-06 1.26866e-06 1.26866e-06 1.26867e-06 1.26867e-06 1.26866e-06 1.26866e-06 1.26867e-06 1.26867e-06 1.26866e-06 1.26866e-06 1.26867e-06 1.26867e-06 1.26866e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26866e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26866e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26866e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26866e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26867e-06 1.26868e-06 1.26868e-06 1.26868e-06 1.26868e-06 1.26868e-06 1.26868e-06 1.26868e-06 1.26868e-06 1.26867e-06 1.26867e-06 1.26868e-06 1.26868e-06 1.26867e-06 1.26867e-06 1.26868e-06 ) ; // ************************************************************************* //
a84e68ba8e9057da440047e90ac041e4a466c381
d15ae0d359bb794fc5718674caea50a7e8c4d753
/Darts_501/Darts_501/Level.h
787de18ac330c4fb233657be188bd75f9656ab45
[]
no_license
Fibonacci1664/Darts_501
c2e23b6239a133326ebe09b02a0ababa45e05f86
e9921c247f8dcc0c2f6b513633f131836c36a1d1
refs/heads/master
2021-04-14T03:47:15.951369
2020-04-07T12:31:13
2020-04-07T12:31:13
248,964,425
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
877
h
Level.h
/* * This is the 'Level' class and handles all things related to generating a window to display a checkout table: * * * Original @author D. Green. * * © D. Green. 2020. * */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma once // INCLUDES. #include <iostream> #include <SFML/Graphics.hpp> #include <string> /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class Level { public: // CONSTRUCTORS & DESTRUCTOR. Level(sf::RenderWindow* p_window); ~Level(); // MEMBER FUNCTIONS. void render(); private: // DATA MEMBERS. sf::RenderWindow* m_window; sf::Texture bgTexture; sf::RectangleShape rect; // MEMBER FUNCTIONS. void beginDraw(); void endDraw(); };
c499d716ab17dcea15ff71723a3bd1ccfeacba0b
5d1a033cf72f630688da2b8de788d1cebf6339e6
/Source/WebKit/mui/Api/WebError.cpp
679bda62970fa6b478d973331b0a20a622600362
[ "BSD-2-Clause" ]
permissive
jaokim/odyssey
e2115123f75df185fcda87452f455f25907b0c79
5ee0f826dd3502f04e077b3df59e3d855c7afd0c
refs/heads/kas1e_branch
2022-11-07T17:48:02.860664
2017-04-05T20:43:43
2017-04-05T20:43:43
55,713,581
2
1
null
2022-10-28T23:56:32
2016-04-07T17:17:09
C++
UTF-8
C++
false
false
3,249
cpp
WebError.cpp
/* * Copyright (C) 2008 Pleyo. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Pleyo 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 PLEYO AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL PLEYO OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "WebError.h" #include "HTTPHeaderPropertyBag.h" #include <wtf/text/CString.h> #include <wtf/text/WTFString.h> #include <ResourceError.h> using namespace WebCore; WebError::WebError(const ResourceError& error, HTTPHeaderPropertyBag* userInfo) : m_userInfo(userInfo) , m_error(const_cast<ResourceError*>(&error)) { } WebError::~WebError() { if(m_userInfo) delete m_userInfo; } WebError* WebError::createInstance(const ResourceError& error, HTTPHeaderPropertyBag* userInfo) { WebError* instance = new WebError(error, userInfo); return instance; } WebError* WebError::createInstance() { return createInstance(ResourceError()); } void WebError::init(const char* domain, int code, const char* url) { m_error = new ResourceError(domain, code, url, String()); } int WebError::code() { return m_error->errorCode(); } const char* WebError::domain() { return strdup(m_error->domain().utf8().data()); } const char* WebError::localizedDescription() { return strdup(m_error->localizedDescription().utf8().data()); } const char* WebError::localizedFailureReason() { return ""; } const char* WebError::localizedRecoverySuggestion() { return ""; } HTTPHeaderPropertyBag* WebError::userInfo() { return m_userInfo; } const char* WebError::failingURL() { return strdup(m_error->failingURL().utf8().data()); } bool WebError::isPolicyChangeError() { return m_error->domain() == String("WebKitErrorDomain") && m_error->errorCode() == WebKitErrorFrameLoadInterruptedByPolicyChange; } const ResourceError& WebError::resourceError() const { return *m_error; }
44fbc1180ad93a232551fe988373d4a9deab9be5
d144881a7a8f7cea08106436410901a89bb035f9
/NCT/Source/Allocators/NctStaticAlloc.h
6769fa535fae884368103f758ca15bbdb5588b7e
[]
no_license
XMatrixXiang/MiddleWare
0cf429cf3c38de0c175cb9964f4b07cc2cfbe38c
42ca224b1052090237fc56dae869cd44e7bd8926
refs/heads/master
2020-03-14T11:43:47.535221
2018-05-01T13:27:06
2018-05-01T13:27:06
131,596,432
0
0
null
null
null
null
GB18030
C++
false
false
5,355
h
NctStaticAlloc.h
/************************************************************************** ** Copyright (C) 2002-2018 北京捷安申谋军工科技有限公司, All Rights Reserved ** ** 文件名: NctStaticAlloc.h ** 创建者: 闫相伟 ** 创建日期:2018年4月27日 ** 详细信息:内存开辟 ** ** ***************************************************************************/ #pragma once #include "Prerequisites/NctPrerequisitesUtil.h" #include "Allocators/NctFreeAlloc.h" #include "Allocators/NctFrameAlloc.h" namespace Nct { template<int BlockSize = 512, class DynamicAllocator = TFrameAlloc<BlockSize>> class StaticAlloc { private: class MemBlock { public: MemBlock( std::uint8_t * data, std::uint32_t size) :mData(data), mSize(size) { } std::uint8_t* alloc(std::uint32_t amount) { std::uint8_t* freePtr = &mData[mFreePtr]; mFreePtr += amount; return freePtr; } void free(std::uint8_t* data, std::uint32_t allocSize) { if((data + allocSize) == (mData + mFreePtr)) mFreePtr -= allocSize; } void clear() { mFreePtr = 0; } std::uint8_t* mData = nullptr; std::uint32_t mFreePtr = 0; std::uint32_t mSize = 0; MemBlock* mNextBlock = nullptr; }; public: StaticAlloc() = default; ~StaticAlloc() = default; std::uint8_t* alloc(std::uint32_t amount) { if (amount == 0) return nullptr; std::uint32_t freeMem = BlockSize - mFreePtr; std::uint8_t* data; if (amount > freeMem) data = mDynamicAlloc.alloc(amount); else { data = &mStaticData[mFreePtr]; mFreePtr += amount; } return data; } void free(void* data, std::uint32_t allocSize) { if (data == nullptr) return; std::uint8_t* dataPtr = (std::uint8_t*)data; if(data > mStaticData && data < (mStaticData + BlockSize)) { if((((std::uint8_t*)data) + allocSize) == (mStaticData + mFreePtr)) mFreePtr -= allocSize; } else mDynamicAlloc.free(dataPtr); } void free(void* data) { if (data == nullptr) return; std::uint8_t* dataPtr = (std::uint8_t*)data; if(data < mStaticData || data >= (mStaticData + BlockSize)) mDynamicAlloc.free(dataPtr); } template<class T> T* construct(std::uint32_t count = 0) { T* data = (T*)alloc(sizeof(T) * count); for(unsigned int i = 0; i < count; i++) new ((void*)&data[i]) T; return data; } template<class T, class... Args> T* construct(Args &&...args, std::uint32_t count = 0) { T* data = (T*)alloc(sizeof(T) * count); for(unsigned int i = 0; i < count; i++) new ((void*)&data[i]) T(std::forward<Args>(args)...); return data; } template<class T> void destruct(T* data) { data->~T(); free(data, sizeof(T)); } template<class T> void destruct(T* data, std::uint32_t count) { for(unsigned int i = 0; i < count; i++) data[i].~T(); free(data, sizeof(T) * count); } void clear() { assert(mTotalAllocBytes == 0); mFreePtr = 0; mDynamicAlloc.clear(); } private: std::uint8_t mStaticData[BlockSize]; std::uint32_t mFreePtr = 0; DynamicAllocator mDynamicAlloc; std::uint32_t mTotalAllocBytes = 0; }; template <int BlockSize, class T> class StdStaticAlloc { public: typedef T value_type; typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type& reference; typedef const value_type& const_reference; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; StdStaticAlloc() = default; StdStaticAlloc(StaticAlloc<BlockSize, FreeAlloc>* alloc) noexcept :mStaticAlloc(alloc) { } template<class U> StdStaticAlloc(const StdStaticAlloc<BlockSize, U>& alloc) noexcept :mStaticAlloc(alloc.mStaticAlloc) { } template<class U> class rebind { public: typedef StdStaticAlloc<BlockSize, U> other; }; T* allocate(const size_t num) const { if (num == 0) return nullptr; if (num > static_cast<size_t>(-1) / sizeof(T)) return nullptr; void* const pv = mStaticAlloc->alloc((std::uint32_t)(num * sizeof(T))); if (!pv) return nullptr; return static_cast<T*>(pv); } void deallocate(T* p, size_t num) const noexcept { mStaticAlloc->free((std::uint8_t*)p, (std::uint32_t)num); } StaticAlloc<BlockSize, FreeAlloc>* mStaticAlloc = nullptr; size_t max_size() const { return std::numeric_limits<std::uint32_t>::max() / sizeof(T); } void construct(pointer p, const_reference t) { new (p) T(t); } void destroy(pointer p) { p->~T(); } template<class U, class... Args> void construct(U* p, Args&&... args) { new(p) U(std::forward<Args>(args)...); } template <class T1, int N1, class T2, int N2> friend bool operator== (const StdStaticAlloc<N1, T1>& a, const StdStaticAlloc<N2, T2>& b) throw(); }; template <class T1, int N1, class T2, int N2> bool operator== (const StdStaticAlloc<N1, T1>& a, const StdStaticAlloc<N2, T2>& b) throw() { return N1 == N2 && a.mStaticAlloc == b.mStaticAlloc; } template <class T1, int N1, class T2, int N2> bool operator!= (const StdStaticAlloc<N1, T1>& a, const StdStaticAlloc<N2, T2>& b) throw() { return !(a == b); } template <typename T, int Count> using StaticVector = std::vector<T, StdStaticAlloc<sizeof(T) * Count, T>>; }
0b5d39fb8786e10f7c158f0dcd3e9eca327a5ea8
a01645d71e953f515436ce842946778c284e5d3e
/Futhark/src/out/Camera.h
7b59f8a18aefb070e706ce55b2af27a296c5acd3
[]
no_license
t3chma/Futhark
1102965897c78673b8df1eba5388b5f91651af3b
d9b1d343a9687b9a42492929899ae4f6f2e91fae
refs/heads/master
2021-06-02T04:05:50.866706
2020-02-29T13:03:45
2020-02-29T13:03:45
115,884,276
1
0
null
null
null
null
UTF-8
C++
false
false
2,387
h
Camera.h
#pragma once #include <glm/gtc/matrix_transform.hpp> namespace fk { /* This represents a virtual camera for use in 2D games. [t3chma] */ class Camera { public: /* Sets the base screen dimensions. (dimensions) The camera screen dimensions in pixels. [t3chma] */ void setDimensions(glm::vec2 dimensions); /* Used to update the camera if it needs to. This should probably be called once every frame and is usually called in the process input method of your custom screen class. ^ CustomScreen: p_customUpdate() [t3chma] */ void update(); void setPosition(const glm::vec2& position); /* Translates the camera. (position) The translation. [t3chma] */ void move(const glm::vec2& position); void setZoom(float zoom); /* Zooms in the camera. This is the inverse of zoomOut(). (scale) The zoom multiplier. [t3chma] */ void zoomIn(float scale = 1.03); /* Zooms out the camera. This is the inverse of zoomIn(). (scale) The zoom multiplier. [t3chma] */ void zoomOut(float scale = 1.03); glm::vec2 getPosition() const; glm::vec2 getScreenTopRight() const; glm::vec2 getScreenTopLeft() const; glm::vec2 getScreenBottomRight() const; glm::vec2 getScreenBottomLeft() const; glm::vec2 getLensTopRight() const; glm::vec2 getLensTopLeft() const; glm::vec2 getLensBottomRight() const; glm::vec2 getLensBottomLeft() const; /* Translates window coordinates into world coordinates. (windowCoordinates) window coordinates. < World coordinates. [t3chma] */ glm::vec2 getWorldCoordinates(const glm::vec2& windowCoordinates) const; float getZoom() const; glm::vec2 getScreenDimentions() const; glm::vec2 getLensDimentions() const; glm::mat4 getBaseMatrix() const; glm::mat4 getTransMatrix() const; glm::mat4 getTransScaledMatrix() const; private: // Used to determine if the camera actually needs to be updated when update() is called. bool m_pendingUpdate{ true }; // The zoom scale of the camera. float m_zoom{ 1.0f }; // The base lense dimensions. glm::vec2 m_screenDimensions{ 1000.0f, 500.0f }; // The scaled lense dimensions. glm::vec2 m_lensDimensions{ 1000.0f, 500.0f }; // The focus (center) of the camera. glm::vec2 m_position{ 0.0f }; // Base camera lense. glm::mat4 m_baseMatrix{ 1.0f }; // Transformed camera lense. glm::mat4 m_transMatrix{ 1.0f }; // Transformed and scaled camera lense. glm::mat4 m_transScaledMatrix{ 1.0f }; }; }
7414f76774ab99afff131b747822d7fe8a6a816c
38175acbbd791d5062891023ddff69570bb9aabd
/snpduo.cpp
5f0b12ab5e0a72c13abd9f8b58b8dfd716dc1445
[]
no_license
wangdi2014/snpduo
9ddeb1658da6560c2b28b6d4bb8a1971aa07522a
8b05102900f3525786a106a417d7a3c56d0d87ee
refs/heads/master
2021-05-26T16:38:55.525479
2013-07-17T15:22:13
2013-07-17T15:22:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,967
cpp
snpduo.cpp
// stl #include <cstdlib> #include <ctime> #include <fstream> #include <iostream> #include <string> // imports using std::cout; using std::ofstream; using std::string; using std::time_t; // Custom includes #include "cargs.h" #include "duo.h" #include "helper.h" #include "input.h" #include "options.h" #include "output.h" #include "ped.h" // Externalized LOG declaration ofstream LOG; // Functions int main (int argc, char *argv[]) { // Set up variables to time the program time_t sysTime; // Set Options before continuing CArgs options(argc, argv); options.parse(); options.validity(); checkMinimumInput(); LOG.open( string(par::out + ".log").c_str() ); if (!LOG.good()) { screenError("Unable to write log file " + string2Filename( par::out + ".log")); } // show splash screen writeHeader(); // Print log text writeLog( "Logging text to " + string2Filename(par::out + ".log") + "\n" ); options.write(); // write options to screen // initialize variables DuoMap myDuo; LocusMap myMap; Ped myPed; // keep track of analysis time sysTime = time( 0 ); writeLog( "\nAnalysis started: " + convertToString( ctime(&sysTime) ) + "\n"); // file import if (par::pedFile != "null") { myMap.read(); myPed.read(myMap); } else if (par::tpedFile != "null") { readTpedFile( myPed, myMap ); } else if (par::genomeFile != "null") { readPlinkGenome( myDuo, myPed ); } // file recoding if (par::recode and par::genomeFile == "null") { if (par::transpose) { writeTranspose( myPed, myMap ); } else if (par::webDuo) { writeForWeb( myPed, myMap ); } else { myPed.write(myMap); myMap.write(); } } // calculate everything first. print results last // get ibs counts if ((par::counts or par::summary or par::calculated or par::conflicting) and !par::genome) { myDuo.getCounts( myPed ); } // ibs counts if (par::summary or par::calculated or par::conflicting) { myDuo.getMeanAndSDFromCounts(); } // mean and sd of ibs if ( (par::specified or par::calculated or par::conflicting) and !par::genome) { myDuo.specifiedRelationships( myPed ); } // parse known info if (par::oldCalculated and par::conflicting) { myDuo.oldCalculatedRelationships(); } // calculate relationships -- old algorithm else if (par::calculated or par::conflicting) { myDuo.calculatedRelationships(); } // calculate relationships -- new algorithm // print results if (par::counts) { myDuo.printCounts(); } if (par::summary) { myDuo.printMeanSD(); } if (par::specified and not par::genome) { myDuo.printRelationships(); } if (par::calculated and not par::genome) { myDuo.printSpecifiedAndCalculated(); } if (par::calculated and par::genome) { myDuo.printCalculatedOnly(); } if (par::conflicting and !par::genome) { myDuo.printConflicted(); } // when did it end? sysTime = time( 0 ); writeLog( "\nAnalysis ended: " + convertToString( ctime( &sysTime ) )); return RETURN_GOOD; // constant string from helper.h }
8525c9505b373b9f349d21bfa721f3807552b842
ab1afbdd931b9fe8c66ba325fb40a9f555386d39
/TAGEngine/TAGEngine/Game/MyInputHandler.cpp
50cbd769ef1a41458ff91ede0273dcf654accb16
[]
no_license
jimmybeer/TAGEngine
d1d2e5c501d6d5969344651e048848ea43f1486a
a2b6d5fa8c312fc3b14657f17c24e5ccd4b514ff
refs/heads/master
2019-01-02T02:08:34.105999
2015-07-30T19:07:57
2015-07-30T19:07:57
37,448,600
0
0
null
null
null
null
UTF-8
C++
false
false
2,166
cpp
MyInputHandler.cpp
#include "MyInputHandler.hpp" #include "CommandQueue.hpp" #include "SceneNode.hpp" #include "Aircraft.hpp" #include "MyCategory.hpp" #include <map> #include <string> #include <algorithm> using namespace std::placeholders; struct AircraftMover { AircraftMover(float vx, float vy) : velocity(vx, vy) {} void operator() (Aircraft& aircraft, sf::Time) const { aircraft.accelerate(velocity * aircraft.getMaxSpeed()); } sf::Vector2f velocity; }; MyInputHandler::MyInputHandler() : mCurrentMissionStatus(MissionRunning) { // set initial key bindings mKeyBinding[sf::Keyboard::Left] = MoveLeft; mKeyBinding[sf::Keyboard::Right] = MoveRight; mKeyBinding[sf::Keyboard::Up] = MoveUp; mKeyBinding[sf::Keyboard::Down] = MoveDown; mKeyBinding[sf::Keyboard::Space] = Fire; mKeyBinding[sf::Keyboard::M] = LaunchMissile; initialiseActions(); for(auto& pair : mActionBinding) { pair.second.category = Category::PlayerAircraft; } } void MyInputHandler::setMissionStatus(MissionStatus status) { mCurrentMissionStatus = status; } MyInputHandler::MissionStatus MyInputHandler::getMissionStatus() const { return mCurrentMissionStatus; } void MyInputHandler::initialiseActions() { mActionBinding[MoveLeft].action = derivedAction<Aircraft>(AircraftMover(-1, 0)); mActionBinding[MoveRight].action = derivedAction<Aircraft>(AircraftMover(+1, 0)); mActionBinding[MoveUp].action = derivedAction<Aircraft>(AircraftMover(0, -1)); mActionBinding[MoveDown].action = derivedAction<Aircraft>(AircraftMover(0, +1)); mActionBinding[Fire].action = derivedAction<Aircraft>([] (Aircraft& a, sf::Time) {a.fire();}); mActionBinding[LaunchMissile].action = derivedAction<Aircraft>([] (Aircraft& a, sf::Time) {a.launchMissile();}); } bool MyInputHandler::isRealTimeAction(unsigned int action) { switch (action) { case MoveLeft: case MoveRight: case MoveDown: case MoveUp: case Fire: return true; default: return false; } }
9baa5c390610eebfa4b99852cac58efca154dfb4
59ca9c7bad3bab085c4311c674ae38727b3cf7c2
/mainwindow.cpp
df71d20baad0fd6abd4db61bb23a54d4fdd4fed3
[]
no_license
SoraMause/MazeSolver
0020b6f4f7074b00ae1c33a83064c2fef18c70a4
c65c062928ba20cab2e6623bd8cf1edbb283d977
refs/heads/master
2020-05-09T22:31:42.475392
2019-04-24T02:36:27
2019-04-24T02:36:27
181,474,269
0
0
null
null
null
null
UTF-8
C++
false
false
2,011
cpp
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); init(); } MainWindow::~MainWindow() { delete simulator; delete ui; } void MainWindow::init() { history_string.clear(); ui->mazeFilePathEdit->setReadOnly(true); ui->actionHistory->setReadOnly(true); simulator = new MazeSimulator(); simulator->maze_paint->init(&scene); ui->graphicsView->setScene(&scene); ui->graphicsView->setStyleSheet("background:#000000"); } void MainWindow::writeHistoryDate( QString str_data ) { QDateTime dt = QDateTime::currentDateTime(); history_string += dt.toString("yyyy/MM/dd"); history_string += dt.toString(" hh:mm:ss\n"); history_string += str_data; ui->actionHistory->setText(history_string); } void MainWindow::on_mazeFileLoadButton_clicked() { QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), "", tr("Text File (*.txt);;")); if ( !fileName.isEmpty() ){ QFile file(fileName); if ( !file.open(QIODevice::ReadOnly)){ QMessageBox::critical(this, tr("Error"), tr("This System could not open File")); return; } QFileInfo fileInfo(file); ui->mazeFilePathEdit->setText(fileInfo.absoluteFilePath()); QTextStream stream(&file); writeHistoryDate( "file load\n" + fileInfo.fileName() + "\n" ); simulator->loadMaze(&stream, &scene); ui->graphicsView->setScene(&scene); file.close(); } } void MainWindow::on_drawMaze_clicked() { writeHistoryDate( "Draw Maze Data\n" ); simulator->drawMaze(&scene); ui->graphicsView->setScene(&scene); } void MainWindow::on_start_clicked() { writeHistoryDate("simulation start\n"); simulator->run(&scene); ui->graphicsView->setScene(&scene); writeHistoryDate("simulation end\n"); } void MainWindow::on_quitButton_clicked() { qApp->quit(); }
f3186051794b379ee95d3add8c226ac942daf3fd
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
/contest/1542579743.cpp
df569e192946aac02e1ef18d764fea84c9d2d573
[]
no_license
thegamer1907/Code_Analysis
0a2bb97a9fb5faf01d983c223d9715eb419b7519
48079e399321b585efc8a2c6a84c25e2e7a22a61
refs/heads/master
2020-05-27T01:20:55.921937
2019-11-20T11:15:11
2019-11-20T11:15:11
188,403,594
2
1
null
null
null
null
UTF-8
C++
false
false
558
cpp
1542579743.cpp
#include<bits/stdc++.h> using namespace std; int main(){ char s[105][105]; char a[5]; int n; scanf("%s",a); scanf("%d",&n); getchar(); int f1=1,f2=1; for(int i=0;i<n;i++){ scanf("%s",s[i]); } for(int i=0;i<n;i++){ if(a[0]==s[i][1]){ for(int j=0;j<n;j++){ if(a[1]==s[j][0]&&f1){ // printf("%s %s",s[i],s[j]); printf("YES\n"); f1 = 0; } } } if(strcmp(a,s[i])==0&&f1){ printf("YES\n"); f1 = 0; } } if(f1) printf("NO\n"); return 0; }
d660fe7b8d8bedeb9ab66669b506e1688ccb3a45
0dd186625725d2aabd7f81296617409ba05d0873
/1/grid.cpp
9fb1fa2061f9fc496a1b6894af216baf404378d7
[]
no_license
Sl07h/nstu_EMP
cd859c3ffbf722f2abafada1ab1bb5135df83b89
875c4e2050487a969fcfb557551e6848607ec995
refs/heads/master
2022-02-19T00:36:08.350338
2019-06-06T04:22:52
2019-06-06T04:22:52
176,553,018
1
1
null
null
null
null
UTF-8
C++
false
false
9,882
cpp
grid.cpp
#include "grid.h" #include "fdm.h" void GRID::inputGrid() { string filepath; if (isGridUniform) filepath = "input/uniform_grid.txt"; else filepath = "input/nonuniform_grid.txt"; std::ifstream fin(filepath); fin >> xLeft >> xRight >> yLower >> yUpper; fin >> width >> heigth >> widthLeft >> widthRight >> heigthLower >> heigthUpper; if (!isGridUniform) { fin >> kx >> ky; nx = width - 1; ny = heigth - 1; } fin.close(); } void GRID::buildGrid() { // c d Where: // -----==== a - height // | 66665xxxx ! b - width // | 10005xxxx ! e c - widthLeft // a| 10005xxxx ! d - widthRight // | 100004443 | e - heightUpper // | 100000003 | f f - heightLower // | 100000003 | // | 122222222 | // --------- // b // // 66665xxxx // 10005xxxx // 10005xxxx // 100004443 // 100000003 // 100000003 // 122222222 // if (isGridUniform) { hx = ((xRight - xLeft) / double(width - 1)) / pow(2, coef); hy = ((yUpper - yLower) / double(heigth - 1)) / pow(2, coef); cout << hx << "\t" << hy << endl; if (coef != 0) { width = (width - 1) * pow(2, coef) + 1; heigth = (heigth - 1) * pow(2, coef) + 1; widthLeft = (widthLeft)* pow(2, coef); widthRight = (widthRight - 1) * pow(2, coef) + 1; heigthLower = (heigthLower)* pow(2, coef); heigthUpper = (heigthUpper - 1) * pow(2, coef) + 1; } } else { if (coef != 0) { width = (width - 1) * pow(2, coef) + 1; heigth = (heigth - 1) * pow(2, coef) + 1; widthLeft = (widthLeft)* pow(2, coef); widthRight = (widthRight - 1) * pow(2, coef) + 1; heigthLower = (heigthLower)* pow(2, coef); heigthUpper = (heigthUpper - 1) * pow(2, coef) + 1; nx *= pow(2, coef); ny *= pow(2, coef); kx *= pow(kx, 1.0 / coef); ky *= pow(ky, 1.0 / coef); } hx = (xRight - xLeft) * (1 - kx) / (1 - pow(kx, nx)); hy = (yUpper - yLower) * (1 - ky) / (1 - pow(ky, ny)); } elemCount = width * heigth; cout << "Grid is uniform" << endl << "Coef: " << coef << endl << "Width: " << width << endl << "Height: " << heigth << endl << "Count of elements: " << elemCount << endl << "hx: " << hx << endl << "hy: " << hy << endl; nodes.resize(elemCount); if (isGridUniform) { size_t i, j, elem; double x, y, xPrev, yPrev; // Обходим все внутренние элементы нижней части "L" по пяти точкам for (j = 1; j < heigthLower - 1; j++) { i = 1; for (elem = j * width + 1; elem < (j + 1) * width - 1; elem++, i++) { x = xLeft + hx * i; y = yLower + hy * j; nodes[elem].setNodesData(x, y, i, j, 0, coef); } } // Обходим все внутренние элементы средней части части "L" по пяти точкам i = 1; j = heigthLower - 1; y = yLower + hy * j; for (elem = j * width + 1; elem < j * width + widthLeft; elem++, i++) { x = xLeft + hx * i; nodes[elem].setNodesData(x, y, i, j, 0, coef); } // Обходим все внутренние элементы верхней части "L" по пяти точкам for (j = heigthLower; j < heigth - 1; j++) { i = 1; for (elem = j * width + 1; elem < j * width + widthLeft - 1; elem++, i++) { x = xLeft + hx * i; y = yLower + hy * j; nodes[elem].setNodesData(x, y, i, j, 0, coef); } } // 1 i = 0; j = 0; x = xLeft + hx * i; for (elem = 0; elem < (heigth - 1) * width; elem += width, j++) { y = yLower + hy * j; nodes[elem].setNodesData(x, y, i, j, condType, coef); nodes[elem].border = 1; } // 2 i = 1; j = 0; y = yLower + hy * j; for (elem = 1; elem < width; elem++, i++) { x = xLeft + hx * i; nodes[elem].setNodesData(x, y, i, j, condType, coef); nodes[elem].border = 2; } // 3 i = width - 1; j = 1; x = xLeft + hx * i; for (elem = 2 * width - 1; elem < (width * heigthLower); elem += width, j++) { y = yLower + hy * j; nodes[elem].setNodesData(x, y, i, j, condType, coef); nodes[elem].border = 3; } // 4 i = widthLeft; j = heigthLower - 1; y = yLower + hy * j; for (elem = width * heigthLower - widthRight; elem < width * heigthLower - 1; elem++, i++) { x = xLeft + hx * i; nodes[elem].setNodesData(x, y, i, j, condType, coef); nodes[elem].border = 4; } // 5 i = widthLeft - 1; j = heigthLower; x = xLeft + hx * i; for (elem = width * j + widthLeft - 1; elem < elemCount; elem += width, j++) { y = yLower + hy * j; nodes[elem].setNodesData(x, y, i, j, condType, coef); nodes[elem].border = 5; } // 6 i = 0; j = heigth - 1; y = yLower + hy * j; for (elem = width * j; elem < width * j + widthLeft - 1; elem++, i++) { x = xLeft + hx * i; nodes[elem].setNodesData(x, y, i, j, condType, coef); nodes[elem].border = 6; } // fictitious nodes for (j = heigthLower; j < heigth; j++) { i = widthLeft; for (elem = width * j + widthLeft; elem < width * (j + 1); elem++, i++) { x = xLeft + hx * i; y = yLower + hy * j; nodes[elem].setNodesData(x, y, i, j, -1, coef); } } } else { double x, y; size_t i, j, elem; // Обходим все внутренние элементы нижней части "L" по пяти точкам dy = hy * ky; y = yLower + hy; for (j = 1; j < heigthLower - 1; j++, dy *= ky) { i = 1; dx = hx * kx; x = xLeft + hx; for (elem = j * width + 1; elem < (j + 1) * width - 1; elem++, i++, dx *= kx) { nodes[elem].setNodesData(x, y, i, j, 0, coef); x += dx; } y += dy; } // Обходим все внутренние элементы средней части части "L" по пяти точкам i = 1; dx = hx * kx; x = xLeft + hx; j = heigthLower - 1; dy = hy * pow(ky, j); y = yLower + hy * (1 - pow(ky, j)) / (1 - ky); for (elem = j * width + 1; elem < j * width + widthLeft; elem++, i++, dx *= kx) { nodes[elem].setNodesData(x, y, i, j, 0, coef); x += dx; } // Обходим все внутренние элементы верхней части "L" по пяти точкам dy = hy * pow(ky, heigthLower); y = yLower + hy * (1 - pow(ky, heigthLower)) / (1 - ky); for (j = heigthLower; j < heigth - 1; j++, dy *= ky) { i = 1; dx = hx * kx; x = xLeft + hx; for (elem = j * width + 1; elem < j * width + widthLeft - 1; elem++, i++, dx *= kx) { nodes[elem].setNodesData(x, y, i, j, 0, coef); x += dx; } y += dy; } // 1 i = 0; dx = hx; x = xLeft; j = 0; dy = hy; y = yLower; for (elem = 0; elem < (heigth - 1) * width; elem += width, j++, dy *= ky) { nodes[elem].setNodesData(x, y, i, j, condType, coef); nodes[elem].border = 1; y += dy; } // 2 i = 1; dx = hx * kx; x = xLeft + hx; j = 0; dy = hy; y = yLower; for (elem = 1; elem < width; elem++, i++, dx *= kx) { nodes[elem].setNodesData(x, y, i, j, condType, coef); nodes[elem].border = 2; x += dx; } // 3 i = width - 1; dx = hx * pow(kx, i - 1); x = xLeft + hx * (1 - pow(kx, i)) / (1 - kx); j = 1; dy = hy * ky; y = yLower + hy; for (elem = 2 * width - 1; elem < (width * heigthLower); elem += width, j++, dy *= ky) { nodes[elem].setNodesData(x, y, i, j, condType, coef); nodes[elem].border = 3; y += dy; } // 4 i = widthLeft; dx = hx * pow(kx, i); x = xLeft + hx * (1 - pow(kx, i)) / (1 - kx); j = heigthLower - 1; dy = hy * pow(ky, j); y = yLower + hy * (1 - pow(ky, j)) / (1 - ky); for (elem = width * heigthLower - widthRight; elem < width * heigthLower - 1; elem++, i++, dx *= kx) { nodes[elem].setNodesData(x, y, i, j, condType, coef); nodes[elem].border = 4; x += dx; } // 5 i = widthLeft - 1; x = xLeft + hx * (1 - pow(kx, i)) / (1 - kx); j = heigthLower; dy = hy * pow(ky, j); y = yLower + hy * (1 - pow(ky, j)) / (1 - ky); for (elem = width * j + widthLeft - 1; elem < elemCount; elem += width, j++, dy *= ky) { nodes[elem].setNodesData(x, y, i, j, condType, coef); nodes[elem].border = 5; y += dy; } // 6 i = 0; dx = hx; x = xLeft; j = heigth - 1; y = yLower + hy * (1 - pow(ky, j)) / (1 - ky); for (elem = width * j; elem < width * j + widthLeft - 1; elem++, i++, dx *= kx) { nodes[elem].setNodesData(x, y, i, j, condType, coef); nodes[elem].border = 6; x += dx; } // fictitious nodes j = heigthLower; dy = hy * pow(ky, j); y = yLower + hy * (1 - pow(ky, j)) / (1 - ky); for (j = heigthLower; j < heigth; j++, dy *= ky) { i = widthLeft; dx = hx * pow(kx, i); x = xLeft + hx * (1 - pow(kx, i)) / (1 - kx); for (elem = width * j + widthLeft; elem < width * (j + 1); elem++, i++, dx *= kx) { nodes[elem].setNodesData(x, y, i, j, -1, coef); x += dx; } y += dy; } } } // Отображние сетки на экран void GRID::showGrid() { cout << "X:" << endl; for (size_t j = 0; j < heigth; j++) { size_t elem = j * width; for (size_t i = 0; i < width; i++, elem++) { cout << nodes[elem].x << " "; } cout << endl; } cout << endl << endl << "Y:" << endl; for (size_t j = 0; j < heigth; j++) { size_t elem = j * width; for (size_t i = 0; i < width; i++, elem++) { cout << nodes[elem].y << " "; } cout << endl; } } // Сохранение внутренних и внешних узлов в 2 файлах void GRID::saveGridAndBorder(const string &filepathGrid, const string &filepathGridBorder) { ofstream grid(filepathGrid); ofstream border(filepathGridBorder); for (size_t i = 0; i < elemCount; i++) { if (nodes[i].type > 0) border << nodes[i].x << " " << nodes[i].y << endl; else grid << nodes[i].x << " " << nodes[i].y << endl; } border.close(); grid.close(); }
2ea257282e44fee7f48e2cec5a5707a862982441
e30e9a05829baf54b28a4a953c98f6ea2ca5f3cf
/TopCoder/SRM 253 Div 2/250/sol.cpp
e39f52252a3a24b7c0069aee9d9e718a7b9f0a15
[]
no_license
ailyanlu/ACM-13
fdaf4fea13c3ef4afc39a522e12c5dee52a66a24
389ec1e7f9201639a22ce37ea8a44969424b6764
refs/heads/master
2018-02-24T00:33:02.205005
2013-01-09T18:03:08
2013-01-09T18:03:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
813
cpp
sol.cpp
#include <iostream> #include <string> #include <vector> #include <cmath> #include <queue> #include <stack> #include <algorithm> #include <map> #include <set> using namespace std; class ObjectPacking{ public: int smallBox(int objWidth, int objLength, vector <int> boxWidth, vector <int> boxLength){ int ans=-1; for (int i=0; i<boxWidth.size(); ++i){ if ( (objWidth<=boxWidth[i]&&objLength<=boxLength[i]) || (objLength<=boxWidth[i]&&objWidth<=boxLength[i]) ){ if (ans<0 || boxWidth[i]*boxLength[i]<ans){ ans=boxWidth[i]*boxLength[i]; } } } return ans; } }; //declarations void input (void){ } void output (void){ } int main (void) { freopen ("in.txt", "r", stdin); freopen ("out.txt", "w", stdout); input(); output(); return 0; }
a2bbdc6f3267bf81ba4e07083cbcce009530fb24
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/squid/gumtree/squid_repos_function_1796_last_repos.cpp
48cee0d823f6bb6f9eb11c47146de80e805c2ac2
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,281
cpp
squid_repos_function_1796_last_repos.cpp
void operator()(StoreMeta const &x) { switch (x.getType()) { case STORE_META_KEY: std::cout << "MD5: " << storeKeyText((const cache_key *)x.value) << std::endl; break; case STORE_META_STD: std::cout << "STD, Size:" << ((struct MetaStd*)x.value)->swap_file_sz << " Flags: 0x" << std::hex << ((struct MetaStd*)x.value)->flags << std::dec << " Refcount: " << ((struct MetaStd*)x.value)->refcount << std::endl; break; case STORE_META_STD_LFS: std::cout << "STD_LFS, Size: " << ((struct MetaStdLfs*)x.value)->swap_file_sz << " Flags: 0x" << std::hex << ((struct MetaStdLfs*)x.value)->flags << std::dec << " Refcount: " << ((struct MetaStdLfs*)x.value)->refcount << std::endl; break; case STORE_META_URL: assert (((char *)x.value)[x.length - 1] == 0); std::cout << "URL: " << (char *)x.value << std::endl; break; default: std::cout << "Unknown store meta type: " << (int)x.getType() << " of length " << x.length << std::endl; break; } }
c0e0d2f5b4f839821062016d0e8a54681583b7ad
02298b46596d35c248cff9f6664ac311c9af833b
/Fimbul/Fimbul/Color.h
0542df730f0dd7f9f6d0bc3eacce099efbed7380
[]
no_license
TheAtomicGnome/Fimbul
5d332311807b55623f97c250a0d3f7473774ab06
1753d1e836152c42c9fccbe29938fea0109bd6f3
refs/heads/master
2018-12-28T07:57:05.159700
2014-08-21T09:27:51
2014-08-21T09:27:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
560
h
Color.h
#ifndef COLOR #define COLOR #include <SDL_opengl.h> class Color { public: Color() { r = 0xff; g = 0xff; b = 0xff; a = 0xff; } ~Color() { } GLubyte r , g , b , a; void setColor(GLubyte rr , GLubyte gg , GLubyte bb , GLubyte aa) { r = rr; g = gg; b = bb; a = aa; } Color & operator=(const Color &rhs) { this->r = rhs.r; this->g = rhs.g; this->b = rhs.b; this->a = rhs.a; } bool operator==(const Color &rhs) { return this->r == rhs.r && this->g == rhs.g && this->b == rhs.b && this->a == rhs.a; } }; #endif
11551de6f826ba7147bcb807a01c03dc5eb5d68a
912facd4f25962429117c7a3eba1e1f3ac7bf45d
/ECS_miniengine/Game.h
1bf2b012d6bb94b88630de65117b3a008065b3ab
[]
no_license
Weaver-JS/Multithreads_ECS
1aa1381a478021af4d4f47c602965b0e4209c617
b843ba93ff9dc7890690a0f203ce3ff00c4ec1b2
refs/heads/master
2021-10-02T07:32:58.906866
2018-10-31T14:09:31
2018-10-31T14:09:31
153,389,272
0
0
null
null
null
null
UTF-8
C++
false
false
595
h
Game.h
#pragma once #include "SDL.h" #include "ECS.h" #include "ECS_Components.h" #include "ECS_Systems.h" #include "InputHandler.h" #include "ManagerConstants.h" /* Clase padre de todos los Juegos. Para crear una clase que herede de juego y sobrescriba sus metodos virtuales. */ class Game { friend class GameManager; protected: virtual void init(std::string gameName, ECS::World * world, InputHandler * inputHandler) = 0; virtual void update() = 0; virtual void destroy() = 0; std::string gameName; InputHandler* inputHandler; ECS::World * world; bool quit; public: Game(); ~Game(); };
9041586dbcec6897360a88c622cac28845dd3109
907551ebcd410a08388df308ff811b6d1b75a8f9
/Source/U03_EnemyAI/Player/CPlayerController.h
572480e79f5b2b2de59db0ff11fc85ce4fea3115
[]
no_license
header-file/U03_EnemyAI
f3a70401c29c2ac3c084b42f432bf419ec8b5a93
58812a4a3ed8edca383ff2ddad892e4d542fc74d
refs/heads/master
2020-06-23T22:26:21.050530
2019-07-25T06:32:24
2019-07-25T06:32:24
198,771,770
0
0
null
null
null
null
UTF-8
C++
false
false
447
h
CPlayerController.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/PlayerController.h" #include "CPlayerController.generated.h" /** * */ UCLASS() class U03_ENEMYAI_API ACPlayerController : public APlayerController { GENERATED_BODY() public: ACPlayerController(); protected: void PlayerTick(float DeltaTime) override; void SetupInputComponent() override; };
fed505fc29f98e262dafa5fe17016b07002aed9e
2baf6f0d497c396c9071ecd28d43df9d9ed6a40c
/project/tests/battery_tests.cc
8c8a3695df07ffeb72c71fdf7e13414e79c3c7f8
[]
no_license
yilong233/CSCI-3081W-project
e986f284c82b7ffb3d8c0968cdfe3d5a48633ddd
ed6f861aeae32271b66a0bd87b048af720674a44
refs/heads/main
2023-06-10T07:31:59.565268
2021-07-01T10:25:35
2021-07-01T10:25:35
381,992,611
0
0
null
null
null
null
UTF-8
C++
false
false
1,100
cc
battery_tests.cc
#include "gtest/gtest.h" #include <EntityProject/project_settings.h> #include "../include/delivery_simulation.h" #include "../include/battery.h" #include <EntityProject/entity.h> #include "json_helper.h" #include <iostream> namespace csci3081 { using entity_project::IEntity; class BatteryTest : public ::testing::Test { protected: virtual void SetUp() { batt = new Battery(6793.4); } protected: Battery* batt; }; TEST_F(BatteryTest, MaxChargeTest){ EXPECT_FLOAT_EQ(batt -> GetMax(), 10000); } TEST_F(BatteryTest, GetRemainingTest){ batt -> SetRemaining(453.3); EXPECT_FLOAT_EQ(batt -> GetRemaining(), 453.3); } TEST_F(BatteryTest, ReduceRemainingTest){ batt -> ReduceRemaining(23); EXPECT_FLOAT_EQ(batt -> GetRemaining(), 6770.3999); } TEST_F(BatteryTest, IsEmptyTest){ EXPECT_FLOAT_EQ(batt -> IsEmpty(), false); } TEST_F(BatteryTest, SetEmptyTest){ batt -> SetRemaining(0.0); batt -> SetEmpty(true); EXPECT_FLOAT_EQ(batt -> IsEmpty(), true); } }
0a0813615fecaa256cb1d23f088c16321e0ca70b
8020ee737f9d88efac93bba3b9ff4e03bb96ff2a
/src/tetris.h
f15e221b6aed8e56d56d400f3f942e5ce4cc4db9
[ "WTFPL" ]
permissive
osgcc/osgcc2-OMGWTFADD
f4169c06436ae0357e9143015ccf671041925154
2ec7d0de5deea28980c5d4e66501406e71f36205
refs/heads/master
2020-08-23T16:28:06.086903
2010-03-11T22:14:47
2010-03-11T22:14:47
823,620
2
0
null
null
null
null
UTF-8
C++
false
false
1,750
h
tetris.h
#ifndef TETRIS_INCLUDED #define TETRIS_INCLUDED #include "game.h" class Tetris : public Game { public: // conventions: void Update(game_info* gi, float deltatime); void Draw(game_info* gi); void DrawOrtho(game_info* gi); void KeyDown(game_info* gi, Uint32 key); void KeyUp(game_info* gi, Uint32 key); void KeyRepeat(game_info* gi); void Attack(game_info* gi, int severity); void MouseMovement(game_info* gi, Uint32 x, Uint32 y); void MouseDown(game_info* gi); void InitGame(game_info* gi); // stuffs: void GetNewPiece(game_info* gi); void DrawBoard(game_info* gi); void DrawPiece(game_info* gi, double x, double y); void DrawBlock(int type, game_info* gi, double x, double y); void AddPiece(game_info* gi); void AddPiece(game_info* gi, int start_x, int start_y); void AddBlock(game_info* gi, int i, int j, int type); void DropPiece(game_info* gi); int ClearLines(game_info* gi); void PushUp(game_info* gi, int num); void DropLine(game_info* gi, int lineIndex); bool TestGameOver(game_info* gi); bool TestCollisionBlock(game_info* gi, double x, double y); bool TestCollision(game_info* gi); bool TestCollision(game_info* gi, double x, double y); double TestSideCollision(game_info* gi, double x, double y); // materials: // board posts: static GLfloat board_piece_amb[4]; static GLfloat board_piece_diff[4]; static GLfloat board_piece_spec[4]; static GLfloat board_piece_shine; static GLfloat board_piece_emi[4]; // block materials static GLfloat tet_piece_amb[4]; static GLfloat tet_piece_diff[6][4]; static GLfloat tet_piece_spec[4]; static GLfloat tet_piece_emi[4]; static GLfloat tet_piece_shine; }; #endif
6c02a9cae7bfa77246580000fa221ab4ec664a97
9a34a22e3c8121ba5d57f3c981640221f0cf4050
/Yocto Bootloader/variants/bobuino/pins_arduino.h
fcfd4ca2623cc5dd41587a5d38a6dabc5a2d692a
[]
no_license
HomoElectromagneticus/Yocto_808
53d858d9672625839739b4c1a9c8a5121c3c9b8d
e4cc0ba945dd6ff6b9236c745bc00b862862c523
refs/heads/master
2021-06-27T18:56:05.695924
2020-02-02T02:48:20
2020-02-02T02:48:20
101,703,098
13
5
null
2020-02-02T02:48:22
2017-08-29T01:09:57
C++
UTF-8
C++
false
false
6,224
h
pins_arduino.h
#ifndef Pins_Arduino_h #define Pins_Arduino_h #include <avr/pgmspace.h> // ATMEL ATMEGA1284P on Bobuino // // +---\/---+ // (D 4) PB0 1 | | 40 PA0 (D 21) AI 7 // (D 5) PB1 2 | | 39 PA1 (D 20) AI 6 // INT2 (D 6) PB2 3 | | 38 PA2 (D 19) AI 5 // PWM (D 7) PB3 4 | | 37 PA3 (D 18) AI 4 // PWM/SS (D 10) PB4 5 | | 36 PA4 (D 17) AI 3 // MOSI (D 11) PB5 6 | | 35 PA5 (D 16) AI 2 // PWM/MISO (D 12) PB6 7 | | 34 PA6 (D 15) AI 1 // PWM/SCK (D 13) PB7 8 | | 33 PA7 (D 14) AI 0 // RST 9 | | 32 AREF // VCC 10 | | 31 GND // GND 11 | | 30 AVCC // XTAL2 12 | | 29 PC7 (D 29) // XTAL1 13 | | 28 PC6 (D 28) // RX0 (D 0) PD0 14 | | 27 PC5 (D 27) TDI // TX0 (D 1) PD1 15 | | 26 PC4 (D 26) TDO // INT0 RX1 (D 2) PD2 16 | | 25 PC3 (D 25) TMS // INT1 TX1 (D 3) PD3 17 | | 24 PC2 (D 24) TCK // PWM (D 30) PD4 18 | | 23 PC1 (D 23) SDA // PWM (D 8) PD5 19 | | 22 PC0 (D 22) SCL // PWM (D 9) PD6 20 | | 21 PD7 (D 31) PWM // +--------+ // #define NUM_DIGITAL_PINS 32 #define NUM_ANALOG_INPUTS 8 #define analogInputToDigitalPin(p) ((p < NUM_ANALOG_INPUTS) ? 21 - (p) : -1) extern const uint8_t digital_pin_to_pcint[NUM_DIGITAL_PINS]; extern const uint16_t __pcmsk[]; extern const uint8_t digital_pin_to_timer_PGM[NUM_DIGITAL_PINS]; #define ifpin(p,what,ifnot) (((p) >= 0 && (p) < NUM_DIGITAL_PINS) ? (what) : (ifnot)) #define digitalPinHasPWM(p) ifpin(p,pgm_read_byte(digital_pin_to_timer_PGM + (p)) != NOT_ON_TIMER,1==0) #define digitalPinToAnalogPin(p) ( (p) >= 14 && (p) <= 21 ? (p) - 14 : -1 ) #define analogPinToChannel(p) ( (p) < NUM_ANALOG_INPUTS ? NUM_ANALOG_INPUTS - (p) : -1 ) static const uint8_t SS = 10; static const uint8_t MOSI = 11; static const uint8_t MISO = 12; static const uint8_t SCK = 13; static const uint8_t SDA = 23; static const uint8_t SCL = 22; static const uint8_t LED = 13; static const uint8_t A0 = 14; static const uint8_t A1 = 15; static const uint8_t A2 = 16; static const uint8_t A3 = 17; static const uint8_t A4 = 18; static const uint8_t A5 = 19; static const uint8_t A6 = 20; static const uint8_t A7 = 21; #define digitalPinToPCICR(p) ifpin(p,&PCICR,(uint8_t *)0) #define digitalPinToPCICRbit(p) ifpin(p,digital_pin_to_pcint[p] >> 3,(uint8_t *)0) #define digitalPinToPCMSK(p) ifpin(p,__pcmsk[digital_pin_to_pcint[]],(uint8_t *)0) #define digitalPinToPCMSKbit(p) ifpin(p,digital_pin_to_pcint[p] & 0x7,(uint8_t *)0) #ifdef ARDUINO_MAIN #define PA 1 #define PB 2 #define PC 3 #define PD 4 const uint8_t digital_pin_to_pcint[NUM_DIGITAL_PINS] = { 24, // D0 PD0 25, // D1 PD1 26, // D2 PD2 27, // D3 PD3 8, // D4 PB0 9, // D5 PB1 10, // D6 PB2 11, // D7 PB3 29, // D8 PD5 30, // D9 PD6 12, // D10 PB4 13, // D11 PB5 14, // D12 PB6 15, // D13 PB7 7, // D14 PA7 6, // D15 PA6 5, // D16 PA5 4, // D17 PA4 3, // D18 PA3 2, // D19 PA2 1, // D20 PA1 0, // D21 PA0 16, // D22 PC0 17, // D23 PC1 18, // D24 PC2 19, // D25 PC3 20, // D26 PC4 21, // D27 PC5 22, // D28 PC6 23, // D29 PC7 28, // D30 PD4 31, // D31 PD7 }; const uint16_t __pcmsk[] = { (uint16_t)&PCMSK0, (uint16_t)&PCMSK1, (uint16_t)&PCMSK2, (uint16_t)&PCMSK3 }; // these arrays map port names (e.g. port B) to the // appropriate addresses for various functions (e.g. reading // and writing) const uint16_t PROGMEM port_to_mode_PGM[] = { NOT_A_PORT, (uint16_t) &DDRA, (uint16_t) &DDRB, (uint16_t) &DDRC, (uint16_t) &DDRD, }; const uint16_t PROGMEM port_to_output_PGM[] = { NOT_A_PORT, (uint16_t) &PORTA, (uint16_t) &PORTB, (uint16_t) &PORTC, (uint16_t) &PORTD, }; const uint16_t PROGMEM port_to_input_PGM[] = { NOT_A_PORT, (uint16_t) &PINA, (uint16_t) &PINB, (uint16_t) &PINC, (uint16_t) &PIND, }; const uint8_t PROGMEM digital_pin_to_port_PGM[NUM_DIGITAL_PINS] = { PD, // D0 PD, // D1 PD, // D2 PD, // D3 PB, // D4 PB, // D5 PB, // D6 PB, // D7 PD, // D8 PD, // D9 PB, // D10 PB, // D11 PB, // D12 PB, // D13 PA, // D14 PA, // D15 PA, // D16 PA, // D17 PA, // D18 PA, // D19 PA, // D20 PA, // D21 PC, // D22 PC, // D23 PC, // D24 PC, // D25 PC, // D26 PC, // D27 PC, // D28 PC, // D29 PD, // D30 PD, // D31 }; const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[NUM_DIGITAL_PINS] = { _BV(0), // D0 PD0 _BV(1), // D1 PD1 _BV(2), // D2 PD2 _BV(3), // D3 PD3 _BV(0), // D4 PB0 _BV(1), // D5 PB1 _BV(2), // D6 PB2 _BV(3), // D7 PB3 _BV(5), // D8 PD5 _BV(6), // D9 PD6 _BV(4), // D10 PB4 _BV(5), // D11 PB5 _BV(6), // D12 PB6 _BV(7), // D13 PB7 _BV(7), // D14 PA7 _BV(6), // D15 PA6 _BV(5), // D16 PA5 _BV(4), // D17 PA4 _BV(3), // D18 PA3 _BV(2), // D19 PA2 _BV(1), // D20 PA1 _BV(0), // D21 PA0 _BV(0), // D22 PC0 _BV(1), // D23 PC1 _BV(2), // D24 PC2 _BV(3), // D25 PC3 _BV(4), // D26 PC4 _BV(5), // D27 PC5 _BV(6), // D28 PC6 _BV(7), // D29 PC7 _BV(4), // D30 PD4 _BV(7), // D31 PD7 }; const uint8_t PROGMEM digital_pin_to_timer_PGM[NUM_DIGITAL_PINS] = { NOT_ON_TIMER, // D0 PD0 NOT_ON_TIMER, // D1 PD1 NOT_ON_TIMER, // D2 PD2 NOT_ON_TIMER, // D3 PD3 NOT_ON_TIMER, // D4 PB0 NOT_ON_TIMER, // D5 PB1 NOT_ON_TIMER, // D6 PB2 TIMER0A, // D7 PB3 TIMER1A, // D8 PD5 TIMER2B, // D9 PD6 TIMER0B, // D10 PB4 NOT_ON_TIMER, // D11 PB5 TIMER3A, // D12 PB6 TIMER3B, // D13 PB7 NOT_ON_TIMER, // D14 PA0 NOT_ON_TIMER, // D15 PA1 NOT_ON_TIMER, // D16 PA2 NOT_ON_TIMER, // D17 PA3 NOT_ON_TIMER, // D18 PA4 NOT_ON_TIMER, // D19 PA5 NOT_ON_TIMER, // D20 PA6 NOT_ON_TIMER, // D21 PA7 NOT_ON_TIMER, // D22 PC0 NOT_ON_TIMER, // D23 PC1 NOT_ON_TIMER, // D24 PC2 NOT_ON_TIMER, // D25 PC3 NOT_ON_TIMER, // D26 PC4 NOT_ON_TIMER, // D27 PC5 NOT_ON_TIMER, // D28 PC6 NOT_ON_TIMER, // D29 PC7 TIMER1B, // D30 PD4 TIMER2A, // D31 PD7 }; #endif // ARDUINO_MAIN #endif // Pins_Arduino_h // vim:ai:cin:sts=2 sw=2 ft=cpp
a875f1a3be75fed8da644c669412e66bb09c71fa
95616c7f826bb2ce308f29a5084a8d960b8b4360
/json.hh
9acd6399a84139d62bf14b408b795d6c86c373c5
[]
no_license
jinoos/qt-screenshot
c2f231b378abf805c3379f8da098d21e10f2a498
75991ec69372c821279748827043705052e86f75
refs/heads/master
2016-09-02T03:00:24.843685
2014-09-15T04:27:47
2014-09-15T04:27:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
158
hh
json.hh
#ifndef JSON_HH #define JSON_HH #include "common.hh" class json { public: json(); static bool validateRequest(json_t *json); }; #endif // JSON_HH
5dadd441e5e313801e6835204225d5eb7cc87d47
ed0684c575102250ad9f9779096f8e0458f3149a
/COMSC-165/la09a.cpp
7b8cf0d88df0a031a01ecd043d1b08167e105c81
[]
no_license
tomyouyouzhu/DVC
e3688417cfad5c7beb1e2fee0af738eade87a327
73d8c2b1dfc85846f26de68e7304e8f9ba0aae6c
refs/heads/master
2023-03-29T04:43:35.044129
2021-03-31T05:28:40
2021-03-31T05:28:40
353,236,361
0
0
null
null
null
null
UTF-8
C++
false
false
221
cpp
la09a.cpp
//Objective: la09a //Name: Kunming Zhu //Course: COMSC-165-3015 #include <iostream> using namespace std; int main() { int a; int *b; cout<<"Please enter an integer: "; cin>>a; b=&a; cout<<"You entered: "<<*b; }
b3285f233f0bbba1fc4171c6870f821c7e605cfe
cf989c712ead02de3425383d0dd2c3cb5bb32985
/acrobat_common/test/test_lie_group_conversions.cpp
0cc499c6b90dedaaf388281f3d4b1f95deaa3ee2
[]
no_license
martindeegan/acrobat
ec29d880c31a7ad168b013e3723c227d03adaf46
159be51d8df81cbf13325e30bb2170e05603807d
refs/heads/master
2021-02-06T16:26:36.140048
2020-04-21T20:19:29
2020-04-21T20:19:29
243,931,006
6
0
null
2021-06-21T21:10:55
2020-02-29T08:20:43
C++
UTF-8
C++
false
false
3,566
cpp
test_lie_group_conversions.cpp
#include <geometry_msgs/msg/pose.hpp> #include <geometry_msgs/msg/transform.hpp> #include <gtest/gtest.h> #include <acrobat_common/lie_groups/lie_group_conversions.hpp> using acrobat::lie_group_conversions::convert; using acrobat::lie_groups::SE3; using acrobat::lie_groups::SO3; using acrobat::lie_groups::Vector3; namespace { void compare_quaternions(const geometry_msgs::msg::Quaternion& q1, const geometry_msgs::msg::Quaternion& q2) { constexpr double tol = 5e-5; EXPECT_NEAR(q1.w, q2.w, tol); EXPECT_NEAR(q1.x, q2.x, tol); EXPECT_NEAR(q1.y, q2.y, tol); EXPECT_NEAR(q1.z, q2.z, tol); } void compare_vectors(const geometry_msgs::msg::Vector3& t1, const geometry_msgs::msg::Vector3& t2) { constexpr double tol = 5e-5; EXPECT_NEAR(t1.x, t2.x, tol); EXPECT_NEAR(t1.y, t2.y, tol); EXPECT_NEAR(t1.z, t2.z, tol); } void compare_points(const geometry_msgs::msg::Point& t1, const geometry_msgs::msg::Point& t2) { constexpr double tol = 5e-5; EXPECT_NEAR(t1.x, t2.x, tol); EXPECT_NEAR(t1.y, t2.y, tol); EXPECT_NEAR(t1.z, t2.z, tol); } geometry_msgs::msg::Quaternion create_quat() { geometry_msgs::msg::Quaternion r1; double norm_inv = 1.0 / (0.692 * 0.692 + -0.002 * -0.002 + -0.685 * -0.685 + 0.228 * 0.228); r1.w = 0.692 * norm_inv; r1.x = -0.002 * norm_inv; r1.y = -0.685 * norm_inv; r1.z = 0.228 * norm_inv; return r1; } geometry_msgs::msg::Vector3 create_vector() { geometry_msgs::msg::Vector3 t1; t1.x = 100.0; t1.y = 231231.1231231; t1.z = -2837182731.123123; return t1; } geometry_msgs::msg::Point create_point() { geometry_msgs::msg::Point t1; t1.x = 100.0; t1.y = 231231.1231231; t1.z = -2837182731.123123; return t1; } TEST(LieGroupConversionsTest, Quaternion) { geometry_msgs::msg::Quaternion r1 = create_quat(); SO3 r2; geometry_msgs::msg::Quaternion result; convert(r1, r2); convert(r2, result); compare_quaternions(r1, result); } // namespace TEST(LieGroupConversionsTest, Vector) { EXPECT_TRUE(true); geometry_msgs::msg::Vector3 t1 = create_vector(); Vector3 t2; geometry_msgs::msg::Vector3 result; convert(t1, t2); convert(t2, result); compare_vectors(t1, result); } TEST(LieGroupConversionsTest, Point) { EXPECT_TRUE(true); geometry_msgs::msg::Point t1 = create_point(); Vector3 t2; geometry_msgs::msg::Point result; convert(t1, t2); convert(t2, result); compare_points(t1, result); } TEST(LieGroupConversionsTest, Transform) { geometry_msgs::msg::Quaternion r1 = create_quat(); geometry_msgs::msg::Vector3 t1 = create_vector(); geometry_msgs::msg::Transform p1; p1.rotation = r1; p1.translation = t1; SE3 p2; geometry_msgs::msg::Transform result; convert(p1, p2); convert(p2, result); compare_quaternions(p1.rotation, result.rotation); compare_vectors(p1.translation, result.translation); } TEST(LieGroupConversionsTest, Pose) { geometry_msgs::msg::Quaternion r1 = create_quat(); geometry_msgs::msg::Point t1 = create_point(); geometry_msgs::msg::Pose p1; p1.orientation = r1; p1.position = t1; SE3 p2; geometry_msgs::msg::Pose result; convert(p1, p2); convert(p2, result); compare_quaternions(p1.orientation, result.orientation); compare_points(p1.position, result.position); } } // namespace
a9bce021e735c50bf4c6d3b1afd6b838493b7b94
b4dc3314ebc2e8d3ba67fd777802960b4aedd84c
/brix-tools/iab/mfc/LABUnitTest/TProjectMetaData.cpp
5c559c9cf6e3e35546036187d4b3abc8427ac17b
[]
no_license
kamilWLca/brix
4c3f504f647a74ba7f51b5ae083bca82f70b9340
c3f2ad913a383bbb34ee64c0bf54980562661e2f
refs/heads/master
2021-01-18T04:08:56.435574
2012-09-18T16:36:32
2012-09-18T16:36:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
695
cpp
TProjectMetaData.cpp
#include "StdAfx.h" #include "TProjectMetaData.h" TProjectMetaData::TProjectMetaData(void) { } TProjectMetaData::~TProjectMetaData(void) { } void TProjectMetaData::setProjectName(CString csProjName) { ProjectMetaData::setProjectName(csProjName); } void TProjectMetaData::setProjectDir(CString csProjDir) { ProjectMetaData::setProjectDir(csProjDir); } void TProjectMetaData::createDefaultGroup() { ProjectMetaData::createDefaultGroup(); } void TProjectMetaData::createFolderStructure() { ProjectMetaData::createFolderStructure(); } void TProjectMetaData::copyFolderTo(CString csNewProjRootDir, CString csNewProjName) { ProjectMetaData::copyFolderTo(csNewProjRootDir, csNewProjName); }
756a254b992c9db60e76414d27079564649bcb2d
3e7a7a1e455677a921a0a979e2fd72fbd67c3ae4
/Communicating with Email Server/Client.cpp
b1065adf462a6440f6f5f3dad3a252277d9042f4
[]
no_license
ghostdevhv/Networks_Assignments
9db795d5f3a19b6ece1f8b30166ef7687de8717d
9517a92d224ce021c57e677fb82808aebb1e91d3
refs/heads/master
2022-02-25T19:39:28.212125
2019-10-19T06:20:41
2019-10-19T06:20:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,691
cpp
Client.cpp
#include <bits/stdc++.h> #include <unistd.h> #include <sys/socket.h> // For the socket (), bind () etc. functions. #include <netinet/in.h> // For IPv4 data struct.. #include <arpa/inet.h> // For inet_pton (), inet_ntop (). #include <time.h> using namespace std; #define BUF_SIZE 1000 const std::string currentDateTime() { time_t now = time(0); struct tm tstruct; char buf[1000]; tstruct = *localtime(&now); strftime(buf, sizeof(buf), "%Y-%m-%d %X", &tstruct); return buf; } int main(int argc, char *argv[]) { int num,check,sfd,rst; sfd = socket(AF_INET, SOCK_STREAM,0); char buf[1000]; if(sfd== -1) { perror("Client: Socket Error"); exit(1); } printf("Socket fd = %d\n",sfd); struct sockaddr_in srv_addr, cli_addr; // Addresses of the server and the client. socklen_t addrlen = sizeof (struct sockaddr_in); // size of the addresses. // Clear the two addresses. memset (&srv_addr, 0, addrlen); // Assign values to the server address. srv_addr.sin_family = AF_INET; // IPv4. char from[1000],to[1000],message[1000],date[1000],username[1000],password[1000]; char **tOkens; char *tOken; char name[1000]; while(1){ printf("Do you want to (1) Send mail or (2) Receive mails or (3) exit?\n"); cin>>num; if(num==1){ // send srv_addr.sin_port = htons(25); rst = inet_pton (AF_INET, "10.5.30.131", &srv_addr.sin_addr); if (rst <= 0) { perror ("Client Presentation to network address conversion.\n"); exit (1); } rst = connect (sfd, (struct sockaddr *) &srv_addr, addrlen); if (rst == -1) { perror ("Client: Connect failed."); exit (1); } memset(buf,0,sizeof(buf)); //sleep(1); rst = recv(sfd,buf,BUF_SIZE,0); printf("%s\n", buf); strcpy(buf,"HELO garudaserver.com\r\n"); //sleep(1); rst = send(sfd,buf,strlen(buf),0); if (rst == -1) { perror ("Client: Receive failed"); exit (1); } memset(buf,'\0',sizeof(buf)); rst = recv(sfd,buf,BUF_SIZE,0); printf("%s\n",buf); labelA: printf("Mail from?\n"); scanf("%s",from); memset(buf,'\0',sizeof(buf)); sprintf(buf,"MAIL FROM: <%s>\r\n",from); rst = send(sfd,buf,strlen(buf),0); memset(buf,'\0',sizeof(buf)); rst = recv(sfd,buf,BUF_SIZE,0); printf("%s\n",buf); if(buf[0]=='2' && buf[1]=='5' && buf[2]=='0'); else{ printf("Error\n"); rst=send(sfd,"RSET\r\n",BUF_SIZE,0); rst = recv(sfd,buf,BUF_SIZE,0); printf("%s\n",buf); goto labelA; } printf("How many clients do you want to mail to?\n"); cin>>num; for(int i=0;i<num;i++){ printf("Enter the receiver #%d mail address\n",i+1); scanf("%s",to); memset(buf,'\0',sizeof(buf)); sprintf(buf,"RCPT TO: <%s>\r\n",to); //usleep(100000); rst = send(sfd,buf,strlen(buf),0); memset(buf,'\0',sizeof(buf)); rst = recv(sfd,buf,BUF_SIZE,0); // 250 Ok printf("%s\n",buf ); if(buf[0]=='2' && buf[1]=='5' && buf[2]=='0'); else{ printf("Error\n"); memset(buf,'\0',sizeof(buf)); strcpy(buf,"RSET\r\n"); rst=send(sfd,"RSET\r\n",BUF_SIZE,0); rst = recv(sfd,buf,BUF_SIZE,0); printf("%s\n",buf); goto labelA; } } memset(buf,'\0',sizeof(buf)); strcpy(buf,"DATA\r\n"); rst = send(sfd,buf,strlen(buf),0); memset(buf,'\0',sizeof(buf)); rst = recv(sfd,buf,BUF_SIZE,0); // 354 START MAIL INPUT printf("Enter sender's name:\n"); char temp[1000]; getchar(); fgets(temp,900,stdin); temp[strlen(temp)-1]='\0'; printf("from=%s\n",temp); sprintf(buf,"From: %s\r\n",temp); rst = send(sfd,buf,strlen(buf),0); memset(buf,'\0',sizeof(buf)); sprintf(buf,"To: "); for(int i=0;i<num;i++){ printf("Enter receiver #%d name:\n",i+1); fgets(temp,900,stdin); temp[strlen(temp)-1]='\0'; printf("temp=%s\n",temp); strcat(buf,temp); if(num-i-1) strcat(buf,","); } strcat(buf,"\r\n"); rst = send(sfd,buf,strlen(buf),0); string tempdate=currentDateTime(); strcpy(date, tempdate.c_str()); printf("%s\n", date); sprintf(buf,"\nDate: %s\r\n",date); // strcpy(buf,"Date: "); // strcat(buf,date); // usleep(100000); rst = send(sfd,buf,strlen(buf),0); memset(buf,'\0',sizeof(buf)); printf("Enter Subject:\n"); fgets(temp,900,stdin); temp[strlen(temp)-1]='\0'; printf("temp=%s\n",temp); sprintf(buf,"Subject: %s\r\n",temp); //printf("%s\n", buf); // usleep(100000); rst = send(sfd,buf,strlen(buf),0); strcpy(buf,"\nContent:\r\n"); rst = send(sfd,buf,strlen(buf),0); printf("Input Mail Body [end with .]\n"); while(1){ memset(message,'\0',sizeof(message)); fgets(message,950,stdin); message[strlen(message)-1]='\0'; printf("message=%s\n", message); sprintf(buf,"%s\r\n",message); rst = send(sfd,buf,strlen(buf),0); if(rst==-1){ printf("server write failed\n"); exit(1); } if(strcmp(message,".")==0) break; } printf("abc\n"); memset(buf,'\0',sizeof(buf)); rst = recv(sfd,buf,BUF_SIZE,0); printf("%s\n",buf); if(buf[0]=='2' && buf[1]=='5' && buf[2]=='0'); else{ printf("Error\n"); rst=send(sfd,"RSET\r\n",BUF_SIZE,0); rst = recv(sfd,buf,BUF_SIZE,0); printf("%s\n",buf); goto labelA; } printf("Do you want to send more mails? 0 for No 1 for Yes\n"); cin>>num; if(num==1) goto labelA; else{ strcpy(buf,"QUIT\r\n"); rst = send(sfd,buf,BUF_SIZE,0); rst = recv(sfd,buf,BUF_SIZE,0); printf("%s\n",buf); break; } } else if(num==2){ //receive srv_addr.sin_port = htons(110); rst = inet_pton(AF_INET,"10.5.30.131",&srv_addr.sin_addr); if (rst <= 0) { perror ("Client Presentation to network address conversion.\n"); exit (1); } rst = connect (sfd, (struct sockaddr *) &srv_addr, addrlen); if (rst == -1) { perror ("Client: Connect failed."); exit (1); } rst=0; while(rst<=0){ memset(buf,'\0',BUF_SIZE); rst = recv(sfd,buf,BUF_SIZE,0); } printf("%s\n",buf); printf("username?\n"); scanf("%s",username); memset(buf,'\0',BUF_SIZE); sprintf(buf,"USER %s\r\n",username); rst = send(sfd,buf,strlen(buf),0); rst=0; while(rst<=0){ memset(buf,'\0',BUF_SIZE); rst = recv(sfd,buf,BUF_SIZE,0); } printf("%s\n",buf); printf("password?\n"); scanf("%s",password); memset(buf,'\0',BUF_SIZE); sprintf(buf,"PASS %s\r\n",password); rst = send(sfd,buf,strlen(buf),0); rst=0; while(rst<=0){ memset(buf,'\0',BUF_SIZE); rst = recv(sfd,buf,BUF_SIZE,0); } printf("%s\n",buf); sprintf(buf,"LIST\r\n"); rst = send(sfd,buf,strlen(buf),0); usleep(100); while(1){ memset(buf,'\0',BUF_SIZE); rst = recv(sfd,buf,BUF_SIZE,0); printf("%s",buf); if(rst<BUF_SIZE-1) break; } labelC: printf("Which message do you want to read?\n"); scanf("%d",&num); memset(buf,'\0',BUF_SIZE); sprintf(buf,"RETR %d\r\n",num); rst = send(sfd,buf,strlen(buf),0); //usleep(100); memset(buf,'\0',BUF_SIZE); printf("This is the mail you requested: \n"); while(1){ rst=0; memset(buf,'\0',BUF_SIZE); while(rst<=0) rst=recv(sfd,buf,BUF_SIZE,0); for(int i=0;i<BUF_SIZE;i++) cout<<buf[i]; if(rst<BUF_SIZE) break; } printf("\nWant to recv more mails? 0 for No 1 for Yes\n"); cin>>num; if(num==0){ memset(buf,'\0',BUF_SIZE); strcpy(buf,"QUIT\r\n"); rst = send(sfd,buf,strlen(buf),0); memset(buf,'\0',BUF_SIZE); rst = recv(sfd,buf,BUF_SIZE,0); printf("%s\n",buf); break; } else goto labelC; } else if(num==3) break; else{ printf("chutiya h kya bc\n"); exit(1); } } close(sfd); }
a4d1c7962b3f4514e33fffde08dfe4097af4b0ae
17c1d4c926b3bbb702a2a232e36bb9337ca7d02c
/NGIRL.cpp
27df04de8d2babd4ed133ea59fbda1377feabb56
[]
no_license
venkat-oss/SPOJ
796c51696061240980935f6fbf2fdc2f9f1ba674
119d0dec0733ca300bb0072d69e9e5bbcbb80c72
refs/heads/master
2021-10-11T05:15:50.696357
2019-01-22T16:52:48
2019-01-22T16:52:48
169,182,392
2
0
null
null
null
null
UTF-8
C++
false
false
1,155
cpp
NGIRL.cpp
#include <iostream> #include <cstdio> #include <cstdlib> #include <cmath> #include <cstring> #include <numeric> #include <algorithm> #include <functional> #include <vector> #include <queue> #include <stack> #include <set> #include <map> #include <unordered_map> #include <list> #include <bitset> #include <utility> #include <cassert> #include <iomanip> #include <ctime> #include <fstream> using namespace std; const int me = 100025; int T; long long N, K; int used[me]; vector<long long> primes; int main(int argc, const char * argv[]) { //ios_base::sync_with_stdio(0); //cin.tie(0); for(int i = 2; i < me; i ++) if(!used[i]){ primes.push_back(1LL * i * i); for(int j = i + i; j < me; j += i) used[j] = 1; } scanf("%d", &T); while(T --){ scanf("%lld%lld", &N, &K); int total = (int)(upper_bound(primes.begin(), primes.end(), N) - primes.begin()); int good = total - (int)(upper_bound(primes.begin(), primes.end(), K) - primes.begin()); if(good < 0) good = 0; printf("%d %d\n", total, good); } return 0; }
642f3fc8df8ec08dab34e20f09a643781433ff39
9a829a3c18fc5b58937694d3ce6967dbb78f22b5
/include/pathviz/ImageWriter.h
46b8093e7a528f0573b24d21fdb80456ff592cb8
[]
no_license
arpg/PathViz
d2efdfbbc1aa1d18c6acf48ba3e23011b1e39edf
e2a5538d562dc09d9ed851c148f0bdd58b9bfc5d
refs/heads/master
2020-04-06T05:12:17.190104
2018-04-25T20:15:59
2018-04-25T20:15:59
55,808,902
1
3
null
2016-08-31T17:11:58
2016-04-08T20:49:39
C++
UTF-8
C++
false
false
587
h
ImageWriter.h
#ifndef PATHVIZ_IMAGEWRITER_H #define PATHVIZ_IMAGEWRITER_H #include <string> #include <pathviz/Types.h> #include <pathviz/Image.h> namespace pathviz { class ImageWriter { public: ImageWriter(const std::string& outDir); public: ~ImageWriter(); public: void Write(uint camera, double timestamp, const Image& image); public: void Write(uint camera, uint frame, const Image& image); public: void Write(const std::string& filename, const Image& image); public: void WriteRaw(const std::string& path, const Image& image); protected: std::string m_outDir; }; } #endif
35418555f7572a5e1edab15c6120906272c95eea
933012ded9ea472d9065306eaa889ead5a6888d6
/src/Magma_Utils.cpp
8936c2c991717c7c77ca7c6133c0945921fddf2d
[]
no_license
Vasia228/Cripto
f6001ae4d651b508ea419ea465fec6a048e8d812
841b870985a21eb7f928547bc56dc6236167f233
refs/heads/master
2020-05-01T05:11:37.153907
2019-03-29T04:19:31
2019-03-29T04:19:31
177,294,936
0
0
null
null
null
null
UTF-8
C++
false
false
3,816
cpp
Magma_Utils.cpp
#include "Magma_Utils.h" const short int K_BLOCK_REPLACEMENT_MATRIX[8][16]= {{4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3}, {14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9}, {5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11}, {7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3}, {6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2}, {4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14}, {13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12}, {1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12}}; bitstring& encrypt_Magma(bitstring& str_bit, bitstring& key) { generate_key_Magma(key); bitstring shedule[8]; create_key_shedule_Magma(key, shedule); bitstring tmp(str_bit, 0, 64); tmp.show(32); encrypt_block_Magma(tmp, shedule); tmp.show(32); decrypt_block_Magma(tmp, shedule); tmp.show(32); return key; } void generate_key_Magma(bitstring& key) ///////////////////////////////////////need rework///////////////////////////////// { srand(time(NULL)); bool n; for (int i= 0; i<256; i++) { n = rand()%2; key.push(n); } } void create_key_shedule_Magma(bitstring key, bitstring shedule[]) { for (int i = 0; i<8; i++) { bitstring tmp(key, 32*i, 32); shedule[i] = tmp; } } bool encrypt_block_Magma(bitstring& block, bitstring shedule[]) { bitstring B(block, 0, 32), A(block, 32, 32), crypt_result, buffer; for (int i = 0; i<24; i++) { buffer = A; crypt_result = crypt_function_Magma(A, shedule[i%8]); //crypt_result.show(); A = B^crypt_result; B = buffer; } for (int i = 7; i > 0; i--) { buffer = A; crypt_result = crypt_function_Magma(A, shedule[i]); A = B^crypt_result; B = buffer; } buffer = B; crypt_result = crypt_function_Magma(A, shedule[0]); B = buffer^crypt_result; block = B + A; } bitstring& crypt_function_Magma(bitstring block, bitstring& key) { bitstring temp = xor_32_Magma(block, key); apply_K_BLOCK_REPLACEMENT(temp); temp.cycle_rotate_left(11); bitstring* tmp = new bitstring(temp); return *tmp; } bitstring& xor_32_Magma(bitstring block, bitstring key) { bitstring temp = block.plus(key); if (temp.get_size() >= 33) { block.generate_2_pow(32); block = temp.minus(block); temp = block.Lbit(32); } bitstring* tmp = new bitstring(temp); return *tmp; } void apply_K_BLOCK_REPLACEMENT(bitstring& block) { bitstring block_part[8]; for (int i = 0; i<8; i++) { bitstring temp(block, i*4, 4); block_part[i] = temp; } block.clear_data(); int index = 0; for (int i = 0; i<8; i++) { index = block_part[i].return_int(); bitstring temp(K_BLOCK_REPLACEMENT_MATRIX[i][index], 4); block += temp; } } bool decrypt_block_Magma(bitstring& block, bitstring shedule[]) { bitstring B(block, 0, 32), A(block, 32, 32), crypt_result, buffer; for (int i = 0; i < 8; i++) { buffer = A; crypt_result = crypt_function_Magma(A, shedule[i]); A = B^crypt_result; B = buffer; } for (int i = 23; i>= 0; i--) { buffer = A; crypt_result = crypt_function_Magma(A, shedule[i%8]); A = B^crypt_result; B = buffer; } block = A + B; }
1a111892a5dc98b59d03a31f68f0e097f91d7859
3a8cf7254ce2f8f79ffa730d4c72049ba198ff01
/C++/rk2/rk2.cpp
58212df7f87e17b7b0a2d704417a6ae18c99e4a2
[ "MIT" ]
permissive
martinvilu/Numerical-Analysis-Examples
3624eb212f2916cf90a2c63f64649c260d4bb67a
6314cf5571ab2984623785f8e28b0661f7af4090
refs/heads/master
2023-06-10T13:47:54.163012
2022-12-10T19:56:11
2022-12-10T19:56:11
58,951,629
0
0
null
2016-05-16T17:14:45
2016-05-16T17:14:45
null
UTF-8
C++
false
false
2,023
cpp
rk2.cpp
#include <iostream> #include <iomanip> #include <cmath> using namespace std; // Def dy/dx double A(double x, double y) { double dydx = pow(x, 2) + y; return dydx; } double B(double x, double y) { double dydx = pow(x, 2) + y; return dydx; } // Set precision and intedentation void print_num(float x, int width = 10, int precision = 3) { cout << setw(width) << setprecision(precision) << x; } int main() { int i, n; // Input Section cout << "Enter number of data points: "; cin >> n; // Allocate the arrays float *x = new float[n]; float *y = new float[n]; // Get the first x cout << "Enter the lowest value of x i.e. x[0]: "; cin >> x[0]; cout << "Enter the lowest value of y i.e. y[0]: "; cin >> y[0]; // And get the spacing cout << "Enter the spacing, h: "; float h; cin >> h; // Generate the x values for (int i = 1; i < n; i++) { x[i] = x[0] + i * h; } // Generate the y values for (i = 1; i < n; i++) { float y_temp = y[i - 1] + h * A(x[i - 1], y[i - 1]); y[(i)] = y[i - 1] + h / 2 * (A(x[i - 1], y[i - 1]) + B(x[i], y_temp)); } // Display the header cout << endl << "**************************"; cout << endl << "RK2 TABLE"; cout << endl << "**************************" << endl; cout << endl << "" << endl; ; cout << "-------------------------------------------" << endl; cout << "******************************************************" << endl; cout << setw(2) << "SNO" << setw(12) << "x[n]" << setw(12) << "y[n]" << setw(12) << "A" << setw(12) << "hA" << endl; cout << "******************************************************" << endl; for (i = 0; i < n; i++) { print_num(i, 2); print_num(x[i], 12); print_num(y[i], 12, 6); print_num(A(x[i], y[i]), 12, 6); print_num(h * A(x[i], y[i]), 12, 6); cout << endl; } return 0; }
5c59f2b9980bd24aa8c59d1907ed036a66863f68
47545ed10a76b098f3c178acce91b5820954a067
/cf/knighttournament.cpp
2fbce7329ac2132757ab9acce1a456c696fe545e
[]
no_license
Taekyukim02/usaco
2e5d65673ef1d64e39cc71a71ebc53dfdedd0bf7
d8eed9db51c22f2476ae77ab779869b411f60cb3
refs/heads/master
2023-06-27T23:50:09.457354
2021-07-28T19:16:01
2021-07-28T19:16:01
390,474,413
0
0
null
null
null
null
UTF-8
C++
false
false
1,665
cpp
knighttournament.cpp
#pragma comment(linker, "/stack:200000000") #pragma GCC optimize("Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") #include <iostream> #define MAX_N 300005 using namespace std; long long done[MAX_N]; bool finished[4*MAX_N]; int N, M; // lazy-fill [q1, q2] range void fill(int node, int l, int r, int q1, int q2, long long val) { if(finished[node]) return; if(l > r || r < q1 || q2 < l) return; if(l == r && q1 <= l && r <= q2) { if(l != val-1) { done[l] = val; finished[node] = true; } return; } fill(2*node+0, l, (l+r)/2+0, q1, q2, val); fill(2*node+1, (l+r)/2+1, r, q1, q2, val); finished[node] = finished[2*node] && finished[2*node+1]; } void fastscan(int &number) { //variable to indicate sign of input number bool negative = false; register int c; number = 0; // extract current character from buffer c = getchar(); if (c=='-') { // number is negative negative = true; // extract the next character from the buffer c = getchar(); } // Keep on extracting characters if they are integers // i.e ASCII Value lies from '0'(48) to '9' (57) for (; (c>47 && c<58); c=getchar()) number = number *10 + c - 48; // if scanned input has a negative sign, negate the // value of the input number if (negative) number *= -1; } int main() { fastscan(N); fastscan(M); int a, b, c; for(int i=0; i<M; i++) { fastscan(a); fastscan(b); fastscan(c); fill(1, 0, N-1, a-1, b-1, c); } for(int i=0; i<N; i++) { cout << done[i] << " "; } cout << endl; }
162086bde17a080416334181e54d1f8c2131f1cb
f5f5351cdb424d0da2014898f362712471a53ae1
/TouchCY8C201A0.h
5192bd626ed297a31e57f7feffe845e3369ba084
[]
no_license
akafugu/TouchCY8C201A0
36b68b3d7868c88af695673251ce3ff49c8336f3
d69c012c494b841a28cd29c66de342feffdc0f48
refs/heads/master
2020-06-08T10:47:05.293924
2013-03-14T05:18:34
2013-03-14T05:18:34
8,768,342
1
0
null
null
null
null
UTF-8
C++
false
false
2,557
h
TouchCY8C201A0.h
/* * TouchCY8C201A0 - Library for CY8C201A0 CapSense Controller * (C) 2013 Akafugu Corporation * * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * */ #include <stdint.h> #define CY8C201A0_SLAVE_ADDR 0x0 enum CY8_RegisterMap { INPUT_PORT0 = 0x00, INPUT_PORT1 = 0x01, STATUS_PORT0 = 0x02, STATUS_PORT1 = 0x03, OUTPUT_PORT0 = 0x04, OUTPUT_PORT1 = 0x05, CS_ENABLE0 = 0x06, CS_ENABLE1 = 0x07, GPIO_ENABLE0 = 0x08, GPIO_ENABLE1 = 0x09, // 0x08~17 // 0x1c- CS_NOISE_TH = 0x4E, CS_BL_UPD_TH = 0x4F, CS_SCAN_POS_00 = 0x57, CS_SCAN_POS_01 = 0x58, CS_SCAN_POS_02 = 0x59, CS_SCAN_POS_03 = 0x5A, CS_SCAN_POS_04 = 0x5B, CS_SCAN_POS_10 = 0x5C, CS_SCAN_POS_11 = 0x5D, CS_SCAN_POS_12 = 0x5E, CS_SCAN_POS_13 = 0x5F, CS_SCAN_POS_14 = 0x60, CS_FINGER_TH_00 = 0x61, CS_FINGER_TH_01 = 0x62, CS_FINGER_TH_02 = 0x63, CS_FINGER_TH_03 = 0x64, CS_FINGER_TH_04 = 0x65, CS_FINGER_TH_10 = 0x66, CS_FINGER_TH_11 = 0x67, CS_FINGER_TH_12 = 0x68, CS_FINGER_TH_13 = 0x69, CS_FINGER_TH_14 = 0x6A, DEVICE_ID = 0x7A, DEVICE_STATUS = 0x7B, CS_SLID_CONFIG = 0x75, I2C_DEV_LOCK = 0x79, CS_READ_BUTTON = 0x81, CS_READ_BLM = 0x82, CS_READ_STATUS0 = 0x88, CS_READ_STATUS1 = 0x89, COMMAND_REG = 0xA0, }; /// class TouchCY8 { private: uint8_t m_addr; public: TouchCY8(uint8_t addr = CY8C201A0_SLAVE_ADDR); // Low level commands bool writeRegister(uint8_t reg); bool writeCommand(uint8_t reg, uint8_t command); bool writeCommandSequence(uint8_t reg, uint8_t* commands, uint8_t n); uint8_t receiveDataByte(); void receiveData(uint8_t* buffer, uint8_t n); // High-level commands uint8_t getDeviceId(); uint8_t getDeviceStatus(); void changeI2CAddress(uint8_t old_addr, uint8_t new_addr); void enterSetupMode(); void enterNormalMode(); void restoreFactoryDefault(); void softwareReset(); void saveToFlash(); // GPIO / buttons / sliders configuration void setupGPIO(bool gpio0, bool gpio1); void setupCapSense(bool cs0, bool cs1); // Read status uint8_t readStatus(uint8_t port); };
190da26031f6d4d89fc673d66667d69242c8a6a7
052b8dcd50dd3d20ebbd3b2cca990df90fa45861
/search_server.cpp
cbb53812803412886a09b80f1e854a053c775e80
[]
no_license
AlexanderLekhan/RedFinal
c33e9b56ca10798b5bc0ca045f770cbb5e557ff9
764b87dd7783d63fd6879f7d667ff7587f13f587
refs/heads/master
2020-04-07T21:26:57.694811
2018-12-05T19:32:44
2018-12-05T19:32:44
158,725,127
0
0
null
null
null
null
UTF-8
C++
false
false
4,327
cpp
search_server.cpp
#include <algorithm> #include <sstream> #include <iostream> #include <cassert> #include "search_server.h" #include "iterator_range.h" #include "profile.h" #include "parse.h" using namespace std; InvertedIndex::InvertedIndex(istream& document_input) { for (string current_document; getline(document_input, current_document); ) { if (current_document.empty()) continue; m_docs.push_back(move(current_document)); const size_t docid = m_docs.size() - 1; for (string_view word : SplitIntoWordsView(m_docs.back())) { DocHits& docHits = m_index[word]; if (!docHits.empty() && docHits.back().first == docid) { ++docHits.back().second; } else { docHits.push_back(make_pair(docid, 1)); } } } } template <typename DocHitsMap> void InvertedIndex::LookupAndSum(string_view word, DocHitsMap& docid_count) const { auto it = m_index.find(word); if (it != m_index.end()) { for (auto& [docid, hits] : it->second) { docid_count[docid] += hits; } } } SearchServer::SearchServer(istream& document_input) { UpdateDocumentBase(document_input); } void update_document_base(istream& document_input, Synchronized<InvertedIndex>& index) { bool flag = true; { auto access = index.GetAccess(); if (access.ref_to_value.DocsCount() == 0) { access.ref_to_value = move(InvertedIndex(document_input)); flag = false; } } if (flag) { InvertedIndex new_index(document_input); index.GetAccess().ref_to_value = move(new_index); } } void SearchServer::UpdateDocumentBase(istream& document_input) { m_tasks.push_back(async(update_document_base, ref(document_input), ref(m_index))); } void process_query_stream(istream& query_input, ostream& search_results_output, Synchronized<InvertedIndex>& index) { static const size_t MAX_OUTPUT = 5; for (string current_query; getline(query_input, current_query); ) { if (current_query.empty()) continue; const auto words = SplitIntoWordsView(current_query); vector<size_t> docHits(0); { auto access = index.GetAccess(); docHits.resize(access.ref_to_value.DocsCount(), 0); for (const auto& word : words) { access.ref_to_value.LookupAndSum(word, docHits); } } SearchResult search_result(MAX_OUTPUT); for (size_t doc = 0; doc < docHits.size(); ++doc) { if (docHits[doc] > 0) search_result.PushBack(make_pair(doc, docHits[doc])); } search_results_output << current_query << ':'; for (auto [docid, hitcount] : search_result) { search_results_output << " {" << "docid: " << docid << ", " << "hitcount: " << hitcount << '}'; } search_results_output << endl; } } void SearchServer::AddQueriesStream(istream& query_input, ostream& search_results_output) { m_tasks.push_back(async(process_query_stream, ref(query_input), ref(search_results_output), ref(m_index))); } void SearchServer::WaitForAllTasks() { for (auto& t : m_tasks) { if (t.valid()) t.get(); } } void SearchResult::PushBack(pair<size_t, size_t>&& docHits) { DocHits::iterator curr = m_data.end(); for ( ; curr != m_data.begin(); --curr) { if (prev(curr)->second >= docHits.second) break; } if (m_data.size() < m_data.capacity()) { if (curr == m_data.end()) m_data.push_back(move(docHits)); else m_data.insert(curr, move(docHits)); } else { if (curr != m_data.end()) { for (DocHits::iterator it = prev(m_data.end()); it != curr; --it) { *it = move(*prev(it)); } *curr = move(docHits); } } }
845ca1a74770021bf8c1bb19c5a9fd6905536456
63af72f27f44ba5c2cfd5fa083e99a3806515163
/CSES/stickLengths.cpp
4b6c0618e1569c4d0c5b9b83c8c74bb6ae810c60
[]
no_license
mhbtz1/USACO
b3777d761c677b6ab3bab7a09575d95a6a8ade59
596fd7066093f937e93d408fc8d0b65ba1a2730f
refs/heads/master
2023-04-04T09:32:33.778783
2021-04-17T03:29:39
2021-04-17T03:29:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
657
cpp
stickLengths.cpp
#include <iostream> #include <map> #include <vector> #include <queue> #include <tuple> #include <utility> using namespace std; typedef pair<int,int> pii; //greedy algorithm: problem reduces to finding the maximally occurring value in the array but since q is up to 10^9, using an array isnt possible int main(){ int n; cin >> n; int a[n]; vector<pii> occur; for(int i = 0; i < n; i++){ cin >> a[i]; occur.push_back(a[i], occur[a[i]].second + 1); } sort(occur.begin(), occur.end(),greater<int>()); pii bq = occur[0]; int amt = 0; for(int i = 0; i < n; i++){ amt += abs(bq - a[i]); } cout << amt << endl; }
29e4822a96d8c1fe4f83cd85d760177ca3ddd5b6
d8d0ece686132fcec71b272a39cb6895b78f8c14
/Libraries/ResourceManager/RHandle.cpp
2ac032df1ce1a10a015746bcf45d8cdc36469606
[]
no_license
Ryxali/SpaceSumo
bce49e1eaa47542d9099e936d94cd8ceb7b35ca5
81da176deb2d825ec052400237c310ddd5352d0c
refs/heads/master
2016-09-05T16:46:55.690164
2014-03-21T14:04:34
2014-03-21T14:04:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
703
cpp
RHandle.cpp
#ifndef SPACESUMO_RESOURCEMANAGER_RHANDLE_INCLUDED #include "RHandle.h" #endif #ifndef SPACESUMO_RESOURCEMANAGER_RESOURCEHANDLER_INCLUDED #include "ResourceHandler.h" #endif #ifndef SPACESUMO_RESOURCEMANAGER_STEXTURE_INCLUDED #include "STexture.h" #endif #ifndef SPACESUMO_RESOURCEMANAGER_SSOUNDBUFFER_INCLUDED #include "SSoundBuffer.h" #endif static ResourceHandler handler; void res::addResource(std::string ref) { handler.add(ref); } void res::loadResource(std::string ref) { handler.load(ref); } const STexture &res::getTexture(std::string ref) { return handler.getTexStore().get(ref); } const SSoundBuffer &res::getSoundBuffer(std::string ref) { return handler.getSBufStore().get(ref); }
1bac97e060c07155d7e5d9ead8d006b77722ec35
5bd9fefbb0120b47771627f2dd0950bcf5160a42
/TopAnalysis/interface/VBFAnalysisCategories.h
5fbb9b62a346792b1a351ed1c36461db7328e5cb
[]
no_license
pfs/TopLJets2015
b55c2fef81067ff8e935a5bc8b8b2d255f4ea9aa
e0711dcaf8625ebe96bacd0e6407c3c1c3f4b867
refs/heads/master
2023-02-18T04:51:02.485047
2021-03-30T07:34:55
2021-03-30T07:34:55
43,517,945
4
39
null
2021-02-22T09:39:44
2015-10-01T20:01:48
C++
UTF-8
C++
false
false
1,910
h
VBFAnalysisCategories.h
#ifndef vbfanalysiscategories_h #define vbfanalysiscategories_h #include <iostream> using namespace std; namespace vbf { TString categoryNames[]={"LowVPtLowMJJ","LowVPtHighMJJ","HighVPtLowMJJ","HighVPtHighMJJ","HighVPt","LowVPt"}; struct Category{ float EE,MM,A,LowVPt,HighVPt,LowMJJ,HighMJJ,AllMJJ; Category(){ reset(); } Category(std::vector<bool> &cat){ reset(); set(cat); }; void reset(){ std::vector<bool> cat(8,false); set(cat); }; void set(std::vector<bool> &cat){ EE = (float) cat[0]; MM = (float) cat[1]; A = (float) cat[2]; LowVPt = (float) cat[3]; HighVPt = (float) cat[4]; LowMJJ = (float) cat[5]; HighMJJ = (float) cat[6]; AllMJJ = (float) cat[7]; }; std::vector<TString> getChannelTags() { std::vector<TString> chTags; TString chTag(""); if(EE>0) chTag="EE"; if(MM>0) chTag="MM"; if(A>0) chTag="A"; if(chTag=="") return chTags; chTags.push_back(chTag); if(LowVPt>0 && LowMJJ>0) {chTags.push_back(categoryNames[0]+chTag); }//cout<<categoryNames[0]<<endl;} if(LowVPt>0 && HighMJJ>0) {chTags.push_back(categoryNames[1]+chTag); }//cout<<categoryNames[1]<<endl;} if(HighVPt>0 && LowMJJ>0) {chTags.push_back(categoryNames[2]+chTag); }//cout<<categoryNames[2]<<endl;} if(HighVPt>0 && HighMJJ>0) {chTags.push_back(categoryNames[3]+chTag); }//cout<<categoryNames[3]<<endl;} if(HighVPt>0 && AllMJJ>0) {chTags.push_back(categoryNames[4]+chTag); }//cout<<categoryNames[4]<<endl;} if(LowVPt>0 && AllMJJ>0) {chTags.push_back(categoryNames[5]+chTag); }//cout<<categoryNames[5]<<endl;} return chTags; } }; } #endif
78bf97899207822b1539566b9ba8dcbf861a504c
bb6806e0bd52cbf26fcea2d7090ba6521c9e31ee
/TM/main.cpp
f850351cb095678cca28648f98da428e9a3faff5
[]
no_license
wuyexkx/cpp_exercises
25b8a08ccdf7d8c0a1ca1da7867b16535c7733aa
cf08035f7acf21ccd34cca55fcf6d7b7ab4d436a
refs/heads/master
2021-07-12T21:19:36.710739
2020-08-25T08:37:26
2020-08-25T08:37:26
196,787,290
4
0
null
null
null
null
UTF-8
C++
false
false
678
cpp
main.cpp
#include <iostream> #include "TicketMachine.h" using namespace std; // 获取私有变量的手段 // 指针和引用都可以 通过公共函数 在类的外部 修改私有变量 int main() { TicketMachine TM; cout << "\ninit balance = "; TM.showBalance(); cout << "\ninert 10 = " ; TM.insertMoney(10); TM.showBalance(); cout << "\ndecrase 5 = "; TM.decraseMoney(5); TM.showBalance(); cout << "\npointer add 100 = "; int *b = TM.pointer_Private_balance(); *b += 100; TM.showBalance(); cout << "\nreference sub 50 = "; int &r = TM.reference_Private_balance(); r -= 50; TM.showBalance(); return 0; }
c2327eb9ca4962ea3674f01a714241b991350889
2173de375327ba2dae1a9a229aa1ea30013abb7c
/DFS/dfs.cpp
b76495d029614779f741256a08f902838db93dd3
[]
no_license
Nikhil-Wagh/Competitive-Coding
963b01bfcbd6ca4241b8c667ae0213defe2493c8
e055e42c265ed41d39efc532736d531b668c535c
refs/heads/master
2020-12-04T02:48:53.093532
2018-08-30T16:20:38
2018-08-30T16:20:38
65,979,469
0
1
null
null
null
null
UTF-8
C++
false
false
696
cpp
dfs.cpp
#include "bits/stdc++.h" using namespace std; typedef unsigned long long ull; typedef long long int ll; typedef vector<long long int> vi; typedef pair<int, int> ii; typedef vector<ii> vii; vector<int > a[1000009]; int visit[1000009]; void dfs(int x) { //cout<<x<<endl; visit[x]=1; for(int i=0;i<a[x].size();i++) if(visit[a[x][i]]==0) dfs(a[x][i]); } int main() { ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL); ll n,sum=0,count=0,m,flag=0; cin>>n; a[1].push_back(2); a[3].push_back(5); for(int i=0;i<n;i++) { if(a[i].size()>0) dfs(i); } for(int i=1;i<=n;i++) cout<<visit[i]<<" "; return 0; }
7ca8482880d6c91c1d2a9f01784fb5d59dafbaec
ec8944284a5fa6f0bb02f76d2ca61fe829fdf8f6
/ui_production_lot_information_win.h
fb88b627b86374c1421efc518fafa614f479ebe0
[]
no_license
SC-ML-cmd/BackLight_QT_0305
3d76884ee167fae47a4a173ef47898776c5f09eb
7c0f02565424c49be03c4067054bbe2bb35a0f70
refs/heads/master
2023-04-23T12:26:05.317672
2021-05-19T02:52:05
2021-05-19T02:52:05
344,696,437
0
0
null
null
null
null
UTF-8
C++
false
false
7,160
h
ui_production_lot_information_win.h
/******************************************************************************** ** Form generated from reading UI file 'production_lot_information_win.ui' ** ** Created by: Qt User Interface Compiler version 5.12.0 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_PRODUCTION_LOT_INFORMATION_WIN_H #define UI_PRODUCTION_LOT_INFORMATION_WIN_H #include <QtCore/QVariant> #include <QtGui/QIcon> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QHeaderView> #include <QtWidgets/QMainWindow> #include <QtWidgets/QPushButton> #include <QtWidgets/QScrollArea> #include <QtWidgets/QStatusBar> #include <QtWidgets/QTableView> #include <QtWidgets/QToolBar> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_production_lot_information_win { public: QAction *action; QAction *action_2; QAction *action_3; QAction *action_4; QWidget *centralwidget; QTableView *tableView; QScrollArea *scrollArea; QWidget *scrollAreaWidgetContents; QPushButton *pushButton_2; QPushButton *pushButton; QStatusBar *statusbar; QToolBar *toolBar; void setupUi(QMainWindow *production_lot_information_win) { if (production_lot_information_win->objectName().isEmpty()) production_lot_information_win->setObjectName(QString::fromUtf8("production_lot_information_win")); production_lot_information_win->resize(953, 577); production_lot_information_win->setMinimumSize(QSize(953, 577)); production_lot_information_win->setMaximumSize(QSize(953, 577)); QIcon icon; QString iconThemeName = QString::fromUtf8("\347\224\237\344\272\247\346\211\271\346\254\241"); if (QIcon::hasThemeIcon(iconThemeName)) { icon = QIcon::fromTheme(iconThemeName); } else { icon.addFile(QString::fromUtf8(":/resourse/peizhi.png"), QSize(), QIcon::Normal, QIcon::Off); } production_lot_information_win->setWindowIcon(icon); action = new QAction(production_lot_information_win); action->setObjectName(QString::fromUtf8("action")); QIcon icon1; icon1.addFile(QString::fromUtf8(":/resourse/xinzeng.png"), QSize(), QIcon::Normal, QIcon::Off); action->setIcon(icon1); action->setIconVisibleInMenu(true); action_2 = new QAction(production_lot_information_win); action_2->setObjectName(QString::fromUtf8("action_2")); QIcon icon2; icon2.addFile(QString::fromUtf8(":/resourse/xiugaiq.png"), QSize(), QIcon::Normal, QIcon::Off); action_2->setIcon(icon2); action_3 = new QAction(production_lot_information_win); action_3->setObjectName(QString::fromUtf8("action_3")); QIcon icon3; icon3.addFile(QString::fromUtf8(":/resourse/shanchu.png"), QSize(), QIcon::Normal, QIcon::Off); action_3->setIcon(icon3); action_4 = new QAction(production_lot_information_win); action_4->setObjectName(QString::fromUtf8("action_4")); QIcon icon4; icon4.addFile(QString::fromUtf8(":/resourse/NMStubiao-.png"), QSize(), QIcon::Normal, QIcon::Off); action_4->setIcon(icon4); centralwidget = new QWidget(production_lot_information_win); centralwidget->setObjectName(QString::fromUtf8("centralwidget")); tableView = new QTableView(centralwidget); tableView->setObjectName(QString::fromUtf8("tableView")); tableView->setGeometry(QRect(0, 0, 951, 471)); scrollArea = new QScrollArea(centralwidget); scrollArea->setObjectName(QString::fromUtf8("scrollArea")); scrollArea->setGeometry(QRect(370, 410, 401, 41)); QFont font; font.setItalic(false); scrollArea->setFont(font); scrollArea->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 255, 255);\n" "selection-color: rgb(255, 255, 255);\n" "gridline-color: rgb(255, 255, 255);\n" "border-color: rgb(255, 255, 255);")); scrollArea->setWidgetResizable(true); scrollAreaWidgetContents = new QWidget(); scrollAreaWidgetContents->setObjectName(QString::fromUtf8("scrollAreaWidgetContents")); scrollAreaWidgetContents->setGeometry(QRect(0, 0, 399, 39)); scrollArea->setWidget(scrollAreaWidgetContents); pushButton_2 = new QPushButton(centralwidget); pushButton_2->setObjectName(QString::fromUtf8("pushButton_2")); pushButton_2->setGeometry(QRect(840, 490, 93, 28)); pushButton = new QPushButton(centralwidget); pushButton->setObjectName(QString::fromUtf8("pushButton")); pushButton->setGeometry(QRect(710, 490, 93, 28)); production_lot_information_win->setCentralWidget(centralwidget); tableView->raise(); pushButton_2->raise(); pushButton->raise(); scrollArea->raise(); statusbar = new QStatusBar(production_lot_information_win); statusbar->setObjectName(QString::fromUtf8("statusbar")); production_lot_information_win->setStatusBar(statusbar); toolBar = new QToolBar(production_lot_information_win); toolBar->setObjectName(QString::fromUtf8("toolBar")); toolBar->setContextMenuPolicy(Qt::PreventContextMenu); toolBar->setIconSize(QSize(20, 20)); toolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); production_lot_information_win->addToolBar(Qt::TopToolBarArea, toolBar); toolBar->addAction(action); toolBar->addAction(action_2); toolBar->addAction(action_3); toolBar->addAction(action_4); retranslateUi(production_lot_information_win); QMetaObject::connectSlotsByName(production_lot_information_win); } // setupUi void retranslateUi(QMainWindow *production_lot_information_win) { production_lot_information_win->setWindowTitle(QApplication::translate("production_lot_information_win", "\347\224\237\344\272\247\346\211\271\346\254\241", nullptr)); action->setText(QApplication::translate("production_lot_information_win", "\346\226\260\345\242\236", nullptr)); action_2->setText(QApplication::translate("production_lot_information_win", "\344\277\256\346\224\271", nullptr)); action_3->setText(QApplication::translate("production_lot_information_win", "\345\210\240\351\231\244", nullptr)); action_4->setText(QApplication::translate("production_lot_information_win", "\346\237\245\350\257\242", nullptr)); pushButton_2->setText(QApplication::translate("production_lot_information_win", "\345\217\226\346\266\210", nullptr)); pushButton->setText(QApplication::translate("production_lot_information_win", "\347\241\256\345\256\232", nullptr)); toolBar->setWindowTitle(QApplication::translate("production_lot_information_win", "toolBar", nullptr)); } // retranslateUi }; namespace Ui { class production_lot_information_win: public Ui_production_lot_information_win {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_PRODUCTION_LOT_INFORMATION_WIN_H
92e8fe568513c1b84faeb8aa9eb1d375571a1980
ce5e253b71be0bb49d239114b0c02b94f715dfe8
/ide/vs/JaSmartObject/temp_project/test_uuid.cpp
3924006ef544e605a35ff9dba457d1b2579f8daf
[]
no_license
PrabhuSammandam/JaSmartObject
fcc2516a685fc985cc35e49b8c8661536197727c
c9e6df7ed9ef9c0c6ff5c8e4c7ded9e86cc0fe0d
refs/heads/master
2021-01-22T01:47:53.503329
2018-12-21T14:37:17
2018-12-21T14:37:17
102,236,037
0
0
null
null
null
null
UTF-8
C++
false
false
969
cpp
test_uuid.cpp
#include <iostream> #include "Uuid.h" #include "OsalRandom.h" using namespace std; using namespace ja_iot::base; using namespace ja_iot::osal; void test_uuid() { uint8_t buf[16]; Uuid uuid1{}; OsalRandom::get_random_bytes(buf, 16); uuid1.set_value(buf, 16); Uuid uuid2{ uuid1 };// copy constructor Uuid uuid3{ std::move(uuid2) };// move constructor Uuid uuid4 = uuid3;// assignment operator Uuid uuid5 = std::move(uuid4);// move operator if (uuid1 == uuid5) { printf("passed\n"); } std::string uuid_string; uuid5 >> uuid_string;// to string Uuid uuid6{}; auto str_len = uuid_string.size(); cout << uuid_string << endl; uuid6 << uuid_string; // from string if (uuid1 == uuid6) { printf("passed\n"); } if (!uuid6.is_nil()) { printf("passed\n"); } uuid6.clear(); if (uuid6.is_nil()) { printf("passed\n"); } cout << uuid1.to_string() << endl; if (Uuid::is_valid_uuid_string(uuid_string)) { printf("passed\n"); } }
d5116ed92f5bd7b818850f50e0c5e18283293e28
dbbdcc830eb1cc6d85c82dbf95b0a8ca0ff1fdd1
/opengl/engine/FramebufferObject.hpp
ff02cf6ceee9f165146b01ebebf294352277d22b
[]
no_license
VladislavKhudziakov/obj_viewer
042108453c7dc6b44d6ef25a72fb50c50b68f0ab
b7ed06259e3ce09b88025db64fa3c10854766156
refs/heads/master
2020-06-02T02:23:29.804323
2019-06-29T21:26:43
2019-06-29T21:26:43
191,004,420
1
0
null
null
null
null
UTF-8
C++
false
false
607
hpp
FramebufferObject.hpp
// // FramebufferObject.hpp // opengl // // Created by Vladislav Khudiakov on 6/29/19. // Copyright © 2019 Vladislav Khudiakov. All rights reserved. // #ifndef FramebufferObject_hpp #define FramebufferObject_hpp #include <iostream> #include "ITexture.hpp" #include "RenderbufferObject.hpp" namespace Engine { class FBO { unsigned int fbo; public: FBO(); void attachColorbuffer(const ITexture& ); void attachRenderbuffer(const RBO& ); void use() const; void unuse() const; unsigned int get() const; void checkStatus(); }; } #endif /* FramebufferObject_hpp */
a2841d2a28af7e0bf8e77bc2326f59a78450aa63
a92b18defb50c5d1118a11bc364f17b148312028
/src/prod/src/data/tstore/MergeHelper.h
eae458e547464700196dda95628cbfe1eea1409b
[ "MIT" ]
permissive
KDSBest/service-fabric
34694e150fde662286e25f048fb763c97606382e
fe61c45b15a30fb089ad891c68c893b3a976e404
refs/heads/master
2023-01-28T23:19:25.040275
2020-11-30T11:11:58
2020-11-30T11:11:58
301,365,601
1
0
MIT
2020-11-30T11:11:59
2020-10-05T10:05:53
null
UTF-8
C++
false
false
6,212
h
MergeHelper.h
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #pragma once namespace Data { namespace TStore { class MergeHelper : public KObject<MergeHelper>, public KShared<MergeHelper> { K_FORCE_SHARED(MergeHelper) public: static NTSTATUS Create( __in KAllocator& Allocator, __out MergeHelper::SPtr& Result); ktl::Awaitable<bool> ShouldMerge( __in MetadataTable& mergeTable, __out KSharedArray<ULONG32>::SPtr& mergeList); // // Determine which file ids to merge. // KSharedArray<ULONG32>::SPtr GetMergeList(__in MetadataTable & mergeTable); // // Get or set the file count for merge. // Exposed for testability only. // __declspec (property(get = get_mergeFilesCountThreshold, put = set_mergeFilesCountThreshold)) ULONG32 MergeFilesCountThreshold; ULONG32 get_mergeFilesCountThreshold() const { return mergeFilesCountThreshold_; } void set_mergeFilesCountThreshold(__in ULONG32 value) { mergeFilesCountThreshold_ = value; } // // Get or sets the percentage of invalid entries that will result in merge. // Exposed for testability only. // __declspec (property(get = get_percentageOfInvalidEntriesPerFile, put = set_percentageOfInvalidEntriesPerFile)) ULONG32 PercentageOfInvalidEntriesPerFile; ULONG32 get_percentageOfInvalidEntriesPerFile() const { return percentageOfInvalidEntriesPerFile_; } void set_percentageOfInvalidEntriesPerFile(__in ULONG32 value) { percentageOfInvalidEntriesPerFile_ = value; } // // Gets or sets the percentage of deleted entries that will result in merge // __declspec(property(get = get_PercentageOfDeletedEntriesPerFile, put = set_percentageOfDeletedEntriesPerFile)) ULONG32 PercentageOfDeletedEntriesPerFile; ULONG32 get_percentageOfDeletedEntriesPerFile() const { return percentageOfDeletedEntriesPerFile_; } void set_percentageOfDeletedEntriesPerFile(__in ULONG32 value) { percentageOfDeletedEntriesPerFile_ = value; } // Exposed for testability only. __declspec (property(get = get_FileCountMergeConfiguration, put = set_FileCountMergeConfiguration)) FileCountMergeConfiguration::SPtr FileCountMergeConfigurationSPtr; FileCountMergeConfiguration::SPtr get_FileCountMergeConfiguration() { return fileCountMergeConfigurationSPtr_; } void set_FileCountMergeConfiguration(__in FileCountMergeConfiguration & config) { fileCountMergeConfigurationSPtr_ = &config; } // Default is zero. ULONG32 NumberOfInvalidEntries; ULONG64 SizeOnDiskThreshold; // Gets the Merge Policy __declspec (property(get = get_mergePolicy, put = set_mergePolicy)) MergePolicy CurrentMergePolicy; MergePolicy get_mergePolicy() const { return mergePolicy_; } void set_mergePolicy(__in MergePolicy value) { mergePolicy_ = value; } private: static ULONG FileTypeHashFunc(__in const USHORT & key) { return ~key; } ktl::Awaitable<bool> ShouldMergeDueToFileCountPolicy( __in MetadataTable& mergeTable, __out KSharedArray<ULONG32>::SPtr& filesToBeMerged); ktl::Awaitable<bool> ShouldMergeForSizeOnDiskPolicy(__in MetadataTable& mergeTable); bool IsFileQualifiedForInvalidEntriesMergePolicy(__in Data::KeyValuePair<ULONG32, FileMetadata::SPtr> item); bool IsFileQualifiedForDeletedEntriesMergePolicy(__in Data::KeyValuePair<ULONG32, FileMetadata::SPtr> item); bool IsMergePolicyEnabled(__in MergePolicy mergePolicy); void CleanMap(); void AssertIfMapIsNotClean(); // Approximate size, 200 MB, of a typical unmerged checkpoint file. static const LONG64 ApproxCheckpointFileSize = 200LL << 20; // // Default file count threshold for invalid entries merge policy. // static const ULONG32 DefaultMergeFilesCountThreshold = 3; // // Default unutilization threshold for invalid entries merge policy. // static const ULONG32 DefaultPercentageOfInvalidEntriesPerFile = 33; // // Default threshold for percentage of deleted entries for a file to be considered for merge. // static const ULONG32 DefaultPercentageOfDeletedEntriesPerFile = 33; // Default threshold, ~30 200MB files = 6GB, for total size on disk for Size on Disk Merge Policy to be triggered. static const LONG64 DefaultSizeForSizeOnDiskPolicy = 30 * ApproxCheckpointFileSize; // Gets or sets the file count merge configuration. File count merge configruation. FileCountMergeConfiguration::SPtr fileCountMergeConfigurationSPtr_; // // Invalid Entries Merge Policy Configuration // ULONG32 mergeFilesCountThreshold_; ULONG32 percentageOfInvalidEntriesPerFile_; ULONG32 percentageOfDeletedEntriesPerFile_; MergePolicy mergePolicy_; Dictionary<ULONG32, KSharedArray<ULONG32>::SPtr>::SPtr fileTypeToMergeList_; }; } }
d60dd616bc8dac4b1955b5f546a0b1e90026fbf9
be06b975f3a4e122f01ec8a086dade18e8504c7e
/Code/scattering3DP.h
91ce670d72920bb9c74ce679fee6479e51e79384
[]
no_license
trannhan/Create-meta-materials
272dcf8581e445a164ffdd2ae556f78dc16a7b80
0e534cd68326d296587181fd94368023f0c4c7e3
refs/heads/master
2021-01-10T01:56:28.360951
2016-02-19T04:12:47
2016-02-19T04:12:47
52,060,712
0
0
null
null
null
null
UTF-8
C++
false
false
18,442
h
scattering3DP.h
#include "common.h" /////////////////////////////////////////////////////////////////// template < class RealVector, class ComplexVector, class Complex, class Real, class Long, class Integer > class Scattering3DP { public: Integer NumParticlePerSide; Integer NumParticlePerPlane; Integer NumCubePerSide; Integer NumCubePerPlane; Integer NumParticlePerSmallCubeSide; Real DomainSize; Real SmallCubeSize; Real ParticleRadius; Real ParticleDistance; Real Kappa; Long TotalParticles; Integer TotalCubes; Integer TotalCollocationPoints; RealVector WaveDirection; //ComplexVector u0; //Initial field Complex OriginalRefractionCoef; Complex DesiredRefractionCoef; Real Distribution; Real VolQ; //Volume of the cube that contains all particles Real SmallCubeVol; Complex p; Complex h; Complex BoundaryImpedance; private: Complex ha2k; //coeficient of entries in Matrix A Complex ha2kPI4; //coeficient of entries in Matrix A Real iNumCubePerPlane; //inverse(NumCubePerPlane) Real iNumCubePerSide; //inverse(NumCubePerSide) RealVector x; //Particles positions RealVector y; RealVector z; public: Scattering3DP() { } /////////////////////////////////////////////////////////////////// virtual ~Scattering3DP() { } /////////////////////////////////////////////////////////////////// void Input(Real ParticleRadius, Real Kappa, RealVector WaveDirection, Real ParticleDistance, Long TotalParticles) { this->ParticleRadius = ParticleRadius; this->Kappa = Kappa; this->WaveDirection = WaveDirection; this->ParticleDistance = ParticleDistance; this->TotalParticles = TotalParticles; } /////////////////////////////////////////////////////////////////// void Input(Real ParticleRadius, Real Kappa, RealVector WaveDirection, Real ParticleDistance, Long TotalParticles,\ Complex OriginalRefractionCoef, Complex DesiredRefractionCoef, Real Distribution, Real VolQ, Integer TotalCubes, \ Integer TotalCollocationPoints) { this->ParticleRadius = ParticleRadius; this->Kappa = Kappa; this->WaveDirection = WaveDirection; this->ParticleDistance = ParticleDistance; this->TotalParticles = TotalParticles; this->OriginalRefractionCoef = OriginalRefractionCoef; this->DesiredRefractionCoef = DesiredRefractionCoef; this->Distribution = Distribution; this->VolQ = VolQ; this->TotalCubes = TotalCubes; this->TotalCollocationPoints = TotalCollocationPoints; } /////////////////////////////////////////////////////////////////// void Init() { // Number of particles on a side of a cube of size 1 NumParticlePerSide = round(pow(TotalParticles,1.0/3)); NumParticlePerPlane = pow(NumParticlePerSide,2); NumCubePerSide = ceil(pow(TotalCubes,1.0/3)); NumCubePerPlane = pow(NumCubePerSide,2); DomainSize = (NumParticlePerSide-1)*ParticleDistance; SmallCubeSize = DomainSize/NumCubePerSide; SmallCubeVol = pow(SmallCubeSize,3); NumParticlePerSmallCubeSide = floor(NumParticlePerSide/NumCubePerSide); //Performance tune: iNumCubePerPlane = 1.0/NumCubePerPlane; iNumCubePerSide = 1.0/NumCubePerSide; // Initial field satisfies Helmholtz equation in R^3 //u0 = InitField(); //Cubes positions UniformDistributeCubes(); p = pow(K,2)*(cpow(OriginalRefractionCoef,2) - cpow(DesiredRefractionCoef,2)); Real h1 = creal(p)/(PI4*Distribution); Real h2 = cimag(p)/(PI4*Distribution); h = (h1+I*h2); ha2k = h*Distribution*SmallCubeVol; ha2kPI4 = ha2k*PI4; BoundaryImpedance = h/pow(ParticleRadius,Kappa); } /////////////////////////////////////////////////////////////////// void UniformDistributeParticles() { // Set the position for each particle (uniformly distributed) Real x0,y0,z0,t; //Set the cube centered at the origin t = pow(VolQ,1.0/3)/2; x0 = -t; y0 = -t; z0 = -t; // The first particle [x1,y1,z1] is at the left bottom corner of the // cube and is called particle number 1. x = RealVector(NumParticlePerSide); y = RealVector(NumParticlePerSide); z = RealVector(NumParticlePerSide); for(Integer s = 0; s < NumParticlePerSide; s++) { t = ParticleDistance*s; x[s] = x0 + t; y[s] = y0 + t; z[s] = z0 + t; } } /////////////////////////////////////////////////////////////////// void UniformDistributeCubes() { // Set the position for each cube (uniformly distributed) Real x0,y0,z0,t; //Set the cube centered at the origin t = pow(VolQ,1.0/3)/2; x0 = -t+SmallCubeSize/2; y0 = x0; z0 = x0; // The first small cube [x1,y1,z1] is at the left bottom corner of the // cube and is called cube number 1. x = RealVector(NumCubePerSide); y = RealVector(NumCubePerSide); z = RealVector(NumCubePerSide); for(Integer s = 0; s < NumCubePerSide; s++) { t = SmallCubeSize*s; x[s] = x0 + t; y[s] = y0 + t; z[s] = z0 + t; } } /////////////////////////////////////////////////////////////////// /* inline const Real DistributionFunc(const Long& CubeNumber) { return 1; } /////////////////////////////////////////////////////////////////// inline const Complex DesiredRefractionCoefFunc(const Long& CubeNumber) { return sqrt(0.2); } /////////////////////////////////////////////////////////////////// inline const Complex OriginalRefractionCoefFunc(const Long& CubeNumber) { return 1; } /////////////////////////////////////////////////////////////////// inline const Complex p_Func(const Long& CubeNumber) { return cpow(K,2)*(cpow(OriginalRefractionCoefFunc(CubeNumber),2) - cpow(DesiredRefractionCoefFunc(CubeNumber),2)); } /////////////////////////////////////////////////////////////////// inline const Complex h_Func(const Long& CubeNumber) { Complex p = p_Func(CubeNumber); Real h1 = creal(p)/(PI4*DistributionFunc(CubeNumber)); Real h2 = cimag(p)/(PI4*DistributionFunc(CubeNumber)); return (h1+I*h2); } */ /////////////////////////////////////////////////////////////////// //Uniform Distribution inline const RealVector Particle2Position(Long s) { // Return the position in the 3D cube of particle s // The first particle [x1,y1,z1] is at the left, bottom corner of the // cube and is called particle number 1. The next one will be on the same // row, go to the right. When finishing the first line, go to the second line // and start at the first column again. When finishing the first plane, move // up. // [x1,x2,x3] is an array index Integer x3 = floor(s/(NumParticlePerPlane)); // Find the plane where the particle s is on Integer x2 = s%NumParticlePerSide; Integer t = s%(NumParticlePerPlane); Integer x1 = floor(t/NumParticlePerSide); RealVector v(3); v[0] = x[x1]; v[1] = y[x2]; v[2] = z[x3]; return v; } /////////////////////////////////////////////////////////////////// //Uniform Distribution - this function increases performance inline const void Particle2Position(Long s,Real& xs,Real& ys,Real& zs) { // Return the position in the 3D cube of particle s // The first particle [x1,y1,z1] is at the left, bottom corner of the // cube and is called particle number 1. The next one will be on the same // row, go to the right. When finishing the first line, go to the second line // and start at the first column again. When finishing the first plane, move // up. // [x1,x2,x3] is an array index Integer x1,x2,x3,t; x3 = floor(s/NumParticlePerPlane); // Find the plane where the particle s is on x2 = s%NumParticlePerSide; t = s%(NumParticlePerPlane); x1 = floor(t/NumParticlePerSide); xs = x[x1]; ys = y[x2]; zs = z[x3]; } /////////////////////////////////////////////////////////////////// //Uniform Distribution inline const RealVector Cube2Position(Integer s) { // Return the position in 3D of cube s // The first small cube [x1,y1,z1] is at the left, bottom corner of the big // cube and is called small cube number 1. The next one will be on the same // row, go to the right. When finishing the first line, go to the second line // and start at the first column again. When finishing the first plane, move // up. // [x1,x2,x3] is an array index Integer x1,x2,x3,t; x3 = floor(s/NumCubePerPlane); // Find the plane where the cube s is on x2 = s%NumCubePerSide; t = s%(NumCubePerPlane); x1 = floor(t/NumCubePerSide); RealVector v(3); v[0] = x[x1]; v[1] = y[x2]; v[2] = z[x3]; return v; } /////////////////////////////////////////////////////////////////// //Uniform Distribution - this function increases performance inline const void Cube2Position(Integer s,Real& xs,Real& ys,Real& zs) { // Return the position in 3D of cube s // The first small cube [x1,y1,z1] is at the left, bottom corner of the big // cube and is called small cube number 1. The next one will be on the same // row, go to the right. When finishing the first line, go to the second line // and start at the first column again. When finishing the first plane, move // up. // [x1,x2,x3] is an array index Integer x1,x2,x3,t; x3 = floor(s*iNumCubePerPlane); // Find the plane where the cube s is on x2 = s%NumCubePerSide; t = s%(NumCubePerPlane); x1 = floor(t*iNumCubePerSide); xs = x[x1]; ys = y[x2]; zs = z[x3]; } /////////////////////////////////////////////////////////////////// Integer FindCube(Integer ParticleNumber) { //Find cube number that contains particle ParticleNumber // [x1,x2,x3] is an array index of particle ParticleNumber Integer x1,x2,x3,t,CubeNumber; x3 = floor(ParticleNumber/NumParticlePerPlane); // Find the plane where the particle ParticleNumber is on x2 = ParticleNumber%NumParticlePerSide; t = ParticleNumber%(NumParticlePerPlane); x1 = floor(t/NumParticlePerSide); //Find the index of the small cube containing particle ParticleNumber x1 = floor(x1/NumParticlePerSmallCubeSide); x2 = floor(x2/NumParticlePerSmallCubeSide); x3 = floor(x3/NumParticlePerSmallCubeSide); if(x1>=NumCubePerSide) x1 = NumCubePerSide - 1; if(x2>=NumCubePerSide) x2 = NumCubePerSide - 1; if(x3>=NumCubePerSide) x3 = NumCubePerSide - 1; CubeNumber = x2 + x1*NumCubePerSide + x3*NumCubePerPlane; return CubeNumber; } /////////////////////////////////////////////////////////////////// Integer FindCubeOfCollocation(Integer CollocationPoint) { //Find cube number that contains particle CollocationPoint // [x1,x2,x3] is an array index of the CollocationPoint Integer x1,x2,x3,t,CubeNumber; Integer NumCollocationPointsPerSide = round(pow(TotalCollocationPoints,1.0/3)); Integer NumCollocationPointsPerPlane = pow(NumCollocationPointsPerSide,2); Integer NumCollocationPointsPerSmallCubeSide = floor(NumCollocationPointsPerSide/NumCubePerSide); x3 = floor(CollocationPoint/NumCollocationPointsPerPlane); // Find the plane where the CollocationPoint is on x2 = CollocationPoint%NumCollocationPointsPerSide; t = CollocationPoint%(NumCollocationPointsPerPlane); x1 = floor(t/NumCollocationPointsPerSide); //Find the index of the small cube containing the CollocationPoint x1 = floor(x1/NumCollocationPointsPerSmallCubeSide); x2 = floor(x2/NumCollocationPointsPerSmallCubeSide); x3 = floor(x3/NumCollocationPointsPerSmallCubeSide); if(x1>=NumCubePerSide) x1 = NumCubePerSide - 1; if(x2>=NumCubePerSide) x2 = NumCubePerSide - 1; if(x3>=NumCubePerSide) x3 = NumCubePerSide - 1; CubeNumber = x2 + x1*NumCubePerSide + x3*NumCubePerPlane; return CubeNumber; } /////////////////////////////////////////////////////////////////// inline const Complex Green(Long s, Long t) { // Create a Green function in R^3, s!=t // Distance from cube s to cube t in R^3 /* RealVector spos = Cube2Position(s); RealVector tpos = Cube2Position(t); RealVector d(3); d[0] = spos[0]-tpos[0]; d[1] = spos[1]-tpos[1]; d[2] = spos[2]-tpos[2]; Real st = Norm<RealVector,Real>(d, 2); */ //For performance: Real xs,ys,zs,xt,yt,zt; Cube2Position(s,xs,ys,zs); Cube2Position(t,xt,yt,zt); Real st = sqrt(pow(xs-xt,2)+pow(ys-yt,2)+pow(zs-zt,2)); if(st<=ZERO) return 0; Complex G = cexp(I*K*st)/(PI4*st); //cout<<"\nnorm(G["<<s<<","<<t<<"])="<<cnorm<Real, Complex>(G); return G; } /////////////////////////////////////////////////////////////////// inline ComplexVector InitField() { // Create an inittial field u0 satisfying Helmholtz equation in R^3 ComplexVector u0(TotalParticles); RealVector parpos; for(Long s = 0; s < TotalParticles; s++) { parpos = Cube2Position(s); u0[s] = cexp(I*K*Dot<Real,RealVector>(WaveDirection,parpos)); } return u0; } /////////////////////////////////////////////////////////////////// inline const Complex InitField(Long s) { // Create an inittial field u0 satisfying Helmholtz equation in R^3 /* RealVector parpos = Cube2Position(s); Complex u0 = cexp(I*K*Dot<Real,RealVector>(WaveDirection,parpos)); */ //For performance: Real xs,ys,zs; Cube2Position(s,xs,ys,zs); Complex u0 = cexp(I*K*(WaveDirection[0]*xs + WaveDirection[1]*ys + WaveDirection[2]*zs)); return u0; } /////////////////////////////////////////////////////////////////// /* inline const ComplexVector AuFunc(const ComplexVector u) { // Compute A*u ComplexVector Au(TotalCubes); for(Long s = 0; s < TotalCubes; s++) { for(Long t = 0; t < TotalCubes; t++) { if (s!=t) Au(s) = Au(s) + (Green(s,t)*h_Func(t)*DistributionFunc(t)*SmallCubeVol*PI4)*u(t); else Au(s) = Au(s) + u(t); //Au(s) += CoefMat(s,t)*u(t); } } return Au; } */ /////////////////////////////////////////////////////////////////// //Matrix A in Ax=u0 inline const Complex CoefMat(Long i, Long j) { // Generate value for entry A(i,j) in Au=u0 if (i==j) return 1; return (Green(i,j)*ha2kPI4); } /////////////////////////////////////////////////////////////////// //Matrix A in Ax=u0, Performance tune inline const Complex CoefMatFast(Long s, Long t) { // Generate value for entry A(i,j) in Au=u0 if (s==t) return 1; Real xs,ys,zs,xt,yt,zt; Cube2Position(s,xs,ys,zs); Cube2Position(t,xt,yt,zt); Real st = sqrt(pow(xs-xt,2)+pow(ys-yt,2)+pow(zs-zt,2)); if(st<=ZERO) return 0; //Green function*PI4: Complex G = cexp(I*K*st)/st; return (G*ha2k); } };
ba98531371d6648f1ae1ba2393335ad2f31ddae5
8301c6345984b2f406b7dc8b68f7afb32c324201
/cpp/asciimation/scroll_left.hpp
8cac74217d6989f3140f99e81fa2d39625631647
[]
no_license
mpresident14/Projects
a9babaaf5497fad52d94fb8bc730fd24df4890c9
4ffb64423e60535ca032db3d631669de4999a8d6
refs/heads/master
2023-01-23T06:51:53.134313
2023-01-10T06:06:12
2023-01-10T06:06:12
105,496,055
0
1
null
null
null
null
UTF-8
C++
false
false
248
hpp
scroll_left.hpp
#ifndef SCROLL_LEFT_HPP #define SCROLL_LEFT_HPP #include "asciimation.hpp" class ScrollLeft : public Asciimation { public: ScrollLeft(const char *filename); void animate(); private: void update(); size_t currentCol_; }; #endif
f2dd1d9bfbfba87430173224824344586e8f51cf
526ee75e53a91f391e479d29b7ca1159bb45f4d3
/practice/pointers/pointers.cpp
ac7e72d2f64591e522c8c9b5e82be96ae7ac721b
[]
no_license
j0sht/csci160
44714c06781d59db446b93aff85cb9f1beada90e
bd57e63aba943040fd7cc0da82c2c7da0af80632
refs/heads/master
2021-03-27T11:08:16.401898
2017-12-08T19:46:59
2017-12-08T19:46:59
103,895,193
0
0
null
null
null
null
UTF-8
C++
false
false
1,059
cpp
pointers.cpp
#include <cstdio> #include <cstdlib> int main() { // Write a complete program that: // 1. Declares a float* variable to store an array address float *fs; // 2. Declares an int variable to store the size of the array int size; // 3. Asks the user what array size they want and reads // the size they enter printf("Enter array size: "); scanf("%d", &size); // 4. Allocates an array of that many floats fs = new float[size]; // 5. Checks that the allocation succeeded, ending the program // if it did not succeed if (fs == NULL) { printf("ERROR: Could not allocate array of size %d\n", size); exit(1); } // 6. Prompts the user to enter the specified number of values and // stores them in the array. for (int i = 0; i < size; i++) { printf("Enter value for index %d: ", i); scanf("%f", &(fs[i])); } // 7. Prints the array contents for (int i = 0; i < size; i++) printf("%d = %g\n", i, fs[i]); // 8. Deletes the array delete [] fs; return 0; }
80319e11b0c3242ca88bc875a9c8c6aa6dbaea3e
f79dec3c4033ca3cbb55d8a51a748cc7b8b6fbab
/net/tigervnc/patches/patch-unix_xserver_hw_vnc_InputXKB.cc
8ea063590ba66e4492d687be8bd3666ef0674ef9
[]
no_license
jsonn/pkgsrc
fb34c4a6a2d350e8e415f3c4955d4989fcd86881
c1514b5f4a3726d90e30aa16b0c209adbc276d17
refs/heads/trunk
2021-01-24T09:10:01.038867
2017-07-07T15:49:43
2017-07-07T15:49:43
2,095,004
106
47
null
2016-09-19T09:26:01
2011-07-23T23:49:04
Makefile
UTF-8
C++
false
false
3,161
cc
patch-unix_xserver_hw_vnc_InputXKB.cc
$NetBSD: patch-unix_xserver_hw_vnc_InputXKB.cc,v 1.2 2015/07/21 21:51:39 markd Exp $ --- unix/xserver/hw/vnc/InputXKB.c.orig 2015-07-11 13:00:36.000000000 +0000 +++ unix/xserver/hw/vnc/InputXKB.c @@ -212,7 +212,7 @@ unsigned vncGetKeyboardState(void) { DeviceIntPtr master; - master = GetMaster(vncKeyboardDev, KEYBOARD_OR_FLOAT); + master = vncKeyboardDev->master; return XkbStateFieldFromRec(&master->key->xkbInfo->state); } @@ -234,7 +234,7 @@ unsigned vncGetLevelThreeMask(void) return 0; } - xkb = GetMaster(vncKeyboardDev, KEYBOARD_OR_FLOAT)->key->xkbInfo->desc; + xkb = vncKeyboardDev->master->key->xkbInfo->desc; act = XkbKeyActionPtr(xkb, keycode, state); if (act == NULL) @@ -259,7 +259,7 @@ KeyCode vncPressShift(void) if (state & ShiftMask) return 0; - xkb = GetMaster(vncKeyboardDev, KEYBOARD_OR_FLOAT)->key->xkbInfo->desc; + xkb = vncKeyboardDev->master->key->xkbInfo->desc; for (key = xkb->min_key_code; key <= xkb->max_key_code; key++) { XkbAction *act; unsigned char mask; @@ -299,7 +299,7 @@ size_t vncReleaseShift(KeyCode *keys, si count = 0; - master = GetMaster(vncKeyboardDev, KEYBOARD_OR_FLOAT); + master = vncKeyboardDev->master; xkb = master->key->xkbInfo->desc; for (key = xkb->min_key_code; key <= xkb->max_key_code; key++) { XkbAction *act; @@ -355,7 +355,7 @@ KeyCode vncPressLevelThree(void) return 0; } - xkb = GetMaster(vncKeyboardDev, KEYBOARD_OR_FLOAT)->key->xkbInfo->desc; + xkb = vncKeyboardDev->master->key->xkbInfo->desc; act = XkbKeyActionPtr(xkb, keycode, state); if (act == NULL) @@ -386,7 +386,7 @@ size_t vncReleaseLevelThree(KeyCode *key count = 0; - master = GetMaster(vncKeyboardDev, KEYBOARD_OR_FLOAT); + master = vncKeyboardDev->master; xkb = master->key->xkbInfo->desc; for (key = xkb->min_key_code; key <= xkb->max_key_code; key++) { XkbAction *act; @@ -429,7 +429,7 @@ KeyCode vncKeysymToKeycode(KeySym keysym if (new_state != NULL) *new_state = state; - xkb = GetMaster(vncKeyboardDev, KEYBOARD_OR_FLOAT)->key->xkbInfo->desc; + xkb = vncKeyboardDev->master->key->xkbInfo->desc; for (key = xkb->min_key_code; key <= xkb->max_key_code; key++) { unsigned int state_out; KeySym dummy; @@ -486,7 +486,7 @@ int vncIsLockModifier(KeyCode keycode, u XkbDescPtr xkb; XkbAction *act; - xkb = GetMaster(vncKeyboardDev, KEYBOARD_OR_FLOAT)->key->xkbInfo->desc; + xkb = vncKeyboardDev->master->key->xkbInfo->desc; act = XkbKeyActionPtr(xkb, keycode, state); if (act == NULL) @@ -524,7 +524,7 @@ int vncIsAffectedByNumLock(KeyCode keyco if (numlock_keycode == 0) return 0; - xkb = GetMaster(vncKeyboardDev, KEYBOARD_OR_FLOAT)->key->xkbInfo->desc; + xkb = vncKeyboardDev->master->key->xkbInfo->desc; act = XkbKeyActionPtr(xkb, numlock_keycode, state); if (act == NULL) @@ -558,7 +558,7 @@ KeyCode vncAddKeysym(KeySym keysym, unsi KeySym *syms; KeySym upper, lower; - master = GetMaster(vncKeyboardDev, KEYBOARD_OR_FLOAT); + master = vncKeyboardDev->master; xkb = master->key->xkbInfo->desc; for (key = xkb->max_key_code; key >= xkb->min_key_code; key--) { if (XkbKeyNumGroups(xkb, key) == 0)
4058f3d969eea0d7ac99585ec9b41ad02ea15792
cf6e89cbb246fe4135f12a7ee8392008c3c03510
/userInterFace.hpp
01db84ac093dbccf195cd10bfa2e364eb72fab09
[]
no_license
Behyna/UT-Trip
58252ac5a0d3a97cdd0ef295dd8c80d8eef112a0
bedbe1c819fdca42793f92e33bb6e2c592cf56ee
refs/heads/main
2023-08-08T04:10:38.041765
2021-09-20T12:34:38
2021-09-20T12:34:38
408,417,216
0
0
null
null
null
null
UTF-8
C++
false
false
336
hpp
userInterFace.hpp
#ifndef USERINTERFACE_HPP #define USERINTERFACE_HPP "USERINTERFACE_HPP" #include "utrip.hpp" #include "user.hpp" class UserInterface{ public: UserInterface(); void readData(std::string hotelsDataAddress, std::string ratingsDataAddress); void getCommands(std::string command); private: Utrip* utrip; User* user; }; #endif