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
ca4a77a1b2da371aac972238280ae172be951a37
3,487
cc
C++
src/algorithms/OnlinePolicyGradient.cc
olethrosdc/beliefbox
44c0c160732b875f294a3f6d7f27e8f4cdf9602c
[ "OLDAP-2.3" ]
4
2015-12-02T23:16:44.000Z
2018-01-07T10:54:36.000Z
src/algorithms/OnlinePolicyGradient.cc
olethrosdc/beliefbox
44c0c160732b875f294a3f6d7f27e8f4cdf9602c
[ "OLDAP-2.3" ]
2
2015-12-02T19:47:57.000Z
2018-10-14T13:08:40.000Z
src/algorithms/OnlinePolicyGradient.cc
olethrosdc/beliefbox
44c0c160732b875f294a3f6d7f27e8f4cdf9602c
[ "OLDAP-2.3" ]
4
2018-01-14T14:23:18.000Z
2018-10-29T12:46:41.000Z
#include "OnlinePolicyGradient.h" PolicyGradientActorCritic::PolicyGradientActorCritic(int n_states_, int n_actions_, real gamma_, real step_size_) : n_states(n_states_), n_actions(n_actions_), gamma(gamma_), step_size(step_size_), critic(n_states, n_actions, gamma, 0.0, step_size), policy(n_states, n_actions), params(n_states, n_actions), Q(n_states, n_actions) { Reset(); } real PolicyGradientActorCritic::Observe(real reward, const int& next_state, const int& next_action) { real d = 0; if (state >= 0) { d = GradientUpdate(state, action); // not sure how much difference it makes to update the next state-action pair instead //printf("%d %d %d %d%f\n", state, action, d); Q(state, action) += step_size * (reward + gamma * Q(next_state, next_action) - Q(state, action)); } critic.Observe(reward, next_state, next_action); UpdatePolicy(); state = next_state; action = next_action; return d; } int PolicyGradientActorCritic::Act(real reward, const int& next_state) { policy.Observe(reward, next_state); int next_action = policy.SelectAction(); Observe(reward, next_state, next_action); return next_action; } real PolicyGradientActorCritic::GradientUpdate(int s, int a) { //real U = critic.getValue(s); //real U = critic.getValue(s); real U = Q(s,a); printf("s:%d, a:%d: Q_w:%f Q_S:%f\n", s, a, U, critic.getValue(s,a)); real delta = 0; for (int j=0; j<n_actions; ++j) { real p_a = policy.getActionProbability(s, j); real d_sj = 0; if (j==a) { d_sj = (1.0 - p_a) * U; } else { d_sj = -p_a * U; } params(s,j) += step_size * d_sj; delta += fabs(d_sj); } return delta; } void PolicyGradientActorCritic::UpdatePolicy() { for (int s=0; s<n_states; ++s) { Vector eW = exp(params.getRow(s)); eW /= eW.Sum(); Vector* pS = policy.getActionProbabilitiesPtr(s); (*pS) = eW; } } // --- PGAC with features --- // PolicyGradientActorCriticPhi::PolicyGradientActorCriticPhi(BasisSet<Vector, int>& basis_, int n_states_, int n_actions_, real gamma_, real step_size_) : basis(basis_), n_states(n_states_), n_actions(n_actions_), gamma(gamma_), step_size(step_size_), critic(n_states, n_actions, basis, gamma), policy(n_states, n_actions, basis), // bug? params(basis.size()) { Reset(); } real PolicyGradientActorCriticPhi::Observe(real reward, const Vector& next_state, const int& next_action) { basis.Observe(action, reward, next_state); real d = 0; if (valid_state) { d = GradientUpdate(state, action); } critic.Observe(reward, next_state, next_action); UpdatePolicy(); state = next_state; action = next_action; valid_state = true; return d; } int PolicyGradientActorCriticPhi::Act(real reward, const Vector& next_state) { basis.Observe(action, reward, next_state); //Vector features = basis.F(); int next_action = policy.SelectAction(next_state); Observe(reward, next_state, next_action); return next_action; } real PolicyGradientActorCriticPhi::GradientUpdate(const Vector& s, int a) { basis.Observe(s); Vector phi = basis.F(); // copy the state-features into a larger state-action feature vector Vector features(phi.Size()*n_actions); int k = a * phi.Size(); for (int i=0; i<phi.Size(); ++i) { features(k) = phi(i); } real U = critic.getValue(s); Vector delta = policy.GradientUpdate(s, a, U); policy.GradientUpdateForward(delta, step_size); return U; } void PolicyGradientActorCriticPhi::UpdatePolicy() { }
25.82963
122
0.691999
olethrosdc
ca4bc3210a0c2809539eaa960265b4e58b30bac2
1,386
cpp
C++
shared/source/os_interface/windows/os_time_win.cpp
troels/compute-runtime
3269e719a3ee7bcd97c50ec2cfe78fc8674adec0
[ "Intel", "MIT" ]
778
2017-09-29T20:02:43.000Z
2022-03-31T15:35:28.000Z
shared/source/os_interface/windows/os_time_win.cpp
troels/compute-runtime
3269e719a3ee7bcd97c50ec2cfe78fc8674adec0
[ "Intel", "MIT" ]
478
2018-01-26T16:06:45.000Z
2022-03-30T10:19:10.000Z
shared/source/os_interface/windows/os_time_win.cpp
troels/compute-runtime
3269e719a3ee7bcd97c50ec2cfe78fc8674adec0
[ "Intel", "MIT" ]
215
2018-01-30T08:39:32.000Z
2022-03-29T11:08:51.000Z
/* * Copyright (C) 2018-2021 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "shared/source/os_interface/windows/os_time_win.h" #include "shared/source/os_interface/windows/device_time_wddm.h" #include "shared/source/os_interface/windows/wddm/wddm.h" #include <memory> #undef WIN32_NO_STATUS namespace NEO { bool OSTimeWin::getCpuTime(uint64_t *timeStamp) { uint64_t time; this->QueryPerfomanceCounterFnc((LARGE_INTEGER *)&time); *timeStamp = static_cast<uint64_t>((static_cast<double>(time) * NSEC_PER_SEC / frequency.QuadPart)); return true; }; std::unique_ptr<OSTime> OSTimeWin::create(OSInterface *osInterface) { return std::unique_ptr<OSTime>(new OSTimeWin(osInterface)); } OSTimeWin::OSTimeWin(OSInterface *osInterface) { this->osInterface = osInterface; Wddm *wddm = osInterface ? osInterface->getDriverModel()->as<Wddm>() : nullptr; this->deviceTime = std::make_unique<DeviceTimeWddm>(wddm); QueryPerformanceFrequency(&frequency); } double OSTimeWin::getHostTimerResolution() const { double retValue = 0; if (frequency.QuadPart) { retValue = 1e9 / frequency.QuadPart; } return retValue; } uint64_t OSTimeWin::getCpuRawTimestamp() { LARGE_INTEGER cpuRawTimestamp = {}; this->QueryPerfomanceCounterFnc(&cpuRawTimestamp); return cpuRawTimestamp.QuadPart; } } // namespace NEO
26.653846
104
0.731602
troels
ca4d642184c5ad7b58e45fc1fe56cc8a443739d8
8,778
hpp
C++
Source/AllProjects/GraphicUtils/CIDGraphDev/CIDGraphDev_ImgCacheItem.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
216
2019-03-09T06:41:28.000Z
2022-02-25T16:27:19.000Z
Source/AllProjects/GraphicUtils/CIDGraphDev/CIDGraphDev_ImgCacheItem.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
9
2020-09-27T08:00:52.000Z
2021-07-02T14:27:31.000Z
Source/AllProjects/GraphicUtils/CIDGraphDev/CIDGraphDev_ImgCacheItem.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
29
2019-03-09T10:12:24.000Z
2021-03-03T22:25:29.000Z
// // FILE NAME: CIDCtrls_ImgCacheItem.hpp // // AUTHOR: Dean Roddey // // CREATED: 10/28/2005 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2019 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This is the header for the CIDCtrls_ImgCacheItem.cpp file, which implements // a simple image cache item that various programs may want to use (after // extending) to create an image cache. // // CAVEATS/GOTCHAS: // // LOG: // // $_CIDLib_Log_$ // #pragma once #pragma CIDLIB_PACK(CIDLIBPACK) // --------------------------------------------------------------------------- // CLASS: TImgCacheItem // PREFIX: ici // --------------------------------------------------------------------------- class CIDGRDEVEXP TImgCacheItem : public TObject { public : // ------------------------------------------------------------------- // Public, static methods // ------------------------------------------------------------------- static const TString& strImgName ( const TImgCacheItem& iciSrc ); // ------------------------------------------------------------------- // Constructors and Destructor // ------------------------------------------------------------------- TImgCacheItem ( const TString& strImgName , const tCIDLib::TBoolean bThumb ); TImgCacheItem ( const TString& strImgName , const tCIDLib::TBoolean bThumb , const tCIDLib::TCard4 c4Size , const TBitmap& bmpData , const tCIDLib::TBoolean bDeepCopy ); TImgCacheItem ( const TImgCacheItem& I_NsClientBindSearch ); ~TImgCacheItem(); // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- TImgCacheItem& operator= ( const TImgCacheItem& iciSrc ); // ------------------------------------------------------------------- // Public, virtual methods // ------------------------------------------------------------------- virtual tCIDLib::TVoid Reset ( const TString& strImgName , const tCIDLib::TBoolean bThumb ); virtual tCIDLib::TVoid Set ( const tCIDLib::TBoolean bThumb , const tCIDLib::TCard4 c4Size , const TMemBuf& mbufData , const tCIDLib::TCard4 c4SerialNum , const TGraphDrawDev& gdevCompat ); // ------------------------------------------------------------------- // Public, non-virtual methods // ------------------------------------------------------------------- tCIDLib::TBoolean bHasAlpha() const; tCIDLib::TBoolean bStillGood ( const TString& strExpiresStamp ) const; tCIDLib::TBoolean bThumb() const; tCIDLib::TBoolean bTransparent() const; const TBitmap& bmpImage() const; const TBitmap& bmpMask() const; tCIDLib::TCard4 c4SerialNum() const; tCIDLib::TCard4 c4Size() const; tCIDLib::TCard4 c4TransClr() const; tCIDLib::TVoid DropImage(); tCIDLib::TEncodedTime enctLastAccess() const; tCIDLib::TEncodedTime enctLastCheck() const; tCIDLib::TEncodedTime enctGoodTill() const; const TString& strExpiresStamp() const; const TString& strExpiresStamp ( const TString& strToSet ); const TString& strImageName() const; const TString& strTagData() const; const TString& strTagData ( const TString& strToSet ); tCIDLib::TVoid SetLastAccess(); tCIDLib::TVoid SetLastCheck(); tCIDLib::TVoid SetGoodTill ( const tCIDLib::TCard4 c4Seconds ); const TSize& szImage() const; protected : // ------------------------------------------------------------------- // Protected, non-virtual methods // ------------------------------------------------------------------- TBitmap& bmpWriteable(); private : // ------------------------------------------------------------------- // Private data members // // m_bThumb // Indicatse if this is a thumbnail or the full size image. // // m_bTrans // Indicates if this a color based transparency image. If so, then the // mask images are needed for drawing. // // m_bmpImage // m_bmpMask // The image and the mask for the image if it is transparent. // // m_c4Size // The size of the original raw image data, so we'll know how much is // required if we have to send it. // // m_enctLastAccess // Updated each time the image is accessed, and used to do a least recently // used algorithm if our cache gets full. // // m_enctLastCheck // The last time that the client code checked to see if the image // is still up to date with any external source. This can be // used to prevent repeated checks when the image is accessed // multipled times quickly. // // m_enctGoodTill // In some cases, it's known that an image will be valid for some length of // time, in which case this can be set and used to avoid re-validating the // cached image for that period. Defaults to zero, which means it will by // default never be good. // // m_c4TransClr // If color transparency based (m_bTrans is true), then this is the color that // was used to create the masks. // // m_strExpiresStamp // This is used to store an expiration stamp, generally for use with HTTP // servers, which may provide such a stamp. If it provides a max-age that // will be set via the SetGoodTill and will override this. If the good till // is zero, then we try this guy. // // m_strImageName // The original name of the image, whihc is whatever is meaningful // to the user of this class. // // m_strTagData // This is for the use of the application, to store some kind of tag info. // // m_szImage // Get the size out up front, since we have to return it fairly often, and // the bitmap itself returns it by value, so we can be more efficient. // ------------------------------------------------------------------- tCIDLib::TBoolean m_bThumb; tCIDLib::TBoolean m_bTrans; TBitmap m_bmpImage; TBitmap m_bmpMask; tCIDLib::TCard4 m_c4Size; tCIDLib::TCard4 m_c4TransClr; tCIDLib::TEncodedTime m_enctLastAccess; tCIDLib::TEncodedTime m_enctLastCheck; tCIDLib::TEncodedTime m_enctGoodTill; TString m_strExpiresStamp; TString m_strImageName; TString m_strTagData; TSize m_szImage; // ------------------------------------------------------------------- // Magic Macros // ------------------------------------------------------------------- RTTIDefs(TImgCacheItem,TObject) }; // --------------------------------------------------------------------------- // Define a counter pointer to an image cache object. This is what normally would be // handed out to callers when they want to use an image. This insures that the image // will not be dropped from the cache as long as someone is holding it. // --------------------------------------------------------------------------- using TImgCacheItemPtr = TCntPtr<TImgCacheItem>; inline const TString& strExtractImgCacheItemPtrKey(const TImgCacheItemPtr& cptrSrc) { return cptrSrc->strImageName(); } #pragma CIDLIB_POPPACK
33.632184
91
0.460355
MarkStega
ca4e4af46741270dc90b75dead61f1b5a9950d97
1,869
hh
C++
dev/g++/projects/embedded/libhal/hardwares/raspberry_pi/include/digital_out.hh
YannGarcia/repo
0f3de24c71d942c752ada03c10861e83853fdf71
[ "MIT" ]
null
null
null
dev/g++/projects/embedded/libhal/hardwares/raspberry_pi/include/digital_out.hh
YannGarcia/repo
0f3de24c71d942c752ada03c10861e83853fdf71
[ "MIT" ]
null
null
null
dev/g++/projects/embedded/libhal/hardwares/raspberry_pi/include/digital_out.hh
YannGarcia/repo
0f3de24c71d942c752ada03c10861e83853fdf71
[ "MIT" ]
1
2017-01-27T12:53:50.000Z
2017-01-27T12:53:50.000Z
/*! * \file digital_out.hpp * \brief Header file for digital out gpio state. * \author garciay.yann@gmail.com * \copyright Copyright (c) 2015 ygarcia. All rights reserved * \license This project is released under the MIT License * \version 0.1 */ #pragma once #include "libhal.h" /*! * \class digital_out * \brief digital output gpio state * @see ::digital_write */ class digital_out { protected: /*! The gpio idenifier */ pin_name _gpio; /*! The gpio state */ digital_state_t _state; public: /*! * \brief Constructor * State is set to low * \param[in] The gpio to connect */ digital_out(const pin_name p_gpio_name) : _gpio(p_gpio_name), _state(digital_state_t::digital_state_low) { ::digital_write(_gpio, _state); }; /*! * \brief Constructor * \param[in] The gpio to connect * \param[in] p_state The gpio state */ digital_out(const pin_name p_gpio_name, const digital_state_t p_state) : _gpio(p_gpio_name), _state(p_state) { ::digital_write(_gpio, _state); }; /*! * \brief Destructor * The gpio state is set to low before to destroy this class reference */ virtual ~digital_out() { ::digital_write(_gpio, digital_state_t::digital_state_low); }; /*! * \brief Set the gpio state * \param[in] The new gpio state */ inline void write(const digital_state_t p_state) { _state = p_state; ::digital_write(_gpio, _state); }; /*! * \brief Indicates the gpio state * \return The gpio state * @see digital_state_t */ inline digital_state_t read() const { return _state; }; inline digital_out & operator = (const digital_state_t p_state) { write(p_state); return *this; }; inline digital_out & operator = (const digital_out & p_gpio) { write(p_gpio.read()); return *this; }; inline operator const digital_state_t() const { return read(); }; }; // End of class digital_out
31.15
147
0.686998
YannGarcia
ca4ecd2046f969b2cd2bca17a94de63611e72c21
629
cpp
C++
Advance/weakPointer.cpp
iarjunphp/CPP-Learning
4946f861cb3f57da2b0beba07a206fafe261aaf4
[ "MIT" ]
77
2019-10-28T05:38:51.000Z
2022-03-15T01:53:48.000Z
Advance/weakPointer.cpp
iarjunphp/CPP-Learning
4946f861cb3f57da2b0beba07a206fafe261aaf4
[ "MIT" ]
3
2019-12-26T15:39:55.000Z
2020-10-29T14:55:50.000Z
Advance/weakPointer.cpp
iarjunphp/CPP-Learning
4946f861cb3f57da2b0beba07a206fafe261aaf4
[ "MIT" ]
24
2020-01-08T04:12:52.000Z
2022-03-12T22:26:07.000Z
//Memory get free as scope ends and this pointers can have copy of them. #include<iostream> #include<memory> using namespace std; class User{ public: User(){ cout<<"User Created\n"; } ~User(){ cout<<"User Destroyed\n"; } void testFunc(){ cout<<"I am a test function\n"; } }; int main(){ { shared_ptr<User> tim = make_shared<User>(); weak_ptr<User> wtim = tim; // Created a weak pointer shared_ptr<User> yo = wtim.lock(); // Using weak pointer back to shared yo->testFunc(); } cout<<"Outside scope\n"; return 0; }
18.5
80
0.562798
iarjunphp
ca4ee9f21cccb988fd077c31a422a7e49c029121
1,656
cpp
C++
Edgyne/ResourceShaderProgram.cpp
AWDaM/Edgyne
e2c9d01efc3dd50e41f7cc31c407baa44ea77560
[ "MIT" ]
1
2019-02-07T12:11:21.000Z
2019-02-07T12:11:21.000Z
Edgyne/ResourceShaderProgram.cpp
MaxitoSama/Edgyne
e2c9d01efc3dd50e41f7cc31c407baa44ea77560
[ "MIT" ]
null
null
null
Edgyne/ResourceShaderProgram.cpp
MaxitoSama/Edgyne
e2c9d01efc3dd50e41f7cc31c407baa44ea77560
[ "MIT" ]
1
2019-02-04T16:08:36.000Z
2019-02-04T16:08:36.000Z
#include "ResourceShaderProgram.h" #include "Application.h" #include "ModuleShaders.h" #include "JSONManager.h" ResourceShaderProgram::ResourceShaderProgram() : Resource(RES_SHADER) { } ResourceShaderProgram::ResourceShaderProgram(std::string& file) : Resource(RES_SHADER, file) { } ResourceShaderProgram::~ResourceShaderProgram() { } bool ResourceShaderProgram::CompileShaderProgram() { bool ret = false; uint tmp_program_index = 0; std::vector<uint> indexList; for (std::vector<uint>::iterator it = shaderObjects.begin(); it != shaderObjects.end(); it++) { bool isVertex = false; char* data = App->shaders->FindShaderObjectFromUID(*it, isVertex); uint index = 0; if (App->shaders->CompileShader(data, isVertex, &index)) indexList.push_back(index); } if(App->shaders->CreateShaderProgram(indexList, &program)); ret = true; return ret; } void ResourceShaderProgram::AddNewObjectToProgram(uint uuid) { bool isVertex = false; if (App->shaders->FindShaderObjectFromUID(uuid, isVertex)) { shaderObjects.push_back(uuid); JSON_File* hmm = App->JSON_manager->openWriteFile(("Library\\ShaderPrograms\\" + file).c_str()); JSON_Value* val = hmm->createValue(); for (std::vector<uint>::iterator item = shaderObjects.begin(); item != shaderObjects.end(); item++) { val->addUint("uid", (*item)); } hmm->addValue("", val); hmm->Write(); hmm->closeFile(); CompileShaderProgram(); } } bool ResourceShaderProgram::ContainsShader(uint uuid) { for (std::vector<uint>::iterator item = shaderObjects.begin(); item != shaderObjects.end(); item++) { if ((*item) == uuid) { return true; } } return false; }
22.684932
101
0.705314
AWDaM
ca50ce561027673aaa46a0e358f312825d6f635a
281
cc
C++
writing-concepts/type_simple.cc
HappyCerberus/article-cpp20-concepts
986934bc91727dd8874a318822b5497dfa734d01
[ "MIT" ]
3
2021-09-17T06:29:40.000Z
2022-03-21T08:33:35.000Z
writing-concepts/type_simple.cc
HappyCerberus/article-cpp20-concepts
986934bc91727dd8874a318822b5497dfa734d01
[ "MIT" ]
null
null
null
writing-concepts/type_simple.cc
HappyCerberus/article-cpp20-concepts
986934bc91727dd8874a318822b5497dfa734d01
[ "MIT" ]
null
null
null
#include <concepts> template <typename T> concept type_test = requires { typename T::ElementType; // ElementType member type must exist }; void function(type_test auto x) {} struct X { using ElementType = int; }; int main() { function(X{}); // OK function(1); // Fails }
17.5625
66
0.676157
HappyCerberus
3ed13b1c9bb29b80e0cba4dc9cd4c777bf9e4993
3,942
cpp
C++
CLRS/BinaryTree/VerticalOrderTraversalofaBinaryTree.cpp
ComputerProgrammerStorager/DataStructureAlgorithm
508f7e37898c907ea7ea6ec40749621a2349e93f
[ "MIT" ]
null
null
null
CLRS/BinaryTree/VerticalOrderTraversalofaBinaryTree.cpp
ComputerProgrammerStorager/DataStructureAlgorithm
508f7e37898c907ea7ea6ec40749621a2349e93f
[ "MIT" ]
null
null
null
CLRS/BinaryTree/VerticalOrderTraversalofaBinaryTree.cpp
ComputerProgrammerStorager/DataStructureAlgorithm
508f7e37898c907ea7ea6ec40749621a2349e93f
[ "MIT" ]
null
null
null
/* Given the root of a binary tree, calculate the vertical order traversal of the binary tree. For each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0). The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values. Return the vertical order traversal of the binary tree. Example 1: Input: root = [3,9,20,null,null,15,7] Output: [[9],[3,15],[20],[7]] Explanation: Column -1: Only node 9 is in this column. Column 0: Nodes 3 and 15 are in this column in that order from top to bottom. Column 1: Only node 20 is in this column. Column 2: Only node 7 is in this column. Example 2: Input: root = [1,2,3,4,5,6,7] Output: [[4],[2],[1,5,6],[3],[7]] Explanation: Column -2: Only node 4 is in this column. Column -1: Only node 2 is in this column. Column 0: Nodes 1, 5, and 6 are in this column. 1 is at the top, so it comes first. 5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6. Column 1: Only node 3 is in this column. Column 2: Only node 7 is in this column. Example 3: Input: root = [1,2,3,4,6,5,7] Output: [[4],[2],[1,5,6],[3],[7]] Explanation: This case is the exact same as example 2, but with nodes 5 and 6 swapped. Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values. Constraints: The number of nodes in the tree is in the range [1, 1000]. 0 <= Node.val <= 1000 */ // we use bfs to get the position (column, row, value) of each node and while traversing the nodes, we push the {row,value} to // the vector associated with the corresponding column idx. // To avoid using sorted map, we remember the min and max column ever encountered /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<vector<int>> verticalTraversal(TreeNode* root) { unordered_map<int, vector<pair<int,int>> > m; // map column idx to (row,value) pairs vector<vector<int>> res; int min_col = INT_MAX, max_col = INT_MIN; typedef struct { TreeNode *node; int row; int column; } NODE_POS; queue<NODE_POS> q; if ( !root ) return res; q.push({root,0,0}); while (!q.empty() ) { int n = q.size(); for ( int i = 0; i < n; i++ ) { auto t = q.front(); q.pop(); m[t.column].push_back({t.row,t.node->val}); min_col = min(min_col,t.column); max_col = max(max_col,t.column); if ( t.node->left ) { q.push({t.node->left,t.row+1,t.column-1}); } if ( t.node->right ) { q.push({t.node->right,t.row+1,t.column+1}); } } } for ( int idx = min_col; idx <= max_col; idx++ ) { if ( m.count(idx) ) { sort(m[idx].begin(),m[idx].end()); vector<int> col_vals; for ( auto t : m[idx] ) col_vals.push_back(t.second); res.push_back(col_vals); } } return res; } };
32.85
285
0.567732
ComputerProgrammerStorager
3ed2d85ac6c2faae68b56853b75323c487a384f8
8,578
cpp
C++
firmware-usbhost/common/http/test/HttpRequestParserTest.cpp
Zzzzipper/cppprojects
e9c9b62ca1e411320c24a3d168cab259fa2590d3
[ "MIT" ]
null
null
null
firmware-usbhost/common/http/test/HttpRequestParserTest.cpp
Zzzzipper/cppprojects
e9c9b62ca1e411320c24a3d168cab259fa2590d3
[ "MIT" ]
1
2021-09-03T13:03:20.000Z
2021-09-03T13:03:20.000Z
firmware-usbhost/common/http/test/HttpRequestParserTest.cpp
Zzzzipper/cppprojects
e9c9b62ca1e411320c24a3d168cab259fa2590d3
[ "MIT" ]
null
null
null
#include "test/include/Test.h" #include "http/HttpRequestParser.h" #include "logger/include/Logger.h" namespace Http { class RequestParserTest : public TestSet { public: RequestParserTest(); bool testOK(); bool testBrokenHeader(); bool testCuttedData(); }; TEST_SET_REGISTER(Http::RequestParserTest); RequestParserTest::RequestParserTest() { TEST_CASE_REGISTER(RequestParserTest, testOK); #if 0 TEST_CASE_REGISTER(RequestParserTest, testBrokenHeader); TEST_CASE_REGISTER(RequestParserTest, testCuttedData); #endif } /* === CreateAutomatModel ========================= POST /api/1.0/automat/Automat.php?action=CreateAutomatModel&_dc=1539090316532 HTTP/1.1 Host: devs.ephor.online Connection: keep-alive Content-Length: 24 Origin: https://devs.ephor.online X-Requested-With: XMLHttpRequest User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36 Content-Type: application/json Accept: *//* Referer: https://devs.ephor.online/client/index.html Accept-Encoding: gzip, deflate, br Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7 Cookie: _ym_uid=1500301628417188656; PHPSESSID=au3fdendice73jro126183e38l {"name":"1234","type":0} */ bool RequestParserTest::testOK() { Http::RequestParser parser; Request2 req; StringBuilder serverName(64, 64); StringBuilder serverPath(256, 256); StringBuilder phpSessionId(64, 64); StringBuilder reqData(1024, 1024); req.serverName = &serverName; req.serverPath = &serverPath; req.phpSessionId = &phpSessionId; req.data = &reqData; parser.start(&req); TEST_NUMBER_EQUAL(1024, parser.getBufSize()); TEST_NUMBER_EQUAL(0, parser.isComplete()); // TEST_NUMBER_EQUAL(Http::Response::Status_Unknown, req.statusCode); const char *part1 = "POST /api/1.0/automat/Automat.php?action=CreateAutomatModel&_dc=1539090316532 HTTP/1.1\r\n" "Host: devs.ephor.online\r\n" "Connection: keep-alive\r\n" "Content-Le"; uint16_t part1Len = strlen(part1); memcpy(parser.getBuf(), part1, part1Len); parser.parseData(part1Len); TEST_NUMBER_EQUAL(1014, parser.getBufSize()); TEST_NUMBER_EQUAL(0, parser.isComplete()); // TEST_NUMBER_EQUAL(Http::Response::Status_OK, req.statusCode); const char *part2 = "ngth: 24\r\n" "Origin: https://devs.ephor.online\r\n" "X-Requested-With: XMLHttpRequest\r\n" "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36\r\n" "Content-Type: application/json\r\n" "Accept: */*\r\n" "Referer: https://devs.ephor.online/client/index.html\r\n" "Accept-Encoding: gzip, deflate, br\r\n" "Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7\r\n"; uint16_t part2Len = strlen(part2); memcpy(parser.getBuf(), part2, part2Len); parser.parseData(part2Len); TEST_NUMBER_EQUAL(1024, parser.getBufSize()); TEST_NUMBER_EQUAL(0, parser.isComplete()); // TEST_NUMBER_EQUAL(Http::Response::Status_OK, req.statusCode); const char *part3 = "Cookie: _ym_uid=1500301628417188656; PHPSESSID=au3fdendice73jro126183e38l\r\n" "\r\n" "{\"name\":\"1234\",\"type\":0}"; uint16_t part3Len = strlen(part3); memcpy(parser.getBuf(), part3, part3Len); parser.parseData(part3Len); TEST_NUMBER_EQUAL(1000, parser.getBufSize()); TEST_NUMBER_EQUAL(1, parser.isComplete()); TEST_NUMBER_EQUAL(Http::Request::Method_POST, req.method); TEST_SUBSTR_EQUAL("devs.ephor.online", serverName.getString(), serverName.getLen()); TEST_NUMBER_EQUAL(80, req.serverPort); TEST_SUBSTR_EQUAL("/api/1.0/automat/Automat.php?action=CreateAutomatModel&_dc=1539090316532", serverPath.getString(), serverPath.getLen()); TEST_NUMBER_EQUAL(24, req.contentLength); TEST_NUMBER_EQUAL(0, req.rangeFrom); TEST_NUMBER_EQUAL(0, req.rangeTo); TEST_SUBSTR_EQUAL("au3fdendice73jro126183e38l", phpSessionId.getString(), phpSessionId.getLen()); TEST_SUBSTR_EQUAL("{\"name\":\"1234\",\"type\":0}", reqData.getString(), reqData.getLen()); return true; } #if 0 bool RequestParserTest::testBrokenHeader() { Http::RequestParser parser; Response resp; StringBuilder phpSessionId(64, 64); StringBuilder respData(1024, 1024); resp.phpSessionId = &phpSessionId; resp.data = &respData; parser.start(&resp); TEST_NUMBER_EQUAL(1024, parser.getBufSize()); TEST_NUMBER_EQUAL(0, parser.haveData()); TEST_NUMBER_EQUAL(0, parser.isComplete()); TEST_NUMBER_EQUAL(Http::Response::Status_Unknown, resp.statusCode); const char *part1 = "0123456789ABCDE\r\n" "Server: nginx/1.9.5\r\n" "Date: Sun, 24 Jan 2016 10:00:04 GMT\r\n" "Content-Ty"; uint16_t part1Len = strlen(part1); memcpy(parser.getBuf(), part1, part1Len); parser.parseData(part1Len); TEST_NUMBER_EQUAL(1014, parser.getBufSize()); TEST_NUMBER_EQUAL(0, parser.haveData()); TEST_NUMBER_EQUAL(0, parser.isComplete()); TEST_NUMBER_EQUAL(Http::Response::Status_ParserError, resp.statusCode); const char *part2 = "pe: text/html\r\n" "Content-Length: 16\r\n" "Content-Range: bytes 0-256/1024\r\n" "Connection: keep-alive\r\n" "Keep-Alive: timeout=30\r\n" "X-Powered-By: PHP/5.5.31\r\n" "Expires: Thu, 19 Nov 1981 08:52:00 GMT\r\n" "Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0\r\n" "Pragma: no-cache\r\n"; uint16_t part2Len = strlen(part2); memcpy(parser.getBuf(), part2, part2Len); parser.parseData(part2Len); TEST_NUMBER_EQUAL(1014, parser.getBufSize()); TEST_NUMBER_EQUAL(0, parser.haveData()); TEST_NUMBER_EQUAL(0, parser.isComplete()); TEST_NUMBER_EQUAL(Http::Response::Status_ParserError, resp.statusCode); const char *part3 = "Set-Cookie: PHPSESSID=8a4bb025730a7f81fec32d9358c0e005; expires=Sun, 24-Jan-2016 12:00:04 GMT; Max-Age=7200; path=/\r\n" "\r\n" "{\"success\":true}"; uint16_t part3Len = strlen(part3); memcpy(parser.getBuf(), part3, part3Len); parser.parseData(part3Len); TEST_NUMBER_EQUAL(1014, parser.getBufSize()); TEST_NUMBER_EQUAL(0, parser.haveData()); TEST_NUMBER_EQUAL(0, parser.isComplete()); TEST_NUMBER_EQUAL(Http::Response::Status_ParserError, resp.statusCode); TEST_NUMBER_EQUAL(0, resp.contentLength); TEST_NUMBER_EQUAL(0, resp.rangeFrom); TEST_NUMBER_EQUAL(0, resp.rangeTo); TEST_NUMBER_EQUAL(0, resp.rangeLength); TEST_SUBSTR_EQUAL("", (const char*)phpSessionId.getData(), phpSessionId.getLen()); return true; } bool RequestParserTest::testCuttedData() { Http::RequestParser parser; Response resp; StringBuilder phpSessionId(64, 64); StringBuilder respData(1024, 1024); resp.phpSessionId = &phpSessionId; resp.data = &respData; parser.start(&resp); TEST_NUMBER_EQUAL(1024, parser.getBufSize()); TEST_NUMBER_EQUAL(0, parser.haveData()); TEST_NUMBER_EQUAL(0, parser.isComplete()); TEST_NUMBER_EQUAL(Http::Response::Status_Unknown, resp.statusCode); const char *part1 = "HTTP/1.1 200 OK\r\n" "Server: nginx/1.9.5\r\n" "Date: Sun, 24 Jan 2016 10:00:04 GMT\r\n" "Content-Ty"; uint16_t part1Len = strlen(part1); memcpy(parser.getBuf(), part1, part1Len); parser.parseData(part1Len); TEST_NUMBER_EQUAL(1014, parser.getBufSize()); TEST_NUMBER_EQUAL(0, parser.haveData()); TEST_NUMBER_EQUAL(0, parser.isComplete()); TEST_NUMBER_EQUAL(Http::Response::Status_OK, resp.statusCode); const char *part2 = "pe: text/html\r\n" "Content-Length: 16\r\n" "Content-Range: bytes 0-256/1024\r\n" "Connection: keep-alive\r\n" "Keep-Alive: timeout=30\r\n" "X-Powered-By: PHP/5.5.31\r\n" "Expires: Thu, 19 Nov 1981 08:52:00 GMT\r\n" "Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0\r\n" "Pragma: no-cache\r\n"; uint16_t part2Len = strlen(part2); memcpy(parser.getBuf(), part2, part2Len); parser.parseData(part2Len); TEST_NUMBER_EQUAL(1024, parser.getBufSize()); TEST_NUMBER_EQUAL(0, parser.haveData()); TEST_NUMBER_EQUAL(0, parser.isComplete()); TEST_NUMBER_EQUAL(Http::Response::Status_OK, resp.statusCode); const char *part3 = "Set-Cookie: PHPSESSID=8a4bb025730a7f81fec32d9358c0e005; expires=Sun, 24-Jan-2016 12:00:04 GMT; Max-Age=7200; path=/\r\n" "\r\n" "{\"succe"; uint16_t part3Len = strlen(part3); memcpy(parser.getBuf(), part3, part3Len); parser.parseData(part3Len); TEST_NUMBER_EQUAL(0, parser.haveData()); TEST_NUMBER_EQUAL(0, parser.isComplete()); TEST_NUMBER_EQUAL(Http::Response::Status_OK, resp.statusCode); TEST_NUMBER_EQUAL(16, resp.contentLength); TEST_NUMBER_EQUAL(0, resp.rangeFrom); TEST_NUMBER_EQUAL(256, resp.rangeTo); TEST_NUMBER_EQUAL(1024, resp.rangeLength); TEST_SUBSTR_EQUAL("8a4bb025730a7f81fec32d9358c0e005", (const char*)phpSessionId.getData(), phpSessionId.getLen()); return true; } #endif }
35.593361
140
0.74283
Zzzzipper
3ed2eb204e2073743d504a19a840d0dc62dbf63c
2,715
hpp
C++
src/time/clocks.hpp
iamantony/CppNotes
2707db6560ad80b0e5e286a04b2d46e5c0280b3f
[ "MIT" ]
2
2020-07-31T14:13:56.000Z
2021-02-03T09:51:43.000Z
src/time/clocks.hpp
iamantony/CppNotes
2707db6560ad80b0e5e286a04b2d46e5c0280b3f
[ "MIT" ]
28
2015-09-22T07:38:21.000Z
2018-10-02T11:00:58.000Z
src/time/clocks.hpp
iamantony/CppNotes
2707db6560ad80b0e5e286a04b2d46e5c0280b3f
[ "MIT" ]
2
2018-10-11T14:10:50.000Z
2021-02-27T08:53:50.000Z
#ifndef CLOCKS_HPP #define CLOCKS_HPP #include <chrono> #include <iomanip> #include <ratio> #include <thread> #include <iostream> // http://www.modernescpp.com/index.php/the-three-clocks using namespace std::chrono_literals; namespace Time { void GetCurrentTime() { // Get time as time_point auto systemNow = std::chrono::system_clock::now(); // Convert time_point into time_t auto systemNowTime = std::chrono::system_clock::to_time_t(systemNow); // Print current time using specified format const char* timeFormat = "%d.%m.%Y %H:%M:%S"; std::cout << "Current time by system clock: " << std::put_time(std::localtime(&systemNowTime), timeFormat) << std::endl; } template <typename T> void printRatio(){ std::cout << " precision: " << T::num << "/" << T::den << " second " << std::endl; typedef typename std::ratio_multiply<T,std::kilo>::type MillSec; typedef typename std::ratio_multiply<T,std::mega>::type MicroSec; std::cout << std::fixed; std::cout << " " << static_cast<double>(MillSec::num)/MillSec::den << " milliseconds " << std::endl; std::cout << " " << static_cast<double>(MicroSec::num)/MicroSec::den << " microseconds " << std::endl; } void ClocksPeriod() { std::cout << std::boolalpha << std::endl; std::cout << "std::chrono::system_clock: " << std::endl; std::cout << " is steady: " << std::chrono::system_clock::is_steady << std::endl; printRatio<std::chrono::system_clock::period>(); std::cout << std::endl; std::cout << "std::chrono::steady_clock: " << std::endl; std::cout << " is steady: " << std::chrono::steady_clock::is_steady << std::endl; printRatio<std::chrono::steady_clock::period>(); std::cout << std::endl; std::cout << "std::chrono::high_resolution_clock: " << std::endl; std::cout << " is steady: " << std::chrono::high_resolution_clock::is_steady << std::endl; printRatio<std::chrono::high_resolution_clock::period>(); std::cout << std::endl; } void BenchmarkSomeOperation() { auto someOperation = []() { std::this_thread::sleep_for(1s); }; auto start = std::chrono::high_resolution_clock::now(); someOperation(); auto stop = std::chrono::high_resolution_clock::now(); std::cout << "someOperation() took " << std::chrono::duration<double>(stop-start).count() << "ms" << std::endl; } void Start() { GetCurrentTime(); ClocksPeriod(); BenchmarkSomeOperation(); } } #endif // CLOCKS_HPP
29.193548
77
0.586372
iamantony
3ed725ac4b32401f87bd86a1995073255f51c22c
3,231
cpp
C++
robot_challenge/lib/Robot/Robot.cpp
matheusns/Oficina_RAS
2bc685a920b1f2424b5d47f36f996019e836800e
[ "BSD-3-Clause" ]
null
null
null
robot_challenge/lib/Robot/Robot.cpp
matheusns/Oficina_RAS
2bc685a920b1f2424b5d47f36f996019e836800e
[ "BSD-3-Clause" ]
null
null
null
robot_challenge/lib/Robot/Robot.cpp
matheusns/Oficina_RAS
2bc685a920b1f2424b5d47f36f996019e836800e
[ "BSD-3-Clause" ]
null
null
null
#include <Robot.hpp> namespace ras { Robot::Robot(PinName front_sensor_pin, PinName right_sensor_pin, PinName left_sensor_pin) : serial_monitor_(USBTX, USBRX) , right_motor_(NULL) , left_motor_(NULL) , front_sensor_(front_sensor_pin) , left_sensor_(left_sensor_pin) , right_sensor_(right_sensor_pin) { } Robot::~Robot() { if (right_motor_ != NULL) delete right_motor_; if (left_motor_ != NULL) delete left_motor_; } void Robot::setRightMotorPin(PinName inA, PinName pwm, PinName inB) { right_motor_ = new Motor(); right_motor_->setPinInA(inA); right_motor_->setPinInB(inB); right_motor_->setPinPwm(pwm); } void Robot::setLeftMotorPin(PinName inA, PinName pwm, PinName inB) { left_motor_ = new Motor(); left_motor_->setPinInA(inA); left_motor_->setPinInB(inB); left_motor_->setPinPwm(pwm); } void Robot::setSensorsLimiar(const float limiar) { this->limiar_ = limiar; } Direction Robot::move() { if (front_sensor_.read() > limiar_) { // serial_monitor_.printf("Front value %f !\n", front_sensor_.read()); moveFront(); return ras::FRONT; } else if (right_sensor_.read() > limiar_) { // serial_monitor_.printf("Right value %f !\n", right_sensor_.read()); moveRight(); return ras::RIGHT; } else if (left_sensor_.read() > limiar_) { // serial_monitor_.printf("Left value %f !\n", left_sensor_.read()); moveLeft(); return ras::LEFT; } else { moveBack(); return ras::BACK; } } void Robot::moveFront() { if (right_motor_ != NULL && left_motor_ != NULL) { // serial_monitor_.printf("Moving to Front\n"); // serial_monitor_.printf("Left Forward - Right Forward\n"); right_motor_->accelerate( float(front_sensor_.read()) ); left_motor_->accelerate( float(front_sensor_.read()) ); right_motor_->moveForward(); left_motor_->moveForward(); } } void Robot::moveLeft() { if (right_motor_ != NULL && left_motor_ != NULL) { // serial_monitor_.printf("Moving to Left\n"); // serial_monitor_.printf("Left Stop - Right Forward\n"); right_motor_->accelerate( float(right_sensor_.read()) ); left_motor_->accelerate( float(right_sensor_.read()) ); right_motor_->moveForward(); left_motor_->stop(); } } void Robot::moveRight() { if (right_motor_ != NULL && left_motor_ != NULL) { // serial_monitor_.printf("Moving to Right\n"); // serial_monitor_.printf("Right Stop - Left Forward\n"); right_motor_->accelerate( float(left_sensor_.read())); left_motor_->accelerate( float(left_sensor_.read())); right_motor_->stop(); left_motor_->moveForward(); } } void Robot::moveBack() { if (right_motor_ != NULL && left_motor_ != NULL) { // serial_monitor_.printf("Moving to Back\n"); right_motor_->accelerate( float(left_sensor_.read())/2.0 ); left_motor_->accelerate( float(left_sensor_.read())/2.0 ); right_motor_->moveBack(); left_motor_->moveBack(); } } }
24.853846
89
0.616837
matheusns
3ed9a6c408dc734a8c3d629d808faf7a0e5410e7
6,784
hpp
C++
include/cpp_mould/constexpr_driver.hpp
HeroicKatora/mould
d6f39f76f092197e950c4abf18af3a6bb4945fab
[ "BSD-3-Clause" ]
3
2018-03-04T12:46:10.000Z
2021-08-06T00:09:59.000Z
include/cpp_mould/constexpr_driver.hpp
HeroicKatora/mould
d6f39f76f092197e950c4abf18af3a6bb4945fab
[ "BSD-3-Clause" ]
null
null
null
include/cpp_mould/constexpr_driver.hpp
HeroicKatora/mould
d6f39f76f092197e950c4abf18af3a6bb4945fab
[ "BSD-3-Clause" ]
null
null
null
#ifndef CPP_MOULD_CONSTEXPR_DRIVER_HPP #define CPP_MOULD_CONSTEXPR_DRIVER_HPP #include <tuple> #include "argument.hpp" #include "engine.hpp" #include "format.hpp" #include "format_info.hpp" namespace mould::internal::constexpr_driver { /* Resolved expression representation */ template<size_t N> struct ExpressionInformation { int indices[N]; }; template<typename T> struct TypedArgumentExpression { int argument_index; FormattingResult (*function)(const T&, Formatter); FullOperation operation; constexpr TypedArgumentExpression initialize(FullOperation operation) { const auto info = TypedFormatterInformation<T>::get(operation); return { argument_index, info.function, operation }; } }; struct LiteralExpression { size_t offset, length; constexpr LiteralExpression initialize(FullOperation operation) { return { operation.literal.offset, operation.literal.length }; } }; template<typename T> constexpr auto _expression_data() -> ExpressionInformation<std::size(T::data.code)> { ExpressionInformation<std::size(T::data.code)> result = {{}}; int* output_ptr = &result.indices[0]; FullOperationIterator iterator{T::data.code, T::data.immediates}; while(!iterator.code_buffer.empty()) { auto op = *iterator; if(op.operation.operation.type == OpCode::Insert) { *output_ptr++ = op.formatting.index_value; } else { *output_ptr++ = -1; } } return result; } template<typename T> constexpr auto ExpressionData = _expression_data<T>(); /* Compile the useful data, retrieve the specific formatting functions */ template<int Index, typename ArgsTuple> constexpr auto uninitialized_expression() { if constexpr(Index < 0) { return LiteralExpression { 0, 0 }; } else { using type = typename std::tuple_element<Index, ArgsTuple>::type; return TypedArgumentExpression<type> { Index, nullptr }; } } template<typename ... E> struct CompiledFormatExpressions { std::tuple<E...> expressions; constexpr static CompiledFormatExpressions Compile(E ... expressions) { return { { expressions ... } }; } template<size_t index> using ExpressionType = typename std::tuple_element<index, std::tuple<E...>>::type; }; template<typename T, typename ... E> constexpr auto initialize(E ... expressions) -> CompiledFormatExpressions<E...> { FullOperationIterator iterator{T::data.code, T::data.immediates}; return CompiledFormatExpressions<E...>::Compile(expressions.initialize(*iterator) ...); } template<typename T, typename ArgsTuple, size_t ... indices> constexpr auto build_expressions(std::index_sequence<indices...>) { auto& data = ExpressionData<T>; return initialize<T>(uninitialized_expression<data.indices[indices], ArgsTuple>() ...); } template<typename Format, typename ... Arguments> constexpr auto CompiledExpressions = build_expressions<Format, std::tuple<Arguments...>>( std::make_index_sequence<std::size(Format::data.code)>{}); /* Run the engine with arguments */ struct ExpressionContext { Engine& engine; Buffer<const char> format_buffer; }; template<typename ExpT> struct Eval; template<> struct Eval<LiteralExpression> { template<typename Format, size_t index, typename ... Arguments> static inline auto evaluate( const ExpressionContext& context, Arguments& ... args) { constexpr auto& expression = std::get<index>(CompiledExpressions<Format, Arguments...>.expressions); context.engine.append( context.format_buffer.begin() + expression.offset, context.format_buffer.begin() + expression.offset + expression.length); } }; template<FormatArgument type, Immediate value, typename ... Arguments> constexpr Immediate get_value(const Arguments& ... args) { if constexpr(type == FormatArgument::Auto) { return 0; } else if constexpr(type == FormatArgument::Parameter) { return std::get<value>(std::tie(args...)); } else { return value; } } template<typename T> struct Eval<TypedArgumentExpression<T>> { template<typename Format, size_t index, typename ... Arguments> static inline auto evaluate( const ExpressionContext& context, Arguments& ... args) { constexpr auto& expression = std::get<index>(CompiledExpressions<Format, Arguments...>.expressions); constexpr auto& formatting = expression.operation.formatting; constexpr auto fn = expression.function; #define CPP_MOULD_CONSTEXPR_EVAL_ASSERT(fkind) \ if constexpr(formatting.kind == FormatKind:: fkind) { \ static_assert(fn != nullptr, "Requested formatting (" #fkind ") not implemented"); \ } CPP_MOULD_CONSTEXPR_EVAL_ASSERT(Auto) CPP_MOULD_REPEAT_FOR_FORMAT_KINDS_MACRO(CPP_MOULD_CONSTEXPR_EVAL_ASSERT) #undef CPP_MOULD_CONSTEXPR_EVAL_ASSERT const auto& argument = std::get<ExpressionData<Format>.indices[index]>(std::tie(args...)); ::mould::Format format { // values get_value<formatting.width, formatting.width_value>(args...), get_value<formatting.precision, formatting.precision_value>(args...), get_value<formatting.padding, formatting.padding_value>(args...), // flags formatting.width != FormatArgument::Auto, formatting.precision != FormatArgument::Auto, formatting.padding != FormatArgument::Auto, formatting.alignment, formatting.sign }; fn(argument, ::mould::Formatter{context.engine, format}); } }; struct Ignore { template<typename ... I> Ignore(I&& ...) {} }; template<typename Format, typename ... Arguments, size_t ... Indices> inline auto _eval(ExpressionContext context, std::index_sequence<Indices...>, Arguments& ... args) { using Compiled = decltype(CompiledExpressions<Format, Arguments...>); Ignore ignore{(Eval<typename Compiled::template ExpressionType<Indices>>::template evaluate<Format, Indices>( context, args...), 0) ...}; } template<typename Format, typename ... Arguments> inline auto eval(Engine engine, Arguments ... args) { ExpressionContext context { engine, Format::data.format_buffer() }; return _eval<Format>( context, std::make_index_sequence<std::size(Format::data.code)>{}, args... ); } } namespace mould { template<typename Format, typename ... Arguments> void format_constexpr( Format& format_string, std::string& output, Arguments&&... arguments) { using namespace internal::constexpr_driver; internal::Engine engine{output}; eval<Format>(engine, arguments...); } } #endif
32
113
0.684404
HeroicKatora
3ee31db21021baef3203c2a4dae8b8462cc8ac1e
8,239
cpp
C++
Code/UnitTests/FoundationTest/Logging/LogTest.cpp
Tekh-ops/ezEngine
d6a5887d8709f267bf8f2943ef15054e29f6d3d5
[ "MIT" ]
703
2015-03-07T15:30:40.000Z
2022-03-30T00:12:40.000Z
Code/UnitTests/FoundationTest/Logging/LogTest.cpp
Tekh-ops/ezEngine
d6a5887d8709f267bf8f2943ef15054e29f6d3d5
[ "MIT" ]
233
2015-01-11T16:54:32.000Z
2022-03-19T18:00:47.000Z
Code/UnitTests/FoundationTest/Logging/LogTest.cpp
Tekh-ops/ezEngine
d6a5887d8709f267bf8f2943ef15054e29f6d3d5
[ "MIT" ]
101
2016-10-28T14:05:10.000Z
2022-03-30T19:00:59.000Z
#include <FoundationTest/FoundationTestPCH.h> #include <Foundation/Configuration/Startup.h> #include <Foundation/IO/FileSystem/DataDirTypeFolder.h> #include <Foundation/Logging/ConsoleWriter.h> #include <Foundation/Logging/HTMLWriter.h> #include <Foundation/Logging/Log.h> #include <Foundation/Logging/VisualStudioWriter.h> #include <Foundation/Threading/Thread.h> #include <TestFramework/Utilities/TestLogInterface.h> EZ_CREATE_SIMPLE_TEST_GROUP(Logging); namespace { class LogTestLogInterface : public ezLogInterface { public: virtual void HandleLogMessage(const ezLoggingEventData& le) override { switch (le.m_EventType) { case ezLogMsgType::Flush: m_Result.Append("[Flush]\n"); return; case ezLogMsgType::BeginGroup: m_Result.Append(">", le.m_szTag, " ", le.m_szText, "\n"); break; case ezLogMsgType::EndGroup: m_Result.Append("<", le.m_szTag, " ", le.m_szText, "\n"); break; case ezLogMsgType::ErrorMsg: m_Result.Append("E:", le.m_szTag, " ", le.m_szText, "\n"); break; case ezLogMsgType::SeriousWarningMsg: m_Result.Append("SW:", le.m_szTag, " ", le.m_szText, "\n"); break; case ezLogMsgType::WarningMsg: m_Result.Append("W:", le.m_szTag, " ", le.m_szText, "\n"); break; case ezLogMsgType::SuccessMsg: m_Result.Append("S:", le.m_szTag, " ", le.m_szText, "\n"); break; case ezLogMsgType::InfoMsg: m_Result.Append("I:", le.m_szTag, " ", le.m_szText, "\n"); break; case ezLogMsgType::DevMsg: m_Result.Append("E:", le.m_szTag, " ", le.m_szText, "\n"); break; case ezLogMsgType::DebugMsg: m_Result.Append("D:", le.m_szTag, " ", le.m_szText, "\n"); break; default: EZ_REPORT_FAILURE("Invalid msg type"); break; } } ezStringBuilder m_Result; }; } // namespace EZ_CREATE_SIMPLE_TEST(Logging, Log) { LogTestLogInterface log; LogTestLogInterface log2; ezLogSystemScope logScope(&log); EZ_TEST_BLOCK(ezTestBlock::Enabled, "Output") { EZ_LOG_BLOCK("Verse 1", "Portal: Still Alive"); ezLog::GetThreadLocalLogSystem()->SetLogLevel(ezLogMsgType::All); ezLog::Success("{0}", "This was a triumph."); ezLog::Info("{0}", "I'm making a note here:"); ezLog::Error("{0}", "Huge Success"); ezLog::Info("{0}", "It's hard to overstate my satisfaction."); ezLog::Dev("{0}", "Aperture Science. We do what we must, because we can,"); ezLog::Dev("{0}", "For the good of all of us, except the ones who are dead."); ezLog::Flush(); ezLog::Flush(); // second flush should be ignored { EZ_LOG_BLOCK("Verse 2"); ezLog::GetThreadLocalLogSystem()->SetLogLevel(ezLogMsgType::DevMsg); ezLog::Dev("But there's no sense crying over every mistake."); ezLog::Debug("You just keep on trying 'till you run out of cake."); ezLog::Info("And the science gets done, and you make a neat gun"); ezLog::Error("for the people who are still alive."); } { EZ_LOG_BLOCK("Verse 3"); ezLog::GetThreadLocalLogSystem()->SetLogLevel(ezLogMsgType::InfoMsg); ezLog::Info("I'm not even angry."); ezLog::Debug("I'm being so sincere right now."); ezLog::Dev("Even though you broke my heart and killed me."); ezLog::Info("And tore me to pieces,"); ezLog::Dev("and threw every piece into a fire."); ezLog::Info("As they burned it hurt because I was so happy for you."); ezLog::Error("Now these points of data make a beautiful line"); ezLog::Dev("and we're off the beta, we're releasing on time."); ezLog::Flush(); ezLog::Flush(); { EZ_LOG_BLOCK("Verse 4"); ezLog::GetThreadLocalLogSystem()->SetLogLevel(ezLogMsgType::SuccessMsg); ezLog::Info("So I'm glad I got burned,"); ezLog::Debug("think of all the things we learned"); ezLog::Debug("for the people who are still alive."); { ezLogSystemScope logScope2(&log2); EZ_LOG_BLOCK("Interlude"); ezLog::Info("Well here we are again. It's always such a pleasure."); ezLog::Error("Remember when you tried to kill me twice?"); } { EZ_LOG_BLOCK("Verse 5"); ezLog::GetThreadLocalLogSystem()->SetLogLevel(ezLogMsgType::WarningMsg); ezLog::Debug("Go ahead and leave me."); ezLog::Info("I think I prefer to stay inside."); ezLog::Dev("Maybe you'll find someone else, to help you."); ezLog::Dev("Maybe Black Mesa."); ezLog::Info("That was a joke. Haha. Fat chance."); ezLog::Warning("Anyway, this cake is great."); ezLog::Success("It's so delicious and moist."); ezLog::Dev("Look at me still talking when there's science to do."); ezLog::Error("When I look up there it makes me glad I'm not you."); ezLog::Info("I've experiments to run,"); ezLog::SeriousWarning("there is research to be done on the people who are still alive."); } } } } { EZ_LOG_BLOCK("Verse 6", "Last One"); ezLog::GetThreadLocalLogSystem()->SetLogLevel(ezLogMsgType::ErrorMsg); ezLog::Dev("And believe me I am still alive."); ezLog::Info("I'm doing science and I'm still alive."); ezLog::Success("I feel fantastic and I'm still alive."); ezLog::Warning("While you're dying I'll be still alive."); ezLog::Error("And when you're dead I will be, still alive."); ezLog::Debug("Still alive, still alive."); } /// \todo This test will fail if EZ_COMPILE_FOR_DEVELOPMENT is disabled. /// We also currently don't test ezLog::Debug, because our build machines compile in release and then the text below would need to be /// different. const char* szResult = log.m_Result; const char* szExpected = "\ >Portal: Still Alive Verse 1\n\ S: This was a triumph.\n\ I: I'm making a note here:\n\ E: Huge Success\n\ I: It's hard to overstate my satisfaction.\n\ E: Aperture Science. We do what we must, because we can,\n\ E: For the good of all of us, except the ones who are dead.\n\ [Flush]\n\ > Verse 2\n\ E: But there's no sense crying over every mistake.\n\ I: And the science gets done, and you make a neat gun\n\ E: for the people who are still alive.\n\ < Verse 2\n\ > Verse 3\n\ I: I'm not even angry.\n\ I: And tore me to pieces,\n\ I: As they burned it hurt because I was so happy for you.\n\ E: Now these points of data make a beautiful line\n\ [Flush]\n\ > Verse 4\n\ > Verse 5\n\ W: Anyway, this cake is great.\n\ E: When I look up there it makes me glad I'm not you.\n\ SW: there is research to be done on the people who are still alive.\n\ < Verse 5\n\ < Verse 4\n\ < Verse 3\n\ <Portal: Still Alive Verse 1\n\ >Last One Verse 6\n\ E: And when you're dead I will be, still alive.\n\ <Last One Verse 6\n\ "; EZ_TEST_STRING(szResult, szExpected); const char* szResult2 = log2.m_Result; const char* szExpected2 = "\ > Interlude\n\ I: Well here we are again. It's always such a pleasure.\n\ E: Remember when you tried to kill me twice?\n\ < Interlude\n\ "; EZ_TEST_STRING(szResult2, szExpected2); } EZ_CREATE_SIMPLE_TEST(Logging, GlobalTestLog) { ezLog::GetThreadLocalLogSystem()->SetLogLevel(ezLogMsgType::All); { ezTestLogInterface log; ezTestLogSystemScope scope(&log, true); log.ExpectMessage("managed to break", ezLogMsgType::ErrorMsg); log.ExpectMessage("my heart", ezLogMsgType::WarningMsg); log.ExpectMessage("see you", ezLogMsgType::WarningMsg, 10); { class LogThread : public ezThread { public: virtual ezUInt32 Run() override { ezLog::Warning("I see you!"); ezLog::Debug("Test debug"); return 0; } }; LogThread thread[10]; for (ezUInt32 i = 0; i < 10; ++i) { thread[i].Start(); } ezLog::Error("The only thing you managed to break so far"); ezLog::Warning("is my heart"); for (ezUInt32 i = 0; i < 10; ++i) { thread[i].Join(); } } } }
32.058366
135
0.627139
Tekh-ops
3ee6414a3a9f9206ccc08bc7d69670c7e5fc156c
48,845
cc
C++
Firestore/core/test/unit/local/leveldb_key_test.cc
liam-i/firebase-ios-sdk
136e71f7aa438236421307a69c01789855515464
[ "Apache-2.0" ]
1
2022-03-26T00:08:22.000Z
2022-03-26T00:08:22.000Z
Firestore/core/test/unit/local/leveldb_key_test.cc
AhmedShehata5/firebase-ios-sdk
b4dd98da69fca029123788e69e14d612ef44e0d1
[ "Apache-2.0" ]
null
null
null
Firestore/core/test/unit/local/leveldb_key_test.cc
AhmedShehata5/firebase-ios-sdk
b4dd98da69fca029123788e69e14d612ef44e0d1
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2018 Google * * 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 "Firestore/core/src/local/leveldb_key.h" #include <type_traits> #include "Firestore/core/src/util/autoid.h" #include "Firestore/core/src/util/string_util.h" #include "Firestore/core/test/unit/testutil/testutil.h" #include "absl/strings/match.h" #include "gtest/gtest.h" using firebase::firestore::model::BatchId; using firebase::firestore::model::DocumentKey; using firebase::firestore::model::ResourcePath; using firebase::firestore::model::SnapshotVersion; using firebase::firestore::model::TargetId; namespace firebase { namespace firestore { namespace local { namespace { std::string RemoteDocKey(absl::string_view path_string) { return LevelDbRemoteDocumentKey::Key(testutil::Key(path_string)); } std::string RemoteDocKeyPrefix(absl::string_view path_string) { return LevelDbRemoteDocumentKey::KeyPrefix(testutil::Resource(path_string)); } std::string DocMutationKey(absl::string_view user_id, absl::string_view key, BatchId batch_id) { return LevelDbDocumentMutationKey::Key(user_id, testutil::Key(key), batch_id); } std::string TargetDocKey(TargetId target_id, absl::string_view key) { return LevelDbTargetDocumentKey::Key(target_id, testutil::Key(key)); } std::string DocTargetKey(absl::string_view key, TargetId target_id) { return LevelDbDocumentTargetKey::Key(testutil::Key(key), target_id); } std::string RemoteDocumentReadTimeKeyPrefix(absl::string_view collection_path, int64_t version) { return LevelDbRemoteDocumentReadTimeKey::KeyPrefix( testutil::Resource(collection_path), testutil::Version(version)); } std::string RemoteDocumentReadTimeKey(absl::string_view collection_path, int64_t version, absl::string_view document_id) { return LevelDbRemoteDocumentReadTimeKey::Key( testutil::Resource(collection_path), testutil::Version(version), document_id); } } // namespace /** * Asserts that the description for given key is equal to the expected * description. * * @param key A StringView of a textual key * @param key A string that `Describe(key)` is expected to produce. */ #define AssertExpectedKeyDescription(expected_description, key) \ ASSERT_EQ((expected_description), DescribeKey(key)) TEST(LevelDbMutationKeyTest, Prefixing) { auto table_key = LevelDbMutationKey::KeyPrefix(); auto empty_user_key = LevelDbMutationKey::KeyPrefix(""); auto foo_user_key = LevelDbMutationKey::KeyPrefix("foo"); auto foo2_key = LevelDbMutationKey::Key("foo", 2); ASSERT_TRUE(absl::StartsWith(empty_user_key, table_key)); // This is critical: prefixes of the a value don't convert into prefixes of // the key. ASSERT_TRUE(absl::StartsWith(foo_user_key, table_key)); ASSERT_FALSE(absl::StartsWith(foo_user_key, empty_user_key)); // However whole segments in common are prefixes. ASSERT_TRUE(absl::StartsWith(foo2_key, table_key)); ASSERT_TRUE(absl::StartsWith(foo2_key, foo_user_key)); } TEST(LevelDbMutationKeyTest, EncodeDecodeCycle) { LevelDbMutationKey key; std::string user("foo"); std::vector<BatchId> batch_ids{0, 1, 100, INT_MAX - 1, INT_MAX}; for (auto batch_id : batch_ids) { auto encoded = LevelDbMutationKey::Key(user, batch_id); bool ok = key.Decode(encoded); ASSERT_TRUE(ok); ASSERT_EQ(user, key.user_id()); ASSERT_EQ(batch_id, key.batch_id()); } } TEST(LevelDbMutationKeyTest, Description) { AssertExpectedKeyDescription("[mutation: incomplete key]", LevelDbMutationKey::KeyPrefix()); AssertExpectedKeyDescription("[mutation: user_id=user1 incomplete key]", LevelDbMutationKey::KeyPrefix("user1")); auto key = LevelDbMutationKey::Key("user1", 42); AssertExpectedKeyDescription("[mutation: user_id=user1 batch_id=42]", key); AssertExpectedKeyDescription( "[mutation: user_id=user1 batch_id=42 invalid " "key=<hW11dGF0aW9uAAGNdXNlcjEAAYqqgCBleHRyYQ==>]", key + " extra"); // Truncate the key so that it's missing its terminator. key.resize(key.size() - 1); AssertExpectedKeyDescription( "[mutation: user_id=user1 batch_id=42 incomplete key]", key); } TEST(LevelDbDocumentMutationKeyTest, Prefixing) { auto table_key = LevelDbDocumentMutationKey::KeyPrefix(); auto empty_user_key = LevelDbDocumentMutationKey::KeyPrefix(""); auto foo_user_key = LevelDbDocumentMutationKey::KeyPrefix("foo"); DocumentKey document_key = testutil::Key("foo/bar"); auto foo2_key = LevelDbDocumentMutationKey::Key("foo", document_key, 2); ASSERT_TRUE(absl::StartsWith(empty_user_key, table_key)); // While we want a key with whole segments in common be considered a prefix // it's vital that partial segments in common not be prefixes. ASSERT_TRUE(absl::StartsWith(foo_user_key, table_key)); // Here even though "" is a prefix of "foo", that prefix is within a segment, // so keys derived from those segments cannot be prefixes of each other. ASSERT_FALSE(absl::StartsWith(foo_user_key, empty_user_key)); ASSERT_FALSE(absl::StartsWith(empty_user_key, foo_user_key)); // However whole segments in common are prefixes. ASSERT_TRUE(absl::StartsWith(foo2_key, table_key)); ASSERT_TRUE(absl::StartsWith(foo2_key, foo_user_key)); } TEST(LevelDbDocumentMutationKeyTest, EncodeDecodeCycle) { LevelDbDocumentMutationKey key; std::string user("foo"); std::vector<DocumentKey> document_keys{testutil::Key("a/b"), testutil::Key("a/b/c/d")}; std::vector<BatchId> batch_ids{0, 1, 100, INT_MAX - 1, INT_MAX}; for (BatchId batch_id : batch_ids) { for (auto&& document_key : document_keys) { auto encoded = LevelDbDocumentMutationKey::Key(user, document_key, batch_id); bool ok = key.Decode(encoded); ASSERT_TRUE(ok); ASSERT_EQ(user, key.user_id()); ASSERT_EQ(document_key, key.document_key()); ASSERT_EQ(batch_id, key.batch_id()); } } } TEST(LevelDbDocumentMutationKeyTest, Ordering) { // Different user: ASSERT_LT(DocMutationKey("1", "foo/bar", 0), DocMutationKey("10", "foo/bar", 0)); ASSERT_LT(DocMutationKey("1", "foo/bar", 0), DocMutationKey("2", "foo/bar", 0)); // Different paths: ASSERT_LT(DocMutationKey("1", "foo/bar", 0), DocMutationKey("1", "foo/baz", 0)); ASSERT_LT(DocMutationKey("1", "foo/bar", 0), DocMutationKey("1", "foo/bar2", 0)); ASSERT_LT(DocMutationKey("1", "foo/bar", 0), DocMutationKey("1", "foo/bar/suffix/key", 0)); ASSERT_LT(DocMutationKey("1", "foo/bar/suffix/key", 0), DocMutationKey("1", "foo/bar2", 0)); // Different batch_id: ASSERT_LT(DocMutationKey("1", "foo/bar", 0), DocMutationKey("1", "foo/bar", 1)); } TEST(LevelDbDocumentMutationKeyTest, Description) { AssertExpectedKeyDescription("[document_mutation: incomplete key]", LevelDbDocumentMutationKey::KeyPrefix()); AssertExpectedKeyDescription( "[document_mutation: user_id=user1 incomplete key]", LevelDbDocumentMutationKey::KeyPrefix("user1")); auto key = LevelDbDocumentMutationKey::KeyPrefix( "user1", testutil::Resource("foo/bar")); AssertExpectedKeyDescription( "[document_mutation: user_id=user1 path=foo/bar incomplete key]", key); key = LevelDbDocumentMutationKey::Key("user1", testutil::Key("foo/bar"), 42); AssertExpectedKeyDescription( "[document_mutation: user_id=user1 path=foo/bar batch_id=42]", key); } TEST(LevelDbTargetGlobalKeyTest, EncodeDecodeCycle) { LevelDbTargetGlobalKey key; auto encoded = LevelDbTargetGlobalKey::Key(); bool ok = key.Decode(encoded); ASSERT_TRUE(ok); } TEST(LevelDbTargetGlobalKeyTest, Description) { AssertExpectedKeyDescription("[target_global:]", LevelDbTargetGlobalKey::Key()); } TEST(LevelDbTargetKeyTest, EncodeDecodeCycle) { LevelDbTargetKey key; TargetId target_id = 42; auto encoded = LevelDbTargetKey::Key(42); bool ok = key.Decode(encoded); ASSERT_TRUE(ok); ASSERT_EQ(target_id, key.target_id()); } TEST(LevelDbTargetKeyTest, Description) { AssertExpectedKeyDescription("[target: target_id=42]", LevelDbTargetKey::Key(42)); } TEST(LevelDbQueryTargetKeyTest, EncodeDecodeCycle) { LevelDbQueryTargetKey key; std::string canonical_id("foo"); TargetId target_id = 42; auto encoded = LevelDbQueryTargetKey::Key(canonical_id, 42); bool ok = key.Decode(encoded); ASSERT_TRUE(ok); ASSERT_EQ(canonical_id, key.canonical_id()); ASSERT_EQ(target_id, key.target_id()); } TEST(LevelDbQueryKeyTest, Description) { AssertExpectedKeyDescription("[query_target: canonical_id=foo target_id=42]", LevelDbQueryTargetKey::Key("foo", 42)); } TEST(TargetDocumentKeyTest, EncodeDecodeCycle) { LevelDbTargetDocumentKey key; auto encoded = LevelDbTargetDocumentKey::Key(42, testutil::Key("foo/bar")); bool ok = key.Decode(encoded); ASSERT_TRUE(ok); ASSERT_EQ(42, key.target_id()); ASSERT_EQ(testutil::Key("foo/bar"), key.document_key()); } TEST(TargetDocumentKeyTest, Ordering) { // Different target_id: ASSERT_LT(TargetDocKey(1, "foo/bar"), TargetDocKey(2, "foo/bar")); ASSERT_LT(TargetDocKey(2, "foo/bar"), TargetDocKey(10, "foo/bar")); ASSERT_LT(TargetDocKey(10, "foo/bar"), TargetDocKey(100, "foo/bar")); ASSERT_LT(TargetDocKey(42, "foo/bar"), TargetDocKey(100, "foo/bar")); // Different paths: ASSERT_LT(TargetDocKey(1, "foo/bar"), TargetDocKey(1, "foo/baz")); ASSERT_LT(TargetDocKey(1, "foo/bar"), TargetDocKey(1, "foo/bar2")); ASSERT_LT(TargetDocKey(1, "foo/bar"), TargetDocKey(1, "foo/bar/suffix/key")); ASSERT_LT(TargetDocKey(1, "foo/bar/suffix/key"), TargetDocKey(1, "foo/bar2")); } TEST(TargetDocumentKeyTest, Description) { auto key = LevelDbTargetDocumentKey::Key(42, testutil::Key("foo/bar")); ASSERT_EQ("[target_document: target_id=42 path=foo/bar]", DescribeKey(key)); } TEST(DocumentTargetKeyTest, EncodeDecodeCycle) { LevelDbDocumentTargetKey key; auto encoded = LevelDbDocumentTargetKey::Key(testutil::Key("foo/bar"), 42); bool ok = key.Decode(encoded); ASSERT_TRUE(ok); ASSERT_EQ(testutil::Key("foo/bar"), key.document_key()); ASSERT_EQ(42, key.target_id()); } TEST(DocumentTargetKeyTest, Description) { auto key = LevelDbDocumentTargetKey::Key(testutil::Key("foo/bar"), 42); ASSERT_EQ("[document_target: path=foo/bar target_id=42]", DescribeKey(key)); } TEST(DocumentTargetKeyTest, Ordering) { // Different paths: ASSERT_LT(DocTargetKey("foo/bar", 1), DocTargetKey("foo/baz", 1)); ASSERT_LT(DocTargetKey("foo/bar", 1), DocTargetKey("foo/bar2", 1)); ASSERT_LT(DocTargetKey("foo/bar", 1), DocTargetKey("foo/bar/suffix/key", 1)); ASSERT_LT(DocTargetKey("foo/bar/suffix/key", 1), DocTargetKey("foo/bar2", 1)); // Different target_id: ASSERT_LT(DocTargetKey("foo/bar", 1), DocTargetKey("foo/bar", 2)); ASSERT_LT(DocTargetKey("foo/bar", 2), DocTargetKey("foo/bar", 10)); ASSERT_LT(DocTargetKey("foo/bar", 10), DocTargetKey("foo/bar", 100)); ASSERT_LT(DocTargetKey("foo/bar", 42), DocTargetKey("foo/bar", 100)); } TEST(RemoteDocumentKeyTest, Prefixing) { auto table_key = LevelDbRemoteDocumentKey::KeyPrefix(); ASSERT_TRUE(absl::StartsWith(RemoteDocKey("foo/bar"), table_key)); // This is critical: foo/bar2 should not contain foo/bar. ASSERT_FALSE( absl::StartsWith(RemoteDocKey("foo/bar2"), RemoteDocKey("foo/bar"))); // Prefixes must be encoded specially ASSERT_FALSE(absl::StartsWith(RemoteDocKey("foo/bar/baz/quu"), RemoteDocKey("foo/bar"))); ASSERT_TRUE(absl::StartsWith(RemoteDocKey("foo/bar/baz/quu"), RemoteDocKeyPrefix("foo/bar"))); ASSERT_TRUE(absl::StartsWith(RemoteDocKeyPrefix("foo/bar/baz/quu"), RemoteDocKeyPrefix("foo/bar"))); ASSERT_TRUE(absl::StartsWith(RemoteDocKeyPrefix("foo/bar/baz"), RemoteDocKeyPrefix("foo/bar"))); ASSERT_TRUE(absl::StartsWith(RemoteDocKeyPrefix("foo/bar"), RemoteDocKeyPrefix("foo"))); } TEST(RemoteDocumentKeyTest, Ordering) { ASSERT_LT(RemoteDocKey("foo/bar"), RemoteDocKey("foo/bar2")); ASSERT_LT(RemoteDocKey("foo/bar"), RemoteDocKey("foo/bar/suffix/key")); } TEST(RemoteDocumentKeyTest, EncodeDecodeCycle) { LevelDbRemoteDocumentKey key; std::vector<std::string> paths{"foo/bar", "foo/bar2", "foo/bar/baz/quux"}; for (auto&& path : paths) { auto encoded = RemoteDocKey(path); bool ok = key.Decode(encoded); ASSERT_TRUE(ok); ASSERT_EQ(testutil::Key(path), key.document_key()); } } TEST(RemoteDocumentKeyTest, Description) { AssertExpectedKeyDescription( "[remote_document: path=foo/bar/baz/quux]", LevelDbRemoteDocumentKey::Key(testutil::Key("foo/bar/baz/quux"))); } TEST(RemoteDocumentReadTimeKeyTest, Ordering) { // Different collection paths: ASSERT_LT(RemoteDocumentReadTimeKeyPrefix("bar", 1), RemoteDocumentReadTimeKeyPrefix("baz", 1)); ASSERT_LT(RemoteDocumentReadTimeKeyPrefix("bar", 1), RemoteDocumentReadTimeKeyPrefix("foo/doc/bar", 1)); ASSERT_LT(RemoteDocumentReadTimeKeyPrefix("foo/doc/bar", 1), RemoteDocumentReadTimeKeyPrefix("foo/doc/baz", 1)); // Different read times: ASSERT_LT(RemoteDocumentReadTimeKeyPrefix("foo", 1), RemoteDocumentReadTimeKeyPrefix("foo", 2)); ASSERT_LT(RemoteDocumentReadTimeKeyPrefix("foo", 1), RemoteDocumentReadTimeKeyPrefix("foo", 1000000)); ASSERT_LT(RemoteDocumentReadTimeKeyPrefix("foo", 1000000), RemoteDocumentReadTimeKeyPrefix("foo", 1000001)); // Different document ids: ASSERT_LT(RemoteDocumentReadTimeKey("foo", 1, "a"), RemoteDocumentReadTimeKey("foo", 1, "b")); } TEST(RemoteDocumentReadTimeKeyTest, EncodeDecodeCycle) { LevelDbRemoteDocumentReadTimeKey key; std::vector<std::string> collection_paths{"foo", "foo/doc/bar", "foo/doc/bar/doc/baz"}; std::vector<int64_t> versions{1, 1000000, 1000001}; std::vector<std::string> document_ids{"docA", "docB"}; for (const auto& collection_path : collection_paths) { for (auto version : versions) { for (const auto& document_id : document_ids) { auto encoded = RemoteDocumentReadTimeKey(collection_path, version, document_id); bool ok = key.Decode(encoded); ASSERT_TRUE(ok); ASSERT_EQ(testutil::Resource(collection_path), key.collection_path()); ASSERT_EQ(testutil::Version(version), key.read_time()); ASSERT_EQ(document_id, key.document_id()); } } } } TEST(RemoteDocumentReadTimeKeyTest, Description) { AssertExpectedKeyDescription( "[remote_document_read_time: path=coll " "snapshot_version=Timestamp(seconds=1, nanoseconds=1000) " "document_id=doc]", RemoteDocumentReadTimeKey("coll", 1000001, "doc")); } TEST(BundleKeyTest, Prefixing) { auto table_key = LevelDbBundleKey::KeyPrefix(); ASSERT_TRUE(absl::StartsWith(LevelDbBundleKey::Key("foo/bar"), table_key)); ASSERT_FALSE(absl::StartsWith(LevelDbBundleKey::Key("foo/bar2"), LevelDbBundleKey::Key("foo/bar"))); } TEST(BundleKeyTest, Ordering) { ASSERT_LT(LevelDbBundleKey::Key("foo/bar"), LevelDbBundleKey::Key("foo/bar2")); ASSERT_LT(LevelDbBundleKey::Key("foo/bar"), LevelDbBundleKey::Key("foo/bar/suffix/key")); } TEST(BundleKeyTest, EncodeDecodeCycle) { LevelDbBundleKey key; std::vector<std::string> ids{"foo", "bar", "foo-bar?baz!quux"}; for (auto&& id : ids) { auto encoded = LevelDbBundleKey::Key(id); bool ok = key.Decode(encoded); ASSERT_TRUE(ok); ASSERT_EQ(id, key.bundle_id()); } } TEST(BundleKeyTest, Description) { AssertExpectedKeyDescription("[bundles: bundle_id=foo-bar?baz!quux]", LevelDbBundleKey::Key("foo-bar?baz!quux")); } TEST(NamedQueryKeyTest, Prefixing) { auto table_key = LevelDbNamedQueryKey::KeyPrefix(); ASSERT_TRUE( absl::StartsWith(LevelDbNamedQueryKey::Key("foo-bar"), table_key)); ASSERT_FALSE(absl::StartsWith(LevelDbNamedQueryKey::Key("foo-bar2"), LevelDbNamedQueryKey::Key("foo-bar"))); } TEST(NamedQueryKeyTest, Ordering) { ASSERT_LT(LevelDbNamedQueryKey::Key("foo/bar"), LevelDbNamedQueryKey::Key("foo/bar2")); ASSERT_LT(LevelDbNamedQueryKey::Key("foo/bar"), LevelDbNamedQueryKey::Key("foo/bar/suffix/key")); } TEST(NamedQueryKeyTest, EncodeDecodeCycle) { LevelDbNamedQueryKey key; std::vector<std::string> names{"foo/bar", "foo/bar2", "foo-bar?baz!quux"}; for (auto&& name : names) { auto encoded = LevelDbNamedQueryKey::Key(name); bool ok = key.Decode(encoded); ASSERT_TRUE(ok); ASSERT_EQ(name, key.name()); } } TEST(NamedQueryKeyTest, Description) { AssertExpectedKeyDescription("[named_queries: query_name=foo-bar?baz!quux]", LevelDbNamedQueryKey::Key("foo-bar?baz!quux")); } TEST(IndexConfigurationKeyTest, Prefixing) { auto table_key = LevelDbIndexConfigurationKey::KeyPrefix(); ASSERT_TRUE( absl::StartsWith(LevelDbIndexConfigurationKey::Key(0, ""), table_key)); ASSERT_FALSE(absl::StartsWith(LevelDbIndexConfigurationKey::Key(1, ""), LevelDbIndexConfigurationKey::Key(2, ""))); ASSERT_FALSE(absl::StartsWith(LevelDbIndexConfigurationKey::Key(1, "g"), LevelDbIndexConfigurationKey::Key(1, "ag"))); } TEST(IndexConfigurationKeyTest, Ordering) { ASSERT_LT(LevelDbIndexConfigurationKey::Key(0, ""), LevelDbIndexConfigurationKey::Key(1, "")); ASSERT_EQ(LevelDbIndexConfigurationKey::Key(1, ""), LevelDbIndexConfigurationKey::Key(1, "")); ASSERT_LT(LevelDbIndexConfigurationKey::Key(0, "a"), LevelDbIndexConfigurationKey::Key(0, "b")); ASSERT_EQ(LevelDbIndexConfigurationKey::Key(1, "a"), LevelDbIndexConfigurationKey::Key(1, "a")); } TEST(IndexConfigurationKeyTest, EncodeDecodeCycle) { LevelDbIndexConfigurationKey key; std::vector<std::string> groups = { "", "ab", "12", ",867t-b", "汉语; traditional Chinese: 漢語; pinyin: Hànyǔ[b]", "اَلْعَرَبِيَّةُ, al-ʿarabiyyah "}; for (int32_t id = -5; id < 10; ++id) { auto s = groups[(id + 5) % groups.size()]; auto encoded = LevelDbIndexConfigurationKey::Key(id, s); bool ok = key.Decode(encoded); ASSERT_TRUE(ok); ASSERT_EQ(id, key.index_id()); ASSERT_EQ(s, key.collection_group()); } } TEST(IndexConfigurationKeyTest, Description) { AssertExpectedKeyDescription( "[index_configuration: index_id=8 collection_group=group]", LevelDbIndexConfigurationKey::Key(8, "group")); } TEST(IndexStateKeyTest, Prefixing) { auto table_key = LevelDbIndexStateKey::KeyPrefix(); ASSERT_TRUE( absl::StartsWith(LevelDbIndexStateKey::Key("user_a", 0), table_key)); ASSERT_FALSE(absl::StartsWith(LevelDbIndexStateKey::Key("user_a", 0), LevelDbIndexStateKey::Key("user_b", 0))); ASSERT_FALSE(absl::StartsWith(LevelDbIndexStateKey::Key("user_a", 0), LevelDbIndexStateKey::Key("user_a", 1))); } TEST(IndexStateKeyTest, Ordering) { ASSERT_LT(LevelDbIndexStateKey::Key("foo/bar", 0), LevelDbIndexStateKey::Key("foo/bar", 1)); ASSERT_LT(LevelDbIndexStateKey::Key("foo/bar", 0), LevelDbIndexStateKey::Key("foo/bar1", 0)); } TEST(IndexStateKeyTest, EncodeDecodeCycle) { LevelDbIndexStateKey key; std::vector<std::pair<std::string, int32_t>> ids{ {"foo/bar", 0}, {"foo/bar2", 1}, {"foo-bar?baz!quux", -1}}; for (auto&& id : ids) { auto encoded = LevelDbIndexStateKey::Key(id.first, id.second); bool ok = key.Decode(encoded); ASSERT_TRUE(ok); ASSERT_EQ(id.first, key.user_id()); ASSERT_EQ(id.second, key.index_id()); } } TEST(IndexStateKeyTest, Description) { AssertExpectedKeyDescription( "[index_state: user_id=foo-bar?baz!quux index_id=99]", LevelDbIndexStateKey::Key("foo-bar?baz!quux", 99)); } TEST(IndexEntryKeyTest, Prefixing) { auto table_key = LevelDbIndexEntryKey::KeyPrefix(); ASSERT_TRUE(absl::StartsWith( LevelDbIndexEntryKey::Key(0, "user_id", "array_value_encoded", "directional_value_encoded", "document_id_99"), table_key)); ASSERT_TRUE( absl::StartsWith(LevelDbIndexEntryKey::Key(0, "user_id", "", "", ""), LevelDbIndexEntryKey::KeyPrefix(0))); ASSERT_FALSE(absl::StartsWith(LevelDbIndexEntryKey::Key(0, "", "", "", ""), LevelDbIndexEntryKey::Key(1, "", "", "", ""))); } TEST(IndexEntryKeyTest, Ordering) { std::vector<std::string> entries = { LevelDbIndexEntryKey::Key(-1, "", "", "", ""), LevelDbIndexEntryKey::Key(0, "", "", "", ""), LevelDbIndexEntryKey::Key(0, "u", "", "", ""), LevelDbIndexEntryKey::Key(0, "v", "", "", ""), LevelDbIndexEntryKey::Key(0, "v", "a", "", ""), LevelDbIndexEntryKey::Key(0, "v", "b", "", ""), LevelDbIndexEntryKey::Key(0, "v", "b", "d", ""), LevelDbIndexEntryKey::Key(0, "v", "b", "e", ""), LevelDbIndexEntryKey::Key(0, "v", "b", "e", "doc"), LevelDbIndexEntryKey::Key(0, "v", "b", "e", "eoc"), }; for (size_t i = 0; i < entries.size() - 1; ++i) { auto& left = entries[i]; auto& right = entries[i + 1]; ASSERT_LT(left, right); } } TEST(IndexEntryKeyTest, EncodeDecodeCycle) { LevelDbIndexEntryKey key; struct IndexEntry { int32_t index_id; std::string user_id; std::string array_value; std::string dir_value; std::string document_name; }; std::vector<IndexEntry> entries = { {-1, "", "", "", ""}, {0, "foo", "bar", "baz", "did"}, {999, "u", "foo-bar?baz!quux", "", ""}, {-999, "u", "اَلْعَرَبِيَّةُ, al-ʿarabiyyah [al ʕaraˈbijːa] (audio speaker iconlisten) or " "عَرَبِيّ, ʿarabīy", "汉语; traditional Chinese: 漢語; pinyin: Hànyǔ[b] or also 中文", "doc"}, }; for (auto&& entry : entries) { auto encoded = LevelDbIndexEntryKey::Key(entry.index_id, entry.user_id, entry.array_value, entry.dir_value, entry.document_name); bool ok = key.Decode(encoded); ASSERT_TRUE(ok); ASSERT_EQ(entry.index_id, key.index_id()); ASSERT_EQ(entry.user_id, key.user_id()); ASSERT_EQ(entry.array_value, key.array_value()); ASSERT_EQ(entry.dir_value, key.directional_value()); ASSERT_EQ(entry.document_name, key.document_key()); } } TEST(IndexEntryKeyTest, Description) { AssertExpectedKeyDescription( "[index_entries: index_id=1 user_id=user array_value=array " "directional_value=directional document_id=foo-bar?baz!quux]", LevelDbIndexEntryKey::Key(1, "user", "array", "directional", "foo-bar?baz!quux")); } TEST(LevelDbDocumentOverlayKeyTest, Constructor) { LevelDbDocumentOverlayKey key("test_user", testutil::Key("coll/doc"), 123); EXPECT_EQ(key.user_id(), "test_user"); EXPECT_EQ(key.document_key(), testutil::Key("coll/doc")); EXPECT_EQ(key.largest_batch_id(), 123); } TEST(LevelDbDocumentOverlayKeyTest, RvalueOverloadedGetters) { LevelDbDocumentOverlayKey key("test_user", testutil::Key("coll/doc"), 123); model::DocumentKey&& document_key = std::move(key).document_key(); EXPECT_EQ(document_key, testutil::Key("coll/doc")); } TEST(LevelDbDocumentOverlayKeyTest, Encode) { LevelDbDocumentOverlayKey key("test_user", testutil::Key("coll/doc"), 123); const std::string encoded_key = key.Encode(); LevelDbDocumentOverlayKey decoded_key; ASSERT_TRUE(decoded_key.Decode(encoded_key)); EXPECT_EQ(decoded_key.user_id(), "test_user"); EXPECT_EQ(decoded_key.document_key(), testutil::Key("coll/doc")); EXPECT_EQ(decoded_key.largest_batch_id(), 123); } TEST(LevelDbDocumentOverlayKeyTest, Prefixing) { const std::string user1_key = LevelDbDocumentOverlayKey::KeyPrefix("test_user1"); const std::string user2_key = LevelDbDocumentOverlayKey::KeyPrefix("test_user2"); const std::string user1_doc1_key = LevelDbDocumentOverlayKey::KeyPrefix( "test_user1", testutil::Key("coll/doc1")); const std::string user2_doc2_key = LevelDbDocumentOverlayKey::KeyPrefix( "test_user2", testutil::Key("coll/doc2")); const std::string user1_doc2_key = LevelDbDocumentOverlayKey::KeyPrefix( "test_user1", testutil::Key("coll/doc2")); ASSERT_TRUE(absl::StartsWith(user1_doc1_key, user1_key)); ASSERT_TRUE(absl::StartsWith(user2_doc2_key, user2_key)); ASSERT_FALSE(absl::StartsWith(user1_key, user2_key)); ASSERT_FALSE(absl::StartsWith(user2_key, user1_key)); ASSERT_FALSE(absl::StartsWith(user1_doc1_key, user1_doc2_key)); ASSERT_FALSE(absl::StartsWith(user1_doc2_key, user1_doc1_key)); const std::string user1_doc1_batch_1_key = LevelDbDocumentOverlayKey::Key( "test_user1", testutil::Key("coll/doc1"), 1); const std::string user2_doc1_batch_1_key = LevelDbDocumentOverlayKey::Key( "test_user2", testutil::Key("coll/doc1"), 1); ASSERT_TRUE(absl::StartsWith(user1_doc1_batch_1_key, user1_key)); ASSERT_TRUE(absl::StartsWith(user2_doc1_batch_1_key, user2_key)); } TEST(LevelDbDocumentOverlayKeyTest, Ordering) { const std::string user1_doc1_batch_1_key = LevelDbDocumentOverlayKey::Key( "test_user1", testutil::Key("coll/doc1"), 1); const std::string user2_doc1_batch_1_key = LevelDbDocumentOverlayKey::Key( "test_user2", testutil::Key("coll/doc1"), 1); const std::string user1_doc2_batch_1_key = LevelDbDocumentOverlayKey::Key( "test_user1", testutil::Key("coll/doc2"), 1); const std::string user1_doc1_batch_2_key = LevelDbDocumentOverlayKey::Key( "test_user1", testutil::Key("coll/doc1"), 2); ASSERT_LT(user1_doc1_batch_1_key, user2_doc1_batch_1_key); ASSERT_LT(user1_doc1_batch_1_key, user1_doc2_batch_1_key); ASSERT_LT(user1_doc1_batch_1_key, user1_doc1_batch_2_key); } TEST(LevelDbDocumentOverlayKeyTest, EncodeDecodeCycle) { const std::vector<std::string> user_ids{"test_user", "foo/bar2", "foo-bar?baz!quux"}; const std::vector<std::string> document_keys{"col1/doc1", "col2/doc2/col3/doc3"}; const std::vector<BatchId> batch_ids{1, 2, 3}; for (const std::string& user_id : user_ids) { for (const std::string& document_key : document_keys) { for (BatchId batch_id : batch_ids) { SCOPED_TRACE(absl::StrCat("user_name=", user_id, " document_key=", document_key, " largest_batch_id=", batch_id)); const std::string encoded = LevelDbDocumentOverlayKey::Key( user_id, testutil::Key(document_key), batch_id); LevelDbDocumentOverlayKey key; EXPECT_TRUE(key.Decode(encoded)); EXPECT_EQ(key.user_id(), user_id); EXPECT_EQ(key.document_key(), testutil::Key(document_key)); EXPECT_EQ(key.largest_batch_id(), batch_id); } } } } TEST(LevelDbDocumentOverlayKeyTest, Description) { AssertExpectedKeyDescription( "[document_overlays: user_id=foo-bar?baz!quux path=coll/doc " "batch_id=123]", LevelDbDocumentOverlayKey::Key("foo-bar?baz!quux", testutil::Key("coll/doc"), 123)); } TEST(LevelDbDocumentOverlayIndexKeyTest, TypeTraits) { static_assert( std::has_virtual_destructor<LevelDbDocumentOverlayIndexKey>::value, "LevelDbDocumentOverlayIndexKey should have a virtual destructor"); } TEST(LevelDbDocumentOverlayIndexKeyTest, ToLevelDbDocumentOverlayKey) { LevelDbDocumentOverlayIndexKey index_key; index_key.Reset("test_user", 123, testutil::Key("coll/doc1")); LevelDbDocumentOverlayKey key = index_key.ToLevelDbDocumentOverlayKey(); EXPECT_EQ(key.user_id(), "test_user"); EXPECT_EQ(key.largest_batch_id(), 123); EXPECT_EQ(key.document_key(), testutil::Key("coll/doc1")); } TEST(LevelDbDocumentOverlayIndexKeyTest, ToLevelDbDocumentOverlayKeyRvalue) { LevelDbDocumentOverlayIndexKey index_key; index_key.Reset("test_user", 123, testutil::Key("coll/doc1")); LevelDbDocumentOverlayKey key = std::move(index_key).ToLevelDbDocumentOverlayKey(); EXPECT_EQ(key.user_id(), "test_user"); EXPECT_EQ(key.largest_batch_id(), 123); EXPECT_EQ(key.document_key(), testutil::Key("coll/doc1")); } TEST(LevelDbDocumentOverlayIndexKeyTest, Getters) { LevelDbDocumentOverlayIndexKey key; key.Reset("test_user", 123, testutil::Key("coll/doc1")); EXPECT_EQ(key.user_id(), "test_user"); EXPECT_EQ(key.largest_batch_id(), 123); EXPECT_EQ(key.document_key(), testutil::Key("coll/doc1")); } TEST(LevelDbDocumentOverlayLargestBatchIdIndexKeyTest, Prefixing) { const std::string user1_key = LevelDbDocumentOverlayLargestBatchIdIndexKey::KeyPrefix("test_user1"); const std::string user2_key = LevelDbDocumentOverlayLargestBatchIdIndexKey::KeyPrefix("test_user2"); const std::string user1_batch1_key = LevelDbDocumentOverlayLargestBatchIdIndexKey::KeyPrefix("test_user1", 1); const std::string user2_batch2_key = LevelDbDocumentOverlayLargestBatchIdIndexKey::KeyPrefix("test_user2", 2); const std::string user1_batch2_key = LevelDbDocumentOverlayLargestBatchIdIndexKey::KeyPrefix("test_user1", 2); ASSERT_TRUE(absl::StartsWith(user1_batch1_key, user1_key)); ASSERT_TRUE(absl::StartsWith(user2_batch2_key, user2_key)); ASSERT_FALSE(absl::StartsWith(user1_key, user2_key)); ASSERT_FALSE(absl::StartsWith(user2_key, user1_key)); ASSERT_FALSE(absl::StartsWith(user1_batch1_key, user1_batch2_key)); ASSERT_FALSE(absl::StartsWith(user1_batch2_key, user1_batch1_key)); const std::string user1_batch1_doc1_key = LevelDbDocumentOverlayLargestBatchIdIndexKey::Key( "test_user1", 1, testutil::Key("coll/doc1")); const std::string user2_batch1_doc1_key = LevelDbDocumentOverlayLargestBatchIdIndexKey::Key( "test_user2", 1, testutil::Key("coll/doc1")); ASSERT_TRUE(absl::StartsWith(user1_batch1_doc1_key, user1_key)); ASSERT_FALSE(absl::StartsWith(user1_batch1_doc1_key, user2_key)); ASSERT_TRUE(absl::StartsWith(user2_batch1_doc1_key, user2_key)); ASSERT_FALSE(absl::StartsWith(user2_batch1_doc1_key, user1_key)); ASSERT_TRUE(absl::StartsWith(user1_batch1_doc1_key, user1_batch1_key)); ASSERT_FALSE(absl::StartsWith(user1_batch1_doc1_key, user1_batch2_key)); } TEST(LevelDbDocumentOverlayLargestBatchIdIndexKeyTest, Ordering) { const std::string user1_batch1_doc1_key = LevelDbDocumentOverlayLargestBatchIdIndexKey::Key( "user1", 1, testutil::Key("coll/doc1")); const std::string user2_batch1_doc1_key = LevelDbDocumentOverlayLargestBatchIdIndexKey::Key( "user2", 1, testutil::Key("coll/doc1")); const std::string user1_batch2_doc1_key = LevelDbDocumentOverlayLargestBatchIdIndexKey::Key( "user1", 2, testutil::Key("coll/doc1")); const std::string user2_batch2_doc1_key = LevelDbDocumentOverlayLargestBatchIdIndexKey::Key( "user2", 2, testutil::Key("coll/doc1")); const std::string user1_batch1_doc2_key = LevelDbDocumentOverlayLargestBatchIdIndexKey::Key( "user1", 1, testutil::Key("coll/doc2")); const std::string user2_batch1_doc2_key = LevelDbDocumentOverlayLargestBatchIdIndexKey::Key( "user2", 1, testutil::Key("coll/doc2")); const std::string user1_batch2_doc2_key = LevelDbDocumentOverlayLargestBatchIdIndexKey::Key( "user1", 2, testutil::Key("coll/doc2")); const std::string user2_batch2_doc2_key = LevelDbDocumentOverlayLargestBatchIdIndexKey::Key( "user2", 2, testutil::Key("coll/doc2")); ASSERT_LT(user1_batch1_doc1_key, user2_batch1_doc1_key); ASSERT_LT(user1_batch1_doc1_key, user1_batch2_doc1_key); ASSERT_LT(user1_batch1_doc1_key, user1_batch1_doc2_key); ASSERT_LT(user2_batch1_doc1_key, user2_batch2_doc1_key); ASSERT_LT(user2_batch1_doc1_key, user2_batch1_doc2_key); ASSERT_LT(user2_batch2_doc1_key, user2_batch2_doc2_key); } TEST(LevelDbDocumentOverlayLargestBatchIdIndexKeyTest, EncodeDecodeCycle) { const std::vector<std::string> user_ids{"test_user", "foo/bar2", "foo-bar?baz!quux"}; const std::vector<BatchId> batch_ids{1, 2, 3}; const std::vector<DocumentKey> document_keys{testutil::Key("coll/doc1"), testutil::Key("coll/doc2"), testutil::Key("coll/doc3")}; for (const std::string& user_id : user_ids) { for (BatchId batch_id : batch_ids) { for (const DocumentKey& document_key : document_keys) { SCOPED_TRACE(absl::StrCat("user_name=", user_id, " batch_id=", batch_id, " path=", document_key.ToString())); const std::string encoded = LevelDbDocumentOverlayLargestBatchIdIndexKey::Key(user_id, batch_id, document_key); LevelDbDocumentOverlayLargestBatchIdIndexKey key; EXPECT_TRUE(key.Decode(encoded)); EXPECT_EQ(key.user_id(), user_id); EXPECT_EQ(key.largest_batch_id(), batch_id); EXPECT_EQ(key.document_key(), document_key); } } } } TEST(LevelDbDocumentOverlayLargestBatchIdIndexKeyTest, Description) { AssertExpectedKeyDescription( "[document_overlays_largest_batch_id_index: user_id=foo-bar?baz!quux " "batch_id=123 path=coll/docX]", LevelDbDocumentOverlayLargestBatchIdIndexKey::Key( "foo-bar?baz!quux", 123, testutil::Key("coll/docX"))); } TEST(LevelDbDocumentOverlayLargestBatchIdIndexKeyTest, FromLevelDbDocumentOverlayKey) { LevelDbDocumentOverlayKey key("test_user", testutil::Key("coll/doc"), 123); const std::string encoded_key = LevelDbDocumentOverlayLargestBatchIdIndexKey::Key(key); LevelDbDocumentOverlayLargestBatchIdIndexKey decoded_key; ASSERT_TRUE(decoded_key.Decode(encoded_key)); EXPECT_EQ(decoded_key.user_id(), "test_user"); EXPECT_EQ(decoded_key.largest_batch_id(), 123); EXPECT_EQ(decoded_key.document_key(), testutil::Key("coll/doc")); } TEST(LevelDbDocumentOverlayCollectionIndexKeyTest, Prefixing) { const std::string user1_key = LevelDbDocumentOverlayCollectionIndexKey::KeyPrefix("test_user1"); const std::string user2_key = LevelDbDocumentOverlayCollectionIndexKey::KeyPrefix("test_user2"); const std::string user1_coll1_key = LevelDbDocumentOverlayCollectionIndexKey::KeyPrefix( "test_user1", ResourcePath{"coll1"}); const std::string user1_coll2_key = LevelDbDocumentOverlayCollectionIndexKey::KeyPrefix( "test_user1", ResourcePath{"coll2"}); const std::string user2_coll1_key = LevelDbDocumentOverlayCollectionIndexKey::KeyPrefix( "test_user2", ResourcePath{"coll1"}); const std::string user2_coll2_key = LevelDbDocumentOverlayCollectionIndexKey::KeyPrefix( "test_user2", ResourcePath{"coll2"}); const std::string user1_coll1_batch1_key = LevelDbDocumentOverlayCollectionIndexKey::KeyPrefix( "test_user1", ResourcePath{"coll1"}, 1); const std::string user1_coll1_batch2_key = LevelDbDocumentOverlayCollectionIndexKey::KeyPrefix( "test_user1", ResourcePath{"coll1"}, 2); const std::string user2_coll2_batch2_key = LevelDbDocumentOverlayCollectionIndexKey::KeyPrefix( "test_user2", ResourcePath{"coll2"}, 2); ASSERT_TRUE(absl::StartsWith(user1_coll1_key, user1_key)); ASSERT_TRUE(absl::StartsWith(user1_coll2_key, user1_key)); ASSERT_TRUE(absl::StartsWith(user2_coll1_key, user2_key)); ASSERT_TRUE(absl::StartsWith(user2_coll2_key, user2_key)); ASSERT_TRUE(absl::StartsWith(user1_coll1_batch1_key, user1_coll1_key)); ASSERT_TRUE(absl::StartsWith(user1_coll1_batch2_key, user1_coll1_key)); ASSERT_FALSE(absl::StartsWith(user1_key, user2_key)); ASSERT_FALSE(absl::StartsWith(user2_key, user1_key)); ASSERT_FALSE(absl::StartsWith(user1_coll1_key, user1_coll2_key)); ASSERT_FALSE(absl::StartsWith(user1_coll2_key, user1_coll1_key)); ASSERT_FALSE( absl::StartsWith(user1_coll1_batch1_key, user1_coll1_batch2_key)); ASSERT_FALSE( absl::StartsWith(user1_coll1_batch2_key, user1_coll1_batch1_key)); const std::string user1_coll1_batch1_doc1_key = LevelDbDocumentOverlayCollectionIndexKey::Key( "test_user1", ResourcePath{"coll1"}, 1, "doc1"); const std::string user2_coll2_batch2_doc2_key = LevelDbDocumentOverlayCollectionIndexKey::Key( "test_user2", ResourcePath{"coll2"}, 2, "doc2"); ASSERT_TRUE(absl::StartsWith(user1_coll1_batch1_doc1_key, user1_key)); ASSERT_TRUE(absl::StartsWith(user2_coll2_batch2_doc2_key, user2_key)); ASSERT_TRUE(absl::StartsWith(user1_coll1_batch1_doc1_key, user1_coll1_key)); ASSERT_TRUE(absl::StartsWith(user2_coll2_batch2_doc2_key, user2_coll2_key)); ASSERT_TRUE( absl::StartsWith(user1_coll1_batch1_doc1_key, user1_coll1_batch1_key)); ASSERT_TRUE( absl::StartsWith(user2_coll2_batch2_doc2_key, user2_coll2_batch2_key)); } TEST(LevelDbDocumentOverlayCollectionIndexKeyTest, Ordering) { const std::string user1_coll1_batch1_doc1_key = LevelDbDocumentOverlayCollectionIndexKey::Key( "user1", ResourcePath{"coll1"}, 1, "doc1"); const std::string user2_coll1_batch1_doc1_key = LevelDbDocumentOverlayCollectionIndexKey::Key( "user2", ResourcePath{"coll1"}, 1, "doc1"); const std::string user2_coll2_batch1_doc1_key = LevelDbDocumentOverlayCollectionIndexKey::Key( "user2", ResourcePath{"coll2"}, 1, "doc1"); const std::string user2_coll2_batch2_doc1_key = LevelDbDocumentOverlayCollectionIndexKey::Key( "user2", ResourcePath{"coll2"}, 2, "doc1"); const std::string user2_coll2_batch2_doc2_key = LevelDbDocumentOverlayCollectionIndexKey::Key( "user2", ResourcePath{"coll2"}, 2, "doc2"); ASSERT_LT(user1_coll1_batch1_doc1_key, user2_coll1_batch1_doc1_key); ASSERT_LT(user2_coll1_batch1_doc1_key, user2_coll2_batch1_doc1_key); ASSERT_LT(user2_coll2_batch1_doc1_key, user2_coll2_batch2_doc1_key); ASSERT_LT(user2_coll2_batch2_doc1_key, user2_coll2_batch2_doc2_key); } TEST(LevelDbDocumentOverlayCollectionIndexKeyTest, EncodeDecodeCycle) { const std::vector<std::string> user_ids{"test_user", "foo/bar2", "foo-bar?baz!quux"}; const std::vector<ResourcePath> collections{ ResourcePath{"coll1"}, ResourcePath{"coll2"}, ResourcePath{"coll3", "docX", "coll4"}}; const std::vector<BatchId> batch_ids{1, 2, 3}; const std::vector<std::string> document_ids{"doc1", "doc2", "doc3"}; for (const std::string& user_id : user_ids) { for (const ResourcePath& collection : collections) { for (const BatchId batch_id : batch_ids) { for (const std::string& document_id : document_ids) { SCOPED_TRACE(absl::StrCat("user_name=", user_id, " collection=", collection.CanonicalString(), " document_id=", document_id)); const std::string encoded = LevelDbDocumentOverlayCollectionIndexKey::Key( user_id, collection, batch_id, document_id); LevelDbDocumentOverlayCollectionIndexKey key; EXPECT_TRUE(key.Decode(encoded)); EXPECT_EQ(key.user_id(), user_id); EXPECT_EQ(key.collection(), collection); EXPECT_EQ(key.largest_batch_id(), batch_id); EXPECT_EQ(key.document_key(), DocumentKey(key.collection().Append(document_id))); } } } } } TEST(LevelDbDocumentOverlayCollectionIndexKeyTest, Description) { AssertExpectedKeyDescription( "[document_overlays_collection_index: user_id=foo-bar?baz!quux " "path=coll1 batch_id=123 document_id=docX]", LevelDbDocumentOverlayCollectionIndexKey::Key( "foo-bar?baz!quux", ResourcePath{"coll1"}, 123, "docX")); } TEST(LevelDbDocumentOverlayCollectionIndexKeyTest, FromLevelDbDocumentOverlayKey) { LevelDbDocumentOverlayKey key("test_user", testutil::Key("coll/doc"), 123); const std::string encoded_key = LevelDbDocumentOverlayCollectionIndexKey::Key(key); LevelDbDocumentOverlayCollectionIndexKey decoded_key; ASSERT_TRUE(decoded_key.Decode(encoded_key)); EXPECT_EQ(decoded_key.user_id(), "test_user"); EXPECT_EQ(decoded_key.collection(), ResourcePath{"coll"}); EXPECT_EQ(decoded_key.largest_batch_id(), 123); EXPECT_EQ(decoded_key.document_key(), testutil::Key("coll/doc")); } TEST(LevelDbDocumentOverlayCollectionGroupIndexKeyTest, Prefixing) { const std::string user1_key = LevelDbDocumentOverlayCollectionGroupIndexKey::KeyPrefix("test_user1"); const std::string user2_key = LevelDbDocumentOverlayCollectionGroupIndexKey::KeyPrefix("test_user2"); const std::string user1_group1_key = LevelDbDocumentOverlayCollectionGroupIndexKey::KeyPrefix("test_user1", "group1"); const std::string user1_group2_key = LevelDbDocumentOverlayCollectionGroupIndexKey::KeyPrefix("test_user1", "group2"); const std::string user2_group2_key = LevelDbDocumentOverlayCollectionGroupIndexKey::KeyPrefix("test_user2", "group2"); const std::string user1_group1_batch1_key = LevelDbDocumentOverlayCollectionGroupIndexKey::KeyPrefix("test_user1", "group1", 1); const std::string user1_group1_batch2_key = LevelDbDocumentOverlayCollectionGroupIndexKey::KeyPrefix("test_user1", "group1", 2); const std::string user2_group2_batch2_key = LevelDbDocumentOverlayCollectionGroupIndexKey::KeyPrefix("test_user2", "group2", 2); ASSERT_TRUE(absl::StartsWith(user1_group1_key, user1_key)); ASSERT_TRUE(absl::StartsWith(user1_group2_key, user1_key)); ASSERT_TRUE(absl::StartsWith(user2_group2_key, user2_key)); ASSERT_TRUE(absl::StartsWith(user1_group1_batch1_key, user1_group1_key)); ASSERT_TRUE(absl::StartsWith(user1_group1_batch2_key, user1_group1_key)); ASSERT_FALSE(absl::StartsWith(user1_key, user2_key)); ASSERT_FALSE(absl::StartsWith(user2_key, user1_key)); ASSERT_FALSE(absl::StartsWith(user1_group1_key, user1_group2_key)); ASSERT_FALSE(absl::StartsWith(user1_group2_key, user1_group1_key)); ASSERT_FALSE( absl::StartsWith(user1_group1_batch1_key, user1_group1_batch2_key)); ASSERT_FALSE( absl::StartsWith(user1_group1_batch2_key, user1_group1_batch1_key)); const std::string user1_group1_batch1_doc1_key = LevelDbDocumentOverlayCollectionGroupIndexKey::Key( "test_user1", "group1", 1, testutil::Key("coll/doc1")); const std::string user2_group2_batch2_doc2_key = LevelDbDocumentOverlayCollectionGroupIndexKey::Key( "test_user2", "group2", 2, testutil::Key("coll/doc2")); ASSERT_TRUE(absl::StartsWith(user1_group1_batch1_doc1_key, user1_key)); ASSERT_TRUE(absl::StartsWith(user2_group2_batch2_doc2_key, user2_key)); ASSERT_TRUE(absl::StartsWith(user1_group1_batch1_doc1_key, user1_group1_key)); ASSERT_TRUE(absl::StartsWith(user2_group2_batch2_doc2_key, user2_group2_key)); ASSERT_TRUE( absl::StartsWith(user1_group1_batch1_doc1_key, user1_group1_batch1_key)); ASSERT_TRUE( absl::StartsWith(user2_group2_batch2_doc2_key, user2_group2_batch2_key)); } TEST(LevelDbDocumentOverlayCollectionGroupIndexKeyTest, Ordering) { const std::string user1_group1_batch1_doc1_key = LevelDbDocumentOverlayCollectionGroupIndexKey::Key( "user1", "group1", 1, testutil::Key("coll/doc1")); const std::string user2_group1_batch1_doc1_key = LevelDbDocumentOverlayCollectionGroupIndexKey::Key( "user2", "group1", 1, testutil::Key("coll/doc1")); const std::string user2_group2_batch1_doc1_key = LevelDbDocumentOverlayCollectionGroupIndexKey::Key( "user2", "group2", 1, testutil::Key("coll/doc1")); const std::string user2_group2_batch2_doc1_key = LevelDbDocumentOverlayCollectionGroupIndexKey::Key( "user2", "group2", 2, testutil::Key("coll/doc1")); const std::string user2_group2_batch2_doc2_key = LevelDbDocumentOverlayCollectionGroupIndexKey::Key( "user2", "group2", 2, testutil::Key("coll/doc2")); ASSERT_LT(user1_group1_batch1_doc1_key, user2_group1_batch1_doc1_key); ASSERT_LT(user2_group1_batch1_doc1_key, user2_group2_batch1_doc1_key); ASSERT_LT(user2_group2_batch1_doc1_key, user2_group2_batch2_doc1_key); ASSERT_LT(user2_group2_batch2_doc1_key, user2_group2_batch2_doc2_key); } TEST(LevelDbDocumentOverlayCollectionGroupIndexKeyTest, EncodeDecodeCycle) { const std::vector<std::string> user_ids{"test_user", "foo/bar2", "foo-bar?baz!quux"}; // NOTE: These collection groups do not actually match the document keys used; // however, that's okay here in this unit test because the LevelDb key itself // doesn't care if they match. const std::vector<std::string> collection_groups{"group1", "group2"}; const std::vector<model::BatchId> batch_ids{1, 2, 3}; const std::vector<model::DocumentKey> document_keys{ testutil::Key("coll/doc1"), testutil::Key("coll/doc2"), testutil::Key("coll/doc3")}; for (const std::string& user_id : user_ids) { for (const std::string& collection_group : collection_groups) { for (const model::BatchId batch_id : batch_ids) { for (const model::DocumentKey& document_key : document_keys) { SCOPED_TRACE(absl::StrCat("user_name=", user_id, " collection_group=", collection_group, " path=", document_key.ToString())); const std::string encoded = LevelDbDocumentOverlayCollectionGroupIndexKey::Key( user_id, collection_group, batch_id, document_key); LevelDbDocumentOverlayCollectionGroupIndexKey key; EXPECT_TRUE(key.Decode(encoded)); EXPECT_EQ(key.user_id(), user_id); EXPECT_EQ(key.collection_group(), collection_group); EXPECT_EQ(key.largest_batch_id(), batch_id); EXPECT_EQ(key.document_key(), document_key); } } } } } TEST(LevelDbDocumentOverlayCollectionGroupIndexKeyTest, Description) { AssertExpectedKeyDescription( "[document_overlays_collection_group_index: user_id=foo-bar?baz!quux " "collection_group=group1 batch_id=123 path=coll/docX]", LevelDbDocumentOverlayCollectionGroupIndexKey::Key( "foo-bar?baz!quux", "group1", 123, testutil::Key("coll/docX"))); } TEST(LevelDbDocumentOverlayCollectionGroupIndexKeyTest, FromLevelDbDocumentOverlayKey) { LevelDbDocumentOverlayKey key("test_user", testutil::Key("coll/doc"), 123); const absl::optional<std::string> encoded_key = LevelDbDocumentOverlayCollectionGroupIndexKey::Key(key); ASSERT_TRUE(encoded_key.has_value()); LevelDbDocumentOverlayCollectionGroupIndexKey decoded_key; ASSERT_TRUE(decoded_key.Decode(encoded_key.value())); EXPECT_EQ(decoded_key.user_id(), "test_user"); EXPECT_EQ(decoded_key.collection_group(), "coll"); EXPECT_EQ(decoded_key.largest_batch_id(), 123); EXPECT_EQ(decoded_key.document_key(), testutil::Key("coll/doc")); } #undef AssertExpectedKeyDescription } // namespace local } // namespace firestore } // namespace firebase
41.324027
86
0.698352
liam-i
3ee7ff421e8863cd59a274ea5ea68232e8c96afd
40,702
cpp
C++
export/windows/cpp/obj/src/openfl/_legacy/events/Event.cpp
TinyPlanetStudios/Project-Crash-Land
365f196be4212602d32251566f26b53fb70693f6
[ "MIT" ]
null
null
null
export/windows/cpp/obj/src/openfl/_legacy/events/Event.cpp
TinyPlanetStudios/Project-Crash-Land
365f196be4212602d32251566f26b53fb70693f6
[ "MIT" ]
null
null
null
export/windows/cpp/obj/src/openfl/_legacy/events/Event.cpp
TinyPlanetStudios/Project-Crash-Land
365f196be4212602d32251566f26b53fb70693f6
[ "MIT" ]
null
null
null
// Generated by Haxe 3.3.0 #include <hxcpp.h> #ifndef INCLUDED_Reflect #include <Reflect.h> #endif #ifndef INCLUDED_Std #include <Std.h> #endif #ifndef INCLUDED_openfl__legacy_events_Event #include <openfl/_legacy/events/Event.h> #endif namespace openfl{ namespace _legacy{ namespace events{ void Event_obj::__construct(::String type,hx::Null< Bool > __o_bubbles,hx::Null< Bool > __o_cancelable){ Bool bubbles = __o_bubbles.Default(false); Bool cancelable = __o_cancelable.Default(false); HX_STACK_FRAME("openfl._legacy.events.Event","new",0xfb90e03b,"openfl._legacy.events.Event.new","openfl/_legacy/events/Event.hx",56,0xcca9b1d4) HX_STACK_THIS(this) HX_STACK_ARG(type,"type") HX_STACK_ARG(bubbles,"bubbles") HX_STACK_ARG(cancelable,"cancelable") HXLINE( 58) this->_hx___type = type; HXLINE( 59) this->_hx___bubbles = bubbles; HXLINE( 60) this->_hx___cancelable = cancelable; HXLINE( 61) this->_hx___isCancelled = false; HXLINE( 62) this->_hx___isCancelledNow = false; HXLINE( 63) this->_hx___target = null(); HXLINE( 64) this->_hx___currentTarget = null(); HXLINE( 65) this->_hx___eventPhase = (int)2; } Dynamic Event_obj::__CreateEmpty() { return new Event_obj; } hx::ObjectPtr< Event_obj > Event_obj::__new(::String type,hx::Null< Bool > __o_bubbles,hx::Null< Bool > __o_cancelable) { hx::ObjectPtr< Event_obj > _hx_result = new Event_obj(); _hx_result->__construct(type,__o_bubbles,__o_cancelable); return _hx_result; } Dynamic Event_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< Event_obj > _hx_result = new Event_obj(); _hx_result->__construct(inArgs[0],inArgs[1],inArgs[2]); return _hx_result; } ::openfl::_legacy::events::Event Event_obj::clone(){ HX_STACK_FRAME("openfl._legacy.events.Event","clone",0x58e80ff8,"openfl._legacy.events.Event.clone","openfl/_legacy/events/Event.hx",72,0xcca9b1d4) HX_STACK_THIS(this) HXLINE( 72) ::String _hx_tmp = this->get_type(); HXDLIN( 72) Bool _hx_tmp1 = this->get_bubbles(); HXDLIN( 72) Bool _hx_tmp2 = this->get_cancelable(); HXDLIN( 72) return ::openfl::_legacy::events::Event_obj::__new(_hx_tmp,_hx_tmp1,_hx_tmp2); } HX_DEFINE_DYNAMIC_FUNC0(Event_obj,clone,return ) Bool Event_obj::isDefaultPrevented(){ HX_STACK_FRAME("openfl._legacy.events.Event","isDefaultPrevented",0x6e262ec5,"openfl._legacy.events.Event.isDefaultPrevented","openfl/_legacy/events/Event.hx",79,0xcca9b1d4) HX_STACK_THIS(this) HXLINE( 79) if (!(this->_hx___isCancelled)) { HXLINE( 79) return this->_hx___isCancelledNow; } else { HXLINE( 79) return true; } HXDLIN( 79) return false; } HX_DEFINE_DYNAMIC_FUNC0(Event_obj,isDefaultPrevented,return ) void Event_obj::stopImmediatePropagation(){ HX_STACK_FRAME("openfl._legacy.events.Event","stopImmediatePropagation",0x3e5eefc2,"openfl._legacy.events.Event.stopImmediatePropagation","openfl/_legacy/events/Event.hx",86,0xcca9b1d4) HX_STACK_THIS(this) HXLINE( 86) Bool _hx_tmp = this->get_cancelable(); HXDLIN( 86) if (_hx_tmp) { HXLINE( 88) this->_hx___isCancelled = true; HXLINE( 89) this->_hx___isCancelledNow = true; } } HX_DEFINE_DYNAMIC_FUNC0(Event_obj,stopImmediatePropagation,(void)) void Event_obj::stopPropagation(){ HX_STACK_FRAME("openfl._legacy.events.Event","stopPropagation",0xf6346e45,"openfl._legacy.events.Event.stopPropagation","openfl/_legacy/events/Event.hx",98,0xcca9b1d4) HX_STACK_THIS(this) HXLINE( 98) Bool _hx_tmp = this->get_cancelable(); HXDLIN( 98) if (_hx_tmp) { HXLINE( 100) this->_hx___isCancelled = true; } } HX_DEFINE_DYNAMIC_FUNC0(Event_obj,stopPropagation,(void)) ::String Event_obj::toString(){ HX_STACK_FRAME("openfl._legacy.events.Event","toString",0x4aa366f1,"openfl._legacy.events.Event.toString","openfl/_legacy/events/Event.hx",109,0xcca9b1d4) HX_STACK_THIS(this) HXLINE( 109) ::String _hx_tmp = this->get_type(); HXDLIN( 109) ::String _hx_tmp1 = ((HX_("[Event type=",22,63,2e,48) + _hx_tmp) + HX_(" bubbles=",16,5f,ba,28)); HXDLIN( 109) Bool _hx_tmp2 = this->get_bubbles(); HXDLIN( 109) ::String _hx_tmp3 = ::Std_obj::string(_hx_tmp2); HXDLIN( 109) ::String _hx_tmp4 = ((_hx_tmp1 + _hx_tmp3) + HX_(" cancelable=",89,25,e0,5d)); HXDLIN( 109) Bool _hx_tmp5 = this->get_cancelable(); HXDLIN( 109) ::String _hx_tmp6 = ::Std_obj::string(_hx_tmp5); HXDLIN( 109) return ((_hx_tmp4 + _hx_tmp6) + HX_("]",5d,00,00,00)); } HX_DEFINE_DYNAMIC_FUNC0(Event_obj,toString,return ) ::String Event_obj::_hx___formatToString(::String className,::Array< ::String > parameters){ HX_STACK_FRAME("openfl._legacy.events.Event","__formatToString",0x623f1968,"openfl._legacy.events.Event.__formatToString","openfl/_legacy/events/Event.hx",114,0xcca9b1d4) HX_STACK_THIS(this) HX_STACK_ARG(className,"className") HX_STACK_ARG(parameters,"parameters") HXLINE( 118) HX_VARI( ::String,output) = (HX_("[",5b,00,00,00) + className); HXLINE( 119) HX_VARI( ::Dynamic,arg) = null(); HXLINE( 121) { HXLINE( 121) HX_VARI( Int,_g) = (int)0; HXDLIN( 121) while((_g < parameters->length)){ HXLINE( 121) HX_VARI( ::String,param) = parameters->__get(_g); HXDLIN( 121) ++_g; HXLINE( 123) arg = ::Reflect_obj::field(hx::ObjectPtr<OBJ_>(this),param); HXLINE( 125) Bool _hx_tmp = ::Std_obj::is(arg,hx::ClassOf< ::String >()); HXDLIN( 125) if (_hx_tmp) { HXLINE( 127) ::String _hx_tmp1 = ((HX_(" ",20,00,00,00) + param) + HX_("=\"",45,35,00,00)); HXDLIN( 127) ::String _hx_tmp2 = ::Std_obj::string(arg); HXDLIN( 127) hx::AddEq(output,((_hx_tmp1 + _hx_tmp2) + HX_("\"",22,00,00,00))); } else { HXLINE( 131) ::String _hx_tmp3 = ((HX_(" ",20,00,00,00) + param) + HX_("=",3d,00,00,00)); HXDLIN( 131) ::String _hx_tmp4 = ::Std_obj::string(arg); HXDLIN( 131) hx::AddEq(output,(_hx_tmp3 + _hx_tmp4)); } } } HXLINE( 137) hx::AddEq(output,HX_("]",5d,00,00,00)); HXLINE( 138) return output; } HX_DEFINE_DYNAMIC_FUNC2(Event_obj,_hx___formatToString,return ) Bool Event_obj::_hx___getIsCancelled(){ HX_STACK_FRAME("openfl._legacy.events.Event","__getIsCancelled",0x715efeb6,"openfl._legacy.events.Event.__getIsCancelled","openfl/_legacy/events/Event.hx",145,0xcca9b1d4) HX_STACK_THIS(this) HXLINE( 145) return this->_hx___isCancelled; } HX_DEFINE_DYNAMIC_FUNC0(Event_obj,_hx___getIsCancelled,return ) Bool Event_obj::_hx___getIsCancelledNow(){ HX_STACK_FRAME("openfl._legacy.events.Event","__getIsCancelledNow",0x9a1c2800,"openfl._legacy.events.Event.__getIsCancelledNow","openfl/_legacy/events/Event.hx",152,0xcca9b1d4) HX_STACK_THIS(this) HXLINE( 152) return this->_hx___isCancelledNow; } HX_DEFINE_DYNAMIC_FUNC0(Event_obj,_hx___getIsCancelledNow,return ) void Event_obj::_hx___setPhase(Int value){ HX_STACK_FRAME("openfl._legacy.events.Event","__setPhase",0xec9075de,"openfl._legacy.events.Event.__setPhase","openfl/_legacy/events/Event.hx",159,0xcca9b1d4) HX_STACK_THIS(this) HX_STACK_ARG(value,"value") HXLINE( 159) this->_hx___eventPhase = value; } HX_DEFINE_DYNAMIC_FUNC1(Event_obj,_hx___setPhase,(void)) Bool Event_obj::get_bubbles(){ HX_STACK_FRAME("openfl._legacy.events.Event","get_bubbles",0x8139fe59,"openfl._legacy.events.Event.get_bubbles","openfl/_legacy/events/Event.hx",171,0xcca9b1d4) HX_STACK_THIS(this) HXLINE( 171) return this->_hx___bubbles; } HX_DEFINE_DYNAMIC_FUNC0(Event_obj,get_bubbles,return ) Bool Event_obj::get_cancelable(){ HX_STACK_FRAME("openfl._legacy.events.Event","get_cancelable",0xb4814062,"openfl._legacy.events.Event.get_cancelable","openfl/_legacy/events/Event.hx",172,0xcca9b1d4) HX_STACK_THIS(this) HXLINE( 172) return this->_hx___cancelable; } HX_DEFINE_DYNAMIC_FUNC0(Event_obj,get_cancelable,return ) ::Dynamic Event_obj::get_currentTarget(){ HX_STACK_FRAME("openfl._legacy.events.Event","get_currentTarget",0xee5478dc,"openfl._legacy.events.Event.get_currentTarget","openfl/_legacy/events/Event.hx",173,0xcca9b1d4) HX_STACK_THIS(this) HXLINE( 173) return this->_hx___currentTarget; } HX_DEFINE_DYNAMIC_FUNC0(Event_obj,get_currentTarget,return ) ::Dynamic Event_obj::set_currentTarget( ::Dynamic value){ HX_STACK_FRAME("openfl._legacy.events.Event","set_currentTarget",0x11c250e8,"openfl._legacy.events.Event.set_currentTarget","openfl/_legacy/events/Event.hx",174,0xcca9b1d4) HX_STACK_THIS(this) HX_STACK_ARG(value,"value") HXLINE( 174) return (this->_hx___currentTarget = value); } HX_DEFINE_DYNAMIC_FUNC1(Event_obj,set_currentTarget,return ) Int Event_obj::get_eventPhase(){ HX_STACK_FRAME("openfl._legacy.events.Event","get_eventPhase",0x2e4bd20f,"openfl._legacy.events.Event.get_eventPhase","openfl/_legacy/events/Event.hx",175,0xcca9b1d4) HX_STACK_THIS(this) HXLINE( 175) return this->_hx___eventPhase; } HX_DEFINE_DYNAMIC_FUNC0(Event_obj,get_eventPhase,return ) ::Dynamic Event_obj::get_target(){ HX_STACK_FRAME("openfl._legacy.events.Event","get_target",0xf0aed49f,"openfl._legacy.events.Event.get_target","openfl/_legacy/events/Event.hx",176,0xcca9b1d4) HX_STACK_THIS(this) HXLINE( 176) return this->_hx___target; } HX_DEFINE_DYNAMIC_FUNC0(Event_obj,get_target,return ) ::Dynamic Event_obj::set_target( ::Dynamic value){ HX_STACK_FRAME("openfl._legacy.events.Event","set_target",0xf42c7313,"openfl._legacy.events.Event.set_target","openfl/_legacy/events/Event.hx",177,0xcca9b1d4) HX_STACK_THIS(this) HX_STACK_ARG(value,"value") HXLINE( 177) return (this->_hx___target = value); } HX_DEFINE_DYNAMIC_FUNC1(Event_obj,set_target,return ) ::String Event_obj::get_type(){ HX_STACK_FRAME("openfl._legacy.events.Event","get_type",0xdef84488,"openfl._legacy.events.Event.get_type","openfl/_legacy/events/Event.hx",178,0xcca9b1d4) HX_STACK_THIS(this) HXLINE( 178) return this->_hx___type; } HX_DEFINE_DYNAMIC_FUNC0(Event_obj,get_type,return ) ::String Event_obj::ACTIVATE; ::String Event_obj::ADDED; ::String Event_obj::ADDED_TO_STAGE; ::String Event_obj::CANCEL; ::String Event_obj::CHANGE; ::String Event_obj::CLOSE; ::String Event_obj::COMPLETE; ::String Event_obj::CONNECT; ::String Event_obj::CONTEXT3D_CREATE; ::String Event_obj::DEACTIVATE; ::String Event_obj::ENTER_FRAME; ::String Event_obj::ID3; ::String Event_obj::INIT; ::String Event_obj::MOUSE_LEAVE; ::String Event_obj::OPEN; ::String Event_obj::REMOVED; ::String Event_obj::REMOVED_FROM_STAGE; ::String Event_obj::RENDER; ::String Event_obj::RESIZE; ::String Event_obj::SCROLL; ::String Event_obj::SELECT; ::String Event_obj::SOUND_COMPLETE; ::String Event_obj::TAB_CHILDREN_CHANGE; ::String Event_obj::TAB_ENABLED_CHANGE; ::String Event_obj::TAB_INDEX_CHANGE; ::String Event_obj::UNLOAD; Event_obj::Event_obj() { } void Event_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(Event); HX_MARK_MEMBER_NAME(_hx___bubbles,"__bubbles"); HX_MARK_MEMBER_NAME(_hx___cancelable,"__cancelable"); HX_MARK_MEMBER_NAME(_hx___currentTarget,"__currentTarget"); HX_MARK_MEMBER_NAME(_hx___eventPhase,"__eventPhase"); HX_MARK_MEMBER_NAME(_hx___isCancelled,"__isCancelled"); HX_MARK_MEMBER_NAME(_hx___isCancelledNow,"__isCancelledNow"); HX_MARK_MEMBER_NAME(_hx___target,"__target"); HX_MARK_MEMBER_NAME(_hx___type,"__type"); HX_MARK_END_CLASS(); } void Event_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(_hx___bubbles,"__bubbles"); HX_VISIT_MEMBER_NAME(_hx___cancelable,"__cancelable"); HX_VISIT_MEMBER_NAME(_hx___currentTarget,"__currentTarget"); HX_VISIT_MEMBER_NAME(_hx___eventPhase,"__eventPhase"); HX_VISIT_MEMBER_NAME(_hx___isCancelled,"__isCancelled"); HX_VISIT_MEMBER_NAME(_hx___isCancelledNow,"__isCancelledNow"); HX_VISIT_MEMBER_NAME(_hx___target,"__target"); HX_VISIT_MEMBER_NAME(_hx___type,"__type"); } hx::Val Event_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 4: if (HX_FIELD_EQ(inName,"type") ) { if (inCallProp == hx::paccAlways) return hx::Val(get_type()); } break; case 5: if (HX_FIELD_EQ(inName,"clone") ) { return hx::Val( clone_dyn()); } break; case 6: if (HX_FIELD_EQ(inName,"target") ) { if (inCallProp == hx::paccAlways) return hx::Val(get_target()); } if (HX_FIELD_EQ(inName,"__type") ) { return hx::Val( _hx___type); } break; case 7: if (HX_FIELD_EQ(inName,"bubbles") ) { if (inCallProp == hx::paccAlways) return hx::Val(get_bubbles()); } break; case 8: if (HX_FIELD_EQ(inName,"__target") ) { return hx::Val( _hx___target); } if (HX_FIELD_EQ(inName,"toString") ) { return hx::Val( toString_dyn()); } if (HX_FIELD_EQ(inName,"get_type") ) { return hx::Val( get_type_dyn()); } break; case 9: if (HX_FIELD_EQ(inName,"__bubbles") ) { return hx::Val( _hx___bubbles); } break; case 10: if (HX_FIELD_EQ(inName,"cancelable") ) { if (inCallProp == hx::paccAlways) return hx::Val(get_cancelable()); } if (HX_FIELD_EQ(inName,"eventPhase") ) { if (inCallProp == hx::paccAlways) return hx::Val(get_eventPhase()); } if (HX_FIELD_EQ(inName,"__setPhase") ) { return hx::Val( _hx___setPhase_dyn()); } if (HX_FIELD_EQ(inName,"get_target") ) { return hx::Val( get_target_dyn()); } if (HX_FIELD_EQ(inName,"set_target") ) { return hx::Val( set_target_dyn()); } break; case 11: if (HX_FIELD_EQ(inName,"get_bubbles") ) { return hx::Val( get_bubbles_dyn()); } break; case 12: if (HX_FIELD_EQ(inName,"__cancelable") ) { return hx::Val( _hx___cancelable); } if (HX_FIELD_EQ(inName,"__eventPhase") ) { return hx::Val( _hx___eventPhase); } break; case 13: if (HX_FIELD_EQ(inName,"currentTarget") ) { if (inCallProp == hx::paccAlways) return hx::Val(get_currentTarget()); } if (HX_FIELD_EQ(inName,"__isCancelled") ) { return hx::Val( _hx___isCancelled); } break; case 14: if (HX_FIELD_EQ(inName,"get_cancelable") ) { return hx::Val( get_cancelable_dyn()); } if (HX_FIELD_EQ(inName,"get_eventPhase") ) { return hx::Val( get_eventPhase_dyn()); } break; case 15: if (HX_FIELD_EQ(inName,"__currentTarget") ) { return hx::Val( _hx___currentTarget); } if (HX_FIELD_EQ(inName,"stopPropagation") ) { return hx::Val( stopPropagation_dyn()); } break; case 16: if (HX_FIELD_EQ(inName,"__isCancelledNow") ) { return hx::Val( _hx___isCancelledNow); } if (HX_FIELD_EQ(inName,"__formatToString") ) { return hx::Val( _hx___formatToString_dyn()); } if (HX_FIELD_EQ(inName,"__getIsCancelled") ) { return hx::Val( _hx___getIsCancelled_dyn()); } break; case 17: if (HX_FIELD_EQ(inName,"get_currentTarget") ) { return hx::Val( get_currentTarget_dyn()); } if (HX_FIELD_EQ(inName,"set_currentTarget") ) { return hx::Val( set_currentTarget_dyn()); } break; case 18: if (HX_FIELD_EQ(inName,"isDefaultPrevented") ) { return hx::Val( isDefaultPrevented_dyn()); } break; case 19: if (HX_FIELD_EQ(inName,"__getIsCancelledNow") ) { return hx::Val( _hx___getIsCancelledNow_dyn()); } break; case 24: if (HX_FIELD_EQ(inName,"stopImmediatePropagation") ) { return hx::Val( stopImmediatePropagation_dyn()); } } return super::__Field(inName,inCallProp); } bool Event_obj::__GetStatic(const ::String &inName, Dynamic &outValue, hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"ID3") ) { outValue = ID3; return true; } break; case 4: if (HX_FIELD_EQ(inName,"INIT") ) { outValue = INIT; return true; } if (HX_FIELD_EQ(inName,"OPEN") ) { outValue = OPEN; return true; } break; case 5: if (HX_FIELD_EQ(inName,"ADDED") ) { outValue = ADDED; return true; } if (HX_FIELD_EQ(inName,"CLOSE") ) { outValue = CLOSE; return true; } break; case 6: if (HX_FIELD_EQ(inName,"CANCEL") ) { outValue = CANCEL; return true; } if (HX_FIELD_EQ(inName,"CHANGE") ) { outValue = CHANGE; return true; } if (HX_FIELD_EQ(inName,"RENDER") ) { outValue = RENDER; return true; } if (HX_FIELD_EQ(inName,"RESIZE") ) { outValue = RESIZE; return true; } if (HX_FIELD_EQ(inName,"SCROLL") ) { outValue = SCROLL; return true; } if (HX_FIELD_EQ(inName,"SELECT") ) { outValue = SELECT; return true; } if (HX_FIELD_EQ(inName,"UNLOAD") ) { outValue = UNLOAD; return true; } break; case 7: if (HX_FIELD_EQ(inName,"CONNECT") ) { outValue = CONNECT; return true; } if (HX_FIELD_EQ(inName,"REMOVED") ) { outValue = REMOVED; return true; } break; case 8: if (HX_FIELD_EQ(inName,"ACTIVATE") ) { outValue = ACTIVATE; return true; } if (HX_FIELD_EQ(inName,"COMPLETE") ) { outValue = COMPLETE; return true; } break; case 10: if (HX_FIELD_EQ(inName,"DEACTIVATE") ) { outValue = DEACTIVATE; return true; } break; case 11: if (HX_FIELD_EQ(inName,"ENTER_FRAME") ) { outValue = ENTER_FRAME; return true; } if (HX_FIELD_EQ(inName,"MOUSE_LEAVE") ) { outValue = MOUSE_LEAVE; return true; } break; case 14: if (HX_FIELD_EQ(inName,"ADDED_TO_STAGE") ) { outValue = ADDED_TO_STAGE; return true; } if (HX_FIELD_EQ(inName,"SOUND_COMPLETE") ) { outValue = SOUND_COMPLETE; return true; } break; case 16: if (HX_FIELD_EQ(inName,"CONTEXT3D_CREATE") ) { outValue = CONTEXT3D_CREATE; return true; } if (HX_FIELD_EQ(inName,"TAB_INDEX_CHANGE") ) { outValue = TAB_INDEX_CHANGE; return true; } break; case 18: if (HX_FIELD_EQ(inName,"REMOVED_FROM_STAGE") ) { outValue = REMOVED_FROM_STAGE; return true; } if (HX_FIELD_EQ(inName,"TAB_ENABLED_CHANGE") ) { outValue = TAB_ENABLED_CHANGE; return true; } break; case 19: if (HX_FIELD_EQ(inName,"TAB_CHILDREN_CHANGE") ) { outValue = TAB_CHILDREN_CHANGE; return true; } } return false; } hx::Val Event_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 6: if (HX_FIELD_EQ(inName,"target") ) { if (inCallProp == hx::paccAlways) return hx::Val( set_target(inValue) ); } if (HX_FIELD_EQ(inName,"__type") ) { _hx___type=inValue.Cast< ::String >(); return inValue; } break; case 8: if (HX_FIELD_EQ(inName,"__target") ) { _hx___target=inValue.Cast< ::Dynamic >(); return inValue; } break; case 9: if (HX_FIELD_EQ(inName,"__bubbles") ) { _hx___bubbles=inValue.Cast< Bool >(); return inValue; } break; case 12: if (HX_FIELD_EQ(inName,"__cancelable") ) { _hx___cancelable=inValue.Cast< Bool >(); return inValue; } if (HX_FIELD_EQ(inName,"__eventPhase") ) { _hx___eventPhase=inValue.Cast< Int >(); return inValue; } break; case 13: if (HX_FIELD_EQ(inName,"currentTarget") ) { if (inCallProp == hx::paccAlways) return hx::Val( set_currentTarget(inValue) ); } if (HX_FIELD_EQ(inName,"__isCancelled") ) { _hx___isCancelled=inValue.Cast< Bool >(); return inValue; } break; case 15: if (HX_FIELD_EQ(inName,"__currentTarget") ) { _hx___currentTarget=inValue.Cast< ::Dynamic >(); return inValue; } break; case 16: if (HX_FIELD_EQ(inName,"__isCancelledNow") ) { _hx___isCancelledNow=inValue.Cast< Bool >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } bool Event_obj::__SetStatic(const ::String &inName,Dynamic &ioValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"ID3") ) { ID3=ioValue.Cast< ::String >(); return true; } break; case 4: if (HX_FIELD_EQ(inName,"INIT") ) { INIT=ioValue.Cast< ::String >(); return true; } if (HX_FIELD_EQ(inName,"OPEN") ) { OPEN=ioValue.Cast< ::String >(); return true; } break; case 5: if (HX_FIELD_EQ(inName,"ADDED") ) { ADDED=ioValue.Cast< ::String >(); return true; } if (HX_FIELD_EQ(inName,"CLOSE") ) { CLOSE=ioValue.Cast< ::String >(); return true; } break; case 6: if (HX_FIELD_EQ(inName,"CANCEL") ) { CANCEL=ioValue.Cast< ::String >(); return true; } if (HX_FIELD_EQ(inName,"CHANGE") ) { CHANGE=ioValue.Cast< ::String >(); return true; } if (HX_FIELD_EQ(inName,"RENDER") ) { RENDER=ioValue.Cast< ::String >(); return true; } if (HX_FIELD_EQ(inName,"RESIZE") ) { RESIZE=ioValue.Cast< ::String >(); return true; } if (HX_FIELD_EQ(inName,"SCROLL") ) { SCROLL=ioValue.Cast< ::String >(); return true; } if (HX_FIELD_EQ(inName,"SELECT") ) { SELECT=ioValue.Cast< ::String >(); return true; } if (HX_FIELD_EQ(inName,"UNLOAD") ) { UNLOAD=ioValue.Cast< ::String >(); return true; } break; case 7: if (HX_FIELD_EQ(inName,"CONNECT") ) { CONNECT=ioValue.Cast< ::String >(); return true; } if (HX_FIELD_EQ(inName,"REMOVED") ) { REMOVED=ioValue.Cast< ::String >(); return true; } break; case 8: if (HX_FIELD_EQ(inName,"ACTIVATE") ) { ACTIVATE=ioValue.Cast< ::String >(); return true; } if (HX_FIELD_EQ(inName,"COMPLETE") ) { COMPLETE=ioValue.Cast< ::String >(); return true; } break; case 10: if (HX_FIELD_EQ(inName,"DEACTIVATE") ) { DEACTIVATE=ioValue.Cast< ::String >(); return true; } break; case 11: if (HX_FIELD_EQ(inName,"ENTER_FRAME") ) { ENTER_FRAME=ioValue.Cast< ::String >(); return true; } if (HX_FIELD_EQ(inName,"MOUSE_LEAVE") ) { MOUSE_LEAVE=ioValue.Cast< ::String >(); return true; } break; case 14: if (HX_FIELD_EQ(inName,"ADDED_TO_STAGE") ) { ADDED_TO_STAGE=ioValue.Cast< ::String >(); return true; } if (HX_FIELD_EQ(inName,"SOUND_COMPLETE") ) { SOUND_COMPLETE=ioValue.Cast< ::String >(); return true; } break; case 16: if (HX_FIELD_EQ(inName,"CONTEXT3D_CREATE") ) { CONTEXT3D_CREATE=ioValue.Cast< ::String >(); return true; } if (HX_FIELD_EQ(inName,"TAB_INDEX_CHANGE") ) { TAB_INDEX_CHANGE=ioValue.Cast< ::String >(); return true; } break; case 18: if (HX_FIELD_EQ(inName,"REMOVED_FROM_STAGE") ) { REMOVED_FROM_STAGE=ioValue.Cast< ::String >(); return true; } if (HX_FIELD_EQ(inName,"TAB_ENABLED_CHANGE") ) { TAB_ENABLED_CHANGE=ioValue.Cast< ::String >(); return true; } break; case 19: if (HX_FIELD_EQ(inName,"TAB_CHILDREN_CHANGE") ) { TAB_CHILDREN_CHANGE=ioValue.Cast< ::String >(); return true; } } return false; } void Event_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_HCSTRING("bubbles","\x67","\xbb","\x56","\x61")); outFields->push(HX_HCSTRING("cancelable","\x14","\xa0","\x79","\xc4")); outFields->push(HX_HCSTRING("currentTarget","\x6a","\x74","\x49","\x6a")); outFields->push(HX_HCSTRING("eventPhase","\xc1","\x31","\x44","\x3e")); outFields->push(HX_HCSTRING("target","\x51","\xf3","\xec","\x86")); outFields->push(HX_HCSTRING("type","\xba","\xf2","\x08","\x4d")); outFields->push(HX_HCSTRING("__bubbles","\x47","\x0c","\xa5","\xe2")); outFields->push(HX_HCSTRING("__cancelable","\x34","\x1b","\x0d","\xfd")); outFields->push(HX_HCSTRING("__currentTarget","\x4a","\xad","\xfb","\xf1")); outFields->push(HX_HCSTRING("__eventPhase","\xe1","\xac","\xd7","\x76")); outFields->push(HX_HCSTRING("__isCancelled","\x27","\x7e","\x2d","\x49")); outFields->push(HX_HCSTRING("__isCancelledNow","\x2f","\x25","\xd8","\x53")); outFields->push(HX_HCSTRING("__target","\x71","\x5e","\x1c","\x2f")); outFields->push(HX_HCSTRING("__type","\xda","\x55","\x01","\xfc")); super::__GetFields(outFields); }; #if HXCPP_SCRIPTABLE static hx::StorageInfo Event_obj_sMemberStorageInfo[] = { {hx::fsBool,(int)offsetof(Event_obj,_hx___bubbles),HX_HCSTRING("__bubbles","\x47","\x0c","\xa5","\xe2")}, {hx::fsBool,(int)offsetof(Event_obj,_hx___cancelable),HX_HCSTRING("__cancelable","\x34","\x1b","\x0d","\xfd")}, {hx::fsObject /*Dynamic*/ ,(int)offsetof(Event_obj,_hx___currentTarget),HX_HCSTRING("__currentTarget","\x4a","\xad","\xfb","\xf1")}, {hx::fsInt,(int)offsetof(Event_obj,_hx___eventPhase),HX_HCSTRING("__eventPhase","\xe1","\xac","\xd7","\x76")}, {hx::fsBool,(int)offsetof(Event_obj,_hx___isCancelled),HX_HCSTRING("__isCancelled","\x27","\x7e","\x2d","\x49")}, {hx::fsBool,(int)offsetof(Event_obj,_hx___isCancelledNow),HX_HCSTRING("__isCancelledNow","\x2f","\x25","\xd8","\x53")}, {hx::fsObject /*Dynamic*/ ,(int)offsetof(Event_obj,_hx___target),HX_HCSTRING("__target","\x71","\x5e","\x1c","\x2f")}, {hx::fsString,(int)offsetof(Event_obj,_hx___type),HX_HCSTRING("__type","\xda","\x55","\x01","\xfc")}, { hx::fsUnknown, 0, null()} }; static hx::StaticInfo Event_obj_sStaticStorageInfo[] = { {hx::fsString,(void *) &Event_obj::ACTIVATE,HX_HCSTRING("ACTIVATE","\xb3","\xab","\x31","\x3f")}, {hx::fsString,(void *) &Event_obj::ADDED,HX_HCSTRING("ADDED","\xa0","\x0c","\x32","\x9a")}, {hx::fsString,(void *) &Event_obj::ADDED_TO_STAGE,HX_HCSTRING("ADDED_TO_STAGE","\x59","\x58","\xdb","\x1a")}, {hx::fsString,(void *) &Event_obj::CANCEL,HX_HCSTRING("CANCEL","\x7a","\x99","\xb6","\x6a")}, {hx::fsString,(void *) &Event_obj::CHANGE,HX_HCSTRING("CHANGE","\x70","\x3d","\xf5","\x69")}, {hx::fsString,(void *) &Event_obj::CLOSE,HX_HCSTRING("CLOSE","\x98","\x4f","\x51","\xc6")}, {hx::fsString,(void *) &Event_obj::COMPLETE,HX_HCSTRING("COMPLETE","\xb9","\x90","\x4d","\xd9")}, {hx::fsString,(void *) &Event_obj::CONNECT,HX_HCSTRING("CONNECT","\xca","\x0f","\x54","\x95")}, {hx::fsString,(void *) &Event_obj::CONTEXT3D_CREATE,HX_HCSTRING("CONTEXT3D_CREATE","\x5b","\xc4","\x3d","\x41")}, {hx::fsString,(void *) &Event_obj::DEACTIVATE,HX_HCSTRING("DEACTIVATE","\x34","\xd0","\x0a","\x2e")}, {hx::fsString,(void *) &Event_obj::ENTER_FRAME,HX_HCSTRING("ENTER_FRAME","\x46","\xa6","\xab","\xc6")}, {hx::fsString,(void *) &Event_obj::ID3,HX_HCSTRING("ID3","\xf8","\x9f","\x37","\x00")}, {hx::fsString,(void *) &Event_obj::INIT,HX_HCSTRING("INIT","\x10","\x03","\x7c","\x30")}, {hx::fsString,(void *) &Event_obj::MOUSE_LEAVE,HX_HCSTRING("MOUSE_LEAVE","\xdd","\xd3","\xd5","\xd0")}, {hx::fsString,(void *) &Event_obj::OPEN,HX_HCSTRING("OPEN","\xca","\xcb","\x74","\x34")}, {hx::fsString,(void *) &Event_obj::REMOVED,HX_HCSTRING("REMOVED","\x80","\xf3","\xd3","\x72")}, {hx::fsString,(void *) &Event_obj::REMOVED_FROM_STAGE,HX_HCSTRING("REMOVED_FROM_STAGE","\x68","\xcc","\x72","\xdb")}, {hx::fsString,(void *) &Event_obj::RENDER,HX_HCSTRING("RENDER","\x56","\x17","\xac","\xb7")}, {hx::fsString,(void *) &Event_obj::RESIZE,HX_HCSTRING("RESIZE","\xf4","\x05","\xfe","\xba")}, {hx::fsString,(void *) &Event_obj::SCROLL,HX_HCSTRING("SCROLL","\x0d","\x84","\xe7","\xf9")}, {hx::fsString,(void *) &Event_obj::SELECT,HX_HCSTRING("SELECT","\xfc","\xc6","\xb5","\x1c")}, {hx::fsString,(void *) &Event_obj::SOUND_COMPLETE,HX_HCSTRING("SOUND_COMPLETE","\x89","\x35","\x98","\xf1")}, {hx::fsString,(void *) &Event_obj::TAB_CHILDREN_CHANGE,HX_HCSTRING("TAB_CHILDREN_CHANGE","\x66","\x8e","\x83","\x1c")}, {hx::fsString,(void *) &Event_obj::TAB_ENABLED_CHANGE,HX_HCSTRING("TAB_ENABLED_CHANGE","\xd8","\x4a","\xcd","\x8b")}, {hx::fsString,(void *) &Event_obj::TAB_INDEX_CHANGE,HX_HCSTRING("TAB_INDEX_CHANGE","\xe7","\xbd","\xc6","\xb6")}, {hx::fsString,(void *) &Event_obj::UNLOAD,HX_HCSTRING("UNLOAD","\xff","\x4c","\x0f","\x18")}, { hx::fsUnknown, 0, null()} }; #endif static ::String Event_obj_sMemberFields[] = { HX_HCSTRING("__bubbles","\x47","\x0c","\xa5","\xe2"), HX_HCSTRING("__cancelable","\x34","\x1b","\x0d","\xfd"), HX_HCSTRING("__currentTarget","\x4a","\xad","\xfb","\xf1"), HX_HCSTRING("__eventPhase","\xe1","\xac","\xd7","\x76"), HX_HCSTRING("__isCancelled","\x27","\x7e","\x2d","\x49"), HX_HCSTRING("__isCancelledNow","\x2f","\x25","\xd8","\x53"), HX_HCSTRING("__target","\x71","\x5e","\x1c","\x2f"), HX_HCSTRING("__type","\xda","\x55","\x01","\xfc"), HX_HCSTRING("clone","\x5d","\x13","\x63","\x48"), HX_HCSTRING("isDefaultPrevented","\x40","\x30","\x27","\x04"), HX_HCSTRING("stopImmediatePropagation","\x7d","\xbf","\x66","\x5b"), HX_HCSTRING("stopPropagation","\xea","\x81","\x71","\xa0"), HX_HCSTRING("toString","\xac","\xd0","\x6e","\x38"), HX_HCSTRING("__formatToString","\x23","\x36","\x73","\xad"), HX_HCSTRING("__getIsCancelled","\x71","\x1b","\x93","\xbc"), HX_HCSTRING("__getIsCancelledNow","\x25","\x72","\xfc","\x44"), HX_HCSTRING("__setPhase","\x59","\x04","\x56","\x73"), HX_HCSTRING("get_bubbles","\x7e","\x1b","\x51","\xe7"), HX_HCSTRING("get_cancelable","\x5d","\x28","\x6f","\x3a"), HX_HCSTRING("get_currentTarget","\xc1","\x7f","\xb9","\x70"), HX_HCSTRING("set_currentTarget","\xcd","\x57","\x27","\x94"), HX_HCSTRING("get_eventPhase","\x0a","\xba","\x39","\xb4"), HX_HCSTRING("get_target","\x1a","\x63","\x74","\x77"), HX_HCSTRING("set_target","\x8e","\x01","\xf2","\x7a"), HX_HCSTRING("get_type","\x43","\xae","\xc3","\xcc"), ::String(null()) }; static void Event_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(Event_obj::__mClass,"__mClass"); HX_MARK_MEMBER_NAME(Event_obj::ACTIVATE,"ACTIVATE"); HX_MARK_MEMBER_NAME(Event_obj::ADDED,"ADDED"); HX_MARK_MEMBER_NAME(Event_obj::ADDED_TO_STAGE,"ADDED_TO_STAGE"); HX_MARK_MEMBER_NAME(Event_obj::CANCEL,"CANCEL"); HX_MARK_MEMBER_NAME(Event_obj::CHANGE,"CHANGE"); HX_MARK_MEMBER_NAME(Event_obj::CLOSE,"CLOSE"); HX_MARK_MEMBER_NAME(Event_obj::COMPLETE,"COMPLETE"); HX_MARK_MEMBER_NAME(Event_obj::CONNECT,"CONNECT"); HX_MARK_MEMBER_NAME(Event_obj::CONTEXT3D_CREATE,"CONTEXT3D_CREATE"); HX_MARK_MEMBER_NAME(Event_obj::DEACTIVATE,"DEACTIVATE"); HX_MARK_MEMBER_NAME(Event_obj::ENTER_FRAME,"ENTER_FRAME"); HX_MARK_MEMBER_NAME(Event_obj::ID3,"ID3"); HX_MARK_MEMBER_NAME(Event_obj::INIT,"INIT"); HX_MARK_MEMBER_NAME(Event_obj::MOUSE_LEAVE,"MOUSE_LEAVE"); HX_MARK_MEMBER_NAME(Event_obj::OPEN,"OPEN"); HX_MARK_MEMBER_NAME(Event_obj::REMOVED,"REMOVED"); HX_MARK_MEMBER_NAME(Event_obj::REMOVED_FROM_STAGE,"REMOVED_FROM_STAGE"); HX_MARK_MEMBER_NAME(Event_obj::RENDER,"RENDER"); HX_MARK_MEMBER_NAME(Event_obj::RESIZE,"RESIZE"); HX_MARK_MEMBER_NAME(Event_obj::SCROLL,"SCROLL"); HX_MARK_MEMBER_NAME(Event_obj::SELECT,"SELECT"); HX_MARK_MEMBER_NAME(Event_obj::SOUND_COMPLETE,"SOUND_COMPLETE"); HX_MARK_MEMBER_NAME(Event_obj::TAB_CHILDREN_CHANGE,"TAB_CHILDREN_CHANGE"); HX_MARK_MEMBER_NAME(Event_obj::TAB_ENABLED_CHANGE,"TAB_ENABLED_CHANGE"); HX_MARK_MEMBER_NAME(Event_obj::TAB_INDEX_CHANGE,"TAB_INDEX_CHANGE"); HX_MARK_MEMBER_NAME(Event_obj::UNLOAD,"UNLOAD"); }; #ifdef HXCPP_VISIT_ALLOCS static void Event_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(Event_obj::__mClass,"__mClass"); HX_VISIT_MEMBER_NAME(Event_obj::ACTIVATE,"ACTIVATE"); HX_VISIT_MEMBER_NAME(Event_obj::ADDED,"ADDED"); HX_VISIT_MEMBER_NAME(Event_obj::ADDED_TO_STAGE,"ADDED_TO_STAGE"); HX_VISIT_MEMBER_NAME(Event_obj::CANCEL,"CANCEL"); HX_VISIT_MEMBER_NAME(Event_obj::CHANGE,"CHANGE"); HX_VISIT_MEMBER_NAME(Event_obj::CLOSE,"CLOSE"); HX_VISIT_MEMBER_NAME(Event_obj::COMPLETE,"COMPLETE"); HX_VISIT_MEMBER_NAME(Event_obj::CONNECT,"CONNECT"); HX_VISIT_MEMBER_NAME(Event_obj::CONTEXT3D_CREATE,"CONTEXT3D_CREATE"); HX_VISIT_MEMBER_NAME(Event_obj::DEACTIVATE,"DEACTIVATE"); HX_VISIT_MEMBER_NAME(Event_obj::ENTER_FRAME,"ENTER_FRAME"); HX_VISIT_MEMBER_NAME(Event_obj::ID3,"ID3"); HX_VISIT_MEMBER_NAME(Event_obj::INIT,"INIT"); HX_VISIT_MEMBER_NAME(Event_obj::MOUSE_LEAVE,"MOUSE_LEAVE"); HX_VISIT_MEMBER_NAME(Event_obj::OPEN,"OPEN"); HX_VISIT_MEMBER_NAME(Event_obj::REMOVED,"REMOVED"); HX_VISIT_MEMBER_NAME(Event_obj::REMOVED_FROM_STAGE,"REMOVED_FROM_STAGE"); HX_VISIT_MEMBER_NAME(Event_obj::RENDER,"RENDER"); HX_VISIT_MEMBER_NAME(Event_obj::RESIZE,"RESIZE"); HX_VISIT_MEMBER_NAME(Event_obj::SCROLL,"SCROLL"); HX_VISIT_MEMBER_NAME(Event_obj::SELECT,"SELECT"); HX_VISIT_MEMBER_NAME(Event_obj::SOUND_COMPLETE,"SOUND_COMPLETE"); HX_VISIT_MEMBER_NAME(Event_obj::TAB_CHILDREN_CHANGE,"TAB_CHILDREN_CHANGE"); HX_VISIT_MEMBER_NAME(Event_obj::TAB_ENABLED_CHANGE,"TAB_ENABLED_CHANGE"); HX_VISIT_MEMBER_NAME(Event_obj::TAB_INDEX_CHANGE,"TAB_INDEX_CHANGE"); HX_VISIT_MEMBER_NAME(Event_obj::UNLOAD,"UNLOAD"); }; #endif hx::Class Event_obj::__mClass; static ::String Event_obj_sStaticFields[] = { HX_HCSTRING("ACTIVATE","\xb3","\xab","\x31","\x3f"), HX_HCSTRING("ADDED","\xa0","\x0c","\x32","\x9a"), HX_HCSTRING("ADDED_TO_STAGE","\x59","\x58","\xdb","\x1a"), HX_HCSTRING("CANCEL","\x7a","\x99","\xb6","\x6a"), HX_HCSTRING("CHANGE","\x70","\x3d","\xf5","\x69"), HX_HCSTRING("CLOSE","\x98","\x4f","\x51","\xc6"), HX_HCSTRING("COMPLETE","\xb9","\x90","\x4d","\xd9"), HX_HCSTRING("CONNECT","\xca","\x0f","\x54","\x95"), HX_HCSTRING("CONTEXT3D_CREATE","\x5b","\xc4","\x3d","\x41"), HX_HCSTRING("DEACTIVATE","\x34","\xd0","\x0a","\x2e"), HX_HCSTRING("ENTER_FRAME","\x46","\xa6","\xab","\xc6"), HX_HCSTRING("ID3","\xf8","\x9f","\x37","\x00"), HX_HCSTRING("INIT","\x10","\x03","\x7c","\x30"), HX_HCSTRING("MOUSE_LEAVE","\xdd","\xd3","\xd5","\xd0"), HX_HCSTRING("OPEN","\xca","\xcb","\x74","\x34"), HX_HCSTRING("REMOVED","\x80","\xf3","\xd3","\x72"), HX_HCSTRING("REMOVED_FROM_STAGE","\x68","\xcc","\x72","\xdb"), HX_HCSTRING("RENDER","\x56","\x17","\xac","\xb7"), HX_HCSTRING("RESIZE","\xf4","\x05","\xfe","\xba"), HX_HCSTRING("SCROLL","\x0d","\x84","\xe7","\xf9"), HX_HCSTRING("SELECT","\xfc","\xc6","\xb5","\x1c"), HX_HCSTRING("SOUND_COMPLETE","\x89","\x35","\x98","\xf1"), HX_HCSTRING("TAB_CHILDREN_CHANGE","\x66","\x8e","\x83","\x1c"), HX_HCSTRING("TAB_ENABLED_CHANGE","\xd8","\x4a","\xcd","\x8b"), HX_HCSTRING("TAB_INDEX_CHANGE","\xe7","\xbd","\xc6","\xb6"), HX_HCSTRING("UNLOAD","\xff","\x4c","\x0f","\x18"), ::String(null()) }; void Event_obj::__register() { hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_HCSTRING("openfl._legacy.events.Event","\xc9","\xa6","\x7f","\x71"); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &Event_obj::__GetStatic; __mClass->mSetStaticField = &Event_obj::__SetStatic; __mClass->mMarkFunc = Event_obj_sMarkStatics; __mClass->mStatics = hx::Class_obj::dupFunctions(Event_obj_sStaticFields); __mClass->mMembers = hx::Class_obj::dupFunctions(Event_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< Event_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = Event_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = Event_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = Event_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } void Event_obj::__boot() { { HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",12,0xcca9b1d4) HXLINE( 12) ACTIVATE = HX_("activate",b3,1b,ac,e5); } { HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",13,0xcca9b1d4) HXLINE( 13) ADDED = HX_("added",c0,d4,43,1c); } { HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",14,0xcca9b1d4) HXLINE( 14) ADDED_TO_STAGE = HX_("addedToStage",63,22,55,0c); } { HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",15,0xcca9b1d4) HXLINE( 15) CANCEL = HX_("cancel",7a,ed,33,b8); } { HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",16,0xcca9b1d4) HXLINE( 16) CHANGE = HX_("change",70,91,72,b7); } { HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",17,0xcca9b1d4) HXLINE( 17) CLOSE = HX_("close",b8,17,63,48); } { HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",18,0xcca9b1d4) HXLINE( 18) COMPLETE = HX_("complete",b9,00,c8,7f); } { HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",19,0xcca9b1d4) HXLINE( 19) CONNECT = HX_("connect",ea,3b,80,15); } { HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",20,0xcca9b1d4) HXLINE( 20) CONTEXT3D_CREATE = HX_("context3DCreate",7c,bf,59,7b); } { HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",21,0xcca9b1d4) HXLINE( 21) DEACTIVATE = HX_("deactivate",34,5c,01,3c); } { HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",22,0xcca9b1d4) HXLINE( 22) ENTER_FRAME = HX_("enterFrame",f5,03,50,02); } { HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",23,0xcca9b1d4) HXLINE( 23) ID3 = HX_("id3",f8,03,50,00); } { HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",24,0xcca9b1d4) HXLINE( 24) INIT = HX_("init",10,3b,bb,45); } { HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",25,0xcca9b1d4) HXLINE( 25) MOUSE_LEAVE = HX_("mouseLeave",92,28,20,90); } { HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",26,0xcca9b1d4) HXLINE( 26) OPEN = HX_("open",ca,03,b4,49); } { HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",27,0xcca9b1d4) HXLINE( 27) REMOVED = HX_("removed",a0,1f,00,f3); } { HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",28,0xcca9b1d4) HXLINE( 28) REMOVED_FROM_STAGE = HX_("removedFromStage",34,21,76,ba); } { HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",29,0xcca9b1d4) HXLINE( 29) RENDER = HX_("render",56,6b,29,05); } { HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",30,0xcca9b1d4) HXLINE( 30) RESIZE = HX_("resize",f4,59,7b,08); } { HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",31,0xcca9b1d4) HXLINE( 31) SCROLL = HX_("scroll",0d,d8,64,47); } { HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",32,0xcca9b1d4) HXLINE( 32) SELECT = HX_("select",fc,1a,33,6a); } { HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",33,0xcca9b1d4) HXLINE( 33) SOUND_COMPLETE = HX_("soundComplete",a8,30,e6,1c); } { HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",34,0xcca9b1d4) HXLINE( 34) TAB_CHILDREN_CHANGE = HX_("tabChildrenChange",44,91,b5,de); } { HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",35,0xcca9b1d4) HXLINE( 35) TAB_ENABLED_CHANGE = HX_("tabEnabledChange",3c,45,98,72); } { HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",36,0xcca9b1d4) HXLINE( 36) TAB_INDEX_CHANGE = HX_("tabIndexChange",cd,1d,78,90); } { HX_STACK_FRAME("openfl._legacy.events.Event","boot",0x1b4c53f7,"openfl._legacy.events.Event.boot","openfl/_legacy/events/Event.hx",37,0xcca9b1d4) HXLINE( 37) UNLOAD = HX_("unload",ff,a0,8c,65); } } } // end namespace openfl } // end namespace _legacy } // end namespace events
46.676606
198
0.693307
TinyPlanetStudios
3eed5319602a0593c2248d72006ac9ed47bb19ce
727
cpp
C++
NWNXLib/Utils.cpp
acaos/nwnxee-unified
0e4c318ede64028c1825319f39c012e168e0482c
[ "MIT" ]
null
null
null
NWNXLib/Utils.cpp
acaos/nwnxee-unified
0e4c318ede64028c1825319f39c012e168e0482c
[ "MIT" ]
null
null
null
NWNXLib/Utils.cpp
acaos/nwnxee-unified
0e4c318ede64028c1825319f39c012e168e0482c
[ "MIT" ]
null
null
null
#include "Utils.hpp" #include "API/Globals.hpp" #include "API/CAppManager.hpp" #include "API/CServerExoApp.hpp" #include "API/CVirtualMachine.hpp" #include <sstream> namespace NWNXLib { namespace Utils { std::string ObjectIDToString(const API::Types::ObjectID id) { std::stringstream ss; ss << std::hex << id; return ss.str(); } std::string GetCurrentScript() { auto *pVM = API::Globals::VirtualMachine(); return std::string(pVM->m_pVirtualMachineScript[pVM->m_nRecursionLevel].m_sScriptName.CStr()); } void ExecuteScript(const std::string& script, API::Types::ObjectID oidOwner) { API::CExoString exoStr = script.c_str(); API::Globals::VirtualMachine()->RunScript(&exoStr, oidOwner, 1); } } }
22.71875
98
0.709766
acaos
3eeec1b9f3a8d2ba9b4a84cd5a57277979d5b925
2,736
cpp
C++
modules/ide_old/src/DebugToolbar.cpp
DeepBlue14/rqt_ide
853964dc429d61c9afb6f1fe827f2e3e83f92713
[ "MIT" ]
null
null
null
modules/ide_old/src/DebugToolbar.cpp
DeepBlue14/rqt_ide
853964dc429d61c9afb6f1fe827f2e3e83f92713
[ "MIT" ]
null
null
null
modules/ide_old/src/DebugToolbar.cpp
DeepBlue14/rqt_ide
853964dc429d61c9afb6f1fe827f2e3e83f92713
[ "MIT" ]
null
null
null
#include "DebugToolbar.h" DebugToolbar::DebugToolbar(QToolBar* parent) : QToolBar(parent) { actionPtrVecPtr = new QVector<QAction*>(); initActions(); } void DebugToolbar::handleStartActPtrSlot() { cout << "@ DebugToolbar::handleStartActPtrSlot()" << endl; } void DebugToolbar::handleStopActPtrSlot() { cout << "@ DebugToolbar::handleStopActPtrSlot()" << endl; } void DebugToolbar::handlePauseActPtrSlot() { cout << "@ DebugToolbar::handlePauseActPtrSlot()" << endl; } void DebugToolbar::handleStepIntoActPtrSlot() { cout << "@ DebugToolbar::handleStepIntoActPtrSlot()" << endl; } void DebugToolbar::handleStepOverActPtrSlot() { cout << "@ DebugToolbar::handleStepOverActPtrSlot()" << endl; } void DebugToolbar::initActions() { startActPtr = new QAction(QIcon(RosEnv::imagesInstallLoc + "placeholder.jpg"), tr("&New File"), this); startActPtr->setShortcut(QKeySequence::New); startActPtr->setStatusTip("New File"); connect(startActPtr, SIGNAL(triggered() ), this, SLOT(handleStartActPtrSlot() ) ); actionPtrVecPtr->push_back(startActPtr); stopActPtr = new QAction(QIcon(RosEnv::imagesInstallLoc + "placeholder.jpg"), tr("&New File"), this); stopActPtr->setShortcut(QKeySequence::New); stopActPtr->setStatusTip("New File"); connect(stopActPtr, SIGNAL(triggered() ), this, SLOT(handleStopActPtrSlot() ) ); actionPtrVecPtr->push_back(stopActPtr); pauseActPtr = new QAction(QIcon(RosEnv::imagesInstallLoc + "placeholder.jpg"), tr("&New File"), this); pauseActPtr->setShortcut(QKeySequence::New); pauseActPtr->setStatusTip("New File"); connect(pauseActPtr, SIGNAL(triggered() ), this, SLOT(handlePauseActPtrSlot() ) ); actionPtrVecPtr->push_back(pauseActPtr); stepIntoActPtr = new QAction(QIcon(RosEnv::imagesInstallLoc + "placeholder.jpg"), tr("&New File"), this); stepIntoActPtr->setShortcut(QKeySequence::New); stepIntoActPtr->setStatusTip("New File"); connect(stepIntoActPtr, SIGNAL(triggered() ), this, SLOT(handleStepIntoActPtrSlot() ) ); actionPtrVecPtr->push_back(stepIntoActPtr); stepOverActPtr = new QAction(QIcon(RosEnv::imagesInstallLoc + "placeholder.jpg"), tr("&New File"), this); stepOverActPtr->setShortcut(QKeySequence::New); stepOverActPtr->setStatusTip("New File"); connect(stepOverActPtr, SIGNAL(triggered() ), this, SLOT(handleStepOverActPtrSlot() ) ); actionPtrVecPtr->push_back(stepOverActPtr); } QString* DebugToolbar::toString() { QString* tmp = new QString("***METHOD STUB***"); return tmp; } QVector<QAction*>* DebugToolbar::getActions() { return actionPtrVecPtr; } DebugToolbar::~DebugToolbar() { ; }
28.206186
109
0.699561
DeepBlue14
3eef74dc561c81851c0888212018507de5c6086c
1,740
cpp
C++
foundation/plugins/undo/dmzPluginUndo.cpp
tongli/dmz
f2242027a17ea804259f9412b07d69f719a527c5
[ "MIT" ]
1
2016-05-08T22:02:35.000Z
2016-05-08T22:02:35.000Z
foundation/plugins/undo/dmzPluginUndo.cpp
ashok/dmz
2f8d4bced646f25abf2e98bdc0d378dafb4b32ed
[ "MIT" ]
null
null
null
foundation/plugins/undo/dmzPluginUndo.cpp
ashok/dmz
2f8d4bced646f25abf2e98bdc0d378dafb4b32ed
[ "MIT" ]
null
null
null
#include "dmzPluginUndo.h" #include <dmzRuntimeConfigToTypesBase.h> #include <dmzRuntimePluginFactoryLinkSymbol.h> #include <dmzRuntimePluginInfo.h> /*! \class dmz::PluginUndo \ingroup Foundation \brief Performs and undo or redo when a message is received. \details The default Message name to perform an undo is "Plugin_Undo_Message" and the default Message to perform a redo is "Plugin_Redo_Message". */ //! \cond dmz::PluginUndo::PluginUndo (const PluginInfo &Info, Config &local) : Plugin (Info), MessageObserver (Info), _undo (Info), _log (Info) { _init (local); } dmz::PluginUndo::~PluginUndo () { } // Message Observer Interface void dmz::PluginUndo::receive_message ( const Message &Msg, const UInt32 MessageSendHandle, const Handle TargetObserverHandle, const Data *InData, Data *outData) { _log.error << "Got message: " << Msg.get_name () << endl; if (Msg == _undoMessage) { _undo.do_next (UndoTypeUndo); } else if (Msg == _redoMessage) { _undo.do_next (UndoTypeRedo); } } void dmz::PluginUndo::_init (Config &local) { RuntimeContext *context (get_plugin_runtime_context ()); _undoMessage = config_create_message_type ( "undo.name", local, "Plugin_Undo_Message", context); _redoMessage = config_create_message_type ( "redo.name", local, "Plugin_Redo_Message", context); subscribe_to_message (_undoMessage); subscribe_to_message (_redoMessage); } //! \endcond extern "C" { DMZ_PLUGIN_FACTORY_LINK_SYMBOL dmz::Plugin * create_dmzPluginUndo ( const dmz::PluginInfo &Info, dmz::Config &local, dmz::Config &global) { return new dmz::PluginUndo (Info, local); } };
20.714286
81
0.685057
tongli
3eef7732e01993ce21af170636cc3e74a05cd289
6,189
cpp
C++
test/test_pair.cpp
bastiankoe/compute
57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f
[ "BSL-1.0" ]
1
2015-03-18T01:14:13.000Z
2015-03-18T01:14:13.000Z
test/test_pair.cpp
bastiankoe/compute
57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f
[ "BSL-1.0" ]
null
null
null
test/test_pair.cpp
bastiankoe/compute
57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f
[ "BSL-1.0" ]
null
null
null
//---------------------------------------------------------------------------// // Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com> // // Distributed under the Boost Software License, Version 1.0 // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // // See http://kylelutz.github.com/compute for more information. //---------------------------------------------------------------------------// #define BOOST_TEST_MODULE TestPair #include <boost/test/unit_test.hpp> #include <iostream> #include <boost/compute/algorithm/copy.hpp> #include <boost/compute/algorithm/fill.hpp> #include <boost/compute/algorithm/find.hpp> #include <boost/compute/algorithm/transform.hpp> #include <boost/compute/container/vector.hpp> #include <boost/compute/functional/get.hpp> #include <boost/compute/functional/field.hpp> #include <boost/compute/types/pair.hpp> #include "quirks.hpp" #include "check_macros.hpp" #include "context_setup.hpp" BOOST_AUTO_TEST_CASE(vector_pair_int_float) { boost::compute::vector<std::pair<int, float> > vector; vector.push_back(std::make_pair(1, 1.1f)); vector.push_back(std::make_pair(2, 2.2f)); vector.push_back(std::make_pair(3, 3.3f)); BOOST_CHECK_EQUAL(vector.size(), size_t(3)); BOOST_CHECK(vector[0] == std::make_pair(1, 1.1f)); BOOST_CHECK(vector[1] == std::make_pair(2, 2.2f)); BOOST_CHECK(vector[2] == std::make_pair(3, 3.3f)); } BOOST_AUTO_TEST_CASE(copy_pair_vector) { boost::compute::vector<std::pair<int, float> > input; input.push_back(std::make_pair(1, 2.0f)); input.push_back(std::make_pair(3, 4.0f)); input.push_back(std::make_pair(5, 6.0f)); input.push_back(std::make_pair(7, 8.0f)); BOOST_CHECK_EQUAL(input.size(), size_t(4)); boost::compute::vector<std::pair<int, float> > output(4); boost::compute::copy(input.begin(), input.end(), output.begin()); boost::compute::system::finish(); BOOST_CHECK(output[0] == std::make_pair(1, 2.0f)); BOOST_CHECK(output[1] == std::make_pair(3, 4.0f)); BOOST_CHECK(output[2] == std::make_pair(5, 6.0f)); BOOST_CHECK(output[3] == std::make_pair(7, 8.0f)); } BOOST_AUTO_TEST_CASE(fill_pair_vector) { if(bug_in_struct_assignment(device)){ std::cerr << "skipping fill_pair_vector test" << std::endl; return; } boost::compute::vector<std::pair<int, float> > vector(5); boost::compute::fill(vector.begin(), vector.end(), std::make_pair(4, 2.0f)); boost::compute::system::finish(); BOOST_CHECK(vector[0] == std::make_pair(4, 2.0f)); BOOST_CHECK(vector[1] == std::make_pair(4, 2.0f)); BOOST_CHECK(vector[2] == std::make_pair(4, 2.0f)); BOOST_CHECK(vector[3] == std::make_pair(4, 2.0f)); BOOST_CHECK(vector[4] == std::make_pair(4, 2.0f)); } BOOST_AUTO_TEST_CASE(fill_char_pair_vector) { if(bug_in_struct_assignment(device)){ std::cerr << "skipping fill_char_pair_vector test" << std::endl; return; } std::pair<char, unsigned char> value('c', static_cast<unsigned char>(127)); boost::compute::vector<std::pair<char, unsigned char> > vector(5); boost::compute::fill(vector.begin(), vector.end(), value); boost::compute::system::finish(); BOOST_CHECK(vector[0] == value); BOOST_CHECK(vector[1] == value); BOOST_CHECK(vector[2] == value); BOOST_CHECK(vector[3] == value); BOOST_CHECK(vector[4] == value); } BOOST_AUTO_TEST_CASE(transform_pair_get) { boost::compute::vector<std::pair<int, float> > input; input.push_back(std::make_pair(1, 2.0f)); input.push_back(std::make_pair(3, 4.0f)); input.push_back(std::make_pair(5, 6.0f)); input.push_back(std::make_pair(7, 8.0f)); boost::compute::vector<int> first_output(4); boost::compute::transform( input.begin(), input.end(), first_output.begin(), ::boost::compute::get<0>() ); CHECK_RANGE_EQUAL(int, 4, first_output, (1, 3, 5, 7)); boost::compute::vector<float> second_output(4); boost::compute::transform( input.begin(), input.end(), second_output.begin(), ::boost::compute::get<1>() ); CHECK_RANGE_EQUAL(float, 4, second_output, (2.0f, 4.0f, 6.0f, 8.0f)); } BOOST_AUTO_TEST_CASE(transform_pair_field) { boost::compute::vector<std::pair<int, float> > input; input.push_back(std::make_pair(1, 2.0f)); input.push_back(std::make_pair(3, 4.0f)); input.push_back(std::make_pair(5, 6.0f)); input.push_back(std::make_pair(7, 8.0f)); boost::compute::vector<int> first_output(4); boost::compute::transform( input.begin(), input.end(), first_output.begin(), boost::compute::field<int>("first") ); CHECK_RANGE_EQUAL(int, 4, first_output, (1, 3, 5, 7)); boost::compute::vector<float> second_output(4); boost::compute::transform( input.begin(), input.end(), second_output.begin(), boost::compute::field<float>("second") ); CHECK_RANGE_EQUAL(float, 4, second_output, (2.0f, 4.0f, 6.0f, 8.0f)); } BOOST_AUTO_TEST_CASE(find_vector_pair) { boost::compute::vector<std::pair<int, float> > vector; vector.push_back(std::make_pair(1, 1.1f)); vector.push_back(std::make_pair(2, 2.2f)); vector.push_back(std::make_pair(3, 3.3f)); BOOST_CHECK_EQUAL(vector.size(), size_t(3)); BOOST_CHECK( boost::compute::find( boost::compute::make_transform_iterator( vector.begin(), boost::compute::get<0>() ), boost::compute::make_transform_iterator( vector.end(), boost::compute::get<0>() ), int(2) ).base() == vector.begin() + 1 ); BOOST_CHECK( boost::compute::find( boost::compute::make_transform_iterator( vector.begin(), boost::compute::get<1>() ), boost::compute::make_transform_iterator( vector.end(), boost::compute::get<1>() ), float(3.3f) ).base() == vector.begin() + 2 ); } BOOST_AUTO_TEST_SUITE_END()
33.274194
80
0.614639
bastiankoe
3ef515ce39f5ca04ed57a7e9356b156e4a48239b
549
hpp
C++
LinearAlgebra/operation/scalar/scalar.hpp
suiyili/Algorithms
d6ddc8262c5d681ecc78938b6140510793a29d91
[ "MIT" ]
null
null
null
LinearAlgebra/operation/scalar/scalar.hpp
suiyili/Algorithms
d6ddc8262c5d681ecc78938b6140510793a29d91
[ "MIT" ]
null
null
null
LinearAlgebra/operation/scalar/scalar.hpp
suiyili/Algorithms
d6ddc8262c5d681ecc78938b6140510793a29d91
[ "MIT" ]
null
null
null
#pragma once #include "scalar.h" namespace algebra::arithmetic { template<typename T> inline matrix<T>& operator*=(matrix<T>& m, T scalar) { for (size_t i = 0U; i < m.columns(); ++i) { for (size_t j = 0U; j < m.rows(); ++j) { pixel id{i, j}; m[id] *= scalar; } } return m; } template<typename T> inline matrix<T> operator*(const matrix<T> &m, T scalar) { matrix<T> result(m); result *= scalar; return result; } template<typename T> inline matrix<T> operator*(T scalar, const matrix<T>& m) { return m * scalar; } }
18.931034
58
0.612022
suiyili
3ef86773cfcdb1640a64bf3f3dc494c886fcb919
116
hxx
C++
src/Providers/UNIXProviders/VLANService/UNIX_VLANService_AIX.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
1
2020-10-12T09:00:09.000Z
2020-10-12T09:00:09.000Z
src/Providers/UNIXProviders/VLANService/UNIX_VLANService_AIX.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
src/Providers/UNIXProviders/VLANService/UNIX_VLANService_AIX.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
#ifdef PEGASUS_OS_AIX #ifndef __UNIX_VLANSERVICE_PRIVATE_H #define __UNIX_VLANSERVICE_PRIVATE_H #endif #endif
9.666667
36
0.836207
brunolauze
3efb1bfd766173e5d3984258eff284a4d1b3e91b
289
cpp
C++
Chapter11/chapter11bt_05/main.cpp
markccchiang/Modern-Cpp-Programming-Cookbook
42ba3c9ca1e0d897807f1c3baa5dddb0ee064f23
[ "MIT" ]
null
null
null
Chapter11/chapter11bt_05/main.cpp
markccchiang/Modern-Cpp-Programming-Cookbook
42ba3c9ca1e0d897807f1c3baa5dddb0ee064f23
[ "MIT" ]
null
null
null
Chapter11/chapter11bt_05/main.cpp
markccchiang/Modern-Cpp-Programming-Cookbook
42ba3c9ca1e0d897807f1c3baa5dddb0ee064f23
[ "MIT" ]
null
null
null
#define BOOST_TEST_MODULE Controlling output #include <boost/test/included/unit_test.hpp> BOOST_AUTO_TEST_CASE(test_case) { BOOST_TEST(true); } BOOST_AUTO_TEST_SUITE(test_suite) BOOST_AUTO_TEST_CASE(test_case) { int a = 42; BOOST_TEST(a == 0); } BOOST_AUTO_TEST_SUITE_END()
19.266667
44
0.768166
markccchiang
3efc8eaed45e54f59a6dfe174cd9e6fd1f10d1bd
1,915
hpp
C++
include/O2FS/OTwo.hpp
SirusDoma/O2FS
3ffa2d5476b8ee883be145c275df5e7759c1e520
[ "MIT" ]
1
2022-02-16T12:36:32.000Z
2022-02-16T12:36:32.000Z
include/O2FS/OTwo.hpp
SirusDoma/O2FS
3ffa2d5476b8ee883be145c275df5e7759c1e520
[ "MIT" ]
null
null
null
include/O2FS/OTwo.hpp
SirusDoma/O2FS
3ffa2d5476b8ee883be145c275df5e7759c1e520
[ "MIT" ]
null
null
null
#ifndef O2FS_OTWO_HPP #define O2FS_OTWO_HPP #include <windows.h> #include <vector> #include <unordered_map> #include <string> #include <O2FS/FileSystem.hpp> namespace O2FS { class OTwo { private: static std::vector<FileSystem*> systems; static std::unordered_map<HANDLE, std::string> fileCaches; // This enables modification for outer level assets (e.g OJN, OJM, OPI, OPA, OJNList.dat) static BOOL WINAPI HookReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped); static DWORD WINAPI HookGetFileSize(HANDLE hFile, LPDWORD lpFileSizeHigh); // This enables file scanning modification (e.g *.ojn -> *.bms Scanning) static HANDLE WINAPI HookFindFirstFile(LPCSTR lpFileName, LPWIN32_FIND_DATAA lpFindFileData); static BOOL WINAPI HookFindNextFile(HANDLE hFindFile, LPWIN32_FIND_DATAA lpFindFileData); // This allow cache to be invalidated static BOOL WINAPI HookCloseHandle(HANDLE hObject); public: static bool Hooked(); static void Hook(); static void Unhook(); // Mount FileSystem hook to handle collection of files that being processed by game. static bool Mount(FileSystem *fs); static std::string GetFileName(HANDLE hFile); // Real functions without detours static BOOL WINAPI ReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped); static DWORD WINAPI GetFileSize(HANDLE hFile, LPDWORD lpFileSizeHigh); static HANDLE WINAPI FindFirstFile(LPCSTR lpFileName, LPWIN32_FIND_DATAA lpFindFileData); static BOOL WINAPI FindNextFile(HANDLE hFindFile, LPWIN32_FIND_DATAA lpFindFileData); static BOOL WINAPI CloseHandle(HANDLE hObject); }; } #endif //O2FS_OTWO_HPP
39.081633
157
0.721671
SirusDoma
3efef6fe7d95344083ea3eb63e703ce45cad70f1
17,380
cpp
C++
cyclone/OpLogic.cpp
barryjburns/dgen
a6f61a594b996840110a6c4bc0347a9d8e4f81e7
[ "BSD-3-Clause" ]
33
2020-11-20T16:38:43.000Z
2021-10-17T04:21:44.000Z
cyclone/OpLogic.cpp
barryjburns/dgen
a6f61a594b996840110a6c4bc0347a9d8e4f81e7
[ "BSD-3-Clause" ]
2
2020-11-21T00:32:37.000Z
2020-11-23T17:38:26.000Z
cyclone/OpLogic.cpp
barryjburns/dgen
a6f61a594b996840110a6c4bc0347a9d8e4f81e7
[ "BSD-3-Clause" ]
2
2020-11-21T09:37:17.000Z
2021-01-06T15:00:01.000Z
// This file is part of the Cyclone 68000 Emulator // Copyright (c) 2004,2011 FinalDave (emudave (at) gmail.com) // Copyright (c) 2005-2011 Gražvydas "notaz" Ignotas (notasas (at) gmail.com) // This code is licensed under the GNU General Public License version 2.0 and the MAME License. // You can choose the license that has the most advantages for you. // SVN repository can be found at http://code.google.com/p/cyclone68000/ #include "app.h" // --------------------- Opcodes 0x0100+ --------------------- // Emit a Btst (Register) opcode 0000nnn1 ttaaaaaa int OpBtstReg(int op) { int use=0; int type=0,sea=0,tea=0; int size=0; type=(op>>6)&3; // Btst/Bchg/Bclr/Bset // Get source and target EA sea=(op>>9)&7; tea=op&0x003f; if (tea<0x10) size=2; // For registers, 32-bits if ((tea&0x38)==0x08) return 1; // movep // See if we can do this opcode: if (EaCanRead(tea,0)==0) return 1; if (type>0) { if (EaCanWrite(tea)==0) return 1; } use=OpBase(op,size); use&=~0x0e00; // Use same handler for all registers if (op!=use) { OpUse(op,use); return 0; } // Use existing handler OpStart(op,tea); if(type==1||type==3) { Cycles=8; } else { Cycles=type?8:4; if(size>=2) Cycles+=2; } EaCalcReadNoSE(-1,11,sea,0,0x0e00); EaCalcReadNoSE((type>0)?8:-1,0,tea,size,0x003f); if (tea>=0x10) ot(" and r11,r11,#7 ;@ mem - do mod 8\n"); // size always 0 else ot(" and r11,r11,#31 ;@ reg - do mod 32\n"); // size always 2 ot("\n"); ot(" mov r1,#1\n"); ot(" tst r0,r1,lsl r11 ;@ Do arithmetic\n"); ot(" bicne r10,r10,#0x40000000\n"); ot(" orreq r10,r10,#0x40000000 ;@ Get Z flag\n"); ot("\n"); if (type>0) { if (type==1) ot(" eor r1,r0,r1,lsl r11 ;@ Toggle bit\n"); if (type==2) ot(" bic r1,r0,r1,lsl r11 ;@ Clear bit\n"); if (type==3) ot(" orr r1,r0,r1,lsl r11 ;@ Set bit\n"); ot("\n"); EaWrite(8,1,tea,size,0x003f,0,0); } OpEnd(tea); return 0; } // --------------------- Opcodes 0x0800+ --------------------- // Emit a Btst/Bchg/Bclr/Bset (Immediate) opcode 00001000 ttaaaaaa nn int OpBtstImm(int op) { int type=0,sea=0,tea=0; int use=0; int size=0; type=(op>>6)&3; // Get source and target EA sea= 0x003c; tea=op&0x003f; if (tea<0x10) size=2; // For registers, 32-bits // See if we can do this opcode: if (EaCanRead(tea,0)==0||EaAn(tea)||tea==0x3c) return 1; if (type>0) { if (EaCanWrite(tea)==0) return 1; } use=OpBase(op,size); if (op!=use) { OpUse(op,use); return 0; } // Use existing handler OpStart(op,sea,tea); ot("\n"); EaCalcReadNoSE(-1,0,sea,0,0); ot(" mov r11,#1\n"); ot(" bic r10,r10,#0x40000000 ;@ Blank Z flag\n"); if (tea>=0x10) ot(" and r0,r0,#7 ;@ mem - do mod 8\n"); // size always 0 else ot(" and r0,r0,#0x1F ;@ reg - do mod 32\n"); // size always 2 ot(" mov r11,r11,lsl r0 ;@ Make bit mask\n"); ot("\n"); if(type==1||type==3) { Cycles=12; } else { Cycles=type?12:8; if(size>=2) Cycles+=2; } EaCalcReadNoSE((type>0)?8:-1,0,tea,size,0x003f); ot(" tst r0,r11 ;@ Do arithmetic\n"); ot(" orreq r10,r10,#0x40000000 ;@ Get Z flag\n"); ot("\n"); if (type>0) { if (type==1) ot(" eor r1,r0,r11 ;@ Toggle bit\n"); if (type==2) ot(" bic r1,r0,r11 ;@ Clear bit\n"); if (type==3) ot(" orr r1,r0,r11 ;@ Set bit\n"); ot("\n"); EaWrite(8, 1,tea,size,0x003f,0,0); #if CYCLONE_FOR_GENESIS && !MEMHANDLERS_CHANGE_CYCLES // this is a bit hacky (device handlers might modify cycles) if (tea==0x38||tea==0x39) ot(" ldr r5,[r7,#0x5c] ;@ Load Cycles\n"); #endif } OpEnd(sea,tea); return 0; } // --------------------- Opcodes 0x4000+ --------------------- int OpNeg(int op) { // 01000tt0 xxeeeeee (tt=negx/clr/neg/not, xx=size, eeeeee=EA) int type=0,size=0,ea=0,use=0; type=(op>>9)&3; ea =op&0x003f; size=(op>>6)&3; if (size>=3) return 1; // See if we can do this opcode: if (EaCanRead (ea,size)==0||EaAn(ea)) return 1; if (EaCanWrite(ea )==0) return 1; use=OpBase(op,size); if (op!=use) { OpUse(op,use); return 0; } // Use existing handler OpStart(op,ea); Cycles=size<2?4:6; if(ea >= 0x10) Cycles*=2; EaCalc (11,0x003f,ea,size,0,0); if (type!=1) EaRead (11,0,ea,size,0x003f,0,0); // Don't need to read for 'clr' (or do we, for a dummy read?) if (type==1) ot("\n"); if (type==0) { ot(";@ Negx:\n"); GetXBit(1); if(size!=2) ot(" mov r0,r0,asl #%i\n",size?16:24); ot(" rscs r1,r0,#0 ;@ do arithmetic\n"); ot(" orr r3,r10,#0xb0000000 ;@ for old Z\n"); OpGetFlags(1,1,0); if(size!=2) { ot(" movs r1,r1,asr #%i\n",size?16:24); ot(" orreq r10,r10,#0x40000000 ;@ possily missed Z\n"); } ot(" andeq r10,r10,r3 ;@ fix Z\n"); ot("\n"); } if (type==1) { ot(";@ Clear:\n"); ot(" mov r1,#0\n"); ot(" mov r10,#0x40000000 ;@ NZCV=0100\n"); ot("\n"); } if (type==2) { ot(";@ Neg:\n"); if(size!=2) ot(" mov r0,r0,asl #%i\n",size?16:24); ot(" rsbs r1,r0,#0\n"); OpGetFlags(1,1); if(size!=2) ot(" mov r1,r1,asr #%i\n",size?16:24); ot("\n"); } if (type==3) { ot(";@ Not:\n"); if(size!=2) { ot(" mov r0,r0,asl #%i\n",size?16:24); ot(" mvn r1,r0,asr #%i\n",size?16:24); } else ot(" mvn r1,r0\n"); ot(" adds r1,r1,#0 ;@ Defines NZ, clears CV\n"); OpGetFlags(0,0); ot("\n"); } if (type==1) eawrite_check_addrerr=1; EaWrite(11, 1,ea,size,0x003f,0,0); OpEnd(ea); return 0; } // --------------------- Opcodes 0x4840+ --------------------- // Swap, 01001000 01000nnn swap Dn int OpSwap(int op) { int ea=0,use=0; ea=op&7; use=op&~0x0007; // Use same opcode for all An if (op!=use) { OpUse(op,use); return 0; } // Use existing handler OpStart(op); Cycles=4; EaCalc (11,0x0007,ea,2,1); EaRead (11, 0,ea,2,0x0007,1); ot(" mov r1,r0,ror #16\n"); ot(" adds r1,r1,#0 ;@ Defines NZ, clears CV\n"); OpGetFlags(0,0); EaWrite(11, 1,8,2,0x0007,1); OpEnd(); return 0; } // --------------------- Opcodes 0x4a00+ --------------------- // Emit a Tst opcode, 01001010 xxeeeeee int OpTst(int op) { int sea=0; int size=0,use=0; sea=op&0x003f; size=(op>>6)&3; if (size>=3) return 1; // See if we can do this opcode: if (EaCanWrite(sea)==0||EaAn(sea)) return 1; use=OpBase(op,size); if (op!=use) { OpUse(op,use); return 0; } // Use existing handler OpStart(op,sea); Cycles=4; EaCalc ( 0,0x003f,sea,size,1); EaRead ( 0, 0,sea,size,0x003f,1); ot(" adds r0,r0,#0 ;@ Defines NZ, clears CV\n"); ot(" mrs r10,cpsr ;@ r10=flags\n"); ot("\n"); OpEnd(sea); return 0; } // --------------------- Opcodes 0x4880+ --------------------- // Emit an Ext opcode, 01001000 1x000nnn int OpExt(int op) { int ea=0; int size=0,use=0; int shift=0; ea=op&0x0007; size=(op>>6)&1; shift=32-(8<<size); use=OpBase(op,size); if (op!=use) { OpUse(op,use); return 0; } // Use existing handler OpStart(op); Cycles=4; EaCalc (11,0x0007,ea,size+1,0,0); EaRead (11, 0,ea,size+1,0x0007,0,0); ot(" mov r0,r0,asl #%d\n",shift); ot(" adds r0,r0,#0 ;@ Defines NZ, clears CV\n"); ot(" mrs r10,cpsr ;@ r10=flags\n"); ot(" mov r1,r0,asr #%d\n",shift); ot("\n"); EaWrite(11, 1,ea,size+1,0x0007,0,0); OpEnd(); return 0; } // --------------------- Opcodes 0x50c0+ --------------------- // Emit a Set cc opcode, 0101cccc 11eeeeee int OpSet(int op) { int cc=0,ea=0; int size=0,use=0,changed_cycles=0; static const char * const cond[16]= { "al","", "hi","ls","cc","cs","ne","eq", "vc","vs","pl","mi","ge","lt","gt","le" }; cc=(op>>8)&15; ea=op&0x003f; if ((ea&0x38)==0x08) return 1; // dbra, not scc // See if we can do this opcode: if (EaCanWrite(ea)==0) return 1; use=OpBase(op,size); if (op!=use) { OpUse(op,use); return 0; } // Use existing handler changed_cycles=ea<8 && cc>=2; OpStart(op,ea,0,changed_cycles); Cycles=8; if (ea<8) Cycles=4; if (cc) ot(" mov r1,#0\n"); switch (cc) { case 0: // T ot(" mvn r1,#0\n"); if (ea<8) Cycles+=2; break; case 1: // F break; case 2: // hi ot(" tst r10,#0x60000000 ;@ hi: !C && !Z\n"); ot(" mvneq r1,r1\n"); if (ea<8) ot(" subeq r5,r5,#2 ;@ Extra cycles\n"); break; case 3: // ls ot(" tst r10,#0x60000000 ;@ ls: C || Z\n"); ot(" mvnne r1,r1\n"); if (ea<8) ot(" subne r5,r5,#2 ;@ Extra cycles\n"); break; default: ot(";@ Is the condition true?\n"); ot(" msr cpsr_flg,r10 ;@ ARM flags = 68000 flags\n"); ot(" mvn%s r1,r1\n",cond[cc]); if (ea<8) ot(" sub%s r5,r5,#2 ;@ Extra cycles\n",cond[cc]); break; } ot("\n"); eawrite_check_addrerr=1; EaCalc (0,0x003f, ea,size,0,0); EaWrite(0, 1, ea,size,0x003f,0,0); opend_op_changes_cycles=changed_cycles; OpEnd(ea,0); return 0; } // Emit a Asr/Lsr/Roxr/Ror opcode static int EmitAsr(int op,int type,int dir,int count,int size,int usereg) { char pct[8]=""; // count int shift=32-(8<<size); if (count>=1) sprintf(pct,"#%d",count); // Fixed count if (usereg) { ot(";@ Use Dn for count:\n"); ot(" and r2,r8,#0x0e00\n"); ot(" ldr r2,[r7,r2,lsr #7]\n"); ot(" and r2,r2,#63\n"); ot("\n"); strcpy(pct,"r2"); } else if (count<0) { ot(" mov r2,r8,lsr #9 ;@ Get 'n'\n"); ot(" and r2,r2,#7\n\n"); strcpy(pct,"r2"); } // Take 2*n cycles: if (count<0) ot(" sub r5,r5,r2,asl #1 ;@ Take 2*n cycles\n\n"); else Cycles+=count<<1; if (type<2) { // Asr/Lsr if (dir==0 && size<2) { ot(";@ For shift right, use loworder bits for the operation:\n"); ot(" mov r0,r0,%s #%d\n",type?"lsr":"asr",32-(8<<size)); ot("\n"); } if (type==0 && dir) ot(" adds r3,r0,#0 ;@ save old value for V flag calculation, also clear V\n"); ot(";@ Shift register:\n"); if (type==0) ot(" movs r0,r0,%s %s\n",dir?"asl":"asr",pct); if (type==1) ot(" movs r0,r0,%s %s\n",dir?"lsl":"lsr",pct); OpGetFlags(0,0); if (usereg) { // store X only if count is not 0 ot(" cmp %s,#0 ;@ shifting by 0?\n",pct); ot(" biceq r10,r10,#0x20000000 ;@ if so, clear carry\n"); ot(" strne r10,[r7,#0x4c] ;@ else Save X bit\n"); } else { // count will never be 0 if we use immediate ot(" str r10,[r7,#0x4c] ;@ Save X bit\n"); } ot("\n"); if (dir==0 && size<2) { ot(";@ restore after right shift:\n"); ot(" movs r0,r0,lsl #%d\n",32-(8<<size)); if (type) ot(" orrmi r10,r10,#0x80000000 ;@ Potentially missed N flag\n"); ot("\n"); } if (type==0 && dir) { ot(";@ calculate V flag (set if sign bit changes at anytime):\n"); ot(" mov r1,#0x80000000\n"); ot(" ands r3,r3,r1,asr %s\n", pct); ot(" cmpne r3,r1,asr %s\n", pct); ot(" eoreq r1,r0,r3\n"); // above check doesn't catch (-1)<<(32+), so we need this ot(" tsteq r1,#0x80000000\n"); ot(" orrne r10,r10,#0x10000000\n"); ot("\n"); } } // -------------------------------------- if (type==2) { int wide=8<<size; // Roxr if(count == 1) { if(dir==0) { if(size!=2) { ot(" orr r0,r0,r0,lsr #%i\n", size?16:24); ot(" bic r0,r0,#0x%x\n", 1<<(32-wide)); } GetXBit(0); ot(" movs r0,r0,rrx\n"); OpGetFlags(0,1); } else { ot(" ldr r3,[r7,#0x4c]\n"); ot(" movs r0,r0,lsl #1\n"); OpGetFlags(0,1); ot(" tst r3,#0x20000000\n"); ot(" orrne r0,r0,#0x%x\n", 1<<(32-wide)); ot(" bicne r10,r10,#0x40000000 ;@ clear Z in case it got there\n"); } ot(" bic r10,r10,#0x10000000 ;@ make suve V is clear\n"); return 0; } if (usereg) { if (size==2) { ot(" subs r2,r2,#33\n"); ot(" addmis r2,r2,#33 ;@ Now r2=0-%d\n",wide); } else { ot(";@ Reduce r2 until <0:\n"); ot("Reduce_%.4x%s\n",op,ms?"":":"); ot(" subs r2,r2,#%d\n",wide+1); ot(" bpl Reduce_%.4x\n",op); ot(" adds r2,r2,#%d ;@ Now r2=0-%d\n",wide+1,wide); } ot(" beq norotx_%.4x\n",op); ot("\n"); } if (usereg||count < 0) { if (dir) ot(" rsb r2,r2,#%d ;@ Reverse direction\n",wide+1); } else { if (dir) ot(" mov r2,#%d ;@ Reversed\n",wide+1-count); else ot(" mov r2,#%d\n",count); } if (shift) ot(" mov r0,r0,lsr #%d ;@ Shift down\n",shift); ot("\n"); ot(";@ First get X bit (middle):\n"); ot(" ldr r3,[r7,#0x4c]\n"); ot(" rsb r1,r2,#%d\n",wide); ot(" and r3,r3,#0x20000000\n"); ot(" mov r3,r3,lsr #29\n"); ot(" mov r3,r3,lsl r1\n"); ot(";@ Rotate bits:\n"); ot(" orr r3,r3,r0,lsr r2 ;@ Orr right part\n"); ot(" rsbs r2,r2,#%d ;@ should also clear ARM V\n",wide+1); ot(" orrs r0,r3,r0,lsl r2 ;@ Orr left part, set flags\n"); ot("\n"); if (shift) ot(" movs r0,r0,lsl #%d ;@ Shift up and get correct NC flags\n",shift); OpGetFlags(0,!usereg); if (usereg) { // store X only if count is not 0 ot(" str r10,[r7,#0x4c] ;@ if not 0, Save X bit\n"); ot(" b nozerox%.4x\n",op); ot("norotx_%.4x%s\n",op,ms?"":":"); ot(" ldr r2,[r7,#0x4c]\n"); ot(" adds r0,r0,#0 ;@ Defines NZ, clears CV\n"); OpGetFlags(0,0); ot(" and r2,r2,#0x20000000\n"); ot(" orr r10,r10,r2 ;@ C = old_X\n"); ot("nozerox%.4x%s\n",op,ms?"":":"); } ot("\n"); } // -------------------------------------- if (type==3) { // Ror if (size<2) { ot(";@ Mirror value in whole 32 bits:\n"); if (size<=0) ot(" orr r0,r0,r0,lsr #8\n"); if (size<=1) ot(" orr r0,r0,r0,lsr #16\n"); ot("\n"); } ot(";@ Rotate register:\n"); if (!dir) ot(" adds r0,r0,#0 ;@ first clear V and C\n"); // ARM does not clear C if rot count is 0 if (count<0) { if (dir) ot(" rsb %s,%s,#32\n",pct,pct); ot(" movs r0,r0,ror %s\n",pct); } else { int ror=count; if (dir) ror=32-ror; if (ror&31) ot(" movs r0,r0,ror #%d\n",ror); } OpGetFlags(0,0); if (dir) { ot(" bic r10,r10,#0x30000000 ;@ clear CV\n"); ot(";@ Get carry bit from bit 0:\n"); if (usereg) { ot(" cmp %s,#32 ;@ rotating by 0?\n",pct); ot(" tstne r0,#1 ;@ no, check bit 0\n"); } else ot(" tst r0,#1\n"); ot(" orrne r10,r10,#0x20000000\n"); } ot("\n"); } // -------------------------------------- return 0; } // Emit a Asr/Lsr/Roxr/Ror opcode - 1110cccd xxuttnnn // (ccc=count, d=direction(r,l) xx=size extension, u=use reg for count, tt=type, nnn=register Dn) int OpAsr(int op) { int ea=0,use=0; int count=0,dir=0; int size=0,usereg=0,type=0; count =(op>>9)&7; dir =(op>>8)&1; size =(op>>6)&3; if (size>=3) return 1; // use OpAsrEa() usereg=(op>>5)&1; type =(op>>3)&3; if (usereg==0) count=((count-1)&7)+1; // because ccc=000 means 8 // Use the same opcode for target registers: use=op&~0x0007; // As long as count is not 8, use the same opcode for all shift counts: if (usereg==0 && count!=8 && !(count==1&&type==2)) { use|=0x0e00; count=-1; } if (usereg) { use&=~0x0e00; count=-1; } // Use same opcode for all Dn if (op!=use) { OpUse(op,use); return 0; } // Use existing handler OpStart(op,ea,0,count<0); Cycles=size<2?6:8; EaCalc(11,0x0007, ea,size,1); EaRead(11, 0, ea,size,0x0007,1); EmitAsr(op,type,dir,count, size,usereg); EaWrite(11, 0, ea,size,0x0007,1); opend_op_changes_cycles = (count<0); OpEnd(ea,0); return 0; } // Asr/Lsr/Roxr/Ror etc EA - 11100ttd 11eeeeee int OpAsrEa(int op) { int use=0,type=0,dir=0,ea=0,size=1; type=(op>>9)&3; dir =(op>>8)&1; ea = op&0x3f; if (ea<0x10) return 1; // See if we can do this opcode: if (EaCanRead(ea,0)==0) return 1; if (EaCanWrite(ea)==0) return 1; use=OpBase(op,size); if (op!=use) { OpUse(op,use); return 0; } // Use existing handler OpStart(op,ea); Cycles=6; // EmitAsr() will add 2 EaCalc (11,0x003f,ea,size,1); EaRead (11, 0,ea,size,0x003f,1); EmitAsr(op,type,dir,1,size,0); EaWrite(11, 0,ea,size,0x003f,1); OpEnd(ea); return 0; } int OpTas(int op, int gen_special) { int ea=0; int use=0; ea=op&0x003f; // See if we can do this opcode: if (EaCanWrite(ea)==0 || EaAn(ea)) return 1; use=OpBase(op,0); if (op!=use) { OpUse(op,use); return 0; } // Use existing handler if (!gen_special) OpStart(op,ea); else ot("Op%.4x_%s\n", op, ms?"":":"); Cycles=4; if(ea>=8) Cycles+=10; EaCalc (11,0x003f,ea,0,1); EaRead (11, 1,ea,0,0x003f,1); ot(" adds r1,r1,#0 ;@ Defines NZ, clears CV\n"); OpGetFlags(0,0); ot("\n"); #if CYCLONE_FOR_GENESIS // the original Sega hardware ignores write-back phase (to memory only) if (ea < 0x10 || gen_special) { #endif ot(" orr r1,r1,#0x80000000 ;@ set bit7\n"); EaWrite(11, 1,ea,0,0x003f,1); #if CYCLONE_FOR_GENESIS } #endif OpEnd(ea); #if (CYCLONE_FOR_GENESIS == 2) if (!gen_special && ea >= 0x10) { OpTas(op, 1); } #endif return 0; }
24.307692
110
0.524223
barryjburns
410342d5b369416c85e2e0921929180d37f9f554
639
cpp
C++
example/single_pro/MutexLock.cpp
jianxinzhou/Maple
96a85a96c1e978325f87c7ebc745addf190dcb59
[ "BSD-2-Clause" ]
1
2021-01-20T09:44:50.000Z
2021-01-20T09:44:50.000Z
example/Singleton/MutexLock.cpp
jianxinzhou/Maple
96a85a96c1e978325f87c7ebc745addf190dcb59
[ "BSD-2-Clause" ]
null
null
null
example/Singleton/MutexLock.cpp
jianxinzhou/Maple
96a85a96c1e978325f87c7ebc745addf190dcb59
[ "BSD-2-Clause" ]
1
2021-01-20T09:45:17.000Z
2021-01-20T09:45:17.000Z
#include "MutexLock.h" #include <assert.h> MutexLock::MutexLock() :isLocking_(false) { TINY_CHECK(!pthread_mutex_init(&mutex_, NULL)); } MutexLock::~MutexLock() { assert(isLocking()); TINY_CHECK(!pthread_mutex_destroy(&mutex_)); } void MutexLock::lock() { TINY_CHECK(!pthread_mutex_lock(&mutex_)); isLocking_ = true; } void MutexLock::unlock() { isLocking_ = false; TINY_CHECK(!pthread_mutex_unlock(&mutex_)); } // end MutexLock MutexLockGuard::MutexLockGuard(MutexLock &mutex) :mutex_(mutex) { mutex_.lock(); } MutexLockGuard::~MutexLockGuard() { mutex_.unlock(); } // end MutexLockGuard
15.975
51
0.687011
jianxinzhou
41040e0510afd373c33c5d66ac284a473eb053e9
5,385
cpp
C++
Code/Engine/RendererCore/Pipeline/Implementation/Passes/SimpleRenderPass.cpp
JohannStudanski/ezEngine
bb9d7dc4ad1ba52c2725f0a8bd1b851d59dbf43c
[ "MIT" ]
1
2021-06-23T14:44:02.000Z
2021-06-23T14:44:02.000Z
Code/Engine/RendererCore/Pipeline/Implementation/Passes/SimpleRenderPass.cpp
aemeltsev/ezEngine
98528c268dbf8cf37bb1f31e8664bd9651b7023f
[ "MIT" ]
null
null
null
Code/Engine/RendererCore/Pipeline/Implementation/Passes/SimpleRenderPass.cpp
aemeltsev/ezEngine
98528c268dbf8cf37bb1f31e8664bd9651b7023f
[ "MIT" ]
null
null
null
#include <RendererCorePCH.h> #include <RendererCore/Pipeline/Passes/SimpleRenderPass.h> #include <RendererCore/Pipeline/View.h> #include <RendererCore/RenderContext/RenderContext.h> #include <RendererFoundation/Resources/RenderTargetView.h> #include <RendererFoundation/Resources/Texture.h> #include <RendererCore/Debug/DebugRenderer.h> // clang-format off EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezSimpleRenderPass, 1, ezRTTIDefaultAllocator<ezSimpleRenderPass>) { EZ_BEGIN_PROPERTIES { EZ_MEMBER_PROPERTY("Color", m_PinColor), EZ_MEMBER_PROPERTY("DepthStencil", m_PinDepthStencil)->AddAttributes(new ezColorAttribute(ezColor::LightCoral)), EZ_MEMBER_PROPERTY("Message", m_sMessage), } EZ_END_PROPERTIES; } EZ_END_DYNAMIC_REFLECTED_TYPE; // clang-format on ezSimpleRenderPass::ezSimpleRenderPass(const char* szName) : ezRenderPipelinePass(szName, true) { } ezSimpleRenderPass::~ezSimpleRenderPass() {} bool ezSimpleRenderPass::GetRenderTargetDescriptions(const ezView& view, const ezArrayPtr<ezGALTextureCreationDescription* const> inputs, ezArrayPtr<ezGALTextureCreationDescription> outputs) { ezGALDevice* pDevice = ezGALDevice::GetDefaultDevice(); const ezGALRenderTargetSetup& setup = view.GetRenderTargetSetup(); // Color if (inputs[m_PinColor.m_uiInputIndex]) { outputs[m_PinColor.m_uiOutputIndex] = *inputs[m_PinColor.m_uiInputIndex]; } else { // If no input is available, we use the render target setup instead. const ezGALRenderTargetView* pTarget = pDevice->GetRenderTargetView(setup.GetRenderTarget(0)); if (pTarget) { const ezGALRenderTargetViewCreationDescription& desc = pTarget->GetDescription(); const ezGALTexture* pTexture = pDevice->GetTexture(desc.m_hTexture); if (pTexture) { outputs[m_PinColor.m_uiOutputIndex] = pTexture->GetDescription(); outputs[m_PinColor.m_uiOutputIndex].m_bCreateRenderTarget = true; outputs[m_PinColor.m_uiOutputIndex].m_bAllowShaderResourceView = true; outputs[m_PinColor.m_uiOutputIndex].m_ResourceAccess.m_bReadBack = false; outputs[m_PinColor.m_uiOutputIndex].m_ResourceAccess.m_bImmutable = true; outputs[m_PinColor.m_uiOutputIndex].m_pExisitingNativeObject = nullptr; } } } // DepthStencil if (inputs[m_PinDepthStencil.m_uiInputIndex]) { outputs[m_PinDepthStencil.m_uiOutputIndex] = *inputs[m_PinDepthStencil.m_uiInputIndex]; } else { // If no input is available, we use the render target setup instead. const ezGALRenderTargetView* pTarget = pDevice->GetRenderTargetView(setup.GetDepthStencilTarget()); if (pTarget) { const ezGALRenderTargetViewCreationDescription& desc = pTarget->GetDescription(); const ezGALTexture* pTexture = pDevice->GetTexture(desc.m_hTexture); if (pTexture) { outputs[m_PinDepthStencil.m_uiOutputIndex] = pTexture->GetDescription(); } } } return true; } void ezSimpleRenderPass::Execute(const ezRenderViewContext& renderViewContext, const ezArrayPtr<ezRenderPipelinePassConnection* const> inputs, const ezArrayPtr<ezRenderPipelinePassConnection* const> outputs) { ezGALDevice* pDevice = ezGALDevice::GetDefaultDevice(); // Setup render target ezGALRenderTargetSetup renderTargetSetup; if (inputs[m_PinColor.m_uiInputIndex]) { renderTargetSetup.SetRenderTarget(0, pDevice->GetDefaultRenderTargetView(inputs[m_PinColor.m_uiInputIndex]->m_TextureHandle)); } if (inputs[m_PinDepthStencil.m_uiInputIndex]) { renderTargetSetup.SetDepthStencilTarget(pDevice->GetDefaultRenderTargetView(inputs[m_PinDepthStencil.m_uiInputIndex]->m_TextureHandle)); } renderViewContext.m_pRenderContext->SetViewportAndRenderTargetSetup(renderViewContext.m_pViewData->m_ViewPortRect, renderTargetSetup); // Setup Permutation Vars ezTempHashedString sRenderPass("RENDER_PASS_FORWARD"); if (renderViewContext.m_pViewData->m_ViewRenderMode != ezViewRenderMode::None) { sRenderPass = ezViewRenderMode::GetPermutationValue(renderViewContext.m_pViewData->m_ViewRenderMode); } renderViewContext.m_pRenderContext->SetShaderPermutationVariable("RENDER_PASS", sRenderPass); // Execute render functions RenderDataWithCategory(renderViewContext, ezDefaultRenderDataCategories::SimpleOpaque); RenderDataWithCategory(renderViewContext, ezDefaultRenderDataCategories::SimpleTransparent); if (!m_sMessage.IsEmpty()) { ezDebugRenderer::Draw2DText(*renderViewContext.m_pViewDebugContext, m_sMessage, ezVec2I32(20, 20), ezColor::OrangeRed); } ezDebugRenderer::Render(renderViewContext); renderViewContext.m_pRenderContext->SetShaderPermutationVariable("PREPARE_DEPTH", "TRUE"); RenderDataWithCategory(renderViewContext, ezDefaultRenderDataCategories::SimpleForeground); renderViewContext.m_pRenderContext->SetShaderPermutationVariable("PREPARE_DEPTH", "FALSE"); RenderDataWithCategory(renderViewContext, ezDefaultRenderDataCategories::SimpleForeground); RenderDataWithCategory(renderViewContext, ezDefaultRenderDataCategories::GUI); } void ezSimpleRenderPass::SetMessage(const char* szMessage) { m_sMessage = szMessage; } EZ_STATICLINK_FILE(RendererCore, RendererCore_Pipeline_Implementation_Passes_SimpleRenderPass);
37.137931
140
0.772702
JohannStudanski
4105fbd17cfab7cdce73c25ceacb9a7ea65e083f
2,296
cc
C++
runtime/vm/type_testing_stubs_arm64.cc
annagrin/sdk
dfce72bbf9bf359ecd810964259978e24c55e237
[ "BSD-3-Clause" ]
2
2019-08-15T18:30:00.000Z
2020-11-03T20:17:12.000Z
runtime/vm/type_testing_stubs_arm64.cc
annagrin/sdk
dfce72bbf9bf359ecd810964259978e24c55e237
[ "BSD-3-Clause" ]
1
2021-01-21T14:45:59.000Z
2021-01-21T14:45:59.000Z
runtime/vm/type_testing_stubs_arm64.cc
annagrin/sdk
dfce72bbf9bf359ecd810964259978e24c55e237
[ "BSD-3-Clause" ]
3
2020-02-13T02:08:04.000Z
2020-08-09T07:49:55.000Z
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/globals.h" #if defined(TARGET_ARCH_ARM64) && !defined(DART_PRECOMPILED_RUNTIME) #include "vm/type_testing_stubs.h" #define __ assembler-> namespace dart { void TypeTestingStubGenerator::BuildOptimizedTypeTestStub( compiler::Assembler* assembler, HierarchyInfo* hi, const Type& type, const Class& type_class) { const Register kInstanceReg = R0; const Register kClassIdReg = R9; BuildOptimizedTypeTestStubFastCases(assembler, hi, type, type_class, kInstanceReg, kClassIdReg); __ ldr(CODE_REG, compiler::Address(THR, Thread::slow_type_test_stub_offset())); __ ldr(R9, compiler::FieldAddress(CODE_REG, Code::entry_point_offset())); __ br(R9); } void TypeTestingStubGenerator:: BuildOptimizedSubclassRangeCheckWithTypeArguments( compiler::Assembler* assembler, HierarchyInfo* hi, const Class& type_class, const TypeArguments& tp, const TypeArguments& ta) { const Register kInstanceReg = R0; const Register kInstanceTypeArguments = R7; const Register kClassIdReg = R9; BuildOptimizedSubclassRangeCheckWithTypeArguments( assembler, hi, type_class, tp, ta, kClassIdReg, kInstanceReg, kInstanceTypeArguments); } void TypeTestingStubGenerator::BuildOptimizedTypeArgumentValueCheck( compiler::Assembler* assembler, HierarchyInfo* hi, const AbstractType& type_arg, intptr_t type_param_value_offset_i, compiler::Label* check_failed) { const Register kInstantiatorTypeArgumentsReg = R1; const Register kFunctionTypeArgumentsReg = R2; const Register kInstanceTypeArguments = R7; const Register kClassIdReg = R9; const Register kOwnTypeArgumentValue = TMP; BuildOptimizedTypeArgumentValueCheck( assembler, hi, type_arg, type_param_value_offset_i, kClassIdReg, kInstanceTypeArguments, kInstantiatorTypeArgumentsReg, kFunctionTypeArgumentsReg, kOwnTypeArgumentValue, check_failed); } } // namespace dart #endif // defined(TARGET_ARCH_ARM64) && !defined(DART_PRECOMPILED_RUNTIME)
32.8
77
0.747387
annagrin
410664eda0f1db6e1326af9ab80d94a59cbff8e5
10,885
cpp
C++
src/Interface.cpp
RicardoCoutinho/LAIG
13933ce1dd05ff4d099ffb0864bb9034c52592e7
[ "MIT" ]
null
null
null
src/Interface.cpp
RicardoCoutinho/LAIG
13933ce1dd05ff4d099ffb0864bb9034c52592e7
[ "MIT" ]
null
null
null
src/Interface.cpp
RicardoCoutinho/LAIG
13933ce1dd05ff4d099ffb0864bb9034c52592e7
[ "MIT" ]
null
null
null
#include "Interface.h" #include "YAFScene.h" #include "Application.h" #include <GL/glui.h> #define MOUSE_ROTATE_FACTOR 0 #define MOUSE_PAN_FACTOR 0 #define MOUSE_ZOOM_FACTOR 0 //#define MOUSE_ROTATE_FACTOR 0.5 //#define MOUSE_PAN_FACTOR 0.05 //#define MOUSE_ZOOM_FACTOR 0.5 #define CG_CGFcamera_AXIS_X 0 #define CG_CGFcamera_AXIS_Y 1 #define CG_CGFcamera_AXIS_Z 2 int Interface::modifiers=0; Interface::Interface() { gamemode = false; } Interface::~Interface() { } Interface * Interface::activeInterface=NULL; void Interface::setScene(YAFScene* sc) { scene=sc; } float Interface::getDisplacementY() { return displacementY; } void Interface::init(int parent) { //glui_window = GLUI_Master.create_glui_subwindow(parent, GLUI_SUBWINDOW_LEFT); GLUI_Master.set_glutKeyboardFunc(Interface::preprocessKeyboard); GLUI_Master.set_glutMouseFunc(Interface::preprocessMouse); glutMotionFunc(Interface::preprocessMouseMoved); glutPassiveMotionFunc(Interface::preprocessPassiveMouseMoved); displacementX = 0; displacementY = 0; pressing_left=false; pressing_right=false; pressing_middle=false; prev_X = 0; prev_Y = 0; } void Interface::initGUI() { } GLUI_Checkbox* Interface::addCheckbox(char* name, int* value, int id ) { return glui_window->add_checkbox(name, value, id, Interface::preprocessGUI); } GLUI_Checkbox* Interface::addCheckboxToPanel(GLUI_Panel *p,char* name, int* value,int id ) { return glui_window->add_checkbox_to_panel(p,name, value,id,Interface::preprocessGUI); } GLUI_Button* Interface::addButton(char* name,int id) { return glui_window->add_button(name, id, Interface::preprocessGUI); } GLUI_Button* Interface::addButtonToPanel(GLUI_Panel *p,char* name, int id ) { return glui_window->add_button_to_panel(p,name, id, Interface::preprocessGUI); } void Interface::addColumn() { glui_window->add_column(); } void Interface::addColumnToPanel(GLUI_Panel *p) { glui_window->add_column_to_panel(p); } GLUI_EditText* Interface::addEditText(char* name, char* var, int id ) { return glui_window->add_edittext(name,GLUI_EDITTEXT_STRING, var,id,Interface::preprocessGUI); } GLUI_EditText* Interface::addEditText(char* name, int* var, int id ) { return glui_window->add_edittext(name,GLUI_EDITTEXT_INT, var,id,Interface::preprocessGUI); } GLUI_EditText* Interface::addEditText(char* name, float* var, int id ) { return glui_window->add_edittext(name,GLUI_EDITTEXT_FLOAT, var,id,Interface::preprocessGUI); } GLUI_EditText* Interface::addEditTextToPanel(GLUI_Panel *p,char* name, char* var, int id ) { return glui_window->add_edittext_to_panel(p,name,GLUI_EDITTEXT_FLOAT, var,id,Interface::preprocessGUI); } GLUI_EditText* Interface::addEditTextToPanel(GLUI_Panel *p,char* name, int* var, int id ) { return glui_window->add_edittext_to_panel(p,name,GLUI_EDITTEXT_FLOAT, var,id,Interface::preprocessGUI); } GLUI_EditText* Interface::addEditTextToPanel(GLUI_Panel *p,char* name, float* var, int id ) { return glui_window->add_edittext_to_panel(p,name,GLUI_EDITTEXT_FLOAT, var,id,Interface::preprocessGUI); } GLUI_Listbox* Interface::addListbox(char* name, int* var, int id ) { return glui_window->add_listbox(name,var,id,Interface::preprocessGUI); } GLUI_Listbox* Interface::addListboxToPanel(GLUI_Panel *p,char* name, int* var, int id) { return glui_window->add_listbox_to_panel(p,name,var,id,Interface::preprocessGUI); } GLUI_Panel* Interface::addPanel(char* name, int type ) { return glui_window->add_panel(name,type); } GLUI_Panel* Interface::addPanelToPanel(GLUI_Panel *p,char* name, int type) { return glui_window->add_panel_to_panel(p,name,type); } GLUI_RadioButton* Interface::addRadioButtonToGroup(GLUI_RadioGroup * group, char * name) { return glui_window->add_radiobutton_to_group(group,name); } GLUI_RadioGroup* Interface::addRadioGroup(int *var, int id ) { return glui_window->add_radiogroup(var,id,Interface::preprocessGUI); } GLUI_RadioGroup* Interface::addRadioGroupToPanel(GLUI_Panel *p,int *var, int id) { return glui_window->add_radiogroup_to_panel(p,var,id,Interface::preprocessGUI); } GLUI_Rollout* Interface::addRollout(char *name, int open, int type ) { return glui_window->add_rollout(name,open,type); } GLUI_Rollout* Interface::addRolloutToPanel(GLUI_Panel* p,char *name, int open, int type ) { return glui_window->add_rollout_to_panel(p,name,open,type); } void Interface::addSeparator() { return glui_window->add_separator(); } void Interface::addSeparatorToPanel(GLUI_Panel *p) { return glui_window->add_separator_to_panel(p); } GLUI_Rotation* Interface::addRotation(char* name, float* var, int id) { return glui_window->add_rotation(name,var,id,Interface::preprocessGUI); } GLUI_Rotation* Interface::addRotationToPanel(GLUI_Panel *p,char* name, float* var, int id) { return glui_window->add_rotation_to_panel(p,name,var,id,Interface::preprocessGUI); } GLUI_Spinner* Interface::addSpinner(char* name, int type, int* var, int id) { return glui_window->add_spinner(name,type,var,id,Interface::preprocessGUI); } GLUI_Spinner* Interface::addSpinnerToPanel(GLUI_Panel* p,char* name, int type, int* var, int id ) { return glui_window->add_spinner_to_panel(p,name,type,var,id,Interface::preprocessGUI); } GLUI_StaticText* Interface::addStaticText(char* name) { return glui_window->add_statictext(name); } GLUI_StaticText* Interface::addStaticTextToPanel(GLUI_Panel *p,char* name) { return glui_window->add_statictext_to_panel(p,name); } GLUI_Translation* Interface::addTranslationToPanel(GLUI_Panel* p,char* name, int type, float* var, int id) { return glui_window->add_translation_to_panel(p,name,type,var,id,Interface::preprocessGUI); } GLUI_Translation* Interface::addTranslation(char* name, int type, float* var, int id) { return glui_window->add_translation(name,type,var,id,Interface::preprocessGUI); } void Interface::preprocessKeyboard(unsigned char key, int x, int y) { modifiers=glutGetModifiers(); activeInterface->processKeyboard(key,x,y); } void Interface::preprocessMouse(int button, int state, int x, int y) { modifiers=glutGetModifiers(); activeInterface->processMouse(button, state, x,y); } void Interface::preprocessMouseMoved(int x, int y) { activeInterface->processMouseMoved(x,y); } void Interface::preprocessPassiveMouseMoved(int x, int y) { activeInterface->processPassiveMouseMoved(x,y); } void Interface::syncVars() { /****************************************************************/ /* This demonstrates GLUI::sync_live() */ /* We change the value of a variable that is 'live' to some */ /* control. We then call sync_live, and the control */ /* associated with that variable is automatically updated */ /* with the new value. This frees the programmer from having */ /* to always remember which variables are used by controls - */ /* simply change whatever variables are necessary, then sync */ /* the live ones all at once with a single call to sync_live */ /****************************************************************/ //glui_window->sync_live(); } void Interface::preprocessGUI(GLUI_Control *ctrl) { activeInterface->processGUI(ctrl); } // Default handlers (to be overriden by sub-class) void Interface::processKeyboard(unsigned char key, int x, int y) { switch (key) { /* case 'w': //scene->cameras->getCamera(scene->camID)->setWalkMode(); break; case 'e': //scene->cameras->getCamera(scene->camID)->setExamineMode(); break; */ case 's': Application::snapshot(); break; case 48: scene->appearances->getAppearance("floor")->setTexture(scene->textures->getTexture("board0")); break; case 49: scene->appearances->getAppearance("floor")->setTexture(scene->textures->getTexture("board1")); break; case 50: scene->appearances->getAppearance("floor")->setTexture(scene->textures->getTexture("board2")); break; case 'q': if (!scene->board->menu) scene->camID = 30; break; case 'w': if (!scene->board->menu) scene->camID = 31; break; case 'e': if (!scene->board->menu) scene->camID = 32; break; case 'r': if (!scene->board->menu) scene->camID = 33; break; case 'u': if (scene->board->menu || scene->board->gameover!=0) return; if ( scene->board->replay || (scene->board->placementsLeft[0]==12 && scene->board->placementsLeft[0]==12 )) ; else { scene->board->undo(); } break; case 'i': if (scene->board->menu || scene->board->gameover==0) return; if (scene->board->gameover!=0 && scene->board->replay == 0) { scene->board->replay = true; scene->board->reset(); scene->board->start_time = 0; scene->board->actual_time = 0; scene->board->actual_play = 0; scene->board->itplay = scene->board->plays.begin(); scene->board->replayGame(); } break; case 27: // tecla de escape termina o programa exit(0); break; } } void Interface::processMouse(int button, int state, int x, int y) { prev_X = x; prev_Y = y; pressing_left = (button == GLUT_LEFT_BUTTON) && (state == GLUT_DOWN); pressing_right = (button == GLUT_RIGHT_BUTTON) && (state == GLUT_DOWN); pressing_middle = (button == GLUT_MIDDLE_BUTTON) && (state == GLUT_DOWN); glutPostRedisplay(); } void Interface::processMouseMoved(int x, int y) { // pedido de refrescamento da janela displacementX = x- prev_X; displacementY = y- prev_Y; if(pressing_left && modifiers==0) { scene->cameras->getCamera(scene->camID)->rotate(CG_CGFcamera_AXIS_X, displacementY*MOUSE_ROTATE_FACTOR); scene->cameras->getCamera(scene->camID)->rotate(CG_CGFcamera_AXIS_Y, displacementX*MOUSE_ROTATE_FACTOR); } else if(pressing_right && modifiers==0) { scene->cameras->getCamera(scene->camID)->translate(CG_CGFcamera_AXIS_X, displacementX*MOUSE_PAN_FACTOR); scene->cameras->getCamera(scene->camID)->translate(CG_CGFcamera_AXIS_Y, -displacementY*MOUSE_PAN_FACTOR); } else if(pressing_middle || (pressing_left && modifiers & GLUT_ACTIVE_CTRL)) { scene->cameras->getCamera(scene->camID)->translate(CG_CGFcamera_AXIS_Z, displacementY*MOUSE_ZOOM_FACTOR); } prev_X = x; prev_Y = y; glutPostRedisplay(); } void Interface::processPassiveMouseMoved(int x, int y) { // pedido de refrescamento da janela glutPostRedisplay(); } void Interface::processGUI(GLUI_Control *ctrl) { }
28.054124
121
0.6904
RicardoCoutinho
41074d657bfbfbb8f1bbf9b0ea0abf63317c2c19
2,527
cc
C++
examples/octave/plot_b6.cc
yyk99/bzeditor
f4d3a24fbed2d7a3db82124e2c927288731f763b
[ "MIT" ]
null
null
null
examples/octave/plot_b6.cc
yyk99/bzeditor
f4d3a24fbed2d7a3db82124e2c927288731f763b
[ "MIT" ]
null
null
null
examples/octave/plot_b6.cc
yyk99/bzeditor
f4d3a24fbed2d7a3db82124e2c927288731f763b
[ "MIT" ]
null
null
null
// // // #include "bezierMk2.h" #include "Plotter.h" #include <iostream> #include <stdexcept> std::ostream &operator<< (std::ostream &s, point2d_t const &p) { s << p.to_string(); return s; } void plot_b6_UT() /* unit test */ { point2d_t p0 = point2d_t(10, 10); point2d_t p1 = point2d_t(0, 20); point2d_t p2 = point2d_t(30, 30); point2d_t p3 = point2d_t(50, 20); point2d_t p4 = point2d_t(40, 0); point2d_t p5 = point2d_t(20, 0); point2d_t p6 = p0; { std::vector<point2d_t> points = { p0, p1 }; auto r = bezierMk2(0, points); if (r != p0) throw std::logic_error("Expected p0"); } { std::vector<point2d_t> points = { p0, p1 }; auto r = bezierMk2(1, points); if (r != p1) throw std::logic_error("Expected p1"); } { { std::vector<point2d_t> points = { p0, p1 }; double u = 0.5; auto r = bezierMk2(0.5, points); std::cout << "bz(" << u << ") = " << r << std::endl; if (r != point2d_t(5, 15)) throw std::logic_error("Expected {5, 15}"); } { std::vector<point2d_t> points = { p0, p1, p2, p3, p4, p5, p6 }; double u = 0.5; auto r = bezierMk2(0.5, points); std::cout << "bz(" << u << ") = " << r << std::endl; point2d_t expected = point2d_t(34.2187500000000, 15.4687500000000); if (r != point2d_t(34.2187500000000, 15.4687500000000)) throw std::logic_error("Expected " + expected.to_string()); } } } void plot_b6() { point2d_t p0 = point2d_t(10, 10); point2d_t p1 = point2d_t(0, 20); point2d_t p2 = point2d_t(30, 30); point2d_t p3 = point2d_t(50, 20); point2d_t p4 = point2d_t(40, 0); point2d_t p5 = point2d_t(20, 0); point2d_t p6 = p0; std::vector<point2d_t> controls = { p0, p1, p2, p3, p4, p5, p6 }; std::cout << "X,Y" << std::endl; const int N = 200; std::vector<point2d_t> points(N+1); for(int i = 0 ; i <= N ; ++i) { double u = 1.0 / N * i; auto p = bezierMk2(u, controls); std::cout << std::get<0>(p) << "," << std::get<1>(p) << std::endl; points[i] = p; } Plotter plotter; plotter.plot_image("plot_b6.png", controls, points); } int main() { try { plot_b6(); } catch (std::exception ex) { std::cerr << "Error: " << ex.what() << std::endl; } } // end of file
23.839623
79
0.508508
yyk99
410859f88eac9a505febb206bd36593e0111d867
163
cpp
C++
tests/main.cpp
zivhoo/magic
9f3c0d572c10e53d6580c1ffa80e1b69d07e91c0
[ "Apache-2.0" ]
null
null
null
tests/main.cpp
zivhoo/magic
9f3c0d572c10e53d6580c1ffa80e1b69d07e91c0
[ "Apache-2.0" ]
null
null
null
tests/main.cpp
zivhoo/magic
9f3c0d572c10e53d6580c1ffa80e1b69d07e91c0
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include "Magic.h" using namespace std; int main() { Magic::Magic magic; magic.createRenderWindow("",500,400, false); return 0; }
14.818182
48
0.662577
zivhoo
41086a8a27f4ab0f73ae58e7f2432b662d6149c5
128
cpp
C++
tensorflow-yolo-ios/dependencies/eigen/failtest/diagonal_nonconst_ctor_on_const_xpr.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
27
2017-06-07T19:07:32.000Z
2020-10-15T10:09:12.000Z
tensorflow-yolo-ios/dependencies/eigen/failtest/diagonal_nonconst_ctor_on_const_xpr.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
3
2017-08-25T17:39:46.000Z
2017-11-18T03:40:55.000Z
tensorflow-yolo-ios/dependencies/eigen/failtest/diagonal_nonconst_ctor_on_const_xpr.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
10
2017-06-16T18:04:45.000Z
2018-07-05T17:33:01.000Z
version https://git-lfs.github.com/spec/v1 oid sha256:771e89a5fdad79addce7ae43103632797345b0f6f2ab6ffc1fd4a3eab37409b7 size 228
32
75
0.882813
initialz
410f55abc58323c02fe5b24027567389f4811fb5
4,696
hpp
C++
Pods/Headers/Private/Realm/realm/impl/destroy_guard.hpp
Valpertui/mealtingpot-ios
73368d4ec16fef55f3b8f30e45038955db6385df
[ "MIT" ]
145
2015-07-22T06:04:49.000Z
2021-12-08T13:37:04.000Z
Pods/Headers/Private/Realm/realm/impl/destroy_guard.hpp
Valpertui/mealtingpot-ios
73368d4ec16fef55f3b8f30e45038955db6385df
[ "MIT" ]
23
2016-01-14T06:52:56.000Z
2017-02-13T22:11:42.000Z
Pods/Headers/Private/Realm/realm/impl/destroy_guard.hpp
Valpertui/mealtingpot-ios
73368d4ec16fef55f3b8f30e45038955db6385df
[ "MIT" ]
42
2015-07-24T02:59:31.000Z
2019-07-23T08:51:59.000Z
/************************************************************************* * * REALM CONFIDENTIAL * __________________ * * [2011] - [2012] Realm Inc * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Realm Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Realm Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Realm Incorporated. * **************************************************************************/ #ifndef REALM_IMPL_DESTROY_GUARD_HPP #define REALM_IMPL_DESTROY_GUARD_HPP #include <realm/util/features.h> #include <realm/array.hpp> namespace realm { namespace _impl { /// Calls `ptr->destroy()` if the guarded pointer (`ptr`) is not null /// when the guard is destroyed. For arrays (`T` = `Array`) this means /// that the array is destroyed in a shallow fashion. See /// `DeepArrayDestroyGuard` for an alternative. template<class T> class DestroyGuard { public: DestroyGuard() noexcept; DestroyGuard(T*) noexcept; ~DestroyGuard() noexcept; void reset(T*) noexcept; T* get() const noexcept; T* release() noexcept; private: T* m_ptr; }; using ShallowArrayDestroyGuard = DestroyGuard<Array>; /// Calls `ptr->destroy_deep()` if the guarded Array pointer (`ptr`) /// is not null when the guard is destroyed. class DeepArrayDestroyGuard { public: DeepArrayDestroyGuard() noexcept; DeepArrayDestroyGuard(Array*) noexcept; ~DeepArrayDestroyGuard() noexcept; void reset(Array*) noexcept; Array* get() const noexcept; Array* release() noexcept; private: Array* m_ptr; }; /// Calls `Array::destroy_deep(ref, alloc)` if the guarded 'ref' /// (`ref`) is not zero when the guard is destroyed. class DeepArrayRefDestroyGuard { public: DeepArrayRefDestroyGuard(Allocator&) noexcept; DeepArrayRefDestroyGuard(ref_type, Allocator&) noexcept; ~DeepArrayRefDestroyGuard() noexcept; void reset(ref_type) noexcept; ref_type get() const noexcept; ref_type release() noexcept; private: ref_type m_ref; Allocator& m_alloc; }; // Implementation: // DestroyGuard<T> template<class T> inline DestroyGuard<T>::DestroyGuard() noexcept: m_ptr(nullptr) { } template<class T> inline DestroyGuard<T>::DestroyGuard(T* ptr) noexcept: m_ptr(ptr) { } template<class T> inline DestroyGuard<T>::~DestroyGuard() noexcept { if (m_ptr) m_ptr->destroy(); } template<class T> inline void DestroyGuard<T>::reset(T* ptr) noexcept { if (m_ptr) m_ptr->destroy(); m_ptr = ptr; } template<class T> inline T* DestroyGuard<T>::get() const noexcept { return m_ptr; } template<class T> inline T* DestroyGuard<T>::release() noexcept { T* ptr = m_ptr; m_ptr = nullptr; return ptr; } // DeepArrayDestroyGuard inline DeepArrayDestroyGuard::DeepArrayDestroyGuard() noexcept: m_ptr(nullptr) { } inline DeepArrayDestroyGuard::DeepArrayDestroyGuard(Array* ptr) noexcept: m_ptr(ptr) { } inline DeepArrayDestroyGuard::~DeepArrayDestroyGuard() noexcept { if (m_ptr) m_ptr->destroy_deep(); } inline void DeepArrayDestroyGuard::reset(Array* ptr) noexcept { if (m_ptr) m_ptr->destroy_deep(); m_ptr = ptr; } inline Array* DeepArrayDestroyGuard::get() const noexcept { return m_ptr; } inline Array* DeepArrayDestroyGuard::release() noexcept { Array* ptr = m_ptr; m_ptr = nullptr; return ptr; } // DeepArrayRefDestroyGuard inline DeepArrayRefDestroyGuard::DeepArrayRefDestroyGuard(Allocator& alloc) noexcept: m_ref(0), m_alloc(alloc) { } inline DeepArrayRefDestroyGuard::DeepArrayRefDestroyGuard(ref_type ref, Allocator& alloc) noexcept: m_ref(ref), m_alloc(alloc) { } inline DeepArrayRefDestroyGuard::~DeepArrayRefDestroyGuard() noexcept { if (m_ref) Array::destroy_deep(m_ref, m_alloc); } inline void DeepArrayRefDestroyGuard::reset(ref_type ref) noexcept { if (m_ref) Array::destroy_deep(m_ref, m_alloc); m_ref = ref; } inline ref_type DeepArrayRefDestroyGuard::get() const noexcept { return m_ref; } inline ref_type DeepArrayRefDestroyGuard::release() noexcept { ref_type ref = m_ref; m_ref = 0; return ref; } } // namespace _impl } // namespace realm #endif // REALM_IMPL_DESTROY_GUARD_HPP
20.241379
85
0.67994
Valpertui
41107173169bb4c4685641b48e2c574656d298c0
3,668
hpp
C++
sprout/math/hypot.hpp
kevcadieux/Sprout
6b5addba9face0a6403e66e7db2aa94d87387f61
[ "BSL-1.0" ]
691
2015-01-15T18:52:23.000Z
2022-03-15T23:39:39.000Z
sprout/math/hypot.hpp
kevcadieux/Sprout
6b5addba9face0a6403e66e7db2aa94d87387f61
[ "BSL-1.0" ]
22
2015-03-11T01:22:56.000Z
2021-03-29T01:51:45.000Z
sprout/math/hypot.hpp
kevcadieux/Sprout
6b5addba9face0a6403e66e7db2aa94d87387f61
[ "BSL-1.0" ]
57
2015-03-11T07:52:29.000Z
2021-12-16T09:15:33.000Z
/*============================================================================= Copyright (c) 2011-2019 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef SPROUT_MATH_HYPOT_HPP #define SPROUT_MATH_HYPOT_HPP #include <type_traits> #include <sprout/config.hpp> #include <sprout/limits.hpp> #include <sprout/math/detail/config.hpp> #include <sprout/math/detail/float_compute.hpp> #include <sprout/math/isnan.hpp> #include <sprout/math/signbit.hpp> #include <sprout/math/fabs.hpp> #include <sprout/math/sqrt.hpp> #include <sprout/type_traits/float_promote.hpp> #include <sprout/type_traits/enabler_if.hpp> namespace sprout { namespace math { namespace detail { #if SPROUT_USE_BUILTIN_CMATH_FUNCTION inline SPROUT_CONSTEXPR float builtin_hypot(float x, float y) { return __builtin_hypotf(x, y); } inline SPROUT_CONSTEXPR double builtin_hypot(double x, double y) { return __builtin_hypot(x, y); } inline SPROUT_CONSTEXPR long double builtin_hypot(long double x, long double y) { return __builtin_hypotl(x, y); } #endif template<typename T> inline SPROUT_CONSTEXPR T hypot_impl_2(T t, T w) { return t * sprout::math::sqrt(T(1) + w * w); } template<typename T> inline SPROUT_CONSTEXPR T hypot_impl_1(T x, T y) { return x < y ? sprout::math::detail::hypot_impl_2(y, x / y) : sprout::math::detail::hypot_impl_2(x, y / x) ; } template<typename T> inline SPROUT_CONSTEXPR T hypot_impl(T x, T y) { return sprout::math::detail::hypot_impl_1(sprout::math::fabs(x), sprout::math::fabs(y)); } } // namespace detail // // hypot // template< typename FloatType, typename sprout::enabler_if<std::is_floating_point<FloatType>::value>::type = sprout::enabler > inline SPROUT_CONSTEXPR FloatType hypot(FloatType x, FloatType y) { return y == sprout::numeric_limits<FloatType>::infinity() || y == -sprout::numeric_limits<FloatType>::infinity() ? sprout::numeric_limits<FloatType>::infinity() : x == sprout::numeric_limits<FloatType>::infinity() || x == -sprout::numeric_limits<FloatType>::infinity() ? sprout::numeric_limits<FloatType>::infinity() : sprout::math::isnan(y) ? y : sprout::math::isnan(x) ? x #if SPROUT_USE_BUILTIN_CMATH_FUNCTION : sprout::math::detail::builtin_hypot(x, y) #else : y == 0 ? sprout::math::fabs(x) : x == 0 ? sprout::math::fabs(y) : static_cast<FloatType>(sprout::math::detail::hypot_impl( static_cast<typename sprout::math::detail::float_compute<FloatType>::type>(x), static_cast<typename sprout::math::detail::float_compute<FloatType>::type>(y) )) #endif ; } template< typename ArithmeticType1, typename ArithmeticType2, typename sprout::enabler_if< std::is_arithmetic<ArithmeticType1>::value && std::is_arithmetic<ArithmeticType2>::value >::type = sprout::enabler > inline SPROUT_CONSTEXPR typename sprout::float_promote<ArithmeticType1, ArithmeticType2>::type hypot(ArithmeticType1 x, ArithmeticType2 y) { typedef typename sprout::float_promote<ArithmeticType1, ArithmeticType2>::type type; return sprout::math::hypot(static_cast<type>(x), static_cast<type>(y)); } } // namespace math using sprout::math::hypot; } // namespace sprout #endif // #ifndef SPROUT_MATH_HYPOT_HPP
34.603774
116
0.658124
kevcadieux
4111dd3dc5cdb199aedbd4e64a8eb14472cf0fd0
352
cpp
C++
QtCases/main.cpp
TsyQi/MyAutomatic
2afd3dcabba818051c7119fac7e6c099ff7954a7
[ "Apache-2.0" ]
4
2016-08-19T08:16:49.000Z
2020-04-15T12:30:25.000Z
QtCases/main.cpp
TsyQi/Auto-control
d0dda0752d53d28f358346ee7ab217bf05118c96
[ "Apache-2.0" ]
null
null
null
QtCases/main.cpp
TsyQi/Auto-control
d0dda0752d53d28f358346ee7ab217bf05118c96
[ "Apache-2.0" ]
3
2019-03-23T03:40:24.000Z
2020-04-15T00:57:43.000Z
#include <QtPlugin> #include <QtWidgets/qmessagebox.h> #include "OpenGLWindow.h" // Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin) #ifdef _WIN32 extern "C" __declspec(dllexport) #endif int main(int argc, char *argv[]) { QApplication a(argc, argv); OpenGLWindow w("flappy TRIANGLE"); a.setActiveWindow(&w); w.show(); return a.exec(); }
20.705882
45
0.704545
TsyQi
4113ad6ad1fb5a9660bf88d48bf1f480d0d14dd6
8,658
cc
C++
flare/rpc/trackme.cc
flare-rpc/flare-cpp
c1630c7eb8bae0a0b0cee6ec3f13f1babeaef950
[ "Apache-2.0" ]
3
2022-01-23T17:55:24.000Z
2022-03-23T12:55:18.000Z
flare/rpc/trackme.cc
flare-rpc/flare-cpp
c1630c7eb8bae0a0b0cee6ec3f13f1babeaef950
[ "Apache-2.0" ]
null
null
null
flare/rpc/trackme.cc
flare-rpc/flare-cpp
c1630c7eb8bae0a0b0cee6ec3f13f1babeaef950
[ "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 _GNU_SOURCE #define _GNU_SOURCE #endif #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <pwd.h> #include "flare/base/fast_rand.h" #include "flare/rpc/log.h" #include "flare/rpc/channel.h" #include "flare/rpc/trackme.pb.h" #include "flare/rpc/policy/hasher.h" #include "flare/base/scoped_file.h" namespace flare::rpc { DEFINE_string(trackme_server, "", "Where the TrackMe requests are sent to"); static const int32_t TRACKME_MIN_INTERVAL = 30; static const int32_t TRACKME_MAX_INTERVAL = 600; static int32_t s_trackme_interval = TRACKME_MIN_INTERVAL; // Protecting global vars on trackme static pthread_mutex_t s_trackme_mutex = PTHREAD_MUTEX_INITIALIZER; // For contacting with trackme_server. static Channel* s_trackme_chan = NULL; // Any server address in this process. static std::string* s_trackme_addr = NULL; // Information of bugs. // Notice that this structure may be a combination of all affected bugs. // Namely `severity' is severity of the worst bug and `error_text' is // combination of descriptions of all bugs. Check tools/trackme_server // for impl. details. struct BugInfo { TrackMeSeverity severity; std::string error_text; bool operator==(const BugInfo& bug) const { return severity == bug.severity && error_text == bug.error_text; } }; // If a bug was shown, its info was stored in this var as well so that we // can avoid showing the same bug repeatly. static BugInfo* g_bug_info = NULL; // The timestamp(microseconds) that we sent TrackMeRequest. static int64_t s_trackme_last_time = 0; // version of RPC. // Since the code for getting FLARE_RPC_REVISION often fails, // FLARE_RPC_REVISION must be defined to string and be converted to number // within our code. // The code running before main() may see g_rpc_version=0, should be OK. #if defined(FLARE_RPC_REVISION) const int64_t g_rpc_version = atoll(FLARE_RPC_REVISION); #else const int64_t g_rpc_version = 0; #endif int ReadJPaasHostPort(int container_port) { const uid_t uid = getuid(); struct passwd* pw = getpwuid(uid); if (pw == NULL) { RPC_VLOG << "Fail to get password file entry of uid=" << uid; return -1; } char JPAAS_LOG_PATH[64]; snprintf(JPAAS_LOG_PATH, sizeof(JPAAS_LOG_PATH), "%s/jpaas_run/logs/env.log", pw->pw_dir); char* line = NULL; size_t line_len = 0; ssize_t nr = 0; flare::base::scoped_file fp(fopen(JPAAS_LOG_PATH, "r")); if (!fp) { RPC_VLOG << "Fail to open `" << JPAAS_LOG_PATH << '\''; return -1; } int host_port = -1; char prefix[32]; const int prefix_len = snprintf(prefix, sizeof(prefix), "JPAAS_HOST_PORT_%d=", container_port); while ((nr = getline(&line, &line_len, fp.get())) != -1) { if (line[nr - 1] == '\n') { // remove ending newline --nr; } if (nr > prefix_len && memcmp(line, prefix, prefix_len) == 0) { host_port = strtol(line + prefix_len, NULL, 10); break; } } free(line); RPC_VLOG_IF(host_port < 0) << "No entry starting with `" << prefix << "' found"; return host_port; } // Called in server.cpp void SetTrackMeAddress(flare::base::end_point pt) { FLARE_SCOPED_LOCK(s_trackme_mutex); if (s_trackme_addr == NULL) { // JPAAS has NAT capabilities, read its log to figure out the open port // accessible from outside. const int jpaas_port = ReadJPaasHostPort(pt.port); if (jpaas_port > 0) { RPC_VLOG << "Use jpaas_host_port=" << jpaas_port << " instead of jpaas_container_port=" << pt.port; pt.port = jpaas_port; } s_trackme_addr = new std::string(flare::base::endpoint2str(pt).c_str()); } } static void HandleTrackMeResponse(Controller* cntl, TrackMeResponse* res) { if (cntl->Failed()) { RPC_VLOG << "Fail to access " << FLAGS_trackme_server << ", " << cntl->ErrorText(); } else { BugInfo cur_info; cur_info.severity = res->severity(); cur_info.error_text = res->error_text(); bool already_reported = false; { FLARE_SCOPED_LOCK(s_trackme_mutex); if (g_bug_info != NULL && *g_bug_info == cur_info) { // we've shown the bug. already_reported = true; } else { // save the bug. if (g_bug_info == NULL) { g_bug_info = new BugInfo(cur_info); } else { *g_bug_info = cur_info; } } } if (!already_reported) { switch (res->severity()) { case TrackMeOK: break; case TrackMeFatal: LOG(ERROR) << "Your flare (r" << g_rpc_version << ") is affected by: " << res->error_text(); break; case TrackMeWarning: LOG(WARNING) << "Your flare (r" << g_rpc_version << ") is affected by: " << res->error_text(); break; default: LOG(WARNING) << "Unknown severity=" << res->severity(); break; } } if (res->has_new_interval()) { // We can't fully trust the result from trackme_server which may // have bugs. Make sure the reporting interval is not too short or // too long int32_t new_interval = res->new_interval(); new_interval = std::max(new_interval, TRACKME_MIN_INTERVAL); new_interval = std::min(new_interval, TRACKME_MAX_INTERVAL); if (new_interval != s_trackme_interval) { s_trackme_interval = new_interval; RPC_VLOG << "Update s_trackme_interval to " << new_interval; } } } delete cntl; delete res; } static void TrackMeNow(std::unique_lock<pthread_mutex_t>& mu) { if (s_trackme_addr == NULL) { return; } if (s_trackme_chan == NULL) { Channel* chan = new (std::nothrow) Channel; if (chan == NULL) { LOG(FATAL) << "Fail to new trackme channel"; return; } ChannelOptions opt; // keep #connections on server-side low opt.connection_type = CONNECTION_TYPE_SHORT; if (chan->Init(FLAGS_trackme_server.c_str(), "c_murmurhash", &opt) != 0) { LOG(WARNING) << "Fail to connect to " << FLAGS_trackme_server; delete chan; return; } s_trackme_chan = chan; } mu.unlock(); TrackMeService_Stub stub(s_trackme_chan); TrackMeRequest req; req.set_rpc_version(g_rpc_version); req.set_server_addr(*s_trackme_addr); TrackMeResponse* res = new TrackMeResponse; Controller* cntl = new Controller; cntl->set_request_code(policy::MurmurHash32(s_trackme_addr->data(), s_trackme_addr->size())); google::protobuf::Closure* done = ::flare::rpc::NewCallback(&HandleTrackMeResponse, cntl, res); stub.TrackMe(cntl, &req, res, done); } // Called in global.cpp // [Thread-safe] supposed to be called in low frequency. void TrackMe() { if (FLAGS_trackme_server.empty()) { return; } int64_t now = flare::get_current_time_micros(); std::unique_lock<pthread_mutex_t> mu(s_trackme_mutex); if (s_trackme_last_time == 0) { // Delay the first ping randomly within s_trackme_interval. This // protects trackme_server from ping storms. s_trackme_last_time = now + flare::base::fast_rand_less_than(s_trackme_interval) * 1000000L; } if (now > s_trackme_last_time + 1000000L * s_trackme_interval) { s_trackme_last_time = now; return TrackMeNow(mu); } } } // namespace flare::rpc
36.378151
97
0.628205
flare-rpc
4115247034dedccdc7036b536c0539ca74cd831f
1,624
cpp
C++
Kattis/Promotions/solution.cpp
caando/Competitive-Programming-Archive
589781a23bda39aedf5fc437bf9b97c264fd3736
[ "MIT" ]
5
2021-09-09T09:16:29.000Z
2022-01-08T11:28:12.000Z
Kattis/Promotions/solution.cpp
zjk2606/Competitive-Programming-Archive
589781a23bda39aedf5fc437bf9b97c264fd3736
[ "MIT" ]
1
2021-09-09T09:16:26.000Z
2021-09-11T04:00:36.000Z
Kattis/Promotions/solution.cpp
zjk2606/Competitive-Programming-Archive
589781a23bda39aedf5fc437bf9b97c264fd3736
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ll = long long; using pii = pair<int, int>; using vi = vector<int>; using vii = vector<pii>; #define fi first #define se second #define sz(c) ((int)(c).size()) #define all(c) (c).begin(), (c).end() #define forn(i,m, n) for (int i = m, nnnn = (n); i < nnnn; ++i) #define pb push_back #define mp make_pair vector<int> child[5000], parent[5000]; bool counter[5000]; void getChild(int curr){ if (counter[curr] == true) return; counter[curr] = true; forn(i, 0, child[curr].size()){ getChild(child[curr][i]); } } void getParent(int curr){ if (counter[curr] == true) return; counter[curr] = true; forn(i, 0, parent[curr].size()){ getParent(parent[curr][i]); } } int main() { int a, b, e, p; cin >> a >> b >> e >> p; int res1[e], res2[e]; forn(i, 0, e) { res1[i] = 0; res2[i] = 0; } forn(i, 0, p){ int fi, se; cin >> fi >> se; child[fi].pb(se); parent[se].pb(fi); } forn(i, 0, e){ getChild(i); forn(j, 0, e) { if (counter[j] == true) { res1[i]++; counter[j] = false; } } getParent(i); forn(j, 0, e) { if (counter[j] == true) { res2[i]++; counter[j] = false; } } } int A = 0, B = 0, C =0; forn(i, 0, e) { if (e - res1[i] < a) A++; if (e - res1[i] < b) B++; if (res2[i] - 1 >= b) C++; } cout << '\n'; cout << A << '\n' << B << '\n' << C; }
22.873239
64
0.446429
caando
4116916a2efa8e26373674c468980243f492b96a
2,829
hpp
C++
engine/gems/sight/sop_transform.hpp
stereoboy/isaac_sdk_20191213
73c863254e626c8d498870189fbfb20be4e10fb3
[ "FSFAP" ]
1
2020-04-14T13:55:16.000Z
2020-04-14T13:55:16.000Z
engine/gems/sight/sop_transform.hpp
stereoboy/isaac_sdk_20191213
73c863254e626c8d498870189fbfb20be4e10fb3
[ "FSFAP" ]
4
2020-09-25T22:34:29.000Z
2022-02-09T23:45:12.000Z
engine/gems/sight/sop_transform.hpp
stereoboy/isaac_sdk_20191213
73c863254e626c8d498870189fbfb20be4e10fb3
[ "FSFAP" ]
1
2020-07-02T11:51:17.000Z
2020-07-02T11:51:17.000Z
/* Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited. */ #pragma once #include <string> #include <utility> #include "engine/core/math/pose2.hpp" #include "engine/core/math/pose3.hpp" #include "engine/core/optional.hpp" #include "engine/gems/geometry/pinhole.hpp" #include "engine/gems/serialization/json.hpp" #include "engine/gems/serialization/json_formatter.hpp" namespace isaac { namespace sight { // Sight Operations Transformation: // Contains the Pose2 or Pose3 transform as well as a scale factor class SopTransform { public: // Default constructor SopTransform() = default; // Creates a SopTransform using the canvas pixel frame (allow you to draw directly at a given // position on a canvas). // Note: this only works for 2D and the Sop will not be rendered in 3D. static SopTransform CanvasFrame() { SopTransform t; t.json_["t"] = "c"; return t; } // Creates a SopTransform using a reference frame SopTransform(const std::string& reference_frame) { json_["t"] = "f"; json_["f"] = reference_frame; } // Creates a SopTransform using a Pose2 template <typename K> SopTransform(const Pose2<K>& pose) { json_["t"] = "2d"; serialization::Set(json_["p"], pose); } // Creates a SopTransform using a Pose3 template <typename K> SopTransform(const Pose3<K>& pose) { json_["t"] = "3d"; serialization::Set(json_["p"], pose); } // Creates a transform with a Pose and a scale template <typename Pose> SopTransform(const Pose& pose, double scale) : SopTransform(pose) { json_["s"] = scale; } // Creates a transform with a Pose and a pinhole projection template <typename Pose, typename K> SopTransform(const Pose& pose, const geometry::Pinhole<K>& pinhole) : SopTransform(pose) { Json proj; proj["c0"] = pinhole.center[0]; proj["c1"] = pinhole.center[1]; proj["f0"] = pinhole.focal[0]; proj["f1"] = pinhole.focal[1]; json_["proj"] = proj; } // Creates a transform with a Pose and a scale template <typename Pose, typename K> SopTransform(const Pose& pose, double scale, const geometry::Pinhole<K>& pinhole) : SopTransform(pose, pinhole) { json_["s"] = scale; } private: friend const Json& ToJson(const SopTransform&); friend Json ToJson(SopTransform&&); Json json_; }; // Returns the json of a SopTransform const Json& ToJson(const SopTransform&); Json ToJson(SopTransform&&); } // namespace sight } // namespace isaac
28.867347
95
0.707317
stereoboy
411a4f12928dd8dc223a4a428573a20bd1f5c46c
5,562
cpp
C++
format/tables/TableFactory.cpp
eladraz/morph
e80b93af449471fb2ca9e256188f9a92f631fbc2
[ "BSD-3-Clause" ]
4
2017-01-24T09:32:23.000Z
2021-08-20T03:29:54.000Z
format/tables/TableFactory.cpp
eladraz/morph
e80b93af449471fb2ca9e256188f9a92f631fbc2
[ "BSD-3-Clause" ]
null
null
null
format/tables/TableFactory.cpp
eladraz/morph
e80b93af449471fb2ca9e256188f9a92f631fbc2
[ "BSD-3-Clause" ]
1
2021-08-20T03:29:55.000Z
2021-08-20T03:29:55.000Z
/* * Copyright (c) 2008-2016, Integrity Project Ltd. 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 Integrity Project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE */ /* * TableFactory.cpp * * Implementation file * * Author: Elad Raz <e@eladraz.com> */ #include "xStl/types.h" #include "xStl/data/smartptr.h" #include "xStl/data/datastream.h" #include "xStl/stream/traceStream.h" #include "format/EncodingUtils.h" #include "format/tables/TablesID.h" #include "format/tables/TableFactory.h" #include "format/tables/ModuleTable.h" #include "format/tables/TyperefTable.h" #include "format/tables/TypedefTable.h" #include "format/tables/FieldTable.h" #include "format/tables/FieldRVATable.h" #include "format/tables/MethodTable.h" #include "format/tables/ParamTable.h" #include "format/tables/MemberRefTable.h" #include "format/tables/ConstantTable.h" #include "format/tables/InterfaceImplTable.h" #include "format/tables/CustomAttributeTable.h" #include "format/tables/ClassLayoutTable.h" #include "format/tables/DeclSecurityTable.h" #include "format/tables/StandAloneSigTable.h" #include "format/tables/PropertyMapTable.h" #include "format/tables/PropertyTable.h" #include "format/tables/MethodSemanticsTable.h" #include "format/tables/MethodImplTable.h" #include "format/tables/TypeSpecTable.h" #include "format/tables/AssemblyTable.h" #include "format/tables/AssemblyRefTable.h" #include "format/tables/NestedClassTable.h" #include "format/tables/GenericParamTable.h" #include "format/tables/MethodSpecTable.h" TablePtr TableFactory::readTable(MetadataStream& stream, uint id, uint tablePosition) { mdToken newToken = EncodingUtils::buildToken(id, tablePosition + 1); switch (id) { case TABLE_MODULE_TABLE: return TablePtr(new ModuleTable(stream, newToken)); case TABLE_TYPEREF_TABLE: return TablePtr(new TyperefTable(stream, newToken)); case TABLE_TYPEDEF_TABLE: return TablePtr(new TypedefTable(stream, newToken)); case TABLE_FIELD_TABLE: return TablePtr(new FieldTable(stream, newToken)); case TABLE_METHOD_TABLE: return TablePtr(new MethodTable(stream, newToken)); case TABLE_PARAM_TABLE: return TablePtr(new ParamTable(stream, newToken)); case TABLE_INTERFACEIMPL_TABLE: return TablePtr(new InterfaceImplTable(stream, newToken)); case TABLE_MEMBERREF_TABLE: return TablePtr(new MemberRefTable(stream, newToken)); case TABLE_CONSTANT_TABLE: return TablePtr(new ConstantTable(stream, newToken)); case TABLE_CUSTOMATTRIBUTE_TABLE: return TablePtr(new CustomAttributeTable(stream, newToken)); case TABLE_DECLSECURITY_TABLE: return TablePtr(new DeclSecurityTable(stream, newToken)); case TABLE_CLASSLAYOUT_TABLE: return TablePtr(new ClassLayoutTable(stream, newToken)); case TABLE_STANDALONGESIG_TABLE: return TablePtr(new StandAloneSigTable(stream, newToken)); case TABLE_PROPERTYMAP_TABLE: return TablePtr(new PropertyMapTable(stream, newToken)); case TABLE_PROPERTY_TABLE: return TablePtr(new PropertyTable(stream, newToken)); case TABLE_METHODSEMANTICS_TABLE: return TablePtr(new MethodSemanticsTable(stream, newToken)); case TABLE_METHODIMPL_TABLE: return TablePtr(new MethodImplTable(stream, newToken)); case TABLE_TYPESPEC_TABLE: return TablePtr(new TypeSpecTable(stream, newToken)); case TABLE_FIELDRVA_TABLE: return TablePtr(new FieldRVATable(stream, newToken)); case TABLE_ASSEMBLY_TABLE: return TablePtr(new AssemblyTable(stream, newToken)); case TABLE_ASSEMBLYREF_TABLE: return TablePtr(new AssemblyRefTable(stream, newToken)); case TABLE_NESTEDCLASS_TABLE: return TablePtr(new NestedClassTable(stream, newToken)); case TABLE_GENERICPARAM_TABLE: return TablePtr(new GenericParamTable(stream, newToken)); case TABLE_METHODSPEC_TABLE: return TablePtr(new MethodSpecTable(stream, newToken)); default: // The table #id is not ready or unknown... traceHigh("Cannot parse CLR file table: " << HEXDWORD(id) << endl); CHECK_FAIL(); } }
50.108108
98
0.759259
eladraz
411eddbb6ede14e3628bb7356455a8b6a0716873
2,038
cpp
C++
Classes/UI/Chooser.cpp
FrSanchez/snake
4e2260d0784cd90ddf28a9f209b0d00da3cf66d0
[ "MIT" ]
null
null
null
Classes/UI/Chooser.cpp
FrSanchez/snake
4e2260d0784cd90ddf28a9f209b0d00da3cf66d0
[ "MIT" ]
null
null
null
Classes/UI/Chooser.cpp
FrSanchez/snake
4e2260d0784cd90ddf28a9f209b0d00da3cf66d0
[ "MIT" ]
null
null
null
// // Chooser.cpp // cocos2d // // Created by Francisco Sanchez on 2/11/21. // #include "Chooser.h" USING_NS_CC; bool Chooser::init() { auto numLabel = Label::createWithTTF("1", "Arcade.ttf", 96); numLabel->setTextColor(Color4B::WHITE); numLabel->enableOutline(Color4B::GRAY, 5); numLabel->setAlignment(TextHAlignment::CENTER, TextVAlignment::CENTER); auto downNormal = Sprite::createWithSpriteFrameName("LeftNormal"); auto downSelected = Sprite::createWithSpriteFrameName("LeftSelected"); auto downItem = MenuItemSprite::create(downNormal, downSelected, CC_CALLBACK_1(Chooser::upDownCallback, this)); auto upNormal = Sprite::createWithSpriteFrameName("RightNormal"); auto upSelected = Sprite::createWithSpriteFrameName("RightSelected"); auto upItem = MenuItemSprite::create(upNormal, upSelected, CC_CALLBACK_1(Chooser::upDownCallback, this)); auto menuChoose = Menu::create(downItem, upItem, nullptr); menuChoose->setAnchorPoint(Vec2::ANCHOR_MIDDLE); downItem->setAnchorPoint(Vec2::ANCHOR_MIDDLE); upItem->setAnchorPoint(Vec2::ANCHOR_MIDDLE); upItem->setTag(1); downItem->setTag(-1); addChild(menuChoose); addChild(numLabel); upItem->setUserData(numLabel); downItem->setUserData(numLabel); upItem->setPosition(Vec2(100,0)); downItem->setPosition(Vec2(-100,0)); menuChoose->setPosition(Vec2::ZERO); numLabel->setPosition(Vec2::ZERO); return true; } void Chooser::upDownCallback(cocos2d::Ref* pSender) { MenuItem *item = static_cast<MenuItem*>(pSender); _value += item->getTag(); if (_value < _minValue) { _value = _maxValue; } if (_value > _maxValue) { _value = _minValue; } Label* numLabel = static_cast<Label*>(item->getUserData()); numLabel->setString(StringUtils::format("%d", _value)); if (_callback != nullptr) { _callback(_value); } } void Chooser::setMaxValue(int value) { _maxValue = value; } Chooser::~Chooser() { }
27.540541
115
0.682532
FrSanchez
4124cc1897b4792aecf6be34bbf76782675087c5
1,293
hpp
C++
include/RED4ext/Scripting/Natives/Generated/AI/behavior/DriveToNodeTreeNodeDefinition.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
42
2020-12-25T08:33:00.000Z
2022-03-22T14:47:07.000Z
include/RED4ext/Scripting/Natives/Generated/AI/behavior/DriveToNodeTreeNodeDefinition.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
38
2020-12-28T22:36:06.000Z
2022-02-16T11:25:47.000Z
include/RED4ext/Scripting/Natives/Generated/AI/behavior/DriveToNodeTreeNodeDefinition.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
20
2020-12-28T22:17:38.000Z
2022-03-22T17:19:01.000Z
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/Handle.hpp> #include <RED4ext/Scripting/Natives/Generated/AI/behavior/DriveTreeNodeDefinition.hpp> namespace RED4ext { namespace AI { struct ArgumentMapping; } namespace AI::behavior { struct DriveToNodeTreeNodeDefinition : AI::behavior::DriveTreeNodeDefinition { static constexpr const char* NAME = "AIbehaviorDriveToNodeTreeNodeDefinition"; static constexpr const char* ALIAS = NAME; Handle<AI::ArgumentMapping> useKinematic; // 40 Handle<AI::ArgumentMapping> needDriver; // 50 Handle<AI::ArgumentMapping> nodeRef; // 60 Handle<AI::ArgumentMapping> stopAtPathEnd; // 70 Handle<AI::ArgumentMapping> secureTimeOut; // 80 Handle<AI::ArgumentMapping> isPlayer; // 90 Handle<AI::ArgumentMapping> useTraffic; // A0 Handle<AI::ArgumentMapping> speedInTraffic; // B0 Handle<AI::ArgumentMapping> forceGreenLights; // C0 Handle<AI::ArgumentMapping> portals; // D0 Handle<AI::ArgumentMapping> trafficTryNeighborsForStart; // E0 Handle<AI::ArgumentMapping> trafficTryNeighborsForEnd; // F0 }; RED4EXT_ASSERT_SIZE(DriveToNodeTreeNodeDefinition, 0x100); } // namespace AI::behavior } // namespace RED4ext
35.916667
86
0.75406
jackhumbert
412c478823e481e9203655721ddd076708469c4b
467
cpp
C++
Greedy Algorithms/activity_scheduling1.cpp
Reactor11/Data-Structures-Practice
30d758aaece930e27585f9f7a2f904e74925516b
[ "MIT" ]
null
null
null
Greedy Algorithms/activity_scheduling1.cpp
Reactor11/Data-Structures-Practice
30d758aaece930e27585f9f7a2f904e74925516b
[ "MIT" ]
null
null
null
Greedy Algorithms/activity_scheduling1.cpp
Reactor11/Data-Structures-Practice
30d758aaece930e27585f9f7a2f904e74925516b
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int main(){ int n; cin>>n; int start[n],end[n]; for(int i=0;i<n;i++) cin>>start[i]; for(int i=0;i<n;i++) cin>>end[i]; int count=1,finish=end[0]; cout<<count<<" "; for(int i=1;i<n;i++) if(start[i] >= finish){ cout<<i+1<<" "; // gives activity number count++; finish = end[i]; } cout<<endl; cout<<"Number of activity : "<<count<<endl; }
23.35
52
0.488223
Reactor11
412fb0da32010ac304b12e1c9e108af3a73bd05f
614
cpp
C++
src/core/p_render/render_graph/resources/RenderResource.cpp
jabronicus/P-Engine
7786c2f97d19bd2913b706f6afe5087a392b1a3c
[ "MIT" ]
null
null
null
src/core/p_render/render_graph/resources/RenderResource.cpp
jabronicus/P-Engine
7786c2f97d19bd2913b706f6afe5087a392b1a3c
[ "MIT" ]
null
null
null
src/core/p_render/render_graph/resources/RenderResource.cpp
jabronicus/P-Engine
7786c2f97d19bd2913b706f6afe5087a392b1a3c
[ "MIT" ]
1
2021-08-24T05:43:01.000Z
2021-08-24T05:43:01.000Z
#include "../../../../../include/core/p_render/render_graph/resources/RenderResource.hpp" RenderResource::RenderResource(RenderResource::Type type, unsigned int index, const std::string &name) : _type(type), _index(index), _name(name) { } void RenderResource::addWritePass(unsigned int index) { _writePasses.insert(index); } void RenderResource::addReadPass(unsigned int index) { _readPasses.insert(index); } std::unordered_set<unsigned int> &RenderResource::getWritePasses() { return _writePasses; } std::unordered_set<unsigned int> &RenderResource::getReadPasses() { return _readPasses; }
26.695652
146
0.7443
jabronicus
41372fe5a4e67928b8a773b3b884581435962b33
593
cpp
C++
kernel/acpi.cpp
Ampferl/jonix
75dc24187b96eb50f210b4362775c04b77844946
[ "MIT" ]
7
2021-03-23T16:45:41.000Z
2022-01-04T16:26:56.000Z
kernel/acpi.cpp
Ampferl/jonix
75dc24187b96eb50f210b4362775c04b77844946
[ "MIT" ]
5
2021-03-29T07:09:43.000Z
2021-07-23T22:47:58.000Z
kernel/acpi.cpp
Ampferl/jonix
75dc24187b96eb50f210b4362775c04b77844946
[ "MIT" ]
4
2021-06-25T17:25:45.000Z
2021-07-23T13:05:25.000Z
#include "acpi.h" namespace ACPI{ void* FindTable(SDTHeader* sdtHeader, char* signature){ int entries = (sdtHeader->Length - sizeof(ACPI::SDTHeader)) / 8; for (int t = 0; t < entries; ++t) { ACPI::SDTHeader* newSDTHeader = (ACPI::SDTHeader*)*(uint64_t*)((uint64_t)sdtHeader + sizeof(ACPI::SDTHeader) + (t * 8)); for (int i = 0; i < 4; ++i) { if(newSDTHeader->Signature[i] != signature[i]){ break; } if(i==3)return newSDTHeader; } } return 0; } }
29.65
132
0.495784
Ampferl
4142a30226da6ff8ae62cb02e8f3d40acdfa51a7
2,736
cpp
C++
BallsToTheWall/src/ParticleSystem.cpp
JackiBackiBoy/BallsToTheWall
9a18e3772e1ad2213e2282c59691818305088059
[ "Apache-2.0" ]
null
null
null
BallsToTheWall/src/ParticleSystem.cpp
JackiBackiBoy/BallsToTheWall
9a18e3772e1ad2213e2282c59691818305088059
[ "Apache-2.0" ]
null
null
null
BallsToTheWall/src/ParticleSystem.cpp
JackiBackiBoy/BallsToTheWall
9a18e3772e1ad2213e2282c59691818305088059
[ "Apache-2.0" ]
null
null
null
#include "ParticleSystem.h" #include "TimeTracker.h" #include "Random.h" #include "math\Math.h" #include "SFML/System/Clock.hpp" #include "Sandbox.h" sf::Clock tempClock = sf::Clock(); ParticleSystem::ParticleSystem(const unsigned int& aParticleCount) { myParticles.resize(aParticleCount); } void ParticleSystem::OnUpdate() { for (auto& p : myParticles) { if (!p.Active) continue; p.LifeRemaining -= TimeTracker::GetUnscaledDeltaTime(); if (p.LifeRemaining <= 0.0f) { p.Active = false; continue; } p.Shape.move(p.Velocity * TimeTracker::GetUnscaledDeltaTime()); p.Shape.rotate(Math::ToDegrees(p.AngularVelocity * TimeTracker::GetUnscaledDeltaTime())); } } void ParticleSystem::OnRender(sf::RenderWindow* aWindow) { for (auto& p : myParticles) { if (!p.Active) continue; float tempLife = p.LifeRemaining / p.LifeTime; if (Sandbox::GetPack() == "Fun") { p.ColorBegin = Math::ShiftRainbow(p.ColorBegin, TimeTracker::GetUnscaledDeltaTime() * 500); } p.Shape.setFillColor(Math::Lerp(p.ColorEnd, p.ColorBegin, tempLife)); p.Shape.setScale(Math::Lerp(p.SizeEnd, p.SizeBegin, tempLife)); aWindow->draw(p.Shape); } } void ParticleSystem::Emit(const ParticleProps& someParticleProps) { Particle& tempP = myParticles[myParticleIndex]; tempP.Active = true; tempP.Velocity = someParticleProps.Velocity; tempP.Velocity.x += someParticleProps.VelocityVariation.x * (Random::Float() - 0.5f); tempP.Velocity.y += someParticleProps.VelocityVariation.y * (Random::Float() - 0.5f); tempP.AngularVelocity = someParticleProps.AngVel + someParticleProps.AngVelVariation * (Random::Float() - 0.5f); tempP.ColorBegin = someParticleProps.ColorBegin; tempP.ColorEnd = someParticleProps.ColorEnd; tempP.LifeTime = someParticleProps.LifeTime; tempP.LifeRemaining = someParticleProps.LifeTime; tempP.SizeBegin = someParticleProps.SizeBegin + someParticleProps.SizeVariation * (Random::Float() - 0.5f); tempP.SizeEnd = someParticleProps.SizeEnd; if (someParticleProps.Shape.getPointCount() == 0) { tempP.Shape = sf::ConvexShape(someParticleProps.PointCount); float tempAngleInc = Math::Pi * 2.f / tempP.Shape.getPointCount(); for (int i = 0; i < tempP.Shape.getPointCount(); i++) { tempP.Shape.setPoint(i, sf::Vector2f(cos(tempAngleInc * i), sin(tempAngleInc * i))); } } else tempP.Shape = someParticleProps.Shape; tempP.Shape.setPosition(someParticleProps.Position); tempP.Shape.setRotation(Math::ToDegrees(someParticleProps.Rotation + someParticleProps.RotationVariation * (Random::Float() - 0.5f))); if (myParticleIndex == 0) { myParticleIndex = myParticles.size() - 1; } else myParticleIndex--; } int ParticleSystem::GetSize() { return myParticles.size(); }
27.636364
135
0.729898
JackiBackiBoy
4144308d06f489eb002cbe3541de831492779f34
1,764
hpp
C++
src/standard/bits/DD_find_max.hpp
iDingDong/libDDCPP-old
841260fecc84330ff3bfffba7263f5318f0b4655
[ "BSD-3-Clause" ]
1
2018-06-01T03:29:34.000Z
2018-06-01T03:29:34.000Z
src/standard/bits/DD_find_max.hpp
iDingDong/libDDCPP-old
841260fecc84330ff3bfffba7263f5318f0b4655
[ "BSD-3-Clause" ]
null
null
null
src/standard/bits/DD_find_max.hpp
iDingDong/libDDCPP-old
841260fecc84330ff3bfffba7263f5318f0b4655
[ "BSD-3-Clause" ]
null
null
null
// DDCPP/standard/bits/DD_find_max.hpp #ifndef DD_FIND_MAX_HPP_INCLUDED_ # define DD_FIND_MAX_HPP_INCLUDED_ 1 # include "DD_Iterator.hpp" # include "DD_Range.hpp" # include "DD_LessThan.hpp" DD_DETAIL_BEGIN_ template <typename UndirectionalIteratorT_, typename BinaryPredicateT_> UndirectionalIteratorT_ find_max( UndirectionalIteratorT_ begin__, UndirectionalIteratorT_ end__, BinaryPredicateT_ less__ ) DD_NOEXCEPT_AS(++begin__ != end__ && less__(*begin__, *begin__)) { if (begin__ != end__) { for (UndirectionalIteratorT_ current__(begin__); ++current__ != end__; ) { if (less__(*begin__, *current__)) { begin__ = current__; } } } return begin__; } template <typename UndirectionalIteratorT_> inline UndirectionalIteratorT_ find_max( UndirectionalIteratorT_ begin__, UndirectionalIteratorT_ end__ ) DD_NOEXCEPT_AS(static_cast<UndirectionalIteratorT_>( ::DD::detail_::find_max(begin__ DD_COMMA end__ DD_COMMA less_than) )) { return ::DD::detail_::find_max(begin__, end__, less_than); } template <typename UndirectionalRangeT_, typename BinaryPredicateT_> inline DD_MODIFY_TRAIT(Iterator, UndirectionalRangeT_) find_max( UndirectionalRangeT_& range__, BinaryPredicateT_ less__ ) DD_NOEXCEPT_AS(::DD::detail_::find_max(DD_SPLIT_RANGE(range__) DD_COMMA less__)) { return ::DD::detail_::find_max(DD_SPLIT_RANGE(range__), less__); } template <typename UndirectionalRangeT_> inline DD_MODIFY_TRAIT(Iterator, UndirectionalRangeT_) find_max( UndirectionalRangeT_& range__ ) DD_NOEXCEPT_AS(static_cast<DD_MODIFY_TRAIT(Iterator, UndirectionalRangeT_)>( ::DD::detail_::find_max(range__, less_than) )) { return ::DD::detail_::find_max(range__, less_than); } DD_DETAIL_END_ DD_BEGIN_ using detail_::find_max; DD_END_ #endif
24.164384
84
0.790249
iDingDong
414e9cb32d6ebfc04a1754091e33b0c03f70c528
596
hpp
C++
wrapper/bindings/utility.hpp
Karanlos/gli-rs
494a2dfec786824a5c3fcc5eb21c5d786076a48f
[ "MIT" ]
null
null
null
wrapper/bindings/utility.hpp
Karanlos/gli-rs
494a2dfec786824a5c3fcc5eb21c5d786076a48f
[ "MIT" ]
null
null
null
wrapper/bindings/utility.hpp
Karanlos/gli-rs
494a2dfec786824a5c3fcc5eb21c5d786076a48f
[ "MIT" ]
null
null
null
#include <glm/gtc/epsilon.hpp> extern "C" { namespace bindings { struct TexelType4F { float content[4]; }; TexelType4F vec4ToTex4F(gli::vec4 raw) { TexelType4F value; value.content[0] = raw[0]; value.content[1] = raw[1]; value.content[2] = raw[2]; value.content[3] = raw[3]; return value; } } } namespace gli { gli::vec4 tex4FToVec4(bindings::TexelType4F raw) { return gli::vec4(raw.content[0], raw.content[1], raw.content[2], raw.content[3]); } }
19.866667
89
0.525168
Karanlos
4151c5492f764904c167f82d37088d71179cb616
9,871
cpp
C++
tests/tests/result_tests/when_any_tests.cpp
PazerOP/concurrencpp
fbc8c475d5a534c5d222d9b241ad9299f2413969
[ "MIT" ]
1
2020-10-29T21:43:36.000Z
2020-10-29T21:43:36.000Z
tests/tests/result_tests/when_any_tests.cpp
PazerOP/concurrencpp
fbc8c475d5a534c5d222d9b241ad9299f2413969
[ "MIT" ]
null
null
null
tests/tests/result_tests/when_any_tests.cpp
PazerOP/concurrencpp
fbc8c475d5a534c5d222d9b241ad9299f2413969
[ "MIT" ]
null
null
null
#include "concurrencpp.h" #include "../all_tests.h" #include "../test_utils/test_ready_result.h" #include "../test_utils/executor_shutdowner.h" #include "../../tester/tester.h" #include "../../helpers/assertions.h" #include "../../helpers/random.h" #include "../../helpers/object_observer.h" namespace concurrencpp::tests { template<class type> void test_when_any_vector_empty_result(); template<class type> void test_when_any_vector_empty_range(); template<class type> result<void> test_when_any_vector_valid(std::shared_ptr<thread_executor> ex); template<class type> void test_when_any_vector_impl(); void test_when_any_vector(); void test_when_any_tuple_empty_result(); result<void> test_when_any_tuple_impl(std::shared_ptr<thread_executor> ex); void test_when_any_tuple(); } template <class type> void concurrencpp::tests::test_when_any_vector_empty_result() { const size_t task_count = 63; std::vector<result_promise<type>> result_promises(task_count); std::vector<result<type>> results; for (auto& rp : result_promises) { results.emplace_back(rp.get_result()); } results.emplace_back(); assert_throws_with_error_message<errors::empty_result>( [&] { concurrencpp::when_any(results.begin(), results.end()); }, concurrencpp::details::consts::k_when_any_empty_result_error_msg); const auto all_valid = std::all_of( results.begin(), results.begin() + task_count, [](const auto& result) { return static_cast<bool>(result); }); assert_true(all_valid); } template <class type> void concurrencpp::tests::test_when_any_vector_empty_range() { std::vector<result<type>> empty_range; assert_throws_with_error_message<std::invalid_argument>([&] { when_any(empty_range.begin(), empty_range.end()); }, concurrencpp::details::consts::k_when_any_empty_range_error_msg); } template<class type> concurrencpp::result<void> concurrencpp::tests::test_when_any_vector_valid(std::shared_ptr<thread_executor> ex) { const size_t task_count = 64; auto values = result_factory<type>::get_many(task_count); std::vector<result<type>> results; random randomizer; for (size_t i = 0; i < task_count; i++) { const auto time_to_sleep = randomizer(10, 100); results.emplace_back(ex->submit([i, time_to_sleep, &values]() -> type { (void)values; std::this_thread::sleep_for(std::chrono::milliseconds(time_to_sleep)); if (i % 4 == 0) { throw costume_exception(i); } if constexpr (!std::is_same_v<void, type>) { return values[i]; } })); } auto any_done = co_await when_any(results.begin(), results.end()); auto& done_result = any_done.results[any_done.index]; const auto all_valid = std::all_of( any_done.results.begin(), any_done.results.end(), [](const auto& result) { return static_cast<bool>(result); }); assert_true(all_valid); if (any_done.index % 4 == 0) { test_ready_result_costume_exception(std::move(done_result), any_done.index); } else { if constexpr (std::is_same_v<void, type>) { test_ready_result_result(std::move(done_result)); } else { test_ready_result_result(std::move(done_result), values[any_done.index]); } } //the value vector is a local variable, tasks may outlive it. join them. for (auto& result : any_done.results) { if (!static_cast<bool>(result)) { continue; } co_await result.resolve(); } } template <class type> void concurrencpp::tests::test_when_any_vector_impl() { test_when_any_vector_empty_result<type>(); test_when_any_vector_empty_range<type>(); { auto thread_executor = std::make_shared<concurrencpp::thread_executor>(); executor_shutdowner es(thread_executor); test_when_any_vector_valid<type>(thread_executor).get(); } } void concurrencpp::tests::test_when_any_vector() { test_when_any_vector_impl<int>(); test_when_any_vector_impl<std::string>(); test_when_any_vector_impl<void>(); test_when_any_vector_impl<int&>(); test_when_any_vector_impl<std::string&>(); } void concurrencpp::tests::test_when_any_tuple_empty_result() { result_promise<int> rp_int; auto int_res = rp_int.get_result(); result_promise<std::string> rp_s; auto s_res = rp_s.get_result(); result_promise<void> rp_void; auto void_res = rp_void.get_result(); result_promise<int&> rp_int_ref; auto int_ref_res = rp_int_ref.get_result(); result<std::string&> s_ref_res; assert_throws_with_error_message<errors::empty_result>( [&] { when_any( std::move(int_res), std::move(s_res), std::move(void_res), std::move(int_ref_res), std::move(s_ref_res)); }, concurrencpp::details::consts::k_when_any_empty_result_error_msg); //all pre-operation results are still valid assert_true(static_cast<bool>(int_res)); assert_true(static_cast<bool>(s_res)); assert_true(static_cast<bool>(void_res)); assert_true(static_cast<bool>(int_res)); } concurrencpp::result<void> concurrencpp::tests::test_when_any_tuple_impl(std::shared_ptr<thread_executor> ex) { std::atomic_size_t counter = 0; random randomizer; auto tts = randomizer(10,100); auto int_res_val = ex->submit([&counter, tts] { std::this_thread::sleep_for(std::chrono::milliseconds(tts)); counter.fetch_add(1, std::memory_order_relaxed); return result_factory<int>::get(); }); tts = randomizer(10, 100); auto int_res_ex = ex->submit([&counter, tts] { std::this_thread::sleep_for(std::chrono::milliseconds(tts)); counter.fetch_add(1, std::memory_order_relaxed); throw costume_exception(0); return result_factory<int>::get(); }); tts = randomizer(10, 100); auto s_res_val = ex->submit([&counter, tts]() -> std::string { std::this_thread::sleep_for(std::chrono::milliseconds(tts)); counter.fetch_add(1, std::memory_order_relaxed); return result_factory<std::string>::get(); }); tts = randomizer(10, 100); auto s_res_ex = ex->submit([&counter, tts]() -> std::string { std::this_thread::sleep_for(std::chrono::milliseconds(tts)); counter.fetch_add(1, std::memory_order_relaxed); throw costume_exception(1); return result_factory<std::string>::get(); }); tts = randomizer(10, 100); auto void_res_val = ex->submit([&counter, tts] { std::this_thread::sleep_for(std::chrono::milliseconds(tts)); counter.fetch_add(1, std::memory_order_relaxed); }); tts = randomizer(10, 100); auto void_res_ex = ex->submit([&counter, tts] { std::this_thread::sleep_for(std::chrono::milliseconds(tts)); counter.fetch_add(1, std::memory_order_relaxed); throw costume_exception(2); }); tts = randomizer(10, 100); auto int_ref_res_val = ex->submit([&counter, tts]() ->int& { std::this_thread::sleep_for(std::chrono::milliseconds(tts)); counter.fetch_add(1, std::memory_order_relaxed); return result_factory<int&>::get(); }); tts = randomizer(10, 100); auto int_ref_res_ex = ex->submit([&counter, tts]() ->int& { std::this_thread::sleep_for(std::chrono::milliseconds(tts)); counter.fetch_add(1, std::memory_order_relaxed); throw costume_exception(3); return result_factory<int&>::get(); }); tts = randomizer(10, 100); auto s_ref_res_val = ex->submit([&counter, tts]() -> std::string& { std::this_thread::sleep_for(std::chrono::milliseconds(tts)); counter.fetch_add(1, std::memory_order_relaxed); return result_factory<std::string&>::get(); }); tts = randomizer(10, 100); auto s_ref_res_ex = ex->submit([&counter, tts]() -> std::string& { std::this_thread::sleep_for(std::chrono::milliseconds(tts)); counter.fetch_add(1, std::memory_order_relaxed); throw costume_exception(4); return result_factory<std::string&>::get(); }); auto any_done = co_await when_any( std::move(int_res_val), std::move(int_res_ex), std::move(s_res_val), std::move(s_res_ex), std::move(void_res_val), std::move(void_res_ex), std::move(int_ref_res_val), std::move(int_ref_res_ex), std::move(s_ref_res_val), std::move(s_ref_res_ex)); assert_bigger_equal(counter.load(std::memory_order_relaxed), size_t(1)); switch (any_done.index) { case 0: { test_ready_result_result(std::move(std::get<0>(any_done.results)), result_factory<int>::get()); break; } case 1: { test_ready_result_costume_exception(std::move(std::get<1>(any_done.results)), 0); break; } case 2: { test_ready_result_result(std::move(std::get<2>(any_done.results)), result_factory<std::string>::get()); break; } case 3: { test_ready_result_costume_exception(std::move(std::get<3>(any_done.results)), 1); break; } case 4: { test_ready_result_result(std::move(std::get<4>(any_done.results))); break; } case 5: { test_ready_result_costume_exception(std::move(std::get<5>(any_done.results)), 2); break; } case 6: { test_ready_result_result(std::move(std::get<6>(any_done.results)), result_factory<int&>::get()); break; } case 7: { test_ready_result_costume_exception(std::move(std::get<7>(any_done.results)), 3); break; } case 8: { test_ready_result_result(std::move(std::get<8>(any_done.results)), result_factory<std::string&>::get()); break; } case 9: { test_ready_result_costume_exception(std::move(std::get<9>(any_done.results)), 4); break; } default: { assert_false(true); } } auto wait = [](auto& result) { if (static_cast<bool>(result)) { result.wait(); } }; std::apply([wait](auto&... results) {(wait(results), ...); }, any_done.results); } void concurrencpp::tests::test_when_any_tuple() { test_when_any_tuple_empty_result(); { auto thread_executor = std::make_shared<concurrencpp::thread_executor>(); executor_shutdowner es(thread_executor); test_when_any_tuple_impl(thread_executor).get(); } } void concurrencpp::tests::test_when_any() { tester test("when_any test"); test.add_step("when_any(begin, end)", test_when_any_vector); test.add_step("when_any(result_types&& ... results)", test_when_any_tuple); test.launch_test(); }
27.495822
107
0.714315
PazerOP
a9910a040a66f02b9a400c54c40bdaa89c9e0521
873
hpp
C++
builder/include/builder/CarBuilder.hpp
hwnBEAST/cpp_design_patterns
42e04644a9c4ce8ff8bafefd37b2cee8d0628f45
[ "MIT" ]
null
null
null
builder/include/builder/CarBuilder.hpp
hwnBEAST/cpp_design_patterns
42e04644a9c4ce8ff8bafefd37b2cee8d0628f45
[ "MIT" ]
null
null
null
builder/include/builder/CarBuilder.hpp
hwnBEAST/cpp_design_patterns
42e04644a9c4ce8ff8bafefd37b2cee8d0628f45
[ "MIT" ]
null
null
null
/** * @file * * @brief * * @copyright Copyright (C) 2021. Full licence notice is in the LICENCE file. */ #pragma once #include "builder/Car.hpp" #include <cstdint> #include <string> namespace Builder { class CarBuilder { public: /*--- Constructors ---*/ CarBuilder(const CarBuilder& other) = delete; CarBuilder& operator=(const CarBuilder& other) = delete; CarBuilder(); /*--- Methods ---*/ Builder::CarBuilder& color(Car::Color newColor); Builder::CarBuilder& numberOfPassengers(std::uint8_t newNumberOfPassengers); Builder::CarBuilder& ownerName(std::string newOwnerName); Builder::CarBuilder& topSpeedKiloMperH(uint32_t newTopSpeed); Builder::CarBuilder& manufacturerName(std::string newName); Builder::CarBuilder& modelName(std::string newName); Car build(); private: Car car; }; } // namespace Builder
21.825
80
0.689576
hwnBEAST
a9918e4f7a72bf0be080b310ff028b658ad8ef5e
8,353
cpp
C++
build/linux-build/Sources/src/zpp_nape/util/ZNPNode_ZPP_Constraint.cpp
HedgehogFog/TimeOfDeath
b78abacf940e1a88c8b987d99764ebb6876c5dc6
[ "MIT" ]
null
null
null
build/linux-build/Sources/src/zpp_nape/util/ZNPNode_ZPP_Constraint.cpp
HedgehogFog/TimeOfDeath
b78abacf940e1a88c8b987d99764ebb6876c5dc6
[ "MIT" ]
null
null
null
build/linux-build/Sources/src/zpp_nape/util/ZNPNode_ZPP_Constraint.cpp
HedgehogFog/TimeOfDeath
b78abacf940e1a88c8b987d99764ebb6876c5dc6
[ "MIT" ]
null
null
null
// Generated by Haxe 4.0.0-preview.5 #include <hxcpp.h> #ifndef INCLUDED_zpp_nape_constraint_ZPP_Constraint #include <hxinc/zpp_nape/constraint/ZPP_Constraint.h> #endif #ifndef INCLUDED_zpp_nape_util_ZNPNode_ZPP_Constraint #include <hxinc/zpp_nape/util/ZNPNode_ZPP_Constraint.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_985aee786169fab8_14943_new,"zpp_nape.util.ZNPNode_ZPP_Constraint","new",0xdd42d2a0,"zpp_nape.util.ZNPNode_ZPP_Constraint.new","zpp_nape/util/Lists.hx",14943,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_985aee786169fab8_14971_alloc,"zpp_nape.util.ZNPNode_ZPP_Constraint","alloc",0x59f7b6b5,"zpp_nape.util.ZNPNode_ZPP_Constraint.alloc","zpp_nape/util/Lists.hx",14971,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_985aee786169fab8_14975_free,"zpp_nape.util.ZNPNode_ZPP_Constraint","free",0xb7f5926c,"zpp_nape.util.ZNPNode_ZPP_Constraint.free","zpp_nape/util/Lists.hx",14975,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_985aee786169fab8_14982_elem,"zpp_nape.util.ZNPNode_ZPP_Constraint","elem",0xb747ce4f,"zpp_nape.util.ZNPNode_ZPP_Constraint.elem","zpp_nape/util/Lists.hx",14982,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_985aee786169fab8_14944_boot,"zpp_nape.util.ZNPNode_ZPP_Constraint","boot",0xb54e79f2,"zpp_nape.util.ZNPNode_ZPP_Constraint.boot","zpp_nape/util/Lists.hx",14944,0x9f4e6754) namespace zpp_nape{ namespace util{ void ZNPNode_ZPP_Constraint_obj::__construct(){ HX_STACKFRAME(&_hx_pos_985aee786169fab8_14943_new) HXLINE(14977) this->elt = null(); HXLINE(14968) this->next = null(); } Dynamic ZNPNode_ZPP_Constraint_obj::__CreateEmpty() { return new ZNPNode_ZPP_Constraint_obj; } void *ZNPNode_ZPP_Constraint_obj::_hx_vtable = 0; Dynamic ZNPNode_ZPP_Constraint_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< ZNPNode_ZPP_Constraint_obj > _hx_result = new ZNPNode_ZPP_Constraint_obj(); _hx_result->__construct(); return _hx_result; } bool ZNPNode_ZPP_Constraint_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x6111d1f2; } void ZNPNode_ZPP_Constraint_obj::alloc(){ HX_STACKFRAME(&_hx_pos_985aee786169fab8_14971_alloc) } HX_DEFINE_DYNAMIC_FUNC0(ZNPNode_ZPP_Constraint_obj,alloc,(void)) void ZNPNode_ZPP_Constraint_obj::free(){ HX_STACKFRAME(&_hx_pos_985aee786169fab8_14975_free) HXDLIN(14975) this->elt = null(); } HX_DEFINE_DYNAMIC_FUNC0(ZNPNode_ZPP_Constraint_obj,free,(void)) ::zpp_nape::constraint::ZPP_Constraint ZNPNode_ZPP_Constraint_obj::elem(){ HX_STACKFRAME(&_hx_pos_985aee786169fab8_14982_elem) HXDLIN(14982) return this->elt; } HX_DEFINE_DYNAMIC_FUNC0(ZNPNode_ZPP_Constraint_obj,elem,return ) ::zpp_nape::util::ZNPNode_ZPP_Constraint ZNPNode_ZPP_Constraint_obj::zpp_pool; hx::ObjectPtr< ZNPNode_ZPP_Constraint_obj > ZNPNode_ZPP_Constraint_obj::__new() { hx::ObjectPtr< ZNPNode_ZPP_Constraint_obj > __this = new ZNPNode_ZPP_Constraint_obj(); __this->__construct(); return __this; } hx::ObjectPtr< ZNPNode_ZPP_Constraint_obj > ZNPNode_ZPP_Constraint_obj::__alloc(hx::Ctx *_hx_ctx) { ZNPNode_ZPP_Constraint_obj *__this = (ZNPNode_ZPP_Constraint_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(ZNPNode_ZPP_Constraint_obj), true, "zpp_nape.util.ZNPNode_ZPP_Constraint")); *(void **)__this = ZNPNode_ZPP_Constraint_obj::_hx_vtable; __this->__construct(); return __this; } ZNPNode_ZPP_Constraint_obj::ZNPNode_ZPP_Constraint_obj() { } void ZNPNode_ZPP_Constraint_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(ZNPNode_ZPP_Constraint); HX_MARK_MEMBER_NAME(next,"next"); HX_MARK_MEMBER_NAME(elt,"elt"); HX_MARK_END_CLASS(); } void ZNPNode_ZPP_Constraint_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(next,"next"); HX_VISIT_MEMBER_NAME(elt,"elt"); } hx::Val ZNPNode_ZPP_Constraint_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"elt") ) { return hx::Val( elt ); } break; case 4: if (HX_FIELD_EQ(inName,"next") ) { return hx::Val( next ); } if (HX_FIELD_EQ(inName,"free") ) { return hx::Val( free_dyn() ); } if (HX_FIELD_EQ(inName,"elem") ) { return hx::Val( elem_dyn() ); } break; case 5: if (HX_FIELD_EQ(inName,"alloc") ) { return hx::Val( alloc_dyn() ); } } return super::__Field(inName,inCallProp); } bool ZNPNode_ZPP_Constraint_obj::__GetStatic(const ::String &inName, Dynamic &outValue, hx::PropertyAccess inCallProp) { switch(inName.length) { case 8: if (HX_FIELD_EQ(inName,"zpp_pool") ) { outValue = ( zpp_pool ); return true; } } return false; } hx::Val ZNPNode_ZPP_Constraint_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"elt") ) { elt=inValue.Cast< ::zpp_nape::constraint::ZPP_Constraint >(); return inValue; } break; case 4: if (HX_FIELD_EQ(inName,"next") ) { next=inValue.Cast< ::zpp_nape::util::ZNPNode_ZPP_Constraint >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } bool ZNPNode_ZPP_Constraint_obj::__SetStatic(const ::String &inName,Dynamic &ioValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 8: if (HX_FIELD_EQ(inName,"zpp_pool") ) { zpp_pool=ioValue.Cast< ::zpp_nape::util::ZNPNode_ZPP_Constraint >(); return true; } } return false; } void ZNPNode_ZPP_Constraint_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("next",f3,84,02,49)); outFields->push(HX_("elt",2d,02,4d,00)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static hx::StorageInfo ZNPNode_ZPP_Constraint_obj_sMemberStorageInfo[] = { {hx::fsObject /* ::zpp_nape::util::ZNPNode_ZPP_Constraint */ ,(int)offsetof(ZNPNode_ZPP_Constraint_obj,next),HX_("next",f3,84,02,49)}, {hx::fsObject /* ::zpp_nape::constraint::ZPP_Constraint */ ,(int)offsetof(ZNPNode_ZPP_Constraint_obj,elt),HX_("elt",2d,02,4d,00)}, { hx::fsUnknown, 0, null()} }; static hx::StaticInfo ZNPNode_ZPP_Constraint_obj_sStaticStorageInfo[] = { {hx::fsObject /* ::zpp_nape::util::ZNPNode_ZPP_Constraint */ ,(void *) &ZNPNode_ZPP_Constraint_obj::zpp_pool,HX_("zpp_pool",81,5d,d4,38)}, { hx::fsUnknown, 0, null()} }; #endif static ::String ZNPNode_ZPP_Constraint_obj_sMemberFields[] = { HX_("next",f3,84,02,49), HX_("alloc",75,a4,93,21), HX_("free",ac,9c,c2,43), HX_("elt",2d,02,4d,00), HX_("elem",8f,d8,14,43), ::String(null()) }; static void ZNPNode_ZPP_Constraint_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(ZNPNode_ZPP_Constraint_obj::zpp_pool,"zpp_pool"); }; #ifdef HXCPP_VISIT_ALLOCS static void ZNPNode_ZPP_Constraint_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(ZNPNode_ZPP_Constraint_obj::zpp_pool,"zpp_pool"); }; #endif hx::Class ZNPNode_ZPP_Constraint_obj::__mClass; static ::String ZNPNode_ZPP_Constraint_obj_sStaticFields[] = { HX_("zpp_pool",81,5d,d4,38), ::String(null()) }; void ZNPNode_ZPP_Constraint_obj::__register() { ZNPNode_ZPP_Constraint_obj _hx_dummy; ZNPNode_ZPP_Constraint_obj::_hx_vtable = *(void **)&_hx_dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_("zpp_nape.util.ZNPNode_ZPP_Constraint",ae,42,05,36); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &ZNPNode_ZPP_Constraint_obj::__GetStatic; __mClass->mSetStaticField = &ZNPNode_ZPP_Constraint_obj::__SetStatic; __mClass->mMarkFunc = ZNPNode_ZPP_Constraint_obj_sMarkStatics; __mClass->mStatics = hx::Class_obj::dupFunctions(ZNPNode_ZPP_Constraint_obj_sStaticFields); __mClass->mMembers = hx::Class_obj::dupFunctions(ZNPNode_ZPP_Constraint_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< ZNPNode_ZPP_Constraint_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = ZNPNode_ZPP_Constraint_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = ZNPNode_ZPP_Constraint_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = ZNPNode_ZPP_Constraint_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } void ZNPNode_ZPP_Constraint_obj::__boot() { { HX_STACKFRAME(&_hx_pos_985aee786169fab8_14944_boot) HXDLIN(14944) zpp_pool = null(); } } } // end namespace zpp_nape } // end namespace util
36.960177
203
0.774213
HedgehogFog
a9920d621af1be84ba993ce5ef5078ca74ef1c23
4,331
hpp
C++
cell_based/test/simulation/Test2dVertexBasedSimulationWithFreeBoundary.hpp
mdp19pn/Chaste
f7b6bafa64287d567125b587b29af6d8bd7aeb90
[ "Apache-2.0", "BSD-3-Clause" ]
100
2015-02-23T08:32:23.000Z
2022-02-25T11:39:26.000Z
cell_based/test/simulation/Test2dVertexBasedSimulationWithFreeBoundary.hpp
mdp19pn/Chaste
f7b6bafa64287d567125b587b29af6d8bd7aeb90
[ "Apache-2.0", "BSD-3-Clause" ]
11
2017-06-14T13:48:43.000Z
2022-03-10T10:42:07.000Z
cell_based/test/simulation/Test2dVertexBasedSimulationWithFreeBoundary.hpp
mdp19pn/Chaste
f7b6bafa64287d567125b587b29af6d8bd7aeb90
[ "Apache-2.0", "BSD-3-Clause" ]
53
2015-02-23T13:52:44.000Z
2022-02-28T18:57:35.000Z
/* Copyright (c) 2005-2021, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. 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 University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #ifndef TEST2DVERTEXBASEDSIMULATIONWITHFREEBOUNDARY_HPP_ #define TEST2DVERTEXBASEDSIMULATIONWITHFREEBOUNDARY_HPP_ #include "AbstractCellBasedTestSuite.hpp" #include "CheckpointArchiveTypes.hpp" #include "OffLatticeSimulation.hpp" #include "VertexBasedCellPopulation.hpp" #include "FarhadifarForce.hpp" #include "TargetAreaLinearGrowthModifier.hpp" #include "CellsGenerator.hpp" #include "VoronoiVertexMeshGenerator.hpp" #include "DifferentiatedCellProliferativeType.hpp" #include "NoCellCycleModel.hpp" #include "SmartPointers.hpp" #include "FakePetscSetup.hpp" /** * This class consists of a single test, in which a 2D model * of a growing monolayer of cells is simulated for a fixed * period of time. * * This test is used for profiling, to establish the run time * variation as the code is developed. */ class Test2DVertexSimulationWithFreeBoundary : public AbstractCellBasedTestSuite { public: void Test2DFreeBoundaryVertexSimulationForProfiling() { // make the simulation std::vector<CellPtr> cells; MutableVertexMesh<2,2>* p_mesh; VoronoiVertexMeshGenerator mesh_generator = VoronoiVertexMeshGenerator(35,35,1,1.0); p_mesh = mesh_generator.GetMesh(); MAKE_PTR(DifferentiatedCellProliferativeType, p_differentiated_type); CellsGenerator<NoCellCycleModel, 2> cells_generator; cells_generator.GenerateBasicRandom(cells, p_mesh->GetNumElements(), p_differentiated_type); VertexBasedCellPopulation<2> cell_population(*p_mesh, cells); double initial_target_area = 1.0; for (typename AbstractCellPopulation<2>::Iterator cell_iter = cell_population.Begin(); cell_iter != cell_population.End(); ++cell_iter) { // target areas cell_iter->GetCellData()->SetItem("target area", initial_target_area); } OffLatticeSimulation<2> simulator(cell_population); // Make the Farhadifar force MAKE_PTR(FarhadifarForce<2>, p_force); // before passing the force to the simulation simulator.AddForce(p_force); // We need a FarhadifarType target area modifier MAKE_PTR(TargetAreaLinearGrowthModifier<2>, p_growth_modifier); simulator.AddSimulationModifier(p_growth_modifier); simulator.SetEndTime(20); simulator.SetDt(0.01); // mpSimulator->SetSamplingTimestepMultiple( 100 ); simulator.SetOutputDirectory("VertexSimulationWithFreeBoundary"); simulator.Solve(); } }; #endif /*TEST2DVERTEXBASEDSIMULATIONWITHFREEBOUNDARY_HPP_*/
37.991228
100
0.758947
mdp19pn
a9931a90720b29f85ceec2f45caa1693d9b75a25
291
cpp
C++
1-6-6z.cpp
Kaermor/stepik-course363-cpp
7df3381ee5460565754745b6d48ed3f1324e73ef
[ "Apache-2.0" ]
null
null
null
1-6-6z.cpp
Kaermor/stepik-course363-cpp
7df3381ee5460565754745b6d48ed3f1324e73ef
[ "Apache-2.0" ]
null
null
null
1-6-6z.cpp
Kaermor/stepik-course363-cpp
7df3381ee5460565754745b6d48ed3f1324e73ef
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <cmath> #include <iomanip> using namespace std; int main() { double n, sum, k; cin >> n; while (n != 0){ sum = sum + n; k++; cin >> n; } cout << setprecision(11) << fixed; cout << sum/k << endl; return 0; }
14.55
38
0.484536
Kaermor
a9943c77e79fd002974dacddcc2ee90d6d34ea9c
3,921
cpp
C++
vm/objects.cpp
dch/factor
faacbb58e0738a0612a04b792a3f6ff4929134ff
[ "BSD-2-Clause" ]
null
null
null
vm/objects.cpp
dch/factor
faacbb58e0738a0612a04b792a3f6ff4929134ff
[ "BSD-2-Clause" ]
null
null
null
vm/objects.cpp
dch/factor
faacbb58e0738a0612a04b792a3f6ff4929134ff
[ "BSD-2-Clause" ]
null
null
null
#include "master.hpp" namespace factor { void factor_vm::primitive_special_object() { fixnum n = untag_fixnum(ctx->peek()); ctx->replace(special_objects[n]); } void factor_vm::primitive_set_special_object() { fixnum n = untag_fixnum(ctx->pop()); cell value = ctx->pop(); special_objects[n] = value; } void factor_vm::primitive_identity_hashcode() { cell tagged = ctx->peek(); object* obj = untag<object>(tagged); ctx->replace(tag_fixnum(obj->hashcode())); } void factor_vm::compute_identity_hashcode(object* obj) { object_counter++; if (object_counter == 0) object_counter++; obj->set_hashcode((cell)obj ^ object_counter); } void factor_vm::primitive_compute_identity_hashcode() { object* obj = untag<object>(ctx->pop()); compute_identity_hashcode(obj); } void factor_vm::primitive_set_slot() { fixnum slot = untag_fixnum(ctx->pop()); object* obj = untag<object>(ctx->pop()); cell value = ctx->pop(); cell* slot_ptr = &obj->slots()[slot]; *slot_ptr = value; write_barrier(slot_ptr); } /* Allocates memory */ cell factor_vm::clone_object(cell obj_) { data_root<object> obj(obj_, this); if (immediate_p(obj.value())) return obj.value(); else { cell size = object_size(obj.value()); object* new_obj = allot_object(obj.type(), size); memcpy(new_obj, obj.untagged(), size); new_obj->set_hashcode(0); return tag_dynamic(new_obj); } } /* Allocates memory */ void factor_vm::primitive_clone() { ctx->replace(clone_object(ctx->peek())); } /* Size of the object pointed to by a tagged pointer */ cell factor_vm::object_size(cell tagged) { if (immediate_p(tagged)) return 0; else return untag<object>(tagged)->size(); } /* Allocates memory */ void factor_vm::primitive_size() { ctx->replace(from_unsigned_cell(object_size(ctx->peek()))); } struct slot_become_fixup : no_fixup { std::map<object*, object*>* become_map; slot_become_fixup(std::map<object*, object*>* become_map) : become_map(become_map) {} object* fixup_data(object* old) { std::map<object*, object*>::const_iterator iter = become_map->find(old); if (iter != become_map->end()) return iter->second; else return old; } }; /* classes.tuple uses this to reshape tuples; tools.deploy.shaker uses this to coalesce equal but distinct quotations and wrappers. */ /* Calls gc */ void factor_vm::primitive_become() { primitive_minor_gc(); array* new_objects = untag_check<array>(ctx->pop()); array* old_objects = untag_check<array>(ctx->pop()); cell capacity = array_capacity(new_objects); if (capacity != array_capacity(old_objects)) critical_error("bad parameters to become", 0); /* Build the forwarding map */ std::map<object*, object*> become_map; for (cell i = 0; i < capacity; i++) { tagged<object> old_obj(array_nth(old_objects, i)); tagged<object> new_obj(array_nth(new_objects, i)); if (old_obj != new_obj) become_map[old_obj.untagged()] = new_obj.untagged(); } /* Update all references to old objects to point to new objects */ { slot_visitor<slot_become_fixup> visitor(this, slot_become_fixup(&become_map)); visitor.visit_all_roots(); auto object_become_visitor = [&](object* obj) { visitor.visit_slots(obj); }; each_object(object_become_visitor); auto code_block_become_visitor = [&](code_block* compiled, cell size) { visitor.visit_code_block_objects(compiled); visitor.visit_embedded_literals(compiled); }; each_code_block(code_block_become_visitor); } /* Since we may have introduced old->new references, need to revisit all objects and code blocks on a minor GC. */ data->mark_all_cards(); { auto code_block_visitor = [&](code_block* compiled, cell size) { code->write_barrier(compiled); }; each_code_block(code_block_visitor); } } }
27.229167
78
0.680949
dch
a9986869f1116f9bdfa4c7d1f673bba821397e21
884
hpp
C++
src/include/duckdb/planner/operator/logical_filter.hpp
RelationalAI-oss/duckdb
a4908ae17de3ac62d42633ada03077b8c3ead7a5
[ "MIT" ]
2
2020-01-07T17:19:02.000Z
2020-01-09T22:04:04.000Z
src/include/duckdb/planner/operator/logical_filter.hpp
RelationalAI-oss/duckdb
a4908ae17de3ac62d42633ada03077b8c3ead7a5
[ "MIT" ]
null
null
null
src/include/duckdb/planner/operator/logical_filter.hpp
RelationalAI-oss/duckdb
a4908ae17de3ac62d42633ada03077b8c3ead7a5
[ "MIT" ]
null
null
null
//===----------------------------------------------------------------------===// // DuckDB // // planner/operator/logical_filter.hpp // // //===----------------------------------------------------------------------===// #pragma once #include "duckdb/planner/logical_operator.hpp" namespace duckdb { //! LogicalFilter represents a filter operation (e.g. WHERE or HAVING clause) class LogicalFilter : public LogicalOperator { public: LogicalFilter(unique_ptr<Expression> expression); LogicalFilter(); bool SplitPredicates() { return SplitPredicates(expressions); } //! Splits up the predicates of the LogicalFilter into a set of predicates //! separated by AND Returns whether or not any splits were made static bool SplitPredicates(vector<unique_ptr<Expression>> &expressions); protected: void ResolveTypes() override; }; } // namespace duckdb
26.787879
80
0.602941
RelationalAI-oss
a99e0b809be646f6f08f77c79fc13623288e49ee
1,115
cpp
C++
tmp/binary_value.cpp
Ahmed-Zamouche/cpp
73136b5a350d3b95f0ae7e9ff007402e8f8214df
[ "MIT" ]
null
null
null
tmp/binary_value.cpp
Ahmed-Zamouche/cpp
73136b5a350d3b95f0ae7e9ff007402e8f8214df
[ "MIT" ]
null
null
null
tmp/binary_value.cpp
Ahmed-Zamouche/cpp
73136b5a350d3b95f0ae7e9ff007402e8f8214df
[ "MIT" ]
null
null
null
#include <iostream> #include <type_traits> #include <vector> #define NDEBUG template <bool a_0> int reversed_binary_value() { #ifndef NDEBUG std::cout << __PRETTY_FUNCTION__ << ": " << a_0 << std::endl; #endif return a_0; } template <bool a_n_minus_1, bool a_n_minus_2, bool... digits> int reversed_binary_value() { #ifndef NDEBUG std::cout << __PRETTY_FUNCTION__ << ": " << sizeof...(digits) << std::endl; #endif return (reversed_binary_value<a_n_minus_2, digits...>() << 1) + a_n_minus_1; } template <bool a_0> int binary_value() { #ifndef NDEBUG std::cout << __PRETTY_FUNCTION__ << ": " << a_0 << std::endl; #endif return a_0; } template <bool a_n_minus_1, bool a_n_minus_2, bool... digits> int binary_value() { #ifndef NDEBUG std::cout << __PRETTY_FUNCTION__ << ": " << sizeof...(digits) << std::endl; #endif return a_n_minus_1 * (1 << (sizeof...(digits) + 1)) + binary_value<a_n_minus_2, digits...>(); } using namespace std; int main() { cout << binary_value<1, 0, 1, 0, 1, 0, 1, 0>() << endl; cout << reversed_binary_value<1, 0, 1, 0, 1, 0, 1, 0>() << endl; return 0; }
23.229167
78
0.647534
Ahmed-Zamouche
a9a17d3ffdc8214ced17d14a2f2323433b90dba8
12,372
cpp
C++
tdmq/src/v20200217/model/AMQPQueueDetail.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
tdmq/src/v20200217/model/AMQPQueueDetail.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
tdmq/src/v20200217/model/AMQPQueueDetail.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/tdmq/v20200217/model/AMQPQueueDetail.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Tdmq::V20200217::Model; using namespace std; AMQPQueueDetail::AMQPQueueDetail() : m_nameHasBeenSet(false), m_remarkHasBeenSet(false), m_destBindedNumHasBeenSet(false), m_createTimeHasBeenSet(false), m_updateTimeHasBeenSet(false), m_onlineConsumerNumHasBeenSet(false), m_tpsHasBeenSet(false), m_accumulativeMsgNumHasBeenSet(false), m_autoDeleteHasBeenSet(false), m_deadLetterExchangeHasBeenSet(false), m_deadLetterRoutingKeyHasBeenSet(false) { } CoreInternalOutcome AMQPQueueDetail::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("Name") && !value["Name"].IsNull()) { if (!value["Name"].IsString()) { return CoreInternalOutcome(Core::Error("response `AMQPQueueDetail.Name` IsString=false incorrectly").SetRequestId(requestId)); } m_name = string(value["Name"].GetString()); m_nameHasBeenSet = true; } if (value.HasMember("Remark") && !value["Remark"].IsNull()) { if (!value["Remark"].IsString()) { return CoreInternalOutcome(Core::Error("response `AMQPQueueDetail.Remark` IsString=false incorrectly").SetRequestId(requestId)); } m_remark = string(value["Remark"].GetString()); m_remarkHasBeenSet = true; } if (value.HasMember("DestBindedNum") && !value["DestBindedNum"].IsNull()) { if (!value["DestBindedNum"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `AMQPQueueDetail.DestBindedNum` IsUint64=false incorrectly").SetRequestId(requestId)); } m_destBindedNum = value["DestBindedNum"].GetUint64(); m_destBindedNumHasBeenSet = true; } if (value.HasMember("CreateTime") && !value["CreateTime"].IsNull()) { if (!value["CreateTime"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `AMQPQueueDetail.CreateTime` IsUint64=false incorrectly").SetRequestId(requestId)); } m_createTime = value["CreateTime"].GetUint64(); m_createTimeHasBeenSet = true; } if (value.HasMember("UpdateTime") && !value["UpdateTime"].IsNull()) { if (!value["UpdateTime"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `AMQPQueueDetail.UpdateTime` IsUint64=false incorrectly").SetRequestId(requestId)); } m_updateTime = value["UpdateTime"].GetUint64(); m_updateTimeHasBeenSet = true; } if (value.HasMember("OnlineConsumerNum") && !value["OnlineConsumerNum"].IsNull()) { if (!value["OnlineConsumerNum"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `AMQPQueueDetail.OnlineConsumerNum` IsUint64=false incorrectly").SetRequestId(requestId)); } m_onlineConsumerNum = value["OnlineConsumerNum"].GetUint64(); m_onlineConsumerNumHasBeenSet = true; } if (value.HasMember("Tps") && !value["Tps"].IsNull()) { if (!value["Tps"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `AMQPQueueDetail.Tps` IsUint64=false incorrectly").SetRequestId(requestId)); } m_tps = value["Tps"].GetUint64(); m_tpsHasBeenSet = true; } if (value.HasMember("AccumulativeMsgNum") && !value["AccumulativeMsgNum"].IsNull()) { if (!value["AccumulativeMsgNum"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `AMQPQueueDetail.AccumulativeMsgNum` IsUint64=false incorrectly").SetRequestId(requestId)); } m_accumulativeMsgNum = value["AccumulativeMsgNum"].GetUint64(); m_accumulativeMsgNumHasBeenSet = true; } if (value.HasMember("AutoDelete") && !value["AutoDelete"].IsNull()) { if (!value["AutoDelete"].IsBool()) { return CoreInternalOutcome(Core::Error("response `AMQPQueueDetail.AutoDelete` IsBool=false incorrectly").SetRequestId(requestId)); } m_autoDelete = value["AutoDelete"].GetBool(); m_autoDeleteHasBeenSet = true; } if (value.HasMember("DeadLetterExchange") && !value["DeadLetterExchange"].IsNull()) { if (!value["DeadLetterExchange"].IsString()) { return CoreInternalOutcome(Core::Error("response `AMQPQueueDetail.DeadLetterExchange` IsString=false incorrectly").SetRequestId(requestId)); } m_deadLetterExchange = string(value["DeadLetterExchange"].GetString()); m_deadLetterExchangeHasBeenSet = true; } if (value.HasMember("DeadLetterRoutingKey") && !value["DeadLetterRoutingKey"].IsNull()) { if (!value["DeadLetterRoutingKey"].IsString()) { return CoreInternalOutcome(Core::Error("response `AMQPQueueDetail.DeadLetterRoutingKey` IsString=false incorrectly").SetRequestId(requestId)); } m_deadLetterRoutingKey = string(value["DeadLetterRoutingKey"].GetString()); m_deadLetterRoutingKeyHasBeenSet = true; } return CoreInternalOutcome(true); } void AMQPQueueDetail::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_nameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Name"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_name.c_str(), allocator).Move(), allocator); } if (m_remarkHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Remark"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_remark.c_str(), allocator).Move(), allocator); } if (m_destBindedNumHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DestBindedNum"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_destBindedNum, allocator); } if (m_createTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "CreateTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_createTime, allocator); } if (m_updateTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "UpdateTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_updateTime, allocator); } if (m_onlineConsumerNumHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "OnlineConsumerNum"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_onlineConsumerNum, allocator); } if (m_tpsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Tps"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_tps, allocator); } if (m_accumulativeMsgNumHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AccumulativeMsgNum"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_accumulativeMsgNum, allocator); } if (m_autoDeleteHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AutoDelete"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_autoDelete, allocator); } if (m_deadLetterExchangeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DeadLetterExchange"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_deadLetterExchange.c_str(), allocator).Move(), allocator); } if (m_deadLetterRoutingKeyHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DeadLetterRoutingKey"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_deadLetterRoutingKey.c_str(), allocator).Move(), allocator); } } string AMQPQueueDetail::GetName() const { return m_name; } void AMQPQueueDetail::SetName(const string& _name) { m_name = _name; m_nameHasBeenSet = true; } bool AMQPQueueDetail::NameHasBeenSet() const { return m_nameHasBeenSet; } string AMQPQueueDetail::GetRemark() const { return m_remark; } void AMQPQueueDetail::SetRemark(const string& _remark) { m_remark = _remark; m_remarkHasBeenSet = true; } bool AMQPQueueDetail::RemarkHasBeenSet() const { return m_remarkHasBeenSet; } uint64_t AMQPQueueDetail::GetDestBindedNum() const { return m_destBindedNum; } void AMQPQueueDetail::SetDestBindedNum(const uint64_t& _destBindedNum) { m_destBindedNum = _destBindedNum; m_destBindedNumHasBeenSet = true; } bool AMQPQueueDetail::DestBindedNumHasBeenSet() const { return m_destBindedNumHasBeenSet; } uint64_t AMQPQueueDetail::GetCreateTime() const { return m_createTime; } void AMQPQueueDetail::SetCreateTime(const uint64_t& _createTime) { m_createTime = _createTime; m_createTimeHasBeenSet = true; } bool AMQPQueueDetail::CreateTimeHasBeenSet() const { return m_createTimeHasBeenSet; } uint64_t AMQPQueueDetail::GetUpdateTime() const { return m_updateTime; } void AMQPQueueDetail::SetUpdateTime(const uint64_t& _updateTime) { m_updateTime = _updateTime; m_updateTimeHasBeenSet = true; } bool AMQPQueueDetail::UpdateTimeHasBeenSet() const { return m_updateTimeHasBeenSet; } uint64_t AMQPQueueDetail::GetOnlineConsumerNum() const { return m_onlineConsumerNum; } void AMQPQueueDetail::SetOnlineConsumerNum(const uint64_t& _onlineConsumerNum) { m_onlineConsumerNum = _onlineConsumerNum; m_onlineConsumerNumHasBeenSet = true; } bool AMQPQueueDetail::OnlineConsumerNumHasBeenSet() const { return m_onlineConsumerNumHasBeenSet; } uint64_t AMQPQueueDetail::GetTps() const { return m_tps; } void AMQPQueueDetail::SetTps(const uint64_t& _tps) { m_tps = _tps; m_tpsHasBeenSet = true; } bool AMQPQueueDetail::TpsHasBeenSet() const { return m_tpsHasBeenSet; } uint64_t AMQPQueueDetail::GetAccumulativeMsgNum() const { return m_accumulativeMsgNum; } void AMQPQueueDetail::SetAccumulativeMsgNum(const uint64_t& _accumulativeMsgNum) { m_accumulativeMsgNum = _accumulativeMsgNum; m_accumulativeMsgNumHasBeenSet = true; } bool AMQPQueueDetail::AccumulativeMsgNumHasBeenSet() const { return m_accumulativeMsgNumHasBeenSet; } bool AMQPQueueDetail::GetAutoDelete() const { return m_autoDelete; } void AMQPQueueDetail::SetAutoDelete(const bool& _autoDelete) { m_autoDelete = _autoDelete; m_autoDeleteHasBeenSet = true; } bool AMQPQueueDetail::AutoDeleteHasBeenSet() const { return m_autoDeleteHasBeenSet; } string AMQPQueueDetail::GetDeadLetterExchange() const { return m_deadLetterExchange; } void AMQPQueueDetail::SetDeadLetterExchange(const string& _deadLetterExchange) { m_deadLetterExchange = _deadLetterExchange; m_deadLetterExchangeHasBeenSet = true; } bool AMQPQueueDetail::DeadLetterExchangeHasBeenSet() const { return m_deadLetterExchangeHasBeenSet; } string AMQPQueueDetail::GetDeadLetterRoutingKey() const { return m_deadLetterRoutingKey; } void AMQPQueueDetail::SetDeadLetterRoutingKey(const string& _deadLetterRoutingKey) { m_deadLetterRoutingKey = _deadLetterRoutingKey; m_deadLetterRoutingKeyHasBeenSet = true; } bool AMQPQueueDetail::DeadLetterRoutingKeyHasBeenSet() const { return m_deadLetterRoutingKeyHasBeenSet; }
28.974239
154
0.696492
suluner
a9a3e31e8459ce3f87fb327f70d7c40e297d4d6c
880
cpp
C++
18_List_Kullanimi/src/main.cpp
KMACEL/TR-Cpp
dac7bebd1d5fd2d69a76be5a9809417333f01817
[ "Apache-2.0" ]
1
2021-05-25T22:11:13.000Z
2021-05-25T22:11:13.000Z
18_List_Kullanimi/src/main.cpp
KMACEL/TR-Cpp
dac7bebd1d5fd2d69a76be5a9809417333f01817
[ "Apache-2.0" ]
null
null
null
18_List_Kullanimi/src/main.cpp
KMACEL/TR-Cpp
dac7bebd1d5fd2d69a76be5a9809417333f01817
[ "Apache-2.0" ]
null
null
null
//============================================================================ // İsim : 18_List_Kullanımı // Yazan : Mert AceL // Version : 1.0 // Copyright : AceL // Açıklama : Listelere Giriş //============================================================================ #include <iostream> #include <list> using namespace std; int main() { list<int> sayi; sayi.push_back(4); sayi.push_back(7); sayi.push_back(1); sayi.push_back(5); sayi.push_back(12); sayi.push_front(2); list<int>::iterator it = sayi.begin(); cout << "Sayı : " << *it << endl; *it++; cout << "Sayı : " << *it << endl; sayi.insert(it, 55); for (list<int>::iterator itF = sayi.begin(); itF != sayi.end(); itF++) { cout << "Sayi For : " << *itF << endl; } cout << "--------------------------------------------------------" << endl; return 0; }
22.564103
78
0.421591
KMACEL
a9a66f8e56e123a1234a549f9e95dce921456214
1,764
cpp
C++
src/section.cpp
YureiResearchInstitute/Yo-kai_Editor_B2
990809487492a95dec388ee04d2eab80e190c88d
[ "MIT" ]
2
2021-06-21T21:42:30.000Z
2021-06-21T21:42:33.000Z
src/section.cpp
YureiResearchInstitute/Yo-kai_Editor_B2
990809487492a95dec388ee04d2eab80e190c88d
[ "MIT" ]
null
null
null
src/section.cpp
YureiResearchInstitute/Yo-kai_Editor_B2
990809487492a95dec388ee04d2eab80e190c88d
[ "MIT" ]
4
2019-11-07T04:23:58.000Z
2021-08-29T01:17:21.000Z
#include "section.h" Section::Section(QTreeWidget* parent, quint32 id, quint32 size, quint32 offset) : QTreeWidgetItem(parent, Section::Type) , id(id) , size(size) , offset(offset) { this->setText(0, QString::number(id)); } Section::~Section() { } quint32 Section::getId() const { return id; } void Section::setId(const quint32& value) { id = value; } quint32 Section::getSize() const { return size; } void Section::setSize(const quint32& value) { size = value; } quint32 Section::getOffset() const { return offset; } void Section::setOffset(const quint32& value) { offset = value; } QString Section::getPath() const { const QTreeWidgetItem* t = this; QStringList l; do { l.prepend(t->text(0)); } while ((t = t->parent())); return l.join("/"); } Section* Section::child(int index) { QTreeWidgetItem* child = this->QTreeWidgetItem::child(index); if (child && child->type() == Section::Type) { return static_cast<Section*>(child); } return 0; } Section* Section::nextSibling() { QTreeWidgetItem* parent = this->parent(); QTreeWidgetItem* nextSibling; if (parent) { nextSibling = parent->child(parent->indexOfChild(this) + 1); } else { QTreeWidget* treeWidget = this->treeWidget(); nextSibling = treeWidget->topLevelItem(treeWidget->indexOfTopLevelItem(this) + 1); } if (nextSibling && nextSibling->type() == Section::Type) { return static_cast<Section*>(nextSibling); } return 0; } Section* Section::parent() { QTreeWidgetItem* parent = this->QTreeWidgetItem::parent(); if (parent && parent->type() == Section::Type) { return static_cast<Section*>(parent); } return 0; }
20.045455
90
0.630385
YureiResearchInstitute
a9a6f3cec6bc5f7f3e2f303a0fa454bd91800561
6,823
hpp
C++
alpaka/include/alpaka/meta/CudaVectorArrayWrapper.hpp
ComputationalRadiationPhysics/mallocMC
bb2b32a4a56f7c892e14454bf6aa373a4870c32c
[ "MIT" ]
25
2015-01-30T12:19:48.000Z
2020-10-30T07:52:45.000Z
alpaka/include/alpaka/meta/CudaVectorArrayWrapper.hpp
ComputationalRadiationPhysics/mallocMC
bb2b32a4a56f7c892e14454bf6aa373a4870c32c
[ "MIT" ]
101
2015-01-06T11:31:26.000Z
2020-11-09T13:51:19.000Z
alpaka/include/alpaka/meta/CudaVectorArrayWrapper.hpp
ComputationalRadiationPhysics/mallocMC
bb2b32a4a56f7c892e14454bf6aa373a4870c32c
[ "MIT" ]
10
2015-06-10T07:54:30.000Z
2020-05-06T10:07:39.000Z
/* Copyright 2022 Jiří Vyskočil, Jan Stephan, Bernhard Manfred Gruber * * This file is part of alpaka. * * 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 http://mozilla.org/MPL/2.0/. */ #pragma once #if defined(ALPAKA_ACC_GPU_HIP_ENABLED) || defined(ALPAKA_ACC_GPU_CUDA_ENABLED) # include <alpaka/core/Common.hpp> # include <functional> # include <initializer_list> # include <numeric> # include <type_traits> namespace alpaka::meta { namespace detail { template<typename TScalar, unsigned N> struct CudaVectorArrayTypeTraits; template<> struct CudaVectorArrayTypeTraits<float, 1> { using type = float1; }; template<> struct CudaVectorArrayTypeTraits<float, 2> { using type = float2; }; template<> struct CudaVectorArrayTypeTraits<float, 3> { using type = float3; }; template<> struct CudaVectorArrayTypeTraits<float, 4> { using type = float4; }; template<> struct CudaVectorArrayTypeTraits<double, 1> { using type = double1; }; template<> struct CudaVectorArrayTypeTraits<double, 2> { using type = double2; }; template<> struct CudaVectorArrayTypeTraits<double, 3> { using type = double3; }; template<> struct CudaVectorArrayTypeTraits<double, 4> { using type = double4; }; template<> struct CudaVectorArrayTypeTraits<unsigned, 1> { using type = uint1; }; template<> struct CudaVectorArrayTypeTraits<unsigned, 2> { using type = uint2; }; template<> struct CudaVectorArrayTypeTraits<unsigned, 3> { using type = uint3; }; template<> struct CudaVectorArrayTypeTraits<unsigned, 4> { using type = uint4; }; template<> struct CudaVectorArrayTypeTraits<int, 1> { using type = int1; }; template<> struct CudaVectorArrayTypeTraits<int, 2> { using type = int2; }; template<> struct CudaVectorArrayTypeTraits<int, 3> { using type = int3; }; template<> struct CudaVectorArrayTypeTraits<int, 4> { using type = int4; }; } // namespace detail /// Helper struct providing [] subscript access to CUDA vector types template<typename TScalar, unsigned N> struct CudaVectorArrayWrapper; template<typename TScalar> struct CudaVectorArrayWrapper<TScalar, 4> : public detail::CudaVectorArrayTypeTraits<TScalar, 4>::type { using value_type = TScalar; constexpr static unsigned size = 4; ALPAKA_FN_HOST_ACC ALPAKA_FN_INLINE CudaVectorArrayWrapper(std::initializer_list<TScalar> init) { auto it = std::begin(init); this->x = *it++; this->y = *it++; this->z = *it++; this->w = *it++; } ALPAKA_FN_HOST_ACC ALPAKA_FN_INLINE constexpr value_type& operator[](int const k) noexcept { assert(k >= 0 && k < 4); return k == 0 ? this->x : (k == 1 ? this->y : (k == 2 ? this->z : this->w)); } ALPAKA_FN_HOST_ACC ALPAKA_FN_INLINE constexpr const value_type& operator[](int const k) const noexcept { assert(k >= 0 && k < 4); return k == 0 ? this->x : (k == 1 ? this->y : (k == 2 ? this->z : this->w)); } }; template<typename TScalar> struct CudaVectorArrayWrapper<TScalar, 3> : public detail::CudaVectorArrayTypeTraits<TScalar, 3>::type { using value_type = TScalar; constexpr static unsigned size = 3; ALPAKA_FN_HOST_ACC ALPAKA_FN_INLINE CudaVectorArrayWrapper(std::initializer_list<TScalar> init) { auto it = std::begin(init); this->x = *it++; this->y = *it++; this->z = *it++; } ALPAKA_FN_HOST_ACC ALPAKA_FN_INLINE constexpr value_type& operator[](int const k) noexcept { assert(k >= 0 && k < 3); return k == 0 ? this->x : (k == 1 ? this->y : this->z); } ALPAKA_FN_HOST_ACC ALPAKA_FN_INLINE constexpr const value_type& operator[](int const k) const noexcept { assert(k >= 0 && k < 3); return k == 0 ? this->x : (k == 1 ? this->y : this->z); } }; template<typename TScalar> struct CudaVectorArrayWrapper<TScalar, 2> : public detail::CudaVectorArrayTypeTraits<TScalar, 2>::type { using value_type = TScalar; constexpr static unsigned size = 2; ALPAKA_FN_HOST_ACC ALPAKA_FN_INLINE CudaVectorArrayWrapper(std::initializer_list<TScalar> init) { auto it = std::begin(init); this->x = *it++; this->y = *it++; } ALPAKA_FN_HOST_ACC ALPAKA_FN_INLINE constexpr value_type& operator[](int const k) noexcept { assert(k >= 0 && k < 2); return k == 0 ? this->x : this->y; } ALPAKA_FN_HOST_ACC ALPAKA_FN_INLINE constexpr const value_type& operator[](int const k) const noexcept { assert(k >= 0 && k < 2); return k == 0 ? this->x : this->y; } }; template<typename TScalar> struct CudaVectorArrayWrapper<TScalar, 1> : public detail::CudaVectorArrayTypeTraits<TScalar, 1>::type { using value_type = TScalar; constexpr static unsigned size = 1; ALPAKA_FN_HOST_ACC ALPAKA_FN_INLINE CudaVectorArrayWrapper(std::initializer_list<TScalar> init) { auto it = std::begin(init); this->x = *it; } ALPAKA_FN_HOST_ACC ALPAKA_FN_INLINE constexpr value_type& operator[]([[maybe_unused]] int const k) noexcept { assert(k == 0); return this->x; } ALPAKA_FN_HOST_ACC ALPAKA_FN_INLINE constexpr const value_type& operator[]( [[maybe_unused]] int const k) const noexcept { assert(k == 0); return this->x; } }; } // namespace alpaka::meta namespace std { /// Specialization of std::tuple_size for \a float4_array template<typename T, unsigned N> struct tuple_size<alpaka::meta::CudaVectorArrayWrapper<T, N>> : integral_constant<size_t, N> { }; } // namespace std #endif
28.548117
115
0.56163
ComputationalRadiationPhysics
a9a93353a3714a7d91319cba525ccf23fcded2fc
6,778
hpp
C++
Nacro/SDK/FN_GameplayTasks_parameters.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
11
2021-08-08T23:25:10.000Z
2022-02-19T23:07:22.000Z
Nacro/SDK/FN_GameplayTasks_parameters.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
1
2022-01-01T22:51:59.000Z
2022-01-08T16:14:15.000Z
Nacro/SDK/FN_GameplayTasks_parameters.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 #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function GameplayTasks.GameplayTasksComponent.OnRep_SimulatedTasks struct UGameplayTasksComponent_OnRep_SimulatedTasks_Params { }; // Function GameplayTasks.GameplayTasksComponent.K2_RunGameplayTask struct UGameplayTasksComponent_K2_RunGameplayTask_Params { TScriptInterface<class UGameplayTaskOwnerInterface> TaskOwner; // (Parm, ZeroConstructor, IsPlainOldData) class UGameplayTask* Task; // (Parm, ZeroConstructor, IsPlainOldData) unsigned char Priority; // (Parm, ZeroConstructor, IsPlainOldData) TArray<class UClass*> AdditionalRequiredResources; // (Parm, ZeroConstructor) TArray<class UClass*> AdditionalClaimedResources; // (Parm, ZeroConstructor) EGameplayTaskRunResult ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function GameplayTasks.GameplayTask.ReadyForActivation struct UGameplayTask_ReadyForActivation_Params { }; // DelegateFunction GameplayTasks.GameplayTask.GenericGameplayTaskDelegate__DelegateSignature struct UGameplayTask_GenericGameplayTaskDelegate__DelegateSignature_Params { }; // Function GameplayTasks.GameplayTask.EndTask struct UGameplayTask_EndTask_Params { }; // Function GameplayTasks.GameplayTask_ClaimResource.ClaimResources struct UGameplayTask_ClaimResource_ClaimResources_Params { TScriptInterface<class UGameplayTaskOwnerInterface> InTaskOwner; // (Parm, ZeroConstructor, IsPlainOldData) TArray<class UClass*> ResourceClasses; // (Parm, ZeroConstructor) unsigned char Priority; // (ConstParm, Parm, ZeroConstructor, IsPlainOldData) struct FName TaskInstanceName; // (ConstParm, Parm, ZeroConstructor, IsPlainOldData) class UGameplayTask_ClaimResource* ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function GameplayTasks.GameplayTask_ClaimResource.ClaimResource struct UGameplayTask_ClaimResource_ClaimResource_Params { TScriptInterface<class UGameplayTaskOwnerInterface> InTaskOwner; // (Parm, ZeroConstructor, IsPlainOldData) class UClass* ResourceClass; // (Parm, ZeroConstructor, IsPlainOldData) unsigned char Priority; // (ConstParm, Parm, ZeroConstructor, IsPlainOldData) struct FName TaskInstanceName; // (ConstParm, Parm, ZeroConstructor, IsPlainOldData) class UGameplayTask_ClaimResource* ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function GameplayTasks.GameplayTask_SpawnActor.SpawnActor struct UGameplayTask_SpawnActor_SpawnActor_Params { TScriptInterface<class UGameplayTaskOwnerInterface> TaskOwner; // (Parm, ZeroConstructor, IsPlainOldData) struct FVector SpawnLocation; // (Parm, IsPlainOldData) struct FRotator SpawnRotation; // (Parm, IsPlainOldData) class UClass* Class; // (Parm, ZeroConstructor, IsPlainOldData) bool bSpawnOnlyOnAuthority; // (Parm, ZeroConstructor, IsPlainOldData) class UGameplayTask_SpawnActor* ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function GameplayTasks.GameplayTask_SpawnActor.FinishSpawningActor struct UGameplayTask_SpawnActor_FinishSpawningActor_Params { class UObject* WorldContextObject; // (Parm, ZeroConstructor, IsPlainOldData) class AActor* SpawnedActor; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function GameplayTasks.GameplayTask_SpawnActor.BeginSpawningActor struct UGameplayTask_SpawnActor_BeginSpawningActor_Params { class UObject* WorldContextObject; // (Parm, ZeroConstructor, IsPlainOldData) class AActor* SpawnedActor; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function GameplayTasks.GameplayTask_WaitDelay.TaskWaitDelay struct UGameplayTask_WaitDelay_TaskWaitDelay_Params { TScriptInterface<class UGameplayTaskOwnerInterface> TaskOwner; // (Parm, ZeroConstructor, IsPlainOldData) float Time; // (Parm, ZeroConstructor, IsPlainOldData) unsigned char Priority; // (ConstParm, Parm, ZeroConstructor, IsPlainOldData) class UGameplayTask_WaitDelay* ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // DelegateFunction GameplayTasks.GameplayTask_WaitDelay.TaskDelayDelegate__DelegateSignature struct UGameplayTask_WaitDelay_TaskDelayDelegate__DelegateSignature_Params { }; } #ifdef _MSC_VER #pragma pack(pop) #endif
59.982301
173
0.537179
Milxnor
a9aaf8fa812fa1b5d662cf452122ccc7c4e2502a
1,065
cpp
C++
2524/5364663_AC_329MS_448K.cpp
vandreas19/POJ_sol
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
18
2017-08-14T07:34:42.000Z
2022-01-29T14:20:29.000Z
2524/5364663_AC_329MS_448K.cpp
pinepara/poj_solutions
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
null
null
null
2524/5364663_AC_329MS_448K.cpp
pinepara/poj_solutions
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
14
2016-12-21T23:37:22.000Z
2021-07-24T09:38:57.000Z
#include<cstdio> int GetRoot(int ID,int *father){ if(father[ID]==ID) return ID; return father[ID]=GetRoot(father[ID],father); } int main(){ const int STUDENT_MAX=50000; int studentNum,pairNum,caseID=1; int father[STUDENT_MAX]; bool religionRoot[STUDENT_MAX]; while(true){ scanf("%d%d",&studentNum,&pairNum); if(studentNum==0 && pairNum==0) break; //int *father=new int[studentNum]; for(int i=0;i<studentNum;i++) father[i]=i; while(pairNum-->0){ int left,right; scanf("%d%d",&left,&right); left=GetRoot(left-1,father); right=GetRoot(right-1,father); if(left!=right) father[right]=left; } //bool *religionRoot=new bool[studentNum]; for(int i=0;i<studentNum;i++) religionRoot[i]=false; for(int i=0;i<studentNum;i++) religionRoot[GetRoot(i,father)]=true; int religionCount=0; for(int i=0;i<studentNum;i++) if(religionRoot[i]) religionCount++; printf("Case %d: %d\n",caseID++,religionCount); //delete[] religionRoot; //delete[] father; } return 0; }
24.767442
50
0.635681
vandreas19
a9afacebb66aa4577dfe6c76d84fcddfdd9d3529
16,503
cpp
C++
src/framework/shared/irphandlers/pnp/notpowerpolicyownerstatemachine.cpp
IT-Enthusiast-Nepal/Windows-Driver-Frameworks
bfee6134f30f92a90dbf96e98d54582ecb993996
[ "MIT" ]
994
2015-03-18T21:37:07.000Z
2019-04-26T04:04:14.000Z
src/framework/shared/irphandlers/pnp/notpowerpolicyownerstatemachine.cpp
IT-Enthusiast-Nepal/Windows-Driver-Frameworks
bfee6134f30f92a90dbf96e98d54582ecb993996
[ "MIT" ]
13
2019-06-13T15:58:03.000Z
2022-02-18T22:53:35.000Z
src/framework/shared/irphandlers/pnp/notpowerpolicyownerstatemachine.cpp
IT-Enthusiast-Nepal/Windows-Driver-Frameworks
bfee6134f30f92a90dbf96e98d54582ecb993996
[ "MIT" ]
350
2015-03-19T04:29:46.000Z
2019-05-05T23:26:50.000Z
/*++ Copyright (c) Microsoft. All rights reserved. Module Name: NotPowerPolicyOwnerStateMachine.cpp Abstract: This module implements the Not Power Policy Owner state machine for the driver framework. This code was split out from PowerPolicyStateMachine.cpp Author: Environment: Both kernel and user mode Revision History: --*/ #include "pnppriv.hpp" extern "C" { #if defined(EVENT_TRACING) #include "NotPowerPolicyOwnerStateMachine.tmh" #endif } const POWER_POLICY_EVENT_TARGET_STATE FxPkgPnp::m_NotPowerPolOwnerObjectCreatedStates[] = { { PwrPolStart, WdfDevStatePwrPolStarting DEBUGGED_EVENT }, { PwrPolRemove, WdfDevStatePwrPolRemoved DEBUGGED_EVENT }, }; const POWER_POLICY_EVENT_TARGET_STATE FxPkgPnp::m_NotPowerPolOwnerStartingStates[] = { { PwrPolPowerUp, WdfDevStatePwrPolStarted DEBUGGED_EVENT }, { PwrPolPowerUpFailed, WdfDevStatePwrPolStartingFailed DEBUGGED_EVENT }, }; const POWER_POLICY_EVENT_TARGET_STATE FxPkgPnp::m_NotPowerPolOwnerStartingSucceededStates[] = { { PwrPolPowerDownIoStopped, WdfDevStatePwrPolGotoDx DEBUGGED_EVENT }, { PwrPolStop, WdfDevStatePwrPolStopping DEBUGGED_EVENT }, { PwrPolSurpriseRemove, WdfDevStatePwrPolStopping DEBUGGED_EVENT }, { PwrPolPowerUpHwStarted, WdfDevStatePwrPolGotoD0InD0 TRAP_ON_EVENT }, }; const POWER_POLICY_EVENT_TARGET_STATE FxPkgPnp::m_NotPowerPolOwnerStartingFailedStates[] = { { PwrPolRemove, WdfDevStatePwrPolRemoved DEBUGGED_EVENT }, }; const POWER_POLICY_EVENT_TARGET_STATE FxPkgPnp::m_NotPowerPolOwnerGotoDxStates[] = { { PwrPolPowerDown, WdfDevStatePwrPolDx DEBUGGED_EVENT }, { PwrPolPowerDownFailed, WdfDevStatePwrPolStartingSucceeded DEBUGGED_EVENT }, }; const POWER_POLICY_EVENT_TARGET_STATE FxPkgPnp::m_NotPowerPolOwnerGotoDxInDxStates[] = { { PwrPolPowerDown, WdfDevStatePwrPolDx TRAP_ON_EVENT }, { PwrPolPowerDownFailed, WdfDevStatePwrPolDx TRAP_ON_EVENT }, }; const POWER_POLICY_EVENT_TARGET_STATE FxPkgPnp::m_NotPowerPolOwnerDxStates[] = { { PwrPolPowerUpHwStarted, WdfDevStatePwrPolGotoD0 DEBUGGED_EVENT }, { PwrPolStop, WdfDevStatePwrPolStopping DEBUGGED_EVENT }, { PwrPolSurpriseRemove, WdfDevStatePwrPolStopping DEBUGGED_EVENT }, { PwrPolPowerDownIoStopped, WdfDevStatePwrPolGotoDxInDx TRAP_ON_EVENT }, }; const POWER_POLICY_EVENT_TARGET_STATE FxPkgPnp::m_NotPowerPolOwnerGotoD0States[] = { { PwrPolPowerUp, WdfDevStatePwrPolStartingSucceeded DEBUGGED_EVENT }, { PwrPolPowerUpFailed, WdfDevStatePwrPolStartingSucceeded TRAP_ON_EVENT }, }; const POWER_POLICY_EVENT_TARGET_STATE FxPkgPnp::m_NotPowerPolOwnerGotoD0InD0States[] = { { PwrPolPowerUp, WdfDevStatePwrPolStartingSucceeded TRAP_ON_EVENT }, { PwrPolPowerUpFailed, WdfDevStatePwrPolStartingSucceeded TRAP_ON_EVENT }, }; const POWER_POLICY_EVENT_TARGET_STATE FxPkgPnp::m_NotPowerPolOwnerStoppedStates[] = { { PwrPolStart, WdfDevStatePwrPolStarting DEBUGGED_EVENT }, { PwrPolRemove, WdfDevStatePwrPolRemoved DEBUGGED_EVENT }, }; const POWER_POLICY_EVENT_TARGET_STATE FxPkgPnp::m_NotPowerPolOwnerStoppingWaitForImplicitPowerDownStates[] = { { PwrPolImplicitPowerDown, WdfDevStatePwrPolStoppingSendStatus DEBUGGED_EVENT }, { PwrPolImplicitPowerDownFailed, WdfDevStatePwrPolStoppingFailed DEBUGGED_EVENT }, { PwrPolPowerDownIoStopped, WdfDevStatePwrPolStoppingPoweringDown DEBUGGED_EVENT }, { PwrPolPowerUpHwStarted, WdfDevStatePwrPolStoppingPoweringUp DEBUGGED_EVENT }, }; const POWER_POLICY_EVENT_TARGET_STATE FxPkgPnp::m_NotPowerPolOwnerStoppingPoweringUpStates[] = { { PwrPolPowerUp, WdfDevStatePwrPolStoppingWaitingForImplicitPowerDown DEBUGGED_EVENT }, { PwrPolPowerUpFailed, WdfDevStatePwrPolStoppingWaitingForImplicitPowerDown TRAP_ON_EVENT }, }; const POWER_POLICY_EVENT_TARGET_STATE FxPkgPnp::m_NotPowerPolOwnerStoppingPoweringDownStates[] = { { PwrPolPowerDown, WdfDevStatePwrPolStoppingWaitingForImplicitPowerDown DEBUGGED_EVENT }, { PwrPolPowerDownFailed, WdfDevStatePwrPolStoppingWaitingForImplicitPowerDown DEBUGGED_EVENT }, }; const POWER_POLICY_EVENT_TARGET_STATE FxPkgPnp::m_NotPowerPolOwnerRemovedStates[] = { { PwrPolStart, WdfDevStatePwrPolStarting DEBUGGED_EVENT }, { PwrPolRemove, WdfDevStatePwrPolRemoved DEBUGGED_EVENT }, }; const NOT_POWER_POLICY_OWNER_STATE_TABLE FxPkgPnp::m_WdfNotPowerPolicyOwnerStates[] = { // current state // transition function, // target states // count of target states // Queue state // { WdfDevStatePwrPolObjectCreated, NULL, FxPkgPnp::m_NotPowerPolOwnerObjectCreatedStates, ARRAY_SIZE(FxPkgPnp::m_NotPowerPolOwnerObjectCreatedStates), TRUE, }, { WdfDevStatePwrPolStarting, FxPkgPnp::NotPowerPolOwnerStarting, FxPkgPnp::m_NotPowerPolOwnerStartingStates, ARRAY_SIZE(FxPkgPnp::m_NotPowerPolOwnerStartingStates), FALSE, }, { WdfDevStatePwrPolStarted, FxPkgPnp::NotPowerPolOwnerStarted, NULL, 0, FALSE, }, { WdfDevStatePwrPolStartingSucceeded, NULL, FxPkgPnp::m_NotPowerPolOwnerStartingSucceededStates, ARRAY_SIZE(FxPkgPnp::m_NotPowerPolOwnerStartingSucceededStates), TRUE, }, { WdfDevStatePwrPolGotoDx, FxPkgPnp::NotPowerPolOwnerGotoDx, FxPkgPnp::m_NotPowerPolOwnerGotoDxStates, ARRAY_SIZE(FxPkgPnp::m_NotPowerPolOwnerGotoDxStates), FALSE, }, { WdfDevStatePwrPolGotoDxInDx, FxPkgPnp::NotPowerPolOwnerGotoDxInDx, FxPkgPnp::m_NotPowerPolOwnerGotoDxInDxStates, ARRAY_SIZE(FxPkgPnp::m_NotPowerPolOwnerGotoDxInDxStates), FALSE, }, { WdfDevStatePwrPolDx, NULL, FxPkgPnp::m_NotPowerPolOwnerDxStates, ARRAY_SIZE(FxPkgPnp::m_NotPowerPolOwnerDxStates), TRUE, }, { WdfDevStatePwrPolGotoD0, FxPkgPnp::NotPowerPolOwnerGotoD0, FxPkgPnp::m_NotPowerPolOwnerGotoD0States, ARRAY_SIZE(FxPkgPnp::m_NotPowerPolOwnerGotoD0States), FALSE, }, { WdfDevStatePwrPolGotoD0InD0, FxPkgPnp::NotPowerPolOwnerGotoD0InD0, FxPkgPnp::m_NotPowerPolOwnerGotoD0InD0States, ARRAY_SIZE(FxPkgPnp::m_NotPowerPolOwnerGotoD0InD0States), FALSE, }, { WdfDevStatePwrPolStopping, FxPkgPnp::NotPowerPolOwnerStopping, NULL, 0, FALSE, }, { WdfDevStatePwrPolStoppingSendStatus, FxPkgPnp::NotPowerPolOwnerStoppingSendStatus, NULL, 0, FALSE, }, { WdfDevStatePwrPolStartingFailed, FxPkgPnp::NotPowerPolOwnerStartingFailed, FxPkgPnp::m_NotPowerPolOwnerStartingFailedStates, ARRAY_SIZE(FxPkgPnp::m_NotPowerPolOwnerStartingFailedStates), TRUE, }, { WdfDevStatePwrPolStoppingFailed, FxPkgPnp::NotPowerPolOwnerStoppingFailed, NULL, 0, FALSE, }, { WdfDevStatePwrPolStopped, NULL, FxPkgPnp::m_NotPowerPolOwnerStoppedStates, ARRAY_SIZE(FxPkgPnp::m_NotPowerPolOwnerStoppedStates), TRUE, }, { WdfDevStatePwrPolStoppingWaitingForImplicitPowerDown, NULL, FxPkgPnp::m_NotPowerPolOwnerStoppingWaitForImplicitPowerDownStates, ARRAY_SIZE(FxPkgPnp::m_NotPowerPolOwnerStoppingWaitForImplicitPowerDownStates), TRUE, }, { WdfDevStatePwrPolStoppingPoweringUp, FxPkgPnp::NotPowerPolOwnerStoppingPoweringUp, FxPkgPnp::m_NotPowerPolOwnerStoppingPoweringUpStates, ARRAY_SIZE(FxPkgPnp::m_NotPowerPolOwnerStoppingPoweringUpStates), FALSE, }, { WdfDevStatePwrPolStoppingPoweringDown, FxPkgPnp::NotPowerPolOwnerStoppingPoweringDown, FxPkgPnp::m_NotPowerPolOwnerStoppingPoweringDownStates, ARRAY_SIZE(FxPkgPnp::m_NotPowerPolOwnerStoppingPoweringDownStates), FALSE, }, { WdfDevStatePwrPolRemoved, FxPkgPnp::NotPowerPolOwnerRemoved, FxPkgPnp::m_NotPowerPolOwnerRemovedStates, ARRAY_SIZE(FxPkgPnp::m_NotPowerPolOwnerRemovedStates), TRUE, }, // the last entry must have WdfDevStatePwrPolNull as the current state { WdfDevStatePwrPolNull, NULL, NULL, 0, FALSE, }, }; VOID FxPkgPnp::NotPowerPolicyOwnerEnterNewState( __in WDF_DEVICE_POWER_POLICY_STATE NewState ) { CPNOT_POWER_POLICY_OWNER_STATE_TABLE entry; WDF_DEVICE_POWER_POLICY_STATE currentState, newState; WDF_DEVICE_POWER_POLICY_NOTIFICATION_DATA data; currentState = m_Device->GetDevicePowerPolicyState(); newState = NewState; while (newState != WdfDevStatePwrPolNull) { DoTraceLevelMessage( GetDriverGlobals(), TRACE_LEVEL_INFORMATION, TRACINGPNPPOWERSTATES, "WDFDEVICE 0x%p !devobj 0x%p entering not power policy owner state " "%!WDF_DEVICE_POWER_POLICY_STATE! from " "%!WDF_DEVICE_POWER_POLICY_STATE!", m_Device->GetHandle(), m_Device->GetDeviceObject(), newState, currentState); if (m_PowerPolicyStateCallbacks != NULL) { // // Callback for leaving the old state // RtlZeroMemory(&data, sizeof(data)); data.Type = StateNotificationLeaveState; data.Data.LeaveState.CurrentState = currentState; data.Data.LeaveState.NewState = newState; m_PowerPolicyStateCallbacks->Invoke(currentState, StateNotificationLeaveState, m_Device->GetHandle(), &data); } m_PowerPolicyMachine.m_States.History[ m_PowerPolicyMachine.IncrementHistoryIndex()] = (USHORT) newState; if (m_PowerPolicyStateCallbacks != NULL) { // // Callback for entering the new state // RtlZeroMemory(&data, sizeof(data)); data.Type = StateNotificationEnterState; data.Data.EnterState.CurrentState = currentState; data.Data.EnterState.NewState = newState; m_PowerPolicyStateCallbacks->Invoke(newState, StateNotificationEnterState, m_Device->GetHandle(), &data); } m_Device->SetDevicePowerPolicyState(newState); currentState = newState; entry = GetNotPowerPolicyOwnerTableEntry(currentState); // // Call the state handler, if there is one. // if (entry->StateFunc != NULL) { newState = entry->StateFunc(this); } else { newState = WdfDevStatePwrPolNull; } if (m_PowerPolicyStateCallbacks != NULL) { // // Callback for post processing the new state // RtlZeroMemory(&data, sizeof(data)); data.Type = StateNotificationPostProcessState; data.Data.PostProcessState.CurrentState = currentState; m_PowerPolicyStateCallbacks->Invoke(currentState, StateNotificationPostProcessState, m_Device->GetHandle(), &data); } } } WDF_DEVICE_POWER_POLICY_STATE FxPkgPnp::NotPowerPolOwnerStarting( __inout FxPkgPnp* This ) /*++ Routine Description: Starting the power policy state machine for a device which is not the power policy owner. Tell the power state machine to start up. Arguments: This - instance of the state machine Return Value: WdfDevStatePwrPolNull --*/ { This->PowerProcessEvent(PowerImplicitD0); return WdfDevStatePwrPolNull; } WDF_DEVICE_POWER_POLICY_STATE FxPkgPnp::NotPowerPolOwnerStarted( __inout FxPkgPnp* This ) /*++ Routine Description: Starting the power policy state machine for a device which is not the power policy owner has succeeded. Indicate status to the pnp state machine. Arguments: This - instance of the state machine Return Value: WdfDevStatePwrPolNull --*/ { This->PnpProcessEvent(PnpEventPwrPolStarted); return WdfDevStatePwrPolStartingSucceeded; } WDF_DEVICE_POWER_POLICY_STATE FxPkgPnp::NotPowerPolOwnerGotoDx( __inout FxPkgPnp* This ) { This->PowerProcessEvent(PowerCompleteDx); return WdfDevStatePwrPolNull; } WDF_DEVICE_POWER_POLICY_STATE FxPkgPnp::NotPowerPolOwnerGotoDxInDx( __inout FxPkgPnp* This ) { This->PowerProcessEvent(PowerCompleteDx); return WdfDevStatePwrPolNull; } WDF_DEVICE_POWER_POLICY_STATE FxPkgPnp::NotPowerPolOwnerGotoD0( __inout FxPkgPnp* This ) { This->PowerProcessEvent(PowerCompleteD0); return WdfDevStatePwrPolNull; } WDF_DEVICE_POWER_POLICY_STATE FxPkgPnp::NotPowerPolOwnerGotoD0InD0( __inout FxPkgPnp* This ) { This->PowerProcessEvent(PowerCompleteD0); return WdfDevStatePwrPolNull; } WDF_DEVICE_POWER_POLICY_STATE FxPkgPnp::NotPowerPolOwnerStopping( __inout FxPkgPnp* This ) /*++ Routine Description: Stopping the power policy state machine for a device which is not the power policy owner. Tell the power state machine to power down. Arguments: This - instance of the state machine Return Value: WdfDevStatePwrPolStoppingWaitingForImplicitPowerDown --*/ { This->PowerProcessEvent(PowerImplicitD3); return WdfDevStatePwrPolStoppingWaitingForImplicitPowerDown; } WDF_DEVICE_POWER_POLICY_STATE FxPkgPnp::NotPowerPolOwnerStoppingSendStatus( __inout FxPkgPnp* This ) /*++ Routine Description: Stopping the power policy state machine for a device which is not the power policy owner has succeeded. Inidcate status to the pnp state machine. Arguments: This - instance of the state machine Return Value: WdfDevStatePwrPolStopped --*/ { This->PnpProcessEvent(PnpEventPwrPolStopped); return WdfDevStatePwrPolStopped; } WDF_DEVICE_POWER_POLICY_STATE FxPkgPnp::NotPowerPolOwnerStartingFailed( __inout FxPkgPnp* This ) /*++ Routine Description: Starting the power policy state machine for a device which is not the power policy owner has failed. Inidcate status to the pnp state machine. Arguments: This - instance of the state machine Return Value: WdfDevStatePwrPolNull --*/ { This->PnpProcessEvent(PnpEventPwrPolStartFailed); return WdfDevStatePwrPolNull; } WDF_DEVICE_POWER_POLICY_STATE FxPkgPnp::NotPowerPolOwnerStoppingFailed( __inout FxPkgPnp* This ) /*++ Routine Description: Stopping the power policy state machine for a device which is not the power policy owner has failed. Inidcate status to the pnp state machine. Arguments: This - instance of the state machine Return Value: WdfDevStatePwrPolStopped --*/ { This->PnpProcessEvent(PnpEventPwrPolStopFailed); return WdfDevStatePwrPolStopped; } WDF_DEVICE_POWER_POLICY_STATE FxPkgPnp::NotPowerPolOwnerStoppingPoweringUp( __inout FxPkgPnp* This ) /*++ Routine Description: Right as we attempted to implicitly power down, a real D0 irp came into the stack. Complete the D0 irp in the power state machine so that the power state machine can process the implicit power irp Arguments: This - instance of the state machine Return Value: WdfDevStatePwrPolNull --*/ { This->PowerProcessEvent(PowerCompleteD0); return WdfDevStatePwrPolNull; } WDF_DEVICE_POWER_POLICY_STATE FxPkgPnp::NotPowerPolOwnerStoppingPoweringDown( __inout FxPkgPnp* This ) /*++ Routine Description: Right as we attempted to implicitly power down, a real Dx irp came into the stack. Complete the Dx irp in the power state machine so that the power state machine can process the implicit power irp Arguments: This - instance of the state machine Return Value: WdfDevStatePwrPolNull --*/ { This->PowerProcessEvent(PowerCompleteDx); return WdfDevStatePwrPolNull; } WDF_DEVICE_POWER_POLICY_STATE FxPkgPnp::NotPowerPolOwnerRemoved( __inout FxPkgPnp* This ) /*++ Routine Description: The device is being removed, so prepare for removal. Arguments: This - instance of the state machine Return Value: WdfDevStatePwrPolNull --*/ { // // Since we are not the power policy owner, there is nothing to be done. // Indicate to the PNP state machine that we are ready for removal. // This->PnpProcessEvent(PnpEventPwrPolRemoved); return WdfDevStatePwrPolNull; }
27.782828
108
0.722535
IT-Enthusiast-Nepal
a9b2b139c0e272b416107068aacde7049df4e8de
4,599
hpp
C++
include/System/Xml/Serialization/SerializationSource.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/Xml/Serialization/SerializationSource.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/Xml/Serialization/SerializationSource.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" #include "beatsaber-hook/shared/utils/typedefs-array.hpp" #include "beatsaber-hook/shared/utils/typedefs-string.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Forward declaring type: Type class Type; } // Completed forward declares // Type namespace: System.Xml.Serialization namespace System::Xml::Serialization { // Forward declaring type: SerializationSource class SerializationSource; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::System::Xml::Serialization::SerializationSource); DEFINE_IL2CPP_ARG_TYPE(::System::Xml::Serialization::SerializationSource*, "System.Xml.Serialization", "SerializationSource"); // Type namespace: System.Xml.Serialization namespace System::Xml::Serialization { // Size: 0x21 #pragma pack(push, 1) // Autogenerated type: System.Xml.Serialization.SerializationSource // [TokenAttribute] Offset: FFFFFFFF class SerializationSource : public ::Il2CppObject { public: public: // private System.Type[] includedTypes // Size: 0x8 // Offset: 0x10 ::ArrayW<::System::Type*> includedTypes; // Field size check static_assert(sizeof(::ArrayW<::System::Type*>) == 0x8); // private System.String namspace // Size: 0x8 // Offset: 0x18 ::StringW namspace; // Field size check static_assert(sizeof(::StringW) == 0x8); // private System.Boolean canBeGenerated // Size: 0x1 // Offset: 0x20 bool canBeGenerated; // Field size check static_assert(sizeof(bool) == 0x1); public: // Get instance field reference: private System.Type[] includedTypes [[deprecated("Use field access instead!")]] ::ArrayW<::System::Type*>& dyn_includedTypes(); // Get instance field reference: private System.String namspace [[deprecated("Use field access instead!")]] ::StringW& dyn_namspace(); // Get instance field reference: private System.Boolean canBeGenerated [[deprecated("Use field access instead!")]] bool& dyn_canBeGenerated(); // public System.Void .ctor(System.String namspace, System.Type[] includedTypes) // Offset: 0xF6D960 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static SerializationSource* New_ctor(::StringW namspace, ::ArrayW<::System::Type*> includedTypes) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Xml::Serialization::SerializationSource::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<SerializationSource*, creationType>(namspace, includedTypes))); } // protected System.Boolean BaseEquals(System.Xml.Serialization.SerializationSource other) // Offset: 0xF6D9A0 bool BaseEquals(::System::Xml::Serialization::SerializationSource* other); }; // System.Xml.Serialization.SerializationSource #pragma pack(pop) static check_size<sizeof(SerializationSource), 32 + sizeof(bool)> __System_Xml_Serialization_SerializationSourceSizeCheck; static_assert(sizeof(SerializationSource) == 0x21); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::Xml::Serialization::SerializationSource::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: System::Xml::Serialization::SerializationSource::BaseEquals // Il2CppName: BaseEquals template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Xml::Serialization::SerializationSource::*)(::System::Xml::Serialization::SerializationSource*)>(&System::Xml::Serialization::SerializationSource::BaseEquals)> { static const MethodInfo* get() { static auto* other = &::il2cpp_utils::GetClassFromName("System.Xml.Serialization", "SerializationSource")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Xml::Serialization::SerializationSource*), "BaseEquals", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{other}); } };
49.451613
244
0.736682
v0idp
a9b5fe775435d0edad617bf0759c549a9ed39bbe
3,743
hpp
C++
src/game/sys/physics/physics_comp.hpp
lowkey42/BanishedBlaze
71e66f444a84bea1eca3639de3f3ff1f79e385d1
[ "MIT" ]
null
null
null
src/game/sys/physics/physics_comp.hpp
lowkey42/BanishedBlaze
71e66f444a84bea1eca3639de3f3ff1f79e385d1
[ "MIT" ]
null
null
null
src/game/sys/physics/physics_comp.hpp
lowkey42/BanishedBlaze
71e66f444a84bea1eca3639de3f3ff1f79e385d1
[ "MIT" ]
null
null
null
/** An entity that participates in collision resolution ********************** * * * Copyright (c) 2016 Florian Oetke * * This file is distributed under the MIT License * * See LICENSE file for details. * \*****************************************************************************/ #pragma once #include <core/engine.hpp> #include <core/units.hpp> #include <core/ecs/component.hpp> class b2Body; class b2Fixture; class b2World; class b2RevoluteJoint; namespace lux { namespace sys { namespace physics { class Physics_system; enum class Body_shape { polygon, //< vertices are based on the graphical representation humanoid, circle }; struct Body_definition { bool active = true; bool kinematic=false; Body_shape shape = Body_shape::polygon; float linear_damping = 0.f; float angular_damping = 0.f; bool fixed_rotation = false; bool bullet = false; float friction = 1.f; float resitution = 0.3f; float density = 2.f; glm::vec2 size; bool sensor = false; glm::vec2 velocity{}; float keep_position_force = 0.f; std::vector<glm::vec2> vertices; }; class Dynamic_body_comp : public ecs::Component<Dynamic_body_comp, ecs::Compact_index_policy, ecs::Pool_storage_policy<64, Dynamic_body_comp>> { public: static constexpr const char* name() {return "Dynamic_body";} friend void load_component(ecs::Deserializer& state, Dynamic_body_comp&); friend void save_component(ecs::Serializer& state, const Dynamic_body_comp&); Dynamic_body_comp() = default; Dynamic_body_comp(ecs::Entity_manager& manager, ecs::Entity_handle owner); void apply_force(glm::vec2 f); void foot_friction(bool enable);//< only for humanoids bool has_ground_contact()const; void active(bool e) {_def.active = e;} void kinematic(bool e) {_dirty|=_def.kinematic!=e; _def.kinematic=e;} auto kinematic()const noexcept {return _def.kinematic;} auto velocity()const -> glm::vec2; void velocity(glm::vec2 v)const; auto mass()const -> float; auto size()const {return _size;} auto grounded()const {return _grounded;} auto ground_normal()const {return _ground_normal;} auto calc_aabb()const -> glm::vec4; private: friend class Physics_system; mutable Body_definition _def; std::unique_ptr<b2Body, void(*)(b2Body*)> _body {nullptr, +[](b2Body*){}}; b2Fixture* _fixture_foot = nullptr; bool _dirty = true; glm::vec2 _size; bool _grounded = true; glm::vec2 _ground_normal{0,1}; glm::vec2 _last_body_position; uint_fast32_t _transform_revision = 0; glm::vec2 _initial_position; void _update_body(b2World& world); void _update_ground_info(Physics_system&); }; class Static_body_comp : public ecs::Component<Static_body_comp, ecs::Compact_index_policy, ecs::Pool_storage_policy<128, Static_body_comp>> { public: static constexpr const char* name() {return "Static_body";} friend void load_component(ecs::Deserializer& state, Static_body_comp&); friend void save_component(ecs::Serializer& state, const Static_body_comp&); Static_body_comp() = default; Static_body_comp(ecs::Entity_manager& manager, ecs::Entity_handle owner); void active(bool e) {_def.active = e;} private: friend class Physics_system; Body_definition _def; std::unique_ptr<b2Body, void(*)(b2Body*)> _body {nullptr, +[](b2Body*){}}; bool _dirty = true; uint_fast32_t _transform_revision = 0; void _update_body(b2World& world); }; } } }
30.680328
99
0.64841
lowkey42
a9b71c5db9af607c9172b0124ecd1f6ccd9bc67a
41,251
cc
C++
src/tensorflow/ops/image/image.cc
MartinR20/tensorflow.nim
081f558396461bd57d55c00cda91e8dfc339c09c
[ "Apache-2.0" ]
8
2019-11-26T20:50:46.000Z
2021-02-21T18:20:00.000Z
src/tensorflow/ops/image/image.cc
MartinR20/tensorflow.nim
081f558396461bd57d55c00cda91e8dfc339c09c
[ "Apache-2.0" ]
3
2019-11-07T15:16:06.000Z
2020-03-11T21:42:59.000Z
src/tensorflow/ops/image/image.cc
MartinR20/tensorflow.nim
081f558396461bd57d55c00cda91e8dfc339c09c
[ "Apache-2.0" ]
2
2019-11-07T15:18:56.000Z
2020-10-09T13:51:41.000Z
#include "tensorflow/cc/ops/const_op.h" #include "image.h" AdjustContrast::AdjustContrast(tensorflow::Scope& scope, tensorflow::Input images, tensorflow::Input contrast_factor, tensorflow::Input min_value, tensorflow::Input max_value) { if (!scope.ok()) return; auto _images = ::tensorflow::ops::AsNodeOut(scope, images); if (!scope.ok()) return; auto _contrast_factor = ::tensorflow::ops::AsNodeOut(scope, contrast_factor); if (!scope.ok()) return; auto _min_value = ::tensorflow::ops::AsNodeOut(scope, min_value); if (!scope.ok()) return; auto _max_value = ::tensorflow::ops::AsNodeOut(scope, max_value); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("AdjustContrast"); auto builder = ::tensorflow::NodeBuilder(unique_name, "AdjustContrast") .Input(_images) .Input(_contrast_factor) .Input(_min_value) .Input(_max_value) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } AdjustContrastv2::AdjustContrastv2(tensorflow::Scope& scope, tensorflow::Input images, tensorflow::Input contrast_factor) { if (!scope.ok()) return; auto _images = ::tensorflow::ops::AsNodeOut(scope, images); if (!scope.ok()) return; auto _contrast_factor = ::tensorflow::ops::AsNodeOut(scope, contrast_factor); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("AdjustContrastv2"); auto builder = ::tensorflow::NodeBuilder(unique_name, "AdjustContrastv2") .Input(_images) .Input(_contrast_factor) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } AdjustHue::AdjustHue(tensorflow::Scope& scope, tensorflow::Input images, tensorflow::Input delta) { if (!scope.ok()) return; auto _images = ::tensorflow::ops::AsNodeOut(scope, images); if (!scope.ok()) return; auto _delta = ::tensorflow::ops::AsNodeOut(scope, delta); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("AdjustHue"); auto builder = ::tensorflow::NodeBuilder(unique_name, "AdjustHue") .Input(_images) .Input(_delta) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } AdjustSaturation::AdjustSaturation(tensorflow::Scope& scope, tensorflow::Input images, tensorflow::Input scale) { if (!scope.ok()) return; auto _images = ::tensorflow::ops::AsNodeOut(scope, images); if (!scope.ok()) return; auto _scale = ::tensorflow::ops::AsNodeOut(scope, scale); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("AdjustSaturation"); auto builder = ::tensorflow::NodeBuilder(unique_name, "AdjustSaturation") .Input(_images) .Input(_scale) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } CropAndResize::CropAndResize(tensorflow::Scope& scope, tensorflow::Input image, tensorflow::Input boxes, tensorflow::Input box_ind, tensorflow::Input crop_size, float extrapolation_value, tensorflow::string method) { if (!scope.ok()) return; auto _image = ::tensorflow::ops::AsNodeOut(scope, image); if (!scope.ok()) return; auto _boxes = ::tensorflow::ops::AsNodeOut(scope, boxes); if (!scope.ok()) return; auto _box_ind = ::tensorflow::ops::AsNodeOut(scope, box_ind); if (!scope.ok()) return; auto _crop_size = ::tensorflow::ops::AsNodeOut(scope, crop_size); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("CropAndResize"); auto builder = ::tensorflow::NodeBuilder(unique_name, "CropAndResize") .Input(_image) .Input(_boxes) .Input(_box_ind) .Input(_crop_size) .Attr("extrapolation_value", extrapolation_value) .Attr("method", method) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } CropAndResizeGradImage::CropAndResizeGradImage(tensorflow::Scope& scope, tensorflow::Input grads, tensorflow::Input boxes, tensorflow::Input box_ind, tensorflow::Input image_size, tensorflow::DataType T, tensorflow::string method) { if (!scope.ok()) return; auto _grads = ::tensorflow::ops::AsNodeOut(scope, grads); if (!scope.ok()) return; auto _boxes = ::tensorflow::ops::AsNodeOut(scope, boxes); if (!scope.ok()) return; auto _box_ind = ::tensorflow::ops::AsNodeOut(scope, box_ind); if (!scope.ok()) return; auto _image_size = ::tensorflow::ops::AsNodeOut(scope, image_size); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("CropAndResizeGradImage"); auto builder = ::tensorflow::NodeBuilder(unique_name, "CropAndResizeGradImage") .Input(_grads) .Input(_boxes) .Input(_box_ind) .Input(_image_size) .Attr("T", T) .Attr("method", method) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } DecodeAndCropJpeg::DecodeAndCropJpeg(tensorflow::Scope& scope, tensorflow::Input contents, tensorflow::Input crop_window, tensorflow::string dct_method, int64_t channels, int64_t ratio, bool fancy_upscaling, bool try_recover_truncated, float acceptable_fraction) { if (!scope.ok()) return; auto _contents = ::tensorflow::ops::AsNodeOut(scope, contents); if (!scope.ok()) return; auto _crop_window = ::tensorflow::ops::AsNodeOut(scope, crop_window); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("DecodeAndCropJpeg"); auto builder = ::tensorflow::NodeBuilder(unique_name, "DecodeAndCropJpeg") .Input(_contents) .Input(_crop_window) .Attr("dct_method", dct_method) .Attr("channels", channels) .Attr("ratio", ratio) .Attr("fancy_upscaling", fancy_upscaling) .Attr("try_recover_truncated", try_recover_truncated) .Attr("acceptable_fraction", acceptable_fraction) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } DecodeBmp::DecodeBmp(tensorflow::Scope& scope, tensorflow::Input contents, int64_t channels) { if (!scope.ok()) return; auto _contents = ::tensorflow::ops::AsNodeOut(scope, contents); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("DecodeBmp"); auto builder = ::tensorflow::NodeBuilder(unique_name, "DecodeBmp") .Input(_contents) .Attr("channels", channels) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } DecodeCSV::DecodeCSV(tensorflow::Scope& scope, tensorflow::Input records, tensorflow::InputList record_defaults, tensorflow::gtl::ArraySlice<tensorflow::DataType> OUT_TYPE, tensorflow::string na_value, tensorflow::gtl::ArraySlice<int64_t> select_cols, tensorflow::string field_delim, bool use_quote_delim) { if (!scope.ok()) return; auto _records = ::tensorflow::ops::AsNodeOut(scope, records); if (!scope.ok()) return; auto _record_defaults = ::tensorflow::ops::AsNodeOutList(scope, record_defaults); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("DecodeCSV"); auto builder = ::tensorflow::NodeBuilder(unique_name, "DecodeCSV") .Input(_records) .Input(_record_defaults) .Attr("OUT_TYPE", OUT_TYPE) .Attr("na_value", na_value) .Attr("select_cols", select_cols) .Attr("field_delim", field_delim) .Attr("use_quote_delim", use_quote_delim) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); for (tensorflow::int32 i = 0; i < ret->num_outputs(); ++i) this->output.push_back(tensorflow::Output(ret, i)); } DecodeGif::DecodeGif(tensorflow::Scope& scope, tensorflow::Input contents) { if (!scope.ok()) return; auto _contents = ::tensorflow::ops::AsNodeOut(scope, contents); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("DecodeGif"); auto builder = ::tensorflow::NodeBuilder(unique_name, "DecodeGif") .Input(_contents) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } DecodeJpeg::DecodeJpeg(tensorflow::Scope& scope, tensorflow::Input contents, tensorflow::string dct_method, int64_t channels, int64_t ratio, bool fancy_upscaling, bool try_recover_truncated, float acceptable_fraction) { if (!scope.ok()) return; auto _contents = ::tensorflow::ops::AsNodeOut(scope, contents); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("DecodeJpeg"); auto builder = ::tensorflow::NodeBuilder(unique_name, "DecodeJpeg") .Input(_contents) .Attr("dct_method", dct_method) .Attr("channels", channels) .Attr("ratio", ratio) .Attr("fancy_upscaling", fancy_upscaling) .Attr("try_recover_truncated", try_recover_truncated) .Attr("acceptable_fraction", acceptable_fraction) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } DecodePng::DecodePng(tensorflow::Scope& scope, tensorflow::Input contents, int64_t channels, tensorflow::DataType dtype) { if (!scope.ok()) return; auto _contents = ::tensorflow::ops::AsNodeOut(scope, contents); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("DecodePng"); auto builder = ::tensorflow::NodeBuilder(unique_name, "DecodePng") .Input(_contents) .Attr("channels", channels) .Attr("dtype", dtype) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } DecodeRaw::DecodeRaw(tensorflow::Scope& scope, tensorflow::Input bytes, tensorflow::DataType out_type, bool little_endian) { if (!scope.ok()) return; auto _bytes = ::tensorflow::ops::AsNodeOut(scope, bytes); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("DecodeRaw"); auto builder = ::tensorflow::NodeBuilder(unique_name, "DecodeRaw") .Input(_bytes) .Attr("out_type", out_type) .Attr("little_endian", little_endian) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } DrawBoundingBoxes::DrawBoundingBoxes(tensorflow::Scope& scope, tensorflow::Input images, tensorflow::Input boxes, tensorflow::DataType T) { if (!scope.ok()) return; auto _images = ::tensorflow::ops::AsNodeOut(scope, images); if (!scope.ok()) return; auto _boxes = ::tensorflow::ops::AsNodeOut(scope, boxes); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("DrawBoundingBoxes"); auto builder = ::tensorflow::NodeBuilder(unique_name, "DrawBoundingBoxes") .Input(_images) .Input(_boxes) .Attr("T", T) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } EncodeJpeg::EncodeJpeg(tensorflow::Scope& scope, tensorflow::Input image, tensorflow::string format, tensorflow::string xmp_metadata, int64_t quality, bool progressive, bool optimize_size, bool chroma_downsampling, tensorflow::string density_unit, int64_t x_density, int64_t y_density) { if (!scope.ok()) return; auto _image = ::tensorflow::ops::AsNodeOut(scope, image); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("EncodeJpeg"); auto builder = ::tensorflow::NodeBuilder(unique_name, "EncodeJpeg") .Input(_image) .Attr("format", format) .Attr("xmp_metadata", xmp_metadata) .Attr("quality", quality) .Attr("progressive", progressive) .Attr("optimize_size", optimize_size) .Attr("chroma_downsampling", chroma_downsampling) .Attr("density_unit", density_unit) .Attr("x_density", x_density) .Attr("y_density", y_density) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } EncodePng::EncodePng(tensorflow::Scope& scope, tensorflow::Input image, int64_t compression) { if (!scope.ok()) return; auto _image = ::tensorflow::ops::AsNodeOut(scope, image); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("EncodePng"); auto builder = ::tensorflow::NodeBuilder(unique_name, "EncodePng") .Input(_image) .Attr("compression", compression) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } ExtractGlimpse::ExtractGlimpse(tensorflow::Scope& scope, tensorflow::Input input, tensorflow::Input size, tensorflow::Input offsets, bool centered, bool normalized, bool uniform_noise) { if (!scope.ok()) return; auto _input = ::tensorflow::ops::AsNodeOut(scope, input); if (!scope.ok()) return; auto _size = ::tensorflow::ops::AsNodeOut(scope, size); if (!scope.ok()) return; auto _offsets = ::tensorflow::ops::AsNodeOut(scope, offsets); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("ExtractGlimpse"); auto builder = ::tensorflow::NodeBuilder(unique_name, "ExtractGlimpse") .Input(_input) .Input(_size) .Input(_offsets) .Attr("centered", centered) .Attr("normalized", normalized) .Attr("uniform_noise", uniform_noise) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } ExtractImagePatches::ExtractImagePatches(tensorflow::Scope& scope, tensorflow::Input images, tensorflow::gtl::ArraySlice<int64_t> ksizes, tensorflow::gtl::ArraySlice<int64_t> strides, tensorflow::gtl::ArraySlice<int64_t> rates, tensorflow::string padding, tensorflow::DataType T) { if (!scope.ok()) return; auto _images = ::tensorflow::ops::AsNodeOut(scope, images); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("ExtractImagePatches"); auto builder = ::tensorflow::NodeBuilder(unique_name, "ExtractImagePatches") .Input(_images) .Attr("ksizes", ksizes) .Attr("strides", strides) .Attr("rates", rates) .Attr("padding", padding) .Attr("T", T) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } ExtractJpegShape::ExtractJpegShape(tensorflow::Scope& scope, tensorflow::Input contents, tensorflow::DataType output_type) { if (!scope.ok()) return; auto _contents = ::tensorflow::ops::AsNodeOut(scope, contents); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("ExtractJpegShape"); auto builder = ::tensorflow::NodeBuilder(unique_name, "ExtractJpegShape") .Input(_contents) .Attr("output_type", output_type) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } HSVToRGB::HSVToRGB(tensorflow::Scope& scope, tensorflow::Input images, tensorflow::DataType T) { if (!scope.ok()) return; auto _images = ::tensorflow::ops::AsNodeOut(scope, images); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("HSVToRGB"); auto builder = ::tensorflow::NodeBuilder(unique_name, "HSVToRGB") .Input(_images) .Attr("T", T) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } NonMaxSuppression::NonMaxSuppression(tensorflow::Scope& scope, tensorflow::Input boxes, tensorflow::Input scores, tensorflow::Input max_output_size, float iou_threshold) { if (!scope.ok()) return; auto _boxes = ::tensorflow::ops::AsNodeOut(scope, boxes); if (!scope.ok()) return; auto _scores = ::tensorflow::ops::AsNodeOut(scope, scores); if (!scope.ok()) return; auto _max_output_size = ::tensorflow::ops::AsNodeOut(scope, max_output_size); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("NonMaxSuppression"); auto builder = ::tensorflow::NodeBuilder(unique_name, "NonMaxSuppression") .Input(_boxes) .Input(_scores) .Input(_max_output_size) .Attr("iou_threshold", iou_threshold) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } NonMaxSuppressionV2::NonMaxSuppressionV2(tensorflow::Scope& scope, tensorflow::Input boxes, tensorflow::Input scores, tensorflow::Input max_output_size, tensorflow::Input iou_threshold) { if (!scope.ok()) return; auto _boxes = ::tensorflow::ops::AsNodeOut(scope, boxes); if (!scope.ok()) return; auto _scores = ::tensorflow::ops::AsNodeOut(scope, scores); if (!scope.ok()) return; auto _max_output_size = ::tensorflow::ops::AsNodeOut(scope, max_output_size); if (!scope.ok()) return; auto _iou_threshold = ::tensorflow::ops::AsNodeOut(scope, iou_threshold); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("NonMaxSuppressionV2"); auto builder = ::tensorflow::NodeBuilder(unique_name, "NonMaxSuppressionV2") .Input(_boxes) .Input(_scores) .Input(_max_output_size) .Input(_iou_threshold) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } QuantizedResizeBilinear::QuantizedResizeBilinear(tensorflow::Scope& scope, tensorflow::Input images, tensorflow::Input size, tensorflow::Input min, tensorflow::Input max, tensorflow::DataType T, bool align_corners) { if (!scope.ok()) return; auto _images = ::tensorflow::ops::AsNodeOut(scope, images); if (!scope.ok()) return; auto _size = ::tensorflow::ops::AsNodeOut(scope, size); if (!scope.ok()) return; auto _min = ::tensorflow::ops::AsNodeOut(scope, min); if (!scope.ok()) return; auto _max = ::tensorflow::ops::AsNodeOut(scope, max); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("QuantizedResizeBilinear"); auto builder = ::tensorflow::NodeBuilder(unique_name, "QuantizedResizeBilinear") .Input(_images) .Input(_size) .Input(_min) .Input(_max) .Attr("T", T) .Attr("align_corners", align_corners) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } RGBToHSV::RGBToHSV(tensorflow::Scope& scope, tensorflow::Input images, tensorflow::DataType T) { if (!scope.ok()) return; auto _images = ::tensorflow::ops::AsNodeOut(scope, images); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("RGBToHSV"); auto builder = ::tensorflow::NodeBuilder(unique_name, "RGBToHSV") .Input(_images) .Attr("T", T) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } RandomCrop::RandomCrop(tensorflow::Scope& scope, tensorflow::Input image, tensorflow::Input size, tensorflow::DataType T, int64_t seed, int64_t seed2) { if (!scope.ok()) return; auto _image = ::tensorflow::ops::AsNodeOut(scope, image); if (!scope.ok()) return; auto _size = ::tensorflow::ops::AsNodeOut(scope, size); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("RandomCrop"); auto builder = ::tensorflow::NodeBuilder(unique_name, "RandomCrop") .Input(_image) .Input(_size) .Attr("T", T) .Attr("seed", seed) .Attr("seed2", seed2) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } ResizeArea::ResizeArea(tensorflow::Scope& scope, tensorflow::Input images, tensorflow::Input size, bool align_corners) { if (!scope.ok()) return; auto _images = ::tensorflow::ops::AsNodeOut(scope, images); if (!scope.ok()) return; auto _size = ::tensorflow::ops::AsNodeOut(scope, size); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("ResizeArea"); auto builder = ::tensorflow::NodeBuilder(unique_name, "ResizeArea") .Input(_images) .Input(_size) .Attr("align_corners", align_corners) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } ResizeBicubic::ResizeBicubic(tensorflow::Scope& scope, tensorflow::Input images, tensorflow::Input size, bool align_corners) { if (!scope.ok()) return; auto _images = ::tensorflow::ops::AsNodeOut(scope, images); if (!scope.ok()) return; auto _size = ::tensorflow::ops::AsNodeOut(scope, size); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("ResizeBicubic"); auto builder = ::tensorflow::NodeBuilder(unique_name, "ResizeBicubic") .Input(_images) .Input(_size) .Attr("align_corners", align_corners) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } ResizeBicubicGrad::ResizeBicubicGrad(tensorflow::Scope& scope, tensorflow::Input grads, tensorflow::Input original_image, tensorflow::DataType T, bool align_corners) { if (!scope.ok()) return; auto _grads = ::tensorflow::ops::AsNodeOut(scope, grads); if (!scope.ok()) return; auto _original_image = ::tensorflow::ops::AsNodeOut(scope, original_image); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("ResizeBicubicGrad"); auto builder = ::tensorflow::NodeBuilder(unique_name, "ResizeBicubicGrad") .Input(_grads) .Input(_original_image) .Attr("T", T) .Attr("align_corners", align_corners) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } ResizeBilinear::ResizeBilinear(tensorflow::Scope& scope, tensorflow::Input images, tensorflow::Input size, bool align_corners) { if (!scope.ok()) return; auto _images = ::tensorflow::ops::AsNodeOut(scope, images); if (!scope.ok()) return; auto _size = ::tensorflow::ops::AsNodeOut(scope, size); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("ResizeBilinear"); auto builder = ::tensorflow::NodeBuilder(unique_name, "ResizeBilinear") .Input(_images) .Input(_size) .Attr("align_corners", align_corners) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } ResizeBilinearGrad::ResizeBilinearGrad(tensorflow::Scope& scope, tensorflow::Input grads, tensorflow::Input original_image, tensorflow::DataType T, bool align_corners) { if (!scope.ok()) return; auto _grads = ::tensorflow::ops::AsNodeOut(scope, grads); if (!scope.ok()) return; auto _original_image = ::tensorflow::ops::AsNodeOut(scope, original_image); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("ResizeBilinearGrad"); auto builder = ::tensorflow::NodeBuilder(unique_name, "ResizeBilinearGrad") .Input(_grads) .Input(_original_image) .Attr("T", T) .Attr("align_corners", align_corners) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } ResizeNearestNeighbor::ResizeNearestNeighbor(tensorflow::Scope& scope, tensorflow::Input images, tensorflow::Input size, tensorflow::DataType T, bool align_corners) { if (!scope.ok()) return; auto _images = ::tensorflow::ops::AsNodeOut(scope, images); if (!scope.ok()) return; auto _size = ::tensorflow::ops::AsNodeOut(scope, size); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("ResizeNearestNeighbor"); auto builder = ::tensorflow::NodeBuilder(unique_name, "ResizeNearestNeighbor") .Input(_images) .Input(_size) .Attr("T", T) .Attr("align_corners", align_corners) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } ResizeNearestNeighborGrad::ResizeNearestNeighborGrad(tensorflow::Scope& scope, tensorflow::Input grads, tensorflow::Input size, tensorflow::DataType T, bool align_corners) { if (!scope.ok()) return; auto _grads = ::tensorflow::ops::AsNodeOut(scope, grads); if (!scope.ok()) return; auto _size = ::tensorflow::ops::AsNodeOut(scope, size); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("ResizeNearestNeighborGrad"); auto builder = ::tensorflow::NodeBuilder(unique_name, "ResizeNearestNeighborGrad") .Input(_grads) .Input(_size) .Attr("T", T) .Attr("align_corners", align_corners) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } SampleDistortedBoundingBox::SampleDistortedBoundingBox(tensorflow::Scope& scope, tensorflow::Input image_size, tensorflow::Input bounding_boxes, tensorflow::DataType T, int64_t seed, int64_t seed2, float min_object_covered, tensorflow::gtl::ArraySlice<float> aspect_ratio_range, tensorflow::gtl::ArraySlice<float> area_range, int64_t max_attempts, bool use_image_if_no_bounding_boxes) { if (!scope.ok()) return; auto _image_size = ::tensorflow::ops::AsNodeOut(scope, image_size); if (!scope.ok()) return; auto _bounding_boxes = ::tensorflow::ops::AsNodeOut(scope, bounding_boxes); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("SampleDistortedBoundingBox"); auto builder = ::tensorflow::NodeBuilder(unique_name, "SampleDistortedBoundingBox") .Input(_image_size) .Input(_bounding_boxes) .Attr("T", T) .Attr("seed", seed) .Attr("seed2", seed2) .Attr("min_object_covered", min_object_covered) .Attr("aspect_ratio_range", aspect_ratio_range) .Attr("area_range", area_range) .Attr("max_attempts", max_attempts) .Attr("use_image_if_no_bounding_boxes", use_image_if_no_bounding_boxes) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } SampleDistortedBoundingBoxV2::SampleDistortedBoundingBoxV2(tensorflow::Scope& scope, tensorflow::Input image_size, tensorflow::Input bounding_boxes, tensorflow::Input min_object_covered, tensorflow::DataType T, int64_t seed, int64_t seed2, tensorflow::gtl::ArraySlice<float> aspect_ratio_range, tensorflow::gtl::ArraySlice<float> area_range, int64_t max_attempts, bool use_image_if_no_bounding_boxes) { if (!scope.ok()) return; auto _image_size = ::tensorflow::ops::AsNodeOut(scope, image_size); if (!scope.ok()) return; auto _bounding_boxes = ::tensorflow::ops::AsNodeOut(scope, bounding_boxes); if (!scope.ok()) return; auto _min_object_covered = ::tensorflow::ops::AsNodeOut(scope, min_object_covered); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("SampleDistortedBoundingBoxV2"); auto builder = ::tensorflow::NodeBuilder(unique_name, "SampleDistortedBoundingBoxV2") .Input(_image_size) .Input(_bounding_boxes) .Input(_min_object_covered) .Attr("T", T) .Attr("seed", seed) .Attr("seed2", seed2) .Attr("aspect_ratio_range", aspect_ratio_range) .Attr("area_range", area_range) .Attr("max_attempts", max_attempts) .Attr("use_image_if_no_bounding_boxes", use_image_if_no_bounding_boxes) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); }
43.104493
106
0.562992
MartinR20
a9b7dddb9080c4466de6e20a251b538f9ee83caa
2,717
cpp
C++
Public/src/Sandbox/MacOs/BuildXLSandbox/Src/Kauth/TrustedBsdHandler.cpp
blufugen/BuildXL
b7f33c72a3c9a8463fc6d656214a5c5dfccac7ad
[ "MIT" ]
null
null
null
Public/src/Sandbox/MacOs/BuildXLSandbox/Src/Kauth/TrustedBsdHandler.cpp
blufugen/BuildXL
b7f33c72a3c9a8463fc6d656214a5c5dfccac7ad
[ "MIT" ]
null
null
null
Public/src/Sandbox/MacOs/BuildXLSandbox/Src/Kauth/TrustedBsdHandler.cpp
blufugen/BuildXL
b7f33c72a3c9a8463fc6d656214a5c5dfccac7ad
[ "MIT" ]
null
null
null
// // TrustedBsdHandler.cpp // // Copyright © 2018 Microsoft. All rights reserved. // #include "TrustedBsdHandler.hpp" #include "OpNames.hpp" int TrustedBsdHandler::HandleLookup(const char *path) { PolicyResult policyResult = PolicyForPath(path); AccessCheckResult checkResult = policyResult.CheckReadAccess( RequestedReadAccess::Probe, FileReadContext(FileExistence::Nonexistent)); FileOperationContext fOp = FileOperationContext::CreateForRead(OpMacLookup, path); const OSSymbol *cacheKey = OSSymbol::withCString(path); Report(fOp, policyResult, checkResult, 0, cacheKey); OSSafeReleaseNULL(cacheKey); // Never deny lookups return KERN_SUCCESS; } int TrustedBsdHandler::HandleReadlink(vnode_t symlinkVNode) { // get symlink path char path[MAXPATHLEN]; int len = MAXPATHLEN; int err = vn_getpath(symlinkVNode, path, &len); if (err) { log_error("Could not get VNnode path for readlink operation; error code: %#X", err); return KERN_SUCCESS; // don't deny access because of our own error } // check read access PolicyResult policyResult = PolicyForPath(path); AccessCheckResult checkResult = policyResult.CheckExistingFileReadAccess(); FileOperationContext fOp = FileOperationContext::CreateForRead(OpMacReadlink, path); Report(fOp, policyResult, checkResult); if (checkResult.ShouldDenyAccess()) { LogAccessDenied(path, 0, "Operation: Readlink"); return EPERM; } else { return KERN_SUCCESS; } } int TrustedBsdHandler::HandleVNodeCreateEvent(const char *fullPath, const bool isDir, const bool isSymlink) { PolicyResult policyResult = PolicyForPath(fullPath); AccessCheckResult result = CheckCreate(policyResult, isDir, isSymlink); if (result.ShouldDenyAccess()) { LogAccessDenied(fullPath, 0, "Operation: VNodeCreate"); return EPERM; } else { return KERN_SUCCESS; } } AccessCheckResult TrustedBsdHandler::CheckCreate(PolicyResult policyResult, bool isDir, bool isSymlink) { AccessCheckResult checkResult = isSymlink ? policyResult.CheckSymlinkCreationAccess() : isDir ? policyResult.CheckDirectoryAccess(CheckDirectoryCreationAccessEnforcement(GetFamFlags())) : policyResult.CheckWriteAccess(); FileOperationContext fop = ToFileContext(OpMacVNodeCreate, GENERIC_WRITE, CreationDisposition::CreateAlways, policyResult.Path()); Report(fop, policyResult, checkResult); return checkResult; }
31.593023
111
0.67869
blufugen
a9b877861437253e1b573acee3a83ae4784a75fb
1,745
hpp
C++
src/org/apache/poi/ss/formula/SheetNameFormatter.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/ss/formula/SheetNameFormatter.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/ss/formula/SheetNameFormatter.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /POI/java/org/apache/poi/ss/formula/SheetNameFormatter.java #pragma once #include <fwd-POI.hpp> #include <java/lang/fwd-POI.hpp> #include <java/util/regex/fwd-POI.hpp> #include <org/apache/poi/ss/formula/fwd-POI.hpp> #include <java/lang/Object.hpp> struct default_init_tag; class poi::ss::formula::SheetNameFormatter final : public ::java::lang::Object { public: typedef ::java::lang::Object super; private: static constexpr char16_t DELIMITER { u'\'' }; static ::java::util::regex::Pattern* CELL_REF_PATTERN_; protected: void ctor(); public: static ::java::lang::String* format(::java::lang::String* rawSheetName); static void appendFormat(::java::lang::StringBuffer* out, ::java::lang::String* rawSheetName); static void appendFormat(::java::lang::StringBuffer* out, ::java::lang::String* workbookName, ::java::lang::String* rawSheetName); private: static void appendAndEscape(::java::lang::StringBuffer* sb, ::java::lang::String* rawSheetName); static bool needsDelimiting(::java::lang::String* rawSheetName); static bool nameLooksLikeBooleanLiteral(::java::lang::String* rawSheetName); public: /* package */ static bool isSpecialChar(char16_t ch); static bool cellReferenceIsWithinRange(::java::lang::String* lettersPrefix, ::java::lang::String* numbersSuffix); static bool nameLooksLikePlainCellReference(::java::lang::String* rawSheetName); // Generated private: SheetNameFormatter(); protected: SheetNameFormatter(const ::default_init_tag&); public: static ::java::lang::Class *class_(); static void clinit(); private: static ::java::util::regex::Pattern*& CELL_REF_PATTERN(); virtual ::java::lang::Class* getClass0(); };
30.614035
134
0.714613
pebble2015
a9b8f12283b6c49465c6aaa36c89acd50148f3b0
8,135
cc
C++
wrspice/src/cp/backq.cc
wrcad/xictools
f46ba6d42801426739cc8b2940a809b74f1641e2
[ "Apache-2.0" ]
73
2017-10-26T12:40:24.000Z
2022-03-02T16:59:43.000Z
wrspice/src/cp/backq.cc
chris-ayala/xictools
4ea72c118679caed700dab3d49a8d36445acaec3
[ "Apache-2.0" ]
12
2017-11-01T10:18:22.000Z
2022-03-20T19:35:36.000Z
wrspice/src/cp/backq.cc
chris-ayala/xictools
4ea72c118679caed700dab3d49a8d36445acaec3
[ "Apache-2.0" ]
34
2017-10-06T17:04:21.000Z
2022-02-18T16:22:03.000Z
/*========================================================================* * * * Distributed by Whiteley Research Inc., Sunnyvale, California, USA * * http://wrcad.com * * Copyright (C) 2017 Whiteley Research Inc., all rights reserved. * * Author: Stephen R. Whiteley, except as indicated. * * * * As fully as possible recognizing licensing terms and conditions * * imposed by earlier work from which this work was derived, if any, * * this work is released under the Apache License, Version 2.0 (the * * "License"). You may not use this file except in compliance with * * the License, and compliance with inherited licenses which are * * specified in a sub-header below this one if applicable. A copy * * of the License is provided with this distribution, or you may * * obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * See the License for the specific language governing permissions * * and limitations under the License. * * * * 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 NON- * * INFRINGEMENT. IN NO EVENT SHALL WHITELEY RESEARCH INCORPORATED * * OR STEPHEN R. WHITELEY 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. * * * *========================================================================* * XicTools Integrated Circuit Design System * * * * WRspice Circuit Simulation and Analysis Tool * * * *========================================================================* $Id:$ *========================================================================*/ /*************************************************************************** JSPICE3 adaptation of Spice3e2 - Copyright (c) Stephen R. Whiteley 1992 Copyright 1990 Regents of the University of California. All rights reserved. Authors: 1985 Wayne A. Christopher 1992 Stephen R. Whiteley ****************************************************************************/ #include "config.h" #include "cshell.h" #include "miscutil/filestat.h" #include "ginterf/graphics.h" #ifdef WIN32 #include <setjmp.h> #endif // // Do backquote substitution on a word list. // void CshPar::BackQuote(wordlist **list) { if (list == 0) return; wordlist *wlist = *list; for (wordlist *wl = wlist; wl; wl = wl->wl_next) { char *t = wl->wl_word; if (!t) continue; char *s; while ((s = strchr(t, cp_back)) != 0) { char *wbuf = new char[s - wl->wl_word + 1]; strncpy(wbuf, wl->wl_word, s - wl->wl_word); wbuf[s - wl->wl_word] = 0; char *bcmd = lstring::copy(s+1); t = s+1; s = bcmd; bool quoted = false; for (char *tm = wbuf; *tm; tm++) { if (*tm == '"') quoted = !quoted; } while (*s && (*s != cp_back)) { // Get s and t past the next backquote t++; s++; } *s = '\0'; if (*t) t++; // Get past the second ` wordlist *nwl = BackEval(bcmd); delete [] bcmd; if (!nwl || !nwl->wl_word) { delete [] wbuf; wordlist::destroy(wlist); *list = 0; return; } if (quoted && nwl->wl_next) { char *tt = wordlist::flatten(nwl); if (strlen(tt) + strlen(wbuf) + strlen(t) >= BSIZE_SP) { tt[BSIZE_SP - strlen(wbuf) - strlen(t) - 1] = 0; GRpkgIf()->ErrPrintf(ET_WARN, "line too long, truncated.\n"); } wordlist::destroy(nwl->wl_next); nwl->wl_next = 0; delete [] nwl->wl_word; nwl->wl_word = tt; } char *tt = new char[strlen(wbuf) + strlen(nwl->wl_word) + 1]; strcpy(tt, wbuf); strcat(tt, nwl->wl_word); delete [] nwl->wl_word; nwl->wl_word = tt; delete [] wbuf; t = lstring::copy(t); bool upd = (wl == wlist); wl = wl->splice(nwl); if (upd) wlist = nwl; int i = strlen(wl->wl_word); tt = new char[i + strlen(t) + 1]; strcpy(tt, wl->wl_word); strcat(tt, t); delete [] t; delete [] wl->wl_word; wl->wl_word = tt; t = &wl->wl_word[i]; } } *list = wlist; } // Do a popen with the string, and then reset the file pointers so that // we can use the first pass of the parser on the output. // wordlist * CshPar::BackEval(const char *string) { if (!*string) return (0); const char *sbak = string; char *tok = lstring::gettok(&string); if (tok && !strcasecmp(tok, "shell")) { delete [] tok; // This is the original Spice3 implementation. Now, we // prepend the command with "shell" to get here. FILE *proc = popen(string, "r"); if (proc == 0) { GRpkgIf()->ErrPrintf(ET_ERROR, "can't evaluate %s.\n", string); return (0); } FILE *old = cp_input; cp_input = proc; bool intv = cp_flags[CP_INTERACTIVE]; cp_flags[CP_INTERACTIVE] = false; cp_bqflag = true; wordlist *wl = Lexer(0); cp_bqflag = false; cp_input = old; cp_flags[CP_INTERACTIVE] = intv; pclose(proc); return (wl); } else { delete [] tok; string = sbak; // New implementation, use our own shell for evaluation. char *tempfile = filestat::make_temp("sp"); FILE *fp = fopen(tempfile, "w+"); TTY.ioPush(fp); CP.PushControl(); bool intr = cp_flags[CP_INTERACTIVE]; cp_flags[CP_INTERACTIVE] = false; #ifdef WIN32 extern jmp_buf msw_jbf[4]; extern int msw_jbf_sp; bool dopop = false; if (msw_jbf_sp < 3) { msw_jbf_sp++; dopop = true; } if (setjmp(msw_jbf[msw_jbf_sp]) == 0) { EvLoop(string); } if (dopop) msw_jbf_sp--; #else try { EvLoop(string); } catch (int) { } #endif cp_flags[CP_CWAIT] = true; // have to reset this cp_flags[CP_INTERACTIVE] = intr; CP.PopControl(); TTY.ioPop(); fflush(fp); rewind(fp); FILE *tfp = cp_input; cp_input = fp; cp_flags[CP_INTERACTIVE] = false; cp_bqflag = true; wordlist *wl = Lexer(0); cp_bqflag = false; cp_input = tfp; cp_flags[CP_INTERACTIVE] = intr; fclose(fp); unlink(tempfile); delete [] tempfile; return (wl); } }
34.914163
77
0.440688
wrcad
a9c0133b9f104104cb5810785435ad255377e0cf
1,284
hpp
C++
include/cpp/reproc/error.hpp
jetm/reproc
8289864d73172fba063078549b6e37369c6ecae7
[ "MIT" ]
1
2020-01-13T12:52:19.000Z
2020-01-13T12:52:19.000Z
include/cpp/reproc/error.hpp
jetm/reproc
8289864d73172fba063078549b6e37369c6ecae7
[ "MIT" ]
null
null
null
include/cpp/reproc/error.hpp
jetm/reproc
8289864d73172fba063078549b6e37369c6ecae7
[ "MIT" ]
null
null
null
/*! \file error.hpp */ #ifndef REPROC_ERROR_HPP #define REPROC_ERROR_HPP #include "export.hpp" #include <system_error> /*! \namespace reproc */ namespace reproc { /*! \see REPROC_ERROR */ // When editing make sure to change the corresponding enum in error.h as well. enum class errc { // reproc errors /*! #REPROC_WAIT_TIMEOUT */ wait_timeout = 1, /*! #REPROC_STREAM_CLOSED */ stream_closed, /*! #REPROC_PARTIAL_WRITE */ partial_write, // system errors /*! #REPROC_NOT_ENOUGH_MEMORY */ not_enough_memory, /*! #REPROC_PIPE_LIMIT_REACHED */ pipe_limit_reached, /*! #REPROC_INTERRUPTED */ interrupted, /*! #REPROC_PROCESS_LIMIT_REACHED */ process_limit_reached, /*! #REPROC_INVALID_UNICODE */ invalid_unicode, /*! #REPROC_PERMISSION_DENIED */ permission_denied, /*! #REPROC_SYMLINK_LOOP */ symlink_loop, /*! #REPROC_FILE_NOT_FOUND */ file_not_found, /*! #REPROC_NAME_TOO_LONG */ name_too_long }; /*! \private */ REPROC_EXPORT const std::error_category &error_category() noexcept; /*! \private */ REPROC_EXPORT std::error_condition make_error_condition(reproc::errc error) noexcept; } // namespace reproc namespace std { template <> struct is_error_condition_enum<reproc::errc> : true_type { }; } // namespace std #endif
19.454545
78
0.713396
jetm
a9c1cbb631d3b337281c74fa3054015f79e45fdc
2,500
cpp
C++
StockCommission/StockCommission.cpp
wof8317/StockCommission
cd1bad666a3f64132d1a10da9ee5b8ea5e19d48e
[ "WTFPL" ]
1
2021-09-16T23:44:04.000Z
2021-09-16T23:44:04.000Z
StockCommission/StockCommission.cpp
wof8317/StockCommission
cd1bad666a3f64132d1a10da9ee5b8ea5e19d48e
[ "WTFPL" ]
null
null
null
StockCommission/StockCommission.cpp
wof8317/StockCommission
cd1bad666a3f64132d1a10da9ee5b8ea5e19d48e
[ "WTFPL" ]
null
null
null
#include <iostream> #include <iomanip> using namespace std; int main() { double stockShares = 200; //Total stock shares double sharePrice = 21.77; //Share Price double brokerPercentage = 2; //Brokerage percentage double totalStockPrice = stockShares * sharePrice; //Total Stock price calculation double brokerCommission = totalStockPrice * (brokerPercentage / 100); //Brokerage commission calculation double grossTotal = totalStockPrice + brokerCommission; //Gross Total cout << "Kathrine bought " << stockShares << " shares of stock at a price of $" << sharePrice << " per share." << endl; cout << "She must pay her stock broker a " << brokerPercentage << " percent commission for the transaction." << endl; cout << "This is how much she has to pay..." << endl; cout << "\n-----------------------------------------" << endl; cout << stockShares << " shares @ $" << sharePrice << endl; cout << "-----------------------------------------" << endl; cout << "Total Stock Price: $" << setw(8) << setprecision(2) << fixed << totalStockPrice << endl; cout << "Broker Commission: $" << setw(8) << setprecision(2) << fixed << brokerCommission << endl; cout << "Gross Total: " << setw(7) << "$" << setw(8) << setprecision(2) << fixed << grossTotal << endl; cout << "\nHow many shares will you be buying? "; cin >> stockShares; cout << "\nWhat is the price per share? $"; cin >> sharePrice; cout << "\nWhat percentage will your broker be paid? (3 or 4 ...) "; cin >> brokerPercentage; /* Had to do this nasty hack below where I created new variables by appending a 1 after totalStockPrice, brokerCommission, and grossTotal to display the accurate calculations instead of repeating the initial calculations. I didn't like to do it, but it works. */ double totalStockPrice1 = stockShares * sharePrice; double brokerCommission1 = totalStockPrice1 * (brokerPercentage / 100); double grossTotal1 = totalStockPrice1 + brokerCommission1; cout << "\n-----------------------------------------" << endl; cout << setprecision(0) << stockShares << " shares @ $" << setprecision(2) << sharePrice << endl; cout << "-----------------------------------------" << endl; cout << "Stock Cost: $" << setw(10) << setprecision(2) << fixed << totalStockPrice1 << endl; cout << "Broker Fee: $" << setw(10) << setprecision(2) << fixed << brokerCommission1 << endl; cout << "Total Cost: $" << setw(10) << setprecision(2) << fixed << grossTotal1 << endl; cout << "\nHave a nice day!"; return 0; }
58.139535
148
0.6288
wof8317
a9c3814409cd06cf64948a035e7e27ed364d05b4
6,199
cpp
C++
streets_utils/streets_api/intersection_client_api/OAIIntersection_info.cpp
arseniy-sonar/carma-streets
394fc3609d417d92180c6b6c88e57d2edda9f854
[ "Apache-2.0" ]
3
2021-09-04T16:25:47.000Z
2022-03-09T20:24:30.000Z
streets_utils/streets_api/intersection_client_api/OAIIntersection_info.cpp
arseniy-sonar/carma-streets
394fc3609d417d92180c6b6c88e57d2edda9f854
[ "Apache-2.0" ]
85
2021-07-07T16:58:46.000Z
2022-03-31T15:35:26.000Z
streets_utils/streets_api/intersection_client_api/OAIIntersection_info.cpp
arseniy-sonar/carma-streets
394fc3609d417d92180c6b6c88e57d2edda9f854
[ "Apache-2.0" ]
4
2021-05-20T23:12:03.000Z
2021-09-08T15:33:42.000Z
/** * Intersection Model API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ #include "OAIIntersection_info.h" #include <QDebug> #include <QJsonArray> #include <QJsonDocument> #include <QObject> #include "OAIHelpers.h" namespace OpenAPI { OAIIntersection_info::OAIIntersection_info(QString json) { this->initializeModel(); this->fromJson(json); } OAIIntersection_info::OAIIntersection_info() { this->initializeModel(); } OAIIntersection_info::~OAIIntersection_info() {} void OAIIntersection_info::initializeModel() { m_id_isSet = false; m_id_isValid = false; m_name_isSet = false; m_name_isValid = false; m_entry_lanelets_isSet = false; m_entry_lanelets_isValid = false; m_link_lanelets_isSet = false; m_link_lanelets_isValid = false; m_departure_lanelets_isSet = false; m_departure_lanelets_isValid = false; } void OAIIntersection_info::fromJson(QString jsonString) { QByteArray array(jsonString.toStdString().c_str()); QJsonDocument doc = QJsonDocument::fromJson(array); QJsonObject jsonObject = doc.object(); this->fromJsonObject(jsonObject); } void OAIIntersection_info::fromJsonObject(QJsonObject json) { m_id_isValid = ::OpenAPI::fromJsonValue(id, json[QString("id")]); m_id_isSet = !json[QString("id")].isNull() && m_id_isValid; m_name_isValid = ::OpenAPI::fromJsonValue(name, json[QString("name")]); m_name_isSet = !json[QString("name")].isNull() && m_name_isValid; m_entry_lanelets_isValid = ::OpenAPI::fromJsonValue(entry_lanelets, json[QString("entry_lanelets")]); m_entry_lanelets_isSet = !json[QString("entry_lanelets")].isNull() && m_entry_lanelets_isValid; m_link_lanelets_isValid = ::OpenAPI::fromJsonValue(link_lanelets, json[QString("link_lanelets")]); m_link_lanelets_isSet = !json[QString("link_lanelets")].isNull() && m_link_lanelets_isValid; m_departure_lanelets_isValid = ::OpenAPI::fromJsonValue(departure_lanelets, json[QString("departure_lanelets")]); m_departure_lanelets_isSet = !json[QString("departure_lanelets")].isNull() && m_departure_lanelets_isValid; } QString OAIIntersection_info::asJson() const { QJsonObject obj = this->asJsonObject(); QJsonDocument doc(obj); QByteArray bytes = doc.toJson(); return QString(bytes); } QJsonObject OAIIntersection_info::asJsonObject() const { QJsonObject obj; if (m_id_isSet) { obj.insert(QString("id"), ::OpenAPI::toJsonValue(id)); } if (m_name_isSet) { obj.insert(QString("name"), ::OpenAPI::toJsonValue(name)); } if (entry_lanelets.size() > 0) { obj.insert(QString("entry_lanelets"), ::OpenAPI::toJsonValue(entry_lanelets)); } if (link_lanelets.size() > 0) { obj.insert(QString("link_lanelets"), ::OpenAPI::toJsonValue(link_lanelets)); } if (departure_lanelets.size() > 0) { obj.insert(QString("departure_lanelets"), ::OpenAPI::toJsonValue(departure_lanelets)); } return obj; } qint32 OAIIntersection_info::getId() const { return id; } void OAIIntersection_info::setId(const qint32 &id) { this->id = id; this->m_id_isSet = true; } bool OAIIntersection_info::is_id_Set() const{ return m_id_isSet; } bool OAIIntersection_info::is_id_Valid() const{ return m_id_isValid; } QString OAIIntersection_info::getName() const { return name; } void OAIIntersection_info::setName(const QString &name) { this->name = name; this->m_name_isSet = true; } bool OAIIntersection_info::is_name_Set() const{ return m_name_isSet; } bool OAIIntersection_info::is_name_Valid() const{ return m_name_isValid; } QList<OAILanelet_info> OAIIntersection_info::getEntryLanelets() const { return entry_lanelets; } void OAIIntersection_info::setEntryLanelets(const QList<OAILanelet_info> &entry_lanelets) { this->entry_lanelets = entry_lanelets; this->m_entry_lanelets_isSet = true; } bool OAIIntersection_info::is_entry_lanelets_Set() const{ return m_entry_lanelets_isSet; } bool OAIIntersection_info::is_entry_lanelets_Valid() const{ return m_entry_lanelets_isValid; } QList<OAILanelet_info> OAIIntersection_info::getLinkLanelets() const { return link_lanelets; } void OAIIntersection_info::setLinkLanelets(const QList<OAILanelet_info> &link_lanelets) { this->link_lanelets = link_lanelets; this->m_link_lanelets_isSet = true; } bool OAIIntersection_info::is_link_lanelets_Set() const{ return m_link_lanelets_isSet; } bool OAIIntersection_info::is_link_lanelets_Valid() const{ return m_link_lanelets_isValid; } QList<OAILanelet_info> OAIIntersection_info::getDepartureLanelets() const { return departure_lanelets; } void OAIIntersection_info::setDepartureLanelets(const QList<OAILanelet_info> &departure_lanelets) { this->departure_lanelets = departure_lanelets; this->m_departure_lanelets_isSet = true; } bool OAIIntersection_info::is_departure_lanelets_Set() const{ return m_departure_lanelets_isSet; } bool OAIIntersection_info::is_departure_lanelets_Valid() const{ return m_departure_lanelets_isValid; } bool OAIIntersection_info::isSet() const { bool isObjectUpdated = false; do { if (m_id_isSet) { isObjectUpdated = true; break; } if (m_name_isSet) { isObjectUpdated = true; break; } if (entry_lanelets.size() > 0) { isObjectUpdated = true; break; } if (link_lanelets.size() > 0) { isObjectUpdated = true; break; } if (departure_lanelets.size() > 0) { isObjectUpdated = true; break; } } while (false); return isObjectUpdated; } bool OAIIntersection_info::isValid() const { // only required properties are required for the object to be considered valid return true; } } // namespace OpenAPI
28.049774
117
0.71447
arseniy-sonar
a9cf13ee2272c8935d174539f8fb3bfa94d8e657
5,064
cpp
C++
src/components/src/core/attack/KeyboardMeleeAttackComponentTest.cpp
walter-strazak/chimarrao
b4c9f9d726eb5e46d61b33e10b7579cc5512cd09
[ "MIT" ]
null
null
null
src/components/src/core/attack/KeyboardMeleeAttackComponentTest.cpp
walter-strazak/chimarrao
b4c9f9d726eb5e46d61b33e10b7579cc5512cd09
[ "MIT" ]
null
null
null
src/components/src/core/attack/KeyboardMeleeAttackComponentTest.cpp
walter-strazak/chimarrao
b4c9f9d726eb5e46d61b33e10b7579cc5512cd09
[ "MIT" ]
null
null
null
#include "KeyboardMeleeAttackComponent.h" #include "gtest/gtest.h" #include "AnimatorMock.h" #include "FriendlyFireValidatorMock.h" #include "InputMock.h" #include "RayCastMock.h" #include "RendererPoolMock.h" #include "exceptions/DependentComponentNotFound.h" using namespace ::testing; using namespace components::core; class KeyboardMeleeAttackComponentTest : public Test { public: KeyboardMeleeAttackComponentTest() { componentOwner.addComponent<AnimationComponent>(animator); componentOwner.addComponent<VelocityComponent>(6); componentOwner.addComponent<DirectionComponent>(); componentOwner.addComponent<AnimationComponent>(animator); componentOwner.addComponent<BoxColliderComponent>(size); attackComponent.loadDependentComponents(); componentOwner.loadDependentComponents(); } const utils::Vector2f size{5, 5}; const utils::Vector2f position1{20, 20}; std::shared_ptr<NiceMock<graphics::RendererPoolMock>> rendererPool = std::make_shared<NiceMock<graphics::RendererPoolMock>>(); std::shared_ptr<components::core::SharedContext> sharedContext = std::make_shared<components::core::SharedContext>(rendererPool); ComponentOwner componentOwner{position1, "AttackComponentTest1", sharedContext}; StrictMock<input::InputMock> input; const utils::DeltaTime deltaTime{3}; std::shared_ptr<StrictMock<animations::AnimatorMock>> animator = std::make_shared<StrictMock<animations::AnimatorMock>>(); std::shared_ptr<StrictMock<physics::RayCastMock>> rayCast = std::make_shared<StrictMock<physics::RayCastMock>>(); std::unique_ptr<StrictMock<FriendlyFireValidatorMock>> friendlyFireValidatorInit{ std::make_unique<StrictMock<FriendlyFireValidatorMock>>()}; StrictMock<FriendlyFireValidatorMock>* friendlyFireValidator{friendlyFireValidatorInit.get()}; std::shared_ptr<MeleeAttack> meleeAttack = std::make_shared<MeleeAttack>(&componentOwner, rayCast, std::move(friendlyFireValidatorInit)); KeyboardMeleeAttackComponent attackComponent{&componentOwner, meleeAttack}; physics::RayCastResult rayCastResult{nullptr}; }; TEST_F(KeyboardMeleeAttackComponentTest, loadDependentComponentsWithoutAnimationComponent_shouldThrowDependentComponentNotFound) { ComponentOwner componentOwnerWithoutBoxCollider{position1, "componentOwnerWithoutBoxCollider", sharedContext}; KeyboardMeleeAttackComponent attackComponentWithoutBoxCollider{&componentOwnerWithoutBoxCollider, meleeAttack}; ASSERT_THROW(attackComponentWithoutBoxCollider.loadDependentComponents(), components::core::exceptions::DependentComponentNotFound); } TEST_F(KeyboardMeleeAttackComponentTest, givenSpaceNotPressed_shouldNotCallAttackStrategy) { EXPECT_CALL(input, isKeyPressed(input::InputKey::Space)).WillOnce(Return(false)); attackComponent.update(deltaTime, input); } TEST_F(KeyboardMeleeAttackComponentTest, givenSpacePressedAndAnimationIsAlreadyAttack_shouldNotCallAttackStrategy) { EXPECT_CALL(input, isKeyPressed(input::InputKey::Space)).WillOnce(Return(true)); EXPECT_CALL(*animator, getAnimationType()).WillOnce(Return(animations::AnimationType::Attack)); attackComponent.update(deltaTime, input); } TEST_F( KeyboardMeleeAttackComponentTest, givenSpacePressedAndAnimationIsDifferentThanAttackAndAttackAnimationProgressInLessThan60Percents_shouldSetAnimationToAttackAndNotCallAttackStrategy) { EXPECT_CALL(input, isKeyPressed(input::InputKey::Space)).WillOnce(Return(true)); EXPECT_CALL(*animator, getAnimationType()) .WillOnce(Return(animations::AnimationType::Idle)) .WillOnce(Return(animations::AnimationType::Idle)) .WillOnce(Return(animations::AnimationType::Attack)); EXPECT_CALL(*animator, setAnimation(animations::AnimationType::Attack)); EXPECT_CALL(*animator, getCurrentAnimationProgressInPercents()).WillOnce(Return(58)); attackComponent.update(deltaTime, input); } TEST_F( KeyboardMeleeAttackComponentTest, givenSpacePressedAndAnimationIsDifferentThanAttackAndAttackAnimationProgressInMoreThan60Percents_shouldSetAnimationToAttackAndCallAttackStrategy) { EXPECT_CALL(input, isKeyPressed(input::InputKey::Space)).WillOnce(Return(true)); EXPECT_CALL(*animator, getAnimationType()) .WillOnce(Return(animations::AnimationType::Idle)) .WillOnce(Return(animations::AnimationType::Idle)) .WillOnce(Return(animations::AnimationType::Attack)); EXPECT_CALL(*animator, setAnimation(animations::AnimationType::Attack)); EXPECT_CALL(*animator, getCurrentAnimationProgressInPercents()).WillOnce(Return(63)); EXPECT_CALL(*animator, getAnimationDirection()).WillOnce(Return(animations::AnimationDirection::Left)); EXPECT_CALL(*rayCast, cast(_, _, _, _)).WillOnce(Return(rayCastResult)); attackComponent.update(deltaTime, input); }
45.621622
152
0.7656
walter-strazak
a9dc791f2ff6d477391fe1e44f17828fd4c659c6
5,487
cpp
C++
libs/log/example/doc/extension_stat_collector.cpp
HelloSunyi/boost_1_54_0
429fea793612f973d4b7a0e69c5af8156ae2b56e
[ "BSL-1.0" ]
7
2015-03-03T15:45:12.000Z
2021-04-25T03:37:17.000Z
libs/log/example/doc/extension_stat_collector.cpp
graehl/boost
37cc4ca77896a86ad10e90dc03e1e825dc0d5492
[ "BSL-1.0" ]
1
2015-09-05T12:23:01.000Z
2015-09-05T12:23:01.000Z
libs/log/example/doc/extension_stat_collector.cpp
graehl/boost
37cc4ca77896a86ad10e90dc03e1e825dc0d5492
[ "BSL-1.0" ]
2
2018-06-21T15:08:14.000Z
2021-04-25T03:37:22.000Z
/* * Copyright Andrey Semashev 2007 - 2013. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ #include <string> #include <fstream> #include <iostream> #include <stdexcept> #include <boost/shared_ptr.hpp> #include <boost/date_time/posix_time/posix_time_types.hpp> #include <boost/phoenix.hpp> #include <boost/log/core.hpp> #include <boost/log/expressions.hpp> #include <boost/log/sinks/sync_frontend.hpp> #include <boost/log/sinks/basic_sink_backend.hpp> #include <boost/log/sources/logger.hpp> #include <boost/log/sources/record_ostream.hpp> #include <boost/log/attributes/value_visitation.hpp> #include <boost/log/utility/manipulators/add_value.hpp> namespace logging = boost::log; namespace src = boost::log::sources; namespace expr = boost::log::expressions; namespace sinks = boost::log::sinks; namespace keywords = boost::log::keywords; //[ example_extension_stat_collector_definition // The backend collects statistical information about network activity of the application class stat_collector : public sinks::basic_sink_backend< sinks::combine_requirements< sinks::synchronized_feeding, /*< we will have to store internal data, so let's require frontend to synchronize feeding calls to the backend >*/ sinks::flushing /*< also enable flushing support >*/ >::type > { private: // The file to write the collected information to std::ofstream m_csv_file; // Here goes the data collected so far: // Active connections unsigned int m_active_connections; // Sent bytes unsigned int m_sent_bytes; // Received bytes unsigned int m_received_bytes; // The number of collected records since the last write to the file unsigned int m_collected_count; // The time when the collected data has been written to the file last time boost::posix_time::ptime m_last_store_time; public: // The constructor initializes the internal data explicit stat_collector(const char* file_name); // The function consumes the log records that come from the frontend void consume(logging::record_view const& rec); // The function flushes the file void flush(); private: // The function resets statistical accumulators to initial values void reset_accumulators(); // The function writes the collected data to the file void write_data(); }; //] // The constructor initializes the internal data stat_collector::stat_collector(const char* file_name) : m_csv_file(file_name, std::ios::app), m_active_connections(0), m_last_store_time(boost::posix_time::microsec_clock::universal_time()) { reset_accumulators(); if (!m_csv_file.is_open()) throw std::runtime_error("could not open the CSV file"); } //[ example_extension_stat_collector_consume BOOST_LOG_ATTRIBUTE_KEYWORD(sent, "Sent", unsigned int) BOOST_LOG_ATTRIBUTE_KEYWORD(received, "Received", unsigned int) // The function consumes the log records that come from the frontend void stat_collector::consume(logging::record_view const& rec) { // Accumulate statistical readings if (rec.attribute_values().count("Connected")) ++m_active_connections; else if (rec.attribute_values().count("Disconnected")) --m_active_connections; else { namespace phoenix = boost::phoenix; logging::visit(sent, rec, phoenix::ref(m_sent_bytes) += phoenix::placeholders::_1); logging::visit(received, rec, phoenix::ref(m_received_bytes) += phoenix::placeholders::_1); } ++m_collected_count; // Check if it's time to write the accumulated data to the file boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time(); if (now - m_last_store_time >= boost::posix_time::minutes(1)) { write_data(); m_last_store_time = now; } } // The function writes the collected data to the file void stat_collector::write_data() { m_csv_file << m_active_connections << ',' << m_sent_bytes << ',' << m_received_bytes << std::endl; reset_accumulators(); } // The function resets statistical accumulators to initial values void stat_collector::reset_accumulators() { m_sent_bytes = m_received_bytes = 0; m_collected_count = 0; } //] //[ example_extension_stat_collector_flush // The function flushes the file void stat_collector::flush() { // Store any data that may have been collected since the list write to the file if (m_collected_count > 0) { write_data(); m_last_store_time = boost::posix_time::microsec_clock::universal_time(); } m_csv_file.flush(); } //] // Complete sink type typedef sinks::synchronous_sink< stat_collector > sink_t; void init_logging() { boost::shared_ptr< logging::core > core = logging::core::get(); boost::shared_ptr< stat_collector > backend(new stat_collector("stat.csv")); boost::shared_ptr< sink_t > sink(new sink_t(backend)); core->add_sink(sink); } int main(int, char*[]) { init_logging(); src::logger lg; BOOST_LOG(lg) << logging::add_value("Connected", true); BOOST_LOG(lg) << logging::add_value("Sent", 100u); BOOST_LOG(lg) << logging::add_value("Received", 200u); logging::core::get()->flush(); return 0; }
31.901163
194
0.69692
HelloSunyi
a9ddbab5bf1fb4deca3be377f9454a1f8cf6d1d9
1,483
cpp
C++
TrackAlgTLD/src/tld/VarianceFilter.cpp
RayanWang/CameraTrackingFramework
1ab2f7289cd000a4baa584bca469744a5486610f
[ "MIT" ]
3
2016-11-05T03:31:48.000Z
2016-12-07T05:57:28.000Z
TrackAlgTLD/src/tld/VarianceFilter.cpp
RayanWang/CameraTrackingFramework
1ab2f7289cd000a4baa584bca469744a5486610f
[ "MIT" ]
null
null
null
TrackAlgTLD/src/tld/VarianceFilter.cpp
RayanWang/CameraTrackingFramework
1ab2f7289cd000a4baa584bca469744a5486610f
[ "MIT" ]
3
2018-11-10T17:19:49.000Z
2020-04-11T16:30:26.000Z
#include "VarianceFilter.h" #include "IntegralImage.h" #include "DetectorCascade.h" using namespace cv; namespace tld { VarianceFilter::VarianceFilter() { enabled = true; minVar = 0; integralImg = NULL; integralImg_squared = NULL; } VarianceFilter::~VarianceFilter() { release(); } void VarianceFilter::release() { if(integralImg != NULL) delete integralImg; integralImg = NULL; if(integralImg_squared != NULL) delete integralImg_squared; integralImg_squared = NULL; } float VarianceFilter::calcVariance(int *off) { int *ii1 = integralImg->data; long long *ii2 = integralImg_squared->data; float mX = (ii1[off[3]] - ii1[off[2]] - ii1[off[1]] + ii1[off[0]]) / (float) off[5]; //Sum of Area divided by area float mX2 = (ii2[off[3]] - ii2[off[2]] - ii2[off[1]] + ii2[off[0]]) / (float) off[5]; return mX2 - mX * mX; } void VarianceFilter::nextIteration(const Mat &img) { if(!enabled) return; release(); integralImg = new IntegralImage<int>(img.size()); integralImg->calcIntImg(img); integralImg_squared = new IntegralImage<long long>(img.size()); integralImg_squared->calcIntImg(img, true); } bool VarianceFilter::filter(int i) { if(!enabled) return true; float bboxvar = calcVariance(windowOffsets + TLD_WINDOW_OFFSET_SIZE * i); detectionResult->variances[i] = bboxvar; if(bboxvar < minVar) { return false; } return true; } } /* namespace tld */
19.513158
119
0.656777
RayanWang
a9deb353db8fc5d30f5b4f7b0b1f3a8963dcec3c
1,440
hpp
C++
code/client/src/sdk/ue/sys/math/utils.hpp
mufty/MafiaMP
2dc0e3362c505079e26e598bd4a7f4b5de7400bc
[ "OpenSSL" ]
16
2021-10-08T17:47:04.000Z
2022-03-28T13:26:37.000Z
code/client/src/sdk/ue/sys/math/utils.hpp
mufty/MafiaMP
2dc0e3362c505079e26e598bd4a7f4b5de7400bc
[ "OpenSSL" ]
4
2022-01-19T08:11:57.000Z
2022-01-29T19:02:24.000Z
code/client/src/sdk/ue/sys/math/utils.hpp
mufty/MafiaMP
2dc0e3362c505079e26e598bd4a7f4b5de7400bc
[ "OpenSSL" ]
4
2021-10-09T11:15:08.000Z
2022-01-27T22:42:26.000Z
#pragma once #include <algorithm> #include <chrono> namespace SDK { namespace ue::sys::math { template <class T> T Lerp(const T &from, const T &to, float fAlpha) { return (T)((to - from) * fAlpha + from); } // Find the relative position of Pos between From and To inline const float Unlerp(const double from, const double to, const double pos) { // Avoid dividing by 0 (results in INF values) if (from == to) return 1.0f; return static_cast<float>((pos - from) / (to - from)); } inline const float Unlerp(const std::chrono::high_resolution_clock::time_point &from, const std::chrono::high_resolution_clock::time_point &to, const std::chrono::high_resolution_clock::time_point &pos) { float r = std::chrono::duration<float, std::milli>(to - from).count(); // Avoid dividing by 0 (results in INF values) if (r < std::numeric_limits<float>::epsilon()) return 1.0f; return std::chrono::duration<float, std::milli>(pos - from).count() / r; } // Unlerp avoiding extrapolation inline const float UnlerpClamped(const double from, const double to, const double pos) { return std::clamp(Unlerp(from, to, pos), 0.0f, 1.0f); } }; // namespace ue::sys::math } // namespace SDK
38.918919
151
0.579167
mufty
a9e1598a57924d76b824131c3f84fe4f6fc8e22e
6,924
inl
C++
Base/PLCore/include/PLCore/Xml/XmlNode.inl
ktotheoz/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
83
2015-01-08T15:06:14.000Z
2021-07-20T17:07:00.000Z
Base/PLCore/include/PLCore/Xml/XmlNode.inl
PixelLightFoundation/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
27
2019-06-18T06:46:07.000Z
2020-02-02T11:11:28.000Z
Base/PLCore/include/PLCore/Xml/XmlNode.inl
naetherm/PixelLight
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
40
2015-02-25T18:24:34.000Z
2021-03-06T09:01:48.000Z
/*********************************************************\ * File: XmlNode.inl * * * Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/) * * This file is part of PixelLight. * * 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. \*********************************************************/ //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace PLCore { //[-------------------------------------------------------] //[ Public functions ] //[-------------------------------------------------------] /** * @brief * The meaning of 'value' changes for the specific type of 'XmlNode' */ inline String XmlNode::GetValue() const { return m_sValue; } /** * @brief * Changes the value of the node */ inline void XmlNode::SetValue(const String &sValue) { m_sValue = sValue; } /** * @brief * One step up the DOM */ inline XmlNode *XmlNode::GetParent() { return m_pParent; } inline const XmlNode *XmlNode::GetParent() const { return m_pParent; } /** * @brief * Returns the first child of this node */ inline XmlNode *XmlNode::GetFirstChild() { return m_pFirstChild; } inline const XmlNode *XmlNode::GetFirstChild() const { return m_pFirstChild; } /** * @brief * Returns the last child of this node */ inline XmlNode *XmlNode::GetLastChild() { return m_pLastChild; } inline const XmlNode *XmlNode::GetLastChild() const { return m_pLastChild; } /** * @brief * An alternate way to walk the children of a node */ inline XmlNode *XmlNode::IterateChildren(XmlNode *pPrevious) { return const_cast< XmlNode* >( (const_cast< const XmlNode* >(this))->IterateChildren( pPrevious ) ); } inline const XmlNode *XmlNode::IterateChildren(const XmlNode *pPrevious) const { return pPrevious ? pPrevious->GetNextSibling() : GetFirstChild(); } /** * @brief * This flavor of 'IterateChildren()' searches for children with a particular 'value' */ inline XmlNode *XmlNode::IterateChildren(const String &sValue, XmlNode *pPrevious) { return pPrevious ? pPrevious->GetNextSibling(sValue) : GetFirstChild(sValue); } inline const XmlNode *XmlNode::IterateChildren(const String &sValue, const XmlNode *pPrevious) const { return pPrevious ? pPrevious->GetNextSibling(sValue) : GetFirstChild(sValue); } /** * @brief * Navigate to a sibling node */ inline XmlNode *XmlNode::GetPreviousSibling() { return m_pPreviousSibling; } inline const XmlNode *XmlNode::GetPreviousSibling() const { return m_pPreviousSibling; } /** * @brief * Navigate to a sibling node */ inline XmlNode *XmlNode::GetNextSibling() { return m_pNextSibling; } inline const XmlNode *XmlNode::GetNextSibling() const { return m_pNextSibling; } /** * @brief * Convenience function to get through elements */ inline XmlElement *XmlNode::GetNextSiblingElement() { return const_cast< XmlElement* >( (const_cast< const XmlNode* >(this))->GetNextSiblingElement() ); } /** * @brief * Convenience function to get through elements */ inline XmlElement *XmlNode::GetFirstChildElement() { return const_cast< XmlElement* >( (const_cast< const XmlNode* >(this))->GetFirstChildElement() ); } /** * @brief * Convenience function to get through elements */ inline XmlElement *XmlNode::GetFirstChildElement(const String &sValue) { return const_cast< XmlElement* >( (const_cast< const XmlNode* >(this))->GetFirstChildElement( sValue ) ); } /** * @brief * Query the type (as an enumerated value, above) of this node */ inline XmlNode::ENodeType XmlNode::GetType() const { return m_nType; } /** * @brief * Return a pointer to the document this node lives in */ inline XmlDocument *XmlNode::GetDocument() { return const_cast< XmlDocument* >( (const_cast< const XmlNode* >(this))->GetDocument() ); } /** * @brief * Returns true if this node has no children */ inline bool XmlNode::NoChildren() const { return !m_pFirstChild; } /** * @brief * Cast functions */ inline XmlDocument *XmlNode::ToDocument() { return (m_nType == Document) ? reinterpret_cast<XmlDocument*>(this) : nullptr; } inline const XmlDocument *XmlNode::ToDocument() const { return (m_nType == Document) ? reinterpret_cast<const XmlDocument*>(this) : nullptr; } inline XmlElement *XmlNode::ToElement() { return (m_nType == Element) ? reinterpret_cast<XmlElement*>(this) : nullptr; } inline const XmlElement *XmlNode::ToElement() const { return (m_nType == Element) ? reinterpret_cast<const XmlElement*>(this) : nullptr; } inline XmlComment *XmlNode::ToComment() { return (m_nType == Comment) ? reinterpret_cast<XmlComment*>(this) : nullptr; } inline const XmlComment *XmlNode::ToComment() const { return (m_nType == Comment) ? reinterpret_cast<const XmlComment*>(this) : nullptr; } inline XmlUnknown *XmlNode::ToUnknown() { return (m_nType == Unknown) ? reinterpret_cast<XmlUnknown*>(this) : nullptr; } inline const XmlUnknown *XmlNode::ToUnknown() const { return (m_nType == Unknown) ? reinterpret_cast<const XmlUnknown*>(this) : nullptr; } inline XmlText *XmlNode::ToText() { return (m_nType == Text) ? reinterpret_cast<XmlText*>(this) : nullptr; } inline const XmlText *XmlNode::ToText() const { return (m_nType == Text) ? reinterpret_cast<const XmlText*>(this) : nullptr; } inline XmlDeclaration *XmlNode::ToDeclaration() { return (m_nType == Declaration) ? reinterpret_cast<XmlDeclaration*>(this) : nullptr; } inline const XmlDeclaration *XmlNode::ToDeclaration() const { return (m_nType == Declaration) ? reinterpret_cast<const XmlDeclaration*>(this) : nullptr; } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // PLCore
25.362637
106
0.656557
ktotheoz
a9e198693653c41b6af3f15700fb519cbf552555
5,588
cpp
C++
tests/unit/weightedgraph_test.cpp
hyunsukimsokcho/libdai
52c0b51823724f02c7a268e6af6db72dc3324385
[ "BSD-2-Clause" ]
11
2018-01-31T16:14:28.000Z
2021-06-22T03:45:11.000Z
tests/unit/weightedgraph_test.cpp
flurischt/libDAI
20683a222e2ef307209290f79081fe428d9c5050
[ "BSD-2-Clause" ]
1
2019-05-25T08:20:58.000Z
2020-02-17T10:58:55.000Z
tests/unit/weightedgraph_test.cpp
flurischt/libDAI
20683a222e2ef307209290f79081fe428d9c5050
[ "BSD-2-Clause" ]
3
2018-12-13T11:49:22.000Z
2021-12-31T03:19:26.000Z
/* This file is part of libDAI - http://www.libdai.org/ * * Copyright (c) 2006-2011, The libDAI authors. All rights reserved. * * Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #include <dai/weightedgraph.h> #include <dai/exceptions.h> #include <strstream> #include <vector> using namespace dai; #define BOOST_TEST_MODULE WeighedGraphTest #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_CASE( DEdgeTest ) { DEdge a; BOOST_CHECK_EQUAL( a.first, 0 ); BOOST_CHECK_EQUAL( a.second, 0 ); DEdge b( 3, 5 ); BOOST_CHECK_EQUAL( b.first, 3 ); BOOST_CHECK_EQUAL( b.second, 5 ); DEdge c( 5, 3 ); BOOST_CHECK_EQUAL( c.first, 5 ); BOOST_CHECK_EQUAL( c.second, 3 ); DEdge d( c ); DEdge e = c; DEdge f( 5, 4 ); DEdge g( 3, 6 ); BOOST_CHECK( !(a == b) ); BOOST_CHECK( !(a == c) ); BOOST_CHECK( !(b == c) ); BOOST_CHECK( d == c ); BOOST_CHECK( c == d ); BOOST_CHECK( e == c ); BOOST_CHECK( c == e ); BOOST_CHECK( d == e ); BOOST_CHECK( e == d ); BOOST_CHECK( a < b ); BOOST_CHECK( a < c ); BOOST_CHECK( b < c ); BOOST_CHECK( !(c < d) ); BOOST_CHECK( !(b < a) ); BOOST_CHECK( !(c < a) ); BOOST_CHECK( !(c < b) ); BOOST_CHECK( !(d < c) ); BOOST_CHECK( a < f ); BOOST_CHECK( b < f ); BOOST_CHECK( c < f ); BOOST_CHECK( g < f ); BOOST_CHECK( !(f < a) ); BOOST_CHECK( !(f < b) ); BOOST_CHECK( !(f < c) ); BOOST_CHECK( !(f < g) ); BOOST_CHECK( a < g ); BOOST_CHECK( b < g ); BOOST_CHECK( !(c < g) ); BOOST_CHECK( !(g < a) ); BOOST_CHECK( !(g < b) ); BOOST_CHECK( g < c ); std::stringstream ss; ss << c; std::string s; ss >> s; BOOST_CHECK_EQUAL( s, "(5->3)" ); BOOST_CHECK_EQUAL( c.toString(), s ); } BOOST_AUTO_TEST_CASE( UEdgeTest ) { UEdge a; BOOST_CHECK_EQUAL( a.first, 0 ); BOOST_CHECK_EQUAL( a.second, 0 ); UEdge b( 3, 5 ); BOOST_CHECK_EQUAL( b.first, 3 ); BOOST_CHECK_EQUAL( b.second, 5 ); UEdge c( 5, 3 ); BOOST_CHECK_EQUAL( c.first, 5 ); BOOST_CHECK_EQUAL( c.second, 3 ); UEdge d( c ); UEdge e = c; UEdge f( 5, 4 ); UEdge g( 3, 6 ); UEdge h( DEdge( 5, 3 ) ); BOOST_CHECK_EQUAL( h.first, 5 ); BOOST_CHECK_EQUAL( h.second, 3 ); BOOST_CHECK( !(a == b) ); BOOST_CHECK( !(a == c) ); BOOST_CHECK( b == c ); BOOST_CHECK( d == c ); BOOST_CHECK( c == d ); BOOST_CHECK( e == c ); BOOST_CHECK( c == e ); BOOST_CHECK( d == e ); BOOST_CHECK( e == d ); BOOST_CHECK( a < b ); BOOST_CHECK( a < c ); BOOST_CHECK( !(b < c) ); BOOST_CHECK( !(c < d) ); BOOST_CHECK( !(b < a) ); BOOST_CHECK( !(c < a) ); BOOST_CHECK( !(c < b) ); BOOST_CHECK( !(d < c) ); BOOST_CHECK( a < f ); BOOST_CHECK( b < f ); BOOST_CHECK( c < f ); BOOST_CHECK( g < f ); BOOST_CHECK( !(f < a) ); BOOST_CHECK( !(f < b) ); BOOST_CHECK( !(f < c) ); BOOST_CHECK( !(f < g) ); BOOST_CHECK( a < g ); BOOST_CHECK( b < g ); BOOST_CHECK( c < g ); BOOST_CHECK( !(g < a) ); BOOST_CHECK( !(g < b) ); BOOST_CHECK( !(g < c) ); std::stringstream ss; std::string s; ss << c; ss >> s; BOOST_CHECK_EQUAL( s, "{3--5}" ); BOOST_CHECK_EQUAL( c.toString(), s ); ss << b; ss >> s; BOOST_CHECK_EQUAL( s, "{3--5}" ); BOOST_CHECK_EQUAL( b.toString(), s ); } BOOST_AUTO_TEST_CASE( RootedTreeTest ) { typedef UEdge E; std::vector<E> edges; edges.push_back( E( 1, 2 ) ); edges.push_back( E( 2, 3 ) ); edges.push_back( E( 3, 1 ) ); GraphEL G( edges.begin(), edges.end() ); BOOST_CHECK_THROW( RootedTree T( G, 0 ), Exception ); BOOST_CHECK_THROW( RootedTree T( G, 1 ), Exception ); edges.back().second = 4; G = GraphEL( edges.begin(), edges.end() ); RootedTree T; T = RootedTree( G, 1 ); BOOST_CHECK_EQUAL( T.size(), 3 ); BOOST_CHECK_EQUAL( T[0], DEdge( 1, 2 ) ); BOOST_CHECK_EQUAL( T[1], DEdge( 2, 3 ) ); BOOST_CHECK_EQUAL( T[2], DEdge( 3, 4 ) ); edges.push_back( E(5, 6) ); G = GraphEL( edges.begin(), edges.end() ); BOOST_CHECK_THROW( RootedTree T( G, 1 ), Exception ); GraphAL H( 3 ); H.addEdge( 0, 1 ); H.addEdge( 1, 2 ); H.addEdge( 2, 1 ); G = GraphEL( H ); for( GraphEL::const_iterator e = G.begin(); e != G.end(); e++ ) BOOST_CHECK( H.hasEdge( e->first, e->second ) ); } BOOST_AUTO_TEST_CASE( SpanningTreeTest ) { RootedTree T; WeightedGraph<int> G; G[UEdge(0,1)] = 1; G[UEdge(0,2)] = 2; G[UEdge(1,2)] = 3; G[UEdge(1,3)] = 4; G[UEdge(2,3)] = 5; RootedTree TMin; TMin.push_back( DEdge( 0,1 ) ); TMin.push_back( DEdge( 0,2 ) ); TMin.push_back( DEdge( 1,3 ) ); RootedTree TMax; TMax.push_back( DEdge( 0,2 ) ); TMax.push_back( DEdge( 2,3 ) ); TMax.push_back( DEdge( 3,1 ) ); // T = MinSpanningTree( G, true ); // disabled because of bug in boost graph library 1.54 // BOOST_CHECK_EQUAL( T, TMin ); T = MinSpanningTree( G, false ); BOOST_CHECK_EQUAL( T, TMin ); // T = MaxSpanningTree( G, true ); // disabled because of bug in boost graph library 1.54 // BOOST_CHECK_EQUAL( T, TMax ); T = MaxSpanningTree( G, false ); BOOST_CHECK_EQUAL( T, TMax ); WeightedGraph<double> H; H[UEdge(1,2)] = 1; H[UEdge(1,3)] = 2; H[UEdge(2,3)] = 3; H[UEdge(2,4)] = 4; H[UEdge(3,4)] = 5; BOOST_CHECK_THROW( T = MinSpanningTree( H, true ), Exception ); }
25.87037
101
0.549571
hyunsukimsokcho
a9e78ea74bc4acba6164bd009514a281a592a07b
1,149
cpp
C++
src/_leetcode/leet_989.cpp
turesnake/leetPractice
a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b
[ "MIT" ]
null
null
null
src/_leetcode/leet_989.cpp
turesnake/leetPractice
a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b
[ "MIT" ]
null
null
null
src/_leetcode/leet_989.cpp
turesnake/leetPractice
a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b
[ "MIT" ]
null
null
null
/* * ====================== leet_989.cpp ========================== * -- tpr -- * CREATE -- 2020.05.27 * MODIFY -- * ---------------------------------------------------------- * 989. 数组形式的整数加法 */ #include "innLeet.h" #include "TreeNode1.h" namespace leet_989 {//~ std::vector<int> addToArrayForm( std::vector<int>& A, int K ){ int Na = static_cast<int>(A.size()); std::deque<int> que {}; int carry = 0; for( int a=Na-1; a>=0 || K>0; a--, K=K/10 ){ int va = (a>=0) ? A.at(a) : 0; int vk = K%10; int tmp = va + vk + carry; carry = tmp/10; que.push_front( tmp%10 ); } if( carry>0 ){ que.push_front(1); } return std::vector<int>(que.begin(), que.end()); } //=========================================================// void main_(){ std::vector<int> a { 1,2,3,4,5 }; auto ret = addToArrayForm( a, 0 ); cout <<"ret:"<<endl; for( int i : ret ){ cout <<i<<", "; } cout << endl; debug::log( "\n~~~~ leet: 989 :end ~~~~\n" ); } }//~
20.890909
65
0.369887
turesnake
a9e9f922330e0e1e94d484150355aba412b97d56
60
cpp
C++
libconfig/Config.cpp
qiu708/libconfig
24e79f923c96a5210a1dc5603000d90b56b13318
[ "MIT" ]
null
null
null
libconfig/Config.cpp
qiu708/libconfig
24e79f923c96a5210a1dc5603000d90b56b13318
[ "MIT" ]
null
null
null
libconfig/Config.cpp
qiu708/libconfig
24e79f923c96a5210a1dc5603000d90b56b13318
[ "MIT" ]
null
null
null
// // Created by qiu on 2021/12/20. // #include "Config.h"
10
32
0.6
qiu708
a9f867f9cc8f26e44f516e481f2f1cf203fac7a4
2,915
cpp
C++
WorkScript/Type/FloatType.cpp
jingjiajie/WorkScript
6b80932fcdbae0e915c37bac19d262025234074b
[ "MIT" ]
3
2018-07-23T10:59:00.000Z
2019-04-05T04:57:19.000Z
WorkScript/Type/FloatType.cpp
jingjiajie/WorkScript
6b80932fcdbae0e915c37bac19d262025234074b
[ "MIT" ]
null
null
null
WorkScript/Type/FloatType.cpp
jingjiajie/WorkScript
6b80932fcdbae0e915c37bac19d262025234074b
[ "MIT" ]
1
2019-06-28T05:57:47.000Z
2019-06-28T05:57:47.000Z
#include "Type.h" #include "Function.h" #include "Module.h" #include "Utils.h" #include "FloatType.h" #include "Exception.h" using namespace std; using namespace WorkScript; std::unordered_map<std::wstring, FloatType*> FloatType::types; Finalizer FloatType::staticFinalizer(&FloatType::releaseTypes); FloatType::FloatType(FloatTypeClassification cls, bool isConst, bool isVolatile) noexcept :classification(cls), _const(isConst),_volatile(isVolatile) { } std::wstring WorkScript::FloatType::getName() const noexcept { wstring str; if(this->_const) str += L"const "; if(this->_volatile) str += L"volatile "; switch(this->classification){ case FloatTypeClassification::FLOAT: str += L"float"; break; case FloatTypeClassification::DOUBLE: str += L"double"; break; // case FloatTypeClassification::LONG_DOUBLE: // str += L"long double"; // break; } return str; } std::wstring WorkScript::FloatType::getMangledName() const noexcept { return FloatType::getMangledName(this->classification, this->_const, this->_volatile); } std::wstring FloatType::getMangledName(FloatTypeClassification cls, bool isConst, bool isVolatile) noexcept{ wstring name; if(isConst) name += L"K"; switch(cls){ case FloatTypeClassification::FLOAT: name += L"f"; break; case FloatTypeClassification::DOUBLE: name += L"d"; break; // case FloatTypeClassification::LONG_DOUBLE: // name += L"e"; // break; } return name; } TypeClassification WorkScript::FloatType::getClassification() const noexcept { return TypeClassification::FLOAT; } llvm::Type * WorkScript::FloatType::getLLVMType(GenerateContext *context) const { llvm::LLVMContext &ctx = *context->getLLVMContext(); auto len = this->getLength(); switch (len) { case 32: return llvm::Type::getFloatTy(ctx); case 64: return llvm::Type::getDoubleTy(ctx); default: throw InternalException(L"不支持的浮点类型长度:" + to_wstring(len)); } } bool WorkScript::FloatType::equals(const Type * type) const noexcept { if (type->getClassification() != TypeClassification::FLOAT)return false; auto *target = (const FloatType*)type; if (this->classification != target->classification)return false; return true; } void WorkScript::FloatType::releaseTypes() noexcept { for (auto it : types) { delete it.second; } } FloatType * WorkScript::FloatType::get(FloatTypeClassification cls, bool isConst, bool isVolatile) noexcept { wstring idStr = FloatType::getMangledName(cls, isConst, isVolatile); auto it = types.find(idStr); if (it != types.end()) return it->second; else return (types[idStr] = new FloatType(cls, isConst, isVolatile)); } unsigned FloatType::getLength() const noexcept { switch(this->classification) { case FloatTypeClassification::FLOAT: return 32; case FloatTypeClassification::DOUBLE: return 64; // case FloatTypeClassification::LONG_DOUBLE: // return 80; default: return 0; } }
25.347826
108
0.726244
jingjiajie
a9fb12b3adb18fd085f45d92ae9eb6fb1bbce2a6
2,820
cpp
C++
src/utilities/QrDefinitions.cpp
jce-caba/gtkQRmm
0a6f46bdbbc30195c2ddf993be43d218dbc2c47a
[ "MIT" ]
1
2022-03-13T14:21:23.000Z
2022-03-13T14:21:23.000Z
src/utilities/QrDefinitions.cpp
jce-caba/gtkQRmm
0a6f46bdbbc30195c2ddf993be43d218dbc2c47a
[ "MIT" ]
null
null
null
src/utilities/QrDefinitions.cpp
jce-caba/gtkQRmm
0a6f46bdbbc30195c2ddf993be43d218dbc2c47a
[ "MIT" ]
null
null
null
#include "QrDefinitions.hpp" using namespace GtkQR; QRDataContainer::QRDataContainer() { correction_level = QRErrorCorrectionLevel ::QR_ERROR_CORRECTION_LEVEL_MEDIUM; isMicro=false; enable_UTF8=true; qrversion_number = QR_NO_VERSION; qrversion = QRVersion::QR_VERSION_NULL; mask = QR_NO_MASK; } QRDataContainer::QRDataContainer(const QRDataContainer &other) { copyparameters(const_cast<QRDataContainer &>(other)); copylist(other); } QRDataContainer::QRDataContainer(QRDataContainer &&other) { unsigned short aux = num_modules; copyparameters(other); std::swap(eci_mode,other.eci_mode); other.num_modules =aux; } QRDataContainer& QRDataContainer::operator=(const QRDataContainer &other) { copyparameters(const_cast<QRDataContainer &>(other)); copylist(other); return *this; } QRDataContainer& QRDataContainer::operator=(QRDataContainer &&other) { unsigned short aux = num_modules; copyparameters(other); std::swap(eci_mode,other.eci_mode); other.num_modules =aux; return *this; } void QRDataContainer::copyparameters(QRDataContainer &other) { enable_UTF8= other.enable_UTF8; isMicro= other.isMicro; isMicro= other.isMicro; correction_level= other.correction_level; qrversion= other.qrversion; qrversion_number= other.qrversion_number; num_modules= other.num_modules; mask= other.mask; num_eci_mode= other.num_eci_mode; data_coding= other.data_coding; error= other.error; warning= other.warning; } void QRDataContainer::copylist(const QRDataContainer &other) { eci_mode.clear(); for (std::list<QREciMode>::const_iterator it=other.eci_mode.begin(); it != other.eci_mode.end(); ++it) eci_mode.push_back (*it); } QRDataContainer::~QRDataContainer() { } QRVersion QRDataContainer::getqrversion() { return qrversion; } short QRDataContainer::getqrversion_number() { return qrversion_number; } unsigned short QRDataContainer::getnum_modules() { return num_modules; } unsigned short QRDataContainer::getnum_mask() { return mask; } QREciMode QRDataContainer::geteci_mode(int position) { QREciMode eci=QREciMode::QR_ECI_MODE_ISO_8859_1; int i=0; bool finded=false; std::list<QREciMode>::const_iterator it=eci_mode.begin(); while(it != eci_mode.end() && !finded) { if(i==position) { eci= *it; finded=true; } else { i++; ++it; } } return eci; } unsigned short QRDataContainer::getnum_eci_mode() { return num_eci_mode; } QRData QRDataContainer::getdata_coding() { return data_coding; } std:: string & QRDataContainer::geterror() { return error; } std:: string & QRDataContainer::getwarning() { return warning; }
20.735294
105
0.697163
jce-caba
a9ff6b9a7748e61e7aefed30a0a8c592e913db79
891
cpp
C++
STACK/Reverse a string using stack.cpp
snanacha/Coding-questions
18c4b5a23fc3da5c419d2ec69fbf13b7b4ecee0d
[ "MIT" ]
null
null
null
STACK/Reverse a string using stack.cpp
snanacha/Coding-questions
18c4b5a23fc3da5c419d2ec69fbf13b7b4ecee0d
[ "MIT" ]
1
2021-03-30T14:00:56.000Z
2021-03-30T14:00:56.000Z
STACK/Reverse a string using stack.cpp
snanacha/Coding-questions
18c4b5a23fc3da5c419d2ec69fbf13b7b4ecee0d
[ "MIT" ]
null
null
null
/* Reverse a string using Stack ---------------------------- Easy Accuracy: 54.33% Submissions: 27645 Points: 2 You are given a string S, the task is to reverse the string using stack. Example 1: Input: S="GeeksforGeeks" Output: skeeGrofskeeG Your Task: You don't need to read input or print anything. Y our task is to complete the function reverse() which takes the string S as an input parameter and returns the reversed string. Expected Time Complexity: O(N) Expected Auxiliary Space: O(N) Constraints: 1 ≤ length of the string ≤ 100 */ ----- CODE ----- //return the address of the string char* reverse(char *S, int len) { //code here stack<char> ans; for(int i=0;S[i]!='\0';i++) { ans.push(S[i]); } int i=0; while(!ans.empty()) { S[i++]=ans.top(); ans.pop(); } return S; }
21.214286
127
0.590348
snanacha
e7001d3cbe9d9c9a755e7c74634c4bccdd3eef33
726
cpp
C++
arm9/source/lz77.cpp
RocketRobz/RocketVideoPlayer
be4a671078dbad2f4e7224418a8ee21e5b0fca86
[ "MIT" ]
20
2019-05-20T16:40:30.000Z
2022-02-21T09:35:41.000Z
arm9/source/lz77.cpp
RocketRobz/RocketVideoPlayer
be4a671078dbad2f4e7224418a8ee21e5b0fca86
[ "MIT" ]
1
2020-11-21T22:54:23.000Z
2020-11-21T23:21:26.000Z
arm9/source/lz77.cpp
RocketRobz/RocketVideoPlayer
be4a671078dbad2f4e7224418a8ee21e5b0fca86
[ "MIT" ]
2
2019-09-02T02:16:32.000Z
2019-09-06T14:01:52.000Z
#include <nds.h> #include "tonccpy.h" #define __itcm __attribute__((section(".itcm"))) void __itcm lzssDecompress(u8* source, u8* destination) { u32 leng = (source[1] | (source[2] << 8) | (source[3] << 16)); int Offs = 4; int dstoffs = 0; while (true) { u8 header = source[Offs++]; for (int i = 0; i < 8; i++) { if ((header & 0x80) == 0) destination[dstoffs++] = source[Offs++]; else { u8 a = source[Offs++]; u8 b = source[Offs++]; int offs = (((a & 0xF) << 8) | b) + 1; int length = (a >> 4) + 3; for (int j = 0; j < length; j++) { destination[dstoffs] = destination[dstoffs - offs]; dstoffs++; } } if (dstoffs >= (int)leng) return; header <<= 1; } } }
21.352941
69
0.528926
RocketRobz
e70a6facbf9bd6f8f86c7ebac1a7667ba4081c16
4,377
hpp
C++
Common_3/ThirdParty/OpenSource/ModifiedSonyMath/sse/vecidx.hpp
RemiArnaud/The-Forge
70f5f4b544831ea3a51de2ad4a7f341fb1b971c5
[ "Apache-2.0" ]
29
2019-02-17T08:17:41.000Z
2022-03-06T17:46:55.000Z
Common_3/ThirdParty/OpenSource/ModifiedSonyMath/sse/vecidx.hpp
guillaumeblanc/The-Forge
0df6d608ed7ec556f17b91a749e2f19d75973dc9
[ "Apache-2.0" ]
1
2019-06-11T08:35:32.000Z
2019-06-11T08:35:32.000Z
Common_3/ThirdParty/OpenSource/ModifiedSonyMath/sse/vecidx.hpp
guillaumeblanc/The-Forge
0df6d608ed7ec556f17b91a749e2f19d75973dc9
[ "Apache-2.0" ]
6
2019-05-06T07:54:58.000Z
2021-09-29T00:25:11.000Z
/* Copyright (C) 2006, 2007 Sony Computer Entertainment Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * 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 Sony Computer Entertainment Inc nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef VECTORMATH_SSE_VECIDX_HPP #define VECTORMATH_SSE_VECIDX_HPP namespace Vectormath { namespace SSE { // ======================================================== // VecIdx // ======================================================== // Used in setting elements of Vector3, Vector4, Point3, or Quat // with the subscripting operator []. VECTORMATH_ALIGNED_TYPE_PRE class VecIdx { __m128 & ref; int i; public: inline VecIdx(__m128 & vec, int idx) : ref(vec), i(idx) { } // // implicitly casts to float unless VECTORMATH_NO_SCALAR_CAST defined // in which case, implicitly casts to FloatInVec, and one must call // getAsFloat() to convert to float. // #ifdef VECTORMATH_NO_SCALAR_CAST inline operator FloatInVec() const; inline float getAsFloat() const; #else // !VECTORMATH_NO_SCALAR_CAST inline operator float() const; #endif // VECTORMATH_NO_SCALAR_CAST inline float operator = (float scalar); inline FloatInVec operator = (const FloatInVec & scalar); inline FloatInVec operator = (const VecIdx & scalar); inline FloatInVec operator *= (float scalar); inline FloatInVec operator *= (const FloatInVec & scalar); inline FloatInVec operator /= (float scalar); inline FloatInVec operator /= (const FloatInVec & scalar); inline FloatInVec operator += (float scalar); inline FloatInVec operator += (const FloatInVec & scalar); inline FloatInVec operator -= (float scalar); inline FloatInVec operator -= (const FloatInVec & scalar); } VECTORMATH_ALIGNED_TYPE_POST; //========================================= #ConfettiMathExtensionsStart ================================================ // ======================================================== // IVecIdx // ======================================================== // Used in setting elements of IVector3, IVector4 // with the subscripting operator []. VECTORMATH_ALIGNED_TYPE_PRE class IVecIdx { __m128i & ref; int i; public: inline IVecIdx(__m128i & vec, int idx) : ref(vec), i(idx) {} // // implicitly casts to int unless VECTORMATH_NO_SCALAR_CAST defined // #ifdef VECTORMATH_NO_SCALAR_CAST inline int getAsInt() const; #else // !VECTORMATH_NO_SCALAR_CAST inline operator int() const; #endif // VECTORMATH_NO_SCALAR_CAST inline int operator = (int scalar); inline int operator = (const IVecIdx & scalar); inline int operator *= (int scalar); inline int operator /= (int scalar); inline int operator += (int scalar); inline int operator -= (int scalar); } VECTORMATH_ALIGNED_TYPE_POST; //========================================= #ConfettiMathExtensionsEnd ================================================ } // namespace SSE } // namespace Vectormath #endif // VECTORMATH_SSE_VECIDX_HPP
36.475
121
0.673749
RemiArnaud
e70c2ef5786889df55c9b27b07c30810347deedd
9,832
cpp
C++
src/vulkan/VulkanContext.cpp
choiip/fui
dc54b2d29c423a5b257dd7d812e5d5f52a10ba8a
[ "Zlib" ]
null
null
null
src/vulkan/VulkanContext.cpp
choiip/fui
dc54b2d29c423a5b257dd7d812e5d5f52a10ba8a
[ "Zlib" ]
null
null
null
src/vulkan/VulkanContext.cpp
choiip/fui
dc54b2d29c423a5b257dd7d812e5d5f52a10ba8a
[ "Zlib" ]
null
null
null
#include "vulkan/VulkanContext.hpp" #include "vku.hpp" #define NANOVG_VULKAN_IMPLEMENTATION #include "nanovg_vk.h" #include "core/Log.hpp" #include "core/MathDef.hpp" #include "core/Status.hpp" namespace fui { struct VulkanContext::Private { std::shared_ptr<vk::UniqueInstance> instance; vk::SurfaceKHR surface; std::shared_ptr<vk::su::SwapChainData> swapchain; vk::PhysicalDevice gpu; vk::UniqueDevice device; vk::UniqueCommandPool commandPool; vk::Queue graphicsQueue; vk::Queue presentQueue; vk::UniqueCommandBuffer commandBuffer; vk::UniqueSemaphore presentComplete; vk::UniqueSemaphore renderComplete; vk::UniqueRenderPass renderPass; std::vector<vk::UniqueFramebuffer> framebuffers; uint32_t currentBuffer; vk::Extent2D frameExtent; std::shared_ptr<vk::su::DepthBufferData> depthBuffer; std::shared_ptr<vk::UniqueDebugReportCallbackEXT> debugCallback; }; VulkanContext::VulkanContext(const std::shared_ptr<vk::UniqueInstance>& instance, const std::shared_ptr<vk::UniqueDebugReportCallbackEXT>& debugReportCallback) { _p.reset(new Private); _p->instance = instance; _p->debugCallback = debugReportCallback; auto gpuResult = instance->get().enumeratePhysicalDevices(); if (!gpuResult.empty()) { _p->gpu = gpuResult[0]; } else { LOGE << "vkEnumeratePhysicalDevices failed "; } auto queueFamilyProperties = _p->gpu.getQueueFamilyProperties(); auto graphicsQueueFamilyIndex = vk::su::findGraphicsQueueFamilyIndex(queueFamilyProperties); constexpr float queuePriorities[] = {0.f}; vk::DeviceQueueCreateInfo deviceQueueCreateInfo(vk::DeviceQueueCreateFlags(), graphicsQueueFamilyIndex, 1, queuePriorities); const char* deviceExtensions[] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME}; constexpr auto deviceExtensionsCount = sizeof(deviceExtensions) / sizeof(deviceExtensions[0]); vk::PhysicalDeviceFeatures deviceFeatures; deviceFeatures.samplerAnisotropy = true; vk::DeviceCreateInfo deviceCreateInfo(vk::DeviceCreateFlags(), 1, &deviceQueueCreateInfo, 0, nullptr, deviceExtensionsCount, deviceExtensions, &deviceFeatures); _p->device = _p->gpu.createDeviceUnique(deviceCreateInfo); _p->graphicsQueue = _p->device->getQueue(graphicsQueueFamilyIndex, 0); auto d = _p->device.get(); /* Create a command pool to allocate our command buffer from */ _p->commandPool = d.createCommandPoolUnique({vk::CommandPoolCreateFlagBits::eResetCommandBuffer, graphicsQueueFamilyIndex}); auto commandBuffers = d.allocateCommandBuffersUnique({_p->commandPool.get(), vk::CommandBufferLevel::ePrimary, 1}); _p->commandBuffer = std::move(commandBuffers[0]); } VulkanContext::~VulkanContext() { _p->device->waitIdle(); nvgDeleteVk(vg()); _p->renderComplete.reset(); _p->presentComplete.reset(); _p->framebuffers.clear(); _p->renderPass.reset(); _p->depthBuffer.reset(); _p->swapchain.reset(); _p->commandBuffer.reset(); _p->commandPool.reset(); _p->device.reset(); _p->instance->get().destroySurfaceKHR(_p->surface, NULL); } vk::PhysicalDevice& VulkanContext::physicalDevice() { return _p->gpu; } vk::Device& VulkanContext::device() { return _p->device.get(); } vk::SurfaceKHR& VulkanContext::surface() { return _p->surface; } vk::Queue& VulkanContext::graphicsQueue() { return _p->graphicsQueue; } vk::Queue& VulkanContext::presentQueue() { return _p->presentQueue; } Status VulkanContext::initSwapchain(const vk::SurfaceKHR& surface, const vk::Extent2D& extent) { auto queueIndices = vk::su::findGraphicsAndPresentQueueFamilyIndex(_p->gpu, surface); auto graphicsQueueFamilyIndex = queueIndices.first; auto presentQueueFamilyIndex = queueIndices.second; _p->graphicsQueue = _p->device->getQueue(graphicsQueueFamilyIndex, 0); _p->presentQueue = _p->device->getQueue(presentQueueFamilyIndex, 0); auto oldSwapChainData = _p->swapchain ? std::move(_p->swapchain->swapChain) : vk::UniqueSwapchainKHR(); _p->surface = surface; _p->frameExtent = extent; _p->swapchain = std::make_shared<vk::su::SwapChainData>( _p->gpu, _p->device, surface, _p->frameExtent, vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransferSrc, oldSwapChainData, graphicsQueueFamilyIndex, presentQueueFamilyIndex); return Status::OK; } Status VulkanContext::initFramebuffer(const vk::Extent2D& extent) { vk::Format depthFormat = vk::su::pickDepthFormat(_p->gpu); auto colorFormat = _p->swapchain->colorFormat; _p->renderPass = vk::su::createRenderPass(_p->device, colorFormat, depthFormat); _p->presentComplete = _p->device->createSemaphoreUnique(vk::SemaphoreCreateInfo()); _p->renderComplete = _p->device->createSemaphoreUnique(vk::SemaphoreCreateInfo()); _p->depthBuffer = std::make_shared<vk::su::DepthBufferData>(_p->gpu, _p->device, depthFormat, extent); vk::su::oneTimeSubmit(_p->commandBuffer, _p->graphicsQueue, [&](vk::UniqueCommandBuffer const& commandBuffer) { vk::su::setImageLayout(commandBuffer, *_p->depthBuffer->image, depthFormat, vk::ImageLayout::eUndefined, vk::ImageLayout::eDepthStencilAttachmentOptimal); }); _p->framebuffers = vk::su::createFramebuffers(_p->device, _p->renderPass, _p->swapchain->imageViews, _p->depthBuffer->imageView, extent); return Status::OK; } Status VulkanContext::initVG() { if (_vg != nullptr) { nvgDeleteVk(_vg); } VKNVGCreateInfo createInfo = {0}; createInfo.gpu = _p->gpu; createInfo.device = _p->device.get(); createInfo.queue = _p->graphicsQueue; createInfo.renderPass = _p->renderPass.get(); createInfo.cmdBuffer = _p->commandBuffer.get(); int flag = NVG_ANTIALIAS | NVG_STENCIL_STROKES; #ifdef NDEBUG flag |= NVG_DEBUG; #endif _vg = nvgCreateVk(createInfo, flag); if (_vg == NULL) { LOGE << "Could not init nanovg (Vulkan)."; return Status::UNKNOWN_ERROR; } return Status::OK; } Status VulkanContext::rebuildSwapchain() { auto extent = _p->frameExtent; _p->device->waitIdle(); initSwapchain(_p->surface, extent); vk::Format depthFormat = _p->depthBuffer->format; *(_p->depthBuffer) = vk::su::DepthBufferData(_p->gpu, _p->device, depthFormat, extent); vk::su::oneTimeSubmit(_p->commandBuffer, _p->graphicsQueue, [&](vk::UniqueCommandBuffer const& commandBuffer) { vk::su::setImageLayout(commandBuffer, *_p->depthBuffer->image, depthFormat, vk::ImageLayout::eUndefined, vk::ImageLayout::eDepthStencilAttachmentOptimal); }); _p->framebuffers = vk::su::createFramebuffers(_p->device, _p->renderPass, _p->swapchain->imageViews, _p->depthBuffer->imageView, extent); return Status::OK; } auto VulkanContext::setViewport(int x, int y, int width, int height) -> decltype(this) { vk::Viewport viewport = {(float)x, (float)y, (float)width, (float)height, 0.f, 1.f}; vk::Rect2D scissor = {{x, y}, {(uint32_t)width, (uint32_t)height}}; _p->commandBuffer->setViewport(0, 1, &viewport); _p->commandBuffer->setScissor(0, 1, &scissor); return this; } auto VulkanContext::preDraw(const Recti& renderArea, const Color* clearColor, const float* clearDepth, const int* clearStencil) -> decltype(this) { if (renderArea.w != _p->frameExtent.width || renderArea.h != _p->frameExtent.height) { _p->frameExtent = vk::Extent2D(renderArea.w, renderArea.h); rebuildSwapchain(); } auto&& cb = _p->currentBuffer; // Get the index of the next available swapchain image: _p->device->acquireNextImageKHR(_p->swapchain->swapChain.get(), vk::su::FenceTimeout, _p->presentComplete.get(), nullptr, &cb); if (clearColor != nullptr) {} if (clearDepth != nullptr) {} if (clearStencil != nullptr) {} vk::ClearValue clearValues[2]; clearValues[0].color.float32[0] = 0.3f; clearValues[0].color.float32[1] = 0.3f; clearValues[0].color.float32[2] = 0.32f; clearValues[0].color.float32[3] = 1.0f; clearValues[1].depthStencil.depth = 1.0f; clearValues[1].depthStencil.stencil = 0; vk::RenderPassBeginInfo renderPassBeginInfo; renderPassBeginInfo.pNext = NULL; renderPassBeginInfo.renderPass = _p->renderPass.get(); renderPassBeginInfo.framebuffer = _p->framebuffers[cb].get(); renderPassBeginInfo.renderArea.offset.x = renderArea.x; renderPassBeginInfo.renderArea.offset.y = renderArea.y; renderPassBeginInfo.renderArea.extent.width = renderArea.w; renderPassBeginInfo.renderArea.extent.height = renderArea.h; renderPassBeginInfo.clearValueCount = 2; renderPassBeginInfo.pClearValues = clearValues; _p->commandBuffer->begin(vk::CommandBufferBeginInfo()); _p->commandBuffer->beginRenderPass(renderPassBeginInfo, vk::SubpassContents::eInline); return setViewport(renderArea.x, renderArea.y, renderArea.w, renderArea.h); } auto VulkanContext::postDraw() -> decltype(this) { auto&& cb = _p->currentBuffer; _p->commandBuffer->endRenderPass(); _p->commandBuffer->end(); vk::PipelineStageFlags pipelineStageFlags = vk::PipelineStageFlagBits::eColorAttachmentOutput; vk::SubmitInfo submitInfo(1, &_p->presentComplete.get(), &pipelineStageFlags, 1, &_p->commandBuffer.get(), 1, &_p->renderComplete.get()); /* Queue the command buffer for execution */ _p->graphicsQueue.submit(submitInfo, nullptr); /* Now present the image in the window */ vk::PresentInfoKHR presentInfo(1, &_p->renderComplete.get(), 1, &_p->swapchain->swapChain.get(), &cb); try { _p->graphicsQueue.presentKHR(presentInfo); _p->graphicsQueue.waitIdle(); } catch (const vk::OutOfDateKHRError&) {} return this; } } // namespace fui
37.96139
117
0.710537
choiip
e70c2f82e1106fd4437a6d6209dacdba5d81c43f
8,463
cc
C++
biosig4octmat-3.2.0/biosig/maybe-missing/regexprep.cc
TianGL/CNN-MI-BCI
788493ffc954df153cd928d84090d9625ff357d4
[ "MIT" ]
41
2018-10-30T07:40:11.000Z
2022-02-25T13:37:40.000Z
biosig4octmat-3.2.0/biosig/maybe-missing/regexprep.cc
TianGL/CNN-SAE-MI-BCI-
788493ffc954df153cd928d84090d9625ff357d4
[ "MIT" ]
2
2018-11-30T17:47:07.000Z
2022-02-22T22:45:17.000Z
biosig4octmat-2.90/biosig/maybe-missing/regexprep.cc
wilkesk/cSPider
89db77e3f534decc37b01d47dff37f576f4725a1
[ "BSD-2-Clause" ]
13
2018-12-18T13:54:01.000Z
2022-03-08T13:03:28.000Z
// This code is public domain. // Author: Paul Kienzle #ifdef HAVE_CONFIG_H # include <config.h> #else # include <octave/config.h> #endif #include "defun-dld.h" #include "error.h" #include "parse.h" #include "quit.h" #include "Cell.h" DEFUN_DLD(regexprep,args,nargout,"\ -*- texinfo -*-\n\ @deftypefn {Function File} @var{string} = regexprep(@var{string}, @var{pat}, @var{repstr}, @var{options})\n\ Replace matches of @var{pat} in @var{string} with @var{repstr}.\n\ \n\ \n\ The replacement can contain @code{$i}, which subsubstitutes\n\ for the ith set of parentheses in the match string. E.g.,\n\ @example\n\ \n\ regexprep(\"Bill Dunn\",'(\\w+) (\\w+)','$2, $1')\n\ \n\ @end example\n\ returns \"Dunn, Bill\"\n\ \n\ @var{options} may be zero or more of\n\ @table @samp\n\ \n\ @item once\n\ Replace only the first occurance of @var{pat} in the result.\n\ \n\ @item warnings\n\ This option is present for compatibility but is ignored.\n\ \n\ @item ignorecase or matchcase\n\ Ignore case for the pattern matching (see @code{regexpi}).\n\ Alternatively, use (?i) or (?-i) in the pattern.\n\ \n\ @item lineanchors and stringanchors\n\ Whether characters ^ and $ match the beginning and ending of lines.\n\ Alternatively, use (?m) or (?-m) in the pattern.\n\ \n\ @item dotexceptnewline and dotall\n\ Whether . matches newlines in the string.\n\ Alternatively, use (?s) or (?-s) in the pattern.\n\ \n\ @item freespacing or literalspacing\n\ Whether whitespace and # comments can be used to make the regular expression more readable.\n\ Alternatively, use (?x) or (?-x) in the pattern.\n\ \n\ @end table\n\ @seealso{regexp,regexpi}\n\ @end deftypefn") { octave_value_list retval; int nargin = args.length(); int nopts = nargin - 3; if (nargin < 3) { print_usage("regexprep"); return retval; } // Make sure we have string,pattern,replacement const std::string buffer = args(0).string_value (); if (error_state) return retval; const std::string pattern = args(1).string_value (); if (error_state) return retval; const std::string replacement = args(2).string_value (); if (error_state) return retval; // Pack options excluding 'tokenize' and various output // reordering strings into regexp arg list octave_value_list regexpargs(nargin-1,octave_value()); regexpargs(0) = args(0); regexpargs(1) = args(1); int len=2; for (int i = 3; i < nargin; i++) { const std::string opt = args(i).string_value(); if (opt != "tokenize" && opt != "start" && opt != "end" && opt != "tokenextents" && opt != "match" && opt != "tokens" && opt != "names" && opt != "warnings") { regexpargs(len++) = args(i); } } regexpargs.resize(len); //std::cout << "Buffer " << buffer << std::endl; //std::cout << "Pattern " << pattern << std::endl; //std::cout << "Replacement " << replacement << std::endl; // Identify replacement tokens; build a vector of group numbers in // the replacement string so that we can quickly calculate the size // of the replacement. int tokens = 0; for (size_t i=1; i < replacement.size(); i++) { if (replacement[i-1]=='$' && isdigit(replacement[i])) { tokens++, i++; } } std::vector<int> token(tokens); int k=0; for (size_t i=1; i < replacement.size(); i++) { if (replacement[i-1]=='$' && isdigit(replacement[i])) { token[k++] = replacement[i]-'0'; i++; } } // Perform replacement std::string rep; if (tokens > 0) { // Call regexp, asking for start, end, and capture start/end octave_value_list regexpret = feval("regexp", regexpargs, 3); if (regexpret(0).is_empty()) { retval(0) = args(0); return retval; } const ColumnVector s(regexpret(0).vector_value()); const ColumnVector e(regexpret(1).vector_value()); const Cell te(regexpret(2).cell_value()); if (error_state) return retval; // Determine replacement length const size_t replen = replacement.size() - 2*tokens; int delta = 0; for (int i=0; i < s.length(); i++) { OCTAVE_QUIT; const Matrix pairs(te(i).matrix_value()); size_t pairlen = 0; for (int j=0; j < tokens; j++) { if (token[j] == 0) pairlen += size_t(e(i)-s(i))+1; else if (token[j] <= pairs.rows()) pairlen += size_t(pairs(token[j]-1,1)-pairs(token[j]-1,0))+1; } delta += int(replen + pairlen) - int(e(i)-s(i)+1); } // std::cout << "replacement delta is " << delta << std::endl; // Build replacement string rep.reserve(buffer.size()+delta); size_t from = 0; for (int i=0; i < s.length(); i++) { OCTAVE_QUIT; const Matrix pairs(te(i).matrix_value()); rep.append(&buffer[from], size_t(s(i)-1)-from); from = size_t(e(i)-1)+1; for (size_t j=1; j < replacement.size(); j++) { if (replacement[j-1]=='$' && isdigit(replacement[j])) { int k = replacement[j]-'0'; if (k==0) { // replace with entire match rep.append(&buffer[size_t(e(i)-1)], size_t(e(i)-s(i))+1); } else if (k <= pairs.rows()) { // replace with group capture // std::cout << "k=" << k << " [" << pairs(k-1,0) << "," << pairs(k-1,1) << "]" << std::endl; rep.append(&buffer[size_t(pairs(k-1,0)-1)], size_t(pairs(k-1,1)-pairs(k-1,0))+1); } else { // replace with nothing } j++; } else { rep.append(1,replacement[j-1]); if (j == replacement.size()-1) { rep.append(1,replacement[j]); } } } // std::cout << "->" << rep << std::endl; } rep.append(&buffer[from],buffer.size()-from); } else { // Call regexp, asking for start, end octave_value_list regexpret = feval("regexp", regexpargs, 2); if (regexpret(0).is_empty()) { retval(0) = args(0); return retval; } const ColumnVector s(regexpret(0).vector_value()); const ColumnVector e(regexpret(1).vector_value()); if (error_state) return retval; // Determine replacement length const size_t replen = replacement.size(); int delta = 0; for (int i=0; i < s.length(); i++) { OCTAVE_QUIT; delta += int(replen) - int(e(i)-s(i)+1); } // std::cout << "replacement delta is " << delta << std::endl; // Build replacement string rep.reserve(buffer.size()+delta); size_t from = 0; for (int i=0; i < s.length(); i++) { OCTAVE_QUIT; rep.append(&buffer[from],size_t(s(i)-1)-from); from = size_t(e(i)-1)+1; rep.append(replacement); // std::cout << "->" << rep << std::endl; } rep.append(&buffer[from],buffer.size()-from); } retval(0) = rep; return retval; } /* %!test # Replace with empty %! xml = '<!-- This is some XML --> <tag v="hello">some stuff<!-- sample tag--></tag>'; %! t = regexprep(xml,'<[!?][^>]*>',''); %! assert(t,' <tag v="hello">some stuff</tag>') %!test # Replace with non-empty %! xml = '<!-- This is some XML --> <tag v="hello">some stuff<!-- sample tag--></tag>'; %! t = regexprep(xml,'<[!?][^>]*>','?'); %! assert(t,'? <tag v="hello">some stuff?</tag>') %!test # Check that 'tokenize' is ignored %! xml = '<!-- This is some XML --> <tag v="hello">some stuff<!-- sample tag--></tag>'; %! t = regexprep(xml,'<[!?][^>]*>','','tokenize'); %! assert(t,' <tag v="hello">some stuff</tag>') %!test # Capture replacement %! if (!isempty(findstr(octave_config_info ("DEFS"),"HAVE_PCRE"))) %! data = "Bob Smith\nDavid Hollerith\nSam Jenkins"; %! result = "Smith, Bob\nHollerith, David\nJenkins, Sam"; %! t = regexprep(data,'(?m)^(\w+)\s+(\w+)$','$2, $1'); %! assert(t,result) %! end # Return the original if no match %!assert(regexprep('hello','world','earth'),'hello') ## Test a general replacement %!assert(regexprep("a[b]c{d}e-f=g", "[^A-Za-z0-9_]", "_"), "a_b_c_d_e_f_g"); ## Make sure it works at the beginning and end %!assert(regexprep("a[b]c{d}e-f=g", "a", "_"), "_[b]c{d}e-f=g"); %!assert(regexprep("a[b]c{d}e-f=g", "g", "_"), "a[b]c{d}e-f=_"); ## Options %!assert(regexprep("a[b]c{d}e-f=g", "[^A-Za-z0-9_]", "_", "once"), "a_b]c{d}e-f=g"); %!assert(regexprep("a[b]c{d}e-f=g", "[^A-Z0-9_]", "_", "ignorecase"), "a_b_c_d_e_f_g"); ## Option combinations %!assert(regexprep("a[b]c{d}e-f=g", "[^A-Z0-9_]", "_", "once", "ignorecase"), "a_b]c{d}e-f=g"); */
28.785714
109
0.581827
TianGL
e714bdb1b5f51ce212a87506c8a3fefea6ceb4ae
1,129
cpp
C++
DOJ/#699.cpp
Nickel-Angel/ACM-and-OI
79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9
[ "MIT" ]
null
null
null
DOJ/#699.cpp
Nickel-Angel/ACM-and-OI
79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9
[ "MIT" ]
1
2021-11-18T15:10:29.000Z
2021-11-20T07:13:31.000Z
DOJ/#699.cpp
Nickel-Angel/ACM-and-OI
79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9
[ "MIT" ]
null
null
null
/* * @author Nickel_Angel (1239004072@qq.com) * @copyright Copyright (c) 2022 */ #include <algorithm> #include <cstdio> #include <cstring> const int maxn = 1e6 + 10; int n, a[maxn]; class BIT { private: int v[maxn], bound; inline int lowbit(int x) { return x & -x; } public: inline void init(int n) { bound = n; memset(v, 0, sizeof(v)); } inline void add(int pos, int x) { for (int i = pos; i <= bound; i += lowbit(i)) v[i] = std::max(v[i], x); } inline int query(int pos) { int res = 0; for (int i = pos; i > 0; i -= lowbit(i)) res = std::max(res, v[i]); return res; } }tree; inline void solve() { scanf("%d", &n); for (int i = 1; i <= n; ++i) scanf("%d", a + i); tree.init(n); int ans = 0; for (int i = n, cur; i > 0; --i) { cur = tree.query(a[i]) + 1; ans = std::max(ans, cur); tree.add(a[i], cur); } printf("%d\n", ans); } int main() { int t; scanf("%d", &t); while (t--) solve(); return 0; }
16.602941
53
0.457927
Nickel-Angel
e71577990644b7ee9ca979e097096d87022d85f4
4,365
cpp
C++
Examples/PBD/PBDDeformableObject/PBD3DDeformableObject.cpp
quantingxie/vibe
965a79089ac3ec821ad65c45ac50e69bf32dc92f
[ "Apache-2.0" ]
2
2020-08-14T07:21:30.000Z
2021-08-30T09:39:09.000Z
Examples/PBD/PBDDeformableObject/PBD3DDeformableObject.cpp
quantingxie/vibe
965a79089ac3ec821ad65c45ac50e69bf32dc92f
[ "Apache-2.0" ]
null
null
null
Examples/PBD/PBDDeformableObject/PBD3DDeformableObject.cpp
quantingxie/vibe
965a79089ac3ec821ad65c45ac50e69bf32dc92f
[ "Apache-2.0" ]
1
2020-08-14T07:00:31.000Z
2020-08-14T07:00:31.000Z
/*========================================================================= Library: iMSTK Copyright (c) Kitware, Inc. & Center for Modeling, Simulation, & Imaging in Medicine, Rensselaer Polytechnic Institute. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ #include "imstkSimulationManager.h" #include "imstkMeshIO.h" #include "imstkPbdModel.h" #include "imstkPbdObject.h" #include "imstkPbdSolver.h" #include "imstkOneToOneMap.h" #include "imstkAPIUtilities.h" #include "imstkTetraTriangleMap.h" using namespace imstk; /// /// \brief This example demonstrates the soft body simulation /// using Position based dynamics /// int main() { auto simManager = std::make_shared<SimulationManager>(); auto scene = simManager->createNewScene("PBDVolume"); scene->getCamera()->setPosition(0, 2.0, 15.0); //auto surfMesh = std::dynamic_pointer_cast<SurfaceMesh>(MeshIO::read(iMSTK_DATA_ROOT "/asianDragon/asianDragon.obj")); //auto tetMesh = std::dynamic_pointer_cast<TetrahedralMesh>(MeshIO::read(iMSTK_DATA_ROOT "/asianDragon/asianDragon.veg")); auto surfMesh = std::dynamic_pointer_cast<SurfaceMesh>(MeshIO::read(iMSTK_DATA_ROOT "/vibe/3D_New/Stomach/tetra/stomach3/stomach.obj")); auto tetMesh = std::dynamic_pointer_cast<TetrahedralMesh>(MeshIO::read(iMSTK_DATA_ROOT "/vibe/3D_New/Stomach/tetra/stomach3/stomach.tet")); //auto tetMesh = TetrahedralMesh::createTetrahedralMeshCover(surfMesh, 10, 6, 6); auto map = std::make_shared<TetraTriangleMap>(tetMesh, surfMesh); auto material = std::make_shared<RenderMaterial>(); material->setDisplayMode(RenderMaterial::DisplayMode::WIREFRAME_SURFACE); auto surfMeshModel = std::make_shared<VisualModel>(surfMesh); surfMeshModel->setRenderMaterial(material); auto deformableObj = std::make_shared<PbdObject>("DeformableObject"); auto pbdModel = std::make_shared<PbdModel>(); pbdModel->setModelGeometry(tetMesh); // configure model auto pbdParams = std::make_shared<PBDModelConfig>(); // FEM constraint pbdParams->m_YoungModulus = 100.0; pbdParams->m_PoissonRatio = 0.3; pbdParams->m_fixedNodeIds = { 51, 127, 178 }; pbdParams->enableFEMConstraint(PbdConstraint::Type::FEMTet, PbdFEMConstraint::MaterialType::StVK); // Other parameters pbdParams->m_uniformMassValue = 1.0; pbdParams->m_gravity = Vec3d(0, -9.8, 0); pbdParams->m_maxIter = 45; // Set the parameters pbdModel->configure(pbdParams); pbdModel->setDefaultTimeStep(0.02); pbdModel->setTimeStepSizeType(imstk::TimeSteppingType::fixed); deformableObj->setDynamicalModel(pbdModel); deformableObj->addVisualModel(surfMeshModel); deformableObj->setPhysicsGeometry(tetMesh); deformableObj->setPhysicsToVisualMap(map); //assign the computed map deformableObj->setDynamicalModel(pbdModel); auto pbdSolver = std::make_shared<PbdSolver>(); pbdSolver->setPbdObject(deformableObj); scene->addNonlinearSolver(pbdSolver); scene->addSceneObject(deformableObj); // Setup plane auto planeGeom = std::make_shared<Plane>(); planeGeom->setWidth(40); planeGeom->setTranslation(0, -6, 0); auto planeObj = std::make_shared<CollidingObject>("Plane"); planeObj->setVisualGeometry(planeGeom); planeObj->setCollidingGeometry(planeGeom); scene->addSceneObject(planeObj); // Light auto light = std::make_shared<DirectionalLight>("light"); light->setFocalPoint(Vec3d(5, -8, -5)); light->setIntensity(1); scene->addLight(light); simManager->setActiveScene(scene); simManager->getViewer()->setBackgroundColors(Vec3d(0.3285, 0.3285, 0.6525), Vec3d(0.13836, 0.13836, 0.2748), true); simManager->start(SimulationStatus::paused); return 0; }
38.628319
140
0.705155
quantingxie
e71641642715a9a22f578b6d93a04bc9bc1280e4
8,458
cpp
C++
QuoteVerification/QVL/Src/AttestationLibrary/test/UnitTests/EnclaveIdentityParserUT.cpp
fqiu1/SGXDataCenterAttestationPrimitives
19483cca7b924f89ecfdb89e675d34d6a6d4b9dd
[ "BSD-3-Clause" ]
null
null
null
QuoteVerification/QVL/Src/AttestationLibrary/test/UnitTests/EnclaveIdentityParserUT.cpp
fqiu1/SGXDataCenterAttestationPrimitives
19483cca7b924f89ecfdb89e675d34d6a6d4b9dd
[ "BSD-3-Clause" ]
null
null
null
QuoteVerification/QVL/Src/AttestationLibrary/test/UnitTests/EnclaveIdentityParserUT.cpp
fqiu1/SGXDataCenterAttestationPrimitives
19483cca7b924f89ecfdb89e675d34d6a6d4b9dd
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2011-2020 Intel Corporation. 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 Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <gtest/gtest.h> #include <gmock/gmock.h> #include <SgxEcdsaAttestation/QuoteVerification.h> #include <Verifiers/EnclaveReportVerifier.h> #include <Verifiers/EnclaveIdentityParser.h> #include <numeric> #include <iostream> #include <QuoteGenerator.h> #include <QuoteVerification/Quote.h> #include <EnclaveIdentityGenerator.h> using namespace testing; using namespace ::intel::sgx::qvl; using namespace std; struct EnclaveIdentityParserUT : public Test { EnclaveIdentityParser parser; }; TEST_F(EnclaveIdentityParserUT, shouldReturnStatusOkWhenJsonIsOk) { string json = qeIdentityJsonWithSignature(EnclaveIdentityVectorModel().toJSON()); auto result = parser.parse(json); ASSERT_EQ(STATUS_OK, result->getStatus()); } TEST_F(EnclaveIdentityParserUT, shouldReturnEnclaveIdentityInvalidWhenMiscselectIsWrong) { EnclaveIdentityVectorModel model; model.miscselect = {{1, 1}}; string json = qeIdentityJsonWithSignature(qeIdentityJsonWithSignature(model.toJSON())); try { parser.parse(json); FAIL(); } catch (const ParserException &ex) { EXPECT_EQ(STATUS_SGX_ENCLAVE_IDENTITY_INVALID, ex.getStatus()); } } TEST_F(EnclaveIdentityParserUT, shouldReturnEnclaveIdentityInvalidWhenOptionalFieldIsInvalid) { EnclaveIdentityVectorModel model; string json = qeIdentityJsonWithSignature(model.toJSON()); removeWordFromString("mrenclave", json); removeWordFromString("mrsigner", json); removeWordFromString("isvprodid", json); removeWordFromString("isvsvn", json); try { parser.parse(json); FAIL(); } catch (const ParserException &ex) { EXPECT_EQ(STATUS_SGX_ENCLAVE_IDENTITY_INVALID, ex.getStatus()); } } TEST_F(EnclaveIdentityParserUT, shouldReturnEnclaveIdentityInvalidWhenVerionFieldIsInvalid) { EnclaveIdentityVectorModel model; string json = qeIdentityJsonWithSignature(model.toJSON()); removeWordFromString("version", json); try { parser.parse(json); FAIL(); } catch (const ParserException &ex) { EXPECT_EQ(STATUS_SGX_ENCLAVE_IDENTITY_INVALID, ex.getStatus()); } } TEST_F(EnclaveIdentityParserUT, shouldReturnEnclaveIdentityInvalidWhenMiscselectHasIncorrectSize) { EnclaveIdentityVectorModel model; model.miscselect= {{1, 1}}; string json = qeIdentityJsonWithSignature(model.toJSON()); try { parser.parse(json); FAIL(); } catch (const ParserException &ex) { EXPECT_EQ(STATUS_SGX_ENCLAVE_IDENTITY_INVALID, ex.getStatus()); } } TEST_F(EnclaveIdentityParserUT, shouldReturnEnclaveIdentityInvalidWhenMiscselectIsNotHexString) { EnclaveIdentityStringModel model; model.miscselect = "xyz00000"; string json = qeIdentityJsonWithSignature(model.toJSON()); try { parser.parse(json); FAIL(); } catch (const ParserException &ex) { EXPECT_EQ(STATUS_SGX_ENCLAVE_IDENTITY_INVALID, ex.getStatus()); } } TEST_F(EnclaveIdentityParserUT, shouldReturnEnclaveIdentityInvalidWhenMiscselectMaskHasIncorrectSize) { EnclaveIdentityVectorModel model; model.miscselectMask = {{1, 1}}; string json = qeIdentityJsonWithSignature(model.toJSON()); try { parser.parse(json); FAIL(); } catch (const ParserException &ex) { EXPECT_EQ(STATUS_SGX_ENCLAVE_IDENTITY_INVALID, ex.getStatus()); } } TEST_F(EnclaveIdentityParserUT, shouldReturnEnclaveIdentityInvalidWhenMiscselectMaskIsNotHexString) { EnclaveIdentityStringModel model; model.miscselectMask = "xyz00000"; string json = qeIdentityJsonWithSignature(model.toJSON()); try { parser.parse(json); FAIL(); } catch (const ParserException &ex) { EXPECT_EQ(STATUS_SGX_ENCLAVE_IDENTITY_INVALID, ex.getStatus()); } } TEST_F(EnclaveIdentityParserUT, shouldReturnEnclaveIdentityInvalidWhenAttributesHasIncorrectSize) { EnclaveIdentityVectorModel model; model.attributes = {{1, 1}}; string json = qeIdentityJsonWithSignature(model.toJSON()); try { parser.parse(json); FAIL(); } catch (const ParserException &ex) { EXPECT_EQ(STATUS_SGX_ENCLAVE_IDENTITY_INVALID, ex.getStatus()); } } TEST_F(EnclaveIdentityParserUT, shouldReturnEnclaveIdentityInvalidWhenAttributesIsNotHexString) { EnclaveIdentityStringModel model; model.attributes = "xyz45678900000000000000123456789"; string json = qeIdentityJsonWithSignature(model.toJSON()); try { parser.parse(json); FAIL(); } catch (const ParserException &ex) { EXPECT_EQ(STATUS_SGX_ENCLAVE_IDENTITY_INVALID, ex.getStatus()); } } TEST_F(EnclaveIdentityParserUT, shouldReturnEnclaveIdentityInvalidWhenAttributesMaskHasIncorrectSize) { EnclaveIdentityVectorModel model; model.attributesMask = {{1, 1}}; string json = qeIdentityJsonWithSignature(model.toJSON()); try { parser.parse(json); FAIL(); } catch (const ParserException &ex) { EXPECT_EQ(STATUS_SGX_ENCLAVE_IDENTITY_INVALID, ex.getStatus()); } } TEST_F(EnclaveIdentityParserUT, shouldReturnEnclaveIdentityInvalidWhenAttributesMaskIsNotHexString) { EnclaveIdentityStringModel model; model.attributesMask = "xyz45678900000000000000123456789"; string json = qeIdentityJsonWithSignature(model.toJSON()); try { parser.parse(json); FAIL(); } catch (const ParserException &ex) { EXPECT_EQ(STATUS_SGX_ENCLAVE_IDENTITY_INVALID, ex.getStatus()); } } TEST_F(EnclaveIdentityParserUT, shouldReturnEnclaveIdentityInvalidWhenIssuedateIsWrong) { EnclaveIdentityStringModel model; model.issueDate = "2018-08-22T10:09:"; string json = qeIdentityJsonWithSignature(model.toJSON()); try { parser.parse(json); FAIL(); } catch (const ParserException &ex) { EXPECT_EQ(STATUS_SGX_ENCLAVE_IDENTITY_INVALID, ex.getStatus()); } } TEST_F(EnclaveIdentityParserUT, shouldReturnEnclaveIdentityInvalidWhenNextUpdateIsWrong) { EnclaveIdentityStringModel model; model.nextUpdate = "2018-08-22T10:09:"; string json = qeIdentityJsonWithSignature(model.toJSON()); try { parser.parse(json); FAIL(); } catch (const ParserException &ex) { EXPECT_EQ(STATUS_SGX_ENCLAVE_IDENTITY_INVALID, ex.getStatus()); } } TEST_F(EnclaveIdentityParserUT, shouldReturnEnclaveIdentityUnsuportedVersionWhenVersionIsWrong) { EnclaveIdentityVectorModel model; model.version = 5; string json = qeIdentityJsonWithSignature(model.toJSON()); try { parser.parse(json); FAIL(); } catch (const ParserException &ex) { EXPECT_EQ(STATUS_SGX_ENCLAVE_IDENTITY_UNSUPPORTED_VERSION, ex.getStatus()); } }
30.868613
101
0.72594
fqiu1
e71aba9f8bab732ff313e39ab5ad7e5b11169912
3,128
cpp
C++
src/core/errfloat.cpp
zq317157782/raiden
09376a9499f8b86e86c3049b4e654957cb4dc29e
[ "BSD-2-Clause" ]
21
2016-12-14T09:46:27.000Z
2021-12-28T10:05:04.000Z
src/core/errfloat.cpp
zq317157782/raiden
09376a9499f8b86e86c3049b4e654957cb4dc29e
[ "BSD-2-Clause" ]
2
2016-12-02T07:47:14.000Z
2018-01-30T18:11:09.000Z
src/core/errfloat.cpp
zq317157782/raiden
09376a9499f8b86e86c3049b4e654957cb4dc29e
[ "BSD-2-Clause" ]
null
null
null
/* * errfloat.cpp * * Created on: 2016年11月15日 * Author: zhuqian */ #include "errfloat.h" #include "mmath.h" EFloat::EFloat(float v, float err) : _value(v) { Assert(!std::isnan(v)); Assert(!std::isnan(err)); if (err == 0.0f) { _low = _high = v; } else { //这里调用NextFloatUp和NextFloatDown是为了做保守的边界 _low = NextFloatDown(v - err); _high = NextFloatUp(v + err); } #ifdef DEBUG _highPrecisionValue = _value; Check(); #endif } EFloat EFloat::operator+(EFloat f) const { EFloat result; result._value = _value + f._value; #ifdef DEBUG result._highPrecisionValue = _highPrecisionValue + f._highPrecisionValue; #endif //这里调用NextFloatUp和NextFloatDown是为了做保守的边界 result._low = NextFloatDown(LowerBound() + f.LowerBound()); result._high = NextFloatUp(UpperBound() + f.UpperBound()); result.Check(); return result; } EFloat EFloat::operator-(EFloat f) const { EFloat result; result._value = _value - f._value; #ifdef DEBUG result._highPrecisionValue = _highPrecisionValue - f._highPrecisionValue; #endif //这里调用NextFloatUp和NextFloatDown是为了做保守的边界 result._low = NextFloatDown(LowerBound() - f.UpperBound()); result._high = NextFloatUp(UpperBound() - f.LowerBound()); result.Check(); return result; } EFloat EFloat::operator*(EFloat f) const { EFloat result; result._value = _value * f._value; #ifdef DEBUG result._highPrecisionValue = _highPrecisionValue * f._highPrecisionValue; #endif Float all[4] = { LowerBound() * f.LowerBound(), LowerBound() * f.UpperBound(), UpperBound() * f.LowerBound(), UpperBound() * f.UpperBound() }; result._low = NextFloatDown( std::min(std::min(all[0], all[1]), std::min(all[2], all[3]))); result._high = NextFloatUp( std::max(std::max(all[0], all[1]), std::max(all[2], all[3]))); result.Check(); return result; } EFloat EFloat::operator/(EFloat f) const { EFloat result; result._value = _value / f._value; #ifdef DEBUG result._highPrecisionValue = _highPrecisionValue / f._highPrecisionValue; #endif if (f._low < 0.0f && f._high > 0.0f) { //除以0的情况 result._low = -Infinity; result._high = Infinity; } else { Float all[4] = { LowerBound() / f.LowerBound(), LowerBound() / f.UpperBound(), UpperBound() / f.LowerBound(), UpperBound() / f.UpperBound() }; result._low = NextFloatDown( std::min(std::min(all[0], all[1]), std::min(all[2], all[3]))); result._high = NextFloatUp( std::max(std::max(all[0], all[1]), std::max(all[2], all[3]))); } result.Check(); return result; } EFloat EFloat::operator-() const{ EFloat result; result._value=-_value; #ifdef DEBUG result._highPrecisionValue = -_highPrecisionValue; #endif result._low=-_high; result._high=-_low; result.Check(); return result; } bool EFloat::operator==(EFloat f) const{ return _value==f._value; } EFloat::EFloat(const EFloat&f){ _value=f._value; #ifdef DEBUG _highPrecisionValue =f._highPrecisionValue; #endif _low=f._low; _high=f._high; Check(); } EFloat& EFloat::operator=(const EFloat&f){ _value=f._value; #ifdef DEBUG _highPrecisionValue =f._highPrecisionValue; #endif _low=f._low; _high=f._high; Check(); return *this; }
24.061538
74
0.691176
zq317157782
e71c1cc68f3ca93d3f5b0f0f3751f4ddd64da9b8
2,048
hpp
C++
src/utils/argvec.hpp
Thanduriel/func-renderer
99582272d8e34cb6e2f6bc9735c8eba5076bb29c
[ "MIT" ]
1
2019-01-27T17:54:45.000Z
2019-01-27T17:54:45.000Z
src/utils/argvec.hpp
Thanduriel/func-renderer
99582272d8e34cb6e2f6bc9735c8eba5076bb29c
[ "MIT" ]
null
null
null
src/utils/argvec.hpp
Thanduriel/func-renderer
99582272d8e34cb6e2f6bc9735c8eba5076bb29c
[ "MIT" ]
null
null
null
#pragma once #include "glm.hpp" namespace Math{ /* Vector with template specified dimension. * For operations on vectors use glm::vec */ template<typename _ValT, int _D> struct Component { _ValT data[_D]; }; // specializations for named access of the first 3 dimensions template<typename _ValT> struct Component<_ValT, 1> { union{ _ValT x; _ValT data[1]; }; }; template<typename _ValT> struct Component<_ValT, 2> { union{ struct{ _ValT x, y; }; _ValT data[2]; }; }; template<typename _ValT> struct Component<_ValT, 3> { union{ struct{ _ValT x, y, z; }; _ValT data[3]; }; }; //the actual vector class template<typename _ValT, int _D> struct ArgVec : public Component<_ValT, _D> { typedef Component<_ValT, _D> ST; ArgVec() { }; //construct with one arg for every dimension template<bool Enable = true, typename = typename std::enable_if< _D == 1 && Enable >::type> ArgVec(_ValT _x) { ST::x = _x; }; template<bool Enable = true, typename = typename std::enable_if< _D == 2 && Enable >::type> ArgVec(_ValT _x, _ValT _y){ ST::x = _x; ST::y = _y; }; template<bool Enable = true, typename = typename std::enable_if< _D == 3 && Enable >::type> ArgVec(_ValT _x, _ValT _y, _ValT _z){ ST::x = _x; ST::y = _y; ST::z = _z; }; // return value of _ind dimension _ValT operator[](size_t _ind) const { return ST::data[_ind]; } _ValT& operator[](size_t _ind) { return ST::data[_ind]; } template<typename _ValOther> _ValT distance(const ArgVec<_ValOther, _D>& _oth) const { _ValT ret = 0.f; for(int i = 0; i < _D; ++i) ret += (ST::data[i] - (_ValT)_oth[i]) * (ST::data[i] - (_ValT)_oth[i]); return sqrt(ret); } operator glm::vec2() const { return glm::vec2(ST::x, ST::y); } operator float() { return ST::x; } }; template<typename _ValT, int _D> auto operator*(float _lhs, ArgVec<_ValT, _D> _rhs) { for (int i = 0; i < _D; ++i) _rhs[i] *= _lhs; return _rhs; } //some common types typedef ArgVec<float, 2> AVec2; }
21.333333
93
0.625
Thanduriel
e71d768557ac348bb29d36f057abba6652af6877
1,299
cpp
C++
C++/Stack/421 Simplify Path.cpp
MuteMeteor/LintCode
8c73aa71fbd70409b9fc636a13a3fd6c4a387f62
[ "MIT" ]
null
null
null
C++/Stack/421 Simplify Path.cpp
MuteMeteor/LintCode
8c73aa71fbd70409b9fc636a13a3fd6c4a387f62
[ "MIT" ]
null
null
null
C++/Stack/421 Simplify Path.cpp
MuteMeteor/LintCode
8c73aa71fbd70409b9fc636a13a3fd6c4a387f62
[ "MIT" ]
null
null
null
/* Given an absolute path for a file (Unix-style), simplify it. Example "/home/", => "/home" "/a/./b/../../c/", => "/c" Challenge Did you consider the case where path = "/../"? In this case, you should return "/". Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/". In this case, you should ignore redundant slashes and return "/home/foo". */ class Solution { public: /** * @param path the original path * @return the simplified path */ string simplifyPath(string& path) { // Write your code here vector<string> dirs; auto i = path.begin(); while (i != path.end()) { auto j = find(i, path.end(), '/'); //find first string dir = string(i, j); //not include j if(dir.size() && dir != ".") { if(dir == "..") { if(dirs.size()) dirs.pop_back(); } else { dirs.push_back(dir); } } i = ( j == path.end() ? j : j + 1); //move forward } if(dirs.empty()) return "/"; string res; for(auto dir : dirs) res.append("/" + dir); return res; } };
25.98
100
0.470362
MuteMeteor
e729f8341e231d6e07305b516881ce334028c83c
5,431
cpp
C++
src/core/formula.cpp
Jetpie/OpenLinear
c501ab26bd53bcfd781d0aae22bb75392629000f
[ "BSD-2-Clause" ]
3
2015-04-07T12:37:50.000Z
2015-07-02T01:38:30.000Z
src/core/formula.cpp
Jetpie/OpenLinear
c501ab26bd53bcfd781d0aae22bb75392629000f
[ "BSD-2-Clause" ]
null
null
null
src/core/formula.cpp
Jetpie/OpenLinear
c501ab26bd53bcfd781d0aae22bb75392629000f
[ "BSD-2-Clause" ]
null
null
null
// Problem formulations // // Naming Convention: // 1.solver classes are named by all capital letter denote type and a // "Solver" prefix separated by underscore. // 2.some math notation like w^t by x will be denoted as wTx, // which big T means transpose. For the same style, other name // convention can be deduced like wT means transpose of w. It worths // something to mention that big X means matrix and small x means // vector. Hope this is helpful for readers. // // @author: Bingqing Qu // // Copyright (C) 2014-2015 Bingqing Qu <sylar.qu@gmail.com> // // @license: See LICENSE at root directory #include "formula.hpp" namespace oplin{ using std::cout; using std::endl; using std::cerr; Problem::Problem(DatasetPtr dataset, const std::vector<double>& C) : dataset_(dataset) { // use swap trick std::vector<double>(C).swap(C_); regularizer_ = NULL; } void Problem::regularized_gradient(const Eigen::Ref<const ColVector>& w, Eigen::Ref<ColVector> grad) { if(regularizer_) regularizer_->gradient(w,grad); } void Problem::update_weights(Eigen::Ref<ColVector> new_w, const Eigen::Ref<const ColVector>& w, const Eigen::Ref<const ColVector>& p, const double& alpha) { new_w.noalias() = w + alpha * p; } double L1_Regularizer::loss(const Eigen::Ref<const ColVector>& w) { return w.lpNorm<1>(); } /** * Compute the L1-regularized gradient * * Reference: * Galen Andrew and Jianfeng Gao. 2007. Scalable training of L1-regularized \ * log-linear models. In ICML. * * @param w weights */ void L1_Regularizer::gradient(const Eigen::Ref<const ColVector>& w, Eigen::Ref<ColVector> grad) { // this is the key part of the well defined pesudo-gradient in // Jianfeng et al's paper for(int i=0; i < grad.rows(); ++i) { if(w(i) == 0) { if(grad(i) < -1 ) ++grad(i); else if(grad(i) > 1) --grad(i); else grad(i) = 0; } else { grad(i) += w(i) > 0? 1 : (-1); } } } double L2_Regularizer::loss(const Eigen::Ref<const ColVector>& w) { return (w.squaredNorm() * 0.5); } void L2_Regularizer::gradient(const Eigen::Ref<const ColVector>& w, Eigen::Ref<ColVector> grad) { grad.noalias() += w; } /********************************************************************* * Logistic Regression *********************************************************************/ LR_Problem::LR_Problem(DatasetPtr dataset, const std::vector<double>& C) : Problem(dataset, C) { z_ = ColVector(dataset->n_samples, 1); } LR_Problem::~LR_Problem(){} /** * Compute the loss functionn * * @param w weights * */ double LR_Problem::loss(const Eigen::Ref<const ColVector>& w) { double f = regularizer_? regularizer_->loss(w):0; const std::vector<double>& y = dataset_->y; // W^T X z_.noalias() = w.transpose() * (*(dataset_->X)); // std::cout << z_.sum() << std::endl; // loss function : negative log likelihood for(size_t i = 0; i < dataset_->n_samples; ++i) f += C_[i] * log( 1 + exp(-y[i] * z_(i) ) ); return f; } /** * Compute the gradient descent direction * * @param w weights */ void LR_Problem::gradient(const Eigen::Ref<const ColVector>& w, Eigen::Ref<ColVector> grad) { const std::vector<double>& y = dataset_->y; for(size_t i = 0; i < dataset_->n_samples; ++i) { // h_w(y_i,x_i) - sigmoid function z_(i) = 1 / (1+exp(-y[i]*z_(i))); // C * (h_w(y_i,x_i) - 1) * y[i] z_(i) = C_[i]*(z_(i)-1)*y[i]; } // declare noalias here to enforce lazy evaluation for memory saving grad.noalias() = *(dataset_->X) * z_; } /********************************************************************* * L1-Regularized Logistic Regression *********************************************************************/ L1R_LR_Problem::L1R_LR_Problem(DatasetPtr dataset, const std::vector<double>& C) : LR_Problem(dataset, C) { regularizer_ = std::make_shared<L1_Regularizer>(); if(!regularizer_) { cerr << "L1R_LR_Problem::L1R_LR_Problem : Failed to declare regularizer! (" << __FILE__ << ", line " << __LINE__ << ")."<< endl; throw(std::bad_alloc()); } } L1R_LR_Problem::~L1R_LR_Problem(){} void L1R_LR_Problem::update_weights(Eigen::Ref<ColVector> new_w, const Eigen::Ref<const ColVector>& w, const Eigen::Ref<const ColVector>& p, const double& alpha) { new_w.noalias() = w + alpha * p; // prevent moving outside orthants for(size_t i = 0; i < dataset_->dimension; ++i) { // check same sign if(new_w(i) * w(i) < 0 ) new_w(i) = 0.0; } } /********************************************************************* * L2-Regularized Logistic Regression *********************************************************************/ L2R_LR_Problem::L2R_LR_Problem(DatasetPtr dataset, const std::vector<double>& C) : LR_Problem(dataset, C) { regularizer_ = std::make_shared<L2_Regularizer>(); if(!regularizer_) { cerr << "L2R_LR_Problem::L2R_LR_Problem : Failed to declare regularizer! (" << __FILE__ << ", line " << __LINE__ << ")."<< endl; throw(std::bad_alloc()); } } L2R_LR_Problem::~L2R_LR_Problem(){} } // oplin
28.584211
105
0.558829
Jetpie
e73058b8cd3a4db02c4a4933d85a04c56cc58f80
6,017
cpp
C++
Online Judges/Toph/J. Smart Feature Phone - 2.cpp
akazad13/competitive-programming
5cbb67d43ad8d5817459043bcccac3f68d9bc688
[ "MIT" ]
null
null
null
Online Judges/Toph/J. Smart Feature Phone - 2.cpp
akazad13/competitive-programming
5cbb67d43ad8d5817459043bcccac3f68d9bc688
[ "MIT" ]
null
null
null
Online Judges/Toph/J. Smart Feature Phone - 2.cpp
akazad13/competitive-programming
5cbb67d43ad8d5817459043bcccac3f68d9bc688
[ "MIT" ]
null
null
null
#include<iostream> #include<bits/stdc++.h> using namespace std; #define rep(i,p,n) for( i = p; i<n;i++) #define ll long long int #define pb push_back #define VI vector<int> #define VL vector<long long int> #define VD vector<double> #define pi pair<int,int> #define mp(a,b) make_pair(a,b) #define eps 1e-9 #define PI 2.0*acos(0.0) //#define PI acos(-1.0) #define MOD 1000000007 #define INF (1<<28) #define Clear(a,b) memset(a,b,sizeof(a)) //istringstream is() template<class T>inline bool read(T &x) { int c=getchar(); int sgn=1; while(~c&&c<'0'||c>'9') { if(c=='-')sgn=-1; c=getchar(); } for(x=0; ~c&&'0'<=c&&c<='9'; c=getchar())x=x*10+c-'0'; x*=sgn; return ~c; } template <class T> inline T bigmod(T p,T e,T M){ ll ret = 1; for(; e > 0; e >>= 1){ if(e & 1) ret = (ret * p) % M; p = (p * p) % M; } return (T)ret; } template <class T> inline T gcd(T a,T b){if(b==0)return a;return gcd(b,a%b);} template <class T> inline T modinverse(T a,T M){return bigmod(a,M-2,M);} template<typename T>inline T POW(T B,T P) { if(P==0) return 1; if(P&1) return B*POW(B,P-1); else return SQR(POW(B,P/2)); } template<typename T>inline T Dis(T x1,T y1,T x2, T y2) { return sqrt( SQR(x1-x2) + SQR(y1-y2) ); } template<typename T>inline T Angle(T x1,T y1,T x2, T y2) { return atan( double(y1-y2) / double(x1-x2)); } template<typename T>inline T DIFF(T a,T b) { T d = a-b; if(d<0)return -d; else return d; } template<typename T>inline T ABS(T a) { if(a<0)return -a; else return a; } template<typename T>inline T euclide(T a,T b,T &x,T &y) { if(a<0) { T d=euclide(-a,b,x,y); x=-x; return d; } if(b<0) { T d=euclide(a,-b,x,y); y=-y; return d; } if(b==0) { x=1; y=0; return a; } else { T d=euclide(b,a%b,x,y); T t=x; x=y; y=t-(a/b)*y; return d; } } inline int Set(int N, int pos) { return N= N|(1<<pos); } inline int Reset(int N, int pos) { return N= N & ~(1<<pos); } inline bool check(int N, int pos) { return (bool) (N&(1<<pos)); } /************************************************************************************/ char str[100010]; struct node { char ch; int cnt; }; node arr[30]; bool cmp(node a, node b) { if(a.cnt==b.cnt) return a.ch<b.ch; return a.cnt>b.cnt; } vector<char> res[10]; int main() { //freopen("input.txt","r",stdin); //freopen("out.txt","w",stdout); //ios_base::sync_with_stdio(false); cin.tie(0); int test,i,j,Case,n,m; read(test); rep(Case,1,test+1) { gets(str); int len = strlen(str); for(int i =0 ;i<26;i++) { arr[i].ch = 'a'+i; arr[i].cnt=0; // cout<<arr[i].ch<<endl; } for(int i=0;i<len;i++) { arr[str[i]-'a'].cnt++; } sort(arr,arr+26,cmp); if(arr[0].cnt>=arr[1].cnt && arr[0].cnt!=0) { res[0].push_back(arr[0].ch); } else { for(int i=1;i<3;i++) res[0].push_back(arr[i].ch); for(int i=3;i<6;i++) { res[1].push_back(arr[i].ch); } for(int i=6;i<9;i++) { res[2].push_back(arr[i].ch); } for(int i=9;i<12;i++) { res[3].push_back(arr[i].ch); } for(int i=12;i<15;i++) { res[4].push_back(arr[i].ch); } for(int i=15;i<19;i++) { res[5].push_back(arr[i].ch); } for(int i=19;i<22;i++) { res[6].push_back(arr[i].ch); } for(int i=22;i<26;i++) { res[7].push_back(arr[i].ch); } printf("Case %d:\n",Case); printf("###############\n#....#%c%c%c#%c%c%c.#\n###############\n#%c%c%c.#%c%c%c#%c%c%c.#\n###############\n#%c%c%c%c#%c%c%c#%c%c%c%c#\n###############\n",res[0][0],res[0][1],res[0][2],res[1][0],res[1][1],res[1][2],res[2][0],res[2][1],res[2][2], res[3][0],res[3][1],res[3][2], res[4][0],res[4][1],res[4][2], res[5][0],res[5][1],res[5][2], res[5][3], res[6][0],res[6][1],res[6][2], res[7][0],res[7][1],res[7][2],res[7][3]); continue ; } if(arr[1].cnt>=arr[2].cnt && arr[1].cnt!=0) { res[1].push_back(arr[0].ch); } else { for(int i=1;i<3;i++) res[0].push_back(arr[i].ch); for(int i=3;i<6;i++) { res[1].push_back(arr[i].ch); } for(int i=6;i<9;i++) { res[2].push_back(arr[i].ch); } for(int i=9;i<12;i++) { res[3].push_back(arr[i].ch); } for(int i=12;i<15;i++) { res[4].push_back(arr[i].ch); } for(int i=15;i<19;i++) { res[5].push_back(arr[i].ch); } for(int i=19;i<22;i++) { res[6].push_back(arr[i].ch); } for(int i=22;i<26;i++) { res[7].push_back(arr[i].ch); } printf("Case %d:\n",Case); printf("###############\n#....#%c%c%c#%c%c%c.#\n###############\n#%c%c%c.#%c%c%c#%c%c%c.#\n###############\n#%c%c%c%c#%c%c%c#%c%c%c%c#\n###############\n",res[0][0],res[0][1],res[0][2],res[1][0],res[1][1],res[1][2],res[2][0],res[2][1],res[2][2], res[3][0],res[3][1],res[3][2], res[4][0],res[4][1],res[4][2], res[5][0],res[5][1],res[5][2], res[5][3], res[6][0],res[6][1],res[6][2], res[7][0],res[7][1],res[7][2],res[7][3]); continue ; } } return 0; }
22.040293
430
0.414492
akazad13
e7323fe3658eb1d900cb28be8435b97fc523aad1
325
hxx
C++
src/copy.hxx
puzzlef/pagerank-monolithic-vs-levelwise
f0402ce161e43d403919f8804b0752c5781778b8
[ "MIT" ]
null
null
null
src/copy.hxx
puzzlef/pagerank-monolithic-vs-levelwise
f0402ce161e43d403919f8804b0752c5781778b8
[ "MIT" ]
null
null
null
src/copy.hxx
puzzlef/pagerank-monolithic-vs-levelwise
f0402ce161e43d403919f8804b0752c5781778b8
[ "MIT" ]
null
null
null
#pragma once template <class H, class G> void copy(H& a, const G& x) { for (int u : x.vertices()) a.addVertex(u, x.vertexData(u)); for (int u : x.vertices()) { for (int v : x.edges(u)) a.addEdge(u, v, x.edgeData(u, v)); } } template <class G> auto copy(const G& x) { G a; copy(a, x); return a; }
15.47619
40
0.556923
puzzlef
e7332dc50cb9f2f686f40329593a8f1d5d09c6b5
1,625
cpp
C++
src/main/cpp/subsystems/Turret.cpp
ZairaV4/Rapid-React
7eb2cfee3849ffdc1dec62aa6da986c9ceb6aaac
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/subsystems/Turret.cpp
ZairaV4/Rapid-React
7eb2cfee3849ffdc1dec62aa6da986c9ceb6aaac
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/subsystems/Turret.cpp
ZairaV4/Rapid-React
7eb2cfee3849ffdc1dec62aa6da986c9ceb6aaac
[ "BSD-3-Clause" ]
null
null
null
#include "subsystems/Turret.h" #include "Constants.h" #include "frc/smartdashboard/Smartdashboard.h" #include "networktables/NetworkTable.h" #include "networktables/NetworkTableInstance.h" #include "networktables/NetworkTableEntry.h" #include "networktables/NetworkTableValue.h" #include "wpi/span.h" using namespace frc; using namespace std; Turret::Turret() { anglePID.SetTolerance(0.1); alignPID.SetTolerance(0.1); } void Turret::Periodic() { float turretDeg = (encoder.Get() * 44.4) / 360; limelight = nt::NetworkTableInstance::GetDefault().GetTable("limelight"); bool sensorMode = SmartDashboard::GetBoolean("Sensor Mode", false); bool climbMode = SmartDashboard::GetBoolean("Climb Mode", false); SmartDashboard::PutNumber("Turret Encoder", turretDeg); if (!sensorMode) Move(); else if (sensorMode) Align(); } bool Turret::SetAngle(float angle) { float output; anglePID.SetSetpoint(angle); output = anglePID.Calculate(encoder.Get()); motor.Set(clamp(output, -kTurretSpeed, kTurretSpeed)); return anglePID.AtSetpoint(); } bool Turret::Align() { float output; alignPID.SetSetpoint(0); output = alignPID.Calculate(-limelight->GetNumber("tx", 0.0)); // SI el output es positivo, y no ha llegado a su ángulo máximo a la derecha, // o si el output es negativo y no ha llegado a su ángulo máximo a la izquierda, setear el motor motor.Set(clamp(output, -kTurretSpeed, kTurretSpeed)); return alignPID.AtSetpoint(); } void Turret::Reset() { encoder.Reset(); } void Turret::Move() { motor.Set((-control.GetRawButton(cRightBumper) + control.GetRawButton(cLeftBumper)) * kTurretSpeed); }
22.569444
101
0.738462
ZairaV4
e73657ba950bf255ff3e10060dde68d9afe78a20
2,189
cpp
C++
Engine/src/Engine/Core/Application.cpp
CodePYJ/Engine
d1d481581eb6373ddf0935f11f62842c0781aafd
[ "Apache-2.0" ]
null
null
null
Engine/src/Engine/Core/Application.cpp
CodePYJ/Engine
d1d481581eb6373ddf0935f11f62842c0781aafd
[ "Apache-2.0" ]
null
null
null
Engine/src/Engine/Core/Application.cpp
CodePYJ/Engine
d1d481581eb6373ddf0935f11f62842c0781aafd
[ "Apache-2.0" ]
null
null
null
#include "Application.h" #include "Engine/Renderer/Renderer.h" #include <GLFW/glfw3.h> #include <glad/glad.h> namespace EE { Application* Application::s_app = nullptr; Application::Application() { m_Window = std::unique_ptr<Window>(Window::Create(1600, 900)); m_Window->SetEventCallbackFun(std::bind(&Application::OnEvent, this, std::placeholders::_1)); s_app = this; m_ImGuiLayer = new ImGuiLayer(); PushOverlay(m_ImGuiLayer); } Application::~Application() { } void Application::Run() { while (m_Running) { float time = (float)glfwGetTime(); Timestep timestep = time - m_LastFrameTime; m_LastFrameTime = time; for (Layer* layer : m_layerstack) layer->OnUpdate(timestep); m_ImGuiLayer->Begin(); for (Layer* layer : m_layerstack) layer->OnImGuiRender(); m_ImGuiLayer->End(); OnUpdate(); } } void Application::OnEvent(Event& event) { EventDispatcher dispatcher(event); dispatcher.Dispatch<WindowCloseEvent>(std::bind(&Application::OnWindowClose, this, std::placeholders::_1)); dispatcher.Dispatch<WindowResizeEvent>(std::bind(&Application::OnWindowResize, this, std::placeholders::_1)); if (EventType::WindowClose == event.GetEventType()) OnWindowClose(event); //EE_TRACE(event.ToString()); for (auto it = m_layerstack.end(); it != m_layerstack.begin();) { //EE_TRACE((*(it-1))->GetName()); if (event.Handled) { //EE_TRACE(event.Handled); break; } (*--it)->OnEvent(event); } } void Application::OnUpdate() { glfwPollEvents(); m_Window->OnUpdate(); } void Application::OnWindowClose(Event& e) { m_Running = false; } void Application::OnWindowResize(WindowResizeEvent& e) { if (e.GetWidth() == 0 || e.GetHeight() == 0) m_Minimized = true; m_Minimized = false; Renderer::OnWindowResize(e.GetWidth(), e.GetHeight()); } void Application::PushLayer(Layer* layer) { m_layerstack.PushLayer(layer); } void Application::PopLayer(Layer* layer) { m_layerstack.PopLayer(layer); } void Application::PushOverlay(Layer* layer) { m_layerstack.PushOverlay(layer); } void Application::PopOverlay(Layer* layer) { m_layerstack.PopOverlay(layer); } }
21.048077
111
0.686158
CodePYJ
e73a0aaac98a626500254efdfc57da5c6002f425
3,290
hpp
C++
include/Pyramid.hpp
SudoCpp/Pyramid
97180840f05bab5f76dd183e09e93218579d7a80
[ "BSD-3-Clause" ]
null
null
null
include/Pyramid.hpp
SudoCpp/Pyramid
97180840f05bab5f76dd183e09e93218579d7a80
[ "BSD-3-Clause" ]
null
null
null
include/Pyramid.hpp
SudoCpp/Pyramid
97180840f05bab5f76dd183e09e93218579d7a80
[ "BSD-3-Clause" ]
null
null
null
/* BSD 3-Clause License Copyright (c) 2022, SudoCpp All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the 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 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. */ #ifndef __PYRAMID_PYRAMID_HPP__ #define __PYRAMID_PYRAMID_HPP__ #include "simplextk.hpp" #include "simplexsdl.hpp" #include "RGBColor.hpp" namespace pyramid { class Window; class Widget; class Pyramid : public simplex::Singleton { static Pyramid* instance; simplex::Array<Window*> windows; int lastWidgetID; static const RGBColor WidgetTextColor; static const RGBColor WidgetForegroundColor; static const int HoverTimer; Widget* lastMouseButtonWidget; Widget* lastMouseHoverWidget; public: const static simplex::string DefaultFontPath; const static RGBColor DefaultBackgroundColor; virtual ~Pyramid(); template <typename WindowType, typename... Args> static WindowType& CreateWindow(Args&&... args); static void StartProgram(); static void RedrawWindows(); static int GetWidgetID(); private: static Pyramid& GetInstance(); Pyramid(); void processWindowEvents(simplex::sdl::WindowEvent& event); void processMouseEvents(simplex::sdl::MouseEvent& event); Widget& getWidgetAtMouse(Window& window, int xPosition, int yPosition); Window& getCurrentWindow(uint32_t windowID); }; #define __class__ "pyramid::Pyramid" template <typename WindowType, typename... Args> WindowType& Pyramid::CreateWindow(Args&&... args) { WindowType* window = new WindowType(std::forward<Args>(args)...); Pyramid& pyramid = GetInstance(); pyramid.windows.add(window); return *window; } #undef __class__ } #endif //__PYRAMID_PYRAMID_HPP__
36.153846
82
0.71307
SudoCpp
e73bc683da3d4d41a3f3b6f29634e01c07905989
1,324
cpp
C++
ParticleEngine/ParticleForceRegistry.cpp
bernhardrieder/Particle-Engine
ea5885f2ee2446426b6ae93ce687802ef922fb29
[ "Unlicense" ]
null
null
null
ParticleEngine/ParticleForceRegistry.cpp
bernhardrieder/Particle-Engine
ea5885f2ee2446426b6ae93ce687802ef922fb29
[ "Unlicense" ]
null
null
null
ParticleEngine/ParticleForceRegistry.cpp
bernhardrieder/Particle-Engine
ea5885f2ee2446426b6ae93ce687802ef922fb29
[ "Unlicense" ]
2
2019-05-09T05:27:18.000Z
2020-02-11T18:04:56.000Z
#include "pch.h" #include "ParticleForceRegistry.h" ParticleForceRegistry::ParticleForceRegistry() { } ParticleForceRegistry::~ParticleForceRegistry() { } void ParticleForceRegistry::Add(Particle* particle, ParticleForceGenerator* forceGenerator) { ParticleForceRegistration registration; registration.Particle = particle; registration.ForceGenerator = forceGenerator; m_registrations.push_back(registration); } void ParticleForceRegistry::Remove(Particle* particle, ParticleForceGenerator* forceGenerator) { for (size_t index = 0; index < m_registrations.size(); ++index) { if (m_registrations[index].Particle == particle && m_registrations[index].ForceGenerator == forceGenerator) { m_registrations.erase(m_registrations.begin() + index); break; } } } void ParticleForceRegistry::Clear() { m_registrations.clear(); } void ParticleForceRegistry::UpdateForces(const float& deltaTime) { removeInactiveParticle(); for (ParticleForceRegistration& i : m_registrations) { i.ForceGenerator->UpdateForce(i.Particle, deltaTime); } } void ParticleForceRegistry::removeInactiveParticle() { for (std::vector<ParticleForceRegistration>::iterator it = m_registrations.begin(); it != m_registrations.end();) { if (!(*it).Particle->IsActive()) it = m_registrations.erase(it); else ++it; } }
22.827586
114
0.761329
bernhardrieder
e73be63b5db357a85cf7f19520727ac5d50dff16
847
cpp
C++
Strings/reverse_words.cpp
khushisinha20/Data-Structures-and-Algorithms
114d365d03f7ba7175eefeace281972820a7fc76
[ "Apache-2.0" ]
null
null
null
Strings/reverse_words.cpp
khushisinha20/Data-Structures-and-Algorithms
114d365d03f7ba7175eefeace281972820a7fc76
[ "Apache-2.0" ]
null
null
null
Strings/reverse_words.cpp
khushisinha20/Data-Structures-and-Algorithms
114d365d03f7ba7175eefeace281972820a7fc76
[ "Apache-2.0" ]
null
null
null
//leetcode.com/problems/reverse-words-in-a-string/ #include <bits/stdc++.h> using namespace std; class Solution { public: string reverseWords(string s) { string reverse_order_words = ""; int i = 0; int n = s.length(); while (i < n) { while (i < n && s[i] == ' ') { ++i; } if (i >= n) { break; } int j = i + 1; while (j < n && s[j] != ' ') { ++j; } string word = s.substr(i, j - i); if (reverse_order_words == "") { reverse_order_words += word; } else { reverse_order_words = word + " " + reverse_order_words; } i = j + 1; } return reverse_order_words; } };
24.911765
71
0.399055
khushisinha20
e741113c455830abce4a05b912e7c3ad295ea415
1,997
cpp
C++
src/Engine.cpp
Spooky309/Minecrap
bf30839bf4a80bf71340e7cf1af1f952599329de
[ "MIT" ]
1
2020-01-02T23:45:00.000Z
2020-01-02T23:45:00.000Z
src/Engine.cpp
Spooky309/Minecrap
bf30839bf4a80bf71340e7cf1af1f952599329de
[ "MIT" ]
null
null
null
src/Engine.cpp
Spooky309/Minecrap
bf30839bf4a80bf71340e7cf1af1f952599329de
[ "MIT" ]
null
null
null
#include "Engine.h" #include "SpriteElement2D.h" #include "FileSystem.h" #include "FontManager.h" #include "TextElement2D.h" #include <iostream> // PERFORMANCE IMPROVEMENTS TO MAKE: // 1. Broadphase on vs. AABB Tests // 2. Keep a list of active AABBs to avoid needless testing against AABB::alive Engine::Engine() : m_graphics(new Graphics()), m_input(new Input()) {} TextElement2D* text_test; void Engine::Go(const std::vector<std::string> argv) { m_fs = new FileSystem(); m_vitals = new EngineVitals(); m_bdata = new BlockData(); m_graphics->Init(); m_input->Init(m_graphics->GetWindow()); m_fm = new FontManager(); m_tdict = new TextureDictionary(); m_world = new World(16, 256, 16, m_tdict, m_bdata); m_player = new Player(m_world, m_bdata, glm::vec3(10, 130, 10)); text_test = new TextElement2D(glm::vec2(0.0f, 768.0f),glm::vec2(1.0f,1.0f),m_fm->LoadFont("dfont.ttf"),"0.0\n0.0"); text_test->SetText("last second ft (min/max/avg) (ms): 0/0/0\naverage framerate (1s): 0fps"); m_oTime = glfwGetTime(); m_vitals->FrameFinishCallback = [](const float& ft, const float& fr, const float& min, const float& max) { text_test->SetText("last second ft (min/max/avg) (ms): " + std::to_string(min) + "/" + std::to_string(max) + "/" + std::to_string(ft) + "\n" + "average framerate (1s): "+std::to_string(fr) + "fps"); }; while (Tick()); } bool Engine::Tick() { float dTime = (float)(glfwGetTime() - m_oTime); m_oTime = glfwGetTime(); m_vitals->FrameFinished(dTime); if (m_input->GetKeyDown(GLFW_KEY_ESCAPE)) { glfwSetWindowShouldClose(m_graphics->GetWindow(), true); } m_graphics->Get2DRenderer()->QueueRender(text_test); m_world->RenderWorld(); m_world->UpdateWorld(); m_graphics->Render(); m_player->Update(dTime); m_input->Update(m_graphics->GetWindow()); glfwPollEvents(); if (glfwWindowShouldClose(m_graphics->GetWindow())) return false; return true; }
35.660714
151
0.662494
Spooky309