hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
22e212002a88c7e751084384cc1acc28ec76208a
315
hpp
C++
Main course/Homework3/Problem1/Header files/Counter.hpp
nia-flo/FMI-OOP
9d6ab384b5b7a48e76965ca5bff1e6a995b1bcba
[ "MIT" ]
null
null
null
Main course/Homework3/Problem1/Header files/Counter.hpp
nia-flo/FMI-OOP
9d6ab384b5b7a48e76965ca5bff1e6a995b1bcba
[ "MIT" ]
null
null
null
Main course/Homework3/Problem1/Header files/Counter.hpp
nia-flo/FMI-OOP
9d6ab384b5b7a48e76965ca5bff1e6a995b1bcba
[ "MIT" ]
null
null
null
#pragma once class Counter { public: Counter(); Counter(int initial); Counter(int initial, unsigned step); virtual void increment(); virtual int getTotal() const; virtual unsigned getStep() const; protected: const int DEFAULT_INITIAL_VALUE = 0; const int DEFAULT_STEP = 1; int value; unsigned step; };
15.75
37
0.733333
nia-flo
22f11ea3e8f409014978db4f07563439b38c7790
418
cpp
C++
code/client/src/core/hooks/application.cpp
mufty/MafiaMP
2dc0e3362c505079e26e598bd4a7f4b5de7400bc
[ "OpenSSL" ]
16
2021-10-08T17:47:04.000Z
2022-03-28T13:26:37.000Z
code/client/src/core/hooks/application.cpp
mufty/MafiaMP
2dc0e3362c505079e26e598bd4a7f4b5de7400bc
[ "OpenSSL" ]
4
2022-01-19T08:11:57.000Z
2022-01-29T19:02:24.000Z
code/client/src/core/hooks/application.cpp
mufty/MafiaMP
2dc0e3362c505079e26e598bd4a7f4b5de7400bc
[ "OpenSSL" ]
4
2021-10-09T11:15:08.000Z
2022-01-27T22:42:26.000Z
#include <MinHook.h> #include <utils/hooking/hook_function.h> #include <utils/hooking/hooking.h> #include "../../sdk/patterns.h" bool __fastcall C_GameFramework__IsSuspended(void *_this) { return false; } static InitFunction init([]() { // Don't pause the game when out of window MH_CreateHook((LPVOID)SDK::gPatterns.C_GameFramework__IsSuspendedAddr, (PBYTE)&C_GameFramework__IsSuspended, nullptr); });
27.866667
122
0.746411
mufty
22fb5c516feb119498f1af063d0adf8783349e05
1,542
cpp
C++
src/problem_14.cpp
MihailsKuzmins/daily-coding-problem
ca8b7589b6ce2eb6dec846829c82a12c1272a5ec
[ "Apache-2.0" ]
null
null
null
src/problem_14.cpp
MihailsKuzmins/daily-coding-problem
ca8b7589b6ce2eb6dec846829c82a12c1272a5ec
[ "Apache-2.0" ]
null
null
null
src/problem_14.cpp
MihailsKuzmins/daily-coding-problem
ca8b7589b6ce2eb6dec846829c82a12c1272a5ec
[ "Apache-2.0" ]
null
null
null
// The area of a circle is defined as πr^2. Estimate π to 3 decimal places using a Monte Carlo method. // Hint: The basic equation of a circle is x^2 + y^2 = r^2. // Example: // auto result = problem_fourteen(1'000'000); #include <random> #include <math.h> using namespace std; double problem_fourteen(const unsigned int n) noexcept { const double radius_square = 0.25; // r = 0.5, a and b = 1 double pi_estimated = 0; int circle_count = 0; const uniform_real_distribution<double> distr(-0.5, 0.5); default_random_engine random_enginde; for (unsigned int i = 0; i < n; i++) { const auto x = distr(random_enginde); const auto y = distr(random_enginde); if (x * x + y * y <= radius_square) circle_count++; } // see below for explanation const auto pi = 4 * static_cast<double>(circle_count) / n; return round(pi * 1000) / 1000; } // Explanation: // Area (circle) / Area (square) = Points (circle) / Points (square) // We imagined a square with a length of 1, i.e. d = 1, and r = 0.5 (1 / 2) // Area (circle) = PI * r^2; Area (square) = l^2, therefore, the left-hand side is as follows: // (PI * (0.5)^2) / 1^2 => PI * 0.25 / 1 => PI / 4 // Now let us express PI: // PI = 4 * Points (circe) / Points (square) // Implementation // All random numbers we generate are within [-0.5; 0.5], which guarantees that 100% of (x;y) Points // will be withing the quare. So we need to get a probaility that a Point is within the circle // Points (circle) / Points (square). // This probability is compared to the area equations.
32.808511
102
0.667315
MihailsKuzmins
22fc45d7d1beb4bb0cad838f729daa87e94c159e
7,108
cpp
C++
Samples/Client/DirectxUWP/DirectxClientComponent/Common/DeviceResources.cpp
rozele/3dtoolkit
a15fca73be15f96a165dd18e62180de693a5ab86
[ "MIT" ]
null
null
null
Samples/Client/DirectxUWP/DirectxClientComponent/Common/DeviceResources.cpp
rozele/3dtoolkit
a15fca73be15f96a165dd18e62180de693a5ab86
[ "MIT" ]
null
null
null
Samples/Client/DirectxUWP/DirectxClientComponent/Common/DeviceResources.cpp
rozele/3dtoolkit
a15fca73be15f96a165dd18e62180de693a5ab86
[ "MIT" ]
null
null
null
#include "pch.h" #include <Collection.h> #include <windows.graphics.directx.direct3d11.interop.h> #include "DeviceResources.h" #include "DirectXHelper.h" using namespace D2D1; using namespace Microsoft::WRL; using namespace Platform; using namespace Windows::Foundation; using namespace Windows::Graphics::DirectX::Direct3D11; using namespace Windows::Graphics::Display; using namespace Windows::Graphics::Holographic; using namespace Windows::UI::Core; // Constructor for DeviceResources. DX::DeviceResources::DeviceResources() : m_holographicSpace(nullptr), m_supportsVprt(false) { CreateDeviceIndependentResources(); } // Configures resources that don't depend on the Direct3D device. void DX::DeviceResources::CreateDeviceIndependentResources() { // Initialize Direct2D resources. D2D1_FACTORY_OPTIONS options; ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS)); #if defined(_DEBUG) // If the project is in a debug build, enable Direct2D debugging via SDK Layers. options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION; #endif // Initialize the Direct2D Factory. DX::ThrowIfFailed( D2D1CreateFactory( D2D1_FACTORY_TYPE_SINGLE_THREADED, __uuidof(ID2D1Factory3), &options, &m_d2dFactory ) ); // Initialize the DirectWrite Factory. DX::ThrowIfFailed( DWriteCreateFactory( DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory3), &m_dwriteFactory ) ); } // Configures the Direct3D device, and stores handles to it and the device context. void DX::DeviceResources::CreateDeviceResources() { // Creates the Direct3D 11 API device object and a corresponding context. ComPtr<ID3D11Device> device; ComPtr<ID3D11DeviceContext> context; // Init device and device context D3D11CreateDevice( m_dxgiAdapter.Get(), D3D_DRIVER_TYPE_HARDWARE, 0, D3D11_CREATE_DEVICE_BGRA_SUPPORT, nullptr, 0, D3D11_SDK_VERSION, &device, nullptr, &context); device.As(&m_d3dDevice); context.As(&m_d3dContext); // Acquires the DXGI interface for the Direct3D device. ComPtr<IDXGIDevice3> dxgiDevice; DX::ThrowIfFailed( m_d3dDevice.As(&dxgiDevice) ); // Wrap the native device using a WinRT interop object. m_d3dInteropDevice = CreateDirect3DDevice(dxgiDevice.Get()); // Cache the DXGI adapter. // This is for the case of no preferred DXGI adapter, or fallback to WARP. ComPtr<IDXGIAdapter> dxgiAdapter; DX::ThrowIfFailed( dxgiDevice->GetAdapter(&dxgiAdapter) ); DX::ThrowIfFailed( dxgiAdapter.As(&m_dxgiAdapter) ); DX::ThrowIfFailed( m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice) ); DX::ThrowIfFailed( m_d2dDevice->CreateDeviceContext( D2D1_DEVICE_CONTEXT_OPTIONS_NONE, &m_d2dContext ) ); } void DX::DeviceResources::SetHolographicSpace(HolographicSpace^ holographicSpace) { // Cache the holographic space. Used to re-initalize during device-lost scenarios. m_holographicSpace = holographicSpace; InitializeUsingHolographicSpace(); } void DX::DeviceResources::InitializeUsingHolographicSpace() { // The holographic space might need to determine which adapter supports // holograms, in which case it will specify a non-zero PrimaryAdapterId. LUID id = { m_holographicSpace->PrimaryAdapterId.LowPart, m_holographicSpace->PrimaryAdapterId.HighPart }; // When a primary adapter ID is given to the app, the app should find // the corresponding DXGI adapter and use it to create Direct3D devices // and device contexts. Otherwise, there is no restriction on the DXGI // adapter the app can use. if ((id.HighPart != 0) && (id.LowPart != 0)) { UINT createFlags = 0; #ifdef DEBUG if (DX::SdkLayersAvailable()) { createFlags |= DXGI_CREATE_FACTORY_DEBUG; } #endif // Create the DXGI factory. ComPtr<IDXGIFactory1> dxgiFactory; DX::ThrowIfFailed( CreateDXGIFactory2( createFlags, IID_PPV_ARGS(&dxgiFactory) ) ); ComPtr<IDXGIFactory4> dxgiFactory4; DX::ThrowIfFailed(dxgiFactory.As(&dxgiFactory4)); // Retrieve the adapter specified by the holographic space. DX::ThrowIfFailed( dxgiFactory4->EnumAdapterByLuid( id, IID_PPV_ARGS(&m_dxgiAdapter) ) ); } else { m_dxgiAdapter.Reset(); } CreateDeviceResources(); m_holographicSpace->SetDirect3D11Device(m_d3dInteropDevice); // Check for device support for the optional feature that allows setting // the render target array index from the vertex shader stage. D3D11_FEATURE_DATA_D3D11_OPTIONS3 options; m_d3dDevice->CheckFeatureSupport( D3D11_FEATURE_D3D11_OPTIONS3, &options, sizeof(options)); if (options.VPAndRTArrayIndexFromAnyShaderFeedingRasterizer) { m_supportsVprt = true; } } // Validates the back buffer for each HolographicCamera and recreates // resources for back buffers that have changed. // Locks the set of holographic camera resources until the function exits. void DX::DeviceResources::EnsureCameraResources( HolographicFrame^ frame, HolographicFramePrediction^ prediction) { UseHolographicCameraResources<void>([this, frame, prediction](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap) { for (HolographicCameraPose^ pose : prediction->CameraPoses) { HolographicCameraRenderingParameters^ renderingParameters = frame->GetRenderingParameters(pose); CameraResources* pCameraResources = cameraResourceMap[pose->HolographicCamera->Id].get(); pCameraResources->CreateResourcesForBackBuffer(this, renderingParameters); } }); } // Prepares to allocate resources and adds resource views for a camera. // Locks the set of holographic camera resources until the function exits. void DX::DeviceResources::AddHolographicCamera(HolographicCamera^ camera) { UseHolographicCameraResources<void>([this, camera](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap) { cameraResourceMap[camera->Id] = std::make_unique<CameraResources>(camera); }); m_d3dRenderTargetSize = camera->RenderTargetSize; } // Deallocates resources for a camera and removes the camera from the set. // Locks the set of holographic camera resources until the function exits. void DX::DeviceResources::RemoveHolographicCamera(HolographicCamera^ camera) { UseHolographicCameraResources<void>([this, camera](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap) { CameraResources* pCameraResources = cameraResourceMap[camera->Id].get(); if (pCameraResources != nullptr) { pCameraResources->ReleaseResourcesForBackBuffer(this); cameraResourceMap.erase(camera->Id); } }); } // Present the contents of the swap chain to the screen. // Locks the set of holographic camera resources until the function exits. void DX::DeviceResources::Present(HolographicFrame^ frame) { // By default, this API waits for the frame to finish before it returns. // Holographic apps should wait for the previous frame to finish before // starting work on a new frame. This allows for better results from // holographic frame predictions. HolographicFramePresentResult presentResult = frame->PresentUsingCurrentPrediction(HolographicFramePresentWaitBehavior::DoNotWaitForFrameToFinish); }
29.131148
148
0.770962
rozele
fe033aa598dc17ae2171f63cc50814b2ca3d56c1
1,394
cpp
C++
soj/4315.cpp
huangshenno1/project_euler
8a3c91fd11bcb6a6a830e963b1d5aed3f5ff787d
[ "MIT" ]
null
null
null
soj/4315.cpp
huangshenno1/project_euler
8a3c91fd11bcb6a6a830e963b1d5aed3f5ff787d
[ "MIT" ]
null
null
null
soj/4315.cpp
huangshenno1/project_euler
8a3c91fd11bcb6a6a830e963b1d5aed3f5ff787d
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstring> #include <cstdlib> #include <ctime> #include <climits> #include <cmath> #include <cassert> #include <iostream> #include <string> #include <vector> #include <set> #include <map> #include <list> #include <queue> #include <stack> #include <deque> #include <algorithm> using namespace std; #define ll long long #define pii pair<int, int> #define fr first #define sc second #define mp make_pair #define FOR(i,j,k) for(int i=j;i<=(k);i++) #define FORD(i,j,k) for(int i=j;i>=(k);i--) #define REP(i,n) for(int i=0;i<(n);i++) const int maxn = 100005; int n, a[maxn]; int dp[2][32][2]; int main() {     while (scanf("%d", &n) == 1)     {         for (int i=1;i<=n;i++) scanf("%d", &a[i]);         bool flag = 0;         memset(dp[flag], 0, sizeof(dp[flag]));         ll ans = 0;         for (int i=1;i<=n;i++)         {             flag ^= 1;             memset(dp[flag], 0, sizeof(dp[flag]));             for (int j=0;j<32;j++)                 for (int k=0;k<2;k++)                 {                     if ((a[i]>>j)&1) dp[flag][j][k^1] += dp[flag^1][j][k];                     else dp[flag][j][k] += dp[flag^1][j][k];                 }             for (int j=0;j<32;j++)                 dp[flag][j][(a[i]>>j)&1]++;             for (int j=0;j<32;j++)                 ans += (ll)dp[flag][j][1] << j;         }         printf("%lld\n", ans);     }     return 0; }
23.233333
74
0.484218
huangshenno1
fe03caba543e551b40eb40cb515eb6588cde5c41
1,603
cpp
C++
src/HighQueue/Message.cpp
dale-wilson/HSQueue
04d01ed42707069d28e81b5494aba61904e6e591
[ "BSD-3-Clause" ]
2
2015-12-29T17:33:25.000Z
2021-12-20T02:30:44.000Z
src/HighQueue/Message.cpp
dale-wilson/HighQueue
04d01ed42707069d28e81b5494aba61904e6e591
[ "BSD-3-Clause" ]
null
null
null
src/HighQueue/Message.cpp
dale-wilson/HighQueue
04d01ed42707069d28e81b5494aba61904e6e591
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2014 Object Computing, Inc. // All rights reserved. // See the file license.txt for licensing information. #include <Common/HighQueuePch.hpp> #include "Message.hpp" #include <HighQueue/details/HQMemoryBlockPool.hpp> using namespace HighQueue; Message::~Message() { try{ release(); } catch(...) { //ignore this (sorry!) } } void Message::set(HQMemoryBlockPool * container, size_t capacity, size_t offset, size_t used) { container_ = reinterpret_cast<byte_t *>(container); capacity_ = (capacity == 0) ? used : capacity; offset_ = offset; used_ = used; } byte_t * Message::getContainer()const { return container_; } size_t Message::getOffset()const { return offset_; } void Message::release() { if(container_ != 0) { auto pool = reinterpret_cast<HQMemoryBlockPool *>(container_); pool->release(*this); } } void Message::reset() { container_ = 0; capacity_ = 0; offset_ = 0; used_ = 0; } namespace { const char * messageTypeNames[] = { "Unused", "Shutdown", "Heartbeat", "MulticastPacket", "Gap", "MockMessage", "LocalType0", "LocalType1", "LocalType2", "LocalType3", "LocalType4", "LocalType5", "LocalType6", "LocalType7", "ExtraTypeBase" }; } const char * Message::toText(Message::MessageType type) { auto index = size_t(type); if(index, sizeof(messageTypeNames) / sizeof(messageTypeNames[0])) { return messageTypeNames[index]; } return "MessageTypeOutOfRange"; }
19.54878
93
0.622583
dale-wilson
fe094de6b61b8f744ba80583d38cb3c435fd166f
103
hpp
C++
libng/core/src/libng_core/net/packet.hpp
gapry/libng
8fbf927e5bb73f105bddbb618430d3e1bf2cf877
[ "MIT" ]
null
null
null
libng/core/src/libng_core/net/packet.hpp
gapry/libng
8fbf927e5bb73f105bddbb618430d3e1bf2cf877
[ "MIT" ]
null
null
null
libng/core/src/libng_core/net/packet.hpp
gapry/libng
8fbf927e5bb73f105bddbb618430d3e1bf2cf877
[ "MIT" ]
null
null
null
#pragma once namespace libng { class packet_header; class packet { public: }; } // namespace libng
8.583333
20
0.708738
gapry
fe0e474b85c6744928713cb3c16d8dfb8b3b8a58
609
cpp
C++
Visual Studio 2010/Projects/bjarneStroustrupC++PartIV/bjarneStroustrupC++PartIV/Chapter25Exercise7.cpp
Ziezi/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup-
6fd64801863e883508f15d16398744405f4f9e34
[ "Unlicense" ]
9
2018-10-24T15:16:47.000Z
2021-12-14T13:53:50.000Z
Visual Studio 2010/Projects/bjarneStroustrupC++PartIV/bjarneStroustrupC++PartIV/Chapter25Exercise7.cpp
ChrisBKirov/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup-
6fd64801863e883508f15d16398744405f4f9e34
[ "Unlicense" ]
null
null
null
Visual Studio 2010/Projects/bjarneStroustrupC++PartIV/bjarneStroustrupC++PartIV/Chapter25Exercise7.cpp
ChrisBKirov/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup-
6fd64801863e883508f15d16398744405f4f9e34
[ "Unlicense" ]
7
2018-10-29T15:30:37.000Z
2021-01-18T15:15:09.000Z
/* TITLE Hex values in a range Chapter25Exercise7.cpp COMMENT Objective: Write out the hexadecimal values from 0 to 400; and from -200 to 200. Input: - Output: - Author: Chris B. Kirov Date: 13.05.2017 */ #include <iostream> void print_hex(int from, int to) { for (int i = from; i < to; ++i) { std::cout << std::hex << i <<' '; if(i % 8 == 0 && i != 0) { std::cout <<'\n'; } } std::cout <<'\n'; } int main() { try { print_hex(0, 400); print_hex(-200, 200); } catch(std::exception& e) { std::cerr << e.what(); exit(1); } getchar(); }
14.853659
61
0.53202
Ziezi
fe11fc1ec25703833a65d495c42cf0f0f78363e1
4,291
hpp
C++
examples/smith_waterman/smith_waterman.hpp
drichmond/HOPS
9684c0c9ebe5511fe0c202219a0bcd51fbf61079
[ "BSD-3-Clause" ]
10
2018-10-03T09:19:48.000Z
2021-09-15T14:46:32.000Z
examples/smith_waterman/smith_waterman.hpp
drichmond/HOPS
9684c0c9ebe5511fe0c202219a0bcd51fbf61079
[ "BSD-3-Clause" ]
1
2019-09-24T17:38:25.000Z
2019-09-24T17:38:25.000Z
examples/smith_waterman/smith_waterman.hpp
drichmond/HOPS
9684c0c9ebe5511fe0c202219a0bcd51fbf61079
[ "BSD-3-Clause" ]
null
null
null
// ---------------------------------------------------------------------- // Copyright (c) 2018, The Regents of the University of California All // rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // // * Neither the name of The Regents of the University of California // nor the names of its contributors may be used to endorse or // promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL REGENTS OF THE // UNIVERSITY OF CALIFORNIA BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS // OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR // TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. // ---------------------------------------------------------------------- #ifndef __SMITH_WATERMAN_HPP #define __SMITH_WATERMAN_HPP #include <stdio.h> #include <array> #define MATCH 2 #define ALPHA 2 #define BETA 1 #define REF_LENGTH 32 #define READ_LENGTH 16 #define SW_HIST 2 typedef char base; #ifdef BIT_ACCURATE #include "ap_int.h" typedef ap_uint<2> hw_base; #else typedef char hw_base; #endif template<typename T> base randtobase(T IN){ switch(IN >> (8*sizeof(IN)-3)){ case 0:return 'a'; case 1:return 'c'; case 2:return 't'; case 3:return 'g'; default: return 'x'; } } struct toHwBase{ hw_base operator()(base const& IN) const{ #ifdef BIT_ACCURATE switch(IN){ case 'a': return 0; case 'c': return 1; case 't': return 2; case 'g': return 3; default: return 0; } #else return IN; #endif } } to_hw_base; struct toSwBase{ base operator()(hw_base const& IN) const{ #ifdef BIT_ACCURATE switch(IN){ case 0: return 'a'; case 1: return 'c'; case 2: return 't'; case 3: return 'g'; default: return 'x'; } #else return IN; #endif } } to_sw_base; struct score{ char v, e, f; }; struct sw_ref{ hw_base b; bool last; }; template<std::size_t LEN> void print_top(char const& matid, std::array<char, LEN> const& top){ printf("%c", matid); for (auto t : top) { printf("%3c ", t); } printf("\n"); } template<std::size_t LEN> void print_top(char const& matid, std::array<sw_ref, LEN> const& top){ printf("%c", matid); for (auto t : top) { printf("%3c ", to_sw_base(t.b)); } printf("\n"); } template<std::size_t LEN> void print_row(char const& matid, base const& lbase, std::array<score, LEN> const& row){ printf("%c", lbase); for (auto r : row) { switch(matid) { case 'E': printf("%3d ", r.e); break; case 'F': printf("%3d ", r.f); break; case 'V': printf("%3d ", r.v); break; default: break; } } printf("\n"); } template<std::size_t SW, std::size_t W, std::size_t H, typename T> void print_mat(char matid, std::array<base, H> left, std::array<T, W> top, matrix<score, SW, H> smatrix){ print_top(matid, top); for(int j = 0; j < H; ++j){ print_row(matid, left[j], smatrix[j]); } printf("\n"); } template<std::size_t SW, std::size_t W, std::size_t H, typename T> void print_state(std::array<base, H> left, std::array<T, W> top, matrix<score, SW, H> smatrix){ print_mat('E', left, top, smatrix); print_mat('F', left, top, smatrix); print_mat('V', left, top, smatrix); } #endif //__SMITH_WATERMAN_HPP
24.380682
105
0.656024
drichmond
fe27f1eff0b3f4ba7dfe9da78c7ef5a79cc161b1
1,038
cpp
C++
command/remote/lib/light.cpp
Jeonghum/hfdpcpp11
5864973163991b58b89efa50ddfd75b201af2bed
[ "AFL-3.0" ]
3
2018-12-18T03:44:23.000Z
2019-11-20T20:45:43.000Z
command/remote/lib/light.cpp
Jeonghum/hfdpcpp11
5864973163991b58b89efa50ddfd75b201af2bed
[ "AFL-3.0" ]
2
2018-04-07T06:36:23.000Z
2018-04-08T13:35:38.000Z
command/remote/lib/light.cpp
Jeonghum/hfdpcpp11
5864973163991b58b89efa50ddfd75b201af2bed
[ "AFL-3.0" ]
2
2018-05-30T11:14:14.000Z
2021-04-18T22:38:48.000Z
//===--- light.cpp - --------------------------------------------*- C++ -*-===// // // Head First Design Patterns // // //===----------------------------------------------------------------------===// /// /// \file /// \brief /// //===----------------------------------------------------------------------===// //https://google.github.io/styleguide/cppguide.html#Names_and_Order_of_Includes //dir2 / foo2.h. #include "light.hpp" //C system files. //C++ system files. #include <iostream> //Other libraries' .h files. //Your project's .h files. namespace headfirst { Light::Light( const std::string location) : location_( location ) { std::cout << "Light::Light" << std::endl; } void Light::TurnOn() const { std::cout << "Light::on" << std::endl; std::cout << location_.c_str() << " light is on" << std::endl; } void Light::TurnOff() const { std::cout << "Light::off" << std::endl; std::cout << location_.c_str() << " light is off" << std::endl; } } //namespace headfirst
24.139535
80
0.460501
Jeonghum
fe3a669389e59c38d2010261d65786853a9c3950
33
hpp
C++
include/BESSCore/src/Renderer/Renderer.hpp
shivang51/BESS
8c53c5cb13863fd05574ebf20bf57624d83b0d25
[ "MIT" ]
null
null
null
include/BESSCore/src/Renderer/Renderer.hpp
shivang51/BESS
8c53c5cb13863fd05574ebf20bf57624d83b0d25
[ "MIT" ]
null
null
null
include/BESSCore/src/Renderer/Renderer.hpp
shivang51/BESS
8c53c5cb13863fd05574ebf20bf57624d83b0d25
[ "MIT" ]
null
null
null
#pragma once #include "Quad.hpp"
11
19
0.727273
shivang51
fe3aa498e736eb6385f47787de0ffaada3844c92
29,671
hpp
C++
include/NP-Engine/Graphics/RHI/Vulkan/VulkanPipeline.hpp
naphipps/NP-Engine
0cac8b2d5e76c839b96f2061bf57434bdc37915e
[ "MIT" ]
null
null
null
include/NP-Engine/Graphics/RHI/Vulkan/VulkanPipeline.hpp
naphipps/NP-Engine
0cac8b2d5e76c839b96f2061bf57434bdc37915e
[ "MIT" ]
null
null
null
include/NP-Engine/Graphics/RHI/Vulkan/VulkanPipeline.hpp
naphipps/NP-Engine
0cac8b2d5e76c839b96f2061bf57434bdc37915e
[ "MIT" ]
null
null
null
//##===----------------------------------------------------------------------===##// // // Author: Nathan Phipps 12/8/21 // //##===----------------------------------------------------------------------===##// #ifndef NP_ENGINE_VULKAN_PIPELINE_HPP #define NP_ENGINE_VULKAN_PIPELINE_HPP #include "NP-Engine/Filesystem/Filesystem.hpp" #include "NP-Engine/Vendor/VulkanInclude.hpp" #include "NP-Engine/Vendor/GlfwInclude.hpp" #include "VulkanInstance.hpp" #include "VulkanSurface.hpp" #include "VulkanDevice.hpp" #include "VulkanSwapchain.hpp" #include "VulkanShader.hpp" #include "VulkanVertex.hpp" namespace np::graphics::rhi { class VulkanPipeline { private: constexpr static siz MAX_FRAMES = 2; VulkanSwapchain _swapchain; container::vector<VulkanVertex> _vertices; VkBuffer _vertex_buffer; VkDeviceMemory _vertex_buffer_memory; VulkanShader _vertex_shader; VulkanShader _fragment_shader; VkRenderPass _render_pass; VkPipelineLayout _pipeline_layout; VkPipeline _pipeline; bl _rebuild_swapchain; container::vector<VkFramebuffer> _framebuffers; VkCommandPool _command_pool; container::vector<VkCommandBuffer> _command_buffers; siz _current_frame; container::vector<VkSemaphore> _image_available_semaphores; container::vector<VkSemaphore> _render_finished_semaphores; container::vector<VkFence> _fences; container::vector<VkFence> _image_fences; static void WindowResizeCallback(void* pipeline, ui32 width, ui32 height) { ((VulkanPipeline*)pipeline)->SetRebuildSwapchain(); ((VulkanPipeline*)pipeline)->Draw(time::DurationMilliseconds(0)); } VkPipelineShaderStageCreateInfo CreatePipelineShaderStageInfo() { VkPipelineShaderStageCreateInfo info{}; info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; return info; } VkPipelineVertexInputStateCreateInfo CreatePipelineVertexInputStateInfo() { VkPipelineVertexInputStateCreateInfo info{}; info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; return info; } VkPipelineInputAssemblyStateCreateInfo CreatePipelineInputAssemblyStateInfo() { VkPipelineInputAssemblyStateCreateInfo info{}; info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; info.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; info.primitiveRestartEnable = VK_FALSE; // TODO: it's possible to break up lines and triangles in the _STRIP topology modes by using a special index of // 0xFFFF or 0xFFFFFFFF. return info; } VkViewport CreateViewport() { VkViewport viewport{}; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = (flt)Swapchain().Extent().width; viewport.height = (flt)Swapchain().Extent().height; viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; return viewport; } VkRect2D CreateScissor() { VkRect2D scissor{}; scissor.offset = {0, 0}; scissor.extent = Swapchain().Extent(); return scissor; } VkPipelineViewportStateCreateInfo CreatePipelineViewportStateInfo() { VkPipelineViewportStateCreateInfo info{}; info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; return info; } VkPipelineRasterizationStateCreateInfo CreatePipelineRasterizationStateInfo() { VkPipelineRasterizationStateCreateInfo info{}; info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; /* //TODO: If depthClampEnable is set to VK_TRUE, then fragments that are beyond the near and far planes are clamped to them as opposed to discarding them. This is useful in some special cases like shadow maps. Using this requires enabling a GPU feature. */ info.depthClampEnable = VK_FALSE; info.rasterizerDiscardEnable = VK_FALSE; info.polygonMode = VK_POLYGON_MODE_FILL; // TODO: or VK_POLYGON_MODE_LINE or VK_POLYGON_MODE_POINT info.lineWidth = 1.0f; // TODO: any larger value required enabling wideLines GPU feature info.cullMode = VK_CULL_MODE_BACK_BIT; info.frontFace = VK_FRONT_FACE_CLOCKWISE; /* //TODO: The rasterizer can alter the depth values by adding a constant value or biasing them based on a fragment's slope. This is sometimes used for shadow mapping, but we won't be using it. Just set depthBiasEnable to VK_FALSE. */ info.depthBiasEnable = VK_FALSE; info.depthBiasConstantFactor = 0.0f; // Optional info.depthBiasClamp = 0.0f; // Optional info.depthBiasSlopeFactor = 0.0f; // Optional return info; } VkPipelineMultisampleStateCreateInfo CreatePipelineMultisampleStateInfo() { VkPipelineMultisampleStateCreateInfo info{}; info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; info.sampleShadingEnable = VK_FALSE; info.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; info.minSampleShading = 1.0f; // Optional info.pSampleMask = nullptr; // Optional info.alphaToCoverageEnable = VK_FALSE; // Optional info.alphaToOneEnable = VK_FALSE; // Optional return info; } VkPipelineColorBlendAttachmentState CreatePipelineColorBlendAttachmentState() { VkPipelineColorBlendAttachmentState state{}; state.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; state.blendEnable = VK_FALSE; state.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; // Optional state.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO; // Optional state.colorBlendOp = VK_BLEND_OP_ADD; // Optional state.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; // Optional state.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; // Optional state.alphaBlendOp = VK_BLEND_OP_ADD; // Optional return state; /* //TODO: The most common way to use color blending is to implement alpha blending, where we want the new color to be blended with the old color based on its opacity finalColor.rgb = newAlpha * newColor + (1 - newAlpha) * oldColor; finalColor.a = newAlpha.a; colorBlendAttachment.blendEnable = VK_TRUE; colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; colorBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD; colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD; */ } VkPipelineColorBlendStateCreateInfo CreatePipelineColorBlendStateInfo() { VkPipelineColorBlendStateCreateInfo info{}; info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; info.logicOpEnable = VK_FALSE; info.logicOp = VK_LOGIC_OP_COPY; // Optional info.blendConstants[0] = 0.0f; // Optional info.blendConstants[1] = 0.0f; // Optional info.blendConstants[2] = 0.0f; // Optional info.blendConstants[3] = 0.0f; // Optional return info; } container::vector<VkDynamicState> CreateDynamicStates() { return {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_LINE_WIDTH}; } VkPipelineDynamicStateCreateInfo CreatePipelineDynamicStateInfo() { VkPipelineDynamicStateCreateInfo info{}; info.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; info.dynamicStateCount = 2; // info.pDynamicStates = dynamicStates; return info; } VkAttachmentDescription CreateAttachmentDescription() { VkAttachmentDescription desc{}; desc.format = Device().SurfaceFormat().format; desc.samples = VK_SAMPLE_COUNT_1_BIT; // TODO: multisampling // TODO: The loadOp and storeOp determine what to do with the data in the // attachment before rendering and after rendering desc.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; desc.storeOp = VK_ATTACHMENT_STORE_OP_STORE; // TODO: we don't do anything with the stencil buffer desc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; desc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; desc.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; desc.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; return desc; } VkAttachmentReference CreateAttachmentReference() { VkAttachmentReference ref{}; ref.attachment = 0; ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; return ref; } VkSubpassDescription CreateSubpassDescription() { VkSubpassDescription desc{}; desc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; return desc; } VkRenderPassCreateInfo CreateRenderPassInfo() { VkRenderPassCreateInfo info{}; info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; return info; } VkGraphicsPipelineCreateInfo CreateGraphicsPipelineInfo() { VkGraphicsPipelineCreateInfo info{}; info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; return info; } container::vector<VkPipelineShaderStageCreateInfo> CreateShaderStages() { container::vector<VkPipelineShaderStageCreateInfo> stages; VkPipelineShaderStageCreateInfo vertex_stage = CreatePipelineShaderStageInfo(); vertex_stage.stage = VK_SHADER_STAGE_VERTEX_BIT; vertex_stage.module = _vertex_shader; vertex_stage.pName = _vertex_shader.Entrypoint().c_str(); stages.emplace_back(vertex_stage); VkPipelineShaderStageCreateInfo fragment_stage = CreatePipelineShaderStageInfo(); fragment_stage.stage = VK_SHADER_STAGE_FRAGMENT_BIT; fragment_stage.module = _fragment_shader; fragment_stage.pName = _fragment_shader.Entrypoint().c_str(); stages.emplace_back(fragment_stage); return stages; } VkPipelineLayoutCreateInfo CreatePipelineLayoutInfo() { VkPipelineLayoutCreateInfo info{}; info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; info.setLayoutCount = 0; // Optional info.pSetLayouts = nullptr; // Optional info.pushConstantRangeCount = 0; // Optional info.pPushConstantRanges = nullptr; // Optional return info; } VkFramebufferCreateInfo CreateFramebufferInfo() { VkFramebufferCreateInfo info{}; info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; info.width = Swapchain().Extent().width; info.height = Swapchain().Extent().height; info.layers = 1; return info; } VkCommandPoolCreateInfo CreateCommandPoolInfo() { VkCommandPoolCreateInfo info{}; info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; info.queueFamilyIndex = Device().QueueFamilyIndices().graphics.value(); info.flags = 0; // Optional return info; } VkCommandBufferAllocateInfo CreateCommandBufferAllocateInfo() { VkCommandBufferAllocateInfo info{}; info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; info.commandPool = _command_pool; info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; return info; } VkCommandBufferBeginInfo CreateCommandBufferBeginInfo() { VkCommandBufferBeginInfo info{}; info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; info.flags = 0; // Optional info.pInheritanceInfo = nullptr; // Optional return info; } VkRenderPassBeginInfo CreateRenderPassBeginInfo() { VkRenderPassBeginInfo info{}; info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; info.renderPass = _render_pass; info.renderArea.offset = {0, 0}; info.renderArea.extent = Swapchain().Extent(); return info; } container::vector<VkClearValue> CreateClearValues() { container::vector<VkClearValue> values; VkClearValue clear_color = {{{0.0f, 0.0f, 0.0f, 1.0f}}}; values.emplace_back(clear_color); return values; } container::vector<VkSubpassDependency> CreateSubpassDependencies() { container::vector<VkSubpassDependency> dependencies{}; VkSubpassDependency dependency{}; dependency.srcSubpass = VK_SUBPASS_EXTERNAL; dependency.dstSubpass = 0; dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.srcAccessMask = 0; dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; dependencies.emplace_back(dependency); return dependencies; } VkBufferCreateInfo CreateBufferInfo() { VkBufferCreateInfo info{}; info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; info.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; return info; } VkMemoryAllocateInfo CreateMemoryAllocateInfo() { VkMemoryAllocateInfo info{}; info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; return info; } ui32 ChooseMemoryTypeIndex(ui32 type_filter, VkMemoryPropertyFlags property_flags) { VkPhysicalDeviceMemoryProperties memory_properties; vkGetPhysicalDeviceMemoryProperties(Device().PhysicalDevice(), &memory_properties); bl found = false; ui32 memory_type_index = 0; for (ui32 i = 0; i < memory_properties.memoryTypeCount; i++) { if ((type_filter & (1 << i)) && (memory_properties.memoryTypes[i].propertyFlags & property_flags) == property_flags) { found = true; memory_type_index = i; } } return found ? memory_type_index : -1; } VkRenderPass CreateRenderPass() { VkRenderPass render_pass = nullptr; container::vector<VkAttachmentReference> attachment_references = {CreateAttachmentReference()}; VkSubpassDescription subpass_description = CreateSubpassDescription(); subpass_description.colorAttachmentCount = attachment_references.size(); subpass_description.pColorAttachments = attachment_references.data(); container::vector<VkSubpassDescription> subpass_descriptions = {subpass_description}; container::vector<VkAttachmentDescription> attachment_descriptions = {CreateAttachmentDescription()}; container::vector<VkSubpassDependency> subpass_dependencies = CreateSubpassDependencies(); VkRenderPassCreateInfo render_pass_info = CreateRenderPassInfo(); render_pass_info.attachmentCount = attachment_descriptions.size(); render_pass_info.pAttachments = attachment_descriptions.data(); render_pass_info.subpassCount = subpass_descriptions.size(); render_pass_info.pSubpasses = subpass_descriptions.data(); render_pass_info.dependencyCount = subpass_dependencies.size(); render_pass_info.pDependencies = subpass_dependencies.data(); if (vkCreateRenderPass(Device(), &render_pass_info, nullptr, &render_pass) != VK_SUCCESS) { render_pass = nullptr; } return render_pass; } VkPipelineLayout CreatePipelineLayout() { VkPipelineLayout pipeline_layout = nullptr; VkPipelineLayoutCreateInfo pipeline_layout_info = CreatePipelineLayoutInfo(); if (vkCreatePipelineLayout(Device(), &pipeline_layout_info, nullptr, &pipeline_layout) != VK_SUCCESS) { pipeline_layout = nullptr; } return pipeline_layout; } VkPipeline CreatePipeline() { VkPipeline pipeline = nullptr; if (_pipeline_layout != nullptr && _render_pass != nullptr) { container::vector<VkVertexInputBindingDescription> vertex_binding_descs = VulkanVertex::BindingDescriptions(); container::array<VkVertexInputAttributeDescription, 2> vertex_attribute_descs = VulkanVertex::AttributeDescriptions(); VkPipelineVertexInputStateCreateInfo vertex_input_state_info = CreatePipelineVertexInputStateInfo(); vertex_input_state_info.vertexBindingDescriptionCount = (ui32)vertex_binding_descs.size(); vertex_input_state_info.pVertexBindingDescriptions = vertex_binding_descs.data(); vertex_input_state_info.vertexAttributeDescriptionCount = (ui32)vertex_attribute_descs.size(); vertex_input_state_info.pVertexAttributeDescriptions = vertex_attribute_descs.data(); container::vector<VkPipelineShaderStageCreateInfo> shader_stages = CreateShaderStages(); VkPipelineInputAssemblyStateCreateInfo input_assembly_state_info = CreatePipelineInputAssemblyStateInfo(); container::vector<VkViewport> viewports = {CreateViewport()}; container::vector<VkRect2D> scissors = {CreateScissor()}; VkPipelineViewportStateCreateInfo viewport_state_info = CreatePipelineViewportStateInfo(); viewport_state_info.viewportCount = viewports.size(); viewport_state_info.pViewports = viewports.data(); viewport_state_info.scissorCount = scissors.size(); viewport_state_info.pScissors = scissors.data(); VkPipelineRasterizationStateCreateInfo rasterization_state_info = CreatePipelineRasterizationStateInfo(); VkPipelineMultisampleStateCreateInfo multisample_state_info = CreatePipelineMultisampleStateInfo(); container::vector<VkPipelineColorBlendAttachmentState> color_blend_attachment_states = { CreatePipelineColorBlendAttachmentState()}; VkPipelineColorBlendStateCreateInfo color_blend_state_info = CreatePipelineColorBlendStateInfo(); color_blend_state_info.attachmentCount = color_blend_attachment_states.size(); color_blend_state_info.pAttachments = color_blend_attachment_states.data(); VkGraphicsPipelineCreateInfo pipeline_info = CreateGraphicsPipelineInfo(); pipeline_info.stageCount = shader_stages.size(); pipeline_info.pStages = shader_stages.data(); pipeline_info.pVertexInputState = &vertex_input_state_info; pipeline_info.pInputAssemblyState = &input_assembly_state_info; pipeline_info.pViewportState = &viewport_state_info; pipeline_info.pRasterizationState = &rasterization_state_info; pipeline_info.pMultisampleState = &multisample_state_info; pipeline_info.pDepthStencilState = nullptr; // Optional pipeline_info.pColorBlendState = &color_blend_state_info; pipeline_info.pDynamicState = nullptr; // Optional pipeline_info.layout = _pipeline_layout; pipeline_info.renderPass = _render_pass; pipeline_info.subpass = 0; pipeline_info.basePipelineHandle = VK_NULL_HANDLE; // Optional pipeline_info.basePipelineIndex = -1; // Optional if (vkCreateGraphicsPipelines(Device(), nullptr, 1, &pipeline_info, nullptr, &pipeline) != VK_SUCCESS) { pipeline = nullptr; } } return pipeline; } container::vector<VkFramebuffer> CreateFramebuffers() { container::vector<VkFramebuffer> framebuffers(Swapchain().ImageViews().size()); for (siz i = 0; i < Swapchain().ImageViews().size(); i++) { container::vector<VkImageView> image_views = {Swapchain().ImageViews()[i]}; VkFramebufferCreateInfo framebuffer_info = CreateFramebufferInfo(); framebuffer_info.renderPass = _render_pass; framebuffer_info.attachmentCount = image_views.size(); framebuffer_info.pAttachments = image_views.data(); if (vkCreateFramebuffer(Device(), &framebuffer_info, nullptr, &framebuffers[i]) != VK_SUCCESS) { framebuffers[i] = nullptr; } } return framebuffers; } VkCommandPool CreateCommandPool() { VkCommandPool command_pool = nullptr; VkCommandPoolCreateInfo command_pool_info = CreateCommandPoolInfo(); if (vkCreateCommandPool(Device(), &command_pool_info, nullptr, &command_pool) != VK_SUCCESS) { command_pool = nullptr; } return command_pool; } container::vector<VkCommandBuffer> CreateCommandBuffers() { container::vector<VkCommandBuffer> command_buffers(_framebuffers.size()); VkCommandBufferAllocateInfo command_buffer_allocate_info = CreateCommandBufferAllocateInfo(); command_buffer_allocate_info.commandBufferCount = (ui32)command_buffers.size(); if (vkAllocateCommandBuffers(Device(), &command_buffer_allocate_info, command_buffers.data()) != VK_SUCCESS) { command_buffers.clear(); } for (siz i = 0; i < command_buffers.size(); i++) { VkCommandBufferBeginInfo command_buffer_begin_info = CreateCommandBufferBeginInfo(); if (vkBeginCommandBuffer(command_buffers[i], &command_buffer_begin_info) != VK_SUCCESS) { command_buffers.clear(); break; } container::vector<VkClearValue> clear_values = CreateClearValues(); VkRenderPassBeginInfo render_pass_begin_info = CreateRenderPassBeginInfo(); render_pass_begin_info.framebuffer = _framebuffers[i]; render_pass_begin_info.clearValueCount = clear_values.size(); render_pass_begin_info.pClearValues = clear_values.data(); container::vector<VkBuffer> vertex_buffers{_vertex_buffer}; container::vector<VkDeviceSize> offsets{0}; vkCmdBeginRenderPass(command_buffers[i], &render_pass_begin_info, VK_SUBPASS_CONTENTS_INLINE); vkCmdBindPipeline(command_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, _pipeline); vkCmdBindVertexBuffers(command_buffers[i], 0, (ui32)vertex_buffers.size(), vertex_buffers.data(), offsets.data()); vkCmdDraw(command_buffers[i], (ui32)_vertices.size(), 1, 0, 0); vkCmdEndRenderPass(command_buffers[i]); if (vkEndCommandBuffer(command_buffers[i]) != VK_SUCCESS) { command_buffers.clear(); break; } } return command_buffers; } container::vector<VkSemaphore> CreateSemaphores(siz count) { container::vector<VkSemaphore> semaphores(count); for (siz i = 0; i < count; i++) { VkSemaphoreCreateInfo semaphore_info{}; semaphore_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; if (vkCreateSemaphore(Device(), &semaphore_info, nullptr, &semaphores[i]) != VK_SUCCESS) { semaphores.clear(); break; } } return semaphores; } container::vector<VkFence> CreateFences(siz count, bl initialize = true) { container::vector<VkFence> fences(count, nullptr); if (initialize) { for (siz i = 0; i < count; i++) { VkFenceCreateInfo fence_info{}; fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fence_info.flags = VK_FENCE_CREATE_SIGNALED_BIT; if (vkCreateFence(Device(), &fence_info, nullptr, &fences[i]) != VK_SUCCESS) { fences.clear(); break; } } } return fences; } VkBuffer CreateVertexBuffer() { VkBuffer buffer = nullptr; VkBufferCreateInfo buffer_info = CreateBufferInfo(); buffer_info.size = sizeof(_vertices[0]) * _vertices.size(); if (vkCreateBuffer(Device(), &buffer_info, nullptr, &buffer) != VK_SUCCESS) { buffer = nullptr; } return buffer; } VkDeviceMemory CreateVertexBufferMemory() { VkDeviceMemory buffer_memory = nullptr; VkMemoryRequirements requirements; vkGetBufferMemoryRequirements(Device(), _vertex_buffer, &requirements); VkMemoryAllocateInfo allocate_info = CreateMemoryAllocateInfo(); allocate_info.allocationSize = requirements.size; allocate_info.memoryTypeIndex = ChooseMemoryTypeIndex( requirements.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); if (vkAllocateMemory(Device(), &allocate_info, nullptr, &buffer_memory) != VK_SUCCESS) { buffer_memory = nullptr; } else { vkBindBufferMemory(Device(), _vertex_buffer, buffer_memory, 0); } return buffer_memory; } void RebuildSwapchain() { SetRebuildSwapchain(false); vkDeviceWaitIdle(Device()); vkFreeCommandBuffers(Device(), _command_pool, (ui32)_command_buffers.size(), _command_buffers.data()); for (auto framebuffer : _framebuffers) vkDestroyFramebuffer(Device(), framebuffer, nullptr); vkDestroyPipeline(Device(), _pipeline, nullptr); vkDestroyPipelineLayout(Device(), _pipeline_layout, nullptr); vkDestroyRenderPass(Device(), _render_pass, nullptr); _swapchain.Rebuild(); _render_pass = CreateRenderPass(); _pipeline_layout = CreatePipelineLayout(); _pipeline = CreatePipeline(); _framebuffers = CreateFramebuffers(); _command_buffers = CreateCommandBuffers(); } public: VulkanPipeline(VulkanDevice& device): _swapchain(device), _vertices(3), _vertex_buffer(CreateVertexBuffer()), _vertex_buffer_memory(CreateVertexBufferMemory()), _vertex_shader(Device(), fs::append(fs::append("Vulkan", "shaders"), "vertex.glsl"), VulkanShader::Type::VERTEX), _fragment_shader(Device(), fs::append(fs::append("Vulkan", "shaders"), "fragment.glsl"), VulkanShader::Type::FRAGMENT), _render_pass(CreateRenderPass()), _pipeline_layout(CreatePipelineLayout()), _pipeline(CreatePipeline()), _framebuffers(CreateFramebuffers()), // TODO: can we put this in a VulkanFramebuffer? I don't think so _command_pool(CreateCommandPool()), // TODO: can we put this in a VulkanCommand_____?? maybe....? _command_buffers(CreateCommandBuffers()), _current_frame(0), _image_available_semaphores(CreateSemaphores(MAX_FRAMES)), _render_finished_semaphores(CreateSemaphores(MAX_FRAMES)), _fences(CreateFences(MAX_FRAMES)), _image_fences(CreateFences(Swapchain().Images().size(), false)), _rebuild_swapchain(false) { Surface().Window().SetResizeCallback(this, WindowResizeCallback); const container::vector<Vertex> vertices = { {{0.0f, -0.5f}, {1.0f, 0.0f, 1.0f}}, {{0.5f, 0.5f}, {1.0f, 1.0f, 0.0f}}, {{-0.5f, 0.5f}, {0.0f, 1.0f, 1.0f}}}; siz data_size = sizeof(_vertices[0]) * _vertices.size(); void* data; vkMapMemory(device, _vertex_buffer_memory, 0, data_size, 0, &data); memcpy(data, vertices.data(), data_size); vkUnmapMemory(device, _vertex_buffer_memory); } ~VulkanPipeline() { vkDeviceWaitIdle(Device()); vkDestroyBuffer(Device(), _vertex_buffer, nullptr); vkFreeMemory(Device(), _vertex_buffer_memory, nullptr); for (VkSemaphore& semaphore : _render_finished_semaphores) vkDestroySemaphore(Device(), semaphore, nullptr); for (VkSemaphore& semaphore : _image_available_semaphores) vkDestroySemaphore(Device(), semaphore, nullptr); for (VkFence& fence : _fences) vkDestroyFence(Device(), fence, nullptr); vkDestroyCommandPool(Device(), _command_pool, nullptr); for (auto framebuffer : _framebuffers) vkDestroyFramebuffer(Device(), framebuffer, nullptr); vkDestroyPipeline(Device(), _pipeline, nullptr); vkDestroyPipelineLayout(Device(), _pipeline_layout, nullptr); vkDestroyRenderPass(Device(), _render_pass, nullptr); } VulkanInstance& Instance() const { return _swapchain.Instance(); } VulkanSurface& Surface() const { return _swapchain.Surface(); } VulkanDevice& Device() const { return _swapchain.Device(); } const VulkanSwapchain& Swapchain() const { return _swapchain; } const VulkanShader& VertexShader() const { return _vertex_shader; } const VulkanShader& FragmentShader() const { return _fragment_shader; } void SetRebuildSwapchain(bl rebuild_swapchain = true) { _rebuild_swapchain = rebuild_swapchain; } void Draw(time::DurationMilliseconds time_delta) { i32 width = 0; i32 height = 0; glfwGetFramebufferSize((GLFWwindow*)Surface().Window().GetNativeWindow(), &width, &height); if (width == 0 || height == 0) { return; } vkWaitForFences(Device(), 1, &_fences[_current_frame], VK_TRUE, UI64_MAX); ui32 image_index; VkResult acquire_result = vkAcquireNextImageKHR(Device(), Swapchain(), UI64_MAX, _image_available_semaphores[_current_frame], nullptr, &image_index); if (acquire_result == VK_ERROR_OUT_OF_DATE_KHR) { RebuildSwapchain(); return; } else if (acquire_result != VK_SUCCESS && acquire_result != VK_SUBOPTIMAL_KHR) { NP_ASSERT(false, "vkAcquireNextImageKHR error"); } // Check if a previous frame is using this image (i.e. there is its fence to wait on) if (_image_fences[image_index] != nullptr) { vkWaitForFences(Device(), 1, &_image_fences[image_index], VK_TRUE, UI64_MAX); } // Mark the image as now being in use by this frame _image_fences[image_index] = _fences[_current_frame]; container::vector<VkSemaphore> wait_semaphores{_image_available_semaphores[_current_frame]}; container::vector<VkPipelineStageFlags> wait_stages{VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT}; container::vector<VkSemaphore> signal_semaphores{_render_finished_semaphores[_current_frame]}; container::vector<VkSwapchainKHR> swapchains{Swapchain()}; VkSubmitInfo submit_info{}; submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submit_info.waitSemaphoreCount = wait_semaphores.size(); submit_info.pWaitSemaphores = wait_semaphores.data(); submit_info.pWaitDstStageMask = wait_stages.data(); submit_info.commandBufferCount = 1; // _command_buffers.size(); submit_info.pCommandBuffers = &_command_buffers[image_index]; submit_info.signalSemaphoreCount = signal_semaphores.size(); submit_info.pSignalSemaphores = signal_semaphores.data(); vkResetFences(Device(), 1, &_fences[_current_frame]); if (vkQueueSubmit(Device().GraphicsDeviceQueue(), 1, &submit_info, _fences[_current_frame]) != VK_SUCCESS) { NP_ASSERT(false, "failed to submit draw command buffer!"); } VkPresentInfoKHR present_info{}; present_info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; present_info.waitSemaphoreCount = signal_semaphores.size(); present_info.pWaitSemaphores = signal_semaphores.data(); present_info.swapchainCount = swapchains.size(); present_info.pSwapchains = swapchains.data(); present_info.pImageIndices = &image_index; present_info.pResults = nullptr; // Optional VkResult present_result = vkQueuePresentKHR(Device().PresentDeviceQueue(), &present_info); if (present_result == VK_ERROR_OUT_OF_DATE_KHR || present_result == VK_SUBOPTIMAL_KHR || _rebuild_swapchain) { RebuildSwapchain(); } else if (present_result != VK_SUCCESS) { NP_ASSERT(false, "vkQueuePresentKHR error"); } vkQueueWaitIdle(Device().PresentDeviceQueue()); _current_frame = (_current_frame + 1) % MAX_FRAMES; } operator VkPipeline() const { return _pipeline; } }; } // namespace np::graphics::rhi #endif /* NP_ENGINE_VULKAN_PIPELINE_HPP */
33.64059
116
0.753497
naphipps
fe3d9919a750669b1b6838020b96b55eed484d4c
4,650
cpp
C++
la-test.cpp
busysteve/la
bcd53b1676ef91d93ba6a1e606b5098a5712a293
[ "MIT" ]
1
2020-05-25T05:28:10.000Z
2020-05-25T05:28:10.000Z
la-test.cpp
busysteve/dsp
1a80f719c7af38beafdf7656f19690783ae5b00e
[ "Apache-2.0" ]
null
null
null
la-test.cpp
busysteve/dsp
1a80f719c7af38beafdf7656f19690783ae5b00e
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <fstream> #include <vector> #include <complex> #include <string> #include <cstring> #include <cmath> #include <float.h> #include "tnt/tnt.h" #include <initializer_list> #include "Signal.h" #include "la.h" template <typename T> int VectorTest() { const double PI = 3.141592653589793238463; const double PI2 = PI * 2.0; { cout << "Vector tests:" << endl; Vector<T> v1( { (T)13.0, (T)-12.0, (T)2.0 } ); Vector<T> v2( { (T)14.0, (T)15.0, (T)-3.0 } ); T s1 = (T)23.0; cout << v1 << " dot " << v2 << " = " << v1.dot( v2 ) << endl; cout << v1 << " mul " << v2 << " = " << v1.mul( v2 ) << endl; cout << v1 << " div " << v2 << " = " << v1.div( v2 ) << endl; cout << v1 << " add " << v2 << " = " << v1.add( v2 ) << endl; cout << v1 << " sub " << v2 << " = " << v1.sub( v2 ) << endl; cout << v1 << " mul " << s1 << " = " << v1.mul( s1 ) << endl; cout << v1 << " div " << s1 << " = " << v1.div( s1 ) << endl; cout << v1 << " add " << s1 << " = " << v1.add( s1 ) << endl; cout << v1 << " sub " << s1 << " = " << v1.sub( s1 ) << endl; cout << v1 << " * " << v2 << " = " << v1 * v2 << endl; cout << s1 << " * " << v2 << " = " << s1 * v2 << endl; cout << v1 << " * " << s1 << " = " << v1 * s1 << endl; cout << v1 << " / " << v2 << " = " << v1 / v2 << endl; cout << s1 << " / " << v2 << " = " << s1 / v2 << endl; cout << v1 << " / " << s1 << " = " << v1 / s1 << endl; cout << v1 << " + " << v2 << " = " << v1 + v2 << endl; cout << s1 << " + " << v2 << " = " << s1 + v2 << endl; cout << v1 << " + " << s1 << " = " << v1 + s1 << endl; cout << v1 << " - " << v2 << " = " << v1 - v2 << endl; cout << s1 << " - " << v2 << " = " << s1 - v2 << endl; cout << v1 << " - " << s1 << " = " << v1 - s1 << endl; cout << v1 << " negated = " << -v1 << endl; Vector<T> v3( 3, (T)1.0 ); Vector<T> v4( 4, (T)2.0 ); cout << v3.dot( v4 ) << endl; } { cout << endl << "Matrix * Matrix tests:" << endl; Matrix<T> mA( { { 5.0, 34.0, -28.0 }, { 8.0, -83.4, 71.7 }, { 92.6, 23.3, 9.2 } } ); Matrix<T> mB( { { 56.0, 26.0, 4.3 }, { 6.5, 33.4, 5.6 }, { 8.4, 1.9, 2.3 } } ); Matrix<T> mC( { { 5.0, 34.0, -28.0 }, { 8.0, -83.4, 71.7 }, { 83.4, 4.3, 71.7 }, { 92.6, 23.3, 9.2 } } ); try{ cout << mA << " + " << mC << " = " << mA + mC << endl << endl; } catch ( linear_algebra_error e ) { cerr << endl << e.what() << endl; } Matrix<T> m3( { { 5.0, 34.0, -28.0 }, { 8.0, -83.4, 71.7 }, { 83.4, 4.3, 71.7 }, { 92.6, 23.3, 9.2 } } ); Matrix<T> m4( { { 56.0, 26.0 }, { 6.5, 33.4 }, { 8.4, 1.9 } } ); cout << m3 << " * " << m4 << " = " << m3 * m4 << endl; Matrix<T> m1( { { 34.0, -28.0 }, { -83.4, 71.7 }, { 83.4, 71.7 }, { 92.6, 23.3 } } ); Matrix<T> m2( { { 56.0, 26.0 }, { 8.4, 1.9 } } ); cout << m1 << " * " << m2 << " = " << m1 * m2 << endl; m3.print() << endl; m3.transpose(); m3.print() << endl; //cout << m1 << " / " << m2 << " = " << m1 / m2 << endl; cout << endl << "Matrix * Vector tests:" << endl; Matrix<T> m5( { { 34.0, -28.0 }, { -83.4, 71.7 }, { 92.6, 23.3 } } ); Vector<T> v1( { 23.4, 45.6 } ); Vector<T> v2( { 23.4, 45.6, 77.0 } ); try { cout << m5 << " * " << v1 << " = " << m5 * v1 << endl << endl; cout << m5 << " * " << v2 << " = " << m5 * v2 << endl << endl; } catch( linear_algebra_error e ) { cerr << endl << e.what() << endl; } Matrix<T> a( {{2,3},{4,5},{4,5}} ); Vector<T> b( {6,7} ); cout << endl << a << " * " << b << " = " << a * b << endl; double framerate = 11025.0; Vector<T> amps( {0.6,0.25,0.1,0.05} ); Vector<T> fs( {300.0,400.0,500.0,600.0} ); Vector<T> ts; for( double t=0.0; t <1.0; t += 1.0/framerate) ts.push_back(t); cout << endl << amps << " * " << fs << " = " << amps * fs << endl; //cout << endl << ts << endl; //cout << endl << ts << " * " << fs << " = " << ts * fs << endl; auto args = ts.outer(fs); auto M = args; M.func( [&]( T x ){ return std::cos( PI2 * x); } ); cout << endl << M << endl; auto ys = M * amps; cout << endl << ys << endl << ys.size() << endl; cout << endl << ys[1000] << endl << endl; Wave wav( framerate, 16 ); wav.setsignal(ys, 100.0); wav.write( "quad-tone.wav" ); std::complex<T> c1( 0, 1 ); auto z = std::exp( c1 * 1.5 ); std::cout << z << std::endl; } return 0; } int main() { VectorTest<double>(); return 0; }
21.933962
68
0.389032
busysteve
fe4335c2f43990f89ab3b3b4137f1d35ca8cae3f
5,472
cpp
C++
examples/livelocation.cpp
Sil3ntStorm/libtelegram
a0c52ba4aac5519a3031dba506ad4a64cd8fca83
[ "MIT" ]
118
2016-10-02T10:49:02.000Z
2022-03-23T14:32:05.000Z
examples/livelocation.cpp
Sil3ntStorm/libtelegram
a0c52ba4aac5519a3031dba506ad4a64cd8fca83
[ "MIT" ]
21
2017-04-21T13:34:36.000Z
2021-12-08T17:00:40.000Z
examples/livelocation.cpp
Sil3ntStorm/libtelegram
a0c52ba4aac5519a3031dba506ad4a64cd8fca83
[ "MIT" ]
35
2016-06-08T15:31:03.000Z
2022-03-23T16:43:28.000Z
/// This example demonstrates a bot that accepts two locations, and then sends /// a live location interpolating smoothly between the two. /// As this is a very simple example, it does not keep track of multiple users, /// so should only be used by one user at a time. /// It could be extended to support multiple users by tracking each user's /// status along with user ID, with a separate thread running to update the live /// locations for each. #include <libtelegram/libtelegram.h> auto main()->int { std::string const token("123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"); telegram::sender sender(token); telegram::listener::poll listener(sender); auto lerp = [](float from, float to, float coefficient){ // helper function to linearly interpolate return from + coefficient * (to - from); }; std::optional<telegram::types::location> first_location; // cache our first location, when it arrives std::optional<telegram::types::location> second_location; // cache our second location, when it arrives listener.set_callback_message([&](telegram::types::message const &message){ auto const message_chat_id = message.chat.id; if(!first_location) { // we haven't received any locations yet from the user if(!message.location) { // early exit if this message doesn't contain a location sender.send_message(message_chat_id, "Send me the first location."); return; } first_location = message.location; // cache the first location sender.send_message(message_chat_id, "Interpolating from " + std::to_string(first_location->latitude) + ", " + std::to_string(first_location->longitude) + ".\n" "Send me the second location."); } else { // we already received the first location, so we want the second if(!message.location) { // early exit if this message doesn't contain a location sender.send_message(message_chat_id, "Send me the second location."); return; } second_location = message.location; // cache the second location sender.send_message(message_chat_id, "Interpolating from " + std::to_string(first_location->latitude) + ", " + std::to_string(first_location->longitude) + " to " + std::to_string(second_location->latitude) + ", " + std::to_string(second_location->longitude) + "...\n"); unsigned int constexpr const live_location_period = 60; // time in seconds unsigned int constexpr const seconds_per_update = 2; // don't flood with updates too frequently auto const location_message = sender.send_location(message_chat_id, // send the initial location first, we'll then update it. This function returns the message we sent, we'll need its id to update it *first_location, live_location_period); // minimum 60, maximum 86400 if(!location_message || !location_message->location) { // error checking: make sure we got back a message with a correctly sent location sender.send_message(message_chat_id, "Something went wrong - unable to send back that first location!"); return; } auto sent_message_id = location_message->message_id; // this is the message id of the location message we're updating unsigned int constexpr const steps = live_location_period / seconds_per_update; for(unsigned int step = 0; step != steps; ++step) { float coefficient = static_cast<float>(step) / steps; telegram::types::location const interpolated_location{ lerp(first_location->latitude, second_location->latitude, coefficient), lerp(first_location->longitude, second_location->longitude, coefficient) }; std::cout << "DEBUG: updating message id " << sent_message_id << std::endl; auto const updated_message = sender.edit_message_live_location(message_chat_id, // update the live location - we need both the chat id and... sent_message_id, // ...the message id we're updating interpolated_location); //sent_message_id = updated_message->message_id; using namespace std::chrono_literals; // to let us use the "seconds" literal std::this_thread::sleep_for(1s * seconds_per_update); // sleep this thread until it's time to send the next message } } }); listener.set_num_threads(1); // run single-threaded listener.run(); // launch the listener - this call blocks until interrupted return EXIT_SUCCESS; };
64.376471
212
0.572917
Sil3ntStorm
e8054ed8bad581e4c6ee7f22377ba4aef07865b2
278
cpp
C++
171-Excel_Sheet_Column_Number.cpp
elsdrium/LeetCode-practice
a3b1fa5dd200155a636d36cd570e2454f7194e10
[ "MIT" ]
null
null
null
171-Excel_Sheet_Column_Number.cpp
elsdrium/LeetCode-practice
a3b1fa5dd200155a636d36cd570e2454f7194e10
[ "MIT" ]
null
null
null
171-Excel_Sheet_Column_Number.cpp
elsdrium/LeetCode-practice
a3b1fa5dd200155a636d36cd570e2454f7194e10
[ "MIT" ]
null
null
null
class Solution { public: int titleToNumber(string s) { int result = 0, base = 1; char c = char('A' - 1); for ( int i=s.size()-1; i>=0; --i ) { result += (s[i] - c) * base; base *= 26; } return result; } };
21.384615
45
0.413669
elsdrium
e80acbdb590acad486f57b22858631f77fa9b758
1,410
cc
C++
resonance_audio/utils/sum_and_difference_processor_test.cc
seba10000/resonance-audio
e1923fe6fe733ae4d3c8460ff883c87e2ad05d6b
[ "Apache-2.0" ]
396
2018-03-14T09:55:52.000Z
2022-03-27T14:58:38.000Z
resonance_audio/utils/sum_and_difference_processor_test.cc
seba10000/resonance-audio
e1923fe6fe733ae4d3c8460ff883c87e2ad05d6b
[ "Apache-2.0" ]
46
2018-04-18T17:14:29.000Z
2022-02-19T21:35:57.000Z
resonance_audio/utils/sum_and_difference_processor_test.cc
seba10000/resonance-audio
e1923fe6fe733ae4d3c8460ff883c87e2ad05d6b
[ "Apache-2.0" ]
96
2018-03-14T17:20:50.000Z
2022-03-03T01:12:37.000Z
/* Copyright 2018 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "utils/sum_and_difference_processor.h" #include "third_party/googletest/googletest/include/gtest/gtest.h" namespace vraudio { // Tests Process method. TEST(SumAndDifferenceProcessor, TestProcessMethod) { static const std::vector<std::vector<float>> kTestVector = { {0.0f, 1.0f, 2.0f}, {3.0f, 4.0f, 5.0f}}; AudioBuffer audio_buffer(kTestVector.size(), kTestVector[0].size()); audio_buffer = kTestVector; SumAndDifferenceProcessor processor(audio_buffer.num_frames()); processor.Process(&audio_buffer); for (size_t frame = 0; frame < kTestVector[0].size(); ++frame) { EXPECT_EQ(kTestVector[0][frame] + kTestVector[1][frame], audio_buffer[0][frame]); EXPECT_EQ(kTestVector[0][frame] - kTestVector[1][frame], audio_buffer[1][frame]); } } } // namespace vraudio
32.790698
72
0.734043
seba10000
e819cde9d0c5b65887b08a125a144e40513fe00f
430
cpp
C++
Simple_Problem/BOJ(9095).cpp
kkkHoon/algorithm_study
b16ab6118511059d28e77c1807f3e8fabb13e5f0
[ "MIT" ]
null
null
null
Simple_Problem/BOJ(9095).cpp
kkkHoon/algorithm_study
b16ab6118511059d28e77c1807f3e8fabb13e5f0
[ "MIT" ]
null
null
null
Simple_Problem/BOJ(9095).cpp
kkkHoon/algorithm_study
b16ab6118511059d28e77c1807f3e8fabb13e5f0
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <queue> #include <functional> using namespace std; int n, num, cnt; void calculate(int num); int main() { cin >> n; for (int i = 0; i < n; i++) { cin >> num; cnt = 0; calculate(num); cout << cnt << endl; } return 0; } void calculate(int num) { if (num <= 0) { if (num == 0) cnt++; return; } calculate(num - 1); calculate(num - 2); calculate(num - 3); }
13.030303
30
0.574419
kkkHoon
e81ad576080bb897a8df9fc83debde671fd663ed
845
cpp
C++
TPP/TBB/material/actividad2.cpp
zhonskate/MCPD
14e8f41c5b9317dc5c4ccbddba95e6db69087d29
[ "MIT" ]
null
null
null
TPP/TBB/material/actividad2.cpp
zhonskate/MCPD
14e8f41c5b9317dc5c4ccbddba95e6db69087d29
[ "MIT" ]
null
null
null
TPP/TBB/material/actividad2.cpp
zhonskate/MCPD
14e8f41c5b9317dc5c4ccbddba95e6db69087d29
[ "MIT" ]
null
null
null
/* El código desarrollado en la Actividad 2 debe funcionar con el siguiente programa principal */ /* donde getN es el método que permite obtener la dimensión de la Tabla */ /* Si el código está correcto mostrará lo siguiente */ /* Tabla 1: [ 83 86 77 15 93 35 86 92 49 21 ] */ /* Tabla 2: [ 62 27 90 59 63 ] */ /* Tabla 3: [ 62 27 90 59 63 ] */ /* Tabla 4: [ 83 86 77 15 93 35 86 92 49 21 ] */ /*int main() { Tabla t1; Tabla t2(5); for( int i=0; i<t1.getN(); i++ ) { t1[i] = rand() % 100; } cout << "Tabla 1: " << t1; for( int i=0; i<t2.getN(); i++ ) { t2[i] = rand() % 100; } cout << "Tabla 2: " << t2; Tabla t3(t2); cout << "Tabla 3: " << t3; Tabla t4(5); t4 = t1; cout << "Tabla 4: " << t4; } */
26.40625
97
0.47574
zhonskate
e81aebed47e6eb18ed58f218cee4be929d85bbbe
6,460
hpp
C++
models/epidemic/epidemic.hpp
pvelesko/warped2-models
e0afe5119374c9e2191c946f70510bb6d7558f44
[ "MIT" ]
4
2015-04-13T17:22:51.000Z
2018-01-16T14:54:33.000Z
models/epidemic/epidemic.hpp
pvelesko/warped2-models
e0afe5119374c9e2191c946f70510bb6d7558f44
[ "MIT" ]
3
2017-08-14T21:41:32.000Z
2020-08-21T08:21:14.000Z
models/epidemic/epidemic.hpp
pvelesko/warped2-models
e0afe5119374c9e2191c946f70510bb6d7558f44
[ "MIT" ]
8
2015-09-28T08:25:34.000Z
2020-04-01T12:25:15.000Z
#ifndef EPIDEMIC_HPP #define EPIDEMIC_HPP #include <string> #include <vector> #include <map> #include <random> #include "memory.hpp" #include "warped.hpp" #include "Person.hpp" #include "DiseaseModel.hpp" #include "DiffusionNetwork.hpp" WARPED_DEFINE_LP_STATE_STRUCT(LocationState) { LocationState() { current_population_ = std::make_shared<std::map <unsigned long, std::shared_ptr<Person>>>(); } LocationState(const LocationState& other) { current_population_ = std::make_shared<std::map <unsigned long, std::shared_ptr<Person>>>(); for (auto it = other.current_population_->begin(); it != other.current_population_->end(); it++) { auto person = it->second; auto new_person = std::make_shared<Person>( person->pid_, person->susceptibility_, person->vaccination_status_, person->infection_state_, person->loc_arrival_timestamp_, person->prev_state_change_timestamp_ ); current_population_->insert(current_population_->begin(), std::pair <unsigned long, std::shared_ptr<Person>> (person->pid_, new_person)); } }; std::shared_ptr<std::map <unsigned long, std::shared_ptr<Person>>> current_population_; }; enum event_type_t { DISEASE_UPDATE_TRIGGER, DIFFUSION_TRIGGER, DIFFUSION }; class EpidemicEvent : public warped::Event { public: EpidemicEvent() = default; EpidemicEvent(const std::string receiver_name, unsigned int timestamp, std::shared_ptr<Person> person, event_type_t event_type) : receiver_name_(receiver_name), loc_arrival_timestamp_(timestamp), event_type_(event_type) { if (person != nullptr) { pid_ = person->pid_; susceptibility_ = person->susceptibility_; vaccination_status_ = person->vaccination_status_; infection_state_ = person->infection_state_; prev_state_change_timestamp_ = person->prev_state_change_timestamp_; } } const std::string& receiverName() const { return receiver_name_; } unsigned int timestamp() const { return loc_arrival_timestamp_; } unsigned int size() const { return receiver_name_.length() + sizeof(pid_) + sizeof(susceptibility_) + sizeof(vaccination_status_) + sizeof(infection_state_) + sizeof(loc_arrival_timestamp_) + sizeof(prev_state_change_timestamp_) + sizeof(event_type_); } std::string receiver_name_; unsigned long pid_; double susceptibility_; bool vaccination_status_; infection_state_t infection_state_; unsigned int loc_arrival_timestamp_; unsigned int prev_state_change_timestamp_; event_type_t event_type_; WARPED_REGISTER_SERIALIZABLE_MEMBERS(cereal::base_class<warped::Event>(this), receiver_name_, pid_, susceptibility_, vaccination_status_, infection_state_, loc_arrival_timestamp_, prev_state_change_timestamp_, event_type_) }; class Location : public warped::LogicalProcess { public: Location(const std::string& name, float transmissibility, unsigned int latent_dwell_interval, unsigned int incubating_dwell_interval, unsigned int infectious_dwell_interval, unsigned int asympt_dwell_interval, float latent_infectivity, float incubating_infectivity, float infectious_infectivity, float asympt_infectivity, float prob_ulu, float prob_ulv, float prob_urv, unsigned int loc_state_refresh_interval, unsigned int loc_diffusion_trig_interval, std::vector<std::shared_ptr<Person>> population, unsigned int travel_time_to_hub, unsigned int index) : LogicalProcess(name), state_(), location_name_(name), location_state_refresh_interval_(loc_state_refresh_interval), location_diffusion_trigger_interval_(loc_diffusion_trig_interval), rng_(new std::default_random_engine(index)) { state_ = std::make_shared<LocationState>(); disease_model_ = std::make_shared<DiseaseModel>( transmissibility, latent_dwell_interval, incubating_dwell_interval, infectious_dwell_interval, asympt_dwell_interval, latent_infectivity, incubating_infectivity, infectious_infectivity, asympt_infectivity, prob_ulu, prob_ulv, prob_urv); diffusion_network_ = std::make_shared<DiffusionNetwork>(travel_time_to_hub, rng_); for (auto& person : population) { state_->current_population_->insert(state_->current_population_->begin(), std::pair <unsigned long, std::shared_ptr<Person>> (person->pid_, person)); } } virtual warped::LPState& getState() override { return *state_; } virtual std::vector<std::shared_ptr<warped::Event>> initializeLP() override; virtual std::vector<std::shared_ptr<warped::Event>> receiveEvent(const warped::Event& event) override; void populateTravelDistances(std::map<std::string, unsigned int> travel_chart) { diffusion_network_->populateTravelChart(travel_chart); } void statistics ( unsigned long *population_size, unsigned long *affected_cnt ) { auto population_map = *state_->current_population_; *population_size = population_map.size(); *affected_cnt = 0; for (auto& entry : population_map) { auto person = *entry.second; if (person.isAffected()) (*affected_cnt)++; } } std::string getLocationName() { return location_name_; } protected: std::shared_ptr<LocationState> state_; std::string location_name_; std::shared_ptr<DiseaseModel> disease_model_; std::shared_ptr<DiffusionNetwork> diffusion_network_; unsigned int location_state_refresh_interval_; unsigned int location_diffusion_trigger_interval_; std::shared_ptr<std::default_random_engine> rng_; }; #endif
38.224852
106
0.644582
pvelesko
e81c23115fc18d2098aad9d464d36b3d17d027d9
352
hpp
C++
include/LevelSettings.hpp
vyorkin/asteroids
870256e338eefb07466af27735d5b8df0c5c7d42
[ "MIT" ]
1
2015-03-13T10:09:54.000Z
2015-03-13T10:09:54.000Z
include/LevelSettings.hpp
vyorkin-personal/asteroids
870256e338eefb07466af27735d5b8df0c5c7d42
[ "MIT" ]
null
null
null
include/LevelSettings.hpp
vyorkin-personal/asteroids
870256e338eefb07466af27735d5b8df0c5c7d42
[ "MIT" ]
null
null
null
#pragma once #include "Base.hpp" enum LevelDifficulty { Easy, Normal, Hard }; struct LevelSettings { LevelSettings(); LevelSettings(const LevelSettings&) = default; LevelSettings(const LevelDifficulty difficulty, const int numAsteroids); LevelDifficulty difficulty; int numAsteroids; static const LevelSettings initial; };
20.705882
76
0.741477
vyorkin
e8267e60757fdd2e5eda623f9d6321b427be89c7
4,428
cpp
C++
ros/src/sensing/fusion/packages/calibration_camera_lidar/nodes/calibration_test/scan_window.cpp
filiperinaldi/Autoware
9fae6cc7cb8253586578dbb62a2f075b52849e6e
[ "Apache-2.0" ]
4
2019-04-22T10:18:26.000Z
2019-05-20T05:16:03.000Z
ros/src/sensing/fusion/packages/calibration_camera_lidar/nodes/calibration_test/scan_window.cpp
filiperinaldi/Autoware
9fae6cc7cb8253586578dbb62a2f075b52849e6e
[ "Apache-2.0" ]
1
2019-03-05T05:52:41.000Z
2019-03-05T05:52:41.000Z
ros/src/sensing/fusion/packages/calibration_camera_lidar/nodes/calibration_test/scan_window.cpp
filiperinaldi/Autoware
9fae6cc7cb8253586578dbb62a2f075b52849e6e
[ "Apache-2.0" ]
2
2019-06-23T18:08:04.000Z
2019-07-04T14:14:59.000Z
/* * Copyright 2015-2019 Autoware Foundation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "scan_window.h" void plot_vertical_line(IplImage* image, int line_division_num, int window_width, int window_height) { CvPoint line_start, line_end; for (int i = 0; i < line_division_num; i++) { line_start.x = 0; line_start.y = window_height / line_division_num * (i + 1); line_end.x = window_width; line_end.y = window_height / line_division_num * (i + 1); cvLine(image, line_start, line_end, CV_RGB (120, 120, 120), 1, 8, 0); } } void plot_horizontal_line(IplImage* image, int window_width, int window_height) { CvPoint line_start, line_end; line_start.x = window_width / 2; line_start.y = 0; line_end.x = window_width /2; line_end.y = window_height; cvLine(image, line_start, line_end, CV_RGB (120, 120, 120), 1, 8, 0); } void plot_center_pt_line(IplImage *image, CvPoint center_pt, int chess_size, int pat_col, int margin, int window_width, int window_height, int scale) { CvPoint line_start, line_end; /* chessboard horizontal line */ line_start.x = window_width / 2 - ((chess_size / 1000) * (pat_col + 1) + (margin /1000)) * scale / 2; line_start.y = center_pt.y; line_end.x = window_width /2 + ((chess_size / 1000) * (pat_col + 1) + (margin /1000)) * scale / 2; line_end.y = center_pt.y; cvLine(image, line_start, line_end, CV_RGB (255, 255, 0), 1, 8, 0); /* chessboard vertical line */ // left line line_start.x = window_width/2 - ((chess_size/1000.0) * (pat_col+1) + (margin/1000.0)) * scale / 2; line_start.y = 0; line_end.x = window_width/2 - ((chess_size/1000.0) * (pat_col+1) + (margin/1000.0)) * scale / 2; line_end.y = window_height; cvLine(image, line_start, line_end, CV_RGB (255, 255, 0), 1, 8, 0); // right line line_start.x = window_width/2 + (((float)chess_size/1000.0) * (pat_col+1) + ((float)margin/1000.0)) * scale / 2; line_start.y = 0; line_end.x = window_width/2 + (((float)chess_size/1000.0) * (pat_col+1) + ((float)margin/1000.0)) * scale / 2; line_end.y = window_height; cvLine(image, line_start, line_end, CV_RGB (255, 255, 0), 1, 8, 0); } CvPoint get_center_pt(int window_width, Three_dimensional_vector* scan, int scale) { CvPoint center_pt; center_pt.x = scan->x[scan->x.size() / 2] * scale + (window_width / 2); center_pt.y = scan->z[scan->x.size() / 2] * scale; return center_pt; } void plot_string(IplImage* image, const char* text, int thickness, int x, int y, CvScalar color) { CvFont dfont; float hscale = 1.0f; float vscale = 1.0f; float italicscale = 0.0f; cvInitFont (&dfont, CV_FONT_HERSHEY_SIMPLEX , hscale, vscale, italicscale, thickness, CV_AA); cvPutText(image, text, cvPoint(x, y), &dfont, color); } void plot_string_on_buttun(IplImage* image, const char* text, int thickness, int x, int y, bool on_mouse) { if (on_mouse) plot_string(image, text, thickness, x, y, CV_RGB(250, 250, 250)); else plot_string(image, text, thickness, x, y, CV_RGB(150, 150, 150)); } void plot_scan_image(IplImage* image, Two_dimensional_vector* scan_image) { CvSeq *points; CvPoint pt; CvMemStorage *storage = cvCreateMemStorage (0); points = cvCreateSeq (CV_SEQ_ELTYPE_POINT, sizeof (CvSeq), sizeof (CvPoint), storage); for (int i = 0; i < (int)scan_image->x.size(); i++) { if(0 > scan_image->x[i] || scan_image->x[i] > 639) { continue; } if(0 > scan_image->y[i] || scan_image->y[i] > 479) { continue; } pt.x = scan_image->x[i]; pt.y = scan_image->y[i]; cvSeqPush (points, &pt); cvCircle(image, pt, 2, CV_RGB (0, 255, 0), CV_FILLED, 8, 0); } cvClearSeq(points); cvReleaseMemStorage(&storage); }
36.9
149
0.651536
filiperinaldi
e826be4a7e76bd740d4f56a76693422e6828e30d
4,274
hpp
C++
test/verify_r1cs_scheme.hpp
skywinder/crypto3-blueprint
c2b033eaaff1a19ab5332b9f49a32bb4fdd1dc20
[ "MIT" ]
6
2021-05-27T04:52:42.000Z
2022-01-23T23:33:40.000Z
test/verify_r1cs_scheme.hpp
skywinder/crypto3-blueprint
c2b033eaaff1a19ab5332b9f49a32bb4fdd1dc20
[ "MIT" ]
12
2020-12-08T15:17:00.000Z
2022-03-17T22:19:43.000Z
test/verify_r1cs_scheme.hpp
skywinder/crypto3-blueprint
c2b033eaaff1a19ab5332b9f49a32bb4fdd1dc20
[ "MIT" ]
5
2021-05-20T20:02:17.000Z
2022-01-14T12:26:24.000Z
//---------------------------------------------------------------------------// // Copyright (c) 2018-2021 Mikhail Komarov <[email protected]> // Copyright (c) 2020-2021 Nikita Kaskov <[email protected]> // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //---------------------------------------------------------------------------// #ifndef CRYPTO3_ZK_BLUEPRINT_VERIFY_R1CS_SCHEME_COMPONENT_TEST_HPP #define CRYPTO3_ZK_BLUEPRINT_VERIFY_R1CS_SCHEME_COMPONENT_TEST_HPP #include <boost/test/unit_test.hpp> #include <nil/crypto3/zk/snark/algorithms/generate.hpp> #include <nil/crypto3/zk/snark/algorithms/verify.hpp> #include <nil/crypto3/zk/snark/algorithms/prove.hpp> #include <nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark.hpp> #include <nil/crypto3/zk/components/blueprint.hpp> #include <nil/crypto3/algebra/curves/edwards.hpp> using namespace nil::crypto3; using namespace nil::crypto3::zk; using namespace nil::crypto3::algebra; template<typename CurveType, typename SchemeType = snark::r1cs_gg_ppzksnark<CurveType>> bool verify_component(components::blueprint<typename CurveType::scalar_field_type> bp){ if (bp.num_variables() == 0x00){ std::cout << "Empty blueprint!" << std::endl; return false; } using field_type = typename CurveType::scalar_field_type; using scheme_type = SchemeType; const snark::r1cs_constraint_system<field_type> constraint_system = bp.get_constraint_system(); auto begin = std::chrono::high_resolution_clock::now(); const typename scheme_type::keypair_type keypair = snark::generate<scheme_type>(constraint_system); auto end = std::chrono::high_resolution_clock::now(); auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin); std::cout << "Key generation finished, time: " << elapsed.count() * 1e-9 << std::endl; begin = std::chrono::high_resolution_clock::now(); const typename scheme_type::proof_type proof = snark::prove<scheme_type>(keypair.first, bp.primary_input(), bp.auxiliary_input()); end = std::chrono::high_resolution_clock::now(); elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin); std::cout << "Proving finished, time: " << elapsed.count() * 1e-9 << std::endl; begin = std::chrono::high_resolution_clock::now(); bool verified = snark::verify<scheme_type>(keypair.second, bp.primary_input(), proof); end = std::chrono::high_resolution_clock::now(); elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin); std::cout << "Number of R1CS constraints: " << constraint_system.num_constraints() << std::endl; std::cout << "Verification finished, time: " << elapsed.count() * 1e-9 << std::endl; std::cout << "Verification status: " << verified << std::endl; return verified; } template<> bool verify_component<curves::edwards<183>, snark::r1cs_gg_ppzksnark<curves::edwards<183>>>(components::blueprint<typename curves::edwards<183>::scalar_field_type> bp){ std::cout << "Warning! r1cs_gg_ppzksnark for Edwards-183 is not implemented yet" << std::endl; return false; } #endif // CRYPTO3_ZK_BLUEPRINT_VERIFY_R1CS_SCHEME_COMPONENT_TEST_HPP
46.967033
146
0.710108
skywinder
e82d2cb5dcf66a271197b6dc5b78044987cfe354
599
cpp
C++
avs/vis_avs/g_unkn.cpp
semiessessi/vis_avs
e99a3803e9de9032e0e6759963b2c2798f3443ef
[ "BSD-3-Clause" ]
18
2020-07-30T11:55:23.000Z
2022-02-25T02:39:15.000Z
avs/vis_avs/g_unkn.cpp
semiessessi/vis_avs
e99a3803e9de9032e0e6759963b2c2798f3443ef
[ "BSD-3-Clause" ]
34
2021-01-13T02:02:12.000Z
2022-03-23T12:09:55.000Z
avs/vis_avs/g_unkn.cpp
semiessessi/vis_avs
e99a3803e9de9032e0e6759963b2c2798f3443ef
[ "BSD-3-Clause" ]
3
2021-03-18T12:53:58.000Z
2021-10-02T20:24:41.000Z
#include "g__lib.h" #include "g__defs.h" #include "c_unkn.h" #include "resource.h" #include <windows.h> int win32_dlgproc_unknown(HWND hwndDlg, UINT uMsg, WPARAM, LPARAM) { C_UnknClass* g_this = (C_UnknClass*)g_current_render; switch (uMsg) { case WM_INITDIALOG: { char s[512]=""; if (g_this->idString[0]) wsprintf(s,"APE: %s\r\n",g_this->idString); else wsprintf(s,"Built-in ID: %d\r\n",g_this->id); wsprintf(s+strlen(s),"Config size: %d\r\n",g_this->configdata_len); SetDlgItemText(hwndDlg,IDC_EDIT1,s); } return 1; } return 0; }
23.038462
76
0.63606
semiessessi
e82d366ad09f8a438f44b4123bdd65819ad0d51f
5,774
cpp
C++
src/renderer/surface_smoothing_pass.cpp
gustavo4passos/opengl-fluidrendering
572a84760b4338559e16dbca4865931e5062d34a
[ "MIT" ]
2
2019-10-23T09:54:18.000Z
2020-02-05T23:05:33.000Z
src/renderer/surface_smoothing_pass.cpp
gustavo4passos/opengl-fluidrendering
572a84760b4338559e16dbca4865931e5062d34a
[ "MIT" ]
null
null
null
src/renderer/surface_smoothing_pass.cpp
gustavo4passos/opengl-fluidrendering
572a84760b4338559e16dbca4865931e5062d34a
[ "MIT" ]
null
null
null
#include "surface_smoothing_pass.h" #include "../utils/logger.h" #include "../utils/glcall.h" #include <assert.h> namespace fluidity { SurfaceSmoothingPass::SurfaceSmoothingPass( const unsigned bufferWidth, const unsigned bufferHeight, const unsigned kernelRadius, const unsigned nIterations) : m_bufferWidth(bufferWidth), m_bufferHeight(bufferHeight), m_kernelRadius(kernelRadius), m_nIterations(nIterations), m_fbo(0), m_unfilteredSurfaces(0), m_currentWorkingSurfaces(0), m_smoothedSurfaces(0), m_bilateralFilter(nullptr) { } auto SurfaceSmoothingPass::Init() -> bool { GLfloat screenQuadVertices[] = { -1.f, 1.f, 0.f, 1.f, 1.f, 1.f, 1.f, 1.f, -1.f, -1.f, 0.f, 0.f, 1.f, 1.f, 1.f, 1.f, -1.f, -1.f, 0.f, 0.f, 1.f, -1.f, 1.f, 0.f }; GLCall(glGenBuffers(1, &m_screenQuadVbo)); GLCall(glGenVertexArrays(1, &m_screenQuadVao)); GLCall(glBindVertexArray(m_screenQuadVao)); GLCall(glBindBuffer(GL_ARRAY_BUFFER, m_screenQuadVbo)); GLCall(glBufferData( GL_ARRAY_BUFFER, sizeof(screenQuadVertices), screenQuadVertices, GL_STATIC_DRAW)); GLCall(glVertexAttribPointer( 0, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 4, (const GLvoid*)0)); GLCall(glEnableVertexAttribArray(0)); GLCall(glVertexAttribPointer( 1, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 4, (const GLvoid*)(2 * sizeof(GLfloat)))); GLCall(glEnableVertexAttribArray(1)); GLCall(glBindVertexArray(0)); GLCall(glBindBuffer(GL_ARRAY_BUFFER, 0)); GLCall(glGenFramebuffers(1, &m_fbo)); GLCall(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo)); GLCall(glGenTextures(1, &m_currentWorkingSurfaces)); GLCall(glBindTexture(GL_TEXTURE_2D, m_currentWorkingSurfaces)); GLCall(glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA32F, m_bufferWidth, m_bufferHeight, 0, GL_RGBA, GL_FLOAT, nullptr)); GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)); GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)); GLCall(glGenTextures(1, &m_smoothedSurfaces)); GLCall(glBindTexture(GL_TEXTURE_2D, m_smoothedSurfaces)); GLCall(glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA32F, m_bufferWidth, m_bufferHeight, 0, GL_RGBA, GL_FLOAT, nullptr)); GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)); GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)); // GLCall(glFramebufferTexture2D( // GL_FRAMEBUFFER, // GL_COLOR_ATTACHMENT0, // GL_TEXTURE_2D, // m_smoothedSurfaces, // 0)); // if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) // { // LOG_ERROR("Framebuffer is not complete."); // return false; // } unsigned attachments[2] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 }; GLCall(glDrawBuffers(1, attachments)); GLCall(glBindFramebuffer(GL_FRAMEBUFFER, 0)); m_bilateralFilter = new Shader( "../../shaders/texture_rendering.vert", "../../shaders/bilateral_filter.frag"); return true; } auto SurfaceSmoothingPass::SetUnfilteredSurfaces(const GLuint unfilteredSurfaces) -> void { m_unfilteredSurfaces = unfilteredSurfaces; } auto SurfaceSmoothingPass::Render() -> void { assert(m_bilateralFilter != nullptr); GLCall(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo)); m_bilateralFilter->Bind(); m_bilateralFilter->SetInt("kernelRadius", m_kernelRadius); GLCall(glBindVertexArray(m_screenQuadVao)); GLCall(glActiveTexture(GL_TEXTURE0)); glBindTexture(GL_TEXTURE_2D, m_unfilteredSurfaces); GLCall(glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_smoothedSurfaces, 0)); for(unsigned i = 0; i < m_nIterations; i++) { GLCall(glDrawArrays(GL_TRIANGLES, 0, 6)); glBindTexture(GL_TEXTURE_2D, 0); GLCall(glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0)); InvertWorkingAndSmoothedSurfaces(); GLCall(glBindTexture(GL_TEXTURE_2D, m_currentWorkingSurfaces)); GLCall(glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_smoothedSurfaces, 0)); } InvertWorkingAndSmoothedSurfaces(); GLCall(glBindTexture(GL_TEXTURE_2D, 0)); GLCall(glBindVertexArray(0)); m_bilateralFilter->Unbind(); GLCall(glBindFramebuffer(GL_FRAMEBUFFER, 0)); } auto SurfaceSmoothingPass::InvertWorkingAndSmoothedSurfaces() -> void { GLuint tempTex = m_currentWorkingSurfaces; m_currentWorkingSurfaces = m_smoothedSurfaces; m_smoothedSurfaces = tempTex; } };
31.380435
93
0.579841
gustavo4passos
e830a64d4feda6e6919727636b138853ffdfe68b
3,268
cpp
C++
src/Cylinder.cpp
Dav-v/Rha
77fa838ea0830bd1f335349dd88d0a7005b4a921
[ "Apache-2.0" ]
null
null
null
src/Cylinder.cpp
Dav-v/Rha
77fa838ea0830bd1f335349dd88d0a7005b4a921
[ "Apache-2.0" ]
null
null
null
src/Cylinder.cpp
Dav-v/Rha
77fa838ea0830bd1f335349dd88d0a7005b4a921
[ "Apache-2.0" ]
null
null
null
/* * Author: Davide Viero - [email protected] * Rha raytracer * 2019 * License: see LICENSE file * */ #define GLM_ENABLE_EXPERIMENTAL #include "cylinder.h" #include "gtx/transform.hpp" #include <iostream> using namespace glm; Cylinder::Cylinder(std::string name, vec3 pos, vec3 scale, vec3 col, float ka, float kd, float ks, float kr, float n) { this->name = name; coefficients.ka = ka; coefficients.kd = kd; coefficients.ks = ks; coefficients.kr = kr; coefficients.n = n; color = col; //transform = mat4(1.0f); transform = translate(transform,pos); transform = glm::scale(transform,scale); transform = rotate(transform, 90.0f, vec3(1.0, 0.0f,0.0f)); for(int i = 0; i < 4; i++){ std::cout<<"\n"; for(int k = 0; k < 4; k++) std::cout<<transform[k][i]<<"\t"; } normalsTransform = transpose(transform); invTransform = inverse(transform); invNormalsTransform = transpose(invTransform); } vec3 Cylinder::computeNormal(vec3 point) { vec3 invNormal; vec3 localSpacePoint = vec3(invTransform * vec4(point, 1.0f)); if (localSpacePoint.z > 0.49 && localSpacePoint.z < 0.51) invNormal = vec3(0.0f,0.0f,1.0f); else if (localSpacePoint.z > -0.51 && localSpacePoint.z < -0.49) invNormal = vec3(0.0f, 0.0f, -1.0f); else invNormal = normalize(vec3(localSpacePoint.x,localSpacePoint.y, 0.0f)); vec3 normal = normalize(vec3(invNormalsTransform * vec4(invNormal, 0.0f))); return normal; } std::tuple<bool, std::vector<float>> Cylinder::intersections(Ray r) { // transformed direction in cylinder space vec3 c1 = vec3(invTransform * vec4(r.getDirectionVector(), 0.0f)); // transformed point in cylinder space vec3 s1 = vec3(invTransform * vec4(r.getOriginVector(), 1.0f)); /* Equation for a ray intersection a cylinder : t^2 (dot(cd,cd)) + 2*t (dot(cd,sd)) + (dot(sd,sd) -1) = 0 where cd = vec2(c1.x,c1.y) sd = vec2(s1.x,s1.y) z must be -0.5<= z <= 0.5 */ vec2 cd = vec2(c1); vec2 sd = vec2(s1); float a = dot(cd, cd); float b = dot(sd, cd); float c = (dot(sd, sd) - 1.0f); float d = pow(b, 2.0f) - a * c; if (d < 0.0f) return std::make_tuple(false, std::vector<float>{0.0f}); float t0 = (-b + sqrt(d)) / a; float t1 = (-b - sqrt(d)) / a; bool intersected = false; vec3 p0 = c1 * t0 +s1; vec3 p1 = c1 * t1 +s1; std::vector<float> intersectionsT; if(p0.z >= -0.5 && p0.z <= 0.5) { intersected = true; intersectionsT.push_back(t0); } if (p1.z >= -0.5 && p1.z <= 0.5) { intersected = true; intersectionsT.push_back(t1); } float t2 = (0.5f-s1.z) / c1.z; float t3 = (-0.5f-s1.z) / c1.z; float x = c1.x * t2 + s1.x; float y = c1.y * t2 + s1.y; if(pow(x,2)+pow(y,2) <= 1.0f) { intersected = true; intersectionsT.push_back(t2); } x = c1.x * t3 + s1.x; y = c1.y * t3 + s1.y; if(pow(x,2)+pow(y,2) <= 1.0f) { intersected = true; intersectionsT.push_back(t3); } /* if(t0>0.0001f || t1>0.0001f) return std::make_tuple(true, intersectionsT); else return std::make_tuple(false, intersectionsT); */ return std::make_tuple(intersected, intersectionsT); }
25.333333
77
0.596389
Dav-v
e836c767dab22097db382c4364e130cb44e5b488
48
cpp
C++
chapter_2/ex_2.32.cpp
YasserKa/Cpp_Primer
198b10255fd67e31c15423a5e44b7f02abb8bdc2
[ "MIT" ]
null
null
null
chapter_2/ex_2.32.cpp
YasserKa/Cpp_Primer
198b10255fd67e31c15423a5e44b7f02abb8bdc2
[ "MIT" ]
null
null
null
chapter_2/ex_2.32.cpp
YasserKa/Cpp_Primer
198b10255fd67e31c15423a5e44b7f02abb8bdc2
[ "MIT" ]
null
null
null
/** * int null = 0, *p = null; it's legal */
9.6
38
0.4375
YasserKa
e8391600bbf2026275e2b2631d9938ab48d8308b
1,495
hpp
C++
include/gl/primitives/plane.hpp
scholli/unvox
879e06f45a40963527e0a895d742f7be6fb3d490
[ "MIT" ]
null
null
null
include/gl/primitives/plane.hpp
scholli/unvox
879e06f45a40963527e0a895d742f7be6fb3d490
[ "MIT" ]
null
null
null
include/gl/primitives/plane.hpp
scholli/unvox
879e06f45a40963527e0a895d742f7be6fb3d490
[ "MIT" ]
1
2019-10-30T09:35:35.000Z
2019-10-30T09:35:35.000Z
//****************************************************************************** // Module: UnVox // Author: Sebastian Thiele / Andre Schollmeyer // // Copyright 2019 // All rights reserved //****************************************************************************** #ifndef UNVOX_GL_PLANE_HPP #define UNVOX_GL_PLANE_HPP #include <gl/glpp.hpp> #include <gl/arraybuffer.hpp> #include <gl/vertexarrayobject.hpp> #include <glm/glm.hpp> namespace unvox { namespace gl { class UNVOX_GL plane { public : plane ( GLint vertexattrib_index, GLint normalattrib_index, GLint texcoordattrib_index ); ~plane ( ); plane(plane const& other) = delete; plane operator=(plane const& other) = delete; public : void size ( float width, float height ); void texcoords ( glm::vec4 const& a, glm::vec4 const& b, glm::vec4 const& c, glm::vec4 const& d); void normal ( glm::vec4 const& n ); void attrib_location ( GLint vertexattrib_index, GLint normalattrib_index, GLint texcoordattrib_index ); void draw ( ); private : arraybuffer _vertices; arraybuffer _normals; arraybuffer _texcoords; vertexarrayobject _vao; }; } } // namespace unvox / namespace gl #endif // UNVOX_GL_PLANE_HPP
25.338983
111
0.506355
scholli
e83bc97b368b34510632f4702e0282cbd32d4cde
1,206
hpp
C++
Hardware/Sensor/IMU/mpu9150.hpp
SaurusQ/FoamPilot
562acfc50feb19d1216a0fabe6b85cf2f85057e4
[ "MIT" ]
null
null
null
Hardware/Sensor/IMU/mpu9150.hpp
SaurusQ/FoamPilot
562acfc50feb19d1216a0fabe6b85cf2f85057e4
[ "MIT" ]
null
null
null
Hardware/Sensor/IMU/mpu9150.hpp
SaurusQ/FoamPilot
562acfc50feb19d1216a0fabe6b85cf2f85057e4
[ "MIT" ]
null
null
null
#ifndef MPU9150_HPP #define MPU9150_HPP #include "hwSelect.hpp" #ifdef SELECT_MPU9150 #include "imu.hpp" #include "I2cBus.hpp" #define MPU9150_I2C_ADDR 0x68 #define MPU9150_GYRO_CONFIG 0x27 #define MPU9150_ACCEL_CONFIG 0x28 #define MPU9150_ACCEL_XOUT_H 0x3B #define MPU9150_PWR_MGMT_1 0x6B // compass #define MPU9150_MAG_I2C_ADDR 0x0C #define MPU9150_MAG_XOUT_L 0x03 #define MPU9150_INT_PIN_CFG 0x37 enum AccelSens { FS_2 = 0x00, FS_4 = 0x01, FS_8 = 0x02, FS_16 = 0x03, }; enum GyroSens { FS_250 = 0x00, FS_500 = 0x01, FS_1000 = 0x02, FS_2000 = 0x03, }; class MPU9150 : public Imu { public: MPU9150(); virtual ~MPU9150() {} virtual void init(); virtual void reset(); virtual void calibrate(); virtual void update(); virtual void isHealhty(); virtual void setAccelSens(AccelSens sens); virtual void setGyroSens(GyroSens sens); virtual void setSleepEnabled(bool enabled); protected: I2cBus* pI2cBus_; float accSensMult_; float gyroSensMult_; float compSensMult_; }; #endif #endif
19.451613
51
0.635158
SaurusQ
e84aad78cb7c40555ddc41b8a8e2a6a6d231abe4
13,788
cpp
C++
src/common/motion_model/test/test_differential_motion_model.cpp
ruvus/auto
25ae62d6e575cae40212356eed43ec3e76e9a13e
[ "Apache-2.0" ]
19
2021-05-28T06:14:21.000Z
2022-03-10T10:03:08.000Z
src/common/motion_model/test/test_differential_motion_model.cpp
ruvus/auto
25ae62d6e575cae40212356eed43ec3e76e9a13e
[ "Apache-2.0" ]
222
2021-10-29T22:00:27.000Z
2022-03-29T20:56:34.000Z
src/common/motion_model/test/test_differential_motion_model.cpp
ruvus/auto
25ae62d6e575cae40212356eed43ec3e76e9a13e
[ "Apache-2.0" ]
14
2021-05-29T14:59:17.000Z
2022-03-10T10:03:09.000Z
// Copyright 2021 Apex.AI, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // //    http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Developed by Apex.AI, Inc. #include <motion_model/differential_drive_motion_model.hpp> #include <state_vector/common_states.hpp> #include <gtest/gtest.h> #include <array> #include <chrono> #include <cmath> using autoware::common::motion_model::CatrMotionModel32; using autoware::common::motion_model::CvtrMotionModel32; using autoware::common::state_vector::variable::X; using autoware::common::state_vector::variable::Y; using autoware::common::state_vector::variable::YAW; using autoware::common::state_vector::variable::YAW_CHANGE_RATE; using autoware::common::state_vector::variable::XY_VELOCITY; using autoware::common::state_vector::variable::XY_ACCELERATION; using autoware::common::types::float32_t; using std::sqrt; using std::sin; using std::cos; namespace { constexpr auto kEpsilon = 1.0e-6F; } // namespace /// @test Make sure a static object stays static. TEST(CvtrMotionModelTest, PredictStaticObject) { CvtrMotionModel32 model; CvtrMotionModel32::State initial_state{CvtrMotionModel32::State{}}; initial_state.at<X>() = 42.0F; initial_state.at<Y>() = 42.0F; initial_state.at<YAW>() = 1.0F; EXPECT_EQ( initial_state, model.predict(initial_state, std::chrono::milliseconds{100LL})); } /// @test Make sure a static object stays static. TEST(CatrMotionModelTest, PredictStaticObject) { CatrMotionModel32 model; CatrMotionModel32::State initial_state{CatrMotionModel32::State{}}; initial_state.at<X>() = 42.0F; initial_state.at<Y>() = 42.0F; initial_state.at<YAW>() = 1.0F; EXPECT_EQ( initial_state, model.predict(initial_state, std::chrono::milliseconds{100LL})); } /// @test Check that the Jacobian matches one computed symbolically when turn rate is not zero. TEST(CvtrMotionModelTest, TestJacobianNonZeroTurnRate) { CvtrMotionModel32::State state{CvtrMotionModel32::State{}}; state.at<X>() = 42.0F; state.at<Y>() = 23.0F; state.at<YAW>() = 0.5F; state.at<XY_VELOCITY>() = 2.0F; state.at<YAW_CHANGE_RATE>() = 2.0F; // Computed with SymPy. CvtrMotionModel32::State::Matrix expected_jacobian{(CvtrMotionModel32::State::Matrix{} << 1.0F, 0.0F, -0.112740374605884F, 0.082396074316744F, -0.00591185558829518F, 0.0F, 1.0F, 0.164792148633488F, 0.0563701873029421F, 0.00805158142082696F, 0.0F, 0.0F, 1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F, 0.1F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F).finished()}; CvtrMotionModel32 model; const auto jacobian = model.jacobian(state, std::chrono::milliseconds{100LL}); EXPECT_TRUE(expected_jacobian.isApprox(jacobian, kEpsilon)) << "Jacobians don't match: \nExpected:\n" << expected_jacobian << "\nActual:\n" << jacobian; } /// @test Check that the Jacobian matches one computed symbolically when turn rate is not zero. TEST(CatrMotionModelTest, TestJacobianNonZeroTurnRate) { CatrMotionModel32::State state{CatrMotionModel32::State{}}; state.at<X>() = 42.0F; state.at<Y>() = 23.0F; state.at<YAW>() = 0.5F; state.at<XY_VELOCITY>() = 2.0F; state.at<YAW_CHANGE_RATE>() = 2.0F; state.at<XY_ACCELERATION>() = 2.0F; // Computed with SymPy. CatrMotionModel32::State::Matrix expected_jacobian{(CatrMotionModel32::State::Matrix{} << 1.0F, 0.0F, -0.1186522F, 0.0823960F, -0.0063150F, 0.0040257F, 0.0F, 1.0F, 0.1728437F, 0.0563701F, 0.0085819F, 0.0029559277F, 0.0F, 0.0F, 1.0F, 0.0F, 0.1F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F, 0.0F, 0.1F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F).finished()}; CatrMotionModel32 model; const auto jacobian = model.jacobian(state, std::chrono::milliseconds{100LL}); EXPECT_TRUE(expected_jacobian.isApprox(jacobian, kEpsilon)) << "Jacobians don't match: \nExpected:\n" << expected_jacobian << "\nActual:\n" << jacobian; } /// @test Check that the Jacobian matches one computed symbolically when turn rate is zero. TEST(CvtrMotionModelTest, TestJacobianZeroTurnRate) { CvtrMotionModel32::State state{CvtrMotionModel32::State{}}; state.at<X>() = 42.0F; state.at<Y>() = 23.0F; state.at<YAW>() = 0.5F; state.at<XY_VELOCITY>() = 2.0F; state.at<YAW_CHANGE_RATE>() = 0.0F; // Computed with SymPy. CvtrMotionModel32::State::Matrix expected_jacobian{(CvtrMotionModel32::State::Matrix{} << 1.0F, 0.0F, -0.0958851077208406F, 0.0877582561890373F, -0.00958851077208406F, 0.0F, 1.0F, 0.175516512378075F, 0.0479425538604203F, 0.0175516512378075F, 0.0F, 0.0F, 1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F).finished()}; CvtrMotionModel32 model; const auto jacobian = model.jacobian(state, std::chrono::milliseconds{100LL}); EXPECT_TRUE(expected_jacobian.isApprox(jacobian, kEpsilon)) << "Jacobians don't match: \nExpected:\n" << expected_jacobian << "\nActual:\n" << jacobian; } /// @test Check that the Jacobian matches one computed symbolically when turn rate is zero. TEST(CatrMotionModelTest, TestJacobianZeroTurnRate) { CatrMotionModel32::State state{CatrMotionModel32::State{}}; state.at<X>() = 42.0F; state.at<Y>() = 23.0F; state.at<YAW>() = 0.5F; state.at<XY_VELOCITY>() = 2.0F; state.at<YAW_CHANGE_RATE>() = 0.0F; state.at<XY_ACCELERATION>() = 2.0F; // Computed with SymPy. CatrMotionModel32::State::Matrix expected_jacobian{(CatrMotionModel32::State::Matrix{} << 1.0F, 0.0F, -0.1006793F, 0.0877582F, -0.0100679F, 0.0043879F, 0.0F, 1.0F, 0.1842923F, 0.0479425F, 0.0184292F, 0.0023971F, 0.0F, 0.0F, 1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F, 0.0F, 0.1F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F).finished()}; CatrMotionModel32 model; const auto jacobian = model.jacobian(state, std::chrono::milliseconds{100LL}); EXPECT_TRUE(expected_jacobian.isApprox(jacobian, kEpsilon)) << "Jacobians don't match: \nExpected:\n" << expected_jacobian << "\nActual:\n" << jacobian; } /// @test Predict the linear movement with zero turn rate. TEST(CvtrMotionModelTest, PredictLinearMovementWithZeroTurnRate) { CvtrMotionModel32 model; CvtrMotionModel32::State initial_state{}; // Movement in X direction. initial_state = CvtrMotionModel32::State{}; initial_state.at<XY_VELOCITY>() = 1.0F; CvtrMotionModel32::State expected_state{initial_state}; expected_state.at<X>() += 1.0F; EXPECT_EQ(expected_state, model.predict(initial_state, std::chrono::seconds{1LL})); // Movement in negative X direction. initial_state = CvtrMotionModel32::State{}; initial_state.at<XY_VELOCITY>() = -1.0F; expected_state = initial_state; expected_state.at<X>() -= 1.0F; EXPECT_EQ(expected_state, model.predict(initial_state, std::chrono::seconds{1LL})); // Movement in Y direction. initial_state = CvtrMotionModel32::State{}; initial_state.at<XY_VELOCITY>() = 1.0F; initial_state.at<YAW>() = 0.5F * M_PIf32; expected_state = initial_state; expected_state.at<Y>() += 1.0F; EXPECT_EQ(expected_state, model.predict(initial_state, std::chrono::seconds{1LL})); // Movement in negative Y direction. initial_state = CvtrMotionModel32::State{}; initial_state.at<XY_VELOCITY>() = 1.0F; initial_state.at<YAW>() = -0.5F * M_PIf32; expected_state = initial_state; expected_state.at<Y>() -= 1.0F; EXPECT_EQ(expected_state, model.predict(initial_state, std::chrono::seconds{1LL})); // Movement in XY direction. initial_state = CvtrMotionModel32::State{}; initial_state.at<XY_VELOCITY>() = 1.0F; initial_state.at<YAW>() = 0.25F * M_PIf32; expected_state = initial_state; expected_state.at<X>() += 0.5F * sqrt(2.0F); expected_state.at<Y>() += 0.5F * sqrt(2.0F); EXPECT_EQ(expected_state, model.predict(initial_state, std::chrono::seconds{1LL})); // Movement in negative XY direction. initial_state = CvtrMotionModel32::State{}; initial_state.at<XY_VELOCITY>() = 1.0F; initial_state.at<YAW>() = -0.75F * M_PIf32; expected_state = initial_state; expected_state.at<X>() -= 0.5F * sqrt(2.0F); expected_state.at<Y>() -= 0.5F * sqrt(2.0F); EXPECT_EQ(expected_state, model.predict(initial_state, std::chrono::seconds{1LL})); } /// @test Predict the linear movement with zero turn rate. TEST(CatrMotionModelTest, PredictLinearMovementWithZeroTurnRate) { CatrMotionModel32 model; CatrMotionModel32::State initial_state{}; // Movement in X direction. initial_state = CatrMotionModel32::State{}; initial_state.at<XY_VELOCITY>() = 1.0F; initial_state.at<XY_ACCELERATION>() = 1.0F; const auto time_difference{std::chrono::seconds{1LL}}; const auto dt{std::chrono::duration<float32_t>{time_difference}.count()}; CatrMotionModel32::State expected_state{initial_state}; expected_state.at<X>() += dt * initial_state.at<XY_VELOCITY>() + 0.5F * dt * dt * initial_state.at<XY_ACCELERATION>(); expected_state.at<XY_VELOCITY>() += dt * initial_state.at<XY_ACCELERATION>(); EXPECT_EQ(expected_state, model.predict(initial_state, time_difference)); // Movement in negative X direction. initial_state = CatrMotionModel32::State{}; initial_state.at<XY_VELOCITY>() = -1.0F; initial_state.at<XY_ACCELERATION>() = -1.0F; expected_state = initial_state; expected_state.at<X>() += dt * initial_state.at<XY_VELOCITY>() + 0.5F * dt * dt * initial_state.at<XY_ACCELERATION>(); expected_state.at<XY_VELOCITY>() += dt * initial_state.at<XY_ACCELERATION>(); EXPECT_EQ(expected_state, model.predict(initial_state, time_difference)); // Movement in Y direction. initial_state = CatrMotionModel32::State{}; initial_state.at<XY_VELOCITY>() = 1.0F; initial_state.at<XY_ACCELERATION>() = 1.0F; initial_state.at<YAW>() = 0.5F * M_PIf32; expected_state = initial_state; expected_state.at<Y>() += dt * initial_state.at<XY_VELOCITY>() + 0.5F * dt * dt * initial_state.at<XY_ACCELERATION>(); expected_state.at<XY_VELOCITY>() += dt * initial_state.at<XY_ACCELERATION>(); EXPECT_EQ(expected_state, model.predict(initial_state, time_difference)); // Movement in negative Y direction. initial_state = CatrMotionModel32::State{}; initial_state.at<XY_VELOCITY>() = 1.0F; initial_state.at<XY_ACCELERATION>() = 1.0F; initial_state.at<YAW>() = -0.5F * M_PIf32; expected_state = initial_state; expected_state.at<Y>() -= dt * initial_state.at<XY_VELOCITY>() + 0.5F * dt * dt * initial_state.at<XY_ACCELERATION>(); expected_state.at<XY_VELOCITY>() += dt * initial_state.at<XY_ACCELERATION>(); EXPECT_EQ(expected_state, model.predict(initial_state, time_difference)); // Movement in XY direction. initial_state = CatrMotionModel32::State{}; initial_state.at<XY_VELOCITY>() = 1.0F; initial_state.at<XY_ACCELERATION>() = 1.0F; initial_state.at<YAW>() = 0.25F * M_PIf32; expected_state = initial_state; const auto distance = dt * initial_state.at<XY_VELOCITY>() + 0.5F * dt * dt * initial_state.at<XY_ACCELERATION>(); expected_state.at<X>() += sqrt(0.5F * distance * distance); expected_state.at<Y>() += sqrt(0.5F * distance * distance); expected_state.at<XY_VELOCITY>() += dt * initial_state.at<XY_ACCELERATION>(); EXPECT_EQ(expected_state, model.predict(initial_state, time_difference)); // Movement in negative XY direction. initial_state = CatrMotionModel32::State{}; initial_state.at<XY_VELOCITY>() = 1.0F; initial_state.at<XY_ACCELERATION>() = 1.0F; initial_state.at<YAW>() = -0.75F * M_PIf32; expected_state = initial_state; expected_state.at<X>() -= sqrt(0.5F * distance * distance); expected_state.at<Y>() -= sqrt(0.5F * distance * distance); expected_state.at<XY_VELOCITY>() += dt * initial_state.at<XY_ACCELERATION>(); EXPECT_EQ(expected_state, model.predict(initial_state, time_difference)); } /// @test Predict the linear movement with non-zero turn rate. TEST(CvtrMotionModelTest, PredictLinearMovementWithNonzeroTurnRate) { CvtrMotionModel32 model; CvtrMotionModel32::State initial_state{}; initial_state.at<X>() = 42.0F; initial_state.at<Y>() = 23.0F; initial_state.at<YAW>() = 0.5F; initial_state.at<XY_VELOCITY>() = 2.0F; initial_state.at<YAW_CHANGE_RATE>() = 2.0F; CvtrMotionModel32::State expected_state{initial_state}; // Values computed from a symbolic math derivation. expected_state.at<X>() = 42.1647921486335F; expected_state.at<Y>() = 23.1127403746059F; expected_state.at<YAW>() = 0.7F; EXPECT_EQ(expected_state, model.predict(initial_state, std::chrono::milliseconds{100LL})); } /// @test Predict the linear movement with non-zero turn rate. TEST(CatrMotionModelTest, PredictLinearMovementWithNonzeroTurnRate) { CatrMotionModel32 model; CatrMotionModel32::State initial_state{}; initial_state.at<X>() = 42.0F; initial_state.at<Y>() = 23.0F; initial_state.at<YAW>() = 0.5F; initial_state.at<XY_VELOCITY>() = 2.0F; initial_state.at<YAW_CHANGE_RATE>() = 2.0F; initial_state.at<XY_ACCELERATION>() = 2.0F; CatrMotionModel32::State expected_state{initial_state}; // Values computed from a symbolic math derivation. expected_state.at<X>() = 42.1728437300543F; expected_state.at<Y>() = 23.1186522301942F; expected_state.at<YAW>() = 0.7F; expected_state.at<XY_VELOCITY>() = 2.2F; EXPECT_EQ(expected_state, model.predict(initial_state, std::chrono::milliseconds{100LL})); }
42.819876
96
0.715912
ruvus
e84bd307a0b127644bc42956a19244650e5e8920
3,065
cpp
C++
aws-cpp-sdk-cloudformation/source/model/StackDriftDetectionStatus.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
2
2019-03-11T15:50:55.000Z
2020-02-27T11:40:27.000Z
aws-cpp-sdk-cloudformation/source/model/StackDriftDetectionStatus.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-cloudformation/source/model/StackDriftDetectionStatus.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/cloudformation/model/StackDriftDetectionStatus.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace CloudFormation { namespace Model { namespace StackDriftDetectionStatusMapper { static const int DETECTION_IN_PROGRESS_HASH = HashingUtils::HashString("DETECTION_IN_PROGRESS"); static const int DETECTION_FAILED_HASH = HashingUtils::HashString("DETECTION_FAILED"); static const int DETECTION_COMPLETE_HASH = HashingUtils::HashString("DETECTION_COMPLETE"); StackDriftDetectionStatus GetStackDriftDetectionStatusForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == DETECTION_IN_PROGRESS_HASH) { return StackDriftDetectionStatus::DETECTION_IN_PROGRESS; } else if (hashCode == DETECTION_FAILED_HASH) { return StackDriftDetectionStatus::DETECTION_FAILED; } else if (hashCode == DETECTION_COMPLETE_HASH) { return StackDriftDetectionStatus::DETECTION_COMPLETE; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<StackDriftDetectionStatus>(hashCode); } return StackDriftDetectionStatus::NOT_SET; } Aws::String GetNameForStackDriftDetectionStatus(StackDriftDetectionStatus enumValue) { switch(enumValue) { case StackDriftDetectionStatus::DETECTION_IN_PROGRESS: return "DETECTION_IN_PROGRESS"; case StackDriftDetectionStatus::DETECTION_FAILED: return "DETECTION_FAILED"; case StackDriftDetectionStatus::DETECTION_COMPLETE: return "DETECTION_COMPLETE"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace StackDriftDetectionStatusMapper } // namespace Model } // namespace CloudFormation } // namespace Aws
34.829545
104
0.679935
curiousjgeorge
e84f306d88c484e88a6b89bfcadf2b5bea567ef6
4,540
hpp
C++
inc/phi_BLR.hpp
rchan26/hierarchicalFusion
20cb965526b47ae8f0373bdbdcbdb76d99ab8618
[ "CC-BY-4.0" ]
1
2021-09-27T15:32:50.000Z
2021-09-27T15:32:50.000Z
inc/phi_BLR.hpp
rchan26/hierarchicalFusion
20cb965526b47ae8f0373bdbdcbdb76d99ab8618
[ "CC-BY-4.0" ]
null
null
null
inc/phi_BLR.hpp
rchan26/hierarchicalFusion
20cb965526b47ae8f0373bdbdcbdb76d99ab8618
[ "CC-BY-4.0" ]
1
2021-12-09T03:22:51.000Z
2021-12-09T03:22:51.000Z
#ifndef PHI_BLR #define PHI_BLR #include <RcppArmadillo.h> arma::vec log_BLR_gradient(const arma::vec &beta, const arma::vec &y_labels, const arma::mat &X, const arma::vec &X_beta, const arma::vec &count, const arma::vec &prior_means, const arma::vec &prior_variances, const double &C); arma::mat log_BLR_hessian(const arma::mat &X, const arma::vec &X_beta, const arma::vec &count, const arma::vec &prior_variances, const double &C); Rcpp::List ea_phi_BLR_DL_vec(const arma::vec &beta, const arma::vec &y_labels, const arma::mat &X, const arma::vec &count, const arma::vec &prior_means, const arma::vec &prior_variances, const double &C, const arma::mat &precondition_mat); Rcpp::List ea_phi_BLR_DL_matrix(const arma::mat &beta, const arma::vec &y_labels, const arma::mat &X, const arma::vec &count, const arma::vec &prior_means, const arma::vec &prior_variances, const double &C, const arma::mat &precondition_mat); double spectral_radius_BLR(const arma::vec &beta, const int &dim, const arma::mat &X, const arma::vec &count, const arma::vec &prior_variances, const double &C, const arma::mat &Lambda); Rcpp::List obtain_hypercube_centre_BLR(const Rcpp::List &bessel_layers, const arma::mat &transform_to_X, const arma::vec &y_labels, const arma::mat &X, const arma::vec &count, const arma::vec &prior_means, const arma::vec &prior_variances, const double &C); Rcpp::List spectral_radius_bound_BLR_Z(const int &dim, const arma::mat &V, const arma::mat &X, const arma::vec &count, const arma::vec &prior_variances, const double &C, const arma::mat &sqrt_Lambda); Rcpp::List spectral_radius_global_bound_BLR_Z(const int &dim, const arma::mat &X, const arma::vec &count, const arma::vec &prior_variances, const double &C, const arma::mat &sqrt_Lambda); Rcpp::List ea_phi_BLR_DL_bounds(const arma::vec &beta_hat, const arma::vec &grad_log_hat, const int &dim, const arma::mat &X, const arma::vec &count, const arma::vec &prior_variances, const double &C, const Rcpp::List &transform_mats, const Rcpp::List &hypercube_vertices, const bool &local_bounds); double gamma_NB_BLR(const arma::vec &times, const double &h, const arma::vec &x0, const arma::vec &y, const double &s, const double &t, const arma::vec &y_labels, const arma::mat &X, const arma::vec &count, const arma::vec &prior_means, const arma::vec &prior_variances, const double &C, const arma::mat &precondition_mat); #endif
47.291667
79
0.396035
rchan26
e850145eff970058bfbda746530cd3ee98a51fcd
9,709
cpp
C++
OpenGL_GLFW_Project/GeometryShaderExplosion.cpp
millerf1234/OpenGL_Windows_Projects
26161ba3c820df366a83baaf6e2a275d874c6acd
[ "MIT" ]
null
null
null
OpenGL_GLFW_Project/GeometryShaderExplosion.cpp
millerf1234/OpenGL_Windows_Projects
26161ba3c820df366a83baaf6e2a275d874c6acd
[ "MIT" ]
null
null
null
OpenGL_GLFW_Project/GeometryShaderExplosion.cpp
millerf1234/OpenGL_Windows_Projects
26161ba3c820df366a83baaf6e2a275d874c6acd
[ "MIT" ]
null
null
null
//See header file for details //This file will most likely closely resemble the file "RenderProject1.cpp" #include "GeometryShaderExplosion.h" void GeometryShaderExplosion::initialize() { error = false; window = nullptr; frameNumber = 0ull; frameUnpaused = 0ull; frameOfMostRecentColorRecording = 0ull; counter = 0.0f; zRotation = 0.0f; //Set initial background color backgroundColor = glm::vec3(0.25f, 0.5f, 0.75f); glEnable(GL_PROGRAM_POINT_SIZE); } GeometryShaderExplosion::GeometryShaderExplosion(std::shared_ptr<MonitorData> screenInfo) { initialize(); //Make sure we have a monitor to render to if (!screenInfo || !screenInfo->activeMonitor) { error = true; return; } //Make sure the context is set to this monitor (and this thread [see glfw documentation]) if (glfwGetCurrentContext() != screenInfo->activeMonitor) { std::ostringstream warning; warning << "\nWARNING!\n[In GeometryShaderExplosion's constructor]\n" << "GeometryShaderExplosion detected that the glfw active context was set" << "\nto a different monitor or different execution-thread then\n" << "the one passed to GeometryShaderExplosion's contructor!\n"; warning << "This means that running GeometryShaderExplosion will invalidate\n" << "the previoud context by replacing it with this one, which\n" << "could lead to errors! Please ensure that the correct context is\n" << "being passed to GeometryShaderExplosion in the application code!\n"; fprintf(WRNLOG, warning.str().c_str()); glfwMakeContextCurrent(screenInfo->activeMonitor); } window = screenInfo->activeMonitor; } GeometryShaderExplosion::~GeometryShaderExplosion() { } void GeometryShaderExplosion::run() { if (error) { fprintf(ERRLOG, "An error occured while loading GeometryShaderExplosion\n"); return; } fprintf(MSGLOG, "\nGeometryShaderExplosion demo project has loaded and will begin running!\n"); fprintf(MSGLOG, "\n\tDemo Starting...!\n"); fprintf(MSGLOG, "\nEntering Render Loop...\n"); renderLoop(); } void GeometryShaderExplosion::loadAssets() { loadShaders(); //load the GLSL shader code loadTeapot(); //have the GL context load the Teapot vertices to video memory } void GeometryShaderExplosion::loadShaders() { fprintf(MSGLOG, "\nInitializing Shaders!\n"); sceneShader = std::make_unique<ShaderProgram>(); //There is just 1 pipeline here to build. Here is the pipeline //--------------------------- // (VERTEX STAGE) // Attach a helper shader with just some useful functions fprintf(MSGLOG, "\nAttaching secondary helper vertex shader!\n"); std::unique_ptr<ShaderInterface::VertexShader> vertHelper = std::make_unique<ShaderInterface::VertexShader>("VertMath.vert"); if (!vertHelper) return; vertHelper->makeSecondary(); sceneShader->attachSecondaryVert(vertHelper.get()); //Attach the primary vertex shader fprintf(MSGLOG, "\nAttaching main vertex shader!\n"); sceneShader->attachVert("GeometryShaderExplosion.vert"); //--------------------------- //--------------------------- // (Geometry Stage) // Attach the primary geometry shader to the pipeline. (This is where the explosion happens) fprintf(MSGLOG, "\nAttaching geometry shader!\n"); sceneShader->attachGeom("GeometryShaderExplosion.geom"); //-------------------------- //-------------------------- // (Fragment Stage) // Attach the primary Fragment Shader to the pipeline fprintf(MSGLOG, "\nAttaching fragment shader!\n"); sceneShader->attachFrag("GeometryShaderExplosion.frag"); fprintf(MSGLOG, "\nAttempting to link program!\n"); //--------------------------- // AT THIS POINT, ALL OF THE PIPELINE STAGES HAVE BEEN ATTACHED, SO LINK THE PIPELINE AND CHECK FOR ERRORS sceneShader->link(); if (sceneShader->checkIfLinked()) { fprintf(MSGLOG, "Program Successfully linked!\n"); } else { fprintf(ERRLOG, "Shader Program was not successfully linked!\n"); fprintf(MSGLOG, "\t[Press 'ENTER' to attempt to continue program execution]\n"); std::cin.get(); //Hold the window open if there was an error } } void GeometryShaderExplosion::loadTeapot() { fprintf(MSGLOG, "\nLoading Teapot Vertices\n"); std::vector<GLfloat> teapotVertices; for (int i = 0; i < teapot_count; i++) { teapotVertices.push_back(static_cast<GLfloat>(teapot[i])); } fprintf(MSGLOG, "\nTeapot vertices loaded to application.\n" "Application will now load teapot vertices to video memory on GPU.\n"); //Make a vertex attribute set to handle organizing the data for the graphics context vertexAttributes = std::make_unique<GenericVertexAttributeSet>(1); if (!vertexAttributes) return; vertexAttributes->sendDataToVertexBuffer(0, teapotVertices, 3, 0); fprintf(MSGLOG, "\nTeapot Has Been Successfully Loaded To Video Memory!\n"); } void GeometryShaderExplosion::renderLoop() { while (glfwWindowShouldClose(window) == GLFW_FALSE) { if (checkToSeeIfShouldCloseWindow()) { glfwSetWindowShouldClose(window, GLFW_TRUE); continue; //Skip the rest of this loop iteration to close window quickly } if (checkIfShouldPause()) { pause(); continue; } if (checkIfShouldRecordColor()) recordColorToLog(); if (checkIfShouldReset()) reset(); updateFrameClearColor(); updateUniforms(); drawVerts(); counter += 0.00125f; glfwSwapBuffers(window); glfwPollEvents(); frameNumber++; //Increment the frame counter prepareGLContextForNextFrame(); } } bool GeometryShaderExplosion::checkToSeeIfShouldCloseWindow() const { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) { return true; } return false; } bool GeometryShaderExplosion::checkIfShouldPause() const { if ((frameNumber >= (frameUnpaused + DELAY_LENGTH_OF_PAUSE_CHECKING_AFTER_UNPAUSE)) && (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS)) { return true; } return false; } bool GeometryShaderExplosion::checkIfShouldRecordColor() const { if ((frameNumber >= (frameOfMostRecentColorRecording + DELAY_BETWEEN_SCREEN_COLOR_RECORDINGS_IN_RENDER_PROJECTS)) && (glfwGetKey(window, GLFW_KEY_P) == GLFW_PRESS)) { return true; } return false; } bool GeometryShaderExplosion::checkIfShouldReset() const { if (glfwGetKey(window, GLFW_KEY_R) == GLFW_PRESS) return true; return false; } void GeometryShaderExplosion::pause() { auto begin = std::chrono::high_resolution_clock::now(); //Time measurement auto end = std::chrono::high_resolution_clock::now(); fprintf(MSGLOG, "PAUSED!\n"); while (std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count() < 300000000) { std::this_thread::sleep_for(std::chrono::nanoseconds(2000000)); end = std::chrono::high_resolution_clock::now(); } //Enter an infinite loop checking for the unpaused key to be pressed while (true) { glfwPollEvents(); if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS) { frameUnpaused = frameNumber; fprintf(MSGLOG, "UNPAUSED!\n"); return; } else if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) { glfwSetWindowShouldClose(window, GLFW_TRUE); return; } else { //wait for a little bit before polling again std::this_thread::sleep_for(std::chrono::nanoseconds(3333333)); } } } void GeometryShaderExplosion::recordColorToLog() { frameOfMostRecentColorRecording = frameNumber; int colorDigits = 6; //Digits to print out for each color //Syntax Note: With '%*f', the '*' means that the width will be provided as an additional parameter fprintf(MSGLOG, "\nThe background color of frame %llu is:\n\tRed: %*f,\tGreen: %*f,\tBlue: %*f\n", frameNumber, colorDigits, backgroundColor.r, colorDigits, backgroundColor.g, colorDigits, backgroundColor.b); } void GeometryShaderExplosion::reset() { fprintf(MSGLOG, "\nReseting Demo...\n"); counter = 0.0f; //Reset time to 0 zRotation = 0.0f; //Reset rotation backgroundColor = glm::vec3(0.0f, 0.5f, 0.75f); frameNumber = 0ull; } void GeometryShaderExplosion::updateFrameClearColor() { //To look into: //GL_UseProgram_Stages float * red = &(backgroundColor.x); float * green = &(backgroundColor.y); float * blue = &(backgroundColor.z); *red = glm::min(1.0f, (*red + *green + *blue) / 3.0f); //*green = glm::abs(sin(glm::min(1.0f, (*red) + ((*blue) * (*blue) / (*red))))); *blue = 0.5f + 0.25f*cos(counter); //static bool sleep = false; if (abs(ceilf(counter) - counter) < 0.0049f) { float temp = *red; *red = *green; *green = *blue; *blue = temp; //sleep = true; } glClearColor(*red, *green, *blue, 1.0f); } void GeometryShaderExplosion::updateUniforms() { sceneShader->use(); //Update uniform locations sceneShader->uniforms->updateUniform1f("zoom", 1.0f); sceneShader->uniforms->updateUniform1f("time", counter); //Uniforms for the geometry shader effect sceneShader->uniforms->updateUniform1i("level", 2); //tweak this value as needed sceneShader->uniforms->updateUniform1f("gravity", -9.81f); //tweak this value as needed sceneShader->uniforms->updateUniform1f("velocityScale", 3.0f); //tweak this value as needed zRotation += 0.005f; //fprintf(MSGLOG, "zRot is %f\n", zRotation); //sceneShader->uniforms->updateUniform1f("xRotation", 0.0f); //sceneShader->uniforms->updateUniform1f("yRotation", 0.0f*zRotation * 4.0f); sceneShader->uniforms->updateUniform1f("zRotation", zRotation); } void GeometryShaderExplosion::drawVerts() { if (sceneShader) sceneShader->use(); if (vertexAttributes) vertexAttributes->use(); /*glDrawArrays(GL_TRIANGLES, 0, 3);*/ glDrawArrays(GL_TRIANGLES, 0, teapot_count / 3); } void GeometryShaderExplosion::prepareGLContextForNextFrame() { glBindVertexArray(0); glUseProgram(0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); }
29.782209
126
0.712947
millerf1234
e858c316154a7c9e1f62b57de38d96608393a30b
14,735
cpp
C++
setup.cpp
jessexm/dbgutils
149e5ee1a49ff87861601ea992918d1d56873bc2
[ "BSD-3-Clause" ]
2
2019-12-28T10:33:42.000Z
2020-04-02T01:53:33.000Z
setup.cpp
jessexm/dbgutils
149e5ee1a49ff87861601ea992918d1d56873bc2
[ "BSD-3-Clause" ]
null
null
null
setup.cpp
jessexm/dbgutils
149e5ee1a49ff87861601ea992918d1d56873bc2
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (C) 2002, 2003, 2004 Zilog, Inc. * * $Id: setup.cpp,v 1.6 2005/10/20 18:39:37 jnekl Exp $ * * This file initializes the debugger enviroment by reading * settings from a config file and by parsing command-line * options. */ #include <string.h> #include <stdio.h> #include <assert.h> #include <sys/stat.h> #include <readline/readline.h> #include <readline/history.h> #include "xmalloc.h" #include "ez8dbg.h" #include "ocd_serial.h" #include "ocd_parport.h" #include "ocd_tcpip.h" #include "server.h" #include "cfg.h" #include "md5.h" /**************************************************************/ #ifndef CFGFILE #define CFGFILE "ez8mon.cfg" #endif #ifndef _WIN32 #define DIRSEP '/' #else #define DIRSEP '\\' #endif /**************************************************************/ const char *serialports[] = #if (!defined _WIN32) && (defined __sun__) /* solaris */ { "/dev/ttya", "/dev/ttyb", NULL }; #elif (!defined _WIN32) /* linux */ { "/dev/ttyS0", "/dev/ttyS1", "/dev/ttyS2", "/dev/ttyS3", NULL }; #else /* windows */ { "com1", "com2", "com3", "com4", NULL }; #endif char *progname; int verbose; /**************************************************************/ #define str(x) _str(x) #define _str(x) #x #ifndef DEFAULT_CONNECTION #define DEFAULT_CONNECTION serial #endif #ifndef DEFAULT_DEVICE #define DEFAULT_DEVICE auto #endif #ifndef DEFAULT_BAUDRATE #define DEFAULT_BAUDRATE 57600 #endif #ifndef ALT_BAUDRATE #define ALT_BAUDRATE 4800 #endif #ifndef DEFAULT_MTU #define DEFAULT_MTU 4096 #endif #ifndef DEFAULT_SYSCLK #define DEFAULT_SYSCLK 20MHz #endif /************************************************************** * Our debugger object. */ static ez8dbg _ez8; ez8dbg *ez8 = &_ez8; /**************************************************************/ rl_command_func_t *tab_function = rl_insert; static char *connection = NULL; static char *device = NULL; static char *baudrate = NULL; static char *sysclk = NULL; static char *mtu = NULL; static char *server = NULL; static FILE *log_proto = NULL; static int invoke_server = 0; static int disable_cache = 0; static int unlock_ocd = 0; int repeat = 0x40; int show_times = 0; int esc_key = 0; int testmenu = 0; char *tcl_script = NULL; /* option values to load upon reset */ struct option_t { uint8_t addr; uint8_t value; struct option_t *next; } *options = NULL; /************************************************************** * The ESC key is bound to this function. * * This function will terminate any readline call. It is * used to abort a command. */ int esc_function(int count, int key) { esc_key = 1; rl_done = 1; return 0; } /************************************************************** * This initializes the readline library. */ int readline_init(void) { int err; err = rl_bind_key(ESC, esc_function); if(err) { return -1; } err = rl_bind_key('\t', *tab_function); if(err) { return -1; } return 0; } /************************************************************** * This will search for a config file. * * It will first look in the current directory. If it doesn't * find one there, it will then look in the directory pointed * to by the HOME environment variable. */ cfgfile *find_cfgfile(void) { char *filename, *home, *ptr; struct stat mystat; cfgfile *cfg; if(stat(CFGFILE, &mystat) == 0) { cfg = new cfgfile(); cfg->open(CFGFILE); return cfg; } home = getenv("HOME"); if(!home) { return NULL; } filename = (char *)xmalloc(strlen(home) + 1 + sizeof(CFGFILE)); strcpy(filename, home); ptr = strchr(filename, '\0'); *ptr++ = DIRSEP; *ptr = '\0'; strcat(filename, CFGFILE); if(stat(filename, &mystat) == 0) { cfg = new cfgfile(); cfg->open(filename); free(filename); return cfg; } free(filename); return NULL; } /************************************************************** * This function will get parameters from the config file. */ int load_config(void) { char *ptr; cfgfile *cfg; cfg = find_cfgfile(); if(!cfg) { return 1; } ptr = cfg->get("connection"); if(ptr) { connection = xstrdup(ptr); } ptr = cfg->get("device"); if(ptr) { device = xstrdup(ptr); } ptr = cfg->get("baudrate"); if(ptr) { baudrate = xstrdup(ptr); } ptr = cfg->get("mtu"); if(ptr) { mtu = xstrdup(ptr); } ptr = cfg->get("clock"); if(ptr) { sysclk = xstrdup(ptr); } ptr = cfg->get("server"); if(ptr) { server = xstrdup(ptr); invoke_server = 1; } ptr = cfg->get("cache"); if(ptr) { if(!strcasecmp(ptr, "disabled")) { disable_cache = 1; } } ptr = cfg->get("testmenu"); if(ptr) { if(!strcasecmp(ptr, "enabled")) { testmenu = 1; } } ptr = cfg->get("repeat"); if(ptr) { char *tail; repeat = strtol(ptr, &tail, 0); if(!tail || *tail || tail == ptr) { fprintf(stderr, "Invalid repeat = %s\n", ptr); return -1; } } delete cfg; return 0; } /************************************************************** * display_md5hash() * * This routine computes and displays the md5 hash of a text * string. This is useful for generating password hashes. */ void display_md5hash(char *s) { int i; uint8_t hash[16]; MD5_CTX context; assert(s != NULL); MD5Init(&context); MD5Update(&context, (unsigned char *)s, strlen(s)); MD5Final(hash, &context); printf("text = %s\n", s); printf("md5hash = "); for(i=0; i<16; i++) { printf("%02x", hash[i]); } printf("\n"); return; } /************************************************************** * usage() * * This function displays command-line usage info. */ void usage(void) { extern char *build; printf("%s - build %s\n", progname, build); printf("Usage: %s [OPTIONS]\n", progname); printf("Z8 Encore! command line debugger.\n\n"); printf(" -h show this help\n"); printf(" -p DEVICE connect to specified serial port device\n"); printf(" -b BAUDRATE connect using specified baudrate\n"); printf(" -l list valid baudrates\n"); printf(" -t MTU set maximum packet size\n"); printf(" (used to prevent receive overrun errors)\n"); printf(" -c FREQUENCY use specified clock frequency for flash\n"); printf(" program/erase oprations\n"); printf(" -s [:PORT] run as tcp/ip server\n"); printf(" -n [SERVER][:PORT] connect to tcp/ip server\n"); printf(" -m TEXT calculate and display md5hash of text\n"); printf(" -d dump raw ocd communication\n"); printf(" -D disable memory cache\n"); printf(" -T display diagnostic run times\n"); printf(" -S SCRIPT run tcl script\n"); printf(" -u issue OCD unlock sequence for 8-pin device\n"); printf("\n"); return; } /************************************************************** * parse_options() * * This routine handles command line options. */ void parse_options(int argc, char **argv) { int c; const struct baudvalue *b; char *s; progname = *argv; s = strrchr(progname, '/'); if(s) { progname = s+1; } s = strrchr(progname, '\\'); if(s) { progname = s+1; } while((c = getopt(argc, argv, "hldDTp:b:t:c:snm:vS:u")) != EOF) { switch(c) { case '?': printf("Try '%s -h' for more information.\n", progname); exit(EXIT_FAILURE); break; case 'h': usage(); exit(EXIT_SUCCESS); break; case 'l': b = baudrates; while(b->value) { printf("%d\n", b->value); b++; } exit(EXIT_SUCCESS); break; case 'p': connection = xstrdup("serial"); if(device) { free(device); } device = xstrdup(optarg); break; case 'b': if(baudrate) { free(baudrate); } baudrate = xstrdup(optarg); break; case 't': if(mtu) { free(mtu); } mtu = xstrdup(optarg); break; case 'c': if(sysclk) { free(sysclk); } sysclk = xstrdup(optarg); break; case 's': invoke_server = 1; break; case 'n': connection = xstrdup("tcpip"); if(device) { free(device); device = NULL; } break; case 'd': log_proto = stdout; break; case 'D': disable_cache = 1; break; case 'T': show_times = 1; break; case 'm': display_md5hash(optarg); exit(EXIT_SUCCESS); break; case 'v': verbose++; break; case 'S': tcl_script = optarg; break; case 'u': unlock_ocd = 1; break; default: abort(); } } if(invoke_server) { if(optind + 1 == argc) { if(server) { free(server); } server = xstrdup(argv[optind]); } optind++; } if(connection && !strcasecmp(connection, "tcpip")) { if(optind + 1 == argc) { if(device) { free(device); } device = xstrdup(argv[optind]); } optind++; } if(!tcl_script && optind < argc) { printf("%s: too many arguments.\n", progname); printf("Try '%s -h' for more information.\n", progname); exit(EXIT_FAILURE); } return; } /************************************************************** * connect() * * This routine will connect to the on-chip debugger using * the configured interface. */ int connect(void) { int i, value, clk, baud; char *tail; double clock; if(log_proto) { ez8->log_proto = log_proto; } if(mtu) { value = strtol(mtu, &tail, 0); if(!tail || *tail || tail == mtu) { fprintf(stderr, "Invalid mtu \"%s\"\n", mtu); return -1; } ez8->mtu = value; } if(sysclk) { clock = strtod(sysclk, &tail); if(tail == NULL || tail == sysclk) { fprintf(stderr, "Invalid clock \"%s\"\n", sysclk); return -1; } while(*tail && strchr(" \t", *tail)) { tail++; } if(*tail == 'k' || *tail == 'K') { clock *= 1000; tail++; } else if(*tail == 'M') { clock *= 1000000; tail++; } if(*tail != '\0' && strcasecmp(tail, "Hz")) { fprintf(stderr, "Invalid clock suffix \"%s\"\n", tail); return -1; } } else { fprintf(stderr, "Unknown system clock.\n"); return -1; } clk = (int)clock; if(clk < 32000 || clk > 20000000) { fprintf(stderr, "Clock %d out of range\n", clk); return -1; } ez8->set_sysclk(clk); if(disable_cache) { ez8->memcache_enabled = 0; } if(connection == NULL) { fprintf(stderr, "Unknown connection type.\n"); return -1; } else if(!strcasecmp(connection, "serial")) { if(!device) { fprintf(stderr, "Unknown communication device.\n"); return -1; } if(!baudrate) { baud = DEFAULT_BAUDRATE; } else { baud = strtol(baudrate, &tail, 0); if(!tail || *tail || tail == baudrate) { fprintf(stderr, "Invalid baudrate \"%s\"\n", baudrate); return -1; } } if(!strcasecmp(device, "auto")) { bool found = 0; printf("Auto-searching for device ...\n"); for(i=0; serialports[i]; i++) { device = xstrdup(serialports[i]); printf("Trying %s ... ", device); fflush(stdout); try { ez8->connect_serial(device, baud, unlock_ocd); } catch(char *err) { printf("fail\n"); continue; } try { ez8->reset_link(); } catch(char *err) { printf("timeout\n"); ez8->disconnect(); continue; } printf("ok\n"); found = 1; break; } if(!found) { printf( "Could not find dongle during autosearch.\n"); return -1; } try { ez8->rd_revid(); } catch(char *err) { baud = ALT_BAUDRATE; ez8->set_baudrate(baud); ez8->reset_link(); try { ez8->rd_revid(); } catch(char *err) { printf( "Found dongle, but did not receive response from device.\n"); return -1; } } if(ez8->cached_reload() && ez8->cached_sysclk() > 115200*8) { baud = 115200; ez8->set_baudrate(baud); ez8->reset_link(); } } else { try { ez8->connect_serial(device, baud, unlock_ocd); } catch(char *err) { fprintf(stderr, "%s", err); return -1; } try { ez8->reset_link(); } catch(char *err) { printf("Failed connecting to %s\n", device); fprintf(stderr, "%s", err); ez8->disconnect(); return -1; } } printf("Connected to %s @ %d\n", device, baud); } else if(!strcasecmp(connection, "parport")) { if(!device) { fprintf(stderr, "Unknown device"); return -1; } try { ez8->connect_parport(device); } catch(char *err) { printf("Parallel port connection failed\n"); fprintf(stderr, "%s", err); return -1; } try { ez8->reset_link(); } catch(char *err) { printf("IEEE1284 negotiation failed\n"); fprintf(stderr, "%s", err); ez8->disconnect(); return -1; } } else if(!strcasecmp(connection, "tcpip")) { try { ez8->connect_tcpip(device); } catch(char *err) { printf("Connection failed\n"); fprintf(stderr, "%s", err); return -1; } try { ez8->reset_link(); } catch(char *err) { printf("Remote reset failed\n"); fprintf(stderr, "%s", err); ez8->disconnect(); return -1; } } else { printf("Invalid connection type \"%s\"\n", connection); return -1; } return 0; } /************************************************************** * init() * * This routine sets up and connects to the on-chip debugger. */ int init(int argc, char **argv) { int err; tab_function = rl_insert; rl_startup_hook = readline_init; connection = xstrdup(str(DEFAULT_CONNECTION)); device = xstrdup(str(DEFAULT_DEVICE)); baudrate = xstrdup(str(DEFAULT_BAUDRATE)); sysclk = xstrdup(str(DEFAULT_SYSCLK)); mtu = xstrdup(str(DEFAULT_MTU)); err = load_config(); if(err < 0) { return -1; } parse_options(argc, argv); err = connect(); if(err) { return -1; } if(invoke_server) { err = run_server(ez8->iflink(), server); ez8->disconnect(); if(err) { exit(EXIT_FAILURE); } else { exit(EXIT_SUCCESS); } } #ifdef TEST try { extern void check_config(void); check_config(); } catch(char *err) { fprintf(stderr, "%s", err); return -1; } #endif try { ez8->stop(); } catch(char *err) { fprintf(stderr, "%s", err); return -1; } return 0; } /************************************************************** * finish() * * This does the opposite of init(), it terminates a * connection. It will remove any breakpoints that are * set and put the part into "run" mode when finished. */ int finish(void) { try { int addr; while(ez8->get_num_breakpoints() > 0) { addr = ez8->get_breakpoint(0); ez8->remove_breakpoint(addr); } ez8->run(); ez8->disconnect(); } catch(char *err) { fprintf(stderr, "%s", err); return -1; } return 0; } /**************************************************************/
19.111543
84
0.55134
jessexm
e8591699457d2855917c3569dd261352061e7df4
4,730
hpp
C++
inc/Matrixes.hpp
KPO-2020-2021/zad5_2-delipl
b4bd2e673c8b7e92e85aed10919427a6704353ca
[ "Unlicense" ]
1
2022-03-08T03:16:48.000Z
2022-03-08T03:16:48.000Z
inc/Matrixes.hpp
KPO-2020-2021/zad5_2-delipl
b4bd2e673c8b7e92e85aed10919427a6704353ca
[ "Unlicense" ]
null
null
null
inc/Matrixes.hpp
KPO-2020-2021/zad5_2-delipl
b4bd2e673c8b7e92e85aed10919427a6704353ca
[ "Unlicense" ]
null
null
null
/** * @file Matrixes.hpp * @author Delicat Jakub ([email protected]) * @brief File describes implemetations for template class Matrix. * Instantiation of template class Matrix like Matrix4x4, Matrix3x3, Matrix2x2 and MatrixRot. * @version 0.1 * @date 2021-06-23 * * @copyright Copyright (c) 2021 * */ #ifndef __MATRIXROT_H__ #define __MATRIXROT_H__ #include "Vectors.hpp" #include "Matrix.hpp" /** * @file */ #ifndef MIN_DIFF /** * @brief Minimal difference between two double numbers. It might be included from config.hpp */ #define MIN_DIFF 0.000000001 #endif // !MIN_DIFF /** * @brief Square Matrix with double values and comare with MIN_DIFF * @tparam dim */ template<std::size_t dim> class dMatrixSqr: public Matrix<double, dim, dim>{ public: /** * @brief Construct a new d Matrix Sqr object */ dMatrixSqr(): Matrix<double, dim, dim>() {} /** * @brief Construct a new d Matrix Sqr object * @param list of inserted values */ dMatrixSqr(const std::initializer_list<Vector<double, dim>> &list): Matrix<double, dim, dim>(list) {} /** * @brief Construct a new d Matrix Sqr object * @param M copied Matrix */ dMatrixSqr(const Matrix<double, dim, dim> &M): Matrix<double, dim, dim>(M){} /** * @brief Checks if every diffrence is bigger than MIN_DIFF * @param v compared dMatrixSqe * @return true if is lower * @return false if is bigger */ bool operator==(const dMatrixSqr &v) const{ for (std::size_t i = 0; i < dim; ++i) for (std::size_t j = 0; j < dim; ++j) if (abs(this->vector[i][j] - v[i][j]) > MIN_DIFF) return false; return true; } /** * @brief Checks if every diffrence is bigger than MIN_DIFF * @param v compared dMatrixSqe * @return true if is bigger * @return false if is less */ bool operator!=(const dMatrixSqr &v) const{ for (std::size_t i = 0; i < dim; ++i) for (std::size_t j = 0; j < dim; ++j) if (abs(this->vector[i][j] - v[i][j]) <= MIN_DIFF) return false; return true; } /** * @brief Checks if every value is lower than MIN_DIFF * @param v compared dMatrixSqe * @return true if is lower * @return false if is bigger */ bool operator!() const{ for (std::size_t i = 0; i < dim; ++i) for (std::size_t j = 0; j < dim; ++j) if (abs(this->vector[i][j]) >= MIN_DIFF) return false; return true; } }; /** * @brief four dimentional square double Matrix */ typedef dMatrixSqr<4> Matrix4x4; /** * @brief three dimentional square double Matrix */ typedef dMatrixSqr<3> Matrix3x3; /** * @brief two dimentional square double Matrix */ typedef dMatrixSqr<2> Matrix2x2; class MatrixRot: public Matrix3x3{ public: /** * @brief Construct a new Matrix Rot object and fill like unit Matrix */ MatrixRot(); /** * @brief Construct a new Matrix Rot object and copy * @param M Copieied Matrix */ MatrixRot(const Matrix3x3 &M): Matrix3x3(M){} /** * @brief Construct a new Matrix Rot object and copy * @param M Copieied Matrix */ MatrixRot(const Matrix<double, 3, 3> &M): Matrix3x3(M){} /** * @brief Construct a new Matrix Rot object and fill with rotating values * @param angle angle of rotation * @param axis of rotation ex. \p VectorZ , \p VectorX , \p VectorY */ MatrixRot(double angle, const Vector3 &axis); }; /** * @brief Transform Matrix 4x4 which collects translation, rotation and scale */ class MatrixTransform: public Matrix4x4{ public: /** * @brief Construct a new MatrixTransform object and fill like unit Matrix */ MatrixTransform(); /** * @brief Construct a new MatrixTransform object and copy * @param M Copieied Matrix */ MatrixTransform(const Matrix4x4 &M) : Matrix4x4(M) {} /** * @brief Construct a new Matrix Transform object * @param translate translate Vector3 to move bodies * @param angles Vector3 of 3 angles in 3 axis * @param scale Vector3 of scale in every dimention */ MatrixTransform(const Vector3 &translate, const Vector3 &angles, const Vector3 &scale); }; #endif // __MATRIXROT_H__
29.018405
109
0.572939
KPO-2020-2021
e85abaf9084edff95cf3b43144191390184028c3
142
cpp
C++
src/Debug.cpp
JurisPolevskis/PolygonFinder
dd09a89c246f959071ebb1148c2cbe38cdc60edb
[ "Unlicense" ]
null
null
null
src/Debug.cpp
JurisPolevskis/PolygonFinder
dd09a89c246f959071ebb1148c2cbe38cdc60edb
[ "Unlicense" ]
null
null
null
src/Debug.cpp
JurisPolevskis/PolygonFinder
dd09a89c246f959071ebb1148c2cbe38cdc60edb
[ "Unlicense" ]
null
null
null
#include "Debug.h" #include <iostream> void Debug::print(const std::string& str) { #ifdef DEBUG std::cout << str << std::endl; #endif }
14.2
42
0.640845
JurisPolevskis
e85d05c1eddad62c9ec79e5d962f64270864c35e
820
cpp
C++
jobtaskitem.cpp
dayuanyuan1989/RemoteBinder
6c07896828187bbb890115fa1326f9db4fbd7b68
[ "MIT" ]
null
null
null
jobtaskitem.cpp
dayuanyuan1989/RemoteBinder
6c07896828187bbb890115fa1326f9db4fbd7b68
[ "MIT" ]
null
null
null
jobtaskitem.cpp
dayuanyuan1989/RemoteBinder
6c07896828187bbb890115fa1326f9db4fbd7b68
[ "MIT" ]
null
null
null
#include "jobtaskitem.h" #include "ui_jobtaskitem.h" JobTaskItem::JobTaskItem(QWidget *parent) : QWidget(parent), ui(new Ui::JobTaskItem) { ui->setupUi(this); // SetBodyVisible(false); } JobTaskItem::~JobTaskItem() { delete ui; } void JobTaskItem::SetTitle(const QString& str) { ui->title->setText(str); } void JobTaskItem::SetSizeValue(const QString& str) { ui->size->setText(str); } void JobTaskItem::SetQualityValue(const QString& str) { ui->quality->setText(str); } void JobTaskItem::SetBodyVisible(bool visible) { if(visible) { resize(width(), JOB_ITEM_TOTAL_HEIGHT); } else { resize(width(), JOB_ITEM_HEAD_HEIGHT); } } bool JobTaskItem::BodyVisible() { return (height() != JOB_ITEM_HEAD_HEIGHT); }
17.826087
54
0.634146
dayuanyuan1989
e8628b6b7b6a594051ce4cfd1f1c842b4ca0866c
12,960
cpp
C++
copyworker.cpp
haraki/farman
9aab8cfdd3f9d98f3be8dfddd6bad8451ea27297
[ "MIT" ]
5
2018-08-19T05:45:45.000Z
2020-10-09T09:37:57.000Z
copyworker.cpp
haraki/farman
9aab8cfdd3f9d98f3be8dfddd6bad8451ea27297
[ "MIT" ]
95
2018-04-26T12:13:24.000Z
2020-05-03T08:23:56.000Z
copyworker.cpp
haraki/farman
9aab8cfdd3f9d98f3be8dfddd6bad8451ea27297
[ "MIT" ]
1
2018-08-19T05:46:02.000Z
2018-08-19T05:46:02.000Z
#include <QDebug> #include <QFileInfo> #include <QDir> #include <QFile> #include <QTemporaryFile> #include <QDateTime> #include <QMutex> #include <QThread> #include "copyworker.h" #include "workerresult.h" #include "default_settings.h" namespace Farman { CopyWorker::CopyWorker(const QStringList& srcPaths, const QString& dstPath, bool moveMode, qint64 unitSize, QObject *parent) : Worker(parent) , m_srcPaths(srcPaths) , m_dstPath(dstPath) , m_moveMode(moveMode) , m_methodType(DEFAULT_OVERWRITE_METHOD_TYPE) , m_methodTypeKeep(false) , m_renameFileName("") , m_copyUnitSize(unitSize) { } CopyWorker::~CopyWorker() { } void CopyWorker::run() { qDebug() << "start CopyWorker::run()"; m_timer.start(); QString prepareStr = (m_moveMode) ? tr("Preparing move...") : tr("Preparing copy..."); QString prepareAbortStr = (m_moveMode) ? tr("Preparing move...aborted.") : tr("Preparing copy...aborted."); QString prepareFailedStr = (m_moveMode) ? tr("Preparing move...failed.") : tr("Preparing copy...failed."); emitProcess(prepareStr); QMap<QString, QString> copyList; QList<QString> removeDirList; // コピーするファイル・ディレクトリのリストを作成 for(auto srcPath : m_srcPaths) { if(isAborted()) { //emitOutputConsole(tr("Aborted.\n")); // makeList() 内部でコンソール出力しているので、ここではコンソール出力しない emitProcess(prepareAbortStr); emitFinished(static_cast<int>(WorkerResult::Abort)); return; } int ret = makeList(srcPath, m_dstPath, copyList, removeDirList); if(isError(ret)) { qDebug() << "makeList() : ret =" << QString("%1").arg(ret, 0, 16); emitProcess(prepareFailedStr); emitFinished(ret); return; } } emitStart(0, copyList.size()); QString preStr = (m_moveMode) ? tr("%1 file(s) move...") : tr("%1 file(s) copy..."); QString postStr = (m_moveMode) ? tr("%1 file(s) move...done.") : tr("%1 file(s) copy...done."); QString abortStr = (m_moveMode) ? tr("%1 file(s) move...aborted.") : tr("%1 file(s) copy...aborted."); QString failedStr = (m_moveMode) ? tr("%1 file(s) move...failed.") : tr("%1 file(s) copy...failed."); int progress = 0; for(QMap<QString, QString>::const_iterator itr = copyList.cbegin();itr != copyList.cend();itr++) { thread()->msleep(1); // sleep を入れないと Abort できない場合がある emitProcess(QString(preStr).arg(progress + 1)); int ret = copyExec(itr.key(), itr.value()); if(isAborted()) { //emitOutputConsole(tr("Aborted.\n")); // copyExec() 内部でコンソール出力しているので、ここではコンソール出力しない emitProcess(QString(abortStr).arg(progress + 1)); emitFinished(static_cast<int>(WorkerResult::Abort)); return; } if(isError(ret)) { qDebug() << "copyExec() : ret =" << QString("%1").arg(ret, 0, 16); emitProcess(QString(failedStr).arg(progress + 1)); emitFinished(ret); return; } emitProcess(QString(postStr).arg(progress + 1)); progress++; emitProgress(progress); } if(m_moveMode) { // ディレクトリ削除 for(auto dirPath : removeDirList) { qDebug() << "remove dir :" << dirPath; if(!QDir().rmdir(dirPath)) { // 移動元のディレクトリ削除失敗 qDebug() << "remove dir error :" << dirPath; emitProcess(QString(tr("remove %1 folder failed.")).arg(dirPath)); emitFinished(static_cast<int>(WorkerResult::ErrorRemoveDir)); return; } } } emitOutputConsole(QString("Total time : %L1 ms.\n").arg(m_timer.elapsed())); qDebug() << "finish CopyWorker::run()"; emitFinished(static_cast<int>(WorkerResult::Success)); } int CopyWorker::makeList(const QString& srcPath, const QString& dstDirPath, QMap<QString, QString>& copyList, QList<QString>& removeDirList) { if(isAborted()) { emitOutputConsole(tr("Aborted.\n")); return static_cast<int>(WorkerResult::Abort); } QFileInfo srcFileInfo(srcPath); QDir dstDir(dstDirPath); QString dstPath = dstDir.absoluteFilePath(srcFileInfo.fileName()); QFileInfo dstFileInfo(dstPath); copyList.insert(srcFileInfo.absoluteFilePath(), dstFileInfo.absoluteFilePath()); qDebug() << srcFileInfo.absoluteFilePath() << ">>" << dstFileInfo.absoluteFilePath(); if(srcFileInfo.isDir()) { // 再帰処理でコピー元ディレクトリ内のエントリをリストに追加する QDir srcDir(srcPath); QFileInfoList srcChildFileInfoList = srcDir.entryInfoList(QDir::AllEntries | QDir::AccessMask | QDir::AllDirs | QDir::NoDotAndDotDot, QDir::DirsFirst); for(auto srcChildFileInfo : srcChildFileInfoList) { int ret = makeList(srcChildFileInfo.absoluteFilePath(), dstFileInfo.absoluteFilePath(), copyList, removeDirList); if(ret == static_cast<int>(WorkerResult::Abort) || isError(ret)) { return ret; } } if(m_moveMode) { // 最後にディレクトリをまとめて削除するためのリストを作成 removeDirList.push_back(srcFileInfo.absoluteFilePath()); } } return static_cast<int>(WorkerResult::Success); } int CopyWorker::copyExec(const QString& srcPath, const QString& dstPath) { if(isAborted()) { emitOutputConsole(tr("Aborted.\n")); return static_cast<int>(WorkerResult::Abort); } QFileInfo srcFileInfo(srcPath); QFileInfo dstFileInfo(dstPath); emitOutputConsole(QString("%1 >> %2 ... ").arg(srcFileInfo.absoluteFilePath()).arg(dstFileInfo.absoluteFilePath())); qDebug() << srcFileInfo.absoluteFilePath() << ">>" << dstFileInfo.absoluteFilePath(); if(srcFileInfo.isDir()) { // ディレクトリの場合はコピー先にディレクトリを作成する if(dstFileInfo.exists()) { emitOutputConsole(tr("is exists.\n")); } else { QDir dstDir(dstPath); if(!dstDir.mkdir(dstPath)) { // ディレクトリ作成失敗 emitOutputConsole(tr("Failed make directory.\n")); return static_cast<int>(WorkerResult::ErrorMakeDir); } emitOutputConsole(tr("Made directory.\n")); qDebug() << "succeed mkdir(" << dstPath << ")"; } } else { // ファイル while(dstFileInfo.exists()) { // コピー先にファイルが存在している m_renameFileName = ""; if(!m_methodTypeKeep || m_methodType == OverwriteMethodType::Rename) { showConfirmOverwrite(srcFileInfo.absoluteFilePath(), dstFileInfo.absoluteFilePath(), m_methodType); if(isAborted()) { // 中断 emitOutputConsole(tr("Aborted.\n")); return static_cast<int>(WorkerResult::Abort); } } if(m_methodType == OverwriteMethodType::Overwrite) { if(!QFile::remove(dstFileInfo.absoluteFilePath())) { emitOutputConsole((m_moveMode) ? tr("Failed move.\n") : tr("Failed copy.\n")); return static_cast<int>(WorkerResult::ErrorRemoveFile); } break; } else if(m_methodType == OverwriteMethodType::OverwriteIfNewer) { if(srcFileInfo.lastModified() <= dstFileInfo.lastModified()) { emitOutputConsole(tr("Skipped.\n")); return static_cast<int>(WorkerResult::Skip); } if(!QFile::remove(dstFileInfo.absoluteFilePath())) { emitOutputConsole((m_moveMode) ? tr("Failed move.\n") : tr("Failed copy.\n")); return static_cast<int>(WorkerResult::ErrorRemoveFile); } break; } else if(m_methodType == OverwriteMethodType::Skip) { emitOutputConsole(tr("Skipped.\n")); return static_cast<int>(WorkerResult::Skip); } else if(m_methodType == OverwriteMethodType::Rename) { dstFileInfo.setFile(dstFileInfo.absolutePath(), m_renameFileName); } else { // ここにくることはありえないはず emitOutputConsole(tr("Fatal error.\n")); return static_cast<int>(WorkerResult::ErrorFatal); } } int result = copy(srcFileInfo.absoluteFilePath(), dstFileInfo.absoluteFilePath()); if(result == static_cast<int>(WorkerResult::Abort)) { emitOutputConsole(tr("Aborted.\n")); return static_cast<int>(WorkerResult::Abort); } else if(isError(result)) { // コピー失敗 emitOutputConsole((m_moveMode) ? tr("Failed move.\n") : tr("Failed copy.\n")); return static_cast<int>(WorkerResult::ErrorCopyFile); } if(m_moveMode) { qDebug() << "remove file : " << srcFileInfo.absoluteFilePath(); if(!QFile::remove(srcFileInfo.absoluteFilePath())) { // 移動元のファイル削除失敗 emitOutputConsole(tr("Failed move.\n")); return static_cast<int>(WorkerResult::ErrorRemoveFile); } } emitOutputConsole((m_moveMode) ? tr("Moved\n") : tr("Copied\n")); } return static_cast<int>(WorkerResult::Success); } void CopyWorker::showConfirmOverwrite(const QString& srcFilePath, const QString& dstFilePath, OverwriteMethodType methodType) { emitConfirmOverwrite(srcFilePath, dstFilePath, methodType); m_timer.invalidate(); QMutex mutex; { QMutexLocker locker(&mutex); m_confirmWait.wait(&mutex); } m_timer.restart(); } void CopyWorker::emitConfirmOverwrite(const QString& srcFilePath, const QString& dstFilePath, OverwriteMethodType methodType) { emit confirmOverwrite(srcFilePath, dstFilePath, static_cast<int>(methodType)); } void CopyWorker::finishConfirmOverwrite(OverwriteMethodType methodType, bool methodTypeKeep, const QString& renameFileName) { m_methodType = methodType; m_methodTypeKeep = methodTypeKeep; m_renameFileName = renameFileName; m_confirmWait.wakeAll(); } void CopyWorker::cancelConfirmOverwrite() { abort(); m_confirmWait.wakeAll(); } void CopyWorker::emitStartSub(qint64 min, qint64 max) { emit startSub(min, max); } void CopyWorker::emitProgressSub(qint64 value) { emit progressSub(value); } int CopyWorker::copy(const QString& srcPath, const QString& dstPath) { qDebug() << "CopyWorker::copy() : " << srcPath << " >> " << dstPath; QFile srcFile(srcPath); if(!srcFile.open(QIODevice::ReadOnly)) { return static_cast<int>(WorkerResult::ErrorCopyFile); } QTemporaryFile dstFile(QString(QLatin1String("%1/temp.XXXXXX")).arg(QFileInfo(dstPath).path())); if(!dstFile.open()) { srcFile.close(); return static_cast<int>(WorkerResult::ErrorCopyFile); } QByteArray buffer; WorkerResult result = WorkerResult::Success; qint64 remineSize = srcFile.size(); qint64 totalSize = 0; emitStartSub(0, remineSize); while(!srcFile.atEnd()) { thread()->msleep(1); // sleep を入れないと Abort できない場合がある if(isAborted()) { result = WorkerResult::Abort; break; } qint64 readSize = (remineSize > m_copyUnitSize) ? m_copyUnitSize : remineSize; buffer = srcFile.read(readSize); if(buffer.size() < readSize) { result = WorkerResult::ErrorCopyFile; break; } qint64 wroteSize = dstFile.write(buffer); if(wroteSize < readSize) { result = WorkerResult::ErrorCopyFile; break; } remineSize -= readSize; totalSize += readSize; emitProgressSub(totalSize); } if(result == WorkerResult::Success) { dstFile.rename(dstPath); dstFile.setAutoRemove(false); if(!dstFile.setPermissions(srcFile.permissions())) { qDebug() << "set permissons error!! : " << dstPath; result = WorkerResult::ErrorCopyFile; } } srcFile.close(); dstFile.close(); return static_cast<int>(result); } } // namespace Farman
29.930716
140
0.568519
haraki
e86580daa5ca80d60608bb645e9f4c1a64d95dbb
723
cpp
C++
Baekjoon/1864.cpp
Twinparadox/AlgorithmProblem
0190d17555306600cfd439ad5d02a77e663c9a4e
[ "MIT" ]
null
null
null
Baekjoon/1864.cpp
Twinparadox/AlgorithmProblem
0190d17555306600cfd439ad5d02a77e663c9a4e
[ "MIT" ]
null
null
null
Baekjoon/1864.cpp
Twinparadox/AlgorithmProblem
0190d17555306600cfd439ad5d02a77e663c9a4e
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <math.h> using namespace std; int main(void) { while (1) { int len; long long ans = 0; string str; cin >> str; if (str == "#") break; len = str.length(); for (int i = 1; i <= len; i++) { int tmp; switch (str[i - 1]) { case '-': tmp = 0; break; case '\\': tmp = 1; break; case '(': tmp = 2; break; case '@': tmp = 3; break; case '?': tmp = 4; break; case '>': tmp = 5; break; case '&': tmp = 6; break; case '%': tmp = 7; break; case '/': tmp = -1; break; default: break; } ans += tmp * pow(8, len - i); } cout << ans << '\n'; } }
12.910714
32
0.428769
Twinparadox
e866fc219c43821e3401ee5cd626dd689ced361e
419
cpp
C++
ShaderGLTest/DeviceTest.cpp
EPAC-Saxon/environment-map-JuliePreperier
cd024b83236af8cffa2262cad988b43b2f725dcb
[ "MIT" ]
null
null
null
ShaderGLTest/DeviceTest.cpp
EPAC-Saxon/environment-map-JuliePreperier
cd024b83236af8cffa2262cad988b43b2f725dcb
[ "MIT" ]
null
null
null
ShaderGLTest/DeviceTest.cpp
EPAC-Saxon/environment-map-JuliePreperier
cd024b83236af8cffa2262cad988b43b2f725dcb
[ "MIT" ]
null
null
null
#include "DeviceTest.h" namespace test { TEST_F(DeviceTest, CreateDeviceTest) { EXPECT_FALSE(device_); EXPECT_TRUE(window_); device_ = window_->CreateDevice(); EXPECT_TRUE(device_); } TEST_F(DeviceTest, StartupDeviceTest) { EXPECT_FALSE(device_); EXPECT_TRUE(window_); device_ = window_->CreateDevice(); device_->Startup(window_->GetSize()); EXPECT_TRUE(device_); } } // End namespace test.
18.217391
39
0.720764
EPAC-Saxon
e86bf1829ae08a4b9669d9528dbb04e4aa6b9357
966
hpp
C++
SignalDrivers/Hardware/ioport.hpp
NikitaEvs/signal_stm
15fa04392261c535f9104ddc0bbaf07f032421a6
[ "Apache-2.0" ]
null
null
null
SignalDrivers/Hardware/ioport.hpp
NikitaEvs/signal_stm
15fa04392261c535f9104ddc0bbaf07f032421a6
[ "Apache-2.0" ]
null
null
null
SignalDrivers/Hardware/ioport.hpp
NikitaEvs/signal_stm
15fa04392261c535f9104ddc0bbaf07f032421a6
[ "Apache-2.0" ]
null
null
null
#pragma once #include "port.hpp" #include "abstract_master.hpp" namespace SD { namespace Hardware { /** * @brief Wrapper for the base Port abstraction that adds Set/Reset function * and an initialization using Master */ class IOPort : public Port { public: /** * @brief Simple port initialization with a necessary link to the Master * in the purpose of an initialization and Set/Reset functions * @param master - link to the main Master object * @param port * @param pin */ IOPort(AbstractMaster& master, GPIO port, Pin pin) : Port(port, pin), master_(master) { master_.ConfigureIOPort(port, pin); } /** * @brief Set the port's pin using Master */ inline void Set() { master_.SetIOPort(gpio, pin); } /** * @brief Reset the port's pin using Master */ inline void Reset() { master_.ResetIOPort(gpio, pin); } private: AbstractMaster& master_; }; } // namespace Hardware } // namespace SD
20.125
76
0.665631
NikitaEvs
e8832e47044d3687c0d0f79385ef7692eaf1d68b
5,410
hpp
C++
Nacro/SDK/FN_AthenaCustomizationSlotButton_classes.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
11
2021-08-08T23:25:10.000Z
2022-02-19T23:07:22.000Z
Nacro/SDK/FN_AthenaCustomizationSlotButton_classes.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
1
2022-01-01T22:51:59.000Z
2022-01-08T16:14:15.000Z
Nacro/SDK/FN_AthenaCustomizationSlotButton_classes.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
8
2021-08-09T13:51:54.000Z
2022-01-26T20:33:37.000Z
#pragma once // Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // WidgetBlueprintGeneratedClass AthenaCustomizationSlotButton.AthenaCustomizationSlotButton_C // 0x0110 (0x09C8 - 0x08B8) class UAthenaCustomizationSlotButton_C : public UAthenaCustomizationSlotSelectorButton { public: struct FPointerToUberGraphFrame UberGraphFrame; // 0x08B8(0x0008) (Transient, DuplicateTransient) class UImage* EmptyImage; // 0x08C0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UImage* ImageSlotType; // 0x08C8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UNormalBangWrapper_C* NormalBangWrapper; // 0x08D0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UOverlay* OverlayTypeIcon; // 0x08D8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) struct FText TooltipBody; // 0x08E0(0x0018) (Edit, BlueprintVisible) struct FText TooltipHeader; // 0x08F8(0x0018) (Edit, BlueprintVisible) bool ShowSubTypeIcon; // 0x0910(0x0001) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) unsigned char UnknownData00[0x7]; // 0x0911(0x0007) MISSED OFFSET struct FSlateBrush SubTypeIcon; // 0x0918(0x0090) (Edit, BlueprintVisible) bool bSuppressTooltip; // 0x09A8(0x0001) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) EFortItemCardSize SlottedItemCardSize; // 0x09A9(0x0001) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) unsigned char UnknownData01[0x2]; // 0x09AA(0x0002) MISSED OFFSET float TypeIconVerticalOffset; // 0x09AC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) struct FText CustomizationName; // 0x09B0(0x0018) (Edit, BlueprintVisible) static UClass* StaticClass() { static auto ptr = UObject::FindClass("WidgetBlueprintGeneratedClass AthenaCustomizationSlotButton.AthenaCustomizationSlotButton_C"); return ptr; } ESlateVisibility ShouldShowEmptyImage(); void UpdateTypeIconOffset(float VerticalOffset); void Update_SubType_Icon_Glow(bool GlowIcon); void Update_SubType_Icon_Image(); void Construct(); void PreConstruct(bool* IsDesignTime); void ExecuteUbergraph_AthenaCustomizationSlotButton(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
93.275862
644
0.642144
Milxnor
e883a451e601c9b9b21ab8aaa496578cb156eb07
8,825
cpp
C++
src/prod/src/Management/DnsService/test/Helpers/DnsHelper.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/Management/DnsService/test/Helpers/DnsHelper.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/Management/DnsService/test/Helpers/DnsHelper.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" #include "DnsHelper.h" const ULONG LocalhostIP = 16777343; void DnsHelper::CreateDnsServiceHelper( __in KAllocator& allocator, __in DnsServiceParams& params, __out IDnsService::SPtr& spService, __out ComServiceManager::SPtr& spServiceManager, __out ComPropertyManager::SPtr& spPropertyManager, __out FabricData::SPtr& spData, __out IDnsParser::SPtr& spParser, __out INetIoManager::SPtr& spNetIoManager ) { NullTracer::SPtr spTracer; NullTracer::Create(/*out*/spTracer, allocator); DNS::CreateDnsParser(/*out*/spParser, allocator); DNS::CreateNetIoManager(/*out*/spNetIoManager, allocator, spTracer.RawPtr(), params.NumberOfConcurrentQueries); KString::SPtr spName; KString::Create(/*out*/spName, allocator, L"fabric:/System/DNS", TRUE/*appendnull*/); ComServiceManager::Create(/*out*/spServiceManager, allocator); ComPropertyManager::Create(/*out*/spPropertyManager, allocator); FabricData::Create(/*out*/spData, allocator); IDnsCache::SPtr spCache; CreateDnsCache(/*out*/spCache, allocator, params.MaxCacheSize); IFabricResolve::SPtr spResolve; DNS::CreateFabricResolve(/*out*/spResolve, allocator, spName, spTracer.RawPtr(), spData.RawPtr(), spCache.RawPtr(), spServiceManager.RawPtr(), spPropertyManager.RawPtr()); ComFabricStatelessServicePartition2::SPtr spHealth; ComFabricStatelessServicePartition2::Create(/*out*/spHealth, allocator); DNS::CreateDnsService( /*out*/spService, allocator, spTracer.RawPtr(), spParser.RawPtr(), spNetIoManager.RawPtr(), spResolve.RawPtr(), spCache, *spHealth.RawPtr(), params ); } DNS_STATUS DnsHelper::QueryEx( __in KBuffer& buffer, __in LPCWSTR wszQuery, __in USHORT type, __in KArray<DNS_DATA>& results ) { KAllocator& allocator = buffer.GetThisAllocator(); DNS_STATUS status = 0; IDnsService::SPtr spServiceInner; DnsServiceSynchronizer dnsServiceSyncInner; ComServiceManager::SPtr spServiceManagerInner; ComPropertyManager::SPtr spPropertyManagerInner; FabricData::SPtr spDataInner; IDnsParser::SPtr spParser; INetIoManager::SPtr spNetIoManager; DnsServiceParams params; params.IsRecursiveQueryEnabled = true; CreateDnsServiceHelper(allocator, params, /*out*/spServiceInner, /*out*/spServiceManagerInner, /*out*/spPropertyManagerInner, /*out*/spDataInner, /*out*/spParser, /*out*/spNetIoManager); USHORT port = 0; if (!spServiceInner->Open(/*inout*/port, static_cast<DnsServiceCallback>(dnsServiceSyncInner))) { VERIFY_FAIL(L""); } status = DnsHelper::Query(*spNetIoManager, buffer, *spParser, port, wszQuery, type, results); spServiceInner->CloseAsync(); dnsServiceSyncInner.Wait(); return status; } DNS_STATUS DnsHelper::Query( __in INetIoManager& netIoManager, __in KBuffer& buffer, __in IDnsParser& dnsParser, __in USHORT port, __in LPCWSTR wszQuery, __in WORD type, __in KArray<DNS_DATA>& results ) { #if !defined(PLATFORM_UNIX) UNREFERENCED_PARAMETER(dnsParser); #endif DNS_STATUS status = 0; KAllocator& allocator = buffer.GetThisAllocator(); DWORD dwSize = buffer.QuerySize(); DnsHelper::SerializeQuestion(dnsParser, wszQuery, buffer, type, /*out*/dwSize); NullTracer::SPtr spTracer; NullTracer::Create(/*out*/spTracer, allocator); IUdpListener::SPtr spListener; netIoManager.CreateUdpListener(/*out*/spListener, false /*AllowMultipleListeners*/); USHORT portClient = 0; DnsServiceSynchronizer syncListener; if (!spListener->StartListener(nullptr, /*inout*/portClient, syncListener)) { VERIFY_FAIL_FMT(L"Failed to start UDP listener"); } ISocketAddress::SPtr spAddress; DNS::CreateSocketAddress(/*out*/spAddress, allocator, LocalhostIP, htons(port)); DnsServiceSynchronizer syncWrite; spListener->WriteAsync(buffer, dwSize, *spAddress, syncWrite); syncWrite.Wait(5000); ISocketAddress::SPtr spAddressFrom; DNS::CreateSocketAddress(/*out*/spAddressFrom, allocator); DnsServiceSynchronizer syncRead; spListener->ReadAsync(buffer, *spAddressFrom, syncRead, 5000); syncRead.Wait(5000); spListener->CloseAsync(); syncListener.Wait(5000); #if !defined(PLATFORM_UNIX) // From MSDN: // The DnsExtractRecordsFromMessage function is designed to operate on messages in host byte order. // As such, received messages should be converted from network byte order to host byte order before extraction, // or before retransmission onto the network. Use the DNS_BYTE_FLIP_HEADER_COUNTS macro to change byte ordering. // PDNS_MESSAGE_BUFFER dnsBuffer = (PDNS_MESSAGE_BUFFER)buffer.GetBuffer(); DNS_BYTE_FLIP_HEADER_COUNTS(&dnsBuffer->MessageHead); PDNS_RECORD record = nullptr; status = DnsExtractRecordsFromMessage_W(dnsBuffer, (WORD)syncRead.Size(), &record); DNS_DATA dnsData; while (record != NULL) { dnsData.Type = record->wType; switch (record->wType) { case DNS_TYPE_A: { DNS_A_DATA& data = record->Data.A; IN_ADDR addr; addr.S_un.S_addr = data.IpAddress; WCHAR temp[256]; InetNtop(AF_INET, &addr, temp, ARRAYSIZE(temp)); dnsData.DataStr = KString::Create(temp, allocator); results.Append(dnsData); } break; case DNS_TYPE_SRV: { DNS_SRV_DATA& data = record->Data.SRV; WCHAR temp[1024]; STRPRINT(temp, ARRAYSIZE(temp), L"%s:%d", data.pNameTarget, data.wPort); CharLowerBuff(temp, (DWORD)wcslen(temp)); dnsData.DataStr = KString::Create(temp, allocator); results.Append(dnsData); } break; case DNS_TYPE_TEXT: { DNS_TXT_DATA& data = record->Data.TXT; dnsData.DataStr = KString::Create(KStringView(data.pStringArray[0]), allocator); results.Append(dnsData); } break; case DNS_TYPE_AAAA: { // we don't care about the value here results.Append(dnsData); } break; } // switch record = record->pNext; } DnsRecordListFree(record, DnsFreeFlat); #else IDnsMessage::SPtr spAnswerMessage; dnsParser.Deserialize(/*out*/spAnswerMessage, buffer, syncRead.Size(), true); KArray<IDnsRecord::SPtr>& arrDnsRecords = spAnswerMessage->Answers(); for (ULONG i = 0; i < arrDnsRecords.Count(); i++) { IDnsRecord::SPtr spAnswer = arrDnsRecords[i]; DNS_DATA dnsData; dnsData.Type = spAnswer->Type(); dnsData.DataStr = spAnswer->DebugString(); results.Append(dnsData); } status = DNS::DnsFlags::GetResponseCode(spAnswerMessage->Flags()); switch (status) { case DNS::DnsFlags::RC_FORMERR: status = DNS_ERROR_RCODE_FORMAT_ERROR; break; case DNS::DnsFlags::RC_SERVFAIL: status = DNS_ERROR_RCODE_SERVER_FAILURE; break; case DNS::DnsFlags::RC_NXDOMAIN: status = DNS_ERROR_RCODE_NAME_ERROR; break; case DNS::DnsFlags::RC_NOERROR: if (results.Count() == 0) { status = DNS_INFO_NO_RECORDS; } break; } #endif return status; } void DnsHelper::SerializeQuestion( __in IDnsParser& dnsParser, __in LPCWSTR wszQuery, __in KBuffer& buffer, __in WORD type, __out ULONG& size, __in DnsTextEncodingType encodingType ) { buffer.Zero(); size = buffer.QuerySize(); #if !defined(PLATFORM_UNIX) UNREFERENCED_PARAMETER(dnsParser); UNREFERENCED_PARAMETER(encodingType); if (!DnsWriteQuestionToBuffer_W((PDNS_MESSAGE_BUFFER)buffer.GetBuffer(), &size, wszQuery, type, 1, TRUE)) { VERIFY_FAIL_FMT(L"Failed to serialize question to buffer"); } #else KAllocator& allocator = buffer.GetThisAllocator(); KString::SPtr spQuestionStr; KString::Create(/*out*/spQuestionStr, allocator, wszQuery); spQuestionStr->SetNullTerminator(); IDnsMessage::SPtr spMessage = dnsParser.CreateQuestionMessage(rand() % MAXUSHORT, *spQuestionStr, (DnsRecordType)type, encodingType); if (!dnsParser.Serialize(buffer, /*out*/size, *spMessage, 1, encodingType)) { VERIFY_FAIL_FMT(L"Failed to serialize question to buffer"); } #endif }
31.183746
137
0.665609
vishnuk007
e885c8e86dcc42189f8cf0a89042139f50dd1d88
1,393
cpp
C++
src/pathutils.cpp
merelabs/mere-utils
26e4bc834e9b506d7939a9154f14e300458262c1
[ "BSD-2-Clause" ]
null
null
null
src/pathutils.cpp
merelabs/mere-utils
26e4bc834e9b506d7939a9154f14e300458262c1
[ "BSD-2-Clause" ]
null
null
null
src/pathutils.cpp
merelabs/mere-utils
26e4bc834e9b506d7939a9154f14e300458262c1
[ "BSD-2-Clause" ]
null
null
null
#include "pathutils.h" #include <sys/stat.h> #include <unistd.h> #include <iostream> //static bool Mere::Utils::PathUtils::exists(const std::string &path) { struct stat s; stat(path.c_str(), &s); //S_ISDIR(s.st_mode) || S_ISREG(s.st_mode) || S_ISFIFO(s.st_mode) || S_ISLNK(s.st_mode) || S_ISSOCK(s.st_mode); return stat(path.c_str(), &s) == 0; } //static bool Mere::Utils::PathUtils::remove(const std::string &path) { if(exists(path)) return false; int err = rmdir(path.c_str()); return !err; } //static bool Mere::Utils::PathUtils::create(const std::string &path, int mode) { if(exists(path)) return false; auto pos = path.find("/", 0); while (pos != std::string::npos) { std::string part = path.substr(0, pos + 1); if (!exists(part) && mkdir(part.c_str(), mode)) return false; pos = path.find("/", pos + 1); } int err = mkdir(path.c_str(), mode); return !err; } //static bool Mere::Utils::PathUtils::create_if_none(const std::string &path, int mode) { return create(path, mode); } //static std::string Mere::Utils::PathUtils::resolve(const std::string &path, int *resolved) { char buffer[PATH_MAX]; if(realpath(path.c_str(), buffer)) { if (resolved) *resolved = 1; return std::string(buffer); } if (resolved) *resolved = 0; return path; }
20.485294
115
0.605887
merelabs
e886ad54105d8b37897a115fbfd4b2dd6efb2eb3
3,896
hpp
C++
src/univang/format/format_context.hpp
bibmaster/nx.format
0993832a678bea4c1c005a97fba414557985356f
[ "MIT" ]
7
2019-10-08T13:11:07.000Z
2020-01-30T21:29:18.000Z
src/univang/format/format_context.hpp
bibmaster/nx.format
0993832a678bea4c1c005a97fba414557985356f
[ "MIT" ]
null
null
null
src/univang/format/format_context.hpp
bibmaster/nx.format
0993832a678bea4c1c005a97fba414557985356f
[ "MIT" ]
null
null
null
#pragma once #include <cassert> #include <cstddef> #include <cstring> #include <stdexcept> #include <string_view> namespace univang { namespace fmt { class format_context { public: #if FMT_RESPECT_ALIASING using byte = std::byte; #else enum class byte : char {}; #endif format_context() = default; constexpr format_context( void* data, size_t capacity, size_t size = 0) noexcept : data_(static_cast<byte*>(data)), capacity_(capacity), size_(size) { } format_context(const format_context&) = delete; format_context& operator=(const format_context&) = delete; virtual void grow(size_t /*new_capacity*/) { throw std::length_error("format_context limit overflow"); } byte& operator[](size_t index) { assert(index <= capacity_); return data_[index]; } byte operator[](size_t index) const { assert(index <= capacity_); return data_[index]; } void clear() { size_ = 0; } void assign(void* data, size_t capacity) noexcept { data_ = static_cast<byte*>(data); capacity_ = capacity; } void reserve(size_t sz) { if(capacity_ < sz) grow(sz); } void ensure(size_t add_size) { reserve(size_ + add_size); } byte back() const { assert(size_ != 0); return data_[size_ - 1]; } byte* data() const noexcept { return data_; } size_t size() const noexcept { return size_; } bool empty() const noexcept { return size_ == 0; } size_t capacity() const noexcept { return capacity_; } std::string_view get_str() const noexcept { return {reinterpret_cast<const char*>(data_), size_}; } void advance(size_t sz = 1) noexcept { assert(size_ + sz <= capacity_); size_ += sz; } void add(byte b) { assert(size_ < capacity_); data_[size_++] = b; } void add(char c) { assert(size_ < capacity_); data_[size_++] = byte(c); } void write(char c) { ensure(1); add(c); } void add_padding(char c, size_t count) { assert(size_ + count <= capacity_); memset(data_ + size_, int(c), count); size_ += count; } void write_padding(char c, size_t count) { ensure(count); add_padding(c, count); } void make_c_str() { ensure(1); data_[size_] = byte(0); } void add(const void* p, size_t sz) { assert(size_ + sz <= capacity_); memcpy(data_ + size_, p, sz); size_ += sz; } void write(const void* p, size_t sz) { ensure(sz); add(p, sz); } template<class Char, class Traits> auto add(std::basic_string_view<Char, Traits> str) -> std::enable_if_t<sizeof(Char) == 1> { add(str.data(), str.size()); } template<class Char, class Traits> auto write(std::basic_string_view<Char, Traits> str) -> std::enable_if_t<sizeof(Char) == 1> { write(str.data(), str.size()); } private: byte* data_ = nullptr; size_t capacity_ = 0; size_t size_ = 0; }; template<class String> class basic_string_format_context : public format_context { public: basic_string_format_context(String& str) : format_context(str.data(), str.size(), str.size()), str_(str) { } ~basic_string_format_context() { finalize(); } void grow(size_t new_capacity) final { str_.reserve(new_capacity); str_.resize(str_.capacity()); format_context::assign(str_.data(), str_.size()); } size_t finalize() { str_.resize(format_context::size()); return format_context::size(); } private: String& str_; }; using string_format_context = basic_string_format_context<std::string>; } // namespace fmt } // namespace univang
25.973333
77
0.587269
bibmaster
e88a0e10bd069e49e0342ae21caf69cc35eb2cb9
3,376
cpp
C++
src/main.cpp
Piripant/sbodies
19f4cbf4ec449706f82667c7875a2534aa367d76
[ "MIT" ]
1
2021-01-16T04:14:35.000Z
2021-01-16T04:14:35.000Z
src/main.cpp
Piripant/sbodies
19f4cbf4ec449706f82667c7875a2534aa367d76
[ "MIT" ]
null
null
null
src/main.cpp
Piripant/sbodies
19f4cbf4ec449706f82667c7875a2534aa367d76
[ "MIT" ]
null
null
null
#include "world.h" #include <SFML/Graphics.hpp> #include <iostream> #include <imgui.h> #include <imgui-SFML.h> int scale = 20; sf::Color colors[2] = { sf::Color(0, 0, 0), sf::Color(0, 0, 255) }; float step_time = 0.1; bool mouse_pressed = false; int press_y = 0; int press_x = 0; int nvertex = 3; float sim_speed = 1.0; bool edit_mode = true; int main() { // create the window sf::RenderWindow window(sf::VideoMode(800, 600), "tfluids"); debug_window = &window; ImGui::SFML::Init(window); auto body = Body(nvertex); std::cout << body.get_volume() << std::endl; int steps = 0; float elapsed = 0; sf::Clock delta_clock; // run the program as long as the window is open while (window.isOpen()) { auto elapsed = delta_clock.restart(); auto dt = elapsed.asSeconds(); if (dt > 0.001) { dt = 0; } dt *= sim_speed; auto size = window.getSize(); sf::Event event; while (window.pollEvent(event)) { ImGui::SFML::ProcessEvent(event); if (event.type == sf::Event::Closed) { window.close(); } if (event.type == sf::Event::Resized) { window.setView(sf::View(sf::FloatRect(0, 0, event.size.width, event.size.height))); } if (event.type == sf::Event::MouseButtonReleased && edit_mode) { /* if (event.mouseButton.button == sf::Mouse::Button::Left) { auto x = (double)((double)event.mouseButton.x - size.x/2.0) / 5.0; auto y = (double)((double)-event.mouseButton.y + size.y/2.0) / 5.0; body.append_vertex(BodyVertex(Vector(x, y))); } */ if (event.mouseButton.button == sf::Mouse::Button::Right) { body.set_joints(); edit_mode = false; } } } ImGui::SFML::Update(window, elapsed); ImGui::Begin("Settings"); if (ImGui::Button("Restart")) { body = Body(nvertex); edit_mode = true; } ImGui::Text("FPS: %f", 1/dt); ImGui::SliderFloat("Simulation speed", &sim_speed, 0.0f, 16.0f); ImGui::SliderInt("Number of vertexes", &nvertex, 1, 64); window.clear(sf::Color::White); if (!edit_mode) { body.update(dt); } ImGui::End(); sf::ConvexShape body_shape; body_shape.setFillColor(sf::Color(200, 200, 200)); body_shape.setPointCount(body.verts.size()); for (int i = 0; i < body.verts.size(); i++) { auto x = body.verts[i].position.x * 5 + size.x / 2; auto y = -body.verts[i].position.y * 5 + size.y / 2; sf::RectangleShape point(sf::Vector2f(5, 5)); point.setFillColor(sf::Color::Red); point.setPosition(sf::Vector2f(x - 5.0/2, y - 5.0/2)); window.draw(point); body_shape.setPoint(i, sf::Vector2f(x, y)); } window.draw(body_shape); ImGui::SFML::Render(window); window.display(); } return 0; }
28.854701
98
0.492595
Piripant
e88b7fbeebf95dab16a329dd96c4039f1bef2bdc
15,228
cpp
C++
src/uml/src_gen/uml/impl/ActivityGroupImpl.cpp
MDE4CPP/MDE4CPP
9db9352dd3b1ae26a5f640e614ed3925499b93f1
[ "MIT" ]
12
2017-02-17T10:33:51.000Z
2022-03-01T02:48:10.000Z
src/uml/src_gen/uml/impl/ActivityGroupImpl.cpp
ndongmo/MDE4CPP
9db9352dd3b1ae26a5f640e614ed3925499b93f1
[ "MIT" ]
28
2017-10-17T20:23:52.000Z
2021-03-04T16:07:13.000Z
src/uml/src_gen/uml/impl/ActivityGroupImpl.cpp
ndongmo/MDE4CPP
9db9352dd3b1ae26a5f640e614ed3925499b93f1
[ "MIT" ]
22
2017-03-24T19:03:58.000Z
2022-03-31T12:10:07.000Z
#include "uml/impl/ActivityGroupImpl.hpp" #ifdef NDEBUG #define DEBUG_MESSAGE(a) /**/ #else #define DEBUG_MESSAGE(a) a #endif #ifdef ACTIVITY_DEBUG_ON #define ACT_DEBUG(a) a #else #define ACT_DEBUG(a) /**/ #endif //#include "util/ProfileCallCount.hpp" #include <cassert> #include <iostream> #include <sstream> #include "abstractDataTypes/Bag.hpp" #include "abstractDataTypes/Subset.hpp" #include "abstractDataTypes/SubsetUnion.hpp" #include "abstractDataTypes/Union.hpp" #include "abstractDataTypes/Any.hpp" #include "abstractDataTypes/SubsetUnion.hpp" #include "ecore/EAnnotation.hpp" #include "ecore/EClass.hpp" //Includes from codegen annotation //Forward declaration includes #include "persistence/interfaces/XLoadHandler.hpp" // used for Persistence #include "persistence/interfaces/XSaveHandler.hpp" // used for Persistence #include <exception> // used in Persistence #include "uml/Activity.hpp" #include "uml/ActivityEdge.hpp" #include "uml/ActivityGroup.hpp" #include "uml/ActivityNode.hpp" #include "uml/Comment.hpp" #include "uml/Dependency.hpp" #include "uml/Element.hpp" #include "uml/NamedElement.hpp" #include "uml/Namespace.hpp" #include "uml/StringExpression.hpp" //Factories an Package includes #include "uml/impl/umlFactoryImpl.hpp" #include "uml/impl/umlPackageImpl.hpp" #include "ecore/EAttribute.hpp" #include "ecore/EStructuralFeature.hpp" using namespace uml; //********************************* // Constructor / Destructor //********************************* ActivityGroupImpl::ActivityGroupImpl() { } ActivityGroupImpl::~ActivityGroupImpl() { #ifdef SHOW_DELETION std::cout << "-------------------------------------------------------------------------------------------------\r\ndelete ActivityGroup "<< this << "\r\n------------------------------------------------------------------------ " << std::endl; #endif } //Additional constructor for the containments back reference ActivityGroupImpl::ActivityGroupImpl(std::weak_ptr<uml::Activity > par_inActivity) :ActivityGroupImpl() { m_inActivity = par_inActivity; m_owner = par_inActivity; } //Additional constructor for the containments back reference ActivityGroupImpl::ActivityGroupImpl(std::weak_ptr<uml::Namespace > par_namespace) :ActivityGroupImpl() { m_namespace = par_namespace; m_owner = par_namespace; } //Additional constructor for the containments back reference ActivityGroupImpl::ActivityGroupImpl(std::weak_ptr<uml::Element > par_owner) :ActivityGroupImpl() { m_owner = par_owner; } //Additional constructor for the containments back reference ActivityGroupImpl::ActivityGroupImpl(std::weak_ptr<uml::ActivityGroup > par_superGroup) :ActivityGroupImpl() { m_superGroup = par_superGroup; m_owner = par_superGroup; } ActivityGroupImpl::ActivityGroupImpl(const ActivityGroupImpl & obj):ActivityGroupImpl() { //create copy of all Attributes #ifdef SHOW_COPIES std::cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\ncopy ActivityGroup "<< this << "\r\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ " << std::endl; #endif m_name = obj.getName(); m_qualifiedName = obj.getQualifiedName(); m_visibility = obj.getVisibility(); //copy references with no containment (soft copy) std::shared_ptr<Bag<uml::Dependency>> _clientDependency = obj.getClientDependency(); m_clientDependency.reset(new Bag<uml::Dependency>(*(obj.getClientDependency().get()))); std::shared_ptr<Union<uml::ActivityEdge>> _containedEdge = obj.getContainedEdge(); m_containedEdge.reset(new Union<uml::ActivityEdge>(*(obj.getContainedEdge().get()))); std::shared_ptr<Union<uml::ActivityNode>> _containedNode = obj.getContainedNode(); m_containedNode.reset(new Union<uml::ActivityNode>(*(obj.getContainedNode().get()))); m_inActivity = obj.getInActivity(); m_namespace = obj.getNamespace(); m_owner = obj.getOwner(); m_superGroup = obj.getSuperGroup(); //Clone references with containment (deep copy) if(obj.getNameExpression()!=nullptr) { m_nameExpression = std::dynamic_pointer_cast<uml::StringExpression>(obj.getNameExpression()->copy()); } #ifdef SHOW_SUBSET_UNION std::cout << "Copying the Subset: " << "m_nameExpression" << std::endl; #endif std::shared_ptr<Bag<uml::Comment>> _ownedCommentList = obj.getOwnedComment(); for(std::shared_ptr<uml::Comment> _ownedComment : *_ownedCommentList) { this->getOwnedComment()->add(std::shared_ptr<uml::Comment>(std::dynamic_pointer_cast<uml::Comment>(_ownedComment->copy()))); } #ifdef SHOW_SUBSET_UNION std::cout << "Copying the Subset: " << "m_ownedComment" << std::endl; #endif } std::shared_ptr<ecore::EObject> ActivityGroupImpl::copy() const { std::shared_ptr<ActivityGroupImpl> element(new ActivityGroupImpl(*this)); element->setThisActivityGroupPtr(element); return element; } std::shared_ptr<ecore::EClass> ActivityGroupImpl::eStaticClass() const { return uml::umlPackage::eInstance()->getActivityGroup_Class(); } //********************************* // Attribute Setter Getter //********************************* //********************************* // Operations //********************************* std::shared_ptr<uml::Activity> ActivityGroupImpl::containingActivity() { std::cout << __PRETTY_FUNCTION__ << std::endl; throw "UnsupportedOperationException"; } bool ActivityGroupImpl::nodes_and_edges(Any diagnostics,std::map < Any, Any > context) { std::cout << __PRETTY_FUNCTION__ << std::endl; throw "UnsupportedOperationException"; } bool ActivityGroupImpl::not_contained(Any diagnostics,std::map < Any, Any > context) { std::cout << __PRETTY_FUNCTION__ << std::endl; throw "UnsupportedOperationException"; } //********************************* // References //********************************* /* Getter & Setter for reference containedEdge */ /* Getter & Setter for reference containedNode */ /* Getter & Setter for reference inActivity */ std::weak_ptr<uml::Activity > ActivityGroupImpl::getInActivity() const { return m_inActivity; } void ActivityGroupImpl::setInActivity(std::shared_ptr<uml::Activity> _inActivity) { m_inActivity = _inActivity; } /* Getter & Setter for reference subgroup */ /* Getter & Setter for reference superGroup */ //********************************* // Union Getter //********************************* std::shared_ptr<Union<uml::ActivityEdge>> ActivityGroupImpl::getContainedEdge() const { if(m_containedEdge == nullptr) { /*Union*/ m_containedEdge.reset(new Union<uml::ActivityEdge>()); #ifdef SHOW_SUBSET_UNION std::cout << "Initialising Union: " << "m_containedEdge - Union<uml::ActivityEdge>()" << std::endl; #endif } return m_containedEdge; } std::shared_ptr<Union<uml::ActivityNode>> ActivityGroupImpl::getContainedNode() const { if(m_containedNode == nullptr) { /*Union*/ m_containedNode.reset(new Union<uml::ActivityNode>()); #ifdef SHOW_SUBSET_UNION std::cout << "Initialising Union: " << "m_containedNode - Union<uml::ActivityNode>()" << std::endl; #endif } return m_containedNode; } std::shared_ptr<Union<uml::Element>> ActivityGroupImpl::getOwnedElement() const { if(m_ownedElement == nullptr) { /*Union*/ m_ownedElement.reset(new Union<uml::Element>()); #ifdef SHOW_SUBSET_UNION std::cout << "Initialising Union: " << "m_ownedElement - Union<uml::Element>()" << std::endl; #endif } return m_ownedElement; } std::weak_ptr<uml::Element > ActivityGroupImpl::getOwner() const { return m_owner; } std::shared_ptr<SubsetUnion<uml::ActivityGroup, uml::Element>> ActivityGroupImpl::getSubgroup() const { if(m_subgroup == nullptr) { /*SubsetUnion*/ m_subgroup.reset(new SubsetUnion<uml::ActivityGroup, uml::Element >()); #ifdef SHOW_SUBSET_UNION std::cout << "Initialising shared pointer SubsetUnion: " << "m_subgroup - SubsetUnion<uml::ActivityGroup, uml::Element >()" << std::endl; #endif /*SubsetUnion*/ m_subgroup->initSubsetUnion(getOwnedElement()); #ifdef SHOW_SUBSET_UNION std::cout << "Initialising value SubsetUnion: " << "m_subgroup - SubsetUnion<uml::ActivityGroup, uml::Element >(getOwnedElement())" << std::endl; #endif } return m_subgroup; } std::weak_ptr<uml::ActivityGroup > ActivityGroupImpl::getSuperGroup() const { return m_superGroup; } std::shared_ptr<ActivityGroup> ActivityGroupImpl::getThisActivityGroupPtr() const { return m_thisActivityGroupPtr.lock(); } void ActivityGroupImpl::setThisActivityGroupPtr(std::weak_ptr<ActivityGroup> thisActivityGroupPtr) { m_thisActivityGroupPtr = thisActivityGroupPtr; setThisNamedElementPtr(thisActivityGroupPtr); } std::shared_ptr<ecore::EObject> ActivityGroupImpl::eContainer() const { if(auto wp = m_inActivity.lock()) { return wp; } if(auto wp = m_namespace.lock()) { return wp; } if(auto wp = m_owner.lock()) { return wp; } if(auto wp = m_superGroup.lock()) { return wp; } return nullptr; } //********************************* // Structural Feature Getter/Setter //********************************* Any ActivityGroupImpl::eGet(int featureID, bool resolve, bool coreType) const { switch(featureID) { case uml::umlPackage::ACTIVITYGROUP_ATTRIBUTE_CONTAINEDEDGE: { std::shared_ptr<Bag<ecore::EObject>> tempList(new Bag<ecore::EObject>()); Bag<uml::ActivityEdge>::iterator iter = m_containedEdge->begin(); Bag<uml::ActivityEdge>::iterator end = m_containedEdge->end(); while (iter != end) { tempList->add(*iter); iter++; } return eAny(tempList); //109 } case uml::umlPackage::ACTIVITYGROUP_ATTRIBUTE_CONTAINEDNODE: { std::shared_ptr<Bag<ecore::EObject>> tempList(new Bag<ecore::EObject>()); Bag<uml::ActivityNode>::iterator iter = m_containedNode->begin(); Bag<uml::ActivityNode>::iterator end = m_containedNode->end(); while (iter != end) { tempList->add(*iter); iter++; } return eAny(tempList); //1010 } case uml::umlPackage::ACTIVITYGROUP_ATTRIBUTE_INACTIVITY: return eAny(std::dynamic_pointer_cast<ecore::EObject>(getInActivity().lock())); //1011 case uml::umlPackage::ACTIVITYGROUP_ATTRIBUTE_SUBGROUP: { std::shared_ptr<Bag<ecore::EObject>> tempList(new Bag<ecore::EObject>()); Bag<uml::ActivityGroup>::iterator iter = m_subgroup->begin(); Bag<uml::ActivityGroup>::iterator end = m_subgroup->end(); while (iter != end) { tempList->add(*iter); iter++; } return eAny(tempList); //1012 } case uml::umlPackage::ACTIVITYGROUP_ATTRIBUTE_SUPERGROUP: return eAny(std::dynamic_pointer_cast<ecore::EObject>(getSuperGroup().lock())); //1013 } return NamedElementImpl::eGet(featureID, resolve, coreType); } bool ActivityGroupImpl::internalEIsSet(int featureID) const { switch(featureID) { case uml::umlPackage::ACTIVITYGROUP_ATTRIBUTE_CONTAINEDEDGE: return getContainedEdge() != nullptr; //109 case uml::umlPackage::ACTIVITYGROUP_ATTRIBUTE_CONTAINEDNODE: return getContainedNode() != nullptr; //1010 case uml::umlPackage::ACTIVITYGROUP_ATTRIBUTE_INACTIVITY: return getInActivity().lock() != nullptr; //1011 case uml::umlPackage::ACTIVITYGROUP_ATTRIBUTE_SUBGROUP: return getSubgroup() != nullptr; //1012 case uml::umlPackage::ACTIVITYGROUP_ATTRIBUTE_SUPERGROUP: return getSuperGroup().lock() != nullptr; //1013 } return NamedElementImpl::internalEIsSet(featureID); } bool ActivityGroupImpl::eSet(int featureID, Any newValue) { switch(featureID) { case uml::umlPackage::ACTIVITYGROUP_ATTRIBUTE_INACTIVITY: { // BOOST CAST std::shared_ptr<ecore::EObject> _temp = newValue->get<std::shared_ptr<ecore::EObject>>(); std::shared_ptr<uml::Activity> _inActivity = std::dynamic_pointer_cast<uml::Activity>(_temp); setInActivity(_inActivity); //1011 return true; } } return NamedElementImpl::eSet(featureID, newValue); } //********************************* // Persistence Functions //********************************* void ActivityGroupImpl::load(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler) { std::map<std::string, std::string> attr_list = loadHandler->getAttributeList(); loadAttributes(loadHandler, attr_list); // // Create new objects (from references (containment == true)) // // get umlFactory int numNodes = loadHandler->getNumOfChildNodes(); for(int ii = 0; ii < numNodes; ii++) { loadNode(loadHandler->getNextNodeName(), loadHandler); } } void ActivityGroupImpl::loadAttributes(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler, std::map<std::string, std::string> attr_list) { NamedElementImpl::loadAttributes(loadHandler, attr_list); } void ActivityGroupImpl::loadNode(std::string nodeName, std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler) { std::shared_ptr<uml::umlFactory> modelFactory=uml::umlFactory::eInstance(); try { if ( nodeName.compare("subgroup") == 0 ) { std::string typeName = loadHandler->getCurrentXSITypeName(); if (typeName.empty()) { std::cout << "| WARNING | type if an eClassifiers node it empty" << std::endl; return; // no type name given and reference type is abstract } std::shared_ptr<ecore::EObject> subgroup = modelFactory->create(typeName, loadHandler->getCurrentObject(), uml::umlPackage::ACTIVITYGROUP_ATTRIBUTE_SUPERGROUP); if (subgroup != nullptr) { loadHandler->handleChild(subgroup); } return; } } catch (std::exception& e) { std::cout << "| ERROR | " << e.what() << std::endl; } catch (...) { std::cout << "| ERROR | " << "Exception occurred" << std::endl; } //load BasePackage Nodes NamedElementImpl::loadNode(nodeName, loadHandler); } void ActivityGroupImpl::resolveReferences(const int featureID, std::list<std::shared_ptr<ecore::EObject> > references) { switch(featureID) { case uml::umlPackage::ACTIVITYGROUP_ATTRIBUTE_INACTIVITY: { if (references.size() == 1) { // Cast object to correct type std::shared_ptr<uml::Activity> _inActivity = std::dynamic_pointer_cast<uml::Activity>( references.front() ); setInActivity(_inActivity); } return; } } NamedElementImpl::resolveReferences(featureID, references); } void ActivityGroupImpl::save(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const { saveContent(saveHandler); NamedElementImpl::saveContent(saveHandler); ElementImpl::saveContent(saveHandler); ObjectImpl::saveContent(saveHandler); ecore::EObjectImpl::saveContent(saveHandler); } void ActivityGroupImpl::saveContent(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const { try { std::shared_ptr<uml::umlPackage> package = uml::umlPackage::eInstance(); // // Add new tags (from references) // std::shared_ptr<ecore::EClass> metaClass = this->eClass(); // Save 'subgroup' std::shared_ptr<SubsetUnion<uml::ActivityGroup, uml::Element>> list_subgroup = this->getSubgroup(); for (std::shared_ptr<uml::ActivityGroup> subgroup : *list_subgroup) { saveHandler->addReference(subgroup, "subgroup", subgroup->eClass() !=uml::umlPackage::eInstance()->getActivityGroup_Class()); } } catch (std::exception& e) { std::cout << "| ERROR | " << e.what() << std::endl; } }
26.575916
242
0.690307
MDE4CPP
e88be034b39482a4054c2ab7039392fcc995080c
1,053
cpp
C++
07. Sorting/InsersionSort.cpp
R-Arpita/DSA-cpp-Hacktoberfest2021
acc7896fe30ddd54bcf4ec7bb93bd1f0b30b3bc5
[ "MIT" ]
149
2021-09-17T17:11:06.000Z
2021-10-01T17:32:18.000Z
07. Sorting/InsersionSort.cpp
R-Arpita/DSA-cpp-Hacktoberfest2021
acc7896fe30ddd54bcf4ec7bb93bd1f0b30b3bc5
[ "MIT" ]
138
2021-09-29T14:04:05.000Z
2021-10-01T17:43:18.000Z
07. Sorting/InsersionSort.cpp
R-Arpita/DSA-cpp-Hacktoberfest2021
acc7896fe30ddd54bcf4ec7bb93bd1f0b30b3bc5
[ "MIT" ]
410
2021-09-27T03:13:55.000Z
2021-10-01T17:59:42.000Z
/* Sayansree Paria email : [email protected] github : https://github.com/Sayansree Insertion sort algorithm */ #include<bits/stdc++.h> using namespace std; //iterative implementation of Insertion sort // arr is input array of size n void InsertionSort(int arr[],int n ){ for(int i=1; i<n; i++){ int j=i,key=arr[i]; while(key<arr[j-1]&&j>0){ arr[j]=arr[j-1]; j--; } arr[j]=key; } } ////recursive implementation of Insertion sort void RecursiveInsertionSort(int arr[],int n ){ if(n==1)return; RecursiveInsertionSort(arr,n-1); int j=n-1,key=arr[n-1]; while(key<arr[j-1]&&j>0){ arr[j]=arr[j-1]; j--; } arr[j]=key; } ///test run code int main(){ int arr[]={8,9,10,1,4,2,4,8,2,5}; int d=2,n=sizeof(arr)/sizeof(int); for(int i:arr) cout<<i<<"\t"; cout<<endl; RecursiveInsertionSort(arr,n);//sort for(int i:arr) cout<<i<<"\t"; return 0; }
20.25
48
0.531814
R-Arpita
e89006d234203553f289f27916ffa47e482210a0
2,429
hpp
C++
extension/parquet/include/decimal_column_reader.hpp
wesm/duckdb
f2fa094abc59d70a8c981d6e9f9c9c3911f08362
[ "MIT" ]
3
2021-05-13T04:15:45.000Z
2022-03-03T16:57:16.000Z
extension/parquet/include/decimal_column_reader.hpp
wesm/duckdb
f2fa094abc59d70a8c981d6e9f9c9c3911f08362
[ "MIT" ]
2
2021-10-02T02:52:39.000Z
2022-01-04T20:08:06.000Z
extension/parquet/include/decimal_column_reader.hpp
wesm/duckdb
f2fa094abc59d70a8c981d6e9f9c9c3911f08362
[ "MIT" ]
1
2021-11-20T16:09:34.000Z
2021-11-20T16:09:34.000Z
//===----------------------------------------------------------------------===// // DuckDB // // decimal_column_reader.hpp // // //===----------------------------------------------------------------------===// #pragma once #include "column_reader.hpp" #include "templated_column_reader.hpp" namespace duckdb { template <class DUCKDB_PHYSICAL_TYPE> struct DecimalParquetValueConversion { static DUCKDB_PHYSICAL_TYPE DictRead(ByteBuffer &dict, uint32_t &offset, ColumnReader &reader) { auto dict_ptr = (DUCKDB_PHYSICAL_TYPE *)dict.ptr; return dict_ptr[offset]; } static DUCKDB_PHYSICAL_TYPE PlainRead(ByteBuffer &plain_data, ColumnReader &reader) { DUCKDB_PHYSICAL_TYPE res = 0; auto byte_len = (idx_t)reader.Schema().type_length; /* sure, type length needs to be a signed int */ D_ASSERT(byte_len <= sizeof(DUCKDB_PHYSICAL_TYPE)); plain_data.available(byte_len); auto res_ptr = (uint8_t *)&res; // numbers are stored as two's complement so some muckery is required bool positive = (*plain_data.ptr & 0x80) == 0; for (idx_t i = 0; i < byte_len; i++) { auto byte = *(plain_data.ptr + (byte_len - i - 1)); res_ptr[i] = positive ? byte : byte ^ 0xFF; } plain_data.inc(byte_len); if (!positive) { res += 1; return -res; } return res; } static void PlainSkip(ByteBuffer &plain_data, ColumnReader &reader) { plain_data.inc(reader.Schema().type_length); } }; template <class DUCKDB_PHYSICAL_TYPE> class DecimalColumnReader : public TemplatedColumnReader<DUCKDB_PHYSICAL_TYPE, DecimalParquetValueConversion<DUCKDB_PHYSICAL_TYPE>> { public: DecimalColumnReader(ParquetReader &reader, LogicalType type_p, const SchemaElement &schema_p, idx_t file_idx_p, idx_t max_define_p, idx_t max_repeat_p) : TemplatedColumnReader<DUCKDB_PHYSICAL_TYPE, DecimalParquetValueConversion<DUCKDB_PHYSICAL_TYPE>>( reader, move(type_p), schema_p, file_idx_p, max_define_p, max_repeat_p) {}; protected: void Dictionary(shared_ptr<ByteBuffer> dictionary_data, idx_t num_entries) { this->dict = make_shared<ResizeableBuffer>(this->reader.allocator, num_entries * sizeof(DUCKDB_PHYSICAL_TYPE)); auto dict_ptr = (DUCKDB_PHYSICAL_TYPE *)this->dict->ptr; for (idx_t i = 0; i < num_entries; i++) { dict_ptr[i] = DecimalParquetValueConversion<DUCKDB_PHYSICAL_TYPE>::PlainRead(*dictionary_data, *this); } } }; } // namespace duckdb
34.7
113
0.682174
wesm
e8917ddf10b22d3cae43fa102568dafcbb88b447
9,874
cpp
C++
src/hsp3/linux/hsp3ext_sock.cpp
m4saka/OpenHSP
391f0a2100e701138d0610a5b94492d6f57ad1f2
[ "BSD-3-Clause" ]
127
2018-02-24T20:41:15.000Z
2022-03-22T05:57:56.000Z
src/hsp3/linux/hsp3ext_sock.cpp
m4saka/OpenHSP
391f0a2100e701138d0610a5b94492d6f57ad1f2
[ "BSD-3-Clause" ]
21
2018-09-11T15:04:22.000Z
2022-02-03T09:30:16.000Z
src/hsp3/linux/hsp3ext_sock.cpp
m4saka/OpenHSP
391f0a2100e701138d0610a5b94492d6f57ad1f2
[ "BSD-3-Clause" ]
21
2019-03-28T07:49:44.000Z
2021-12-25T02:49:07.000Z
// // hsp3dish socket拡張(linux) // (拡張コマンド・関数処理) // #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <poll.h> #include "../hsp3config.h" #include "../hsp3code.h" #include "../hsp3debug.h" #include "../supio.h" #include "../strbuf.h" #ifndef MAX #define MAX(a, b) ((a) > (b) ? (a) : (b)) #endif /*------------------------------------------------------------*/ /* system data */ /*------------------------------------------------------------*/ static HSPCTX *ctx; // Current Context static HSPEXINFO *exinfo; static int *type; static int *val; static int *exflg; static int p1,p2,p3,p4,p5; /*----------------------------------------------------------*/ // TCP/IP support /*----------------------------------------------------------*/ #include <errno.h> #include <fcntl.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> static int sockprep(); static int sockclose(int); static int sockget(char*, int, int); static int sockgetm(char*, int, int, int); static int sockreadbyte(); #define SOCKMAX 32 static int sockf=0; static int soc[SOCKMAX]; /* Soket Descriptor */ static int socsv[SOCKMAX]; static int svstat[SOCKMAX]; /* Soket Thread Status (server) */ static int sockprep( void ){ sockf++; for(int a = 0; a < SOCKMAX; a++){ soc[a] = -1; socsv[a] = -1; svstat[a] = 0; } return 0; } static int sockopen( int p1, char *p2, int p3){ struct sockaddr_in addr; if(sockf == 0){ if(sockprep()) return -1;; } soc[p1] = socket(AF_INET, SOCK_STREAM, 0); if(soc[p1]<0){ return -2; } addr.sin_family = AF_INET; addr.sin_addr.s_addr=inet_addr(p2); addr.sin_port=htons(p3); if(connect(soc[p1], (struct sockaddr*)&addr, sizeof(addr)) < 0){ return -4; } return 0; } static int sockclose(int p1){ if(socsv[p1]!=-1) close(socsv[p1]); if(soc[p1]!=-1) close(soc[p1]); soc[p1]=-1;socsv[p1]=-1;svstat[p1]=0; return 0; } static int sockget(char* buf, int size, int socid){ return sockgetm(buf, size, socid, 0); } static int sockgetm(char* buf, int size, int socid, int flag){ int recv_len; memset(buf, 0, sizeof(buf)); recv_len = recv(soc[socid], buf, size, flag); if(recv_len == -1) return errno; return 0; } static int sockgetc(int* buf, int socid){ int recv_len; char recv; recv_len = read(soc[socid], &recv, 1); if(recv_len < 0) return errno; buf[0] = (int)recv; return 0; } static int sockgetbm( char *org_buf, int offset, int size, int socid, int flag){ int buf_len; char* buf; buf = org_buf + offset; if(size == 0) size = 64; buf_len = recv(soc[socid], buf, size, flag); if(buf_len == -1) return errno; return -(buf_len); } static int sockgetb( char *org_buf, int offset, int size, int socid){ return sockgetbm(org_buf, offset, size, socid, 0); } static int sockputm(char* buf, int socid, int flag){ if(send(soc[socid], buf, strlen(buf), flag) == -1){ // FIXME: is `strlen(buf)` must be like `lstrlen()` in windows? return errno; } return 0; } static int sockput(char* buf, int socid){ return sockputm(buf, socid, 0); } static int sockputc(int c, int socid){ char buf[2]; buf[0] = (char)c; buf[1] = '\0'; if(send(soc[p3], buf, 1, 0) == -1){ return errno; } return 0; } static int sockputb(char* org_buf, int offset, int size, int socid){ char *buf; int buf_len; buf = org_buf + offset; if(size == 0) size = 64; buf_len = send(soc[socid], buf, size, 0); if(buf_len == -1) return 0; return -(buf_len); } static int sockmake(int socid, int port){ if(sockf == 0){ if(sockprep()) return -1; } if(socsv[socid] == -1){ struct sockaddr_in addr; int len = sizeof(struct sockaddr_in); socsv[socid] = socket(AF_INET, SOCK_STREAM, 0); if(socsv[socid] < 0){ return -2; } bzero((char *)&addr, sizeof(addr)); addr.sin_family = PF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = htons(port); if(bind(socsv[socid], (struct sockaddr *)&addr, len) < 0){ return -3; } }else{ } svstat[socid] = 1; if(listen(socsv[socid], SOMAXCONN) < 0){ svstat[socid] = 0; }else{ svstat[socid]++; } return 0; } static int sockwait(int socid){ static int maxfd = 0; int err; fd_set fdsetread, fdsetwrite, fdseterror; struct timeval TimeVal={0,10000}; int soc2; struct sockaddr_in from; if(socsv[socid] == -1) return -2; if(svstat[socid] == -1) return -4; if(svstat[socid] != 2) return -3; FD_ZERO(&fdsetread); FD_ZERO(&fdsetwrite); FD_ZERO(&fdseterror); FD_SET(socsv[socid], &fdsetread); maxfd = MAX(maxfd, socsv[socid]); if((err = select(maxfd+1, &fdsetread, &fdsetwrite, &fdseterror, &TimeVal))==0){ if(err == -1) return -4; return -1; } svstat[socid] = 0; unsigned int len = sizeof(from); memset(&from, 0, len); soc2 = accept(socsv[socid], (struct sockaddr *)&from, &len); if(soc2 == -1){ close(socsv[socid]); socsv[socid] = -1; return -5; } soc[socid] = soc2; close(socsv[socid]); socsv[socid] = -1; char s1[128]; char s2[128]; sprintf(s1, "%s:%d", inet_ntoa(from.sin_addr), ntohs(from.sin_port)); return 0; } static int sockreadbyte(){ // No arguments // Return read byte int buf_len; char buf[1]; memset(buf, 0, sizeof(buf)); buf_len = read(soc[p2], buf, sizeof(buf)); if(buf_len < 0){ return -2; } if(buf_len == 0){ return -1; } return (int)buf[0]; } /*------------------------------------------------------------*/ /* interface */ /*------------------------------------------------------------*/ static int cmdfunc_extcmd( int cmd ) { // cmdfunc : TYPE_EXTCMD // (内蔵GUIコマンド) // code_next(); // 次のコードを取得(最初に必ず必要です) switch( cmd ) { // サブコマンドごとの分岐 // command part // case 0x60: //sockopen { char *address; int p_res; p1 = code_getdi( 0 ); address = code_stmpstr( code_gets() ); p3 = code_getdi( 0 ); p_res = sockopen(p1, address, p3); ctx->stat = p_res; break; } case 0x61: //sockclose { char *cname; int p_res; p1 = code_geti(); p_res = sockclose(p1); ctx->stat = p_res; break; } case 0x62: //sockreadbyte { char *cname; int p_res; p_res = sockreadbyte(); if(p_res > 0){ printf("%c\n", p_res); } ctx->stat = p_res; break; } case 0x63: //sockget { PVal *pval; char *ptr; int size; ptr = code_getvptr( &pval, &size ); p2 = code_getdi( 0 ); p3 = code_getdi( 0 ); int p_res; p_res = sockget(pval->pt, p2, p3); ctx->stat = p_res; break; } case 0x64: //sockgetc { } case 0x65: //sockgetm { PVal *pval; char *ptr; int size; ptr = code_getvptr( &pval, &size ); p2 = code_getdi( 0 ); p3 = code_getdi( 0 ); p4 = code_getdi( 0 ); int p_res; p_res = sockgetm(pval->pt, p2, p3, p4); ctx->stat = p_res; break; } case 0x66: //sockgetb { PVal *pval; char *ptr; int size; ptr = code_getvptr(&pval, &size); p2 = code_getdi( 0 ); p3 = code_getdi( 0 ); p4 = code_getdi( 0 ); int p_res; p_res = sockgetb(pval->pt, p2, p3, p4); ctx->stat = p_res; break; } case 0x67: //sockgetbm { PVal *pval; char *ptr; int size; ptr = code_getvptr(&pval, &size); p2 = code_getdi( 0 ); p3 = code_getdi( 0 ); p4 = code_getdi( 0 ); p5 = code_getdi( 0 ); int p_res; p_res = sockgetbm(pval->pt, p2, p3, p4, p5); ctx->stat = p_res; break; } case 0x68: // sockput { PVal *pval; char *ptr; int size; ptr = code_getvptr(&pval, &size); p2 = code_getdi( 0 ); int p_res; p_res = sockput(pval->pt, p2); ctx->stat = p_res; break; } case 0x69: // sockputc { PVal *pval; char *ptr; int size; p1 = code_getdi( 0 ); p2 = code_getdi( 0 ); int p_res; p_res = sockputc(p1, p2); ctx->stat = p_res; break; } case 0x6a: // sockputb { PVal *pval; char *ptr; int size; ptr = code_getvptr(&pval, &size); p2 = code_getdi( 0 ); p3 = code_getdi( 0 ); p4 = code_getdi( 0 ); int p_res; p_res = sockputb(ptr, p2, p3, p4); ctx->stat = p_res; break; } case 0x6b: // sockmake { p1 = code_getd(); p2 = code_getd(); int p_res = sockmake(p1, p2); ctx->stat = p_res; break; } case 0x6c: // sockwait { p1 = code_getd(); int p_res = sockwait(p1); ctx->stat = p_res; break; } default: throw HSPERR_UNSUPPORTED_FUNCTION; } return RUNMODE_RUN; } #if 0 static int reffunc_intfunc_ivalue; static void *reffunc_function( int *type_res, int arg ) { void *ptr; // 返値のタイプを設定する // *type_res = HSPVAR_FLAG_INT; // 返値のタイプを指定する ptr = &reffunc_intfunc_ivalue; // 返値のポインタ // '('で始まるかを調べる // if ( *type != TYPE_MARK ) throw HSPERR_INVALID_FUNCPARAM; if ( *val != '(' ) throw HSPERR_INVALID_FUNCPARAM; code_next(); switch( arg & 0xff ) { // int function default: throw HSPERR_UNSUPPORTED_FUNCTION; } // '('で終わるかを調べる // if ( *type != TYPE_MARK ) throw HSPERR_INVALID_FUNCPARAM; if ( *val != ')' ) throw HSPERR_INVALID_FUNCPARAM; code_next(); return ptr; } #endif static int termfunc_extcmd( int option ) { // termfunc : TYPE_EXTCMD // return 0; } void hsp3typeinit_sock_extcmd( HSP3TYPEINFO *info ) { ctx = info->hspctx; exinfo = info->hspexinfo; type = exinfo->nptype; val = exinfo->npval; // function register // info->cmdfunc = cmdfunc_extcmd; info->termfunc = termfunc_extcmd; // Application initalize // } void hsp3typeinit_sock_extfunc( HSP3TYPEINFO *info ) { }
19.987854
119
0.564209
m4saka
e89182d494b33c7ad6e7e41e11da35bf854810e0
3,659
cpp
C++
src/Cpp/Learning_Cpp/Course_Codes/The_LinkedIn_Course/Advanced_Cpp/Chap08/utest.cpp
Ahmopasa/TheCodes
560ed94190fd0da8cc12285e9b4b5e27b19010a5
[ "MIT" ]
null
null
null
src/Cpp/Learning_Cpp/Course_Codes/The_LinkedIn_Course/Advanced_Cpp/Chap08/utest.cpp
Ahmopasa/TheCodes
560ed94190fd0da8cc12285e9b4b5e27b19010a5
[ "MIT" ]
null
null
null
src/Cpp/Learning_Cpp/Course_Codes/The_LinkedIn_Course/Advanced_Cpp/Chap08/utest.cpp
Ahmopasa/TheCodes
560ed94190fd0da8cc12285e9b4b5e27b19010a5
[ "MIT" ]
null
null
null
// utest.cpp by Bill Weinman <http://bw.org/> // version of 2018-10-12 #include <cstdio> #include "BWUTest.h" #include "BWString.h" bool summary_flag = false; int main() { // Versions n things printf("BWString version: %s\n", BWString::version()); printf("BWUTest version: %s\n", BWUTest::version()); BWUTest u("BWLib"); u.summary(summary_flag); // BWString printf("\nTesting BWString -----\n"); u.init("BWString"); // test constructors const char * _ctest = " \tfoo \r\n"; BWString ttest = _ctest; u.test("cstring ctor", ttest.length() == 12); puts(ttest); BWString other = std::move(ttest); u.test("move ctor", other.length() == 12 && ttest.length() == 0); ttest = std::move(other); // assignment operators u.test("move assignment", other.length() == 0 && ttest.length() == 12); other = ttest; u.test("copy assignment", other.length() == 12 && ttest.length() == 12); // concat operators BWString x = "foo"; BWString y = "bar"; x += y; u.test("concat +=", x.length() == 6 && memcmp(x.c_str(), "foobar", 7) == 0); BWString z; z = x + "baz"; u.test("concat +", z.length() == 9 && memcmp(z.c_str(), "foobarbaz", 10) == 0); z = "baz" + x; u.test("concat +", z.length() == 9 && memcmp(z.c_str(), "bazfoobar", 10) == 0); // comparison operators x = y = "foo"; u.test("foo == foo", (x == y)); u.test("foo > foo", !(x > y)); u.test("foo >= foo", (x >= y)); u.test("foo < foo", !(x < y)); u.test("foo <= foo", (x <= y)); x = "bar"; u.test("bar == foo", !(x == y)); u.test("bar > foo", !(x > y)); u.test("bar >= foo", !(x >= y)); u.test("bar < foo", (x < y)); u.test("bar <= foo", (x <= y)); u.test("foo == bar", !(y == x)); u.test("foo > bar", (y > x)); u.test("foo >= bar", (y >= x)); u.test("foo < bar", !(y < x)); u.test("foo <= bar", !(y <= x)); // subscript u.test("subscript x[0]", x[0] == 'b'); u.test("subscript x[1]", x[1] == 'a'); u.test("subscript x[2]", x[2] == 'r'); u.test("subscript terminator x[3]", x[3] == 0); ttest.trim(); u.test("trim", ttest.length() == 3); ttest = "this is a string"; u.test("length is 16", ttest.length() == 16 && ttest.size() == 16); u.test("substr", ttest.substr(10, 3) == BWString("str")); u.test("charfind", ttest.char_find('s') == 3); u.test("charfind (not found)", ttest.char_find('z') == -1); BWString string_upper = ttest.upper(); BWString string_lower = string_upper.lower(); u.test("upper and lower", string_upper == BWString("THIS IS A STRING") && string_lower == BWString("this is a string")); x = "this is a big string ###foobarbaz### this is a big string"; x = x.replace("###foobarbaz###", "foo bar baz"); u.test("replace", x.length() == 53 && memcmp(x.c_str(), "this is a big string foo bar baz this is a big string", 54) == 0); x = "line one/line two/line three"; auto & r = x.split('/'); u.test("split_count is 3", x.split_count() == 3); u.test("split result 1", memcmp(r[0]->c_str(), "line one", 8) == 0); u.test("split result 2", memcmp(r[1]->c_str(), "line two", 8) == 0); u.test("split result 3", memcmp(r[2]->c_str(), "line three", 10) == 0); u.test("split test end", !r[3]); u.test("format test", memcmp(x.format("format test %d", 42).c_str(), "format test 42", 14) == 0); // report results puts(""); u.report(); return 0; // Done. Yay! }
32.380531
127
0.511342
Ahmopasa
e895bb0296dc619d715846cda4f48ffdd67f0594
3,427
cpp
C++
Hydrogen Framework/src/HFR/text/Font.cpp
salmoncatt/HGE
8ae471de46589df54cacd1bd0261989633f1e5ef
[ "BSD-3-Clause" ]
2
2020-11-12T14:42:56.000Z
2021-01-27T18:04:42.000Z
Hydrogen Framework/src/HFR/text/Font.cpp
salmoncatt/Hydrogen-Game-Engine
8ae471de46589df54cacd1bd0261989633f1e5ef
[ "BSD-3-Clause" ]
1
2021-01-27T17:39:21.000Z
2021-01-28T01:42:36.000Z
Hydrogen Framework/src/HFR/text/Font.cpp
salmoncatt/Hydrogen-Game-Engine
8ae471de46589df54cacd1bd0261989633f1e5ef
[ "BSD-3-Clause" ]
null
null
null
#include "hfpch.h" #include "Font.h" #include HFR_FREETYPE #include HFR_UTIL namespace HFR { Font::Font() { size = Vec2f(0, 48); atlasSize = Vec2f(); } Font::Font(const std::string& _path) { size = Vec2f(0, 48); atlasSize = Vec2f(); path = _path; name = Util::removePathFromFilePathAndName(_path); } Font::~Font() { } void Font::create() { FT_Face face = FreeType::loadFace(path); FT_Set_Pixel_Sizes(face, 0, size.y); FT_GlyphSlot glyph = face->glyph; float width = 0; float height = 0; float rowWidth = 0; float rowHeight = 0; for (int i = 0; i < 128; ++i) { //super sophisticated error checking algorithm if (FT_Load_Char(face, i, FT_LOAD_RENDER)) { std::string character; character = (char)(i); std::string error = ("Loading character " + character + " has failed in font: " + name); Debug::systemErr(error); continue; } if (rowWidth + glyph->bitmap.width + 1 >= (unsigned int)maxTextureWidth) { width = max(width, rowWidth); height += rowHeight; rowWidth = 0; rowHeight = 0; } rowWidth += glyph->bitmap.width + 1; rowHeight = max(height, glyph->bitmap.rows); } width = max(width, rowWidth); height += rowHeight; atlasSize = Vec2f(width, height); rowHeight = 0; Vec2i offset = Vec2i(); unsigned char* blankColor = new unsigned char[width * height]; for (int i = 0; i < (width * height); ++i) { blankColor[i] = 0x0; } Image imageData = Image(width, height, 1, blankColor); texture = Texture(imageData); texture.byteAlignment = 1; texture.filterMode = Vec2i(GL_LINEAR); texture.internalFormat = GL_RED; texture.format = GL_RED; texture.generateMipmap = false; texture.wrapMode = Vec2i(GL_CLAMP_TO_EDGE); texture.create(); for (int i = 0; i < 128; ++i) { //super sophisticated error checking algorithm if (FT_Load_Char(face, i, FT_LOAD_RENDER)) { std::string character; character = (char)(i); std::string error = ("Loading character " + character + " has failed in font: " + Util::removePathFromFilePathAndName(path)); Debug::systemErr(error); continue; } if (offset.x + glyph->bitmap.width + 1 >= (unsigned int)maxTextureWidth) { offset.y += rowHeight; rowHeight = 0; offset.x = 0; } texture.setSubImage(0, offset, Vec2i(glyph->bitmap.width, glyph->bitmap.rows), glyph->bitmap.buffer); characters[i].advance = Vec2f((float)(glyph->advance.x >> 6), (float)(glyph->advance.y >> 6)); characters[i].bitmapLeftTop = Vec2f((float)glyph->bitmap_left, (float)glyph->bitmap_top); characters[i].size = Vec2f((float)(glyph->bitmap.width), (float)(glyph->bitmap.rows)); characters[i].textureOffset = Vec2f((float)(offset.x / width), (float)(offset.y / height)); rowHeight = max(rowHeight, glyph->bitmap.rows); offset.x += glyph->bitmap.width + 2; } delete[] blankColor; if (logStatus) { Debug::systemSuccess("Loaded font: " + Util::removePathFromFilePathAndName(path), DebugColor::Blue); Debug::systemSuccess(Util::removePathFromFilePathAndName(path) + " atlas size is " + std::to_string(width) + " x " + std::to_string(height) + " pixels and is " + std::to_string(width * height / 1024) + " kb", DebugColor::Blue); } FT_Done_Face(face); } }
26.565891
231
0.623869
salmoncatt
e8960e501ffe7669b6f153d788fa013573294101
1,470
cpp
C++
source/Ch04/drill/ch04_drill.cpp
gorzsaszarvak/UDProg-Introduction
591d1d05c950da2ab4d59d78cbf5a1408caa78e6
[ "CC0-1.0" ]
null
null
null
source/Ch04/drill/ch04_drill.cpp
gorzsaszarvak/UDProg-Introduction
591d1d05c950da2ab4d59d78cbf5a1408caa78e6
[ "CC0-1.0" ]
null
null
null
source/Ch04/drill/ch04_drill.cpp
gorzsaszarvak/UDProg-Introduction
591d1d05c950da2ab4d59d78cbf5a1408caa78e6
[ "CC0-1.0" ]
null
null
null
#include "../../std_lib_facilities.h" int main() { constexpr double m_per_inch = 0.0254; constexpr double m_per_cm = 0.01; constexpr double m_per_ft = 0.3048; double length = -1; char unit = 0; vector<double> values; double lastvalue = 0; double sum = 0; double minvalue = 999999999999; double maxvalue = 0; cout << "Enter a number and a unit (c, m, i, f):\n"; while(cin >> length >> unit) { switch (unit) { case 'i': lastvalue = length * m_per_inch; values.push_back(lastvalue); sum += lastvalue; cout << "That's " << lastvalue << "m\n"; break; case 'm': lastvalue = length; values.push_back(length); sum += lastvalue; break; case 'c': lastvalue = length * m_per_cm; values.push_back(lastvalue); sum += lastvalue; cout << "That's " << lastvalue << "m\n"; break; case 'f': lastvalue = length * m_per_ft; values.push_back(lastvalue); sum += lastvalue; cout << "That's " << lastvalue << "m\n"; break; default: cout << "Illegal unit.\n"; lastvalue=0; break; } if (lastvalue!=0 and (lastvalue < minvalue)) { minvalue = lastvalue; cout << "smallest so far\n"; } else if (lastvalue!=0 and (lastvalue > maxvalue)) { maxvalue = lastvalue; cout << "largest so far\n"; } } cout << "sum of values: " << sum << "m \n"; sort(values.begin(), values.end()); for (int i = 0; i < values.size(); i++) cout << values[i] <<"m, "; return '|'; }
18.375
53
0.588435
gorzsaszarvak
e89adabe1fe3f16e983541aade1c2e7d63de617e
3,624
hpp
C++
a21/serial.hpp
biappi/a21
6d008bebdbd6c51816ed61aa45664fa3b2715d9b
[ "MIT" ]
6
2017-07-28T13:36:24.000Z
2022-01-30T14:00:32.000Z
a21/serial.hpp
carkang/a21
8f472e75de5734514f152828033a93b88401069a
[ "MIT" ]
3
2018-10-26T20:10:49.000Z
2021-05-15T20:31:45.000Z
a21/serial.hpp
carkang/a21
8f472e75de5734514f152828033a93b88401069a
[ "MIT" ]
2
2021-02-14T14:12:58.000Z
2022-01-13T23:08:26.000Z
// // a21 — Arduino Toolkit. // Copyright (C) 2016-2018, Aleh Dzenisiuk. http://github.com/aleh/a21 // #pragma once #include <Arduino.h> #include <a21/clock.hpp> #include <a21/print.hpp> namespace a21 { #pragma GCC optimize ("O2") /** * Software serial port, 8-N-1, TX only. */ template<typename pinTX, unsigned long baudRate, typename Clock = ArduinoClock> class SerialTx : public Print< SerialTx<pinTX, baudRate, Clock> > { private: static inline void writeBit(bool b) __attribute__((always_inline)) { pinTX::write(b); Clock::delayMicroseconds(1000000.0 * (1.0 / baudRate - 5.0 / F_CPU)); } public: static void begin() { pinTX::setOutput(); pinTX::setHigh(); } static void write(uint8_t value) { noInterrupts(); writeBit(false); writeBit(value & _BV(0)); writeBit(value & _BV(1)); writeBit(value & _BV(2)); writeBit(value & _BV(3)); writeBit(value & _BV(4)); writeBit(value & _BV(5)); writeBit(value & _BV(6)); writeBit(value & _BV(7)); writeBit(true); interrupts(); } }; /** * Simple software serial port, 8-N-1, RX only. */ template<typename pinRX, unsigned long baudRate, typename Clock = ArduinoClock> class SerialRx { static constexpr double oneBitDelayUs = 1000000.0 / baudRate; static inline void readNextBit(uint8_t& result) __attribute__((always_inline)) { result >>= 1; if (pinRX::read()) { result |= 0x80; } else { result |= 0x00; } Clock::delayMicroseconds(oneBitDelayUs); } public: static void begin() { pinRX::setInput(); } /** Tries to read the next byte on the pin. * Zero is returned when no byte is available (don't see the start bit or could finish the reception). */ static uint8_t read(uint8_t start_bit_timeout) { uint8_t result = 0; uint8_t start_time = Clock::micros8(); uint8_t t; while (true) { if (!pinRX::read()) { break; } if (Clock::micros8() - start_time >= start_bit_timeout) { return 0; } } cli(); Clock::delayMicroseconds(1.1 * oneBitDelayUs); readNextBit(result); readNextBit(result); readNextBit(result); readNextBit(result); readNextBit(result); readNextBit(result); readNextBit(result); readNextBit(result); bool stop = pinRX::read(); sei(); return stop ? result : 0; } }; /** * Software serial receiver that can be driven by a pin change interrupt. */ template<uint16_t baudRate> class PinChangeSerialRx { protected: /*~ typedef PinChangeSerialRx<baudRate, timerTicksPerSecond> Self; static Self& getSelf() { static Self s = Self(); return s; } // Bit we are on. enum State : uint8_t { BeforeStartBit, StartBit, Bit0, Bit1, Bit2, Bit3, Bit4, Bit5, Bit6, Bit7, Bit8, StopBit } state; // Timestamp of the last event, if any. uint16_t prevTime; bool prevValue; public: static void begin() { getSelf().state = BeforeStartBit; } */ /** Should be called every time the pin changes, possibily from an interrupt handler. */ /* static void pinChange(uint16_t time, bool value) { Self& self = getSelf(); if (self.state == BeforeStartBit) { if (value) { self.prevTime = time; self.state = StartBit; } } else { uint16_t t = time - prevTime; t += halfBitTime; } } */ static void check(uint16_t time_us) { } }; #pragma GCC reset_options } // namespace
20.24581
107
0.606236
biappi
e89d57dbf5f39dca613fa4db41d0cf512e7b3eda
1,888
hpp
C++
include/Utils/Tracer.hpp
azazelspce/SPGO
04df3c6a0c59120cb054ce2bffcfbc79301c2f27
[ "Apache-2.0", "MIT" ]
4
2016-02-24T17:20:42.000Z
2016-04-09T00:33:50.000Z
include/Utils/Tracer.hpp
azazelspce/SPGO
04df3c6a0c59120cb054ce2bffcfbc79301c2f27
[ "Apache-2.0", "MIT" ]
1
2016-04-29T01:06:48.000Z
2016-12-04T00:35:45.000Z
include/Utils/Tracer.hpp
azazelspce/SPGO
04df3c6a0c59120cb054ce2bffcfbc79301c2f27
[ "Apache-2.0", "MIT" ]
null
null
null
// Copyright 2019 Cristian Sandoval Pineda // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /// @file Tracer.hpp /// /// @brief Base class. /// /// @author Cristian Sandoval Pineda /// Contact: [email protected] #ifndef TRACER_HPP #define TRACER_HPP #include <vector> #include <string> using std::vector; using std::string; namespace spgo { /// @cond HIDDEN_SYMBOLS class Tracer { protected: vector<vector<double>> raw_data; vector<double> line; vector<string> columns; bool verbose; public: Tracer( bool verbose = false ) { this->verbose = verbose; } void Append( double var ) { if( line.size() == columns.size() ) { raw_data.push_back( line ); line.clear(); } line.push_back( var ); } void AddColumn( string name ) { columns.push_back( name ); } void AddColumns( vector<string> names ) { columns.insert( columns.end(), names.begin(), names.end()); } void Reserve( int rows ) { line.reserve( columns.size() ); raw_data.reserve( rows ); } void SetOutput( bool verbose ) { this->verbose = verbose; } void Clear() { line.clear(); raw_data.clear(); columns.clear(); } vector<vector<double>> GetData() const { return raw_data; } vector<string> GetColumns() const { return columns; } ~Tracer() { } }; /// @endcond HIDDEN_SYMBOLS } #endif
19.666667
68
0.558792
azazelspce
e89def63eeab5db8bc1932e5b04d9505152f803c
5,485
hpp
C++
common/trc_io.hpp
hirakuni45/R8C
361d2749b80e738984745bc8d7537eb40191fdd8
[ "BSD-3-Clause" ]
6
2016-03-07T02:40:09.000Z
2021-07-25T11:07:01.000Z
common/trc_io.hpp
hirakuni45/R8C
361d2749b80e738984745bc8d7537eb40191fdd8
[ "BSD-3-Clause" ]
2
2021-11-16T17:51:01.000Z
2021-11-16T17:51:42.000Z
common/trc_io.hpp
hirakuni45/R8C
361d2749b80e738984745bc8d7537eb40191fdd8
[ "BSD-3-Clause" ]
1
2021-01-17T23:03:33.000Z
2021-01-17T23:03:33.000Z
#pragma once //=====================================================================// /*! @file @brief R8C グループ・TimerRC I/O 制御 @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2015, 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/R8C/blob/master/LICENSE */ //=====================================================================// #include "common/vect.h" #include "M120AN/system.hpp" #include "M120AN/intr.hpp" #include "M120AN/timer_rc.hpp" /// F_CLK はタイマー周期計算で必要で、設定が無いとエラーにします。 #ifndef F_CLK # error "trc_io.hpp requires F_CLK to be defined" #endif namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief TimerRC I/O 制御クラス @param[in] TASK 割り込み内で実行されるクラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class TASK> class trc_io { public: static TASK task_; static volatile uint16_t pwm_b_; static volatile uint16_t pwm_c_; static volatile uint16_t pwm_d_; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief PWM-A 割り込み */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// static inline void itask() { task_(); volatile uint8_t f = TRCSR(); TRCGRB = pwm_b_; TRCGRC = pwm_c_; TRCGRD = pwm_d_; TRCSR = 0x00; } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief カウンターディバイド */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// enum class divide : uint8_t { f1, ///< F_CLK / 1 f2, ///< F_CLK / 2 f4, ///< F_CLK / 4 f8, ///< F_CLK / 8 f32 ///< F_CLK / 32 }; private: public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// trc_io() { } //-----------------------------------------------------------------// /*! @brief PWMモード開始(最大3チャネルのPWM出力) @param[in] limit リミット @param[in] cks クロック選択 @param[in] pfl ポートの初期レベル「fasle」0->1、「true」1->0 @param[in] ir_lvl 割り込みレベル(0の場合割り込みを使用しない) @return 設定範囲を超えたら「false」 */ //-----------------------------------------------------------------// void start_pwm(uint16_t limit, divide cks, bool pfl, uint8_t ir_lvl = 0) const { MSTCR.MSTTRC = 0; // モジュールスタンバイ解除 TRCMR.CTS = 0; // カウント停止 TRCCNT = 0x0000; TRCGRA = limit; TRCGRB = pwm_b_ = 128; TRCGRC = pwm_c_ = 128; TRCGRD = pwm_d_ = 128; TRCMR = TRCMR.PWM2.b(1) | TRCMR.PWMB.b(1) | TRCMR.PWMC.b(1) | TRCMR.PWMD.b(1); // コンペア一致Aでカウンタクリア TRCCR1 = TRCCR1.CCLR.b(1) | TRCCR1.TOA.b(0) | TRCCR1.CKS.b(static_cast<uint8_t>(cks)) | TRCCR1.TOB.b(0) | TRCCR1.TOC.b(0) | TRCCR1.TOD.b(0); TRCIOR0 = TRCIOR0.IOA.b(0) | TRCIOR0.IOB.b(2); TRCIOR1 = TRCIOR1.IOC.b(8 | 2) | TRCIOR1.IOD.b(8 | 2); TRCCR2 = TRCCR2.POLB.b(pfl) | TRCCR2.POLC.b(pfl) | TRCCR2.POLD.b(pfl); TRCOER = TRCOER.EB.b(0) | TRCOER.EC.b(0) | TRCOER.ED.b(0); ILVL3.B45 = ir_lvl; if(ir_lvl) { TRCIER = TRCIER.IMIEA.b(1); // カウンターAのマッチをトリガーにして割り込み // TRCIER = TRCIER.IMIEB.b(1); // TRCIER = TRCIER.IMIEC.b(1); } else { TRCIER = 0x00; } TRCMR.CTS = 1; // カウント開始 } //-----------------------------------------------------------------// /*! @brief PWMモード開始(最大3チャネルのPWM出力) @param[in] hz 周期(周波数) @param[in] pfl ポートの初期レベル「fasle」0->1、「true」1->0 @param[in] ir_lvl 割り込みレベル(0の場合割り込みを使用しない) @return 設定範囲を超えたら「false」 */ //-----------------------------------------------------------------// bool start_pwm(uint16_t hz, bool pfl, uint8_t ir_lvl = 0) const { // 周波数から最適な、カウント値を計算 uint32_t tn = F_CLK / hz; uint8_t cks = 0; while(tn > 65536) { tn >>= 1; ++cks; if(cks == 4) { tn >>= 1; } if(cks >= 5) return false; } if(tn) --tn; if(tn == 0) return false; start_pwm(tn, static_cast<divide>(cks), pfl, ir_lvl); return true; } //-----------------------------------------------------------------// /*! @brief PWMリミット値を取得 @return リミット値 */ //-----------------------------------------------------------------// uint16_t get_pwm_limit() const { return TRCGRA(); } //-----------------------------------------------------------------// /*! @brief PWM値Bを設定 @param[in] val 値 */ //-----------------------------------------------------------------// void set_pwm_b(uint16_t val) const { if(ILVL3.B45()) { pwm_b_ = val; } else { TRCGRB = val; } } //-----------------------------------------------------------------// /*! @brief PWM値Cを設定 @param[in] val 値 */ //-----------------------------------------------------------------// void set_pwm_c(uint16_t val) const { if(ILVL3.B45()) { pwm_c_ = val; } else { TRCGRC = val; } } //-----------------------------------------------------------------// /*! @brief PWM値Dを設定 @param[in] val 値 */ //-----------------------------------------------------------------// void set_pwm_d(uint16_t val) const { if(ILVL3.B45()) { pwm_d_ = val; } else { TRCGRD = val; } } }; // スタティック実態定義 template<class TASK> TASK trc_io<TASK>::task_; template<class TASK> volatile uint16_t trc_io<TASK>::pwm_b_; template<class TASK> volatile uint16_t trc_io<TASK>::pwm_c_; template<class TASK> volatile uint16_t trc_io<TASK>::pwm_d_; }
24.707207
88
0.428259
hirakuni45
e89e1c6a679412ed71d9ed0608782c41eeaa537d
4,423
hpp
C++
ui/include/common/constants.hpp
fionser/CODA
db234a1e9761d379fb96ae17eef3b77254f8781c
[ "MIT" ]
12
2017-02-24T19:28:07.000Z
2021-02-05T04:40:47.000Z
ui/include/common/constants.hpp
fionser/CODA
db234a1e9761d379fb96ae17eef3b77254f8781c
[ "MIT" ]
1
2017-04-15T03:41:18.000Z
2017-04-24T09:06:15.000Z
ui/include/common/constants.hpp
fionser/CODA
db234a1e9761d379fb96ae17eef3b77254f8781c
[ "MIT" ]
6
2017-05-14T10:12:50.000Z
2021-02-07T03:50:56.000Z
#ifndef CODA_UI_CONST #define CODA_UI_CONST #include <cstring> #include <string.h> #include <vector> #include <sstream> #include <spdlog/spdlog.h> namespace CConst { extern const std::string VER_SERVER; extern const std::string VER_CLIENT; ///////////////////////////////////////////////// // Server cmd arg ///////////////////////////////////////////////// extern const char* S_MAIN_CMD; ///////////////////////////////////////////////// // Client cmd arg ///////////////////////////////////////////////// extern const char* C_MAIN_CMD_INIT; extern const char* C_MAIN_CMD_SEND_KEY; extern const char* C_MAIN_CMD_JOIN; extern const char* C_MAIN_CMD_SEND_DATA; extern const char* C_MAIN_CMD_RECEIVE_RESULT; extern const char* C_SUB_CMD_NET; ///////////////////////////////////////////////// // filesystem ///////////////////////////////////////////////// extern const char SEP_CH_FILE; extern const std::string CH_CRLF; extern const std::string CODA_CONFIG_FILE_NAME; extern const std::string META_DIR_NAME; extern const std::string META_FILE_NAME; extern const std::string SECRET_KEY_FILE_NAME; extern const std::string PUBLIC_KEY_FILE_NAME; extern const std::string CONTEXT_KEY_FILE_NAME; extern const std::string SCHEMA_FILE_NAME; extern const std::string DATA_DIR_NAME; extern const std::string PLAIN_DIR_NAME; extern const std::string UPLOADING_DIR_NAME; extern const std::string CATEGORICAL; extern const std::string ORDINAL; extern const std::string NUMERICAL; extern const std::string RESULT_DIR_NAME; extern const std::string ENC_DIR_NAME; extern const std::string FLAG_FILE_NAME; extern const std::string RESULT_FILE_NAME; extern const std::string CONFIG_FILE_NAME; ///////////////////////////////////////////////// // META keywords ///////////////////////////////////////////////// extern const std::string CFG_KEY_CORE_BIN; extern const std::string CFG_KEY_HOST; extern const std::string CFG_KEY_PORT; extern const std::string CFG_KEY_UNAME; extern const std::string CFG_KEY_DIRECTORY; extern const std::string META_KEY_ANALYST; extern const std::string META_KEY_SESSION_NAME; extern const std::string META_KEY_PROTOCOL; extern const std::string META_KEY_USER_NAMES; ///////////////////////////////////////////////// // Network MSGs ///////////////////////////////////////////////// extern const char* MSG_OK; extern const char* MSG_NG; extern const char* MSG_REQUEST_CMD; extern const char* MSG_ANALYST_NAME; extern const char* MSG_SESSION_NAME; extern const char* MSG_PROTOCOL; extern const char* MSG_USER_NUM; extern const char* MSG_USER_NAME; extern const char* MSG_FILE_TRANS; extern const char* MSG_CLIENT_SERVER; extern const char* MSG_SERVER_CLIENT; ///////////////////////////////////////////////// // local CMDs ///////////////////////////////////////////////// extern const char* CMD_INIT; extern const char* CMD_SEND_PK; extern const char* CMD_JOIN; extern const char* CMD_SEND_DATA; extern const char* CMD_RECV_RESULT; extern const char* CMD_DEBUG; extern const char* CMD_REQ_NUMBER_FILES; extern const char* CMD_REQ_FILE_NAME; extern const char* CMD_REQ_FILE_SIZE; extern const char* CMD_SEND_FILES; extern const char* CMD_RECEIVE_FILES; ///////////////////////////////////////////////// // FILE KEYWORD ///////////////////////////////////////////////// extern const std::string KPATH_DATA; extern const std::string KPATH_META; extern const std::string KPATH_RESULT; extern const std::string KPATH_DEBUG; ///////////////////////////////////////////////// // KEYWORD ///////////////////////////////////////////////// extern const std::string KEYWORD_FSIZE; ///////////////////////////////////////////////// // for windows ///////////////////////////////////////////////// extern std::vector<std::string> split(std::string str, char sep); }; extern std::shared_ptr<spdlog::logger> _console; ///////////////////////////////////////////////// // for windows ///////////////////////////////////////////////// template<class T> std::string to_string(const T&v) { std::ostringstream out; out << v; return out.str(); } #endif
37.483051
69
0.557314
fionser
e8a1d18b3a83ca676a8a0b5e7ac171aa7cd784b8
410
cpp
C++
src/ppl/nn/engines/x86/impls/src/ppl/kernel/x86/fp32/tile/tile_fp32.cpp
weisk/ppl.nn
7dd75a1077867fc9a762449953417088446ae2f8
[ "Apache-2.0" ]
1
2021-10-06T14:39:58.000Z
2021-10-06T14:39:58.000Z
src/ppl/nn/engines/x86/impls/src/ppl/kernel/x86/fp32/tile/tile_fp32.cpp
wolf15/ppl.nn
ac23e5eb518039536f1ef39b43c63d6bda900e77
[ "Apache-2.0" ]
null
null
null
src/ppl/nn/engines/x86/impls/src/ppl/kernel/x86/fp32/tile/tile_fp32.cpp
wolf15/ppl.nn
ac23e5eb518039536f1ef39b43c63d6bda900e77
[ "Apache-2.0" ]
null
null
null
#include "ppl/kernel/x86/common/tile/tile_common.h" namespace ppl { namespace kernel { namespace x86 { ppl::common::RetCode tile_ndarray_fp32( const ppl::nn::TensorShape *src_shape, const ppl::nn::TensorShape *dst_shape, const float *src, const int64_t *repeats, float *dst) { return tile_ndarray<float>(src_shape, dst_shape, src, repeats, dst); } }}}; // namespace ppl::kernel::x86
25.625
72
0.702439
weisk
e8aef86c979343a6e7f0082aeef4d3514476ae91
1,204
cpp
C++
src/Engine/map/chunkKey.cpp
FraMecca/Coccode
e302c400e0bff40859c65ccefac923133c770861
[ "BSD-3-Clause" ]
null
null
null
src/Engine/map/chunkKey.cpp
FraMecca/Coccode
e302c400e0bff40859c65ccefac923133c770861
[ "BSD-3-Clause" ]
null
null
null
src/Engine/map/chunkKey.cpp
FraMecca/Coccode
e302c400e0bff40859c65ccefac923133c770861
[ "BSD-3-Clause" ]
null
null
null
/* * ====================== chunkKey.cpp ======================= * -- tpr -- * CREATE -- 2019.03.06 * MODIFY -- * ---------------------------------------------------------- * Chunk "id": (int)w + (int)h * ---------------------------- */ #include "chunkKey.h" #include "pch.h" //-------------------- Engine --------------------// #include "sectionKey.h" /* =========================================================== * get_chunkIdx_in_section * ----------------------------------------------------------- * 获得 目标chunk 在其 section 中的 idx [left-bottom] * ------ * param: _mpos -- 任意 mapent 的 mpos */ size_t get_chunkIdx_in_section(IntVec2 anyMPos_) noexcept { IntVec2 mposOff = anyMPos_2_chunkMPos(anyMPos_) - anyMPos_2_sectionMPos(anyMPos_); tprAssert((mposOff.x >= 0) && (mposOff.y >= 0)); //- tmp int w = std::abs(mposOff.x) / ENTS_PER_CHUNK<>; int h = std::abs(mposOff.y) / ENTS_PER_CHUNK<>; tprAssert((w >= 0) && (w < CHUNKS_PER_SECTION<>)&&(h >= 0) && (h < CHUNKS_PER_SECTION<>)); //- tmp return (size_t)(h * CHUNKS_PER_SECTION<> + w); }
36.484848
102
0.399502
FraMecca
e8af3160c9fd52ec20acf41b86bade50f4539fb1
3,012
hpp
C++
src/checks/checker.hpp
Aman-Jain-14/customizedMesos-PSDSF-absolute
9cb45f8cdd9983668c3ce01be6e03e36c94eb2ce
[ "Apache-2.0" ]
1
2021-11-04T09:59:25.000Z
2021-11-04T09:59:25.000Z
src/checks/checker.hpp
Aman-Jain-14/customizedMesos-fine
7e1939f29adebec7a6517e115a1f0e7cc79146e1
[ "Apache-2.0" ]
null
null
null
src/checks/checker.hpp
Aman-Jain-14/customizedMesos-fine
7e1939f29adebec7a6517e115a1f0e7cc79146e1
[ "Apache-2.0" ]
null
null
null
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __CHECKER_HPP__ #define __CHECKER_HPP__ #include <string> #include <vector> #include <mesos/mesos.hpp> #include <process/owned.hpp> #include <stout/error.hpp> #include <stout/lambda.hpp> #include <stout/option.hpp> #include <stout/try.hpp> namespace mesos { namespace internal { namespace checks { // Forward declarations. class CheckerProcess; class Checker { public: /** * Attempts to create a `Checker` object. In case of success, checking * starts immediately after initialization. * * @param check The protobuf message definition of a check. * @param callback A callback `Checker` uses to send check status updates * to its owner (usually an executor). * @param taskId The TaskID of the target task. * @param taskPid The target task's pid used to enter the specified * namespaces. * @param namespaces The namespaces to enter prior to performing the check. * @return A `Checker` object or an error if `create` fails. * * @todo A better approach would be to return a stream of updates, e.g., * `process::Stream<CheckStatusInfo>` rather than invoking a callback. */ static Try<process::Owned<Checker>> create( const CheckInfo& checkInfo, const lambda::function<void(const CheckStatusInfo&)>& callback, const TaskID& taskId, const Option<pid_t>& taskPid, const std::vector<std::string>& namespaces); ~Checker(); // Not copyable, not assignable. Checker(const Checker&) = delete; Checker& operator=(const Checker&) = delete; /** * Immediately stops checking. Any in-flight checks are dropped. */ void stop(); private: explicit Checker(process::Owned<CheckerProcess> process); process::Owned<CheckerProcess> process; }; namespace validation { // TODO(alexr): A better place for these functions would be something like // "mesos_validation.cpp", since they validate API protobufs which are not // solely related to this library. Option<Error> checkInfo(const CheckInfo& checkInfo); Option<Error> checkStatusInfo(const CheckStatusInfo& checkStatusInfo); } // namespace validation { } // namespace checks { } // namespace internal { } // namespace mesos { #endif // __CHECKER_HPP__
31.051546
77
0.727756
Aman-Jain-14
e8b15bc5e40acb31f4c9ac48dd859fbedf52c9f9
789
cc
C++
os_taskqueue/criticalsection.cc
sonyangchang/mycodecollection
d56149742f71ae7ae03f5a92bd009edbb4d5d3c6
[ "Apache-2.0" ]
1
2020-10-18T02:00:01.000Z
2020-10-18T02:00:01.000Z
os_taskqueue/criticalsection.cc
sonyangchang/mycodecollection
d56149742f71ae7ae03f5a92bd009edbb4d5d3c6
[ "Apache-2.0" ]
null
null
null
os_taskqueue/criticalsection.cc
sonyangchang/mycodecollection
d56149742f71ae7ae03f5a92bd009edbb4d5d3c6
[ "Apache-2.0" ]
1
2020-10-18T02:00:03.000Z
2020-10-18T02:00:03.000Z
#include "criticalsection.h" namespace rtc{ CriticalSection::CriticalSection() { pthread_mutexattr_t mutex_attribute; pthread_mutexattr_init(&mutex_attribute); pthread_mutexattr_settype(&mutex_attribute, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&mutex_, &mutex_attribute); pthread_mutexattr_destroy(&mutex_attribute); } CriticalSection::~CriticalSection(){ pthread_mutex_destroy(&mutex_); } void CriticalSection::Enter()const{ pthread_mutex_lock(&mutex_); } bool CriticalSection::TryEnter()const{ if (pthread_mutex_trylock(&mutex_)!= 0) return false; } void CriticalSection::Leave()const{ pthread_mutex_unlock(&mutex_); } CritScope::CritScope(const CriticalSection* cs) : cs_(cs) { cs_->Enter(); } CritScope::~CritScope() { cs_->Leave(); } }
30.346154
76
0.754119
sonyangchang
e8b36383bd73d2480ac8ccc9bd0eb0c2641ffaca
4,250
cpp
C++
phxrpc/mqtt/test_mqtt_protocol.cpp
zhoudayang/phxrpc
e3ca0b7ff68a48593866f0b1e7bac78a7107074f
[ "BSD-3-Clause" ]
null
null
null
phxrpc/mqtt/test_mqtt_protocol.cpp
zhoudayang/phxrpc
e3ca0b7ff68a48593866f0b1e7bac78a7107074f
[ "BSD-3-Clause" ]
null
null
null
phxrpc/mqtt/test_mqtt_protocol.cpp
zhoudayang/phxrpc
e3ca0b7ff68a48593866f0b1e7bac78a7107074f
[ "BSD-3-Clause" ]
null
null
null
/* Tencent is pleased to support the open source community by making PhxRPC available. Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://opensource.org/licenses/BSD-3-Clause 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. See the AUTHORS file for names of contributors. */ #include <cassert> #include <csignal> #include <cstdio> #include <cstdlib> #include <cstring> #include <memory> #include <sstream> #include "mqtt_msg.h" #include "mqtt_protocol.h" #include "phxrpc/file/file_utils.h" #include "phxrpc/file/opt_map.h" #include "phxrpc/network/socket_stream_block.h" using namespace phxrpc; using namespace std; void ShowUsage(const char *program) { printf("\n%s [-r CONNECT|PUBLISH|SUBSCRIBE|UNSUBSCRIBE|PING|DISCONNECT] [-f file] [-v]\n", program); printf("\t-r mqtt method, only support CONNECT|PUBLISH|SUBSCRIBE|UNSUBSCRIBE|PING|DISCONNECT\n"); printf("\t-f the file for content\n"); printf("\t-v show this usage\n"); printf("\n"); exit(0); } void TraceMsg(const MqttMessage &msg) { ostringstream ss_req; msg.SendRemaining(ss_req); const string &s_req(ss_req.str()); cout << s_req.size() << ":" << endl; for (int i{0}; s_req.size() > i; ++i) { cout << static_cast<int>(s_req.data()[i]) << "\t"; } cout << endl; for (int i{0}; s_req.size() > i; ++i) { if (isalnum(s_req.data()[i]) || '_' == s_req.data()[i]) { cout << s_req.data()[i] << "\t"; } else { cout << '.' << "\t"; } } cout << endl; } int main(int argc, char *argv[]) { assert(sigset(SIGPIPE, SIG_IGN) != SIG_ERR); OptMap optMap("r:f:v"); if ((!optMap.Parse(argc, argv)) || optMap.Has('v')) { ShowUsage(argv[0]); } const char *method{optMap.Get('r')}; const char *file{optMap.Get('f')}; if (nullptr == method) { printf("\nPlease specify method!\n"); ShowUsage(argv[0]); } int ret{0}; if (0 == strcasecmp(method, "CONNECT")) { cout << "Req:" << endl; TraceMsg(MqttConnect()); cout << "Resp:" << endl; TraceMsg(MqttConnack()); } else if (0 == strcasecmp(method, "PUBLISH")) { cout << "Req:" << endl; MqttPublish publish; publish.set_topic_name("test_topic_1"); publish.set_packet_identifier(11); TraceMsg(publish); cout << "Resp:" << endl; MqttPuback puback; puback.set_packet_identifier(11); TraceMsg(puback); } else if (0 == strcasecmp(method, "SUBSCRIBE")) { cout << "Req:" << endl; TraceMsg(MqttSubscribe()); cout << "Resp:" << endl; TraceMsg(MqttSuback()); } else if (0 == strcasecmp(method, "UNSUBSCRIBE")) { cout << "Req:" << endl; TraceMsg(MqttUnsubscribe()); cout << "Resp:" << endl; TraceMsg(MqttUnsuback()); } else if (0 == strcasecmp(method, "PING")) { cout << "Req:" << endl; TraceMsg(MqttPingreq()); cout << "Resp:" << endl; TraceMsg(MqttPingresp()); } else if (0 == strcasecmp(method, "DISCONNECT")) { cout << "Req:" << endl; TraceMsg(MqttDisconnect()); } else { printf("unsupport method %s\n", method); } //if (0 == ret) { // printf("response:\n"); // printf("%s %d %s\n", response.GetVersion(), response.GetStatusCode(), // response.GetReasonPhrase()); // printf("%zu headers\n", response.GetHeaderCount()); // for (size_t i{0}; i < response.GetHeaderCount(); ++i) { // const char *name{response.GetHeaderName(i)}; // const char *val{response.GetHeaderValue(i)}; // printf("%s: %s\r\n", name, val); // } // printf("%zu bytes body\n", response.GetContent().size()); // if (response.GetContent().size() > 0) { // //printf("%s\n", (char*)response.getContent()); // } //} else { // printf("mqtt request fail\n"); //} return 0; }
24.285714
102
0.616
zhoudayang
e8bde9ffc0bacad6659929f5d0fcb580fed6a4ab
16,041
cpp
C++
conformance_tests/tools/debug/src/test_debug.cpp
vilvarajintel/level-zero-tests
d841c0abbd7f77f9011bd37d1b6180b319a5e35d
[ "MIT" ]
32
2020-03-05T19:26:02.000Z
2022-02-21T13:13:52.000Z
conformance_tests/tools/debug/src/test_debug.cpp
vilvarajintel/level-zero-tests
d841c0abbd7f77f9011bd37d1b6180b319a5e35d
[ "MIT" ]
9
2020-05-04T20:15:09.000Z
2021-12-19T07:17:50.000Z
conformance_tests/tools/debug/src/test_debug.cpp
vilvarajintel/level-zero-tests
d841c0abbd7f77f9011bd37d1b6180b319a5e35d
[ "MIT" ]
19
2020-04-07T16:00:48.000Z
2022-01-19T00:19:49.000Z
/* * * Copyright (C) 2021 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include <boost/filesystem.hpp> #include <boost/process.hpp> #include <boost/interprocess/shared_memory_object.hpp> #include <boost/interprocess/mapped_region.hpp> #include <boost/interprocess/sync/named_condition.hpp> #include "gtest/gtest.h" #include "logging/logging.hpp" #include "utils/utils.hpp" #include "test_harness/test_harness.hpp" #include "test_debug.hpp" namespace lzt = level_zero_tests; #include <level_zero/ze_api.h> #include <level_zero/zet_api.h> namespace fs = boost::filesystem; namespace bp = boost::process; namespace bi = boost::interprocess; namespace { TEST( zetDeviceGetDebugPropertiesTest, GivenValidDeviceWhenGettingDebugPropertiesThenPropertiesReturnedSuccessfully) { auto driver = lzt::get_default_driver(); for (auto device : lzt::get_devices(driver)) { auto device_properties = lzt::get_device_properties(device); auto properties = lzt::get_debug_properties(device); if (ZET_DEVICE_DEBUG_PROPERTY_FLAG_ATTACH & properties.flags == 0) { LOG_INFO << "Device " << device_properties.name << " does not support debug"; } else { LOG_INFO << "Device " << device_properties.name << " supports debug"; } } } TEST( zetDeviceGetDebugPropertiesTest, GivenSubDeviceWhenGettingDebugPropertiesThenPropertiesReturnedSuccessfully) { auto driver = lzt::get_default_driver(); for (auto &device : lzt::get_devices(driver)) { for (auto &sub_device : lzt::get_ze_sub_devices(device)) { auto device_properties = lzt::get_device_properties(sub_device); auto properties = lzt::get_debug_properties(sub_device); if (ZET_DEVICE_DEBUG_PROPERTY_FLAG_ATTACH & properties.flags == 0) { LOG_INFO << "Device " << device_properties.name << " does not support debug"; } else { LOG_INFO << "Device " << device_properties.name << " supports debug"; } } } } class zetDebugAttachDetachTest : public ::testing::Test { protected: void SetUp() override { bi::shared_memory_object::remove("debug_bool"); shm = new bi::shared_memory_object(bi::create_only, "debug_bool", bi::read_write); shm->truncate(sizeof(debug_signals_t)); region = new bi::mapped_region(*shm, bi::read_write); static_cast<debug_signals_t *>(region->get_address())->debugger_signal = false; static_cast<debug_signals_t *>(region->get_address())->debugee_signal = false; bi::named_mutex::remove("debugger_mutex"); mutex = new bi::named_mutex(bi::create_only, "debugger_mutex"); bi::named_condition::remove("debug_bool_set"); condition = new bi::named_condition(bi::create_only, "debug_bool_set"); } void TearDown() override { bi::shared_memory_object::remove("debug_bool"); bi::named_mutex::remove("debugger_mutex"); bi::named_condition::remove("debug_bool_set"); delete shm; delete region; delete mutex; delete condition; } void run_test(std::vector<ze_device_handle_t> devices, bool use_sub_devices); bi::shared_memory_object *shm; bi::mapped_region *region; bi::named_mutex *mutex; bi::named_condition *condition; }; void zetDebugAttachDetachTest::run_test(std::vector<ze_device_handle_t> devices, bool use_sub_devices) { for (auto &device : devices) { auto device_properties = lzt::get_device_properties(device); auto debug_properties = lzt::get_debug_properties(device); ASSERT_TRUE(ZET_DEVICE_DEBUG_PROPERTY_FLAG_ATTACH & debug_properties.flags); fs::path helper_path(fs::current_path() / "debug"); std::vector<fs::path> paths; paths.push_back(helper_path); fs::path helper = bp::search_path("test_debug_helper", paths); bp::opstream child_input; bp::child debug_helper( helper, "--device_id=" + lzt::to_string(device_properties.uuid), (use_sub_devices ? "--use_sub_devices" : ""), bp::std_in < child_input); zet_debug_config_t debug_config = {}; debug_config.pid = debug_helper.id(); auto debug_session = lzt::debug_attach(device, debug_config); // notify debugged process that this process has attached mutex->lock(); static_cast<debug_signals_t *>(region->get_address())->debugger_signal = true; mutex->unlock(); condition->notify_all(); debug_helper.wait(); // we don't care about the child processes exit code at // the moment lzt::debug_detach(debug_session); } } TEST_F( zetDebugAttachDetachTest, GivenDeviceSupportsDebugAttachWhenAttachingThenAttachAndDetachIsSuccessful) { auto driver = lzt::get_default_driver(); auto devices = lzt::get_devices(driver); run_test(devices, false); } TEST_F( zetDebugAttachDetachTest, GivenSubDeviceSupportsDebugAttachWhenAttachingThenAttachAndDetachIsSuccessful) { auto driver = lzt::get_default_driver(); auto devices = lzt::get_devices(driver); std::vector<ze_device_handle_t> all_sub_devices = {}; for (auto &device : devices) { auto sub_devices = lzt::get_ze_sub_devices(device); sub_devices.insert(all_sub_devices.end(), sub_devices.begin(), sub_devices.end()); } run_test(all_sub_devices, true); } class zetDebugEventReadTest : public zetDebugAttachDetachTest { protected: void SetUp() override { zetDebugAttachDetachTest::SetUp(); } void TearDown() override { zetDebugAttachDetachTest::TearDown(); } void run_test(std::vector<ze_device_handle_t> devices, bool use_sub_devices); void run_advanced_test(std::vector<ze_device_handle_t> devices, bool use_sub_devices, debug_test_type_t test_type); }; void zetDebugEventReadTest::run_test(std::vector<ze_device_handle_t> devices, bool use_sub_devices) { for (auto &device : devices) { auto device_properties = lzt::get_device_properties(device); auto debug_properties = lzt::get_debug_properties(device); ASSERT_TRUE(ZET_DEVICE_DEBUG_PROPERTY_FLAG_ATTACH & debug_properties.flags); fs::path helper_path(fs::current_path() / "debug"); std::vector<fs::path> paths; paths.push_back(helper_path); fs::path helper = bp::search_path("test_debug_helper", paths); bp::opstream child_input; bp::child debug_helper( helper, "--device_id=" + lzt::to_string(device_properties.uuid), (use_sub_devices ? "--use_sub_devices" : ""), bp::std_in < child_input); zet_debug_config_t debug_config = {}; debug_config.pid = debug_helper.id(); auto debug_session = lzt::debug_attach(device, debug_config); // notify debugged process that this process has attached mutex->lock(); static_cast<debug_signals_t *>(region->get_address())->debugger_signal = true; mutex->unlock(); condition->notify_all(); // listen for events generated by child process operation std::vector<zet_debug_event_type_t> expected_event = { ZET_DEBUG_EVENT_TYPE_PROCESS_ENTRY, ZET_DEBUG_EVENT_TYPE_MODULE_LOAD, ZET_DEBUG_EVENT_TYPE_MODULE_UNLOAD, ZET_DEBUG_EVENT_TYPE_PROCESS_EXIT, ZET_DEBUG_EVENT_TYPE_DETACHED}; auto event_num = 0; while (true) { auto debug_event = lzt::debug_read_event( debug_session, std::numeric_limits<uint64_t>::max()); EXPECT_EQ(debug_event.type, expected_event[event_num++]); if (debug_event.flags & ZET_DEBUG_EVENT_FLAG_NEED_ACK) { lzt::debug_ack_event(debug_session, &debug_event); } if (ZET_DEBUG_EVENT_TYPE_DETACHED == debug_event.type) { EXPECT_EQ(debug_event.info.detached.reason, ZET_DEBUG_DETACH_REASON_HOST_EXIT); break; } } lzt::debug_detach(debug_session); debug_helper.wait(); } } TEST_F( zetDebugEventReadTest, GivenDebugCapableDeviceWhenProcessIsBeingDebuggedThenCorrectEventsAreRead) { auto driver = lzt::get_default_driver(); auto devices = lzt::get_devices(driver); run_test(devices, false); } TEST_F( zetDebugEventReadTest, GivenDebugCapableSubDeviceWhenProcessIsBeingDebuggedThenCorrectEventsAreRead) { auto driver = lzt::get_default_driver(); auto devices = lzt::get_devices(driver); std::vector<ze_device_handle_t> all_sub_devices = {}; for (auto &device : devices) { auto sub_devices = lzt::get_ze_sub_devices(device); sub_devices.insert(all_sub_devices.end(), sub_devices.begin(), sub_devices.end()); } run_test(all_sub_devices, true); } //===================================================================================================== void zetDebugEventReadTest::run_advanced_test( std::vector<ze_device_handle_t> devices, bool use_sub_devices, debug_test_type_t test_type) { std::string test_options = ""; for (auto &device : devices) { auto device_properties = lzt::get_device_properties(device); auto debug_properties = lzt::get_debug_properties(device); ASSERT_TRUE(ZET_DEVICE_DEBUG_PROPERTY_FLAG_ATTACH & debug_properties.flags); fs::path helper_path(fs::current_path() / "debug"); std::vector<fs::path> paths; paths.push_back(helper_path); fs::path helper = bp::search_path("test_debug_helper", paths); bp::opstream child_input; bp::child debug_helper( helper, "--device_id=" + lzt::to_string(device_properties.uuid), (use_sub_devices ? "--use_sub_devices" : ""), "--test_type" + test_type, bp::std_in < child_input); zet_debug_config_t debug_config = {}; debug_config.pid = debug_helper.id(); auto debug_session = lzt::debug_attach(device, debug_config); // notify debugged process that this process has attached mutex->lock(); (static_cast<debug_signals_t *>(region->get_address()))->debugger_signal = true; mutex->unlock(); condition->notify_all(); std::vector<zet_debug_event_type_t> events = {}; auto event_num = 0; while (true) { auto debug_event = lzt::debug_read_event( debug_session, std::numeric_limits<uint64_t>::max()); events.push_back(debug_event.type); if (debug_event.flags & ZET_DEBUG_EVENT_FLAG_NEED_ACK) { lzt::debug_ack_event(debug_session, &debug_event); } if (ZET_DEBUG_EVENT_TYPE_DETACHED == debug_event.type) { EXPECT_EQ(debug_event.info.detached.reason, ZET_DEBUG_DETACH_REASON_HOST_EXIT); break; } } switch (test_type) { case THREAD_STOPPED: ASSERT_TRUE(std::find(events.begin(), events.end(), ZET_DEBUG_EVENT_TYPE_THREAD_STOPPED) != events.end()); break; case THREAD_UNAVAILABLE: ASSERT_TRUE(std::find(events.begin(), events.end(), ZET_DEBUG_EVENT_TYPE_THREAD_UNAVAILABLE) != events.end()); break; case PAGE_FAULT: ASSERT_TRUE(std::find(events.begin(), events.end(), ZET_DEBUG_EVENT_TYPE_PAGE_FAULT) != events.end()); break; default: break; } lzt::debug_detach(debug_session); debug_helper.wait(); } } TEST_F(zetDebugEventReadTest, GivenDeviceWhenThenAttachingAfterModuleCreatedThenEventReceived) { auto driver = lzt::get_default_driver(); auto devices = lzt::get_devices(driver); for (auto &device : devices) { auto device_properties = lzt::get_device_properties(device); auto debug_properties = lzt::get_debug_properties(device); ASSERT_TRUE(ZET_DEVICE_DEBUG_PROPERTY_FLAG_ATTACH & debug_properties.flags); fs::path helper_path(fs::current_path() / "debug"); std::vector<fs::path> paths; paths.push_back(helper_path); fs::path helper = bp::search_path("test_debug_helper", paths); bp::opstream child_input; bp::child debug_helper( helper, "--device_id=" + lzt::to_string(device_properties.uuid), "--test_type=" + ATTACH_AFTER_MODULE_CREATED, bp::std_in < child_input); zet_debug_config_t debug_config = {}; debug_config.pid = debug_helper.id(); bi::scoped_lock<bi::named_mutex> lock(*mutex); // wait until child says module created LOG_INFO << "Waiting for Child to create module"; condition->wait(lock, [&] { return (static_cast<debug_signals_t *>(region->get_address()) ->debugee_signal); }); LOG_INFO << "Debugged process proceeding"; auto debug_session = lzt::debug_attach(device, debug_config); // notify debugged process that this process has attached mutex->lock(); static_cast<debug_signals_t *>(region->get_address())->debugger_signal = true; mutex->unlock(); condition->notify_all(); auto event_found = false; while (true) { auto debug_event = lzt::debug_read_event( debug_session, std::numeric_limits<uint64_t>::max()); if (ZET_DEBUG_EVENT_TYPE_MODULE_LOAD == debug_event.type) { event_found = true; } if (debug_event.flags & ZET_DEBUG_EVENT_FLAG_NEED_ACK) { lzt::debug_ack_event(debug_session, &debug_event); } if (ZET_DEBUG_EVENT_TYPE_DETACHED == debug_event.type) { EXPECT_EQ(debug_event.info.detached.reason, ZET_DEBUG_DETACH_REASON_HOST_EXIT); break; } } lzt::debug_detach(debug_session); debug_helper.wait(); ASSERT_TRUE(event_found); } } TEST_F(zetDebugEventReadTest, GivenDeviceWhenCreatingMultipleModulesThenMultipleEventsReceived) { auto driver = lzt::get_default_driver(); auto devices = lzt::get_devices(driver); run_advanced_test(devices, false, MULTIPLE_MODULES_CREATED); } TEST_F( zetDebugEventReadTest, GivenDebugEnabledDeviceWhenAttachingAfterCreatingAndDestroyingModuleThenNoEventReceived) { auto driver = lzt::get_default_driver(); auto devices = lzt::get_devices(driver); run_advanced_test(devices, false, ATTACH_AFTER_MODULE_DESTROYED); } TEST_F(zetDebugEventReadTest, GivenDebugAttachedWhenInterruptLongRunningKernelThenStopEventReceived) { auto driver = lzt::get_default_driver(); auto devices = lzt::get_devices(driver); run_advanced_test(devices, false, LONG_RUNNING_KERNEL_INTERRUPTED); } TEST_F(zetDebugEventReadTest, GivenKernelWithBreakpointsWhenDebugAttachedThenStoppedEventReceived) { auto driver = lzt::get_default_driver(); auto devices = lzt::get_devices(driver); run_advanced_test(devices, false, BREAKPOINTS); } TEST_F(zetDebugEventReadTest, GivenDebugAttachedWhenCallingResumeThenKernelCompletes) { /* *after stopped event, call resume - kernel should finish */ } TEST_F(zetDebugEventReadTest, GivenCalledInterruptAndResumeWhenKernelExecutingThenKernelCompletes) { auto driver = lzt::get_default_driver(); auto devices = lzt::get_devices(driver); run_advanced_test(devices, false, KERNEL_RESUME); } TEST_F(zetDebugEventReadTest, GivenDebugEnabledWhenCallingInterruptTwiceSecondInterruptIsBlocked) { /* *call interrupt , call second interrupt for the second time - second interrupt should be blocked until thread stopped/thread unavailable events are available. */ } TEST_F(zetDebugEventReadTest, GivenDeviceExceptionOccursWhenAttachedThenThreadStoppedEventReceived) { auto driver = lzt::get_default_driver(); auto devices = lzt::get_devices(driver); run_advanced_test(devices, false, THREAD_STOPPED); } TEST_F(zetDebugEventReadTest, GivenThreadUnavailableWhenDebugEnabledThenThreadUnavailableEventRead) { auto driver = lzt::get_default_driver(); auto devices = lzt::get_devices(driver); run_advanced_test(devices, false, THREAD_UNAVAILABLE); } TEST_F(zetDebugEventReadTest, GivenPageFaultInHelperWhenDebugEnabledThenPageFaultEventRead) { auto driver = lzt::get_default_driver(); auto devices = lzt::get_devices(driver); run_advanced_test(devices, false, PAGE_FAULT); } } // namespace
32.537525
103
0.700081
vilvarajintel
e8c1e3d5b22da0eb4a878676a6037d3990b59567
889
cc
C++
prob05/header.cc
crimsonGnome/121-Lab-02
8f5152d902fe71372f4738cdaa33e6378b88482a
[ "MIT" ]
null
null
null
prob05/header.cc
crimsonGnome/121-Lab-02
8f5152d902fe71372f4738cdaa33e6378b88482a
[ "MIT" ]
null
null
null
prob05/header.cc
crimsonGnome/121-Lab-02
8f5152d902fe71372f4738cdaa33e6378b88482a
[ "MIT" ]
null
null
null
// Name: Joseph Eggers // CWID: 885939488 // Email: [email protected] #include "header.h" #include <iostream> #include <string> using std::cout, std::string; void DisplayHeader(string txt) { // Declare Variabeles string asteriskMaker; // This makes the srtring +4 due to the "* " and " *" asterisk and the space const int asteriskCushion = 4; // Loop length + the 4 extra characters const int loopLength = txt.length() + asteriskCushion; // for loop making the Asterisk lines for (int i = 0; i < loopLength; i++) { asteriskMaker.append("*"); } // cout box cout << asteriskMaker << "\n* " << txt << " *\n" << asteriskMaker << "\n"; } bool WithinWidth(string txt, unsigned short x) { // if the the length of the the text is less then are = to the width display // true else return false if (txt.length() <= x) return true; return false; }
27.78125
78
0.661417
crimsonGnome
e8c49e53a9e9aa70c0e9a227745b4db10222d56e
1,457
cpp
C++
Xcode/examples/Mitsudesmas/src/MapObject.cpp
YotioSoft/Mitsudesmas
ea9b98a46321ac268ad2ed35460081d2ae8ad3b8
[ "MIT" ]
null
null
null
Xcode/examples/Mitsudesmas/src/MapObject.cpp
YotioSoft/Mitsudesmas
ea9b98a46321ac268ad2ed35460081d2ae8ad3b8
[ "MIT" ]
null
null
null
Xcode/examples/Mitsudesmas/src/MapObject.cpp
YotioSoft/Mitsudesmas
ea9b98a46321ac268ad2ed35460081d2ae8ad3b8
[ "MIT" ]
null
null
null
#include "MapObject.h" MapObject::MapObject(){} MapObject::MapObject(String init_name, MapChipProfiles::Types init_type) { name = init_name; type = init_type; } MapObject::MapObject(String init_name, MapChipProfiles::Types init_type, MapChip &init_chip) { name = init_name; type = init_type; chips << init_chip; } MapObject::MapObject(String init_name, MapChipProfiles::Types init_type, Array<MapChip> &init_chips) { name = init_name; type = init_type; chips = init_chips; } void MapObject::addMapChip(MapChip init_chip) { chips << init_chip; } void MapObject::setObjectSize(Size new_size) { size = new_size; } Size MapObject::getObjectSize() { return size; } String MapObject::getName() { return name; } Array<MapChipProfiles::Directions> MapObject::getDirections() { Array<MapChipProfiles::Directions> ret_array; for (int i = 0; i < chips.size(); i++) { ret_array << chips[i].getDirection(); } return ret_array; } MapChipProfiles::Types MapObject::getType() { return type; } MapChip* MapObject::getChipP(MapChipProfiles::Directions direction) { for (int i = 0; i < chips.size(); i++) { if (chips[i].getDirection() == direction) { return &chips[i]; } } return nullptr; } bool MapObject::draw(const MapChipProfiles::Directions direction, const Point position) { for (int i = 0; i < chips.size(); i++) { if (chips[i].getDirection() == direction) { chips[i].draw(position); return true; } } return false; }
22.075758
102
0.704873
YotioSoft
e8c5ed6c8d81526e642349277b07c492e56bc4f2
4,796
cpp
C++
src/DirUtils.cpp
Karolpg/camera_monitoring
9e13e25757408be86b49b5e9b1756fea1429fac7
[ "MIT" ]
null
null
null
src/DirUtils.cpp
Karolpg/camera_monitoring
9e13e25757408be86b49b5e9b1756fea1429fac7
[ "MIT" ]
null
null
null
src/DirUtils.cpp
Karolpg/camera_monitoring
9e13e25757408be86b49b5e9b1756fea1429fac7
[ "MIT" ]
null
null
null
// // The MIT License (MIT) // // Copyright 2020 Karolpg // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation the rights to #use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR #COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #include "DirUtils.h" #include <sys/stat.h> #include <sys/dir.h> #include <errno.h> #include <iostream> #include <fstream> namespace DirUtils { std::string cleanPath(const std::string &path) { size_t searchFrom = 0; size_t searchSlash = path.find('/', searchFrom); if (searchSlash == std::string::npos) return path; std::string cleanedPath; cleanedPath.reserve(path.length()); //allocate memory for(;searchSlash != std::string::npos;) { //copy values between slashes and also one slash for (auto i = searchFrom; i <= searchSlash; ++i) { cleanedPath += path[i]; } //skip multiple slashes searchFrom = path.find_first_not_of('/', searchSlash + 1); if (searchFrom == std::string::npos) { // only slashes rest - everything is already copied return cleanedPath; } //search next slash searchSlash = path.find('/', searchFrom); } // there is no more slashes - just cpy rest of path for (auto i = searchFrom; i < path.length(); ++i) { cleanedPath += path[i]; } return cleanedPath; } bool isDir(const std::string& path) { struct stat info; if (stat(path.c_str(), &info) != 0) { return false; } return (info.st_mode & S_IFDIR) != 0; } bool isFile(const std::string& filepath) { struct stat info; if (stat(filepath.c_str(), &info) != 0) { return false; } return (info.st_mode & S_IFREG) != 0; // REG == regular file } bool makePath(const std::string &path, uint32_t mode) { if (path.empty()) { return true; // empty path should already exist it is working directory } if (isDir(path)) { return true; // already exist } if (!mkdir(path.c_str(), mode)) return true; if (errno == ENOENT) // parent doesn't exist { auto notSeparator = path.find_last_not_of('/'); if (notSeparator == std::string::npos) return false; // only slashes in path - it is root - we can't create it auto separatorPos = path.find_last_of('/', notSeparator); if (separatorPos == std::string::npos) return false; // strange but we are just not able to create dir and there is no more supdirs notSeparator = path.find_last_not_of('/', separatorPos - 1); // skip many slashes if (notSeparator == std::string::npos) return false; // only separators rest if (!makePath(path.substr(0, notSeparator+1))) return false; //all subdirs are created - retry to create expected dir if (!mkdir(path.c_str(), mode)) return true; } else { std::cerr << "Can't create dir errno: " << errno << "\n"; } return false; } size_t file_size(const std::string& filePath) { std::fstream file; file.open(filePath, std::ios_base::in|std::ios_base::binary); if (!file.is_open()) { return 0; } file.seekg(0, std::ios_base::end); auto result = file.tellg(); file.close(); return result < 0 ? 0 : size_t(result); } std::vector<std::string> listDir(const std::string &path) { if (!isDir(path)) { return std::vector<std::string>(); } std::vector<std::string> result; DIR *dir = opendir(path.c_str()); if (dir != nullptr) { struct dirent *ent = readdir(dir); while (ent != nullptr) { result.push_back(ent->d_name); ent = readdir(dir); } closedir (dir); } else { std::cerr << "Can NOT open directory: " << path << "\n"; } return result; } } // namespace DirUtils
31.973333
162
0.623853
Karolpg
e8c7e9216658dde41bce090feebe55dc4e7ae886
6,612
cpp
C++
Blatt_02/Wettervorhersage.cpp
KevSed/Computational_Physics
6ebfcd07ae5ceb2bfe5b429e8d1425b6877037d1
[ "MIT" ]
null
null
null
Blatt_02/Wettervorhersage.cpp
KevSed/Computational_Physics
6ebfcd07ae5ceb2bfe5b429e8d1425b6877037d1
[ "MIT" ]
null
null
null
Blatt_02/Wettervorhersage.cpp
KevSed/Computational_Physics
6ebfcd07ae5ceb2bfe5b429e8d1425b6877037d1
[ "MIT" ]
null
null
null
/* * Wettervorhersage.cpp * * Created on: 02.05.2017 * Author: mona */ #include <iostream> #include <iomanip> #include <complex> #include <cstdlib> #include <vector> #include <cmath> #include <sstream> #include <utility> #include <math.h> #include <fstream> #include <functional> using namespace std; //**************************************** // Definition des Startvektors und des DGL-Systems //**************************************** vector<double> DGL_start={-10,15,19}; //Vektor der Startwerte vector<double> f(vector<double> DGL, double sigma, double r, double b){ double fx=sigma*(-DGL[0]+DGL[1]); double fy=-DGL[0]*DGL[2]+r*DGL[0]-DGL[1]; double fz=DGL[0]*DGL[1]-b*DGL[2]; DGL={fx,fy,fz}; return DGL; } //**************************************** // Aufgabenteil a) Integration des gleichungssystems mit dem Euler verfahren und Ausgabe von 3 Textdateien, // welche die werte für N={10,100,1000} ausgibt. //**************************************** void euler(vector<double> DGL, double h1, double h2, double h3, double N, double sigma, double r, double b){ vector<double> DGL_1=DGL; vector<double> DGL_2=DGL; vector<double> DGL_3=DGL; // =============================== ofstream a; a.open("Wetter_h1.txt"); a.precision(10);// // =============================== for(double n=1; n<=N; n++){ vector<double> func1=f(DGL_1,sigma,r,b); double x=DGL_1[0]+h1*func1[0]; double y=DGL_1[1]+h1*func1[1]; double z=DGL_1[2]+h1*func1[2]; if(n==10 || n==100 || n==1000){ a << n << "\t" << h1*n << "\t" << x << "\t" << y << "\t" << z << endl; } DGL_1={x,y,z}; } a.close(); // =============================== ofstream c; c.open("Wetter_h2.txt"); c.precision(10);// // =============================== for(double n=1; n<=N; n++){ vector<double> func2=f(DGL_2,sigma,r,b); double x=DGL_2[0]+h2*func2[0]; double y=DGL_2[1]+h2*func2[1]; double z=DGL_2[2]+h2*func2[2]; if(n==10 || n==100 || n==1000){ c << n << "\t" << h2*n << "\t" << x << "\t" << y << "\t" << z << endl; } DGL_2={x,y,z}; } c.close(); // =============================== ofstream d; d.open("Wetter_h3.txt"); d.precision(10);// // =============================== for(double n=1; n<=N; n++){ vector<double> func3=f(DGL_3,sigma,r,b); double x=DGL_3[0]+h3*func3[0]; double y=DGL_3[1]+h3*func3[1]; double z=DGL_3[2]+h3*func3[2]; if(n==10 || n==100 || n==1000){ d << n << "\t" << h3*n << "\t" << x << "\t" << y << "\t" << z << endl; } DGL_3={x,y,z}; } d.close(); } //**************************************** // Aufgabenteil b) und c) Ausgabe von Datensätzen für x und y für verschiedene r und Startwerte //**************************************** void euler_plot(vector<double> DGL, double h, double N, double sigma, double r1, double r2, double b){ vector<double> DGL_1=DGL; vector<double> DGL_2=DGL; // =============================== ofstream a; a.open("Wetter_plotr20.txt"); a.precision(10);// // =============================== for(double n=1; n<=N; n++){ vector<double> func1=f(DGL_1,sigma,r1,b); double x=DGL_1[0]+h*func1[0]; double y=DGL_1[1]+h*func1[1]; double z=DGL_1[2]+h*func1[2]; a << n << "\t" << h*n << "\t" << x << "\t" << y << endl; DGL_1={x,y,z}; } a.close(); // =============================== ofstream c; c.open("Wetter_plotr28.txt"); c.precision(10);// // =============================== for(double n=1; n<=N; n++){ vector<double> func2=f(DGL_2,sigma,r2,b); double x=DGL_2[0]+h*func2[0]; double y=DGL_2[1]+h*func2[1]; double z=DGL_2[2]+h*func2[2]; c << n << "\t" << h*n << "\t" << x << "\t" << y << endl; DGL_2={x,y,z}; } c.close(); // Aufgabenteil c) vector<double> DGL_3={-10.01,15,19}; // =============================== ofstream d; d.open("Wetter_plotr20_c.txt"); d.precision(10);// // =============================== for(double n=1; n<=N; n++){ vector<double> func3=f(DGL_3,sigma,r1,b); double x=DGL_3[0]+h*func3[0]; double y=DGL_3[1]+h*func3[1]; double z=DGL_3[2]+h*func3[2]; d << n << "\t" << h*n << "\t" << x << "\t" << y << endl; DGL_3={x,y,z}; } d.close(); } //**************************************** // Aufgabenteil d) Numerische Ermittlung des Fixpunktes als letzten Wert //**************************************** vector<double> euler_Fixpunkt(vector<double> DGL, double h, double N, double sigma, double r, double b){ vector<double> DGL_1=DGL; double x_alt=DGL_1[0]; double y_alt=DGL_1[1]; double z_alt=DGL_1[2]; double x; double y; double z; double variation=0.00001; for(double n=1; n<=N; n++){ vector<double> func1=f(DGL_1,sigma,r,b); x=DGL_1[0]+h*func1[0]; y=DGL_1[1]+h*func1[1]; z=DGL_1[2]+h*func1[2]; if(abs(x_alt-x)<variation && abs(y_alt-y)<variation && abs(z_alt-z)<variation){ cout << "fixpunkt bei x = " << x << " , y = " << y << " , z = " << z << endl; break; } x_alt=x; y_alt=y; z_alt=z; DGL_1={x,y,z}; } vector<double> letzterWert= {x,y,z}; return letzterWert; } int main(){ double r=20; double sigma=10; double b= 8./3.; //Wird sonst behandelt wie ein Integer euler(DGL_start,0.05,0.005,0.0005,1000,sigma,r,b); euler_plot(DGL_start,0.01,1e5,sigma,20,28,b); //Berechnung des analytischen Fixpunktes double Fix_20= sqrt(b*(20-1)); double Fix_28= sqrt(b*(28-1)); cout << scientific << setprecision(8)<< "Analytisch berechneter Fixpunkt bei r=20: " << "\t" << Fix_20 << endl; cout << scientific << setprecision(8)<< "Analytisch berechneter Fixpunkt bei r=28: " << "\t" << Fix_28 << endl << endl << endl; // Numerische berechnung der Fixpunkte cout << scientific << setprecision(8)<< "Fixpunkt bei r=20, Start=(-10,15,19): " << "\t" ; vector<double> letzter=euler_Fixpunkt(DGL_start,0.001,1e5,sigma,20,b); cout << "Letzter erreichter Wert: " << "\t" << letzter[0] <<"\t" << letzter[1]<<"\t" << letzter[2] << endl ; //Fehler für x double x_Fehler=abs(-letzter[0]-Fix_20)/Fix_20; double y_Fehler=abs(-letzter[1]-Fix_20)/Fix_20; cout << "Fehler fuer x: " << "\t" << x_Fehler <<"\t" << "Fehler fuer y:"<<"\t" << y_Fehler << endl << endl; cout << "Fixpunkt bei r=20, Start=(10.01,15,19): " << "\t" ; vector<double> DGL_start_neu={10.01,15,19}; //Neuer Vektor der Startwerte letzter=euler_Fixpunkt(DGL_start_neu,0.001,1e5,sigma,20,b); x_Fehler=abs(letzter[0]-Fix_20)/Fix_20; y_Fehler=abs(letzter[1]-Fix_20)/Fix_20; cout << "Letzter erreichter Wert: " << "\t" << letzter[0] <<"\t" << letzter[1]<<"\t" << letzter[2] << endl << endl; cout << "Fehler fuer x: " << "\t" << x_Fehler <<"\t" << "Fehler fuer y:"<<"\t" << y_Fehler << endl << endl; return 0; }
27.781513
129
0.536449
KevSed
e8d06526748e64d0829368791af01f52b62f0441
2,002
hpp
C++
actor.hpp
shane-powell/blit-racers
332ed871bd96d6193ae22cdf419dbb6b189eccee
[ "MIT" ]
null
null
null
actor.hpp
shane-powell/blit-racers
332ed871bd96d6193ae22cdf419dbb6b189eccee
[ "MIT" ]
null
null
null
actor.hpp
shane-powell/blit-racers
332ed871bd96d6193ae22cdf419dbb6b189eccee
[ "MIT" ]
null
null
null
#pragma once #include <32blit.hpp> #include "tiledata.hpp" #include "util.hpp" #include "track.hpp" #include "animation.hpp" class Actor { public: virtual ~Actor() = default; blit::Size size; blit::Rect spriteLocation; float x = 0.0f; float y = 0.0f; blit::Vec2 camera; float degrees = 270.0f; std::map<float, blit::Rect> sprites; uint8_t inputDelay = 0; bool moveEnabled = true; bool lockSpeed = false; const uint8_t STEERINGDELAYMIN = 3; const uint8_t STEERINGDELAYMAX = 5; float prevX = 0.0f; float prevY = 0.0f; blit::Vec2 movement; float speedMultiplier = 0.0; TileScanData currentTileData; uint8_t currentCheckpoint = 1; uint32_t lapTime = 0; std::vector<uint32_t> completedLapTimes; bool isPlayer = false; uint8_t targetNode; uint8_t carNumber = 0; uint8_t position = 0; bool sorted = false; std::function<Position& (uint8_t currentCheckpoint)> getNextTargetCheckpoint; //Animation* animation = nullptr; std::queue<Animation*> animationQueue; Vec2 scale = Vec2(1, 1); Actor() = default; Actor(float xIn, float yIn) { this->x = xIn; this->y = yIn; movement = blit::Vec2(0, 1); this->GenerateSpriteMap(180); } Actor(Position gridPosition, blit::Rect spriteLocation, blit::Size size, uint8_t targetNode, uint8_t carNumber, std::function<Position& (uint8_t currentCheckpoint)> getNextTargetCheckpoint, bool isPlayer = false) { this->SetLocation(gridPosition); this->spriteLocation = spriteLocation; this->size = size; this->isPlayer = isPlayer; this->targetNode = targetNode; movement = blit::Vec2(0, 1); this->GenerateSpriteMap(180); this->carNumber = carNumber; this->getNextTargetCheckpoint = getNextTargetCheckpoint; } void GenerateSpriteMap(float angle); void ProcessTileData(Track* currentTrack); void SetLocation(Position gridPosition); void Respawn(); void Animate(); blit::Point GetPosition(); void Rotate(float rotation); static bool SortByPosition(const Actor* carA, const Actor* carB); };
21.073684
213
0.723277
shane-powell
e8d0bddd9d26de757c21fd9dfb9c583a66ed3c47
7,740
hpp
C++
ajg/synth/engines/options.hpp
ajg/synth
8b9bc9d33f97a40190324108e1e6697f85f19b31
[ "BSL-1.0" ]
36
2015-01-10T02:23:13.000Z
2020-05-31T07:41:02.000Z
ajg/synth/engines/options.hpp
ajg/synth
8b9bc9d33f97a40190324108e1e6697f85f19b31
[ "BSL-1.0" ]
3
2015-12-29T04:19:20.000Z
2018-03-27T04:36:34.000Z
ajg/synth/engines/options.hpp
ajg/synth
8b9bc9d33f97a40190324108e1e6697f85f19b31
[ "BSL-1.0" ]
6
2015-01-10T02:23:18.000Z
2019-09-23T15:25:33.000Z
// (C) Copyright 2014 Alvaro J. Genial (http://alva.ro) // Use, modification and distribution are subject to the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt). #ifndef AJG_SYNTH_ENGINES_BASE_OPTIONS_HPP_INCLUDED #define AJG_SYNTH_ENGINES_BASE_OPTIONS_HPP_INCLUDED #include <map> #include <stack> #include <vector> #include <utility> #include <ajg/synth/cache.hpp> namespace ajg { namespace synth { namespace engines { // // options // TODO: Move out of engines namespace/directory. //////////////////////////////////////////////////////////////////////////////////////////////////// template <class Context> struct options { public: typedef Context context_type; typedef options options_type; typedef typename context_type::value_type value_type; typedef typename context_type::data_type data_type; typedef typename context_type::metadata_type metadata_type; typedef typename value_type::range_type range_type; typedef typename value_type::sequence_type sequence_type; typedef typename value_type::association_type association_type; typedef typename value_type::arguments_type arguments_type; typedef typename value_type::traits_type traits_type; typedef typename traits_type::boolean_type boolean_type; typedef typename traits_type::char_type char_type; typedef typename traits_type::size_type size_type; typedef typename traits_type::integer_type integer_type; typedef typename traits_type::floating_type floating_type; typedef typename traits_type::number_type number_type; typedef typename traits_type::date_type date_type; typedef typename traits_type::datetime_type datetime_type; typedef typename traits_type::duration_type duration_type; typedef typename traits_type::string_type string_type; typedef typename traits_type::url_type url_type; typedef typename traits_type::symbols_type symbols_type; typedef typename traits_type::path_type path_type; typedef typename traits_type::paths_type paths_type; typedef typename traits_type::names_type names_type; typedef typename traits_type::formats_type formats_type; typedef typename traits_type::istream_type istream_type; typedef typename traits_type::ostream_type ostream_type; struct abstract_library; struct abstract_loader; struct abstract_resolver; // TODO[c++11]: Use unique_ptr (scoped_ptr won't work because it isn't container-friendly.) typedef boost::shared_ptr<abstract_library> library_type; typedef boost::shared_ptr<abstract_loader> loader_type; typedef boost::shared_ptr<abstract_resolver> resolver_type; // TODO: Rename builtin_tags::tag_type/builtin_filters::filter_type to make less ambiguous. typedef boost::function<void(arguments_type const&, ostream_type&, context_type&)> renderer_type; typedef std::pair<std::vector<string_type>, renderer_type> segment_type; typedef std::vector<segment_type> segments_type; typedef boost::function<value_type(value_type const&, arguments_type const&, context_type&)> filter_type; typedef struct tag { boost::function<renderer_type(segments_type const&)> function; // string_type/* symbol_type */ first_name; symbols_type middle_names; symbols_type last_names; boolean_type pure; tag() : pure(false) {} inline operator boolean_type() const { return this->function; } } tag_type; typedef std::map<string_type, tag_type> tags_type; typedef std::map<string_type, filter_type> filters_type; typedef std::map<size_type, renderer_type> renderers_type; typedef std::map<string_type, library_type> libraries_type; typedef std::vector<loader_type> loaders_type; typedef std::vector<resolver_type> resolvers_type; typedef struct { size_type position; tag_type tag; segments_type segments; // boolean_type proceed; } entry_type; typedef std::stack<entry_type> entries_type; typedef caching_mask caching_type; public: options() : debug(false), caching(caching_none) {} public: // TODO: Subsume metadata with: // context_type context; metadata_type metadata; // defaults boolean_type debug; paths_type directories; libraries_type libraries; loaders_type loaders; resolvers_type resolvers; caching_type caching; }; template <class Value> struct options<Value>::abstract_library { public: virtual boolean_type has_tag(string_type const& name) const = 0; virtual boolean_type has_filter(string_type const& name) const = 0; virtual names_type list_tags() const = 0; virtual names_type list_filters() const = 0; virtual tag_type get_tag(string_type const& name) = 0; virtual filter_type get_filter(string_type const& name) = 0; virtual ~abstract_library() {} }; template <class Value> struct options<Value>::abstract_loader { public: virtual library_type load_library(string_type const& name) = 0; virtual ~abstract_loader() {} }; template <class Value> struct options<Value>::abstract_resolver { public: virtual url_type resolve( string_type const& path , context_type const& context , options_type const& options ) = 0; virtual url_type reverse( string_type const& name , arguments_type const& arguments , context_type const& context , options_type const& options ) = 0; virtual ~abstract_resolver() {} }; }}} // namespace ajg::synth::engines #endif // AJG_SYNTH_ENGINES_BASE_OPTIONS_HPP_INCLUDED
46.347305
111
0.537209
ajg
e8dce509d13c2fbe2b80ef81ff47b784c7dfd649
1,765
cpp
C++
Data Structure Problems/CF-Sereja and Brackets.cpp
Sohieeb/competitive-programming
fe3fca0d4d2a242053d097c7ae71667a135cfc45
[ "MIT" ]
1
2020-01-30T20:08:24.000Z
2020-01-30T20:08:24.000Z
Data Structure Problems/CF-Sereja and Brackets.cpp
Sohieb/competitive-programming
fe3fca0d4d2a242053d097c7ae71667a135cfc45
[ "MIT" ]
null
null
null
Data Structure Problems/CF-Sereja and Brackets.cpp
Sohieb/competitive-programming
fe3fca0d4d2a242053d097c7ae71667a135cfc45
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using namespace __gnu_cxx; typedef double db; typedef long long ll; typedef pair<int,int> ii; #define F first #define S second #define pnl printf("\n") #define sz(x) (int)x.size() #define sf(x) scanf("%d",&x) #define pf(x) printf("%d\n",x) #define all(x) x.begin(),x.end() #define rall(x) x.rbegin(),x.rend() #define FOR(a,b) for(int i = a; i < b; ++i) const db eps = 1e-12; const db pi = acos(-1); const int inf = 0x3f3f3f3f; const ll INF = inf * 2LL * inf; const int mod = 1000 * 1000 * 1000 + 7; char str[1000005]; int n, q; pair<ii, int> seg[4000005]; pair<ii, int> merge(pair<ii, int> a, pair<ii, int> b){ pair<ii, int> c; c.S = a.S + b.S; int more = min(a.F.F, b.F.S); c.S += more; c.F.F = b.F.F + a.F.F - more; c.F.S = a.F.S + b.F.S - more; return c; } void build(int id = 1, int l = 0, int r = n){ if(r - l < 2){ seg[id] = {{str[l] == '(', str[l] == ')'}, 0}; return; } int mid = (l + r) / 2; build(id * 2, l, mid); build(id * 2 + 1, mid, r); seg[id] = merge(seg[id*2], seg[id*2 + 1]); } pair<ii, int> query(int x, int y, int id = 1, int l = 0, int r = n){ if(x >= r || l >= y) return {{0, 0}, 0}; if(x <= l && r <= y) return seg[id]; int mid = (l + r) / 2; pair<ii, int> a = query(x, y, id * 2, l, mid); pair<ii, int> b = query(x, y, id * 2 + 1, mid, r); return merge(a, b); } int main() { #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); #endif scanf("%s%d", str, &q); n = strlen(str); build(); while(q--){ int l, r; scanf("%d%d", &l, &r); printf("%d\n", 2 * query(l - 1, r).S); } return 0; }
23.851351
68
0.501983
Sohieeb
e8de98bace832fc475349c972c28d7235b2898b3
18,121
hpp
C++
string.hpp
nwehr/kick
0f738e0895a639c977e8c473eb40ee595e301f32
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
string.hpp
nwehr/kick
0f738e0895a639c977e8c473eb40ee595e301f32
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
string.hpp
nwehr/kick
0f738e0895a639c977e8c473eb40ee595e301f32
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
#ifndef _kick_string_h #define _kick_string_h // // Copyright 2012-2014 Kick project developers. // See COPYRIGHT.txt or https://bitbucket.org/nwehr/kick/downloads/COPYRIGHT.txt // // This file is part of the Kick project and subject to license terms. // See LICENSE.txt or https://bitbucket.org/nwehr/kick/downloads/LICENSE.txt // // C #include <string.h> // Kick #include "./common.hpp" #include "./allocator/array_allocator.hpp" /// enable or disable virtual methods to support polymorphism #ifndef KICK_POLYMORPHIC_STRING #define KICK_POLYMORPHIC_STRING KICK_POLYMORPHIC_CONTAINERS #endif namespace kick { /////////////////////////////////////////////////////////////////////////////// // basic_string /////////////////////////////////////////////////////////////////////////////// template<typename CharT, typename AllocT = array_allocator<CharT> > class basic_string { public: static const size_type npos = -1; basic_string( AllocT alloc = AllocT() ); basic_string( const CharT*, AllocT alloc = AllocT() ); basic_string( const CharT*, size_type, AllocT alloc = AllocT() ); basic_string( size_type, AllocT alloc = AllocT() ); basic_string( const basic_string<CharT, AllocT>& ); #if (KICK_POLYMORPHIC_STRING > 0) virtual #endif ~basic_string(); basic_string& operator=( const basic_string<CharT, AllocT>& str ); bool operator==( const basic_string<CharT, AllocT>& ) const; bool operator!=( const basic_string<CharT, AllocT>& ) const; bool operator<( const basic_string<CharT, AllocT>& ) const; bool operator>( const basic_string<CharT, AllocT>& ) const; inline CharT& operator[]( size_type ); inline size_type size() const; inline size_type length() const; inline size_type capacity() const; inline bool empty() const; inline CharT* c_str() const; inline CharT* data() const; size_type copy( CharT*, size_type, size_type pos = 0 ) const; size_type find( const basic_string<CharT, AllocT>&, size_type spos = 0 ) const; inline size_type find( const CharT*, size_type spos = 0 ) const; inline size_type find( const CharT*, size_type, size_type ) const; inline size_type find( CharT, size_type spos = 0 ) const; size_type rfind( const basic_string<CharT, AllocT>&, size_type spos = npos ) const; inline size_type rfind( const CharT*, size_type spos = npos ) const; inline size_type rfind( const CharT* buf, size_type spos, size_type len ) const; inline size_type rfind( CharT c, size_type spos = npos ) const; size_type find_first_of( const basic_string<CharT, AllocT>& nstr, size_type spos = 0 ) const; inline size_type find_first_of( const CharT* buf, size_type spos = 0 ) const; inline size_type find_first_of( const CharT* buf, size_type spos, size_type len ) const; inline size_type find_first_of( CharT c, size_type spos = 0 ) const; size_type find_last_of( const basic_string<CharT, AllocT>& nstr, size_type spos = npos ) const; inline size_type find_last_of( const CharT* buf, size_type spos = npos ) const; inline size_type find_last_of( const CharT* buf, size_type spos, size_type len ) const; inline size_type find_last_of( CharT c, size_type spos = npos ) const; size_type find_first_not_of( const basic_string<CharT, AllocT>& nstr, size_type spos = 0 ) const; inline size_type find_first_not_of( const CharT* buf, size_type spos = 0 ) const; inline size_type find_first_not_of( const CharT* buf, size_type spos, size_type len ) const; inline size_type find_first_not_of( CharT c, size_type spos = 0 ) const; // size_type find_last_not_of( const basic_string<CharT>& nstr, size_type spos = npos ) const; // inline size_type find_last_not_of( const CharT* buf, size_type spos = npos ) const; // inline size_type find_last_not_of( const CharT* buf, size_type spos, size_type len ) const; // inline size_type find_last_not_of( CharT c, size_type spos = npos ) const; size_type find_first_less_than( CharT c, size_type spos = 0 ) const; size_type find_first_greater_than( CharT c, size_type spos = 0 ) const; basic_string<CharT, AllocT> substr( size_type pos, size_type len = npos ) const; protected: CharT* _mem; AllocT _alloc; }; /////////////////////////////////////////////////////////////////////////////// // string /////////////////////////////////////////////////////////////////////////////// typedef basic_string<char> string; /////////////////////////////////////////////////////////////////////////////// // wstring /////////////////////////////////////////////////////////////////////////////// typedef basic_string<wchar_t> wstring; } template<typename CharT, typename AllocT> kick::basic_string<CharT, AllocT>::basic_string( AllocT alloc ) : _mem( nullptr ) , _alloc( alloc ) { _mem = _alloc.malloc( _mem, 0 ); _mem[0] = 0; } template<typename CharT, typename AllocT> kick::basic_string<CharT, AllocT>::basic_string( const CharT* cstr, AllocT alloc ) : _mem( nullptr ) , _alloc( alloc ) { size_type size( 0 ); while( cstr[size] ) ++size; _mem = _alloc.malloc( _mem, ++size ); for( size_type i = 0; i < size; ++i ) _mem[i] = cstr[i]; } template<typename CharT, typename AllocT> kick::basic_string<CharT, AllocT>::basic_string( const CharT* cstr, kick::size_type size, AllocT alloc ) : _mem( nullptr ) , _alloc( alloc ) { _mem = _alloc.malloc( _mem, size + 1 ); for( size_type i = 0; i < size; ++i ) _mem[i] = cstr[i]; _mem[size] = 0; } template<typename CharT, typename AllocT> kick::basic_string<CharT, AllocT>::basic_string( kick::size_type size, AllocT alloc ) : _mem( nullptr ) , _alloc( alloc ) { _mem = _alloc.malloc( _mem, size + 1 ); _mem[0] = 0; _mem[size] = 0; } template<typename CharT, typename AllocT> kick::basic_string<CharT, AllocT>::basic_string( const kick::basic_string<CharT, AllocT>& str ) : _mem( nullptr ) , _alloc( str._alloc ) { size_type size( str.size() + 1 ); _mem = _alloc.malloc( _mem, size ); for( size_type i = 0; i < size; ++i ) _mem[i] = str._mem[i]; } template<typename CharT, typename AllocT> kick::basic_string<CharT, AllocT>::~basic_string() { if( _mem ) _alloc.free( _mem ); } template<typename CharT, typename AllocT> kick::basic_string<CharT, AllocT>& kick::basic_string<CharT, AllocT>::operator=( const kick::basic_string<CharT, AllocT>& str ) { _mem = _alloc.malloc( _mem, (str.size() + 1) ); for( size_type i = 0; i < (str.size() + 1); ++i ) _mem[i] = str._mem[i]; return *this; } template<typename CharT, typename AllocT> bool kick::basic_string<CharT, AllocT>::operator==( const kick::basic_string<CharT, AllocT>& str ) const { return (strcmp( _mem, str._mem ) == 0 ? true : false); } template<typename CharT, typename AllocT> bool kick::basic_string<CharT, AllocT>::operator!=( const kick::basic_string<CharT, AllocT>& str ) const { return !(*this == str); } template<typename CharT, typename AllocT> bool kick::basic_string<CharT, AllocT>::operator<( const kick::basic_string<CharT, AllocT>& str ) const { return (strcmp( _mem, str._mem ) < 0 ? true : false); } template<typename CharT, typename AllocT> bool kick::basic_string<CharT, AllocT>::operator>( const kick::basic_string<CharT, AllocT>& str ) const { return (strcmp( _mem, str._mem ) > 0 ? true : false); } template<typename CharT, typename AllocT> CharT& kick::basic_string<CharT, AllocT>::operator[]( kick::size_type index ) { return _mem[index]; } template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::size() const { if( _alloc.usize() ) return _alloc.usize() - 1; return 0; } template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::length() const { return size(); } template<typename CharT, typename AllocT> bool kick::basic_string<CharT, AllocT>::empty() const { return size() > 0; } template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::capacity() const { return _alloc.asize(); } template<typename CharT, typename AllocT> CharT* kick::basic_string<CharT, AllocT>::c_str() const { return _mem; } template<typename CharT, typename AllocT> CharT* kick::basic_string<CharT, AllocT>::data() const { return c_str(); } template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::copy( CharT* str, kick::size_type len, kick::size_type pos ) const { const size_type ssize = size(); if( pos > ssize - 1 ) return 0; if( pos + len > ssize ) len = ssize - pos; size_type di = 0; for( size_type i = pos; i < ssize; ++i ) { str[di] = _mem[i]; ++di; } return di; } template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find( const kick::basic_string<CharT, AllocT>& nstr, kick::size_type spos ) const { const size_type nsize = nstr.size(); const size_type hsize = size(); if( nsize > hsize ) return npos; if( spos < 0 ) spos = 0; const size_type smax = hsize - nsize; while( spos <= smax ) { while( spos < smax && _mem[spos] != nstr._mem[0] ) ++spos; size_type hpos = spos + 1; size_type epos = 1; while( hpos < hsize && epos < nsize && _mem[hpos] == nstr._mem[epos] ) { ++hpos; ++epos; } if( epos == nsize ) return spos; else ++spos; } return npos; } //TODO: Optimized search for C string template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find( const CharT* buf, kick::size_type spos ) const { basic_string<CharT> n( buf ); return find( n, spos ); } //TODO: Optimized search for char buffer template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find( const CharT* buf, kick::size_type spos, kick::size_type len ) const { basic_string<CharT> n( buf, len ); return find( n, spos ); } //TODO: Optimized search for single char template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find( CharT c, kick::size_type spos ) const { basic_string<CharT> n( &c, 1 ); return find( n ); } template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::rfind( const kick::basic_string<CharT, AllocT>& nstr, kick::size_type spos ) const { const size_type nsize = nstr.size(); const size_type hsize = size(); if( nsize > hsize ) return npos; if( spos == npos || spos > hsize - 1 ) spos = hsize - 1; const size_type smin = nsize - 1; while( spos >= smin ) { while( spos >= smin && _mem[spos] != nstr._mem[nsize - 1] ) --spos; size_type hpos = spos - 1; size_type epos = nsize - 2; while( hpos >= 0 && epos >= 0 && _mem[hpos] == nstr._mem[epos] ) { --hpos; --epos; } if( epos == -1 ) return hpos + 1; else --spos; } return npos; } //TODO: Optimized search for C string template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::rfind( const CharT* buf, kick::size_type spos ) const { basic_string<CharT> n( buf ); return rfind( n, spos ); } //TODO: Optimized search for char buffer template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::rfind( const CharT* buf, kick::size_type spos, kick::size_type len ) const { basic_string<CharT> n( buf, len ); return rfind( n, spos ); } //TODO: Optimized search for single char template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::rfind( CharT c, kick::size_type spos ) const { basic_string<CharT> n( &c, 1 ); return rfind( n ); } template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find_first_of( const kick::basic_string<CharT, AllocT>& nstr, kick::size_type spos ) const { const size_type nsize = nstr.size(); const size_type hsize = size(); if( nsize < 1 ) return npos; if( spos < 0 ) spos = 0; while( spos < hsize ) { size_type npos = 0; while( _mem[spos] != nstr._mem[npos] && npos < nsize ) ++npos; if( npos < nsize ) return spos; ++spos; } return npos; } //TODO: Optimized search for C string template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find_first_of( const CharT* buf, kick::size_type spos ) const { basic_string<CharT> n( buf ); return find_first_of( n, spos ); } //TODO: Optimized search for char buffer template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find_first_of( const CharT* buf, kick::size_type spos, kick::size_type len ) const { basic_string<CharT> n( buf, len ); return find_first_of( n, spos ); } //TODO: Optimized search for single char template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find_first_of( CharT c, kick::size_type spos ) const { basic_string<CharT> n( &c, 1 ); return find_first_of( n ); } template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find_last_of( const kick::basic_string<CharT, AllocT>& nstr, kick::size_type spos ) const { const size_type nsize = nstr.size(); const size_type hsize = size(); if( nsize < 1 ) return npos; if( spos == npos || spos > hsize - 1 ) spos = hsize - 1; while( spos >= 0 ) { size_type npos = 0; while( _mem[spos] != nstr._mem[npos] && npos < nsize ) ++npos; if( npos < nsize ) return spos; --spos; } return npos; } //TODO: Optimized search for C string template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find_last_of( const CharT* buf, kick::size_type spos ) const { basic_string<CharT> n( buf ); return find_last_of( n, spos ); } //TODO: Optimized search for char buffer template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find_last_of( const CharT* buf, kick::size_type spos, kick::size_type len ) const { basic_string<CharT> n( buf, len ); return find_last_of( n, spos ); } //TODO: Optimized search for single char template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find_last_of( CharT c, kick::size_type spos ) const { basic_string<CharT> n( &c, 1 ); return find_last_of( n ); } template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find_first_not_of( const kick::basic_string<CharT, AllocT>& nstr, kick::size_type spos ) const { const size_type nsize = nstr.size(); const size_type hsize = size(); if( nsize < 1 ) return npos; if( spos < 0 ) spos = 0; while( spos < hsize ) { size_type npos = 0; while( _mem[spos] != nstr._mem[npos] && npos < nsize ) ++npos; if( npos < nsize ) ++spos; else return spos; } return npos; } //TODO: Optimized search for C string template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find_first_not_of( const CharT* buf, kick::size_type spos ) const { basic_string<CharT> n( buf ); return find_first_not_of( n, spos ); } //TODO: Optimized search for char buffer template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find_first_not_of( const CharT* buf, kick::size_type spos, kick::size_type len ) const { basic_string<CharT> n( buf, len ); return find_first_not_of( n, spos ); } //TODO: Optimized search for single char template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find_first_not_of( CharT c, kick::size_type spos ) const { basic_string<CharT> n( &c, 1 ); return find_first_not_of( n ); } //template<typename CharT> //kick::size_type kick::basic_string<CharT, AllocT>::find_last_not_of( const kick::basic_string<CharT, AllocT>& nstr, kick::size_type spos ) const { // const size_type nsize = nstr.size(); // const size_type hsize = size(); // // if( nsize < 1 ) return npos; // // if( spos == npos || spos > hsize - 1 ) spos = hsize - 1; // while( spos >= 0 ) { // size_type npos = 0; // while( _mem[spos] != nstr._mem[npos] && npos < nsize ) // ++npos; // // if( npos < nsize ) // --spos; // else // return spos; // } // // return npos; //} // ////TODO: Optimized search for C string //template<typename CharT> //kick::size_type kick::basic_string<CharT, AllocT>::find_last_not_of( const CharT* buf, kick::size_type spos ) const { // basic_string<CharT> n( buf ); // return find_last_not_of( n, spos ); //} // ////TODO: Optimized search for char buffer //template<typename CharT> //kick::size_type kick::basic_string<CharT, AllocT>::find_last_not_of( const CharT* buf, size_type spos, size_type len ) const { // basic_string<CharT> n( buf, len ); // return find_last_not_of( n, spos ); //} // ////TODO: Optimized search for single char //template<typename CharT> //kick::size_type find_last_not_of( CharT c, kick::size_type spos ) const { // basic_string<CharT> n( &c, 1 ); // return find_last_not_of( n, spos ); //} template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find_first_less_than( CharT c, kick::size_type spos ) const { const size_type hsize = size(); for( ; spos < hsize; ++spos ) if( _mem[spos] < c ) return spos; return npos; } template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find_first_greater_than( CharT c, kick::size_type spos ) const { const size_type hsize = size(); for( ; spos < hsize; ++spos ) if( _mem[spos] > c ) return spos; return npos; } template<typename CharT, typename AllocT> kick::basic_string<CharT, AllocT> kick::basic_string<CharT, AllocT>::substr( kick::size_type pos, kick::size_type len ) const { if( len == npos ) len = size(); if( pos < 0 || len <= 0 || pos >= size() ) return basic_string<CharT>(); if( pos + len > size() ) len = size() - pos; return basic_string<CharT>( &_mem[pos], len ); } // Non-member overload for outputting kick strings to stream objects... template<typename StreamT, typename CharT = char, typename AllocT = kick::array_allocator<CharT> > StreamT& operator<<( StreamT& os, const kick::basic_string<CharT, AllocT>& str ) { os << str.c_str(); return os; } #endif // _kick_string_h
30.923208
148
0.679267
nwehr
e8e1ebe8deee9aa578cf9c88492c30f9f4e909c8
25
cpp
C++
src_legacy/2018/test/mock_ws2812.cpp
gmoehler/ledpoi
d1294b172b7069f62119c310399d80500402d882
[ "MIT" ]
null
null
null
src_legacy/2018/test/mock_ws2812.cpp
gmoehler/ledpoi
d1294b172b7069f62119c310399d80500402d882
[ "MIT" ]
75
2017-05-28T23:39:33.000Z
2019-05-09T06:18:44.000Z
test/mock_ws2812.cpp
gmoehler/ledpoi
d1294b172b7069f62119c310399d80500402d882
[ "MIT" ]
null
null
null
#include "mock_ws2812.h"
12.5
24
0.76
gmoehler
e8e28a10f35b82070b02c81757f07a5729b59d14
1,031
hpp
C++
include/thh-bgfx-debug/debug-cube.hpp
pr0g/thh-bgfx-debug
ecf693f1df6ee11f0d49197c7d84cb70dca076dd
[ "MIT" ]
null
null
null
include/thh-bgfx-debug/debug-cube.hpp
pr0g/thh-bgfx-debug
ecf693f1df6ee11f0d49197c7d84cb70dca076dd
[ "MIT" ]
null
null
null
include/thh-bgfx-debug/debug-cube.hpp
pr0g/thh-bgfx-debug
ecf693f1df6ee11f0d49197c7d84cb70dca076dd
[ "MIT" ]
null
null
null
#pragma once #include "as/as-math-ops.hpp" #include "debug-vertex.hpp" #include <vector> namespace dbg { class DebugCubes { static DebugVertex CubeVertices[]; static uint16_t CubeIndices[]; bgfx::VertexBufferHandle cube_vbh_; bgfx::IndexBufferHandle cube_ibh_; bgfx::ProgramHandle program_handle_; bgfx::ViewId view_; struct CubeInstance { CubeInstance() = default; CubeInstance(const as::mat4& transform, const as::vec4& color) : transform_(transform), color_(color) { } as::mat4 transform_; as::vec4 color_; }; std::vector<CubeInstance> instances_; public: static void init(); DebugCubes(); ~DebugCubes(); void setRenderContext(bgfx::ViewId view, bgfx::ProgramHandle program_handle); void reserveCubes(size_t count); void addCube(const as::mat4& transform, const as::vec4& color); void submit(); }; inline void DebugCubes::addCube( const as::mat4& transform, const as::vec4& color) { instances_.emplace_back(transform, color); } } // namespace dbg
19.092593
79
0.706111
pr0g
e8e634251d723dbec0bd14ed84b203fadc20c796
964
hpp
C++
test/framework/call_engine_tests_common.hpp
Insafin/iroha
5e3c3252b2a62fa887274bdf25547dc264c10c26
[ "Apache-2.0" ]
1,467
2016-10-25T12:27:19.000Z
2022-03-28T04:32:05.000Z
test/framework/call_engine_tests_common.hpp
Insafin/iroha
5e3c3252b2a62fa887274bdf25547dc264c10c26
[ "Apache-2.0" ]
2,366
2016-10-25T10:07:57.000Z
2022-03-31T22:03:24.000Z
test/framework/call_engine_tests_common.hpp
Insafin/iroha
5e3c3252b2a62fa887274bdf25547dc264c10c26
[ "Apache-2.0" ]
662
2016-10-26T04:41:22.000Z
2022-03-31T04:15:02.000Z
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef IROHA_TEST_CALL_ENGINE_TESTS_COMMON_HPP #define IROHA_TEST_CALL_ENGINE_TESTS_COMMON_HPP #include <ostream> #include <string> #include <vector> #include "utils/string_builder.hpp" struct LogData { std::string address; std::string data; std::vector<std::string> topics; LogData(std::string address, std::string data, std::vector<std::string> topics) : address(std::move(address)), data(std::move(data)), topics(std::move(topics)) {} }; inline std::ostream &operator<<(std::ostream &os, LogData const &log) { return os << shared_model::detail::PrettyStringBuilder{} .init("Log") .appendNamed("address", log.address) .appendNamed("data", log.data) .appendNamed("topics", log.topics) .finalize(); } #endif
25.368421
71
0.623444
Insafin
e8e6b0ba2bed9fc368edaa7df98cc8bc43451977
942
cpp
C++
UVa/11729.cpp
tico88612/Solution-Note
31a9d220fd633c6920760707a07c9a153c2f76cc
[ "MIT" ]
1
2018-02-11T09:41:54.000Z
2018-02-11T09:41:54.000Z
UVa/11729.cpp
tico88612/Solution-Note
31a9d220fd633c6920760707a07c9a153c2f76cc
[ "MIT" ]
null
null
null
UVa/11729.cpp
tico88612/Solution-Note
31a9d220fd633c6920760707a07c9a153c2f76cc
[ "MIT" ]
null
null
null
#pragma GCC optimize ("O2") #include<bits/stdc++.h> #include<unistd.h> using namespace std; typedef long long ll; typedef vector<int> vi; typedef pair<int,int> pi; #define _ ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); #define FZ(n) memset((n),0,sizeof(n)) #define FMO(n) memset((n),-1,sizeof(n)) #define F first #define S second #define PB push_back #define MP make_pair #define ALL(x) begin(x),end(x) #define SZ(x) ((int)(x).size()) #define REP(i,a,b) for (int i = a; i < b; i++) // Let's Fight! struct Item { int b, j; }; bool cmp(Item A, Item B){ return A.j > B.j; } int main() { _ int N, kase = 1; while(cin >> N){ if(N == 0) break; cout << "Case " << kase++ << ": "; int ans = 0; vector<Item> enter(N); REP(i, 0, N){ cin >> enter[i].b >> enter[i].j; } sort(ALL(enter), cmp); int s = 0; REP(i, 0, N){ s += enter[i].b; ans = max(ans, s + enter[i].j); } cout << ans << '\n'; } return 0; }
18.470588
57
0.572187
tico88612
e8ec852a0be7a394e71c7fc1874ec7287182ab69
1,338
cpp
C++
Source/Reikonoids/Actors/RSpawner.cpp
gunstarpl/Reikonoids
55496bed915aec8c42048c9257b1050fd360b006
[ "MIT", "Unlicense" ]
null
null
null
Source/Reikonoids/Actors/RSpawner.cpp
gunstarpl/Reikonoids
55496bed915aec8c42048c9257b1050fd360b006
[ "MIT", "Unlicense" ]
null
null
null
Source/Reikonoids/Actors/RSpawner.cpp
gunstarpl/Reikonoids
55496bed915aec8c42048c9257b1050fd360b006
[ "MIT", "Unlicense" ]
null
null
null
#include "RSpawner.h" #include "../Gameplay/RSpawnDirector.h" ARSpawner::ARSpawner() = default; ARSpawner::~ARSpawner() = default; void ARSpawner::SetupDeferredSpawnRegistration(URSpawnDirector* InSpawnDirector, TArray<AActor*>* InPopulation) { check(InSpawnDirector); check(InPopulation); SpawnDirector = InSpawnDirector; Population = InPopulation; } void ARSpawner::BeginPlay() { Super::BeginPlay(); // Calculate total weight for list of entries. float WeightSum = 0.0f; for(const auto& Entry : Entries) { WeightSum += FMath::Max(0.0f, Entry.Weight); } // Spawn random entry from the list. float WeightRandom = FMath::RandRange(0.0f, WeightSum); float WeightProbe = 0.0f; for(const auto& Entry : Entries) { if(WeightRandom <= WeightProbe + Entry.Weight) { // Spawn actor definition. FActorSpawnParameters SpawnParams; AActor* SpawnedActor = GetWorld()->SpawnActor<AActor>(Entry.Class, GetActorTransform(), SpawnParams); // Register spawned actor if needed. if(SpawnedActor && SpawnDirector) { Population->Add(SpawnedActor); } break; } WeightProbe += Entry.Weight; } // Destroy spawner. Destroy(); }
23.892857
113
0.622571
gunstarpl
e8f1e57bd3b966e8a458c20f0264efc5656cce4a
4,803
cc
C++
src/blob_index_merge_operator_test.cc
DorianZheng/titan
03f9907355e8140442f0ab3fe44cbdda0f1d8a01
[ "Apache-2.0" ]
220
2019-11-30T02:33:05.000Z
2022-03-25T07:33:55.000Z
src/blob_index_merge_operator_test.cc
DorianZheng/titan
03f9907355e8140442f0ab3fe44cbdda0f1d8a01
[ "Apache-2.0" ]
112
2019-11-25T11:24:27.000Z
2022-03-30T08:11:41.000Z
src/blob_index_merge_operator_test.cc
DorianZheng/titan
03f9907355e8140442f0ab3fe44cbdda0f1d8a01
[ "Apache-2.0" ]
65
2019-12-16T15:26:50.000Z
2022-03-31T10:48:56.000Z
#include "test_util/testharness.h" #include "blob_index_merge_operator.h" namespace rocksdb { namespace titandb { std::string GenKey(int i) { char buffer[32]; snprintf(buffer, sizeof(buffer), "k-%08d", i); return buffer; } std::string GenValue(int i) { char buffer[32]; snprintf(buffer, sizeof(buffer), "v-%08d", i); return buffer; } BlobIndex GenBlobIndex(uint32_t i, uint32_t j = 0) { BlobIndex index; index.file_number = i; index.blob_handle.offset = j; index.blob_handle.size = 10; return index; } MergeBlobIndex GenMergeBlobIndex(BlobIndex src, uint32_t i, uint32_t j = 0) { MergeBlobIndex index; index.file_number = i; index.blob_handle.offset = j; index.blob_handle.size = 10; index.source_file_number = src.file_number; index.source_file_offset = src.blob_handle.offset; return index; } ValueType ToValueType(MergeOperator::MergeValueType value_type) { switch (value_type) { case MergeOperator::kDeletion: return kTypeDeletion; case MergeOperator::kValue: return kTypeValue; case MergeOperator::kBlobIndex: return kTypeBlobIndex; default: return kTypeValue; } } MergeOperator::MergeValueType ToMergeValueType(ValueType value_type) { switch (value_type) { case kTypeDeletion: case kTypeSingleDeletion: case kTypeRangeDeletion: return MergeOperator::kDeletion; case kTypeValue: return MergeOperator::kValue; case kTypeBlobIndex: return MergeOperator::kBlobIndex; default: return MergeOperator::kValue; } } class BlobIndexMergeOperatorTest : public testing::Test { public: std::string key_; ValueType value_type_{kTypeDeletion}; std::string value_; std::vector<std::string> operands_; std::shared_ptr<BlobIndexMergeOperator> merge_operator_; BlobIndexMergeOperatorTest() : key_("k"), merge_operator_(std::make_shared<BlobIndexMergeOperator>()) {} void Put(std::string value, ValueType type = kTypeValue) { value_ = value; value_type_ = type; operands_.clear(); } void Put(BlobIndex blob_index) { value_.clear(); blob_index.EncodeTo(&value_); value_type_ = kTypeBlobIndex; operands_.clear(); } void Merge(MergeBlobIndex blob_index) { std::string tmp; blob_index.EncodeTo(&tmp); operands_.emplace_back(tmp); } void Read(ValueType expect_type, std::string expect_value) { std::string tmp_result_string; Slice tmp_result_operand(nullptr, 0); MergeOperator::MergeValueType merge_type = ToMergeValueType(value_type_); Slice value = value_; std::vector<Slice> operands; for (auto& op : operands_) { operands.emplace_back(op); } const MergeOperator::MergeOperationInput merge_in( key_, merge_type, merge_type == MergeOperator::kDeletion ? nullptr : &value, operands, nullptr); MergeOperator::MergeOperationOutput merge_out(tmp_result_string, tmp_result_operand); ASSERT_EQ(true, merge_operator_->FullMergeV2(merge_in, &merge_out)); ASSERT_EQ(true, merge_out.new_type != MergeOperator::kDeletion); if (merge_out.new_type == merge_type) { ASSERT_EQ(expect_type, value_type_); } else { ASSERT_EQ(expect_type, ToValueType(merge_out.new_type)); } if (tmp_result_operand.data()) { ASSERT_EQ(expect_value, tmp_result_operand); } else { ASSERT_EQ(expect_value, tmp_result_string); } } void Clear() { value_type_ = kTypeDeletion; value_.clear(); operands_.clear(); } }; TEST_F(BlobIndexMergeOperatorTest, KeepBaseValue) { // [1] [2] (1->3) Put(GenBlobIndex(2)); Merge(GenMergeBlobIndex(GenBlobIndex(1), 3)); std::string value; GenBlobIndex(2).EncodeTo(&value); Read(kTypeBlobIndex, value); // [v] (1->2) Clear(); Put(GenValue(1)); Merge(GenMergeBlobIndex(GenBlobIndex(1), 2)); Read(kTypeValue, GenValue(1)); } TEST_F(BlobIndexMergeOperatorTest, KeepLatestMerge) { // [1] (1->2) (3->4) (2->5) Put(GenBlobIndex(1)); Merge(GenMergeBlobIndex(GenBlobIndex(1), 2)); Merge(GenMergeBlobIndex(GenBlobIndex(3), 4)); Merge(GenMergeBlobIndex(GenBlobIndex(2), 5)); std::string value; GenBlobIndex(5).EncodeTo(&value); Read(kTypeBlobIndex, value); } TEST_F(BlobIndexMergeOperatorTest, Delete) { // [delete] (0->1) Merge(GenMergeBlobIndex(GenBlobIndex(0), 1)); std::string value; BlobIndex::EncodeDeletionMarkerTo(&value); Read(kTypeBlobIndex, value); // [deletion marker] (0->1) Clear(); Put(value, kTypeBlobIndex); Merge(GenMergeBlobIndex(GenBlobIndex(0), 1)); Read(kTypeBlobIndex, value); } } // namespace titandb } // namespace rocksdb int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
26.535912
77
0.694149
DorianZheng
e8f2817da1ba7c8fd13adac90f6367724b6524c0
273
hpp
C++
include/pct/util.hpp
IllinoisStateGeologicalSurvey/p_point2grid
8aad94f1d606143ef287944f30f6815c328074ba
[ "BSD-4-Clause" ]
1
2020-11-25T21:26:25.000Z
2020-11-25T21:26:25.000Z
include/pct/util.hpp
IllinoisStateGeologicalSurvey/p_point2grid
8aad94f1d606143ef287944f30f6815c328074ba
[ "BSD-4-Clause" ]
null
null
null
include/pct/util.hpp
IllinoisStateGeologicalSurvey/p_point2grid
8aad94f1d606143ef287944f30f6815c328074ba
[ "BSD-4-Clause" ]
null
null
null
#ifndef UTIL_HPP #define UTIL_HPP double randomVal(int range, int min); void process_mem_usage(double& vm_usage, double& resident_set); double to_degrees(double radians); void compareMin(double* mins, double* tmp); void compareMax(double* maxs, double* tmp); #endif
17.0625
63
0.769231
IllinoisStateGeologicalSurvey
33042e1e7909f668cfce6d4f35d9eb62033dac55
704
cpp
C++
TG/bookcodes/ch2/uva11427.cpp
Anyrainel/aoapc-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
3
2017-08-15T06:00:01.000Z
2018-12-10T09:05:53.000Z
TG/bookcodes/ch2/uva11427.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
null
null
null
TG/bookcodes/ch2/uva11427.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
2
2017-09-16T18:46:27.000Z
2018-05-22T05:42:03.000Z
// UVa11427 Expect the Expected // Rujia Liu #include<cstdio> #include<cmath> #include<cstring> const int maxn = 100 + 5; int main() { int T; scanf("%d", &T); for(int kase = 1; kase <= T; kase++) { int n, a, b; double d[maxn][maxn], p; scanf("%d/%d%d", &a, &b, &n); // 请注意scanf的技巧 p = (double)a/b; memset(d, 0, sizeof(d)); d[0][0] = 1.0; d[0][1] = 0.0; for(int i = 1; i <= n; i++) for(int j = 0; j*b <= a*i; j++) { // 等价于枚举满足j/i <= a/b的j,但避免了误差 d[i][j] = d[i-1][j]*(1-p); if(j) d[i][j] += d[i-1][j-1]*p; } double Q = 0.0; for(int j = 0; j*b <= a*n; j++) Q += d[n][j]; printf("Case #%d: %d\n", kase, (int)(1/Q)); } return 0; }
25.142857
69
0.458807
Anyrainel
330c97f561e08709ab342f9fd6880a22c9a7175f
32,074
cc
C++
library/src/memory_profiling/BP_LibraryMemoryProfiling.cc
jason-medeiros/blockparty
4b1aabe66b13ceac70d6e42feb796909f067df9a
[ "MIT" ]
1
2018-05-31T11:51:43.000Z
2018-05-31T11:51:43.000Z
library/src/memory_profiling/BP_LibraryMemoryProfiling.cc
jason-medeiros/blockparty
4b1aabe66b13ceac70d6e42feb796909f067df9a
[ "MIT" ]
null
null
null
library/src/memory_profiling/BP_LibraryMemoryProfiling.cc
jason-medeiros/blockparty
4b1aabe66b13ceac70d6e42feb796909f067df9a
[ "MIT" ]
null
null
null
/* * BP_LibraryMemoryProfiling.cc * * Created on: Aug 26, 2013 * Author: root */ #include "../../include/BP-Main.h" // // Developer Notice: The code below is fairly complex, but if read carefully should // be fairly simple to understand if provided some context. The contextual summary of the code // found below is simply described as an overlay to the basic libc memory allocators. This // provides blockparty with some capacity to do runtime checks/allocation thresholding during allocation // to prevent undefined behavior. // // Developer Notice: A secondary layer to memory allocation is also provided within blockparty, and should // be used in lieu of using the allocator code below. You can find this capacity // within the BP_LinkedList.cc file, which provides direct access to allocators // managed directly via a libc (optimised) tail queue. While a bit less granular, the tail // queue allocators are designed to be more developer friendly. Additionally, blockparty // also includes a hash table allocator, which has larger entry sizes but O(1) lookup speed. // #if BP_USE_HASH_TABLE_PROFILER // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Global Memory Profiler Hash Table Registry %%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // global hash table registry BP_HASH_TABLE_REGISTRY global_mprof_hash_table_registry; // set the global hash init value to some arbitrary static value size_t global_mprof_hash_table_init_ok_val; size_t global_mprof_hash_table_init_ok; // If this value is non-zero the global memory profiler will create // backtraces for every allocaction. This should only be enabled // if you're debugging leaks. BP_BOOL global_mprof_create_backtrace_on_alloc; // global memory profiler lock sem_t global_mprof_lock; // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Memory Profiler Routines (Called Internally from bp*allocs/frees) % // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // Mark an allocation if it exists. BP_ERROR_T BP_MemProfilerMarkChunkByAddr(void * chunk, char * mark) { // return indicating success return ERR_SUCCESS; } // This must be called once per application run. It initializes // semaphores and insures global data is in the right configuration // before any allocations are performed. Not calling this function // can result in undefined behavior. BP_ERROR_T BP_InitMemProfilerSubsystem ( size_t log_chunk_min_size, size_t diag_bpstrdup, size_t diag_bpstrndup, size_t diag_bprealloc, size_t diag_bpmalloc, size_t diag_bpcalloc, size_t diag_bpfree ) { // only init if no init has already occured if(!BP_GLOBAL_MEMPROF_HASH_TABLE_INIT_OK) return ERR_FAILURE; // initialize the hash table BP_GLOBAL_MEMPROF_HASH_TABLE_INIT; // return indicating success return ERR_SUCCESS; } // disables the memory profiler subsystem and resets/frees memory. BP_ERROR_T BP_ShutdownMemProfilerSubsystem() { // only shutdown if profiler is up if(BP_GLOBAL_MEMPROF_HASH_TABLE_INIT_OK) return ERR_FAILURE; // destroy the hash table registry BP_DestroyHashTableRegistry(&global_mprof_hash_table_registry); // override the profiler init setting global_mprof_hash_table_init_ok_val = 0; // return indicating success return ERR_SUCCESS; } // removes a chunk from update BP_ERROR_T BP_MemProfilerRemoveChunk(void * addr) { // only shutdown if profiler is up if(BP_GLOBAL_MEMPROF_HASH_TABLE_INIT_OK) return ERR_FAILURE; // lock the table modification semaphore BP_HASH_TABLE_LOCK_SEM(global_mprof_lock); // delete a memory entry BP_ERROR_T deleted_ok = BP_HashRegDeleteMemoryEntryByDataPtr ( &global_mprof_hash_table_registry, addr ); // if it wasn't deleted ok, return indicating failure if(!deleted_ok) { return ERR_FAILURE; } // unlock the table modification semaphore BP_HASH_TABLE_UNLOCK_SEM(global_mprof_lock); // return indicating success return ERR_SUCCESS; } // checks to see if the chunk is in the stack P_BP_HASH_TABLE_MEM_PTR_ENTRY BP_MemProfilerFindChunk(void *addr) { // only shutdown if profiler is up if(BP_GLOBAL_MEMPROF_HASH_TABLE_INIT_OK) return NULL; // return found pointer (or null) return BP_HashRegMemPtrFind(&global_mprof_hash_table_registry,(void *) addr ); } // displays the memprofiler BP_ERROR_T BP_DisplayMemProfiler() { // only shutdown if profiler is up if(!BP_GLOBAL_MEMPROF_HASH_TABLE_INIT_OK) { printf("\n[!!] Attempted to display memory profiler but global memory profiler hasn't been initialized yet. Initialize memory profiler before utilizing this routine."); return ERR_FAILURE; } // display the memory profiler hash registry BP_HashRegDisplay(&global_mprof_hash_table_registry, BP_TRUE, BP_FALSE); // return indicating success return ERR_SUCCESS; } // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Blockparty Custom Allocators (Hash Table version) %%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // managed strdup char * bpstrdup_real(char *dup, BPLN_PARMS) { // ensure we're not trying to duplicate a null pointer if(!dup) return NULL; // If the memory profiler isn't active, immediately return // the duplicated string. if(!BP_GLOBAL_MEMPROF_HASH_TABLE_INIT_OK) return strdup(dup); // lock the table modification semaphore BP_HASH_TABLE_LOCK_SEM(global_mprof_lock); // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Managed Allocation %%%%%%%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // calculate the length of the string to duplicate size_t len = bpstrlen(dup); // add a memory entry ("" is 1 byte long just for null terminator) char * dup_string = (char *) BP_HashRegAddMemoryEntry ( &global_mprof_hash_table_registry, BP_HASH_REG_MEM_ENTRY_TYPE_GENERIC_ALLOCATION, len+1, file_name, line_number, func ); // now attempt to lookup the pointer P_BP_HASH_TABLE_MEM_PTR_ENTRY dup_string_hash_entry = BP_HashRegMemPtrFind ( &global_mprof_hash_table_registry, (void *) dup_string ); // if we cant lookup the hash entry, something catestrophic has occured if(!dup_string_hash_entry) { // exit immediately BP_LIBRARY_CRITICAL_DEBUG_EXIT("Unable to lookup block after allocation. This should never happen. Library emitting debug trap."); } // since we have the entry, set the type dup_string_hash_entry->alloc_type = BP_HASH_TABLE_ALLOCATOR_STRDUP; // copy in the string memcpy(dup_string, dup, len); // unlock the table modification semaphore BP_HASH_TABLE_UNLOCK_SEM(global_mprof_lock); // return the duplicated string return dup_string; } // managed strndup char * bpstrndup_real(char *dup, size_t n, BPLN_PARMS) { // ensure we're not trying to duplicate a null pointer if(!dup) return NULL; if(!n) return NULL; // If the memory profiler isn't active, immediately return // the duplicated string. if(!BP_GLOBAL_MEMPROF_HASH_TABLE_INIT_OK) return strndup(dup, n); // lock the table modification semaphore BP_HASH_TABLE_LOCK_SEM(global_mprof_lock); // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Managed Allocation %%%%%%%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // add a memory entry char * dup_string = (char *) BP_HashRegAddMemoryEntry ( &global_mprof_hash_table_registry, BP_HASH_REG_MEM_ENTRY_TYPE_GENERIC_ALLOCATION, n+1, file_name, line_number, func ); // now attempt to lookup the pointer P_BP_HASH_TABLE_MEM_PTR_ENTRY dup_string_hash_entry = BP_HashRegMemPtrFind ( &global_mprof_hash_table_registry, (void *) dup_string ); // if we cant lookup the hash entry, something catestrophic has occured if(!dup_string_hash_entry) { // exit immediately BP_LIBRARY_CRITICAL_DEBUG_EXIT("Unable to lookup block after allocation. This should never happen. Library emitting debug trap."); return NULL; } // since we have the entry, set the type dup_string_hash_entry->alloc_type = BP_HASH_TABLE_ALLOCATOR_STRNDUP; // copy in the string (MUST BE n, CANNOT BE ANYTHING ELSE) memcpy(dup_string, dup, n); // unlock the table modification semaphore BP_HASH_TABLE_UNLOCK_SEM(global_mprof_lock); // return the duplicated string return dup_string; } // managed realloc void * bprealloc_real(void * addr, size_t size, BPLN_PARMS) { // If the memory profiler isn't active, immediately return // the realloc if(!BP_GLOBAL_MEMPROF_HASH_TABLE_INIT_OK) return realloc(addr, size); // unlock the table modification semaphore BP_HASH_TABLE_LOCK_SEM(global_mprof_lock); // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Managed Allocation %%%%%%%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // pointer to hold future mem hash entries P_BP_HASH_TABLE_MEM_PTR_ENTRY dup_mem_hash_entry = NULL; // address of the new allocation to be returned void * new_addr = NULL; // if it's a new allocation, create a new entry here if(!addr) { // add a new memory entry since the behavior of realloc mandates // that we create a new entry on a null lookup. new_addr = (void *) BP_HashRegAddMemoryEntry ( &global_mprof_hash_table_registry, BP_HASH_REG_MEM_ENTRY_TYPE_GENERIC_ALLOCATION, size+1, file_name, line_number, func ); // now attempt to lookup the pointer dup_mem_hash_entry = BP_HashRegMemPtrFind ( &global_mprof_hash_table_registry, (void *) new_addr ); // if we cant lookup the hash entry, something catestrophic has occured if(!dup_mem_hash_entry) { // exit immediately BP_LIBRARY_CRITICAL_DEBUG_EXIT("Unable to lookup block during realloc (initial alloc part). This should never happen. Library emitting debug trap."); } // since we have the entry, set the type dup_mem_hash_entry->alloc_type = BP_HASH_TABLE_ALLOCATOR_REALLOC; } else // find and resize part of realloc() { // now attempt to lookup the pointer dup_mem_hash_entry = BP_HashRegMemPtrFind ( &global_mprof_hash_table_registry, (void *) addr ); // if we cant lookup the hash entry, something catestrophic has occured if(!dup_mem_hash_entry) { // exit immediately BP_LIBRARY_CRITICAL_DEBUG_EXIT("Unable to lookup block during realloc (memory resizing part). This should never happen. Library emitting debug trap."); } // create new addr new_addr = BP_HashRegResizeMemoryEntry ( &global_mprof_hash_table_registry, addr, size, file_name, line_number, func ); // -- lookup a second time to override type and also verify hash table integrity -- // now attempt to lookup the pointer dup_mem_hash_entry = BP_HashRegMemPtrFind ( &global_mprof_hash_table_registry, (void *) new_addr ); // if we cant lookup the hash entry, something catestrophic has occured if(!dup_mem_hash_entry) { // exit immediately BP_LIBRARY_CRITICAL_DEBUG_EXIT("Unable to lookup block during realloc (post creation lookup part). This should never happen. Library emitting debug trap."); } // since we have the entry, set the type dup_mem_hash_entry->alloc_type = BP_HASH_TABLE_ALLOCATOR_REALLOC; } // unlock the table modification semaphore BP_HASH_TABLE_UNLOCK_SEM(global_mprof_lock); // return the resized memory return new_addr; } // managed malloc (this is here mostly as a stub in case people want to use this library // in their own code. This code actually uses calloc in the backend, so you can be guaranteed // that all allocations returned are nullified). void * bpmalloc_real(size_t size, BPLN_PARMS) { // If the memory profiler isn't active, immediately return // the allocated memory. if(!BP_GLOBAL_MEMPROF_HASH_TABLE_INIT_OK) return malloc(size); // lock the table modification semaphore BP_HASH_TABLE_LOCK_SEM(global_mprof_lock); // add a memory entry void * new_mem = (void *) BP_HashRegAddMemoryEntry ( &global_mprof_hash_table_registry, BP_HASH_REG_MEM_ENTRY_TYPE_GENERIC_ALLOCATION, size, file_name, line_number, func ); // unlock the table modification semaphore BP_HASH_TABLE_UNLOCK_SEM(global_mprof_lock); // return the new memory return new_mem; } // managed calloc void * bpcalloc_real(size_t size, size_t size_n, BPLN_PARMS) { // If the memory profiler isn't active, immediately return // the allocated memory. if(!BP_GLOBAL_MEMPROF_HASH_TABLE_INIT_OK) { return calloc(size, size_n); } // lock the table modification semaphore BP_HASH_TABLE_LOCK_SEM(global_mprof_lock); // add a memory entry void * new_mem = (void *) BP_HashRegAddMemoryEntry ( &global_mprof_hash_table_registry, BP_HASH_REG_MEM_ENTRY_TYPE_GENERIC_ALLOCATION, (size * size_n), file_name, line_number, func ); // unlock the table modification semaphore BP_HASH_TABLE_UNLOCK_SEM(global_mprof_lock); // return the new memory return new_mem; } // destroy managed memory void bpfree_real(void * addr, BPLN_PARMS) { // display null free check here if(!addr) { // dbg msg printf("\n [!!] Error: Attempting to free a null chunk. This should never happen. Displaying debug backtrace."); printf("\n - in file_name: %s ", file_name); printf("\n - on line_number: %u ", line_number); printf("\n - in func: %s", func); printf("\n"); // create and display backtrace P_BP_LINUX_DEBUG_BACKTRACE debug_backtrace = BP_LinuxDebugCreateBacktrace(32); BP_LinuxDebugDisplayBacktrace(debug_backtrace, 1, 0, 32, BP_TRUE, BP_TRUE); printf("\n"); // attempt to destroy after debug BP_LinuxDebugDestroyBacktrace(debug_backtrace); // exit return; } // If the memory profiler isn't active, immediately return // the allocated memory. if(!BP_GLOBAL_MEMPROF_HASH_TABLE_INIT_OK) { // free normally if not null free(addr); return; } // lock the table modification semaphore BP_HASH_TABLE_LOCK_SEM(global_mprof_lock); // delete a memory entry BP_ERROR_T deleted_ok = BP_HashRegDeleteMemoryEntryByDataPtr ( &global_mprof_hash_table_registry, addr ); if(!deleted_ok) { printf("\n [!!] Error: Attempted to delete addr %p from the global hreg but the operation failed. Displaying trace.", addr); printf("\n - in file_name: %s ", file_name); printf("\n - on line_number: %u ", line_number); printf("\n - in func: %s", func); printf("\n"); // create and display backtrace // P_BP_LINUX_DEBUG_BACKTRACE debug_backtrace = BP_LinuxDebugCreateBacktrace(32); // BP_LinuxDebugDisplayBacktrace(debug_backtrace, 1, 0, 32, BP_TRUE, BP_TRUE); // printf("\n"); // attempt to destroy after debug // BP_LinuxDebugDestroyBacktrace(debug_backtrace); } // unlock the table modification semaphore BP_HASH_TABLE_UNLOCK_SEM(global_mprof_lock); } #else // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Old / Non-Hash Table Memory Profiler %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // global profiler set sem_t global_memory_profiler_semaphore; // flag indicating whether or not the profiler is enabled size_t global_memory_profiler_enabled = 0; // global memory profiler pool P_BP_MEMPROF_ENTRY global_memprof_pool = NULL; // global size parameter for logged chunks (chunks are only logged // when their logging size_t global_size_for_chunk_logging = 1024; // number of entries in the profiler pool size_t global_memprof_pool_n = 0; // index to the last entry added in the pool size_t global_memprof_last_index_added = 0; // size of the global_memprf_pool_n object. size_t global_memprofiler_pool_memory_usage = 0; // these flags are set via the init routine in-parameters // and are used to display a variety of debug messages. Profiler // debugging must be enabled (in BP-Main.h) in order for any // messages at all to be displayed. size_t global_memprofiler_diag_bpstrdup = 0; size_t global_memprofiler_diag_bpstrndup = 0; size_t global_memprofiler_diag_bprealloc = 0; size_t global_memprofiler_diag_bpmalloc = 0; size_t global_memprofiler_diag_bpcalloc = 0; size_t global_memprofiler_diag_bpfree = 0; // Simple OOM null allocation check for the app. Exits if we have // any 0x00 allocs. size_t global_memprofiler_exit_application_on_null_allocations = 1; // checks to see if the chunk is in the stack P_BP_MEMPROF_ENTRY BP_MemProfilerFindChunk(void *addr) { size_t n = 0; for(; n < global_memprof_pool_n; n++) { // get the entry at the specified location if(global_memprof_pool[n].mem_ptr == addr) return (P_BP_MEMPROF_ENTRY) &global_memprof_pool[n]; } // return indicating failure return NULL; } // adds a chunk to update BP_ERROR_T BP_MemProfilerAddUpdateProfiledChunk(void * addr, size_t new_size, BP_MEMPROF_ALLOC_TYPE type) { // ensure address and new size if(!addr || !new_size) return ERR_FAILURE; // entry P_BP_MEMPROF_ENTRY entry = BP_MemProfilerFindChunk((void *) addr); if(!entry) { // increment the pool stack count global_memprof_pool_n++; global_memprof_pool = (P_BP_MEMPROF_ENTRY) realloc(global_memprof_pool, global_memprof_pool_n * sizeof(BP_MEMPROF_ENTRY)); // zero out the entry memset((void *) &global_memprof_pool[global_memprof_pool_n-1], 0x00, sizeof(BP_MEMPROF_ENTRY)); // set the pointer in the structure global_memprof_pool[global_memprof_pool_n-1].mem_ptr = addr; // set the init alloc size if the current size is zero if(global_memprof_pool[global_memprof_pool_n-1].curr_alloc_size == 0) global_memprof_pool[global_memprof_pool_n-1].init_alloc_size = global_memprof_pool[global_memprof_pool_n-1].curr_alloc_size; // set the current alloc size global_memprof_pool[global_memprof_pool_n-1].curr_alloc_size = new_size; global_memprof_pool[global_memprof_pool_n-1].total_allocations = 1; } else { printf("\n Logging existing chunk"); // set the current alloc size entry->curr_alloc_size = new_size; entry->total_allocations++; } // return indicating success return ERR_SUCCESS; } // removes a chunk if it's been bpfree'd // removes a chunk from update BP_ERROR_T BP_MemProfilerRemoveChunk(void * addr) { #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] Attempting to remove monitored chunk: %p", addr); #endif // cant remove what isn't there if(!addr) return ERR_FAILURE; // set the new entries P_BP_MEMPROF_ENTRY new_entries = (P_BP_MEMPROF_ENTRY) bpcalloc(1, sizeof(BP_MEMPROF_ENTRY) * (global_memprof_pool_n - 1)); if(!new_entries) return ERR_FAILURE; #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] Attempting to find chunk in monitored chunk list: %p", addr); #endif // get chunk index size_t n = 0; for(; n < global_memprof_pool_n; n++) { if(global_memprof_pool[n].mem_ptr == addr) { #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] Found our chunk %p at entry index %u (struct addr: %p)", addr, n, (void *) &global_memprof_pool[n]); #endif // set offset size_t entries_offset = n; size_t following_offset = n+1; size_t remaining_entries = (global_memprof_pool_n - n - 1); // copy in the first half of the stack memcpy((void *)new_entries, (void *) global_memprof_pool, sizeof(BP_MEMPROF_ENTRY) * n); // copy in the remaining entries memcpy((void *)&new_entries[n], (void *) &global_memprof_pool[n+1], sizeof(BP_MEMPROF_ENTRY) * remaining_entries); // set pool to the new stack global_memprof_pool = new_entries; #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] Chunk %p has been removed from the list.", addr); #endif // break the loop break; } } // decrement element count in the pool global_memprof_pool_n--; // return indicating success return ERR_SUCCESS; } // ==================================================== // === Allocators ===================================== // ==================================================== // string duplication char * bpstrdup(char *dup) { if(!dup) return ERR_FAILURE; if(global_memory_profiler_enabled == 0xcafebabe) { // lock global semaphor sem_wait(&global_memory_profiler_semaphore); } // get string length (cap out at 100mb) size_t string_len = strnlen(dup, 1024 * 1024 * 100); if(string_len >= MAXIMUM_VALUE_FOR_ANY_ALLOCATION) { printf("\n [+] Attempted to allocate more than %u (%u) bytes. Error.", MAXIMUM_VALUE_FOR_ANY_ALLOCATION, string_len); if(global_memprofiler_exit_application_on_null_allocations == 1) { __asm("int3"); exit(0); } return NULL; } // duplicate the string char * result = (char *) strdup(dup); if(!result) if(global_memprofiler_exit_application_on_null_allocations == 1) { printf("\n [ERROR] bpstrdup(%p): APPLICATION RAN OUT OF MEMORY WHILE TRYING TO ALLOCATE SPACE.", dup); __asm("int3"); exit(0); } if(string_len >= global_size_for_chunk_logging) if(global_memprofiler_diag_bprealloc) { #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] strdup for (%p) yielded ptr %p (with calculated size: %u) ", dup, result, string_len); #endif } if(global_memory_profiler_enabled == 0xcafebabe) { // add the chunk to the profiler if size check passes if(string_len >= global_size_for_chunk_logging) BP_MemProfilerAddUpdateProfiledChunk(result, string_len, BP_MEMPROF_ALLOC_TYPE_STRDUP); // unlock global semaphore sem_post(&global_memory_profiler_semaphore); } return result; } // length restrained duplication char * bpstrndup(char *dup, size_t n) { if(n >= MAXIMUM_VALUE_FOR_ANY_ALLOCATION) { printf("\n [+] Attempted to allocate more than %u (%n) bytes. Error.", MAXIMUM_VALUE_FOR_ANY_ALLOCATION, n); if(global_memprofiler_exit_application_on_null_allocations == 1) { __asm("int3"); exit(0); } return NULL; } if(global_memory_profiler_enabled == 0xcafebabe) { // lock global semaphor sem_wait(&global_memory_profiler_semaphore); } char * result = (char *) strndup(dup, n); if(!result) if(global_memprofiler_exit_application_on_null_allocations == 1) { printf("\n [ERROR] bpstrndup(%p, %u): APPLICATION RAN OUT OF MEMORY WHILE TRYING TO ALLOCATE SPACE.", dup, n); exit(0); } if(n >= global_size_for_chunk_logging) if(global_memprofiler_diag_bpstrndup) { #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] strndup for (%p, %u) yielded ptr %p", dup, n, result); #endif } if(global_memory_profiler_enabled == 0xcafebabe) { // add the chunk to the profiler if size check passes if(n >= global_size_for_chunk_logging) BP_MemProfilerAddUpdateProfiledChunk(result, n, BP_MEMPROF_ALLOC_TYPE_STRNDUP); // unlock global semaphore sem_post(&global_memory_profiler_semaphore); } return result; } // replacement for realloc void * bprealloc(void * addr, size_t size) { if(size >= MAXIMUM_VALUE_FOR_ANY_ALLOCATION) { printf("\n [+] Attempted to allocate more than %u (%u_ bytes. Error.", MAXIMUM_VALUE_FOR_ANY_ALLOCATION, size); if(global_memprofiler_exit_application_on_null_allocations == 1) { __asm("int3"); exit(0); } return NULL; } if(global_memory_profiler_enabled == 0xcafebabe) { // lock global semaphor sem_wait(&global_memory_profiler_semaphore); } // allocate the result void * result = realloc(addr, size); if(!result) if(global_memprofiler_exit_application_on_null_allocations == 1) { printf("\n [ERROR] bprealloc(%p, %u): APPLICATION RAN OUT OF MEMORY WHILE TRYING TO ALLOCATE SPACE.", addr, size); exit(0); } if(size >= global_size_for_chunk_logging) if(global_memprofiler_diag_bprealloc) { #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] realloc for (%p, %u) yielded ptr %p", addr, size, result); #endif } if(!result) { printf("\n [!!] realloc failed for (%p, %u) yielded ptr %p", addr, size, result); exit(0); } if(global_memory_profiler_enabled == 0xcafebabe) { // add the chunk to the profiler if size check passes if(size >= global_size_for_chunk_logging) BP_MemProfilerAddUpdateProfiledChunk(result, size, BP_MEMPROF_ALLOC_TYPE_REALLOC); // unlock global semaphore sem_post(&global_memory_profiler_semaphore); } // return the allocated data return result; } // replacement for malloc void * bpmalloc(size_t size) { if(size >= MAXIMUM_VALUE_FOR_ANY_ALLOCATION) { printf("\n [+] Attempted to allocate more than %u (%u) bytes. Error.", MAXIMUM_VALUE_FOR_ANY_ALLOCATION, size); if(global_memprofiler_exit_application_on_null_allocations == 1) { __asm("int3"); exit(0); } return NULL; } if(global_memory_profiler_enabled == 0xcafebabe) { // lock global semaphor sem_wait(&global_memory_profiler_semaphore); } // allocate the result void * result = malloc(size); if(!result) if(global_memprofiler_exit_application_on_null_allocations == 1) { printf("\n [ERROR] bpmalloc(%u): APPLICATION RAN OUT OF MEMORY WHILE TRYING TO ALLOCATE SPACE.", size); exit(0); } if(size >= global_size_for_chunk_logging) if(global_memprofiler_diag_bpmalloc) { #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] malloc for (%u) yielded ptr %p", size, result); #endif } if(!result) { printf("\n [!!] Error: malloc failed. Application likely ran out of memory."); exit(0); } if(global_memory_profiler_enabled == 0xcafebabe) { // add the chunk to the profiler if size check passes if(size >= global_size_for_chunk_logging) BP_MemProfilerAddUpdateProfiledChunk(result, size, BP_MEMPROF_ALLOC_TYPE_MALLOC); // unlock global semaphore sem_post(&global_memory_profiler_semaphore); } // return the allocated data return result; } // replacement for bpcalloc void * bpcalloc(size_t size, size_t size_n) { if((size * size_n) >= MAXIMUM_VALUE_FOR_ANY_ALLOCATION) { printf("\n [+] Attempted to allocate more than %u (%u) bytes. Error.", MAXIMUM_VALUE_FOR_ANY_ALLOCATION, size_n); if(global_memprofiler_exit_application_on_null_allocations == 1) { __asm("int3"); exit(0); } return NULL; } if(global_memory_profiler_enabled == 0xcafebabe) { // lock global semaphor sem_wait(&global_memory_profiler_semaphore); } // allocate the result void * result = calloc(size, size_n); if(!result) if(global_memprofiler_exit_application_on_null_allocations == 1) { printf("\n [ERROR] bpcalloc(%u, %u): APPLICATION RAN OUT OF MEMORY WHILE TRYING TO ALLOCATE SPACE.", size, size_n); exit(0); } if(size >= global_size_for_chunk_logging || size_n >= global_size_for_chunk_logging) if(global_memprofiler_diag_bpcalloc) { #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] calloc for (%u,%u) yielded ptr %p", size, size_n, result); #endif } if(global_memory_profiler_enabled == 0xcafebabe) { // add the chunk to the profiler if size check passes if(size >= global_size_for_chunk_logging) BP_MemProfilerAddUpdateProfiledChunk(result, size, BP_MEMPROF_ALLOC_TYPE_CALLOC); // unlock global semaphore sem_post(&global_memory_profiler_semaphore); } // return the allocated data return result; } // replacement for bpcalloc void bpfree(void * addr) { if(global_memory_profiler_enabled == 0xcafebabe) { // lock global semaphor sem_wait(&global_memory_profiler_semaphore); } if(global_memprofiler_diag_bpfree) { #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] Attempting to free %p", addr); #endif } // run check to ensure that the chunk is not being double free'd. If it is being double // freed, throw a sigtrap so that we might debug it. if(global_memory_profiler_enabled == 0xcafebabe) if(!BP_MemProfilerFindChunk((void *) addr)) { printf("\n BPMEMPROF: Attempting to free chunk that doesn't appear to be in the profiled chunk list. Stopping application/launching debugger."); printf("\n\n"); __asm("int3"); return; } // bpfree the result free(addr); if(global_memory_profiler_enabled == 0xcafebabe) { // remove the chunk from the profiler BP_MemProfilerRemoveChunk(addr); // unlock global semaphore sem_post(&global_memory_profiler_semaphore); } } // This must be called once per application run. It initializes // semaphores and insures global data is in the right configuration // before any allocations are performed. Not calling this function // can result in undefined behavior. BP_ERROR_T BP_InitMemProfilerSubsystem ( size_t log_chunk_min_size, size_t diag_bpstrdup, size_t diag_bpstrndup, size_t diag_bprealloc, size_t diag_bpmalloc, size_t diag_bpcalloc, size_t diag_bpfree ) { #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] Attempting to initialize main memory profiler."); #endif // initialize the memory profile semaphore sem_init(&global_memory_profiler_semaphore, 0, 1); #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] Initialized global semaphor at %p, now waiting for lock.", &global_memory_profiler_semaphore); #endif // lock global semaphor sem_wait(&global_memory_profiler_semaphore); #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] Locked global memory profile semaphore."); #endif // set global diagnostic flags from parameters global_memprofiler_diag_bpstrdup = diag_bpstrdup; global_memprofiler_diag_bpstrndup = diag_bpstrndup; global_memprofiler_diag_bprealloc = diag_bprealloc; global_memprofiler_diag_bpmalloc = diag_bpmalloc; global_memprofiler_diag_bpcalloc = diag_bpcalloc; global_memprofiler_diag_bpfree = diag_bpfree; // set the global profiler pool to null global_memprof_pool = NULL; global_memprof_pool_n = 0; global_memprof_last_index_added = 0; global_memprofiler_pool_memory_usage = 0; global_size_for_chunk_logging = log_chunk_min_size; global_memory_profiler_enabled = 0xcafebabe; #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] Memory profiler has been loaded OK. Now unlocking global lock."); #endif // unlock global semaphore sem_post(&global_memory_profiler_semaphore); #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] Global memory profiler lock has been unlocked. Exiting profiler init."); #endif // return indicating success return ERR_SUCCESS; } // disables the memory profiler subsystem and resets/frees memory. BP_ERROR_T BP_ShutdownMemProfilerSubsystem() { #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] Preparing to disable memory profiler.."); #endif // lock global semaphor sem_wait(&global_memory_profiler_semaphore); if(global_memory_profiler_enabled != 0xcafebabe) return ERR_FAILURE; // set flag indicating capability is disabled global_memory_profiler_enabled = 0; if(global_memprof_pool_n) for(size_t j = 0; j < global_memprof_pool_n; j++) { // free marks if necessary if(global_memprof_pool[j].mark) free(global_memprof_pool[j].mark); } if(global_memprof_pool) free(global_memprof_pool); // reset all the global vars global_memprof_pool = NULL; global_memprof_pool_n = 0; global_memprof_last_index_added = 0; global_memprofiler_pool_memory_usage = 0; global_size_for_chunk_logging = 0; // unlock global semaphore sem_post(&global_memory_profiler_semaphore); #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] Memory profiler has been disabled."); #endif // return indicating success return ERR_SUCCESS; } // Mark an allocation if it exists. BP_ERROR_T BP_MemProfilerMarkChunkByAddr(void * chunk, char * mark) { // ensure we have some parameter validation if(!chunk || !mark) return ERR_FAILURE; #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] Attempting to mark chunk: %p with %s", chunk, mark); #endif // look up the entry P_BP_MEMPROF_ENTRY entry = BP_MemProfilerFindChunk(chunk); if(!entry) return ERR_FAILURE; // Dont mark chunks with long strings, stupid. You'll just exhaust // your memory. size_t mark_len = bpstrlen(mark); if(mark_len >= 4096) return ERR_FAILURE; // set the mark here after length validation entry->mark = strdup(mark); #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] Marked chunk %p OK!", chunk); #endif // return indicating success return ERR_SUCCESS; } #endif
25.195601
171
0.716156
jason-medeiros
33163bbfb6a3329f31e140e49979700b2f199390
159
cc
C++
bitlinuxosnetworkclass/lesson35/httpServer.cc
DanteIoVeYou/Linux_Study
701a54caad3d65c511716111430ca08ada78f088
[ "MIT" ]
null
null
null
bitlinuxosnetworkclass/lesson35/httpServer.cc
DanteIoVeYou/Linux_Study
701a54caad3d65c511716111430ca08ada78f088
[ "MIT" ]
null
null
null
bitlinuxosnetworkclass/lesson35/httpServer.cc
DanteIoVeYou/Linux_Study
701a54caad3d65c511716111430ca08ada78f088
[ "MIT" ]
null
null
null
#include "httpServer.hpp" int main(int argc, char *argv[]) { srv::httpServer srvIns(atoi(argv[1])); srvIns.init(); srvIns.start(); return 0; }
17.666667
42
0.616352
DanteIoVeYou
3317953f9c67dbf71858b38ed4840e500ddf6bc1
1,542
cc
C++
unit_tests/test_property.cc
maihd/riku
daca9172f4ee0e303060796e86859247e4306dcc
[ "Unlicense" ]
2
2019-03-22T05:01:03.000Z
2020-05-07T11:26:03.000Z
unit_tests/test_property.cc
maihd/riku
daca9172f4ee0e303060796e86859247e4306dcc
[ "Unlicense" ]
null
null
null
unit_tests/test_property.cc
maihd/riku
daca9172f4ee0e303060796e86859247e4306dcc
[ "Unlicense" ]
null
null
null
// Copyright (c) 2019, MaiHD. All right reversed. // License: Unlicensed #include <stdio.h> #include "./unit_test.h" #if defined(EXTENION_PROPERTY) && (defined(_MSC_VER) || (defined(__has_declspec_attriute) && __has_declspec_attribute(property))) #define test_assert(a, b) console::log(#a " = %d - " #b " = %d", a, b) struct Type { public: PROPERTY(int, value, get_value, set_value); public: int get_value() { return real_value; } void set_value(int v) { real_value = v; } public: int real_value; }; static_assert(sizeof(Type) == sizeof(int), "property should not create new member in data structure, it's just syntax sugar man."); [[noreturn]] void force_exit() { exit(1); } TEST_CASE("Property testing", "[property]") { Type test; test.value = 0; test_assert(test.value, test.real_value); test.value = 1; test_assert(test.value, test.real_value); test.value = 1; test_assert(test.value, test.real_value); test.value = 2; test_assert(test.value, test.real_value); test.value = 3; test_assert(test.value, test.real_value); test.value = 4; test_assert(test.value, test.real_value); test.value = 5; test_assert(test.value, test.real_value); test.value = 6; test_assert(test.value, test.real_value); test.value = 7; test_assert(test.value, test.real_value); test.value = 8; test_assert(test.value, test.real_value); test.value = 9; test_assert(test.value, test.real_value); } #endif
20.837838
131
0.653048
maihd
3319e121c5528eb8172b4366200ac3fbc820fd26
3,343
cpp
C++
vtbl.cpp
Kanda-Motohiro/cppsample
6c010f4cc7a8143debf159435621966bf582f5d6
[ "CC0-1.0" ]
null
null
null
vtbl.cpp
Kanda-Motohiro/cppsample
6c010f4cc7a8143debf159435621966bf582f5d6
[ "CC0-1.0" ]
null
null
null
vtbl.cpp
Kanda-Motohiro/cppsample
6c010f4cc7a8143debf159435621966bf582f5d6
[ "CC0-1.0" ]
null
null
null
/* * 2018.5.6 [email protected] C++ 練習 * released under https://creativecommons.org/publicdomain/zero/1.0/legalcode.ja */ #include "base.h" #include <locale> #include <typeinfo> class Derived: public base { public: int i = 0xdddddddd; Derived(char a) : base(a) {} const string toString() const override { string s = base::toString(); return "==" + s; } }; int main() { p(locale{""}.name()); // ja_JP.utf8 at line 19 Derived d('1'); base *pb = &d; printf("base=%p %u derived=%p %u\n", pb, sizeof(base), &d, sizeof(d)); cout << pb->toString() << endl; Derived *pd = static_cast<Derived *>(pb); pd->i+= 7; pd = dynamic_cast<Derived *>(pb); pd->i-= 5; Base *bad = dynamic_cast<Base *>(pb); p(bad); p(typeid(int).name()); const type_info& ti = typeid(*pb); p(ti.name()); /* (gdb) p ti $1 = (const std::type_info &) @0x80494c4: { _vptr.type_info = 0x804b160 <vtable for __cxxabiv1::__si_class_type_info@@CXXABI_1.3+8>, __name = 0x80494d0 <typeinfo name for Derived> "7Derived"} (gdb) p &ti $2 = (const std::type_info *) 0x80494c4 <typeinfo for Derived> (gdb) x/16x 0x80494c4 0x80494c4 <_ZTI7Derived>: 0x0804b160 0x080494d0 0x080494dc 0x72654437 0x80494d4 <_ZTS7Derived+4>: 0x64657669 0x00000000 0x0804b088 0x080494e4 0x80494e4 <_ZTS4base>: 0x73616234 0x00000065 0x0804b088 0x080494f4 0x80494f4 <_ZTS4Base>: 0x73614234 0x00000065 0x3b031b01 0x00000070 */ } #if 0 base=0xbffff150 20 derived=0xbffff150 24 Breakpoint 1, base::toString[abi:cxx11]() const (this=0xbffff150) at base.h:49 49 virtual const string toString() const { return data; } (gdb) x/8x 0xbffff150 0xbffff150: 0x08049254 0x31313131 0x31313131 0x31313131 # vtbl base::data 0xbffff160: 0x00313131 0xdddddddd # Derived::i (gdb) bt #0 base::toString[abi:cxx11]() const (this=0xbffff150) at base.h:49 #1 0x08049099 in Derived::toString[abi:cxx11]() const (this=0xbffff150) at vtbl.cpp:13 #2 0x08048eab in main () at vtbl.cpp:26 (gdb) x/4x 0x08049254 0x8049254 <_ZTV7Derived+8>: 0x08049082 0x00000000 (gdb) x/i 0x08049082 0x08049082 <Derived::toString[abi:cxx11]() const>: push %ebp (gdb) p pb->toString $6 = {const std::__cxx11::string (const base * const)} 0x8048fe4 <base::toString[abi:cxx11]() const> (gdb) p d.toString $7 = {const std::__cxx11::string (const Derived * const)} 0x8049082 <Derived::toString[abi:cxx11]() const> vtbl に入っているのは後者。でも、pb->toString をデバッガで見た結果が、 base のメンバ関数になっているのはなぜ。 Derived *pd = static_cast<Derived *>(pb); pd->i+= 7; pd = dynamic_cast<Derived *>(pb); pd->i-= 5; static_cast は、実行コードは無い。 (gdb) x/16i $eip => 0x8048cd7 <main()+268>: addl $0x7,-0x40(%ebp) 0x8048cdb <main()+272>: push $0x0 0x8048cdd <main()+274>: push $0x8048fe8 # なんだこれ 0x8048ce2 <main()+279>: push $0x8048fd4 0x8048ce7 <main()+284>: lea -0x54(%ebp),%eax 0x8048cea <main()+287>: push %eax 0x8048ceb <main()+288>: call 0x8048a00 <__dynamic_cast@plt> 0x8048cf0 <main()+293>: add $0x10,%esp 0x8048cf3 <main()+296>: subl $0x5,0x14(%eax) キャスト元先の型情報らしい。 (gdb) x/4x 0x8048fe8 0x8048fe8 <_ZTI7Derived>: 0x0804b154 0x08048fdc 0x08048fd4 0x00000000 (gdb) x/4x 0x8048fd4 0x8048fd4 <_ZTI4base>: 0x0804b088 0x08048fcc 0x72654437 0x64657669 (gdb) p/x $eax $4 = 0xbffff154 (gdb) info locals pb = 0xbffff154 #endif
31.242991
106
0.680826
Kanda-Motohiro
331e515b93ce7cf01cd50da5dbb9d26c669c895c
2,351
hpp
C++
src/xalanc/XercesParserLiaison/XercesNamedNodeMapAttributeList.hpp
rherardi/xml-xalan-c-src_1_10_0
24e6653a617a244e4def60d67b57e70a192a5d4d
[ "Apache-2.0" ]
null
null
null
src/xalanc/XercesParserLiaison/XercesNamedNodeMapAttributeList.hpp
rherardi/xml-xalan-c-src_1_10_0
24e6653a617a244e4def60d67b57e70a192a5d4d
[ "Apache-2.0" ]
null
null
null
src/xalanc/XercesParserLiaison/XercesNamedNodeMapAttributeList.hpp
rherardi/xml-xalan-c-src_1_10_0
24e6653a617a244e4def60d67b57e70a192a5d4d
[ "Apache-2.0" ]
null
null
null
/* * Copyright 1999-2004 The Apache Software Foundation. * * 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. */ #if !defined(XERCESNAMEDNODEMAPATTRIBUTELIST_HEADER_GUARD_1357924680) #define XERCESNAMEDNODEMAPATTRIBUTELIST_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <xalanc/XercesParserLiaison/XercesParserLiaisonDefinitions.hpp> #include <xercesc/sax/AttributeList.hpp> #include <xalanc/XercesParserLiaison/XercesWrapperTypes.hpp> XALAN_CPP_NAMESPACE_BEGIN class XALAN_XERCESPARSERLIAISON_EXPORT XercesNamedNodeMapAttributeList : public XERCES_CPP_NAMESPACE_QUALIFIER AttributeList { public: typedef XERCES_CPP_NAMESPACE_QUALIFIER AttributeList ParentType; explicit XercesNamedNodeMapAttributeList(const DOMNamedNodeMapType* theMap); virtual ~XercesNamedNodeMapAttributeList(); // These are inherited from AttributeList virtual unsigned int getLength() const; virtual const XMLCh* getName(const unsigned int index) const; virtual const XMLCh* getType(const unsigned int index) const; virtual const XMLCh* getValue(const unsigned int index) const; virtual const XMLCh* getType(const XMLCh* const name) const; virtual const XMLCh* getValue(const XMLCh* const name) const; private: virtual const XMLCh* getValue(const char* const name) const; // Not implemented... XercesNamedNodeMapAttributeList& operator=(const XercesNamedNodeMapAttributeList&); bool operator==(const XercesNamedNodeMapAttributeList&); // Data members... const DOMNamedNodeMapType* const m_nodeMap; const XMLSizeType m_lastIndex; static const XMLCh s_typeString[]; }; XALAN_CPP_NAMESPACE_END #endif // XERCESNAMEDNODEMAPATTRIBUTELIST_HEADER_GUARD_1357924680
24.489583
125
0.752871
rherardi
33236e24ea72690d0313ce7f4790bb3d238e5510
951
hpp
C++
src/wire/wire2lua/mapped_type.hpp
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
5
2016-04-07T19:49:39.000Z
2021-08-03T05:24:11.000Z
src/wire/wire2lua/mapped_type.hpp
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
null
null
null
src/wire/wire2lua/mapped_type.hpp
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
1
2020-12-27T11:47:31.000Z
2020-12-27T11:47:31.000Z
/* * mapped_type.hpp * * Created on: 15 мая 2016 г. * Author: sergey.fedorov */ #ifndef WIRE_WIRE2LUA_MAPPED_TYPE_HPP_ #define WIRE_WIRE2LUA_MAPPED_TYPE_HPP_ #include <string> #include <vector> #include <map> #include <wire/idl/ast.hpp> namespace wire { namespace idl { namespace lua { struct mapped_type { static grammar::annotation_list const empty_annotations; ast::type_const_ptr type; grammar::annotation_list const& annotations = empty_annotations; mapped_type(ast::type_const_ptr t, grammar::annotation_list const& al = empty_annotations) : type{t}, annotations{al} {} }; inline mapped_type arg_type(ast::type_const_ptr t) { return { t }; } inline mapped_type arg_type(ast::type_const_ptr t, grammar::annotation_list const& al) { return { t, al }; } } /* namespace lua */ } /* namespace idl */ } /* namespace wire */ #endif /* WIRE_WIRE2LUA_MAPPED_TYPE_HPP_ */
18.647059
68
0.6898
zmij
3324cac708b1831a6e195ba880ee4ef9fb6701e9
646
cpp
C++
src/detail/string_convert.cpp
Guekka/libbsarch-cpp
ad435d488e9a816e0109a6f464961d177d3b61f4
[ "MIT" ]
1
2021-06-16T15:49:07.000Z
2021-06-16T15:49:07.000Z
src/detail/string_convert.cpp
Guekka/libbsarch-cpp
ad435d488e9a816e0109a6f464961d177d3b61f4
[ "MIT" ]
null
null
null
src/detail/string_convert.cpp
Guekka/libbsarch-cpp
ad435d488e9a816e0109a6f464961d177d3b61f4
[ "MIT" ]
null
null
null
/* Copyright (C) 2021 G'k * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ #include "string_convert.hpp" #include <codecvt> #include <locale> namespace libbsarch::detail { static std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> s_converter; std::string to_string(const std::wstring &str) { return s_converter.to_bytes(str); } std::wstring to_wstring(const std::string &str) { return s_converter.from_bytes(str); } } // namespace libbsarch::detail
26.916667
75
0.704334
Guekka
3328adb3ce2e318a1b5a6ffec85e6d470df7f3a0
2,692
cpp
C++
tests/utils.cpp
vle-forge/Echll
f3895dc721ec891b5828fcd17aec0d37be07fb60
[ "BSD-2-Clause" ]
null
null
null
tests/utils.cpp
vle-forge/Echll
f3895dc721ec891b5828fcd17aec0d37be07fb60
[ "BSD-2-Clause" ]
null
null
null
tests/utils.cpp
vle-forge/Echll
f3895dc721ec891b5828fcd17aec0d37be07fb60
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 2013-2014 INRA * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <vle/context.hpp> #include <vle/utils.hpp> #include <cstring> #define CATCH_CONFIG_MAIN #include "catch.hpp" TEST_CASE("try-stringf-format", "run") { const std::string str500( "01234567890123456789012345678901234567890123456789" "01234567890123456789012345678901234567890123456789" "01234567890123456789012345678901234567890123456789" "01234567890123456789012345678901234567890123456789" "01234567890123456789012345678901234567890123456789" "01234567890123456789012345678901234567890123456789" "01234567890123456789012345678901234567890123456789" "01234567890123456789012345678901234567890123456789" "01234567890123456789012345678901234567890123456789" "01234567890123456789012345678901234567890123456789"); std::string small = vle::stringf("%d %d %d", 1, 2, 3); REQUIRE(std::strcmp(small.c_str(), "1 2 3") == 0); REQUIRE(str500.size() == 500u); std::string big; REQUIRE_NOTHROW(big = vle::stringf("%s%s%s%s%s", str500.c_str(), str500.c_str(), str500.c_str(), str500.c_str(), str500.c_str())); REQUIRE(big.size() == (500u * 5 + 1)); }
44.866667
79
0.688707
vle-forge
06a4a6a81b66d5914b5cb512c057c76ba8f6183b
12,948
hxx
C++
src/engine/ivp/ivp_controller/ivp_car_system.hxx
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/engine/ivp/ivp_controller/ivp_car_system.hxx
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/engine/ivp/ivp_controller/ivp_car_system.hxx
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
// Copyright (C) Ipion Software GmbH 1999-2000. All rights reserved. // IVP_EXPORT_PUBLIC #if !defined(IVP_CAR_SYSTEM_INCLUDED) # define IVP_CAR_SYSTEM_INCLUDED #ifndef IVP_LISTENER_PSI_INCLUDED # include <ivp_listener_psi.hxx> #endif enum IVP_POS_WHEEL { IVP_FRONT_LEFT = 0, IVP_FRONT_RIGHT = 1, IVP_REAR_LEFT = 2, IVP_REAR_RIGHT = 3, IVP_CAR_SYSTEM_MAX_WHEELS = 10 }; enum IVP_POS_AXIS { IVP_FRONT = 0, IVP_REAR = 1, IVP_CAR_SYSTEM_MAX_AXIS = 5 }; class IVP_Real_Object; class IVP_Actuator_Torque; class IVP_Constraint_Solver_Car; class IVP_Template_Car_System { public: // Fill in template to build up a functional // car out of given (and set up) IVP_Real_Objects. int n_wheels; int n_axis; /*** Coordinate System Data ***/ /*** Coordinate System Data ***/ IVP_COORDINATE_INDEX index_x; IVP_COORDINATE_INDEX index_y; IVP_COORDINATE_INDEX index_z; IVP_BOOL is_left_handed; /*** Instance Data ***/ /*** Instance Data ***/ IVP_Real_Object *car_body; /******************************************************************************** * Name: car_wheel * Description: the wheels of the car * Note: Not needed of IVP_Controller_Raycast_Car ********************************************************************************/ IVP_Real_Object *car_wheel[IVP_CAR_SYSTEM_MAX_WHEELS]; // index according to IVP_POS_WHEEL IVP_FLOAT friction_of_wheel[IVP_CAR_SYSTEM_MAX_WHEELS]; // to be set for IVP_Controller_Raycast_Car IVP_FLOAT wheel_radius[IVP_CAR_SYSTEM_MAX_WHEELS]; IVP_FLOAT wheel_reversed_sign[IVP_CAR_SYSTEM_MAX_WHEELS]; // Default: 1.0f. Use -1.0f when wheels are turned by 180 degrees. IVP_FLOAT body_counter_torque_factor; // (e.g. 0.3f) for nose dive etc. produced by wheel torque IVP_FLOAT extra_gravity_force_value; // additional gravity force IVP_FLOAT extra_gravity_height_offset; // force anchor height offset relative to center of mass IVP_FLOAT body_down_force_vertical_offset; // vertical offset to mass center for tilted object IVP_FLOAT fast_turn_factor; /*** Archetype Data ***/ /*** Archetype Data ***/ // Standard wheel position IVP_U_Float_Point wheel_pos_Bos[IVP_CAR_SYSTEM_MAX_WHEELS]; // standard position of wheel centers in body's object system IVP_U_Float_Point trace_pos_Bos[IVP_CAR_SYSTEM_MAX_WHEELS]; // standard position of trace centers in body's object system // Springs IVP_FLOAT spring_constant[IVP_CAR_SYSTEM_MAX_WHEELS]; // [Newton/m] IVP_FLOAT spring_dampening[IVP_CAR_SYSTEM_MAX_WHEELS]; // for releasing springs IVP_FLOAT spring_dampening_compression[IVP_CAR_SYSTEM_MAX_WHEELS]; // for compressing springs IVP_FLOAT max_body_force[IVP_CAR_SYSTEM_MAX_WHEELS]; // clipping of spring forces. Reduces the jumpy behaviour of cars with heavy wheels IVP_FLOAT spring_pre_tension[IVP_CAR_SYSTEM_MAX_WHEELS]; // [m] used to keep the wheels at the original position IVP_FLOAT raycast_startpoint_height_offset; // Stabilizer IVP_FLOAT stabilizer_constant[IVP_CAR_SYSTEM_MAX_AXIS]; // [Newton/m] // Etc IVP_FLOAT wheel_max_rotation_speed[IVP_CAR_SYSTEM_MAX_AXIS]; // Car System Setup IVP_Template_Car_System(int n_wheels_, int n_axis_) { P_MEM_CLEAR(this); n_wheels = n_wheels_; n_axis = n_axis_; for (int i = 0; i < n_wheels; i++) { // not reversed by default this->wheel_reversed_sign[i] = 1.0f; // default coordinate system definition index_x = IVP_INDEX_X; index_y = IVP_INDEX_Y; index_z = IVP_INDEX_Z; is_left_handed = IVP_FALSE; } fast_turn_factor = 1.0f; }; }; class IVP_Wheel_Skid_Info { public: IVP_U_Float_Point last_contact_position_ws; IVP_FLOAT last_skid_value; // 0 means no skidding, values > 0 means skidding, check yourself for reasonable ranges IVP_Time last_skid_time; }; struct IVP_CarSystemDebugData_t { IVP_U_Point wheelRaycasts[IVP_CAR_SYSTEM_MAX_WHEELS][2]; // wheels, start = 0, end = 1 IVP_FLOAT wheelRaycastImpacts[IVP_CAR_SYSTEM_MAX_WHEELS]; // wheels, impact raycast floating point min distance // 4-wheel vehicle. IVP_FLOAT wheelRotationalTorque[4][3]; IVP_FLOAT wheelTranslationTorque[4][3]; IVP_U_Float_Point backActuatorLeft; IVP_U_Float_Point backActuatorRight; IVP_U_Float_Point frontActuatorLeft; IVP_U_Float_Point frontActuatorRight; }; class IVP_Car_System { public: virtual ~IVP_Car_System(); IVP_Car_System(); virtual void do_steering_wheel(IVP_POS_WHEEL wheel_pos, IVP_FLOAT s_angle) = 0; // called by do_steering() // Car Adjustment virtual void change_spring_constant(IVP_POS_WHEEL pos, IVP_FLOAT spring_constant) = 0; // [Newton/meter] virtual void change_spring_dampening(IVP_POS_WHEEL pos, IVP_FLOAT spring_dampening) = 0; // when spring is relaxing spring virtual void change_spring_dampening_compression(IVP_POS_WHEEL pos, IVP_FLOAT spring_dampening) = 0; // [Newton/meter] for compressing spring virtual void change_max_body_force(IVP_POS_WHEEL wheel_nr, IVP_FLOAT mforce) = 0; virtual void change_spring_pre_tension(IVP_POS_WHEEL pos, IVP_FLOAT pre_tension_length) = 0; virtual void change_spring_length(IVP_POS_WHEEL wheel_nr, IVP_FLOAT spring_length) = 0; virtual void change_stabilizer_constant(IVP_POS_AXIS pos, IVP_FLOAT stabi_constant) = 0; // [Newton/meter] virtual void change_fast_turn_factor(IVP_FLOAT fast_turn_factor) = 0; virtual void change_wheel_torque(IVP_POS_WHEEL pos, IVP_FLOAT torque) = 0; virtual void update_body_countertorque() = 0; // rotate the body in the opposite direction of the wheels virtual void update_throttle(IVP_FLOAT flThrottle) = 0; virtual void change_body_downforce(IVP_FLOAT force) = 0; // extra force to keep flipped objects flipped over virtual void fix_wheel(IVP_POS_WHEEL, IVP_BOOL stop_wheel) = 0; // stop wheel completely (e.g. handbrake ) // Car Info virtual IVP_DOUBLE get_body_speed(IVP_COORDINATE_INDEX idx_z = IVP_INDEX_Z) = 0; // km/h in 'z' direction virtual IVP_DOUBLE get_wheel_angular_velocity(IVP_POS_WHEEL) = 0; virtual void update_wheel_positions() = 0; // move graphical wheels to correct position virtual IVP_DOUBLE get_orig_front_wheel_distance() = 0; virtual IVP_DOUBLE get_orig_axles_distance() = 0; virtual void get_skid_info(IVP_Wheel_Skid_Info *array_of_skid_info_out) = 0; virtual void set_powerslide(IVP_FLOAT front_accel, IVP_FLOAT rear_accel) = 0; // Tools static IVP_FLOAT calc_ackerman_angle(IVP_FLOAT alpha, IVP_FLOAT dx, IVP_FLOAT dz); // alpha refers to innermost wheel /**** Methods: 2nd Level, based on primitives ****/ /**** Methods: 2nd Level, based on primitives ****/ virtual void do_steering(IVP_FLOAT steering_angle_in, bool bAnalog = false) = 0; // updates this->steering_angle virtual void set_booster_acceleration(IVP_FLOAT acceleration) = 0; // set an additional accerleration force virtual void activate_booster(IVP_FLOAT thrust, IVP_FLOAT duration, IVP_FLOAT recharge_time) = 0; // set a temporary acceleration force as a factor of gravity virtual void update_booster( IVP_FLOAT delta_time) = 0; // should be called every frame to allow the physics system to deactivate a booster virtual IVP_FLOAT get_booster_delay() = 0; virtual IVP_FLOAT get_booster_time_to_go() = 0; // Debug (Getting debug data out to vphysics and the engine to be rendered!) virtual void SetCarSystemDebugData(const IVP_CarSystemDebugData_t &carSystemDebugData) = 0; virtual void GetCarSystemDebugData(IVP_CarSystemDebugData_t &carSystemDebugData) = 0; // handle events virtual void event_object_deleted(IVP_Event_Object *pEvent) {}; }; class IVP_Car_System_Real_Wheels : public IVP_Car_System { private: IVP_Environment *environment; int n_wheels; // number of wheels int n_axis; protected: IVP_Real_Object *car_body; IVP_Real_Object *car_wheel[IVP_CAR_SYSTEM_MAX_WHEELS]; // index according to IVP_POS_WHEEL IVP_Constraint_Solver_Car *car_constraint_solver; IVP_Actuator_Torque *car_act_torque_body; IVP_Actuator_Torque *car_act_torque[IVP_CAR_SYSTEM_MAX_WHEELS]; IVP_Actuator_Suspension *car_spring[IVP_CAR_SYSTEM_MAX_WHEELS]; IVP_Actuator_Stabilizer *car_stabilizer[IVP_CAR_SYSTEM_MAX_AXIS]; IVP_Actuator_Force *car_act_down_force; IVP_Actuator_Force *car_act_extra_gravity; IVP_Actuator_Force *car_act_powerslide_back; IVP_Actuator_Force *car_act_powerslide_front; IVP_Constraint *fix_wheel_constraint[IVP_CAR_SYSTEM_MAX_WHEELS]; IVP_FLOAT wheel_reversed_sign[IVP_CAR_SYSTEM_MAX_WHEELS]; // Default: 1.0f. Use -1.0f when wheels are turned by 180 degrees. IVP_FLOAT wheel_radius[IVP_CAR_SYSTEM_MAX_WHEELS]; IVP_FLOAT body_counter_torque_factor; // response to wheel torque, e.g. 0.3f (for nose dive etc.), call update_body_countertorque() when all wheel torques are changed IVP_FLOAT max_speed; IVP_FLOAT fast_turn_factor; // factor to angular accelerates the car if the wheels are steered ( 0.0f no effect 1.0f strong effect ) // booster IVP_Actuator_Force *booster_actuator[2]; IVP_FLOAT booster_seconds_to_go; IVP_FLOAT booster_seconds_until_ready; IVP_FLOAT steering_angle; // Debug IVP_CarSystemDebugData_t m_CarSystemDebugData; virtual void environment_will_be_deleted(IVP_Environment *); public: /**** Methods: Primitives ****/ /**** Methods: Primitives ****/ // Car Basics IVP_Car_System_Real_Wheels(IVP_Environment *environment, IVP_Template_Car_System *); virtual ~IVP_Car_System_Real_Wheels(); void do_steering_wheel(IVP_POS_WHEEL wheel_pos, IVP_FLOAT s_angle); // called by do_steering() // Car Adjustment void change_spring_constant(IVP_POS_WHEEL pos, IVP_FLOAT spring_constant); // [Newton/meter] void change_spring_dampening(IVP_POS_WHEEL pos, IVP_FLOAT spring_dampening); // when spring is relaxing spring void change_spring_dampening_compression(IVP_POS_WHEEL pos, IVP_FLOAT spring_dampening); // [Newton/meter] for compressing spring void change_max_body_force(IVP_POS_WHEEL wheel_nr, IVP_FLOAT mforce); void change_spring_pre_tension(IVP_POS_WHEEL pos, IVP_FLOAT pre_tension_length); void change_spring_length(IVP_POS_WHEEL wheel_nr, IVP_FLOAT spring_length); void change_stabilizer_constant(IVP_POS_AXIS pos, IVP_FLOAT stabi_constant); // [Newton/meter] void change_fast_turn_factor(IVP_FLOAT); void change_wheel_torque(IVP_POS_WHEEL pos, IVP_FLOAT torque); void change_wheel_speed_dampening(IVP_POS_WHEEL wheel_nr, IVP_FLOAT dampening); void update_body_countertorque(); // rotate the body in the opposite direction of the wheels void update_throttle(IVP_FLOAT /*flThrottle*/) {} void change_body_downforce(IVP_FLOAT force); // extra force to keep flipped objects flipped over void fix_wheel(IVP_POS_WHEEL, IVP_BOOL stop_wheel); // stop wheel completely (e.g. handbrake ) // Car Info IVP_DOUBLE get_body_speed(IVP_COORDINATE_INDEX idx_z = IVP_INDEX_Z); // km/h in 'z' direction IVP_DOUBLE get_wheel_angular_velocity(IVP_POS_WHEEL); void update_wheel_positions() { ; }; IVP_DOUBLE get_orig_front_wheel_distance(); IVP_DOUBLE get_orig_axles_distance(); void get_skid_info(IVP_Wheel_Skid_Info *array_of_skid_info_out); void set_powerslide(IVP_FLOAT front_accel, IVP_FLOAT rear_accel); /**** Methods: 2nd Level, based on primitives ****/ /**** Methods: 2nd Level, based on primitives ****/ virtual void do_steering(IVP_FLOAT steering_angle_in, bool bAnalog = false); // updates this->steering_angle void set_booster_acceleration(IVP_FLOAT acceleration); void activate_booster(IVP_FLOAT thrust, IVP_FLOAT duration, IVP_FLOAT recharge_time); void update_booster(IVP_FLOAT delta_time); virtual IVP_FLOAT get_booster_delay(); virtual IVP_FLOAT get_booster_time_to_go() { return booster_seconds_to_go; } // Debug void SetCarSystemDebugData(const IVP_CarSystemDebugData_t &carSystemDebugData); void GetCarSystemDebugData(IVP_CarSystemDebugData_t &carSystemDebugData); }; #endif /* defined IVP_CAR_SYSTEM_INCLUDED */
39.355623
171
0.716095
cstom4994
06aa8e5d64bd0e3e225cbafeb44e93ff3eeb4c28
345
cpp
C++
20200320STL_1/E.FreeListSort.cpp
Guyutongxue/Practice_of_Programming
70e11cfc0ab6aefbc9e28b279cf3de110426a9b9
[ "WTFPL" ]
6
2020-03-01T03:13:37.000Z
2021-03-20T13:37:11.000Z
20200320STL_1/E.FreeListSort.cpp
Guyutongxue/Practice_of_Programming
70e11cfc0ab6aefbc9e28b279cf3de110426a9b9
[ "WTFPL" ]
null
null
null
20200320STL_1/E.FreeListSort.cpp
Guyutongxue/Practice_of_Programming
70e11cfc0ab6aefbc9e28b279cf3de110426a9b9
[ "WTFPL" ]
3
2020-03-28T03:14:24.000Z
2021-05-20T13:35:15.000Z
#include <algorithm> #include <cstdio> #include <iostream> #include <list> using namespace std; int main() { double a[] = {1.2, 3.4, 9.8, 7.3, 2.6}; list<double> lst(a, a + 5); lst.sort( greater<double>() ); for (list<double>::iterator i = lst.begin(); i != lst.end(); ++i) cout << *i << ","; return 0; }
21.5625
69
0.527536
Guyutongxue
06b3eb3ccbd708291794a1091be8181e797b4350
2,770
hpp
C++
code/lib/graph_operations.hpp
Brunovsky/competitive
41cf49378e430ca20d844f97c67aa5059ab1e973
[ "MIT" ]
7
2020-10-15T22:37:10.000Z
2022-02-26T17:23:49.000Z
code/lib/graph_operations.hpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
null
null
null
code/lib/graph_operations.hpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
null
null
null
#pragma once #include "hash.hpp" #include "random.hpp" using edges_t = vector<array<int, 2>>; /** * Construct adjacency lists */ auto make_adjacency_lists_undirected(int V, const edges_t& g) { vector<vector<int>> adj(V); for (auto [u, v] : g) assert(u < V && v < V), adj[u].push_back(v), adj[v].push_back(u); return adj; } auto make_adjacency_lists_directed(int V, const edges_t& g) { vector<vector<int>> adj(V); for (auto [u, v] : g) assert(u < V && v < V), adj[u].push_back(v); return adj; } auto make_adjacency_lists_reverse(int V, const edges_t& g) { vector<vector<int>> adj(V); for (auto [u, v] : g) assert(u < V && v < V), adj[v].push_back(u); return adj; } auto make_adjacency_set_undirected(const edges_t& g) { unordered_set<array<int, 2>> adj; for (auto [u, v] : g) u < v ? adj.insert({u, v}) : adj.insert({v, u}); return adj; } auto make_adjacency_set_directed(const edges_t& g) { unordered_set<array<int, 2>> adj; for (auto [u, v] : g) adj.insert({u, v}); return adj; } auto make_adjacency_set_reverse(const edges_t& g) { unordered_set<array<int, 2>> adj; for (auto [u, v] : g) adj.insert({v, u}); return adj; } /** * Check if a graph is (strongly) connected */ int count_reachable(const vector<vector<int>>& adj, int s = 0) { int i = 0, S = 1, V = adj.size(); vector<int> bfs{s}; vector<bool> vis(V, false); vis[s] = true; while (i++ < S && S < V) { for (int v : adj[bfs[i - 1]]) { if (!vis[v]) { vis[v] = true, S++; bfs.push_back(v); } } } return S; } bool reachable(const vector<vector<int>>& adj, int s, int t) { int i = 0, S = 1, V = adj.size(); vector<bool> vis(V, false); vector<int> bfs{s}; vis[s] = true; while (i++ < S && S < V) { for (int v : adj[bfs[i - 1]]) { if (!vis[v]) { vis[v] = true, S++; bfs.push_back(v); if (v == t) return true; } } } return false; } bool is_connected_undirected(const edges_t& g, int V) { assert(V > 0); auto adj = make_adjacency_lists_undirected(V, g); return count_reachable(adj) == V; } bool is_connected_directed(const edges_t& g, int V) { assert(V > 0); auto adj = make_adjacency_lists_directed(V, g); if (count_reachable(adj) != V) return false; adj = make_adjacency_lists_reverse(V, g); return count_reachable(adj) == V; } bool is_rooted_directed(const edges_t& g, int V, int s = 0) { assert(V > 0); auto adj = make_adjacency_lists_directed(V, g); return count_reachable(adj, s) == V; }
25.181818
73
0.552708
Brunovsky
06b4a9405c7fc27d5c3844ad93dbd66cc5c6c601
800
cpp
C++
src/backend/expression/tuple_address_expression.cpp
jessesleeping/my_peloton
a19426cfe34a04692a11008eaffc9c3c9b49abc4
[ "Apache-2.0" ]
6
2017-04-28T00:38:52.000Z
2018-11-06T07:06:49.000Z
src/backend/expression/tuple_address_expression.cpp
jessesleeping/my_peloton
a19426cfe34a04692a11008eaffc9c3c9b49abc4
[ "Apache-2.0" ]
4
2017-07-08T00:41:56.000Z
2017-07-08T00:42:13.000Z
src/backend/expression/tuple_address_expression.cpp
eric-haibin-lin/pelotondb
904d6bbd041a0498ee0e034d4f9f9f27086c3cab
[ "Apache-2.0" ]
1
2020-06-19T08:05:03.000Z
2020-06-19T08:05:03.000Z
//===----------------------------------------------------------------------===// // // PelotonDB // // tuple_address_expression.cpp // // Identification: src/backend/expression/tuple_address_expression.cpp // // Copyright (c) 2015, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "backend/expression/tuple_address_expression.h" #include "backend/common/logger.h" #include "backend/expression/abstract_expression.h" namespace peloton { namespace expression { TupleAddressExpression::TupleAddressExpression() : AbstractExpression(EXPRESSION_TYPE_VALUE_TUPLE_ADDRESS) {} TupleAddressExpression::~TupleAddressExpression() {} } // End expression namespace } // End peloton namespace
29.62963
80
0.60625
jessesleeping
06b5f8c149cd7360c43382bef6ae7fb3c9bd3c69
18,024
cxx
C++
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimPerformanceCurve_Mathematical_FanPressureRise.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
3
2016-05-30T15:12:16.000Z
2022-03-22T08:11:13.000Z
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimPerformanceCurve_Mathematical_FanPressureRise.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
21
2016-06-13T11:33:45.000Z
2017-05-23T09:46:52.000Z
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimPerformanceCurve_Mathematical_FanPressureRise.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
null
null
null
// Copyright (c) 2005-2014 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema to // C++ data binding compiler. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // // In addition, as a special exception, Code Synthesis Tools CC gives // permission to link this program with the Xerces-C++ library (or with // modified versions of Xerces-C++ that use the same license as Xerces-C++), // and distribute linked combinations including the two. You must obey // the GNU General Public License version 2 in all respects for all of // the code used other than Xerces-C++. If you modify this copy of the // program, you may extend this exception to your version of the program, // but you are not obligated to do so. If you do not wish to do so, delete // this exception statement from your version. // // Furthermore, Code Synthesis Tools CC makes a special exception for // the Free/Libre and Open Source Software (FLOSS) which is described // in the accompanying FLOSSE file. // // Begin prologue. // // // End prologue. #include <xsd/cxx/pre.hxx> #include "SimPerformanceCurve_Mathematical_FanPressureRise.hxx" namespace schema { namespace simxml { namespace ResourcesGeometry { // SimPerformanceCurve_Mathematical_FanPressureRise // const SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_Coeff1C1_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff1C1 () const { return this->SimPerfCurve_Coeff1C1_; } SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_Coeff1C1_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff1C1 () { return this->SimPerfCurve_Coeff1C1_; } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff1C1 (const SimPerfCurve_Coeff1C1_type& x) { this->SimPerfCurve_Coeff1C1_.set (x); } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff1C1 (const SimPerfCurve_Coeff1C1_optional& x) { this->SimPerfCurve_Coeff1C1_ = x; } const SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_Coeff2C2_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff2C2 () const { return this->SimPerfCurve_Coeff2C2_; } SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_Coeff2C2_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff2C2 () { return this->SimPerfCurve_Coeff2C2_; } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff2C2 (const SimPerfCurve_Coeff2C2_type& x) { this->SimPerfCurve_Coeff2C2_.set (x); } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff2C2 (const SimPerfCurve_Coeff2C2_optional& x) { this->SimPerfCurve_Coeff2C2_ = x; } const SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_Coeff3C3_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff3C3 () const { return this->SimPerfCurve_Coeff3C3_; } SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_Coeff3C3_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff3C3 () { return this->SimPerfCurve_Coeff3C3_; } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff3C3 (const SimPerfCurve_Coeff3C3_type& x) { this->SimPerfCurve_Coeff3C3_.set (x); } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff3C3 (const SimPerfCurve_Coeff3C3_optional& x) { this->SimPerfCurve_Coeff3C3_ = x; } const SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_Coeff4C4_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff4C4 () const { return this->SimPerfCurve_Coeff4C4_; } SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_Coeff4C4_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff4C4 () { return this->SimPerfCurve_Coeff4C4_; } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff4C4 (const SimPerfCurve_Coeff4C4_type& x) { this->SimPerfCurve_Coeff4C4_.set (x); } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff4C4 (const SimPerfCurve_Coeff4C4_optional& x) { this->SimPerfCurve_Coeff4C4_ = x; } const SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_MinValueOfQfan_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MinValueOfQfan () const { return this->SimPerfCurve_MinValueOfQfan_; } SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_MinValueOfQfan_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MinValueOfQfan () { return this->SimPerfCurve_MinValueOfQfan_; } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MinValueOfQfan (const SimPerfCurve_MinValueOfQfan_type& x) { this->SimPerfCurve_MinValueOfQfan_.set (x); } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MinValueOfQfan (const SimPerfCurve_MinValueOfQfan_optional& x) { this->SimPerfCurve_MinValueOfQfan_ = x; } const SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_MaxValueOfQfan_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MaxValueOfQfan () const { return this->SimPerfCurve_MaxValueOfQfan_; } SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_MaxValueOfQfan_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MaxValueOfQfan () { return this->SimPerfCurve_MaxValueOfQfan_; } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MaxValueOfQfan (const SimPerfCurve_MaxValueOfQfan_type& x) { this->SimPerfCurve_MaxValueOfQfan_.set (x); } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MaxValueOfQfan (const SimPerfCurve_MaxValueOfQfan_optional& x) { this->SimPerfCurve_MaxValueOfQfan_ = x; } const SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_MinValueOfPsm_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MinValueOfPsm () const { return this->SimPerfCurve_MinValueOfPsm_; } SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_MinValueOfPsm_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MinValueOfPsm () { return this->SimPerfCurve_MinValueOfPsm_; } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MinValueOfPsm (const SimPerfCurve_MinValueOfPsm_type& x) { this->SimPerfCurve_MinValueOfPsm_.set (x); } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MinValueOfPsm (const SimPerfCurve_MinValueOfPsm_optional& x) { this->SimPerfCurve_MinValueOfPsm_ = x; } const SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_MaxValueOfPsm_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MaxValueOfPsm () const { return this->SimPerfCurve_MaxValueOfPsm_; } SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_MaxValueOfPsm_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MaxValueOfPsm () { return this->SimPerfCurve_MaxValueOfPsm_; } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MaxValueOfPsm (const SimPerfCurve_MaxValueOfPsm_type& x) { this->SimPerfCurve_MaxValueOfPsm_.set (x); } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MaxValueOfPsm (const SimPerfCurve_MaxValueOfPsm_optional& x) { this->SimPerfCurve_MaxValueOfPsm_ = x; } } } } #include <xsd/cxx/xml/dom/parsing-source.hxx> #include <xsd/cxx/tree/type-factory-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::type_factory_plate< 0, char > type_factory_plate_init; } namespace schema { namespace simxml { namespace ResourcesGeometry { // SimPerformanceCurve_Mathematical_FanPressureRise // SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerformanceCurve_Mathematical_FanPressureRise () : ::schema::simxml::ResourcesGeometry::SimPerformanceCurve_Mathematical (), SimPerfCurve_Coeff1C1_ (this), SimPerfCurve_Coeff2C2_ (this), SimPerfCurve_Coeff3C3_ (this), SimPerfCurve_Coeff4C4_ (this), SimPerfCurve_MinValueOfQfan_ (this), SimPerfCurve_MaxValueOfQfan_ (this), SimPerfCurve_MinValueOfPsm_ (this), SimPerfCurve_MaxValueOfPsm_ (this) { } SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerformanceCurve_Mathematical_FanPressureRise (const RefId_type& RefId) : ::schema::simxml::ResourcesGeometry::SimPerformanceCurve_Mathematical (RefId), SimPerfCurve_Coeff1C1_ (this), SimPerfCurve_Coeff2C2_ (this), SimPerfCurve_Coeff3C3_ (this), SimPerfCurve_Coeff4C4_ (this), SimPerfCurve_MinValueOfQfan_ (this), SimPerfCurve_MaxValueOfQfan_ (this), SimPerfCurve_MinValueOfPsm_ (this), SimPerfCurve_MaxValueOfPsm_ (this) { } SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerformanceCurve_Mathematical_FanPressureRise (const SimPerformanceCurve_Mathematical_FanPressureRise& x, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::ResourcesGeometry::SimPerformanceCurve_Mathematical (x, f, c), SimPerfCurve_Coeff1C1_ (x.SimPerfCurve_Coeff1C1_, f, this), SimPerfCurve_Coeff2C2_ (x.SimPerfCurve_Coeff2C2_, f, this), SimPerfCurve_Coeff3C3_ (x.SimPerfCurve_Coeff3C3_, f, this), SimPerfCurve_Coeff4C4_ (x.SimPerfCurve_Coeff4C4_, f, this), SimPerfCurve_MinValueOfQfan_ (x.SimPerfCurve_MinValueOfQfan_, f, this), SimPerfCurve_MaxValueOfQfan_ (x.SimPerfCurve_MaxValueOfQfan_, f, this), SimPerfCurve_MinValueOfPsm_ (x.SimPerfCurve_MinValueOfPsm_, f, this), SimPerfCurve_MaxValueOfPsm_ (x.SimPerfCurve_MaxValueOfPsm_, f, this) { } SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerformanceCurve_Mathematical_FanPressureRise (const ::xercesc::DOMElement& e, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::ResourcesGeometry::SimPerformanceCurve_Mathematical (e, f | ::xml_schema::flags::base, c), SimPerfCurve_Coeff1C1_ (this), SimPerfCurve_Coeff2C2_ (this), SimPerfCurve_Coeff3C3_ (this), SimPerfCurve_Coeff4C4_ (this), SimPerfCurve_MinValueOfQfan_ (this), SimPerfCurve_MaxValueOfQfan_ (this), SimPerfCurve_MinValueOfPsm_ (this), SimPerfCurve_MaxValueOfPsm_ (this) { if ((f & ::xml_schema::flags::base) == 0) { ::xsd::cxx::xml::dom::parser< char > p (e, true, false, true); this->parse (p, f); } } void SimPerformanceCurve_Mathematical_FanPressureRise:: parse (::xsd::cxx::xml::dom::parser< char >& p, ::xml_schema::flags f) { this->::schema::simxml::ResourcesGeometry::SimPerformanceCurve_Mathematical::parse (p, f); for (; p.more_content (); p.next_content (false)) { const ::xercesc::DOMElement& i (p.cur_element ()); const ::xsd::cxx::xml::qualified_name< char > n ( ::xsd::cxx::xml::dom::name< char > (i)); // SimPerfCurve_Coeff1C1 // if (n.name () == "SimPerfCurve_Coeff1C1" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeometry") { if (!this->SimPerfCurve_Coeff1C1_) { this->SimPerfCurve_Coeff1C1_.set (SimPerfCurve_Coeff1C1_traits::create (i, f, this)); continue; } } // SimPerfCurve_Coeff2C2 // if (n.name () == "SimPerfCurve_Coeff2C2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeometry") { if (!this->SimPerfCurve_Coeff2C2_) { this->SimPerfCurve_Coeff2C2_.set (SimPerfCurve_Coeff2C2_traits::create (i, f, this)); continue; } } // SimPerfCurve_Coeff3C3 // if (n.name () == "SimPerfCurve_Coeff3C3" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeometry") { if (!this->SimPerfCurve_Coeff3C3_) { this->SimPerfCurve_Coeff3C3_.set (SimPerfCurve_Coeff3C3_traits::create (i, f, this)); continue; } } // SimPerfCurve_Coeff4C4 // if (n.name () == "SimPerfCurve_Coeff4C4" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeometry") { if (!this->SimPerfCurve_Coeff4C4_) { this->SimPerfCurve_Coeff4C4_.set (SimPerfCurve_Coeff4C4_traits::create (i, f, this)); continue; } } // SimPerfCurve_MinValueOfQfan // if (n.name () == "SimPerfCurve_MinValueOfQfan" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeometry") { if (!this->SimPerfCurve_MinValueOfQfan_) { this->SimPerfCurve_MinValueOfQfan_.set (SimPerfCurve_MinValueOfQfan_traits::create (i, f, this)); continue; } } // SimPerfCurve_MaxValueOfQfan // if (n.name () == "SimPerfCurve_MaxValueOfQfan" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeometry") { if (!this->SimPerfCurve_MaxValueOfQfan_) { this->SimPerfCurve_MaxValueOfQfan_.set (SimPerfCurve_MaxValueOfQfan_traits::create (i, f, this)); continue; } } // SimPerfCurve_MinValueOfPsm // if (n.name () == "SimPerfCurve_MinValueOfPsm" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeometry") { if (!this->SimPerfCurve_MinValueOfPsm_) { this->SimPerfCurve_MinValueOfPsm_.set (SimPerfCurve_MinValueOfPsm_traits::create (i, f, this)); continue; } } // SimPerfCurve_MaxValueOfPsm // if (n.name () == "SimPerfCurve_MaxValueOfPsm" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeometry") { if (!this->SimPerfCurve_MaxValueOfPsm_) { this->SimPerfCurve_MaxValueOfPsm_.set (SimPerfCurve_MaxValueOfPsm_traits::create (i, f, this)); continue; } } break; } } SimPerformanceCurve_Mathematical_FanPressureRise* SimPerformanceCurve_Mathematical_FanPressureRise:: _clone (::xml_schema::flags f, ::xml_schema::container* c) const { return new class SimPerformanceCurve_Mathematical_FanPressureRise (*this, f, c); } SimPerformanceCurve_Mathematical_FanPressureRise& SimPerformanceCurve_Mathematical_FanPressureRise:: operator= (const SimPerformanceCurve_Mathematical_FanPressureRise& x) { if (this != &x) { static_cast< ::schema::simxml::ResourcesGeometry::SimPerformanceCurve_Mathematical& > (*this) = x; this->SimPerfCurve_Coeff1C1_ = x.SimPerfCurve_Coeff1C1_; this->SimPerfCurve_Coeff2C2_ = x.SimPerfCurve_Coeff2C2_; this->SimPerfCurve_Coeff3C3_ = x.SimPerfCurve_Coeff3C3_; this->SimPerfCurve_Coeff4C4_ = x.SimPerfCurve_Coeff4C4_; this->SimPerfCurve_MinValueOfQfan_ = x.SimPerfCurve_MinValueOfQfan_; this->SimPerfCurve_MaxValueOfQfan_ = x.SimPerfCurve_MaxValueOfQfan_; this->SimPerfCurve_MinValueOfPsm_ = x.SimPerfCurve_MinValueOfPsm_; this->SimPerfCurve_MaxValueOfPsm_ = x.SimPerfCurve_MaxValueOfPsm_; } return *this; } SimPerformanceCurve_Mathematical_FanPressureRise:: ~SimPerformanceCurve_Mathematical_FanPressureRise () { } } } } #include <istream> #include <xsd/cxx/xml/sax/std-input-source.hxx> #include <xsd/cxx/tree/error-handler.hxx> namespace schema { namespace simxml { namespace ResourcesGeometry { } } } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue.
36.708758
150
0.684365
EnEff-BIM
06b6b5eeaebceef76699e8b9300e1c9b7f4eea6d
316
hxx
C++
include/acl/export.hxx
obhi-d/acl
8860227ffceff559b32425bdab7419fb99a807d4
[ "MIT" ]
null
null
null
include/acl/export.hxx
obhi-d/acl
8860227ffceff559b32425bdab7419fb99a807d4
[ "MIT" ]
null
null
null
include/acl/export.hxx
obhi-d/acl
8860227ffceff559b32425bdab7419fb99a807d4
[ "MIT" ]
null
null
null
//! A single file must include this one time, this contains mostly debug info collectors #pragma once #include "allocator.hpp" #include <sstream> namespace acl::detail { #ifdef ACL_REC_STATS detail::statistics<default_allocator_tag, true> default_allocator_statistics_instance; #endif } // namespace acl::detail
21.066667
88
0.791139
obhi-d
06ba76bc509b9136ced0ca62bd57d523ae68b43d
506
cpp
C++
src/Messages/AcceptPlayRequestMessage.cpp
BigETI/WhackAStoodentServer
05c670a9b745262ae926aebcb1fce0f1ecc5f4d2
[ "MIT" ]
1
2021-04-28T20:32:57.000Z
2021-04-28T20:32:57.000Z
src/Messages/AcceptPlayRequestMessage.cpp
BigETI/WhackAStoodentServer
05c670a9b745262ae926aebcb1fce0f1ecc5f4d2
[ "MIT" ]
7
2021-08-24T14:09:33.000Z
2021-08-30T12:47:40.000Z
src/Messages/AcceptPlayRequestMessage.cpp
BigETI/WhackAStoodentServer
05c670a9b745262ae926aebcb1fce0f1ecc5f4d2
[ "MIT" ]
null
null
null
#include <Messages/AcceptPlayRequestMessage.hpp> /// <summary> /// Constructs an accept playe request message /// </summary> WhackAStoodentServer::Messages::AcceptPlayRequestMessage::AcceptPlayRequestMessage() : WhackAStoodentServer::Messages::ASerializableMessage<WhackAStoodentServer::EMessageType::AcceptPlayRequest>() { // ... } /// <summary> /// Destroys accept playe request message /// </summary> WhackAStoodentServer::Messages::AcceptPlayRequestMessage::~AcceptPlayRequestMessage() { // ... }
26.631579
110
0.768775
BigETI
06bda34131bfb20597f540583fb588a3dd20cac9
12,336
cpp
C++
dec15-1.cpp
balazs-bamer/adventofcode19
d8166ccbd1d531db1269dfd24065ba552397e884
[ "MIT" ]
1
2019-12-09T16:14:27.000Z
2019-12-09T16:14:27.000Z
dec15-1.cpp
balazs-bamer/adventofcode19
d8166ccbd1d531db1269dfd24065ba552397e884
[ "MIT" ]
null
null
null
dec15-1.cpp
balazs-bamer/adventofcode19
d8166ccbd1d531db1269dfd24065ba552397e884
[ "MIT" ]
null
null
null
#include <list> #include <array> #include <deque> #include <limits> #include <chrono> #include <cctype> #include <fstream> #include <utility> #include <iostream> #include <functional> #include <stdexcept> #include <algorithm> #include <unordered_map> class Int final { private: int mInt; public: Int(int aInt) noexcept : mInt(aInt) { } Int(std::string &aString) : mInt(std::stoi(aString)) { } int toInt() const noexcept { return mInt; } operator int() const noexcept { return mInt; } }; template<typename tNumber> class Intcode final { private: static size_t constexpr cInstLengths[] = {1u, 4u, 4u, 2u, 2u, 3u, 3u, 4u, 4u, 2u, 1u}; static int const cAdd = 1; static int const cMultiply = 2; static int const cInput = 3; static int const cOutput = 4; static int const cJumpIfNot0 = 5; static int const cJumpIf0 = 6; static int const cLessThan = 7; static int const cEquals = 8; static int const cRelativeBase = 9; static int const cInstCount = 10; static int const cHalt = 99; static int const cMaskOpcode = 100; static size_t const cOffsetParameter1 = 1u; static size_t const cOffsetParameter2 = 2u; static size_t const cOffsetResult = 3u; std::list<tNumber> mInputs; std::list<tNumber> mOutputs; std::deque<tNumber> mProgram; std::deque<tNumber> mMemory; size_t mProgramCounter; size_t mRelativeBase; public: Intcode() noexcept = default; Intcode(std::ifstream &aIn) noexcept { while(true) { std::string number; std::getline(aIn, number, ','); if(!aIn.good()) { break; } tNumber integer(number); mProgram.push_back(integer); } } Intcode(Intcode const &aOther) noexcept : mProgram(aOther.mProgram) { } void input(int const aInput) noexcept { mInputs.push_back(aInput); } tNumber output() { return get(mOutputs); } bool hasOutput() { return !mOutputs.empty(); } void start() { mInputs.clear(); mOutputs.clear(); mMemory = mProgram; mProgramCounter = 0u; mRelativeBase = 0u; } void poke(size_t const aLocation, tNumber const &aValue) { expand(aLocation); mMemory[aLocation] = aValue; } bool run() { bool result; while(true) { if(mProgramCounter >= mMemory.size()) { throw std::invalid_argument("Invalid program."); } else { // nothing to do } tNumber opcode = mMemory[mProgramCounter] % cMaskOpcode; if(opcode != cHalt && opcode >= cInstCount) { throw std::invalid_argument("Invalid program."); } else { // nothing to do } bool jumped = false; if(opcode == cAdd) { size_t addressParameter1 = getAddress(cOffsetParameter1); size_t addressParameter2 = getAddress(cOffsetParameter2); size_t addressResult = getAddress(cOffsetResult); mMemory[addressResult] = mMemory[addressParameter1] + mMemory[addressParameter2]; } else if(opcode == cMultiply) { size_t addressParameter1 = getAddress(cOffsetParameter1); size_t addressParameter2 = getAddress(cOffsetParameter2); size_t addressResult = getAddress(cOffsetResult); mMemory[addressResult] = mMemory[addressParameter1] * mMemory[addressParameter2]; } else if(opcode == cInput) { size_t addressParameter1 = getAddress(cOffsetParameter1); if(mInputs.size() == 0u) { result = false; break; } else { mMemory[addressParameter1] = get(mInputs); } } else if(opcode == cOutput) { size_t addressParameter1 = getAddress(cOffsetParameter1); mOutputs.push_back(mMemory[addressParameter1]); } else if(opcode == cJumpIfNot0) { size_t addressToCheck = getAddress(cOffsetParameter1); size_t addressOfJUmp = getAddress(cOffsetParameter2); if(mMemory[addressToCheck] != 0) { mProgramCounter = mMemory[addressOfJUmp].toInt(); jumped = true; } else { // nothing to do } } else if(opcode == cJumpIf0) { size_t addressToCheck = getAddress(cOffsetParameter1); size_t addressOfJUmp = getAddress(cOffsetParameter2); if(mMemory[addressToCheck] == 0) { mProgramCounter = mMemory[addressOfJUmp].toInt(); jumped = true; } else { // nothing to do } } else if(opcode == cLessThan) { size_t addressParameter1 = getAddress(cOffsetParameter1); size_t addressParameter2 = getAddress(cOffsetParameter2); size_t addressResult = getAddress(cOffsetResult); mMemory[addressResult] = (mMemory[addressParameter1] < mMemory[addressParameter2] ? 1 : 0); } else if(opcode == cEquals) { size_t addressParameter1 = getAddress(cOffsetParameter1); size_t addressParameter2 = getAddress(cOffsetParameter2); size_t addressResult = getAddress(cOffsetResult); mMemory[addressResult] = (mMemory[addressParameter1] == mMemory[addressParameter2] ? 1 : 0); } else if(opcode == cRelativeBase) { size_t addressParameter1 = getAddress(cOffsetParameter1); mRelativeBase += mMemory[addressParameter1].toInt(); } else if(opcode == cHalt) { result = true; break; } else { // nothing to do } if(!jumped) { mProgramCounter += cInstLengths[opcode.toInt()]; } else { // nothing to do } } return result; } private: size_t getAddress(size_t const aOffset) { tNumber const dividor[] = {0, 100, 1000, 10000}; tNumber digit = (mMemory[mProgramCounter] / dividor[aOffset]) % 10; size_t result; if(digit == 0) { result = mMemory[mProgramCounter + aOffset].toInt(); } else if(digit == 2) { result = mMemory[mProgramCounter + aOffset].toInt() + mRelativeBase; } else { // else 1, immediate result = mProgramCounter + aOffset; } expand(result); return result; } void expand(size_t const aLocation) { if(aLocation >= mMemory.size()) { tNumber zero{0}; mMemory.resize(aLocation + 1u, zero); } else { // nothing to do } } tNumber get(std::list<tNumber> &aList) { if(aList.size() == 0u) { throw std::invalid_argument("List empty."); } else { // nothing to do } tNumber result = aList.front(); aList.pop_front(); return result; } }; template<typename tNumber> size_t constexpr Intcode<tNumber>::cInstLengths[]; struct Coordinates final { public: static int constexpr cDeltaX[] = { 0, 0, -1, 1}; static int constexpr cDeltaY[] = {-1, 1, 0, 0}; static int constexpr cBackwards[] = { 1, 0, 3, 2}; int x; int y; Coordinates(int const aX, int const aY) : x(aX), y(aY) { } Coordinates operator+(int const aDirection) const noexcept { return Coordinates(x + cDeltaX[aDirection] , y + cDeltaY[aDirection]); } Coordinates& operator+=(int const aDirection) noexcept { x += cDeltaX[aDirection]; y += cDeltaY[aDirection]; return *this; } bool isOrigin() const noexcept { return x == 0 && y == 0; } bool operator==(Coordinates const &aOther) const noexcept { return x == aOther.x && y == aOther.y; } }; int constexpr Coordinates::cDeltaX[]; int constexpr Coordinates::cDeltaY[]; int constexpr Coordinates::cBackwards[]; template<> struct std::hash<Coordinates> { size_t operator()(Coordinates const &aKey) const { return std::hash<int>{}(aKey.x) ^ (std::hash<int>{}(aKey.y) << 1u); } }; class Node final { public: static constexpr size_t cDirectionCount = 4u; static constexpr int cNoParent = -1; private: // index is the <number to control the robot> - 1 std::array<bool, cDirectionCount> mChildren; // Leave so for origin int mParentDirection = cNoParent; bool mInitialized = false; int mDirectionCounter = 0; public: // for origin Node() noexcept { std::fill(mChildren.begin(), mChildren.end(), false); } // for child Node(int const aDirectionFromParent) noexcept : Node() { mParentDirection = Coordinates::cBackwards[aDirectionFromParent]; } void makeChild(int const aDirectionToChild) noexcept { mChildren[aDirectionToChild] = true; } bool isInitialized() const noexcept { return mInitialized; } bool setInitialized() noexcept { mInitialized = true; } int getParentDirection() const noexcept { return mParentDirection; } int getAndAdvanceDirectionCounter() noexcept { for(; mDirectionCounter < cDirectionCount && !mChildren[mDirectionCounter]; ++mDirectionCounter) { } int result = mDirectionCounter; mDirectionCounter = std::min<int>(mDirectionCounter + 1, cDirectionCount); return result; } void resetDirectionCounter() noexcept { mDirectionCounter = 0; } }; class Labyrinth final { private: static int constexpr cOffset = 1; static int constexpr cWall = 0; static int constexpr cMoved = 1; static int constexpr cOxygen = 2; Intcode<Int> mComputer; std::unordered_map<Coordinates, Node> mMap; bool mChanged = false; Coordinates mLocation; int mIteration = 0; public: Labyrinth(std::ifstream &aIn) : mComputer(aIn), mLocation(0, 0) { mComputer.start(); } size_t getShortestPathLengthToOxygen() noexcept { size_t shortest = std::numeric_limits<size_t>::max(); mMap.emplace(mLocation, Node()); while(true) { Node &actual = mMap[mLocation]; int newDirection; if(actual.isInitialized()) { newDirection = step(actual); } else { newDirection = initialize(actual); } if(newDirection == Node::cNoParent) { if(!mChanged) { break; } else { // nothing to do } ++mIteration; mChanged = false; } else { mLocation += newDirection; if(moveRobot(newDirection) == cOxygen) { shortest = (mLocation.isOrigin() ? 0 : mIteration); break; } else { // nothing to do } } } return shortest; } private: int initialize(Node &aActual) noexcept { for(int i = 0; i < Node::cDirectionCount; ++i) { auto newLocation = mLocation + i; if(mMap.find(newLocation) == mMap.end()) { // not seen or wall int result = moveRobot(i); if(result == cMoved || result == cOxygen) { mMap.emplace(newLocation, i); aActual.makeChild(i); moveRobot(Coordinates::cBackwards[i]); mChanged = true; } else { // nothing to do } } else { // nothing to do } } aActual.setInitialized(); return aActual.getParentDirection(); } int step(Node &aActual) noexcept { int newDirection = aActual.getAndAdvanceDirectionCounter(); if(newDirection == Node::cDirectionCount) { aActual.resetDirectionCounter(); newDirection = aActual.getParentDirection(); } else { // nothing to do } return newDirection; } int moveRobot(int const aDirection) { mComputer.input(aDirection + cOffset); mComputer.run(); return mComputer.output().toInt(); } }; int main(int const argc, char **argv) { size_t const cChainLength = 5u; int const cInitialInput = 0; try { if(argc == 1) { throw std::invalid_argument("Need input filename."); } std::ifstream in(argv[1]); Labyrinth labyrinth(in); auto begin = std::chrono::high_resolution_clock::now(); size_t pathLength = labyrinth.getShortestPathLengthToOxygen(); auto end = std::chrono::high_resolution_clock::now(); auto timeSpan = std::chrono::duration_cast<std::chrono::duration<double>>(end - begin); std::cout << "duration: " << timeSpan.count() << '\n'; std::cout << pathLength << '\n'; } catch(std::exception const &e) { std::cerr << e.what() << std::endl; return 1; } return 0; }
27.413333
102
0.613489
balazs-bamer
06be6c05cd8a7f968bd5b57d13263f8480bf8a50
3,140
hpp
C++
include/whack/codegen/elements/args.hpp
onchere/whack
0702e46f13855d4efd8dd0cb67af2fddfb84b00c
[ "Apache-2.0" ]
54
2018-10-28T07:18:31.000Z
2022-03-08T20:30:40.000Z
include/whack/codegen/elements/args.hpp
onchere/whack
0702e46f13855d4efd8dd0cb67af2fddfb84b00c
[ "Apache-2.0" ]
null
null
null
include/whack/codegen/elements/args.hpp
onchere/whack
0702e46f13855d4efd8dd0cb67af2fddfb84b00c
[ "Apache-2.0" ]
5
2018-10-28T14:43:53.000Z
2020-04-26T19:52:58.000Z
/** * Copyright 2018-present Onchere Bironga * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef WHACK_ARGS_HPP #define WHACK_ARGS_HPP #pragma once #include "../types/type.hpp" namespace whack::codegen::elements { class Arg { public: explicit Arg(types::Type&& type, llvm::StringRef name, const bool variadic = false, const bool mut = false) : type{std::forward<types::Type>(type)}, name{name}, variadic{variadic}, mut{mut} {} const types::Type type; llvm::StringRef name; const bool variadic; const bool mut; }; class Args final : public AST { public: explicit Args(const mpc_ast_t* const ast) { const auto tag = getInnermostAstTag(ast); if (tag == "variadicarg") { args_.emplace_back(Arg{types::Type{ast->children[0]->children[0]}, ast->children[1]->contents, true}); } else if (tag == "typeident") { args_.emplace_back( Arg{types::Type{ast->children[0]}, ast->children[1]->contents}); } else { for (auto i = 0; i < ast->children_num; i += 2) { const auto ref = ast->children[i]; if (getInnermostAstTag(ref) == "typeident") { args_.emplace_back( Arg{types::Type{ref->children[0]}, ref->children[1]->contents}); } else { // variadicarg args_.emplace_back(Arg{types::Type{ref->children[0]->children[0]}, ref->children[1]->contents, true}); } } } } inline const auto& arg(const std::size_t index) const { return args_.at(index); } inline const auto& args() const noexcept { return args_; } const llvm::Expected<small_vector<llvm::Type*>> types(llvm::IRBuilder<>& builder) const { small_vector<llvm::Type*> ret; for (const auto& arg : args_) { auto tp = arg.type.codegen(builder); if (!tp) { return tp.takeError(); } auto type = *tp; // @todo if (types::Type::getUnderlyingType(type)->isFunctionTy() || (type->isStructTy() && type->getStructName().startswith("interface::"))) { type = type->getPointerTo(0); } ret.push_back(type); } return ret; } const auto names() const { small_vector<llvm::StringRef> ret; for (const auto& arg : args_) { ret.push_back(arg.name); } return ret; } inline const auto size() const { return args_.size(); } inline const bool variadic() const { return !args_.empty() && args_.back().variadic; } private: std::vector<Arg> args_; }; } // end namespace whack::codegen::elements #endif // WHACK_ARGS_HPP
28.807339
78
0.621019
onchere
06ca27845532ad642ebb1b962842a1fbf55b9066
1,118
hpp
C++
Logger.hpp
PORT-INC/cicada
18730fa951ebf1b92a3116c13ddc75f786595dd1
[ "MIT" ]
null
null
null
Logger.hpp
PORT-INC/cicada
18730fa951ebf1b92a3116c13ddc75f786595dd1
[ "MIT" ]
null
null
null
Logger.hpp
PORT-INC/cicada
18730fa951ebf1b92a3116c13ddc75f786595dd1
[ "MIT" ]
null
null
null
// © 2016 PORT INC. #ifndef LOGGER__H #define LOGGER__H #include "spdlog/spdlog.h" namespace Logger { namespace spd = spdlog; decltype ( spd::stderr_logger_mt("", true) ) out(); void setLevel(int level); void setName(const std::string& name); void setColor(bool flg); void setPattern(const std::string& pattern); int getLevel(); decltype(( out()->trace() )) trace(); decltype(( out()->debug() )) debug(); decltype(( out()->info() )) info(); decltype(( out()->notice() )) notice(); decltype(( out()->warn() )) warn(); decltype(( out()->error() )) error(); decltype(( out()->critical() )) critical(); decltype(( out()->alert() )) alert(); decltype(( out()->trace() )) trace(const char* msg); decltype(( out()->debug() )) debug(const char* msg); decltype(( out()->info() )) info(const char* msg); decltype(( out()->notice() )) notice(const char* msg); decltype(( out()->warn() )) warn(const char* msg); decltype(( out()->error() )) error(const char* msg); decltype(( out()->critical() )) critical(const char* msg); decltype(( out()->alert() )) alert(const char* msg); } #endif // LOGGER__H
27.95
59
0.62254
PORT-INC
06cdbba9971974202cc63958e80a71da8bc866f7
599
cpp
C++
kernel/src/gdt.cpp
cekkr/thor-os
841b088eddc378ef38c98878a51958479dce4a31
[ "MIT" ]
null
null
null
kernel/src/gdt.cpp
cekkr/thor-os
841b088eddc378ef38c98878a51958479dce4a31
[ "MIT" ]
null
null
null
kernel/src/gdt.cpp
cekkr/thor-os
841b088eddc378ef38c98878a51958479dce4a31
[ "MIT" ]
null
null
null
//======================================================================= // Copyright Baptiste Wicht 2013-2016. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://www.opensource.org/licenses/MIT) //======================================================================= #include "gdt.hpp" #include "early_memory.hpp" void gdt::flush_tss(){ asm volatile("mov ax, %0; ltr ax;" : : "i" (gdt::TSS_SELECTOR + 0x3) : "rax"); } gdt::task_state_segment_t& gdt::tss(){ return *reinterpret_cast<task_state_segment_t*>(early::tss_address); }
33.277778
82
0.527546
cekkr
06d18ed979f8f80e67b37a925171e98c9ce375c2
1,403
cpp
C++
cpp/651-660/Find K Closest Elements.cpp
KaiyuWei/leetcode
fd61f5df60cfc7086f7e85774704bacacb4aaa5c
[ "MIT" ]
150
2015-04-04T06:53:49.000Z
2022-03-21T13:32:08.000Z
cpp/651-660/Find K Closest Elements.cpp
yizhu1012/leetcode
d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7
[ "MIT" ]
1
2015-04-13T15:15:40.000Z
2015-04-21T20:23:16.000Z
cpp/651-660/Find K Closest Elements.cpp
yizhu1012/leetcode
d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7
[ "MIT" ]
64
2015-06-30T08:00:07.000Z
2022-01-01T16:44:14.000Z
// Solution 1. class Solution { public: vector<int> findClosestElements(vector<int>& arr, int k, int x) { auto it = lower_bound(arr.begin(), arr.end(), x); int idx = it - arr.begin(); if (idx == arr.size()) { idx--; } else if (idx > 0) { if (abs(arr[idx - 1] - x) <= abs(arr[idx] - x)) { idx = idx - 1; } } int l = idx - 1; int r = idx + 1; for (int i = 2; i <= k; i++) { if (l < 0) { r++; } else if (r >= arr.size()) { l--; } else { if (abs(arr[l] - x) <= abs(arr[r] - x)) { l--; } else { r++; } } } return vector<int>(arr.begin() + l + 1, arr.begin() + r); } }; // Solution 2. class Solution { public: vector<int> findClosestElements(vector<int>& arr, int k, int x) { int left = 0; int right = arr.size() - k; while (left < right) { int mid = (left + right) / 2; if (x - arr[mid] > arr[mid + k] - x) { left = mid + 1; } else { right = mid; } } return vector<int>(arr.begin() + left, arr.begin() + left + k); } };
24.614035
71
0.352815
KaiyuWei
06d7177a575ff3520a80377a7994e37354b1e4fd
11,571
cpp
C++
libloco/src/LocoNetwork.cpp
candycode/loco
4fffb785cf73c577397b107586909a24133ff7c7
[ "BSD-3-Clause" ]
1
2018-07-05T13:43:14.000Z
2018-07-05T13:43:14.000Z
libloco/src/LocoNetwork.cpp
candycode/loco
4fffb785cf73c577397b107586909a24133ff7c7
[ "BSD-3-Clause" ]
null
null
null
libloco/src/LocoNetwork.cpp
candycode/loco
4fffb785cf73c577397b107586909a24133ff7c7
[ "BSD-3-Clause" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// //Copyright (c) 2012, Ugo Varetto //All rights reserved. // //Redistribution and use in source and binary forms, with or without //modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the copyright holder nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND //ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE //DISCLAIMED. IN NO EVENT SHALL UGO VARETTO 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 <QUrl> #include <QNetworkRequest> #include <QNetworkReply> #include <QTimer> #include <QBuffer> #include "LocoNetwork.h" #include "LocoContext.h" #include "LocoURLUtility.h" namespace loco { QVariantMap Http::get( const QString& urlString, int timeout, const QVariantMap& opt ) { QEventLoop loop; QVariantMap reply; QUrl url = ConfigureURL( urlString, opt ); QObject::connect( nam_, SIGNAL( finished( QNetworkReply*) ), &loop, SLOT( quit() ) ); // soft real-time guarantee: kill network request if the total time is >= timeout QTimer::singleShot( timeout, &loop, SLOT( quit() ) ); QNetworkRequest request; request.setUrl( url ); if( opt.contains( "headers" ) ) ConfigureHeaders( request, opt[ "headers" ].toMap() ); QNetworkReply* nr = nam_->get( request ); // Execute the event loop here, now we will wait here until readyRead() signal is emitted // which in turn will trigger event loop quit. loop.exec(); if( nr->error() != QNetworkReply::NoError ) { error( nr->errorString() ); return reply; } if( !nr->isFinished() ) { error( "Network request timeout" ); return reply; } reply[ "content" ] = nr->readAll(); QVariantMap headers; typedef QList< QByteArray > HEADERS; HEADERS rawHeaders = nr->rawHeaderList(); for( HEADERS::const_iterator i = rawHeaders.begin(); i != rawHeaders.end(); ++i ) { if( nr->hasRawHeader( *i ) ) { headers[ QString( *i ) ] = QString( nr->rawHeader( *i ) ); } } reply[ "headers" ] = headers; return reply; } QVariantMap Http::head( const QString& urlString, int timeout, const QVariantMap& opt ) { QEventLoop loop; QVariantMap reply; QUrl url = ConfigureURL( urlString, opt ); QObject::connect( nam_, SIGNAL( finished( QNetworkReply*) ), &loop, SLOT( quit() ) ); // soft real-time guarantee: kill network request if the total time is >= timeout QTimer::singleShot( timeout, &loop, SLOT( quit() ) ); QNetworkRequest request; request.setUrl( url ); if( opt.contains( "headers" ) ) ConfigureHeaders( request, opt[ "headers" ].toMap() ); QNetworkReply* nr = nam_->head( request ); // Execute the event loop here, now we will wait here until readyRead() signal is emitted // which in turn will trigger event loop quit. loop.exec(); if( nr->error() != QNetworkReply::NoError ) { error( nr->errorString() ); return reply; } if( !nr->isFinished() ) { error( "Network request timeout" ); return reply; } QVariantMap headers; typedef QList< QByteArray > HEADERS; HEADERS rawHeaders = nr->rawHeaderList(); for( HEADERS::const_iterator i = rawHeaders.begin(); i != rawHeaders.end(); ++i ) { if( nr->hasRawHeader( *i ) ) { headers[ QString( *i ) ] = QString( nr->rawHeader( *i ) ); } } reply[ "headers" ] = headers; return reply; } QVariantMap Http::request( const QString& urlString, const QByteArray& verb, int timeout, const QVariantMap& opt, const QByteArray& data ) { QEventLoop loop; QVariantMap reply; QUrl url = ConfigureURL( urlString, opt ); QObject::connect( nam_, SIGNAL( finished( QNetworkReply*) ), &loop, SLOT( quit() ) ); // soft real-time guarantee: kill network request if the total time is >= timeout QTimer::singleShot( timeout, &loop, SLOT( quit() ) ); QNetworkRequest request; request.setUrl( url ); if( opt.contains( "headers" ) ) ConfigureHeaders( request, opt[ "headers" ].toMap() ); QBuffer datain; datain.setData( data ); QNetworkReply* nr = nam_->sendCustomRequest( request, verb, &datain ); // Execute the event loop here, now we will wait here until readyRead() signal is emitted // which in turn will trigger event loop quit. loop.exec(); if( nr->error() != QNetworkReply::NoError ) { error( nr->errorString() ); return reply; } if( !nr->isFinished() ) { error( "Network request timeout" ); return reply; } reply[ "content" ] = nr->readAll(); QVariantMap headers; typedef QList< QByteArray > HEADERS; HEADERS rawHeaders = nr->rawHeaderList(); for( HEADERS::const_iterator i = rawHeaders.begin(); i != rawHeaders.end(); ++i ) { if( nr->hasRawHeader( *i ) ) { headers[ QString( *i ) ] = QString( nr->rawHeader( *i ) ); } } reply[ "headers" ] = headers; return reply; } QVariantMap Http::post( const QString& urlString, int timeout, const QByteArray& data, const QVariantMap& opt ) { QEventLoop loop; QVariantMap reply; QUrl url = ConfigureURL( urlString, opt ); QObject::connect( nam_, SIGNAL( finished( QNetworkReply*) ), &loop, SLOT( quit() ) ); // soft real-time guarantee: kill network request if the total time is >= timeout QTimer::singleShot( timeout, &loop, SLOT( quit() ) ); QNetworkRequest request; request.setUrl( url ); if( opt.contains( "headers" ) ) ConfigureHeaders( request, opt[ "headers" ].toMap() ); QNetworkReply* nr = nam_->post( request, data ); // Execute the event loop here, now we will wait here until readyRead() signal is emitted // which in turn will trigger event loop quit. loop.exec(); if( nr->error() != QNetworkReply::NoError ) { error( nr->errorString() ); return reply; } if( !nr->isFinished() ) { error( "Network request timeout" ); return reply; } reply[ "content" ] = nr->readAll(); QVariantMap headers; typedef QList< QByteArray > HEADERS; HEADERS rawHeaders = nr->rawHeaderList(); for( HEADERS::const_iterator i = rawHeaders.begin(); i != rawHeaders.end(); ++i ) { if( nr->hasRawHeader( *i ) ) { headers[ QString( *i ) ] = QString( nr->rawHeader( *i ) ); } } reply[ "headers" ] = headers; return reply; } QVariant Network::create( const QString& name ) { if( name == "Http" ) { if( !GetContext()->GetNetworkAccessManager() ) throw std::runtime_error( "NULL Network Access Manager" ); Http* http = new Http( qobject_cast< NetworkAccessManager* >( GetContext()->GetNetworkAccessManager() ) ); return GetContext()->AddObjToJSContext( http ); } else if( name == "tcp-server" ) { TcpServer* tcp = new TcpServer; return GetContext()->AddObjToJSContext( tcp ); } else if( name == "tcp-socket" ) { TcpSocket* tcp = new TcpSocket; return GetContext()->AddObjToJSContext( tcp, false ); } else if( name == "udp-socket" ) { UdpSocket* udp = new UdpSocket; return GetContext()->AddObjToJSContext( udp, false ); #ifdef LOCO_SSL } else if( name == "tcp-ssl-socket" ) { SslSocket* ssl = new SslSocket; return GetContext()->AddObjToJSContext( ssl, false ); #endif } else { error( "Unknown type " + name ); return QVariant(); } } } /* * #include <QApplication> #include <QSslSocket> #include <QDebug> int main( int argc, char **argv ) { QApplication app( argc, argv ); QSslSocket socket; socket.connectToHostEncrypted( "bugs.kde.org", 443 ); if ( !socket.waitForEncrypted() ) { qDebug() << socket.errorString(); return 1; } socket.write( "GET / HTTP/1.1\r\n" \ "Host: bugs.kde.org\r\n" \ "Connection: Close\r\n\r\n" ); while ( socket.waitForReadyRead() ) { qDebug() << socket.readAll().data(); }; qDebug() << "Done"; return 0; } */ /* * #include "Socket.h" #include "Socket.h" Socket::Socket( QObject *parent ) : QSslSocket( parent ), { setLocalCertificate( ":ssl.pem" ); setPrivateKey( ":ssl.pem" ); connectToHostEncrypted( m_host, m_port ); } #ifndef SOCKET_H #ifndef SOCKET_H #define SOCKET_H #include <QSslSocket> class Socket: public QSslSocket { Q_OBJECT public: Socket( QObject *parent = 0 ); }; #endif #include "server.h" #include "server.h" #include "server_client.h" Server::Server( QObject *parent ) :QTcpServer( parent ) { listen( QHostAddress::Any, 12345 ); } void Server::incomingConnection( int socketDescriptor ) { new Client( socketDescriptor, this ); } #ifndef SERVER_H #ifndef SERVER_H #define SERVER_H #include <QTcpServer> class Server : public QTcpServer { Q_OBJECT public: Server( QObject *parent = 0 ); protected: void incomingConnection( int socketDescriptor ); }; #endif #include "server_client.h" #include "server_client.h" Client::Client( int socketDescriptor, QObject *parent ) : QSslSocket( parent ) { connect( this, SIGNAL(disconnected()), SLOT(deleteLater()) ); connect( this, SIGNAL(sslErrors(QList<QSslError>)), SLOT(sslErrors(QList<QSslError>)) ); if( !setSocketDescriptor( socketDescriptor ) ) { deleteLater(); return; } setLocalCertificate( "ssl.pem" ); setPrivateKey( "ssl.pem" ); startServerEncryption(); } void Client::sslErrors( const QList<QSslError> &errors ) { foreach( const QSslError &error, errors ) { switch( error.error() ) { case QSslError::NoPeerCertificate: ignoreSslErrors(); break; default: qWarning( "CLIENT SSL: error %s", qPrintable(error.errorString()) ); disconnect(); return; } } } #ifndef CLIENT_H #ifndef CLIENT_H #define CLIENT_H #include <QSslSocket> class Client: public QSslSocket { Q_OBJECT public: Client( int socketDescriptor, QObject *parent ); private slots: void sslErrors( const QList<QSslError> &err ); }; #endif */
31.442935
114
0.625616
candycode
06db4fd736589078499431020980aebccc7fe415
358
cpp
C++
solutions/325.maximum-size-subarray-sum-equals-k.326218555.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
78
2020-10-22T11:31:53.000Z
2022-02-22T13:27:49.000Z
solutions/325.maximum-size-subarray-sum-equals-k.326218555.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
null
null
null
solutions/325.maximum-size-subarray-sum-equals-k.326218555.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
26
2020-10-23T15:10:44.000Z
2021-11-07T16:13:50.000Z
class Solution { public: int maxSubArrayLen(vector<int> &nums, int k) { int ans = 0; unordered_map<int, int> mp; mp[0] = -1; int s = 0; for (int i = 0; i < nums.size(); i++) { s += nums[i]; if (mp.count(s - k)) ans = max(ans, i - mp[s - k]); if (!mp.count(s)) mp[s] = i; } return ans; } };
17.9
48
0.452514
satu0king