hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
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
67k
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
90de17ec389124d95613adbbb2026946b6a3af65
1,830
cpp
C++
Tree/HeightBT.cpp
Anirban166/GeeksforGeeks
3b0f4a5a5c9476477e5920692258c097b20b64a0
[ "MIT" ]
19
2019-07-22T06:23:36.000Z
2021-09-12T13:01:41.000Z
Tree/HeightBT.cpp
Anirban166/GeeksforGeeks
3b0f4a5a5c9476477e5920692258c097b20b64a0
[ "MIT" ]
null
null
null
Tree/HeightBT.cpp
Anirban166/GeeksforGeeks
3b0f4a5a5c9476477e5920692258c097b20b64a0
[ "MIT" ]
3
2019-10-10T03:41:06.000Z
2020-05-05T08:27:46.000Z
#include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node* left; struct Node* right; Node(int x){ data = x; left = right = NULL; } }; /* Computes the number of nodes in a tree. */ int height(struct Node* node); void inorder(Node *root) { if (root == NULL) return; inorder(root->left); cout << root->data << " "; inorder(root->right); } /* Driver program to test size function*/ int main() { int t; scanf("%d ", &t); while (t--) { map<int, Node*> m; int n; scanf("%d",&n); struct Node *root = NULL; struct Node *child; while (n--) { Node *parent; char lr; int n1, n2; scanf("%d %d %c", &n1, &n2, &lr); if (m.find(n1) == m.end()) { parent = new Node(n1); m[n1] = parent; if (root == NULL) root = parent; } else parent = m[n1]; child = new Node(n2); if (lr == 'L') parent->left = child; else parent->right = child; m[n2] = child; } cout << height(root) << endl; } return 0; } /* Tree node structure used in the program struct Node { int data; struct Node* left; struct Node* right; Node(int x){ data = x; left = right = NULL; } };*/ /* Computes the height of binary tree with given root. */ int height(Node* node) { if(!node) return 0; int h=0; queue<Node*> q; q.push(node); while(!q.empty()) { int size = q.size(); while(size) { Node* cur = q.front(); q.pop(); if(cur->left) q.push(cur->left); if(cur->right) q.push(cur->right); size--; } h++; } return h; // Your code here }
17.596154
58
0.507104
Anirban166
90debecb1d3764b8d598bed91b713e680c3747fe
3,027
cpp
C++
PALIN.cpp
YourGoodFriendSP/SPOJ-solutions
f8b14cad3452628c2c8e17ee44ec0ba2f70bb518
[ "MIT" ]
3
2020-10-02T15:01:06.000Z
2022-01-15T15:32:25.000Z
PALIN.cpp
YourGoodFriendSP/SPOJ-solutions
f8b14cad3452628c2c8e17ee44ec0ba2f70bb518
[ "MIT" ]
null
null
null
PALIN.cpp
YourGoodFriendSP/SPOJ-solutions
f8b14cad3452628c2c8e17ee44ec0ba2f70bb518
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std ; typedef long long ll ; string add(string &s){ int carry=0 ; string ans(s.size()+1,'0') ; int m=s.size() ; for(int i=m-1;i>=0;i--){ int num=0 ; if(i==m-1){ num=1 ; } int sum=(s[i]-'0')+carry+num ; s[i]=sum%10 +'0' ; carry=sum/10 ; num=0 ; } if(carry==1){ s='1'+s ; } return s ; } string reverseStr(string& str) { int n = str.length(); for (int i = 0; i < n / 2; i++) swap(str[i], str[n - i - 1]); return str ; } void copyPaste(string &s,int i,int j){ for(int k=i;k>=0;k--){ s[j]=s[k] ; j++ ; } cout<<s<<"\n" ; } void addAndMirror(string &q,int z){ string s1=add(q) ; int n=s1.size() ; string s4=s1 ; string s2=reverseStr(s4) ; string s3 ; if(z==0) s3=s1+s2 ; else{ string s5=s2.substr(1) ; s3=s1+s5 ; } cout<<s3<<"\n" ; } void forEvenString(string &s){ int z=0 ; int n=s.size() ; int i=(n/2)-1 ; int j=(n/2) ; int flag=0; while(i>=0 && j<=n-1){ if(s[i]==s[j]){ i-- ; j++ ; } else{ flag++ ; int a=s[i]-'0' ; int b=s[j]-'0' ; if(a<b){ string r=s.substr(0,n/2); addAndMirror(r,z) ; return ; } else{ copyPaste(s,i,j) ; return ; } } } if(flag==0&&i<0&&j>n-1){ string r=s.substr(0,n/2) ; addAndMirror(r,z) ; return ; } } void forOddString(string &s){ int z=1 ; int n=s.size() ; int j=n/2 ; int i=n/2 ; int flag=0; while(i>=0 && j<=n-1){ if(s[i]==s[j]){ i-- ; j++ ; } else{ flag++ ; int a=s[i]-'0' ; int b=s[j]-'0' ; if(a<b){ string m=s.substr(0,(n/2)+1) ; addAndMirror(m,z) ; return ; } else{ copyPaste(s,i,j) ; return ; } } } if(flag==0&&i<0&&j>n-1){ string r=s.substr(0,(n/2)+1) ; addAndMirror(r,z) ; return ; } } void traverse(string &s){ int a=s.size() ; if(a%2==0){ forEvenString(s) ; } else { forOddString(s) ; } } bool ifAll9(string &s){ bool flag=0 ; for(int i=0;i<s.size();i++) { if(s[i]!='9'){ flag=1 ; } } if(flag==0) { string a1=add(s) ; string a2=add(a1) ; cout<<a2<<"\n" ; return 1 ; } return 0 ; } void findPalin(string &s){ bool m=ifAll9(s) ; if(m==0) traverse(s) ; } void ifAll0(string &s){ bool flag=0 ; for(int i=0;i<s.size();i++) { if(s[i]!='0'){ flag=1 ; } } if(flag==0) { cout<<"1" ; return ; } } void solve(){ string s ; cin>>s ; ifAll0(s) ; string s2 ; for(int i=0;i<s.size();i++){ if(s[i]!='0'){ s2=s.substr(i) ; break ; } } findPalin(s2) ; } int main(){ #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin) ; freopen("output.txt", "w", stdout) ; #endif int y ; cin>>y ; //y=1; while(y--){ solve() ; } }
11.870588
39
0.435745
YourGoodFriendSP
90df261d1b5b28ef3d6404ee8efb50d3a4f5f409
6,520
cpp
C++
Stikboldt/_MyPrefabs/Objects/PF_Character.cpp
Kair0z/StikBoldt-PC
5d978aa6b67e9f3a140136f2f0b766061e765c74
[ "MIT" ]
null
null
null
Stikboldt/_MyPrefabs/Objects/PF_Character.cpp
Kair0z/StikBoldt-PC
5d978aa6b67e9f3a140136f2f0b766061e765c74
[ "MIT" ]
null
null
null
Stikboldt/_MyPrefabs/Objects/PF_Character.cpp
Kair0z/StikBoldt-PC
5d978aa6b67e9f3a140136f2f0b766061e765c74
[ "MIT" ]
1
2021-09-23T06:21:53.000Z
2021-09-23T06:21:53.000Z
#include "stdafx.h" #include "PF_Character.h" #include "Components.h" #include "Prefabs.h" #include "GameScene.h" #include "PhysxManager.h" #include "PhysxProxy.h" #include "ControllerComponent.h" PF_Character::PF_Character(float radius, float height, float moveSpeed, float maxJumpHeight, float maxSlopeAngle, float maxMoveSpeed, float drag) : m_Radius(radius), m_Height(height), m_MoveSpeed(moveSpeed), m_pCamera(nullptr), m_pController(nullptr), m_TotalPitch(0), m_TotalYaw(0), m_RotationSpeed(90.f), m_SlopeMax{cosf(maxSlopeAngle)}, m_MaxJumpHeight{maxJumpHeight}, m_GravityEnabled{true}, //Running m_MaxRunVelocity(maxMoveSpeed), m_TerminalVelocity(20), m_Gravity(9.81f), m_RunAccelerationTime(0.3f), m_JumpAccelerationTime(0.8f), m_RunAcceleration(m_MaxRunVelocity/m_RunAccelerationTime), m_JumpAcceleration(m_Gravity/m_JumpAccelerationTime), m_RunVelocity(0), m_JumpVelocity(0), m_Velocity(0,0,0), m_HorVelocity{}, m_VertVelocity{}, m_Acceleration{}, m_Drag{drag} {} void PF_Character::Initialize(const GameContext& gameContext) { using namespace physx; using namespace DirectX; UNREFERENCED_PARAMETER(gameContext); //TODO: Create controller PxMaterial* pMat = PhysxManager::GetInstance()->GetPhysics()->createMaterial(1.f, 1.f, 0.f); m_pController = new ControllerComponent{ pMat, m_Radius, m_Height, m_MaxJumpHeight, m_SlopeMax }; AddComponent(m_pController); } void PF_Character::PostInitialize(const GameContext& gameContext) { using namespace DirectX; UNREFERENCED_PARAMETER(gameContext); } void PF_Character::Update(const GameContext& gameContext) { // Set acceleration to zero, input sets it to something else if needed && Lose the accumulated velocity LoseHorVelocity(gameContext); m_IsGrounded = m_pController->IsGrounded(); if (m_GravityEnabled && !m_IsGrounded) { ApplyAcceleration(0.f, -1.f, 0.f , m_Gravity, gameContext); } // Processes movement based on velocity & acceleration ConsumeVelocity(gameContext); m_Acceleration = {}; } void PF_Character::SetMaxSlopeAngle(const float angle) { m_SlopeMax = cosf(angle); } void PF_Character::ViewMyCamera(bool enabled) { if (m_pCamera && enabled) { m_pCamera->SetActive(); } } void PF_Character::EnableGravity(const bool enabled) { m_GravityEnabled = enabled; } bool PF_Character::IsGrounded() const { return m_IsGrounded; } bool PF_Character::GravityIsEnabled() const { return m_GravityEnabled; } void PF_Character::SimpleMove(const DirectX::XMFLOAT3& direction, float amountPerSecond, const GameContext& gameContext, bool useLocalAxes) { using namespace DirectX; float dt = gameContext.pGameTime->GetElapsed(); XMVECTOR finalDisplacement; if (!useLocalAxes) finalDisplacement = XMLoadFloat3(&direction); else { XMVECTOR forward = XMLoadFloat3(&GetTransform()->GetForward()); XMVECTOR right = XMLoadFloat3(&GetTransform()->GetRight()); XMVECTOR up = XMLoadFloat3(&GetTransform()->GetUp()); XMVECTOR localDirectionVec = forward * direction.z + right * direction.x + up * direction.y; finalDisplacement = localDirectionVec; } finalDisplacement *= amountPerSecond; finalDisplacement = XMVector2ClampLength(finalDisplacement, 0.f, m_MaxRunVelocity); finalDisplacement *= dt; XMFLOAT3 displacementFloats; DirectX::XMStoreFloat3(&displacementFloats, finalDisplacement); m_pController->Move({ displacementFloats }); } void PF_Character::SimpleRotateHorizontal(bool goRight, float amountPerSecond, const GameContext& gameContext) { using namespace DirectX; XMFLOAT3 rot; float amount = amountPerSecond * gameContext.pGameTime->GetElapsed(); rot = { 0.0f, goRight ? -amount : amount, 0.0f }; m_pController->GetTransform()->Rotate(XMLoadFloat3(&rot), true); } #pragma region Acceleration void PF_Character::ApplyAcceleration(const DirectX::XMVECTOR& direction, float power, const GameContext&) { using namespace DirectX; XMFLOAT3 vector; XMStoreFloat3(&vector, direction); if (vector.x == 0.f && vector.y == 0.f && vector.z == 0.0f) return; // If zerovector, don't do anything... XMStoreFloat3(&m_Acceleration, XMVector3NormalizeEst(direction) * power); } void PF_Character::ApplyAcceleration(const DirectX::XMFLOAT3& direction, float power, const GameContext& gameContext) { ApplyAcceleration(DirectX::XMLoadFloat3(&direction), power, gameContext); } void PF_Character::ApplyAcceleration(float x, float y, float z, float power, const GameContext& gameContext) { ApplyAcceleration(DirectX::XMFLOAT3{ x, y, z }, power, gameContext); } #pragma endregion void PF_Character::LoseHorVelocity(const GameContext& gameContext) { if (m_Acceleration.x != 0.f || m_Acceleration.y != 0.f || m_Acceleration.z != 0.f) return; using namespace DirectX; XMFLOAT2 horVelocityLengthXYZ; XMStoreFloat2(&horVelocityLengthXYZ, XMVector2Length(XMLoadFloat2(&m_HorVelocity))); float length = horVelocityLengthXYZ.x; gameContext; float newLength = length - m_Drag * gameContext.pGameTime->GetElapsed(); if (newLength < 0.f) { newLength = 0.f; m_HorVelocity = {}; return; } XMVECTOR newHorVelocity = XMVectorScale(XMVector2NormalizeEst(XMLoadFloat2(&m_HorVelocity)), newLength); XMStoreFloat2(&m_HorVelocity, newHorVelocity); } void PF_Character::ConsumeVelocity(const GameContext& gameContext) { using namespace DirectX; // Get Velocity & splits XMVECTOR horVelocity = XMLoadFloat2(&m_HorVelocity); float vertVelocity = m_VertVelocity; // Get Acceleration & splits XMFLOAT2 horAcc = XMFLOAT2{ m_Acceleration.x, m_Acceleration.z }; // HOR == x & z, not x & y XMVECTOR horAcceleration = XMLoadFloat2(&horAcc); float vertAcceleration = m_Acceleration.y; // DT: float dt = gameContext.pGameTime->GetElapsed(); // Increase velocity with acceleration: horVelocity += horAcceleration * dt; horVelocity = XMVector2ClampLength(horVelocity, 0.0f, m_MaxRunVelocity); vertVelocity += vertAcceleration * dt; // Update velocity: XMStoreFloat2(&m_HorVelocity, horVelocity); // horizontal m_VertVelocity = vertVelocity; // vertical // Horizontal displace: XMVECTOR finalHorDisplacement = XMVector2ClampLength(horVelocity * dt, 0.f, m_MaxRunVelocity); XMFLOAT2 finalHorDisplace; XMStoreFloat2(&finalHorDisplace, finalHorDisplacement); // Vertical displace: (not clamped!) float finalVertDisplacement; finalVertDisplacement = vertVelocity * dt; // Merge displacement: XMFLOAT3 fullDisplacement = { finalHorDisplace.x, finalVertDisplacement, finalHorDisplace.y }; // Move m_pController->Move(fullDisplacement); }
27.744681
148
0.767331
Kair0z
90df8d71df2361262733892562797810024c14ba
1,133
cpp
C++
codex.test/test_object_pool.cpp
codex-tk/old_ref_codex
c0d5a87b991cc2c48fab2902b5e10b8339cecb91
[ "MIT" ]
null
null
null
codex.test/test_object_pool.cpp
codex-tk/old_ref_codex
c0d5a87b991cc2c48fab2902b5e10b8339cecb91
[ "MIT" ]
null
null
null
codex.test/test_object_pool.cpp
codex-tk/old_ref_codex
c0d5a87b991cc2c48fab2902b5e10b8339cecb91
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <codex/convenience/object_pool.hpp> #include "gprintf.hpp" class pooled_object : public codex::object_pool< pooled_object >{ private: void* _dummy; }; TEST( object_pool , single ) { pooled_object* first_object = new pooled_object(); delete first_object; pooled_object* second_object = new pooled_object(); ASSERT_EQ( first_object , second_object ); } TEST( object_pool , many ) { std::set< pooled_object* > pooled_objects; for( int i = 0 ; i < 1024 ; ++i ) { pooled_object* po = new pooled_object(); ASSERT_TRUE( pooled_objects.find( po ) == pooled_objects.end()); pooled_objects.insert( po ); } for ( auto it : pooled_objects) { delete it; } std::vector< pooled_object* > pooled_objects0; for( int i = 0 ; i < 1024 ; ++i ) { pooled_object* po = new pooled_object(); ASSERT_TRUE( pooled_objects.find( po ) != pooled_objects.end()); pooled_objects.erase( po ); pooled_objects0.push_back(po); } while ( !pooled_objects0.empty()){ pooled_object* po = pooled_objects0.back(); pooled_objects0.pop_back(); delete po; } }
24.106383
68
0.673433
codex-tk
90e106faae0b34c0c50fb77d7ed1557cf83b14d8
15,625
hxx
C++
src/factor_unsym.hxx
tasseff/SyLVER
35cb652ece05447ddf12e530e97428078446eaf4
[ "BSD-3-Clause" ]
9
2019-07-02T12:46:22.000Z
2021-07-08T11:54:46.000Z
src/factor_unsym.hxx
tasseff/SyLVER
35cb652ece05447ddf12e530e97428078446eaf4
[ "BSD-3-Clause" ]
2
2020-03-23T22:55:52.000Z
2020-03-24T11:15:16.000Z
src/factor_unsym.hxx
tasseff/SyLVER
35cb652ece05447ddf12e530e97428078446eaf4
[ "BSD-3-Clause" ]
5
2019-06-10T11:11:14.000Z
2020-03-22T02:38:12.000Z
/// @file /// @copyright 2016- The Science and Technology Facilities Council (STFC) /// @author Florent Lopez #pragma once // SyVLER #include "NumericFront.hxx" #include "tasks/tasks_unsym.hxx" // STD #include <limits> // SSIDS #include "ssids/cpu/cpu_iface.hxx" #include "ssids/cpu/Workspace.hxx" namespace sylver { namespace splu { template <typename T, typename PoolAlloc> void factor_front_unsym_app( struct spral::ssids::cpu::cpu_factor_options& options, spldlt::NumericFront<T, PoolAlloc> &node, std::vector<spral::ssids::cpu::Workspace>& workspaces) { // typedef typename std::allocator_traits<PoolAlloc>::template rebind_alloc<int> IntAlloc; typedef typename spldlt::NumericFront<T, PoolAlloc>::IntAlloc IntAlloc; int m = node.get_nrow(); // Frontal matrix order int n = node.get_ncol(); // Number of fully-summed rows/columns int nr = node.get_nr(); // number of block rows int nc = node.get_nc(); // number of fully-summed block columns size_t contrib_dimn = m-n; int blksz = node.blksz; ColumnData<T, IntAlloc>& cdata = *node.cdata; // Column data T u = options.u; // Threshold parameter node.nelim = 0; // for (int k = 0; k < /*1*/ nc; ++k) { BlockUnsym<T>& dblk = node.get_block_unsym(k, k); int *rperm = &node.perm [k*blksz]; int *cperm = &node.cperm[k*blksz]; factor_block_unsym_app_task(dblk, rperm, cperm, cdata); // Compute L factor for (int i = 0; i < k; ++i) { // Super-diagonal block BlockUnsym<T>& lblk = node.get_block_unsym(i, k); appyU_block_app_task(dblk, u, lblk, cdata); } for (int i = k+1; i < nr; ++i) { // Sub-diagonal block BlockUnsym<T>& lblk = node.get_block_unsym(i, k); appyU_block_app_task(dblk, u, lblk, cdata); } adjust_unsym_app_task(k, cdata, node.nelim); // Update nelim in node // Restore failed entries for (int i = 0; i < nr; ++i) { BlockUnsym<T>& blk = node.get_block_unsym(i, k); restore_block_unsym_app_task(k, blk, cdata); } // Compute U factor for (int j = 0; j < k; ++j) { // Left-diagonal block BlockUnsym<T>& ublk = node.get_block_unsym(k, j); applyL_block_app_task(dblk, ublk, cdata, workspaces); } for (int j = k+1; j < nr; ++j) { // Right-diagonal block BlockUnsym<T>& ublk = node.get_block_unsym(k, j); applyL_block_app_task(dblk, ublk, cdata, workspaces); } // continue; // Update previously failed entries // Note: we include the diagonal block which might have some // failed (and restored) entries for (int j = 0; j <= k; ++j) { BlockUnsym<T>& ublk = node.get_block_unsym(k, j); for (int i = 0; i <= k; ++i) { BlockUnsym<T>& lblk = node.get_block_unsym(i, k); BlockUnsym<T>& blk = node.get_block_unsym(i, j); update_block_unsym_app_task(lblk, ublk, blk, cdata); } } // Update uneliminated entries in L for (int j = 0; j <= k; ++j) { BlockUnsym<T>& ublk = node.get_block_unsym(k, j); for (int i = k+1; i < nr; ++i) { BlockUnsym<T>& lblk = node.get_block_unsym(i, k); BlockUnsym<T>& blk = node.get_block_unsym(i, j); update_block_unsym_app_task(lblk, ublk, blk, cdata); } } // Update uneliminated entries in U for (int j = k+1; j < nr; ++j) { BlockUnsym<T>& ublk = node.get_block_unsym(k, j); for (int i = 0; i <= k; ++i) { BlockUnsym<T>& lblk = node.get_block_unsym(i, k); BlockUnsym<T>& blk = node.get_block_unsym(i, j); update_block_unsym_app_task(lblk, ublk, blk, cdata); } } // Udpdate trailing submatrix int en = (n-1)/blksz; // Last block-row/column in factors for (int j = k+1; j < nr; ++j) { BlockUnsym<T>& ublk = node.get_block_unsym(k, j); for (int i = k+1; i < nr; ++i) { // Loop if we are in the cb if ((i > en) && (j > en)) continue; BlockUnsym<T>& lblk = node.get_block_unsym(i, k); BlockUnsym<T>& blk = node.get_block_unsym(i, j); update_block_unsym_app_task(lblk, ublk, blk, cdata); } } // Update contribution blocks if (contrib_dimn>0) { // Update contribution block int rsa = n/blksz; // Last block-row/column in factors for (int j = rsa; j < nr; ++j) { BlockUnsym<T>& ublk = node.get_block_unsym(k, j); for (int i = rsa; i < nr; ++i) { BlockUnsym<T>& lblk = node.get_block_unsym(i, k); spldlt::Tile<T, PoolAlloc>& cblk = node.get_contrib_block(i, j); update_cb_block_unsym_app_task(lblk, ublk, cblk, cdata); } } } } printf("[factor_front_unsym_app] first pass front.nelim = %d\n", node.nelim); // Permute failed entries at the back of the marix // permute_failed_unsym(node); } /// @param a_ij Pointer on block in lower triangular part template <typename T> void copy_failed_diag_unsym( int m, int n, int rfrom, int cfrom, T const* a, int lda, T *out, int ldout, T *lout, int ldlout, T *uout, int lduout) { if(out == a) return; // don't bother moving if memory is the same // Copy failed entries for (int j = cfrom, jout = 0; j < n; ++j, ++jout) { for (int i = rfrom, iout = 0; i < m; ++i, ++iout) { out[jout*ldout+iout] = a[j*lda+i]; } } // Copy L factors for (int j = 0; j < cfrom; ++j) { for (int i = rfrom, iout = 0; i < m; ++i, ++iout) { lout[j*ldlout+iout] = a[j*lda+i]; } } // Copy U factor for (int j = cfrom, jout = 0; j < n; ++j, ++jout) { for (int i = 0; i < rfrom; ++i) { uout[jout*lduout+i] = a[j*lda+i]; } } } template <typename T> void move_up_diag_unsym( int m, int n, T const* a, int lda, T *out, int ldout) { if(out == a) return; // don't bother moving if memory is the same for (int j = 0; j < n; ++j) { for (int i = 0; i < m; ++i) { out[j*ldout+i] = a[j*lda+i]; } } } template <typename T, typename PoolAlloc> void permute_failed_unsym( spldlt::NumericFront<T, PoolAlloc> &node) { // Total number of eliminated rows/columns whithin node int block_size = node.blksz; int num_elim = node.nelim; int n = node.get_ncol(); // Number of fully-summed rows/columns // Number of block rows/columns in the fully-summed int nblk = node.get_nc(); int nfail = n-num_elim; // Number of failed columns // Factor entries T *lcol = node.lcol; int ldl = node.get_ldl(); // Column data typedef typename spldlt::NumericFront<T, PoolAlloc>::IntAlloc IntAlloc; ColumnData<T, IntAlloc>& cdata = *node.cdata; // Column data // Permutation int *rperm = node.perm; int *cperm = node.cperm; printf("[permute_failed_unsym] n = %d\n", n); printf("[permute_failed_unsym] ldl = %d\n", ldl); // std::vector<int, IntAlloc> failed_perm(n-num_elim, alloc); std::vector<int> failed_perm (nfail); std::vector<int> failed_cperm(nfail); // Permute fail entries to the back of the matrix for(int jblk=0, insert=0, fail_insert=0; jblk<nblk; jblk++) { // int blk_n = get_ncol(jblk, n, blksz) int blk_n = std::min(block_size, n-(jblk*block_size)); // Number of fully-summed within block // Move back failed rows cdata[jblk].move_back( blk_n, &rperm[jblk*block_size], &rperm[insert], &failed_perm[fail_insert] ); // Move back failed columns cdata[jblk].move_back( blk_n, &cperm[jblk*block_size], &cperm[insert], &failed_cperm[fail_insert] ); insert += cdata[jblk].nelim; fail_insert += blk_n - cdata[jblk].nelim; } for(int i=0; i < nfail; ++i) { rperm[num_elim+i] = failed_perm [i]; cperm[num_elim+i] = failed_cperm[i]; } std::vector<T> failed_diag(nfail*nfail); std::vector<T> failed_lwr(nfail*num_elim); std::vector<T> failed_upr(num_elim*nfail); // Extract failed entries // Square (diagonal) part for (int jblk=0, jfail=0, jinsert=0; jblk<nblk; ++jblk) { int blk_n = std::min(block_size, n-(jblk*block_size)); // Number of fully-summed within block // printf("[permute_failed_unsym] jblk = %d, blk_n = %d\n", jblk, blk_n); for (int iblk=0, ifail=0, iinsert=0; iblk<nblk; ++iblk) { int blk_m = std::min(block_size, n-(iblk*block_size)); // Number of fully-summed within block // printf("[permute_failed_unsym] iblk = %d, blk_m = %d\n", iblk, blk_m); // printf("[permute_failed_unsym] iblk = %d, jblk = %d, iinsert = %d, jinsert = %d\n", // iblk, jblk, iinsert, jinsert); assert(iblk*block_size < n); assert(jblk*block_size < n); // assert(jfail < nfail); // assert(ifail < nfail); T *failed_diag_ptr = nullptr; if (ifail < nfail && jfail < nfail) failed_diag_ptr = &failed_diag[jfail*nfail+ifail]; copy_failed_diag_unsym( blk_m, blk_n, cdata[iblk].nelim, cdata[jblk].nelim, &lcol[iblk*block_size+jblk*block_size*ldl], ldl, failed_diag_ptr, nfail, &failed_lwr[ifail+jinsert*nfail], nfail, &failed_upr[iinsert+jfail*num_elim], num_elim); iinsert += cdata[iblk].nelim; ifail += blk_m - cdata[iblk].nelim; } jinsert += cdata[jblk].nelim; jfail += blk_n - cdata[jblk].nelim; } // Rectangular (sub-diagonal) part // ... // Move up eliminated entries // Diagonal part for (int jblk=0, jinsert=0; jblk<nblk; ++jblk) { int blk_n = std::min(block_size, n-(jblk*block_size)); // Number of fully-summed within block // printf("[permute_failed_unsym] jblk = %d, blk_n = %d\n", jblk, blk_n); for (int iblk=0, iinsert=0; iblk<nblk; ++iblk) { int blk_m = std::min(block_size, n-(iblk*block_size)); // Number of fully-summed within block // printf("[permute_failed_unsym] iblk = %d, blk_m = %d\n", iblk, blk_m); move_up_diag_unsym( cdata[iblk].nelim, cdata[jblk].nelim, &lcol[jblk*block_size*ldl+iblk*block_size], ldl, &lcol[jinsert*ldl+iinsert], ldl); iinsert += cdata[iblk].nelim; } jinsert += cdata[jblk].nelim; } // printf("[permute_failed_unsym] num_elim = %d, nfail = %d\n", num_elim, nfail); // Copy failed entries back to factor entries // L factor for (int j = 0; j < num_elim; ++j) { for (int i = 0; i < nfail; ++i) { lcol[num_elim+i + j*ldl] = failed_lwr[i+j*nfail]; // lcol[num_elim+i + j*ldl] = std::numeric_limits<double>::quiet_NaN(); } } for (int j = 0; j < nfail; ++j) { for (int i = 0; i < num_elim; ++i) { lcol[i + (j+num_elim)*ldl] = failed_upr[i+j*num_elim]; // lcol[i + (j+num_elim)*ldl] = std::numeric_limits<double>::quiet_NaN(); } for (int i = 0; i < nfail; ++i) { lcol[i+num_elim + (j+num_elim)*ldl] = failed_diag[i+j*nfail]; // lcol[i+num_elim + (j+num_elim)*ldl] = std::numeric_limits<double>::quiet_NaN(); } } } /// @brief Task-based front factorization routine using Restricted /// Pivoting (RP) /// @Note No delays, potentially unstable template <typename T, typename PoolAlloc> void factor_front_unsym_rp( spldlt::NumericFront<T, PoolAlloc> &node, std::vector<spral::ssids::cpu::Workspace>& workspaces) { // Extract front info int m = node.get_nrow(); // Frontal matrix order int n = node.get_ncol(); // Number of fully-summed rows/columns int nr = node.get_nr(); // number of block rows int nc = node.get_nc(); // number of block columns size_t contrib_dimn = m-n; int blksz = node.blksz; printf("[factor_front_unsym_rp] m = %d\n", m); printf("[factor_front_unsym_rp] n = %d\n", n); for(int k = 0; k < nc; ++k) { BlockUnsym<T>& dblk = node.get_block_unsym(k, k); int *perm = &node.perm[k*blksz]; factor_block_lu_pp_task(dblk, perm); // Apply permutation for (int j = 0; j < k; ++j) { BlockUnsym<T>& rblk = node.get_block_unsym(k, j); // Apply row permutation on left-diagonal blocks apply_rperm_block_task(dblk, rblk, workspaces); } // Apply permutation and compute U factors for (int j = k+1; j < nc; ++j) { BlockUnsym<T>& ublk = node.get_block_unsym(k, j); applyL_block_task(dblk, ublk, workspaces); } // Compute L factors for (int i = k+1; i < nr; ++i) { BlockUnsym<T>& lblk = node.get_block_unsym(i, k); applyU_block_task(dblk, lblk); } int en = (n-1)/blksz; // Last block-row/column in factors // Udpdate trailing submatrix for (int j = k+1; j < nr; ++j) { BlockUnsym<T>& ublk = node.get_block_unsym(k, j); for (int i = k+1; i < nr; ++i) { // Loop if we are in the cb if ((i > en) && (j > en)) continue; BlockUnsym<T>& lblk = node.get_block_unsym(i, k); BlockUnsym<T>& blk = node.get_block_unsym(i, j); update_block_lu_task(lblk, ublk, blk); } } if (contrib_dimn>0) { // Update contribution block int rsa = n/blksz; // Last block-row/column in factors for (int j = rsa; j < nr; ++j) { BlockUnsym<T>& ublk = node.get_block_unsym(k, j); for (int i = rsa; i < nr; ++i) { BlockUnsym<T>& lblk = node.get_block_unsym(i, k); spldlt::Tile<T, PoolAlloc>& cblk = node.get_contrib_block(i, j); update_cb_block_lu_task(lblk, ublk, cblk); } } } } // Note: we do not check for stability node.nelim = n; // We eliminated all fully-summed rows/columns node.ndelay_out = 0; // No delays } }} // End of namespace sylver::splu
34.955257
105
0.524416
tasseff
90e1080185a7008f59b9ecfc2909f120fb51b286
198
cpp
C++
net.ssa/itself/itself.cpp
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:19.000Z
2022-03-26T17:00:19.000Z
net.ssa/itself/itself.cpp
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
null
null
null
net.ssa/itself/itself.cpp
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:21.000Z
2022-03-26T17:00:21.000Z
extern"C"int printf(char*,...);char*S="extern%cC%cint printf(char*,...);char*S=%c%s%c;char*T=%c%s%c%s";char*T=";main(){printf(S,34,34,34,S,34,34,T,34,T);}";main(){printf(S,34,34,34,S,34,34,T,34,T);}
198
198
0.611111
ixray-team
90e6605e78f74ac2489927f867407deea660f7d3
2,487
cpp
C++
src/ciphers/vigenere.cpp
Cyclic3/CipheyCore
63cc5fa79b68602e92fd1e16abdbd16b53fcbc53
[ "MIT" ]
35
2020-05-30T10:25:14.000Z
2022-03-09T05:46:28.000Z
src/ciphers/vigenere.cpp
Cyclic3/CipheyCore
63cc5fa79b68602e92fd1e16abdbd16b53fcbc53
[ "MIT" ]
12
2020-08-01T16:52:49.000Z
2021-12-25T22:04:42.000Z
src/ciphers/vigenere.cpp
Cyclic3/CipheyCore
63cc5fa79b68602e92fd1e16abdbd16b53fcbc53
[ "MIT" ]
14
2020-08-06T01:36:08.000Z
2022-02-02T09:53:18.000Z
#include "ciphey/ciphers.hpp" #include "common.hpp" #include <atomic> #include <thread> #include <future> namespace ciphey::vigenere { std::vector<crack_result<key_t>> crack(windowed_prob_table observed, prob_table const& expected, group_t const& group, freq_t count, prob_t p_value) { return detail::reducer<key_t, caesar::key_t, caesar::crack, group_t const&>::crack(observed, expected, count, p_value, group); } void encrypt(string_ref_t str, key_t const& key, group_t const& group) { const auto inverse = invert_group(group); size_t i = 0; for (auto& c : str) { // Ignore letters we cannot find if (auto iter = inverse.find(c); iter != inverse.end()) { c = group[(iter->second + key[i % key.size()]) % group.size()]; ++i; } } } void decrypt(string_ref_t str, key_t const& key, group_t const& group) { std::vector<size_t> inv_key(key.size()); for (size_t i = 0; i < key.size(); ++i) inv_key[i] = group.size() - key[i]; encrypt(str, inv_key, group); } prob_t detect(windowed_prob_table const& observed, prob_table const& expected, freq_t count) { if (count == 0) return 0.; prob_t acc = 1.; for (auto& i : observed) { // FIXME: work out the amount from the count, rather than just flooring it acc *= caesar::detect(i, expected, count / observed.size()); } return acc; } key_len_res likely_key_lens(string_const_ref_t input, prob_table const& expected, domain_t const& domain, prob_t p_value) { key_len_res ret; ret.candidates.reserve(8); // Dividing by 4 is a good guess of what is feasible to crack for (size_t key_len = 2; key_len < input.size() / 8; ++key_len) { ret.candidates.emplace_back(); auto& last = ret.candidates.back(); last.tab = windowed_freq_table(key_len); // I don't think the extra write here has a significant effect of performance ret.count_in_domain = freq_analysis(last.tab, input, domain); auto observed = freq_conv(last.tab, ret.count_in_domain); if (auto prob = detect(observed, expected, ret.count_in_domain); prob > p_value) { last.len = key_len; last.p_value = prob; } else ret.candidates.pop_back(); } std::sort(ret.candidates.rbegin(), ret.candidates.rend(), [](auto& a, auto& b) { return a.p_value < b.p_value; }); return ret; } }
32.723684
130
0.628468
Cyclic3
90e77fb2c6facb656eaed6c70b765736f455498a
131
cpp
C++
Source/Flopnite/Private/GameplayAbilities/FNGameplayAbility.cpp
BEASTSM96/flopnite-ue4
76193544a6b7fe6b969864e74409b6b5a43f3d7a
[ "MIT" ]
null
null
null
Source/Flopnite/Private/GameplayAbilities/FNGameplayAbility.cpp
BEASTSM96/flopnite-ue4
76193544a6b7fe6b969864e74409b6b5a43f3d7a
[ "MIT" ]
null
null
null
Source/Flopnite/Private/GameplayAbilities/FNGameplayAbility.cpp
BEASTSM96/flopnite-ue4
76193544a6b7fe6b969864e74409b6b5a43f3d7a
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "GameplayAbilities/FNGameplayAbility.h"
21.833333
78
0.801527
BEASTSM96
90e7fea70f6a41a06fd08783274321774424f4d8
23,185
cc
C++
components/sync/user_events/user_event_sync_bridge_unittest.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
components/sync/user_events/user_event_sync_bridge_unittest.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
components/sync/user_events/user_event_sync_bridge_unittest.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/sync/user_events/user_event_sync_bridge.h" #include <map> #include <set> #include <utility> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/test/bind_test_util.h" #include "components/sync/driver/fake_sync_service.h" #include "components/sync/model/data_batch.h" #include "components/sync/model/mock_model_type_change_processor.h" #include "components/sync/model/model_type_store_test_util.h" #include "components/sync/protocol/sync.pb.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace syncer { namespace { using sync_pb::UserEventSpecifics; using testing::_; using testing::ElementsAre; using testing::Eq; using testing::Invoke; using testing::IsEmpty; using testing::IsNull; using testing::NotNull; using testing::Pair; using testing::Pointee; using testing::Return; using testing::SaveArg; using testing::SizeIs; using testing::UnorderedElementsAre; using testing::WithArg; using WriteBatch = ModelTypeStore::WriteBatch; MATCHER_P(MatchesUserEvent, expected, "") { if (!arg.has_user_event()) { *result_listener << "which is not a user event"; return false; } const UserEventSpecifics& actual = arg.user_event(); if (actual.event_time_usec() != expected.event_time_usec()) { return false; } if (actual.navigation_id() != expected.navigation_id()) { return false; } if (actual.session_id() != expected.session_id()) { return false; } return true; } UserEventSpecifics CreateSpecifics(int64_t event_time_usec, int64_t navigation_id, uint64_t session_id) { UserEventSpecifics specifics; specifics.set_event_time_usec(event_time_usec); specifics.set_navigation_id(navigation_id); specifics.set_session_id(session_id); return specifics; } std::unique_ptr<UserEventSpecifics> SpecificsUniquePtr(int64_t event_time_usec, int64_t navigation_id, uint64_t session_id) { return std::make_unique<UserEventSpecifics>( CreateSpecifics(event_time_usec, navigation_id, session_id)); } class TestGlobalIdMapper : public GlobalIdMapper { public: void AddGlobalIdChangeObserver(GlobalIdChange callback) override { callback_ = std::move(callback); } int64_t GetLatestGlobalId(int64_t global_id) override { auto iter = id_map_.find(global_id); return iter == id_map_.end() ? global_id : iter->second; } void ChangeId(int64_t old_id, int64_t new_id) { id_map_[old_id] = new_id; callback_.Run(old_id, new_id); } private: GlobalIdChange callback_; std::map<int64_t, int64_t> id_map_; }; class UserEventSyncBridgeTest : public testing::Test { protected: UserEventSyncBridgeTest() { bridge_ = std::make_unique<UserEventSyncBridge>( ModelTypeStoreTestUtil::FactoryForInMemoryStoreForTest(), mock_processor_.CreateForwardingProcessor(), &test_global_id_mapper_, &fake_sync_service_); ON_CALL(*processor(), IsTrackingMetadata()).WillByDefault(Return(true)); } std::string GetStorageKey(const UserEventSpecifics& specifics) { EntityData entity_data; *entity_data.specifics.mutable_user_event() = specifics; return bridge()->GetStorageKey(entity_data); } UserEventSyncBridge* bridge() { return bridge_.get(); } MockModelTypeChangeProcessor* processor() { return &mock_processor_; } FakeSyncService* sync_service() { return &fake_sync_service_; } TestGlobalIdMapper* mapper() { return &test_global_id_mapper_; } std::map<std::string, sync_pb::EntitySpecifics> GetAllData() { base::RunLoop loop; std::unique_ptr<DataBatch> batch; bridge_->GetAllData(base::BindOnce( [](base::RunLoop* loop, std::unique_ptr<DataBatch>* out_batch, std::unique_ptr<DataBatch> batch) { *out_batch = std::move(batch); loop->Quit(); }, &loop, &batch)); loop.Run(); EXPECT_NE(nullptr, batch); std::map<std::string, sync_pb::EntitySpecifics> storage_key_to_specifics; if (batch != nullptr) { while (batch->HasNext()) { const syncer::KeyAndData& pair = batch->Next(); storage_key_to_specifics[pair.first] = pair.second->specifics; } } return storage_key_to_specifics; } std::unique_ptr<sync_pb::EntitySpecifics> GetData( const std::string& storage_key) { base::RunLoop loop; std::unique_ptr<DataBatch> batch; bridge_->GetData( {storage_key}, base::BindOnce( [](base::RunLoop* loop, std::unique_ptr<DataBatch>* out_batch, std::unique_ptr<DataBatch> batch) { *out_batch = std::move(batch); loop->Quit(); }, &loop, &batch)); loop.Run(); EXPECT_NE(nullptr, batch); std::unique_ptr<sync_pb::EntitySpecifics> specifics; if (batch != nullptr && batch->HasNext()) { const syncer::KeyAndData& pair = batch->Next(); specifics = std::make_unique<sync_pb::EntitySpecifics>(pair.second->specifics); EXPECT_FALSE(batch->HasNext()); } return specifics; } private: std::unique_ptr<UserEventSyncBridge> bridge_; testing::NiceMock<MockModelTypeChangeProcessor> mock_processor_; TestGlobalIdMapper test_global_id_mapper_; FakeSyncService fake_sync_service_; base::MessageLoop message_loop_; }; TEST_F(UserEventSyncBridgeTest, MetadataIsInitialized) { EXPECT_CALL(*processor(), ModelReadyToSync(NotNull())); base::RunLoop().RunUntilIdle(); } TEST_F(UserEventSyncBridgeTest, SingleRecord) { const UserEventSpecifics specifics(CreateSpecifics(1u, 2u, 3u)); std::string storage_key; EXPECT_CALL(*processor(), Put(_, _, _)) .WillOnce(WithArg<0>(SaveArg<0>(&storage_key))); bridge()->RecordUserEvent(std::make_unique<UserEventSpecifics>(specifics)); EXPECT_THAT(GetData(storage_key), Pointee(MatchesUserEvent(specifics))); EXPECT_THAT(GetData("bogus"), IsNull()); EXPECT_THAT(GetAllData(), ElementsAre(Pair(storage_key, MatchesUserEvent(specifics)))); } TEST_F(UserEventSyncBridgeTest, ApplyDisableSyncChanges) { const UserEventSpecifics specifics(CreateSpecifics(1u, 2u, 3u)); bridge()->RecordUserEvent(std::make_unique<UserEventSpecifics>(specifics)); ASSERT_THAT(GetAllData(), SizeIs(1)); EXPECT_THAT( bridge()->ApplyDisableSyncChanges(WriteBatch::CreateMetadataChangeList()), Eq(ModelTypeSyncBridge::DisableSyncResponse::kModelStillReadyToSync)); // The bridge may asynchronously query the store to choose what to delete. base::RunLoop().RunUntilIdle(); EXPECT_THAT(GetAllData(), IsEmpty()); } TEST_F(UserEventSyncBridgeTest, ApplyDisableSyncChangesShouldKeepConsents) { UserEventSpecifics user_event_specifics(CreateSpecifics(2u, 2u, 2u)); auto* consent = user_event_specifics.mutable_user_consent(); consent->set_feature(UserEventSpecifics::UserConsent::CHROME_SYNC); consent->set_account_id("account_id"); bridge()->RecordUserEvent( std::make_unique<UserEventSpecifics>(user_event_specifics)); ASSERT_THAT(GetAllData(), SizeIs(1)); EXPECT_THAT( bridge()->ApplyDisableSyncChanges(WriteBatch::CreateMetadataChangeList()), Eq(ModelTypeSyncBridge::DisableSyncResponse::kModelStillReadyToSync)); // The bridge may asynchronously query the store to choose what to delete. base::RunLoop().RunUntilIdle(); // User consent specific must be persisted when sync is disabled. EXPECT_THAT(GetAllData(), ElementsAre(Pair(_, MatchesUserEvent(user_event_specifics)))); } TEST_F(UserEventSyncBridgeTest, MultipleRecords) { std::set<std::string> unique_storage_keys; EXPECT_CALL(*processor(), Put(_, _, _)) .Times(4) .WillRepeatedly( [&unique_storage_keys](const std::string& storage_key, std::unique_ptr<EntityData> entity_data, MetadataChangeList* metadata_change_list) { unique_storage_keys.insert(storage_key); }); bridge()->RecordUserEvent(SpecificsUniquePtr(1u, 1u, 1u)); bridge()->RecordUserEvent(SpecificsUniquePtr(1u, 1u, 2u)); bridge()->RecordUserEvent(SpecificsUniquePtr(1u, 2u, 2u)); bridge()->RecordUserEvent(SpecificsUniquePtr(2u, 2u, 2u)); EXPECT_EQ(2u, unique_storage_keys.size()); EXPECT_THAT(GetAllData(), SizeIs(2)); } TEST_F(UserEventSyncBridgeTest, ApplySyncChanges) { std::string storage_key1; std::string storage_key2; EXPECT_CALL(*processor(), Put(_, _, _)) .WillOnce(WithArg<0>(SaveArg<0>(&storage_key1))) .WillOnce(WithArg<0>(SaveArg<0>(&storage_key2))); bridge()->RecordUserEvent(SpecificsUniquePtr(1u, 1u, 1u)); bridge()->RecordUserEvent(SpecificsUniquePtr(2u, 2u, 2u)); EXPECT_THAT(GetAllData(), SizeIs(2)); auto error_on_delete = bridge()->ApplySyncChanges(bridge()->CreateMetadataChangeList(), {EntityChange::CreateDelete(storage_key1)}); EXPECT_FALSE(error_on_delete); EXPECT_THAT(GetAllData(), SizeIs(1)); EXPECT_THAT(GetData(storage_key1), IsNull()); EXPECT_THAT(GetData(storage_key2), NotNull()); } TEST_F(UserEventSyncBridgeTest, HandleGlobalIdChange) { int64_t first_id = 11; int64_t second_id = 12; int64_t third_id = 13; int64_t fourth_id = 14; std::string storage_key; EXPECT_CALL(*processor(), Put(_, _, _)) .WillOnce(WithArg<0>(SaveArg<0>(&storage_key))); // This id update should be applied to the event as it is initially // recorded. mapper()->ChangeId(first_id, second_id); bridge()->RecordUserEvent(SpecificsUniquePtr(1u, first_id, 2u)); EXPECT_THAT(GetAllData(), ElementsAre(Pair(storage_key, MatchesUserEvent(CreateSpecifics( 1u, second_id, 2u))))); // This id update is done while the event is "in flight", and should result in // it being updated and re-sent to sync. EXPECT_CALL(*processor(), Put(storage_key, _, _)); mapper()->ChangeId(second_id, third_id); EXPECT_THAT(GetAllData(), ElementsAre(Pair(storage_key, MatchesUserEvent(CreateSpecifics( 1u, third_id, 2u))))); auto error_on_delete = bridge()->ApplySyncChanges(bridge()->CreateMetadataChangeList(), {EntityChange::CreateDelete(storage_key)}); EXPECT_FALSE(error_on_delete); EXPECT_THAT(GetAllData(), IsEmpty()); // This id update should be ignored, since we received commit confirmation // above. EXPECT_CALL(*processor(), Put(_, _, _)).Times(0); mapper()->ChangeId(third_id, fourth_id); EXPECT_THAT(GetAllData(), IsEmpty()); } TEST_F(UserEventSyncBridgeTest, MulipleEventsChanging) { int64_t first_id = 11; int64_t second_id = 12; int64_t third_id = 13; int64_t fourth_id = 14; const UserEventSpecifics specifics1 = CreateSpecifics(101u, first_id, 2u); const UserEventSpecifics specifics2 = CreateSpecifics(102u, second_id, 4u); const UserEventSpecifics specifics3 = CreateSpecifics(103u, third_id, 6u); const std::string key1 = GetStorageKey(specifics1); const std::string key2 = GetStorageKey(specifics2); const std::string key3 = GetStorageKey(specifics3); ASSERT_NE(key1, key2); ASSERT_NE(key1, key3); ASSERT_NE(key2, key3); bridge()->RecordUserEvent(std::make_unique<UserEventSpecifics>(specifics1)); bridge()->RecordUserEvent(std::make_unique<UserEventSpecifics>(specifics2)); bridge()->RecordUserEvent(std::make_unique<UserEventSpecifics>(specifics3)); ASSERT_THAT(GetAllData(), UnorderedElementsAre(Pair(key1, MatchesUserEvent(specifics1)), Pair(key2, MatchesUserEvent(specifics2)), Pair(key3, MatchesUserEvent(specifics3)))); mapper()->ChangeId(second_id, fourth_id); EXPECT_THAT( GetAllData(), UnorderedElementsAre( Pair(key1, MatchesUserEvent(specifics1)), Pair(key2, MatchesUserEvent(CreateSpecifics(102u, fourth_id, 4u))), Pair(key3, MatchesUserEvent(specifics3)))); mapper()->ChangeId(first_id, fourth_id); mapper()->ChangeId(third_id, fourth_id); EXPECT_THAT( GetAllData(), UnorderedElementsAre( Pair(key1, MatchesUserEvent(CreateSpecifics(101u, fourth_id, 2u))), Pair(key2, MatchesUserEvent(CreateSpecifics(102u, fourth_id, 4u))), Pair(key3, MatchesUserEvent(CreateSpecifics(103u, fourth_id, 6u))))); } TEST_F(UserEventSyncBridgeTest, RecordBeforeMetadataLoads) { ON_CALL(*processor(), IsTrackingMetadata()).WillByDefault(Return(false)); bridge()->RecordUserEvent(SpecificsUniquePtr(1u, 2u, 3u)); EXPECT_THAT(GetAllData(), IsEmpty()); } // User consents should be buffered if the bridge is not fully initialized. // Other events should get dropped. TEST_F(UserEventSyncBridgeTest, RecordWithLateInitializedStore) { // Wait until bridge() is ready to avoid interference with processor() mock. base::RunLoop().RunUntilIdle(); UserEventSpecifics consent1 = CreateSpecifics(1u, 1u, 1u); consent1.mutable_user_consent()->set_account_id("account_id"); UserEventSpecifics consent2 = CreateSpecifics(2u, 2u, 2u); consent2.mutable_user_consent()->set_account_id("account_id"); UserEventSpecifics specifics1 = CreateSpecifics(3u, 3u, 3u); UserEventSpecifics specifics2 = CreateSpecifics(4u, 4u, 4u); ON_CALL(*processor(), IsTrackingMetadata()).WillByDefault(Return(false)); ModelType store_init_type; ModelTypeStore::InitCallback store_init_callback; UserEventSyncBridge late_init_bridge( base::BindLambdaForTesting( [&](ModelType type, ModelTypeStore::InitCallback callback) { store_init_type = type; store_init_callback = std::move(callback); }), processor()->CreateForwardingProcessor(), mapper(), sync_service()); // Record events before the store is created. Only the consent will be // buffered, the other event is dropped. late_init_bridge.RecordUserEvent( std::make_unique<UserEventSpecifics>(consent1)); late_init_bridge.RecordUserEvent( std::make_unique<UserEventSpecifics>(specifics1)); // Initialize the store. EXPECT_CALL(*processor(), ModelReadyToSync(NotNull())); ON_CALL(*processor(), IsTrackingMetadata()).WillByDefault(Return(true)); std::move(store_init_callback) .Run(/*error=*/base::nullopt, ModelTypeStoreTestUtil::CreateInMemoryStoreForTest(store_init_type)); base::RunLoop().RunUntilIdle(); AccountInfo info; info.account_id = "account_id"; sync_service()->SetAuthenticatedAccountInfo(info); late_init_bridge.OnSyncStarting(); // Record events after metadata is ready. late_init_bridge.RecordUserEvent( std::make_unique<UserEventSpecifics>(consent2)); late_init_bridge.RecordUserEvent( std::make_unique<UserEventSpecifics>(specifics2)); base::RunLoop().RunUntilIdle(); ASSERT_THAT( GetAllData(), UnorderedElementsAre( Pair(GetStorageKey(consent1), MatchesUserEvent(consent1)), Pair(GetStorageKey(consent2), MatchesUserEvent(consent2)), Pair(GetStorageKey(specifics2), MatchesUserEvent(specifics2)))); } TEST_F(UserEventSyncBridgeTest, ShouldReportPreviouslyPersistedConsentsWhenSyncIsReenabled) { UserEventSpecifics consent = CreateSpecifics(1u, 1u, 1u); consent.mutable_user_consent()->set_account_id("account_id"); bridge()->RecordUserEvent(std::make_unique<UserEventSpecifics>(consent)); bridge()->ApplyDisableSyncChanges(WriteBatch::CreateMetadataChangeList()); // The bridge may asynchronously query the store to choose what to delete. base::RunLoop().RunUntilIdle(); ASSERT_THAT(GetAllData(), SizeIs(1)); // Reenable sync. AccountInfo info; info.account_id = "account_id"; sync_service()->SetAuthenticatedAccountInfo(info); ON_CALL(*processor(), IsTrackingMetadata()).WillByDefault(Return(true)); std::string storage_key; EXPECT_CALL(*processor(), Put(_, _, _)) .WillOnce(WithArg<0>(SaveArg<0>(&storage_key))); bridge()->OnSyncStarting(); // The bridge may asynchronously query the store to choose what to resubmit. base::RunLoop().RunUntilIdle(); EXPECT_THAT(storage_key, Eq(GetStorageKey(consent))); } TEST_F(UserEventSyncBridgeTest, ShouldReportPersistedConsentsOnStartupEvenWithLateStoreInitialization) { // Wait until bridge() is ready to avoid interference with processor() mock. base::RunLoop().RunUntilIdle(); UserEventSpecifics consent = CreateSpecifics(1u, 1u, 1u); consent.mutable_user_consent()->set_account_id("account_id"); ON_CALL(*processor(), IsTrackingMetadata()).WillByDefault(Return(false)); ModelType store_init_type; ModelTypeStore::InitCallback store_init_callback; UserEventSyncBridge late_init_bridge( base::BindLambdaForTesting( [&](ModelType type, ModelTypeStore::InitCallback callback) { store_init_type = type; store_init_callback = std::move(callback); }), processor()->CreateForwardingProcessor(), mapper(), sync_service()); // Sync is active, but the store is not ready yet. AccountInfo info; info.account_id = "account_id"; sync_service()->SetAuthenticatedAccountInfo(info); EXPECT_CALL(*processor(), ModelReadyToSync(_)).Times(0); late_init_bridge.OnSyncStarting(); // Initialize the store. std::unique_ptr<ModelTypeStore> store = ModelTypeStoreTestUtil::CreateInMemoryStoreForTest(store_init_type); // TODO(vitaliii): Try to avoid putting the data directly into the store (e.g. // by using a forwarding store), because this is an implementation detail. // However, currently the bridge owns the store and there is no obvious way to // preserve it. // Put the consent manually to simulate a restart with disabled sync. auto batch = store->CreateWriteBatch(); batch->WriteData(GetStorageKey(consent), consent.SerializeAsString()); store->CommitWriteBatch(std::move(batch), base::DoNothing()); base::RunLoop().RunUntilIdle(); EXPECT_CALL(*processor(), ModelReadyToSync(NotNull())); ON_CALL(*processor(), IsTrackingMetadata()).WillByDefault(Return(true)); std::string storage_key; EXPECT_CALL(*processor(), Put(_, _, _)) .WillOnce(WithArg<0>(SaveArg<0>(&storage_key))); std::move(store_init_callback) .Run(/*error=*/base::nullopt, ModelTypeStoreTestUtil::CreateInMemoryStoreForTest(store_init_type)); // The bridge may asynchronously query the store to choose what to resubmit. base::RunLoop().RunUntilIdle(); EXPECT_THAT(storage_key, Eq(GetStorageKey(consent))); } TEST_F(UserEventSyncBridgeTest, ShouldReportPersistedConsentsOnStartupEvenWithLateSyncInitialization) { // Wait until bridge() is ready to avoid interference with processor() mock. base::RunLoop().RunUntilIdle(); UserEventSpecifics consent = CreateSpecifics(1u, 1u, 1u); consent.mutable_user_consent()->set_account_id("account_id"); ON_CALL(*processor(), IsTrackingMetadata()).WillByDefault(Return(false)); ModelType store_init_type; ModelTypeStore::InitCallback store_init_callback; UserEventSyncBridge late_init_bridge( base::BindLambdaForTesting( [&](ModelType type, ModelTypeStore::InitCallback callback) { store_init_type = type; store_init_callback = std::move(callback); }), processor()->CreateForwardingProcessor(), mapper(), sync_service()); // Initialize the store. std::unique_ptr<ModelTypeStore> store = ModelTypeStoreTestUtil::CreateInMemoryStoreForTest(store_init_type); // TODO(vitaliii): Try to avoid putting the data directly into the store (e.g. // by using a forwarding store), because this is an implementation detail. // However, currently the bridge owns the store and there is no obvious way to // preserve it. // Put the consent manually to simulate a restart with disabled sync. auto batch = store->CreateWriteBatch(); batch->WriteData(GetStorageKey(consent), consent.SerializeAsString()); store->CommitWriteBatch(std::move(batch), base::DoNothing()); base::RunLoop().RunUntilIdle(); // The store has been initialized, but the sync is not active yet. ON_CALL(*processor(), IsTrackingMetadata()).WillByDefault(Return(true)); EXPECT_CALL(*processor(), ModelReadyToSync(NotNull())); std::move(store_init_callback) .Run(/*error=*/base::nullopt, ModelTypeStoreTestUtil::CreateInMemoryStoreForTest(store_init_type)); base::RunLoop().RunUntilIdle(); AccountInfo info; info.account_id = "account_id"; sync_service()->SetAuthenticatedAccountInfo(info); late_init_bridge.OnSyncStarting(); std::string storage_key; EXPECT_CALL(*processor(), Put(_, _, _)) .WillOnce(WithArg<0>(SaveArg<0>(&storage_key))); // The bridge may asynchronously query the store to choose what to resubmit. base::RunLoop().RunUntilIdle(); EXPECT_THAT(storage_key, Eq(GetStorageKey(consent))); } TEST_F(UserEventSyncBridgeTest, ShouldSubmitPersistedConsentOnlyIfSameAccount) { AccountInfo info; info.account_id = "first_account"; sync_service()->SetAuthenticatedAccountInfo(info); UserEventSpecifics user_event_specifics(CreateSpecifics(2u, 2u, 2u)); auto* consent = user_event_specifics.mutable_user_consent(); consent->set_account_id("first_account"); bridge()->RecordUserEvent( std::make_unique<UserEventSpecifics>(user_event_specifics)); ASSERT_THAT(GetAllData(), SizeIs(1)); bridge()->ApplyDisableSyncChanges(WriteBatch::CreateMetadataChangeList()); // The bridge may asynchronously query the store to choose what to delete. base::RunLoop().RunUntilIdle(); ASSERT_THAT(GetAllData(), ElementsAre(Pair(_, MatchesUserEvent(user_event_specifics)))); // A new user signs in and enables sync. info.account_id = "second_account"; sync_service()->SetAuthenticatedAccountInfo(info); // The previous account consent should not be resubmited, because the new sync // account is different. EXPECT_CALL(*processor(), Put(_, _, _)).Times(0); ON_CALL(*processor(), IsTrackingMetadata()).WillByDefault(Return(true)); bridge()->OnSyncStarting(); base::RunLoop().RunUntilIdle(); bridge()->ApplyDisableSyncChanges(WriteBatch::CreateMetadataChangeList()); base::RunLoop().RunUntilIdle(); // The previous user signs in again and enables sync. info.account_id = "first_account"; sync_service()->SetAuthenticatedAccountInfo(info); std::string storage_key; EXPECT_CALL(*processor(), Put(_, _, _)) .WillOnce(WithArg<0>(SaveArg<0>(&storage_key))); bridge()->OnSyncStarting(); // The bridge may asynchronously query the store to choose what to resubmit. base::RunLoop().RunUntilIdle(); EXPECT_THAT(storage_key, Eq(GetStorageKey(user_event_specifics))); } } // namespace } // namespace syncer
38.385762
80
0.718007
zipated
90e8850104d10e97d4aa5d749bc4be6afccf0770
5,530
cc
C++
src/sequence_batch.cc
vejnar/chromap
f0ff121845f727b2142f04983211233f27302d13
[ "MIT" ]
null
null
null
src/sequence_batch.cc
vejnar/chromap
f0ff121845f727b2142f04983211233f27302d13
[ "MIT" ]
null
null
null
src/sequence_batch.cc
vejnar/chromap
f0ff121845f727b2142f04983211233f27302d13
[ "MIT" ]
null
null
null
#include "sequence_batch.h" #include <tuple> #include "utils.h" namespace chromap { constexpr uint8_t SequenceBatch::char_to_uint8_table_[256]; constexpr char SequenceBatch::uint8_to_char_table_[8]; void SequenceBatch::InitializeLoading(const std::string &sequence_file_path) { sequence_file_ = gzopen(sequence_file_path.c_str(), "r"); if (sequence_file_ == NULL) { ExitWithMessage("Cannot find sequence file" + sequence_file_path); } sequence_kseq_ = kseq_init(sequence_file_); } uint32_t SequenceBatch::LoadBatch() { double real_start_time = GetRealTime(); uint32_t num_sequences = 0; num_bases_ = 0; for (uint32_t sequence_index = 0; sequence_index < max_num_sequences_; ++sequence_index) { int length = kseq_read(sequence_kseq_); while (length == 0) { // Skip the sequences of length 0 length = kseq_read(sequence_kseq_); } if (length > 0) { kseq_t *sequence = sequence_batch_[sequence_index]; std::swap(sequence_kseq_->seq, sequence->seq); ReplaceByEffectiveRange(sequence->seq); std::swap(sequence_kseq_->name, sequence->name); std::swap(sequence_kseq_->comment, sequence->comment); if (sequence_kseq_->qual.l != 0) { // fastq file std::swap(sequence_kseq_->qual, sequence->qual); ReplaceByEffectiveRange(sequence->qual); } sequence->id = num_loaded_sequences_; ++num_loaded_sequences_; ++num_sequences; num_bases_ += length; } else { if (length != -1) { ExitWithMessage( "Didn't reach the end of sequence file, which might be corrupted!"); } // make sure to reach the end of file rather than meet an error break; } } if (num_sequences != 0) { std::cerr << "Loaded sequence batch successfully in " << GetRealTime() - real_start_time << "s, "; std::cerr << "number of sequences: " << num_sequences << ", "; std::cerr << "number of bases: " << num_bases_ << ".\n"; } else { std::cerr << "No more sequences.\n"; } return num_sequences; } bool SequenceBatch::LoadOneSequenceAndSaveAt(uint32_t sequence_index) { // double real_start_time = Chromap::GetRealTime(); bool no_more_sequence = false; int length = kseq_read(sequence_kseq_); while (length == 0) { // Skip the sequences of length 0 length = kseq_read(sequence_kseq_); } if (length > 0) { kseq_t *sequence = sequence_batch_[sequence_index]; std::swap(sequence_kseq_->seq, sequence->seq); ReplaceByEffectiveRange(sequence->seq); std::swap(sequence_kseq_->name, sequence->name); std::swap(sequence_kseq_->comment, sequence->comment); sequence->id = num_loaded_sequences_; ++num_loaded_sequences_; if (sequence_kseq_->qual.l != 0) { // fastq file std::swap(sequence_kseq_->qual, sequence->qual); ReplaceByEffectiveRange(sequence->qual); } } else { if (length != -1) { ExitWithMessage( "Didn't reach the end of sequence file, which might be corrupted!"); } // make sure to reach the end of file rather than meet an error no_more_sequence = true; } return no_more_sequence; } uint32_t SequenceBatch::LoadAllSequences() { double real_start_time = GetRealTime(); sequence_batch_.reserve(200); uint32_t num_sequences = 0; num_bases_ = 0; int length = kseq_read(sequence_kseq_); while (length >= 0) { if (length == 0) { // Skip the sequences of length 0 continue; } else if (length > 0) { sequence_batch_.emplace_back((kseq_t *)calloc(1, sizeof(kseq_t))); kseq_t *sequence = sequence_batch_.back(); std::swap(sequence_kseq_->seq, sequence->seq); ReplaceByEffectiveRange(sequence->seq); std::swap(sequence_kseq_->name, sequence->name); std::swap(sequence_kseq_->comment, sequence->comment); if (sequence_kseq_->qual.l != 0) { // fastq file std::swap(sequence_kseq_->qual, sequence->qual); ReplaceByEffectiveRange(sequence->qual); } sequence->id = num_loaded_sequences_; ++num_loaded_sequences_; ++num_sequences; num_bases_ += length; } else { if (length != -1) { ExitWithMessage( "Didn't reach the end of sequence file, which might be corrupted!"); } // make sure to reach the end of file rather than meet an error break; } length = kseq_read(sequence_kseq_); } std::cerr << "Loaded all sequences successfully in " << GetRealTime() - real_start_time << "s, "; std::cerr << "number of sequences: " << num_sequences << ", "; std::cerr << "number of bases: " << num_bases_ << ".\n"; return num_sequences; } void SequenceBatch::FinalizeLoading() { kseq_destroy(sequence_kseq_); gzclose(sequence_file_); } void SequenceBatch::ReplaceByEffectiveRange(kstring_t &seq) { if (effective_range_[0] == 0 && effective_range_[1] == -1 && effective_range_[2] == 1) { return; } int i, j; int start = effective_range_[0]; int end = effective_range_[1]; if (effective_range_[1] == -1) end = seq.l - 1; for (i = 0; i < end - start + 1; ++i) { seq.s[i] = seq.s[start + i]; } seq.s[i] = '\0'; seq.l = end - start + 1; if (effective_range_[2] == -1) { for (i = 0; i < (int)seq.l; ++i) { seq.s[i] = Uint8ToChar(((uint8_t)3) ^ (CharToUint8(seq.s[i]))); } for (i = 0, j = seq.l - 1; i < j; ++i, --j) { char tmp = seq.s[i]; seq.s[i] = seq.s[j]; seq.s[j] = tmp; } } } } // namespace chromap
33.113772
80
0.638336
vejnar
90e9d8dab498a49a5ba068712f0162adcd5dff1e
427
cpp
C++
main.cpp
pawbyte/semath
f292718f521d7f6d0d66307f06db854813907b6d
[ "MIT" ]
null
null
null
main.cpp
pawbyte/semath
f292718f521d7f6d0d66307f06db854813907b6d
[ "MIT" ]
null
null
null
main.cpp
pawbyte/semath
f292718f521d7f6d0d66307f06db854813907b6d
[ "MIT" ]
null
null
null
#include "semath.h" #include <iostream> //used to use std::cout to print messages //Make sure to include both "semath.h" and "semath.cpp" in your project directory. int main( int argc, char* args[] ) { std::cout << "Result of <get_direction( 0, 0, 300, 300):" << get_direction( 0, 0, 300, 300) << ".\n"; std::cout << "Result of <get_distance( 0, 0, 300, 300):" << get_distance( 0, 0, 300, 300) << ".\n"; return 0; }
32.846154
104
0.620609
pawbyte
90eb9fc9b4345dbf77c1dca996420342b7c591e5
2,361
cpp
C++
samples/client/petstore/cpp-ue4/Private/OpenAPIUser.cpp
therockstorm/openapi-generator
01d0b5d4780ebe2d6025e2b443ec136c6ce16c45
[ "Apache-2.0" ]
4
2021-02-20T21:39:04.000Z
2021-08-24T13:54:15.000Z
samples/client/petstore/cpp-ue4/Private/OpenAPIUser.cpp
therockstorm/openapi-generator
01d0b5d4780ebe2d6025e2b443ec136c6ce16c45
[ "Apache-2.0" ]
29
2021-04-07T07:38:57.000Z
2022-03-30T12:10:22.000Z
samples/client/petstore/cpp-ue4/Private/OpenAPIUser.cpp
therockstorm/openapi-generator
01d0b5d4780ebe2d6025e2b443ec136c6ce16c45
[ "Apache-2.0" ]
5
2020-11-26T05:13:41.000Z
2021-04-09T15:58:18.000Z
/** * OpenAPI Petstore * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator * https://github.com/OpenAPITools/openapi-generator * Do not edit the class manually. */ #include "OpenAPIUser.h" #include "OpenAPIModule.h" #include "OpenAPIHelpers.h" #include "Templates/SharedPointer.h" namespace OpenAPI { void OpenAPIUser::WriteJson(JsonWriter& Writer) const { Writer->WriteObjectStart(); if (Id.IsSet()) { Writer->WriteIdentifierPrefix(TEXT("id")); WriteJsonValue(Writer, Id.GetValue()); } if (Username.IsSet()) { Writer->WriteIdentifierPrefix(TEXT("username")); WriteJsonValue(Writer, Username.GetValue()); } if (FirstName.IsSet()) { Writer->WriteIdentifierPrefix(TEXT("firstName")); WriteJsonValue(Writer, FirstName.GetValue()); } if (LastName.IsSet()) { Writer->WriteIdentifierPrefix(TEXT("lastName")); WriteJsonValue(Writer, LastName.GetValue()); } if (Email.IsSet()) { Writer->WriteIdentifierPrefix(TEXT("email")); WriteJsonValue(Writer, Email.GetValue()); } if (Password.IsSet()) { Writer->WriteIdentifierPrefix(TEXT("password")); WriteJsonValue(Writer, Password.GetValue()); } if (Phone.IsSet()) { Writer->WriteIdentifierPrefix(TEXT("phone")); WriteJsonValue(Writer, Phone.GetValue()); } if (UserStatus.IsSet()) { Writer->WriteIdentifierPrefix(TEXT("userStatus")); WriteJsonValue(Writer, UserStatus.GetValue()); } Writer->WriteObjectEnd(); } bool OpenAPIUser::FromJson(const TSharedPtr<FJsonValue>& JsonValue) { const TSharedPtr<FJsonObject>* Object; if (!JsonValue->TryGetObject(Object)) return false; bool ParseSuccess = true; ParseSuccess &= TryGetJsonValue(*Object, TEXT("id"), Id); ParseSuccess &= TryGetJsonValue(*Object, TEXT("username"), Username); ParseSuccess &= TryGetJsonValue(*Object, TEXT("firstName"), FirstName); ParseSuccess &= TryGetJsonValue(*Object, TEXT("lastName"), LastName); ParseSuccess &= TryGetJsonValue(*Object, TEXT("email"), Email); ParseSuccess &= TryGetJsonValue(*Object, TEXT("password"), Password); ParseSuccess &= TryGetJsonValue(*Object, TEXT("phone"), Phone); ParseSuccess &= TryGetJsonValue(*Object, TEXT("userStatus"), UserStatus); return ParseSuccess; } }
28.792683
133
0.72554
therockstorm
90ec7873c6b80b7968d92f20f09cfbed0edd3914
4,933
hxx
C++
2/ED/practica1 _ Conjunto/conjunto.hxx
xKuZz/trabajosugr
5dd0cf416ccf5dfe5961713a85581d95cd14aa74
[ "MIT" ]
3
2019-10-23T06:06:43.000Z
2021-05-23T17:20:25.000Z
2/ED/practica1 _ Conjunto/conjunto.hxx
xKuZz/trabajosugr
5dd0cf416ccf5dfe5961713a85581d95cd14aa74
[ "MIT" ]
null
null
null
2/ED/practica1 _ Conjunto/conjunto.hxx
xKuZz/trabajosugr
5dd0cf416ccf5dfe5961713a85581d95cd14aa74
[ "MIT" ]
1
2017-12-18T22:16:47.000Z
2017-12-18T22:16:47.000Z
/** * @file conjunto.hxx * @brief Implementación de la clase conjunto * @author Alejandro Campoy Nieves * @author David Criado Ramón */ /** @brief Constructor por defecto de la clase conjunto (Conjunto vacio). */ conjunto::conjunto(){ } /** * @brief Constructor de copia. * @d Conjunto a copiar. */ conjunto::conjunto(const conjunto &d){ this->vc=d.vc; } /** * @brief Comprueba el invariante de la representación de la clase conjunto. * @return True si se cumple el invariante, false en caso contrario. */ bool conjunto::cheq_rep() const{ for (conjunto::size_type i=0; i<vc.size(); ++i) if (vc[i].getID()<=0) return false; for (conjunto::size_type i=0; i<vc.size()-1; ++i) if(vc[i].getID()>=vc[i+1].getID()) return false; return true; } /** * @brief Comprueba si el conjunto está vacío. * @return True si el conjunto está vacío, false en caso contrario. */ bool conjunto::empty() const{ if (vc.size()==0) return true; return false; } /** * @brief Elimina un elemento del conjunto dado su identificador. * @param id ID de la entrada a eliminar del conjunto. * @return True si se ha podido eliminar, false en caso contrario (no se encontró un crimen con esa id). */ bool conjunto::erase(const long int &id){ vector<conjunto::entrada>::const_iterator it; conjunto::entrada comparativo; comparativo.setID(id); it=lower_bound(vc.begin(),vc.end(),comparativo); if(it->getID()==id){ vc.erase(it); return true; } else{ return false; } } /** * @brief Elimina un elemento del conjunto dado un crimen. * @param e Crimen a eliminar en el conjunto. * @return True si se ha podido eliminar, false en caso contrario (no se encontró el crimen). */ bool conjunto::erase(const conjunto::entrada &e){ return erase(e.getID()); } /** * @brief Busca una entrada dada su id en el conjunto. * @param id ID del crimen a buscar. * @return Par (crimen,verdadero) si se encuentra o (--,falso) si no se encuentra. */ pair<conjunto::entrada,bool> conjunto::find(const long int &id) const{ vector<conjunto::entrada>::const_iterator it; conjunto::entrada comparativo; comparativo.setID(id); pair<conjunto::entrada,bool> salida; it=lower_bound(vc.begin(),vc.end(),comparativo); if (it->getID()==id){ salida.first=*it; salida.second=true; } else { salida.second=false; } return salida; } /** * @brief Inserta una entrada en la posición apropiada del conjunto. * @param e Crimen a introducir. * @return Si se ha insertado correctamente o no (ya existía un crimen con dicha ID). */ bool conjunto::insert(const conjunto::entrada &e){ vector<conjunto::entrada>::const_iterator it; if (vc.size()==0){ vc.push_back(e); return true; } else { it=lower_bound(vc.begin(),vc.end(),e); if (it->getID()!=e.getID()){ vc.insert(it,e); return true; } else { return false; } } } /** * @brief Sobrecarga del operador de asignación. * @param org Conjunto a asignar. * @return Referencia al objeto de la clase (this). */ conjunto& conjunto::operator=(const conjunto &org){ if (this!=&org){ this->vc=org.vc; } return *this; } /** * @brief Devuelve el tamaño del conjunto * @return Tamaño del conjunto */ conjunto::size_type conjunto::size() const{ return vc.size(); } /** * @brief Sobrecarga del operador de extracción de flujos para la clase conjunto. * @param sal Flujo de salida. * @param D Conjunto a mostrar. * @return Referencia al flujo de salida. */ ostream& operator<<(ostream &sal, const conjunto &D){ for(conjunto::size_type i=0; i<D.vc.size(); ++i) sal << D.vc[i] << endl; return sal; } /** * @brief Devuelve un conjunto con todos los crímenes con el mismo IUCR. * @param iucr IUCR a buscar. * @return Conjunto con crímenes con el IUCR proporcionado. */ conjunto conjunto::findIUCR (const string &iucr) const{ conjunto salida; for_each(vc.begin(),vc.end(),[&iucr, &salida](const conjunto::entrada &e){ if (e.getIUCR()==iucr) salida.insert(e); }); return salida; } /** * @brief Devuelve un conjunto con todos los crímenes con la misma descripción. * @param descr Descripción a buscar. * @return Conjunto con todos los crímenes con la descripción proporcionada. */ conjunto conjunto::findDESCR(const string &descr) const { conjunto salida; for_each(vc.begin(),vc.end(),[&descr, &salida](const conjunto::entrada &e){ if (e.getDESCR().rfind(descr)!=string::npos){ salida.insert(e); } }); return salida; }
27.558659
105
0.614433
xKuZz
90ee6174c7fbe76db6759d37259da311e516452e
441
hpp
C++
include/rive/animation/blend_animation.hpp
kariem2k/rive-cpp
f58c3b3d48ea03947a76971bce17e7f567cf0de0
[ "MIT" ]
139
2020-08-17T20:10:24.000Z
2022-03-28T12:22:44.000Z
include/rive/animation/blend_animation.hpp
kariem2k/rive-cpp
f58c3b3d48ea03947a76971bce17e7f567cf0de0
[ "MIT" ]
89
2020-08-28T16:41:01.000Z
2022-03-28T19:10:49.000Z
include/rive/animation/blend_animation.hpp
kariem2k/rive-cpp
f58c3b3d48ea03947a76971bce17e7f567cf0de0
[ "MIT" ]
19
2020-10-19T00:54:40.000Z
2022-02-28T05:34:17.000Z
#ifndef _RIVE_BLEND_ANIMATION_HPP_ #define _RIVE_BLEND_ANIMATION_HPP_ #include "rive/generated/animation/blend_animation_base.hpp" namespace rive { class LinearAnimation; class BlendAnimation : public BlendAnimationBase { private: LinearAnimation* m_Animation = nullptr; public: const LinearAnimation* animation() const { return m_Animation; } StatusCode import(ImportStack& importStack) override; }; } // namespace rive #endif
24.5
66
0.800454
kariem2k
90ef8e39c9035771f1018e3261cac7bd5c5a6271
1,791
hpp
C++
src/main/generic_format/ast/string.hpp
foobar27/generic_format
a44ce919b9c296ce66c0b54a51a61c884ddb78dd
[ "BSL-1.0" ]
null
null
null
src/main/generic_format/ast/string.hpp
foobar27/generic_format
a44ce919b9c296ce66c0b54a51a61c884ddb78dd
[ "BSL-1.0" ]
null
null
null
src/main/generic_format/ast/string.hpp
foobar27/generic_format
a44ce919b9c296ce66c0b54a51a61c884ddb78dd
[ "BSL-1.0" ]
null
null
null
/** @file @copyright Copyright Sebastien Wagener 2014 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) */ #pragma once #include "generic_format/ast/base.hpp" namespace generic_format::ast { /** @brief A format representing a string which is serialized via its length followed by its data. * * @tparam LengthFormat the format used to serialize the length. */ template <IntegralFormat LengthFormat> struct string : base<format_list<LengthFormat>> { using native_type = std::string; using length_format = LengthFormat; using native_length_type = typename length_format::native_type; static constexpr auto size = dynamic_size(); template <class RawWriter, class State> void write(RawWriter& raw_writer, State& state, const std::string& s) const { if (s.length() > std::numeric_limits<native_length_type>::max()) throw serialization_exception(); length_format().write(raw_writer, state, static_cast<native_length_type>(s.length())); raw_writer(reinterpret_cast<const void*>(s.data()), s.length()); } template <class RawReader, class State> void read(RawReader& raw_reader, State& state, std::string& s) const { native_length_type length; length_format().read(raw_reader, state, length); if (length > std::numeric_limits<std::size_t>::max()) throw deserialization_exception(); s = std::string(static_cast<std::size_t>(length), 0); // TODO(sw) we don't need to fill the string raw_reader(const_cast<void*>(reinterpret_cast<const void*>(s.data())), s.length()); } }; } // end namespace generic_format::ast
38.934783
106
0.683975
foobar27
90f1a4536dca3d15b69e4c3bab3d3f518eb2fca4
111,610
cpp
C++
OGDF/src/coin/Symphony/tm_func.cpp
shahnidhi/MetaCarvel
f3bea5fdbbecec4c9becc6bbdc9585a939eb5481
[ "MIT" ]
13
2017-12-21T03:35:41.000Z
2022-01-31T13:45:25.000Z
OGDF/src/coin/Symphony/tm_func.cpp
shahnidhi/MetaCarvel
f3bea5fdbbecec4c9becc6bbdc9585a939eb5481
[ "MIT" ]
7
2017-09-13T01:31:24.000Z
2021-12-14T00:31:50.000Z
OGDF/src/coin/Symphony/tm_func.cpp
shahnidhi/MetaCarvel
f3bea5fdbbecec4c9becc6bbdc9585a939eb5481
[ "MIT" ]
15
2017-09-07T18:28:55.000Z
2022-01-18T14:17:43.000Z
/*===========================================================================*/ /* */ /* This file is part of the SYMPHONY MILP Solver Framework. */ /* */ /* SYMPHONY was jointly developed by Ted Ralphs (ted@lehigh.edu) and */ /* Laci Ladanyi (ladanyi@us.ibm.com). */ /* */ /* (c) Copyright 2000-2011 Ted Ralphs. All Rights Reserved. */ /* */ /* This software is licensed under the Eclipse Public License. Please see */ /* accompanying file for terms. */ /* */ /*===========================================================================*/ #define COMPILING_FOR_TM #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #if !defined(_MSC_VER) && !defined(__MNO_CYGWIN) && defined(SIGHANDLER) #include <signal.h> #if !defined(HAS_SRANDOM) extern int srandom PROTO((unsigned seed)); #endif #if !defined(HAS_RANDOM) extern long random PROTO((void)); #endif #endif #ifdef _OPENMP #include "omp.h" #endif #if !defined (_MSC_VER) #include <unistd.h> /* this defines sleep() */ #endif #include "sym_tm.h" #include "sym_constants.h" #include "sym_types.h" #include "sym_macros.h" #include "sym_messages.h" #include "sym_proccomm.h" #include "sym_timemeas.h" #include "sym_pack_cut.h" #include "sym_pack_array.h" #ifdef COMPILE_IN_LP #include "sym_lp.h" #endif #ifdef COMPILE_IN_TM #include "sym_master.h" #else #include "sym_cp.h" #endif int c_count = 0; /*===========================================================================*/ /*===========================================================================*\ * This file contains basic functions associated with the treemanager process \*===========================================================================*/ /*===========================================================================*/ /*===========================================================================*\ * This function receives the intitial parameters and data and sets up * the tree manager data structures, etc. \*===========================================================================*/ int tm_initialize(tm_prob *tm, base_desc *base, node_desc *rootdesc) { #ifndef COMPILE_IN_TM int r_bufid, bytes, msgtag, i; #endif FILE *f = NULL; tm_params *par; bc_node *root = (bc_node *) calloc(1, sizeof(bc_node)); #ifdef COMPILE_IN_LP int i; #else #ifdef COMPILE_IN_TM int i; #endif int s_bufid; #endif int *termcodes = NULL; #if !defined(_MSC_VER) && !defined(__MNO_CYGWIN) && defined(SIGHANDLER) signal(SIGINT, sym_catch_c); #endif par = &tm->par; #ifdef _OPENMP tm->rpath = (bc_node ***) calloc(par->max_active_nodes, sizeof(bc_node **)); tm->rpath_size = (int *) calloc(par->max_active_nodes, sizeof(int)); tm->bpath = (branch_desc **) calloc(par->max_active_nodes, sizeof(branch_desc *)); tm->bpath_size = (int *) calloc(par->max_active_nodes, sizeof(int)); termcodes = (int *) calloc(par->max_active_nodes, sizeof(int)); #else tm->rpath = (bc_node ***) calloc(1, sizeof(bc_node **)); tm->rpath_size = (int *) calloc(1, sizeof(int)); tm->bpath = (branch_desc **) calloc(1, sizeof(branch_desc *)); tm->bpath_size = (int *) calloc(1, sizeof(int)); termcodes = (int *) calloc(1, sizeof(int)); #endif /*------------------------------------------------------------------------*\ * Receives data from the master \*------------------------------------------------------------------------*/ #ifdef COMPILE_IN_TM tm->bvarnum = base->varnum; tm->bcutnum = base->cutnum; #else r_bufid = receive_msg(ANYONE, TM_DATA); bufinfo(r_bufid, &bytes, &msgtag, &tm->master); receive_char_array((char *)par, sizeof(tm_params)); receive_char_array(&tm->has_ub, 1); if (tm->has_ub) receive_dbl_array(&tm->ub, 1); receive_char_array(&tm->has_ub_estimate, 1); if (tm->has_ub_estimate) receive_dbl_array(&tm->ub_estimate, 1); READ_STR_LIST(par->lp_mach_num, MACH_NAME_LENGTH, par->lp_machs[0], par->lp_machs); READ_STR_LIST(par->cg_mach_num, MACH_NAME_LENGTH, par->cg_machs[0], par->cg_machs); READ_STR_LIST(par->cp_mach_num, MACH_NAME_LENGTH, par->cp_machs[0], par->cp_machs); receive_int_array(&tm->bvarnum, 1); receive_int_array(&tm->bcutnum, 1); #ifdef TRACE_PATH receive_int_array(&tm->feas_sol_size, 1); if (tm->feas_sol_size){ tm->feas_sol = (int *) calloc (tm->feas_sol_size, sizeof(int)); receive_int_array(tm->feas_sol, tm->feas_sol_size); } #endif freebuf(r_bufid); #endif SRANDOM(par->random_seed); #ifdef COMPILE_IN_LP #ifdef _OPENMP omp_set_dynamic(FALSE); omp_set_num_threads(par->max_active_nodes); #else par->max_active_nodes = 1; #endif tm->active_nodes = (bc_node **) calloc(par->max_active_nodes, sizeof(bc_node *)); #ifndef COMPILE_IN_TM tm->lpp = (lp_prob **) malloc(par->max_active_nodes * sizeof(lp_prob *)); for (i = 0; i < par->max_active_nodes; i++){ tm->lpp[i] = (lp_prob *) calloc(1, sizeof(lp_prob)); tm->lpp[i]->proc_index = i; } #ifdef COMPILE_IN_CG tm->cgp = (cg_prob **) malloc(par->max_active_nodes * sizeof(cg_prob *)); for (i = 0; i < par->max_active_nodes; i++) tm->lpp[i]->cgp = tm->cgp[i] = (cg_prob *) calloc(1, sizeof(cg_prob)); par->use_cg = FALSE; #endif #endif #pragma omp parallel for shared(tm) for (i = 0; i < par->max_active_nodes; i++){ if ((termcodes[i] = lp_initialize(tm->lpp[i], 0)) < 0){ printf("LP initialization failed with error code %i in thread %i\n\n", termcodes[i], i); } tm->lpp[i]->tm = tm; } tm->lp.free_num = par->max_active_nodes; for (i = 0; i < par->max_active_nodes; i++){ if (termcodes[i] < 0){ int tmp = termcodes[i]; FREE(termcodes); return(tmp); } } #else tm->active_nodes = (bc_node **) malloc(par->max_active_nodes * sizeof(bc_node *)); /*------------------------------------------------------------------------*\ * Start the lp, cg processes and send cg tid's to the lp's. * Also, start the cp, sp processes. \*------------------------------------------------------------------------*/ tm->lp = start_processes(tm, par->max_active_nodes, par->lp_exe, par->lp_debug, par->lp_mach_num, par->lp_machs); #endif #pragma omp critical (cut_pool) if (!tm->cuts){ tm->cuts = (cut_data **) malloc(BB_BUNCH * sizeof(cut_data *)); } if (par->use_cg){ #ifndef COMPILE_IN_CG tm->cg = start_processes(tm, par->max_active_nodes, par->cg_exe, par->cg_debug, par->cg_mach_num, par->cg_machs); #ifdef COMPILE_IN_LP for (i = 0; i < par->max_active_nodes; i++) tm->lpp[i]->cut_gen = tm->cg.procs[i]; #else for (i = 0; i < tm->lp.procnum; i++){ s_bufid = init_send(DataInPlace); send_int_array(tm->cg.procs + i, 1); send_msg(tm->lp.procs[i], LP__CG_TID_INFO); } #endif #endif } if (par->max_cp_num){ #ifdef COMPILE_IN_CP #ifndef COMPILE_IN_TM tm->cpp = (cut_pool **) malloc(par->max_cp_num * sizeof(cut_pool *)); #endif for (i = 0; i < par->max_cp_num; i++){ #ifndef COMPILE_IN_TM tm->cpp[i] = (cut_pool *) calloc(1, sizeof(cut_pool)); #endif cp_initialize(tm->cpp[i], tm->master); } tm->cp.free_num = par->max_cp_num; tm->cp.procnum = par->max_cp_num; tm->cp.free_ind = (int *) malloc(par->max_cp_num * ISIZE); for (i = par->max_cp_num - 1; i >= 0; i--) tm->cp.free_ind[i] = i; #else tm->cp = start_processes(tm, par->max_cp_num, par->cp_exe, par->cp_debug, par->cp_mach_num, par->cp_machs); #endif tm->nodes_per_cp = (int *) calloc(tm->par.max_cp_num, ISIZE); tm->active_nodes_per_cp = (int *) calloc(tm->par.max_cp_num, ISIZE); }else{ #ifdef COMPILE_IN_CP tm->cpp = (cut_pool **) calloc(1, sizeof(cut_pool *)); #endif } /*------------------------------------------------------------------------*\ * Receive the root node and send out initial data to the LP processes \*------------------------------------------------------------------------*/ FREE(termcodes); if (tm->par.warm_start){ if (!tm->rootnode){ if (!(f = fopen(tm->par.warm_start_tree_file_name, "r"))){ printf("Error reading warm start file %s\n\n", tm->par.warm_start_tree_file_name); return(ERROR__READING_WARM_START_FILE); } read_tm_info(tm, f); }else{ free(root); root = tm->rootnode; } read_subtree(tm, root, f); if (f) fclose(f); if (!tm->rootnode){ if (!read_tm_cut_list(tm, tm->par.warm_start_cut_file_name)){ printf("Error reading warm start file %s\n\n", tm->par.warm_start_cut_file_name); return(ERROR__READING_WARM_START_FILE); } } tm->rootnode = root; if(root->node_status != NODE_STATUS__WARM_STARTED) root->node_status = NODE_STATUS__ROOT; }else{ #ifdef COMPILE_IN_TM (tm->rootnode = root)->desc = *rootdesc; /* Copy the root description in case it is still needed */ root->desc.uind.list = (int *) malloc(rootdesc->uind.size*ISIZE); memcpy((char *)root->desc.uind.list, (char *)rootdesc->uind.list, rootdesc->uind.size*ISIZE); root->bc_index = tm->stat.created++; root->lower_bound = -MAXDOUBLE; tm->stat.tree_size++; insert_new_node(tm, root); tm->phase = 0; tm->lb = 0; #else r_bufid = receive_msg(tm->master, TM_ROOT_DESCRIPTION); receive_node_desc(tm, root); if (root->desc.cutind.size > 0){ /* Hey we got cuts, too! Unpack them. */ unpack_cut_set(tm, 0, 0, NULL); } freebuf(r_bufid); #endif #ifdef TRACE_PATH root->optimal_path = TRUE; #endif } return(FUNCTION_TERMINATED_NORMALLY); } /*===========================================================================*/ /*===========================================================================*\ * This is the main loop that solves the problem \*===========================================================================*/ int solve(tm_prob *tm) { #ifndef COMPILE_IN_LP int r_bufid; #endif int termcode = 0; double start_time = tm->start_time; double no_work_start, ramp_up_tm = 0, ramp_down_time = 0; char ramp_down = FALSE, ramp_up = TRUE; double then, then2, then3, now; double timeout2 = 30, timeout3 = tm->par.logging_interval, timeout4 = 10; /*------------------------------------------------------------------------*\ * The Main Loop \*------------------------------------------------------------------------*/ no_work_start = wall_clock(NULL); termcode = TM_UNFINISHED; for (; tm->phase <= 1; tm->phase++){ if (tm->phase == 1 && !tm->par.warm_start){ if ((termcode = tasks_before_phase_two(tm)) == FUNCTION_TERMINATED_NORMALLY){ termcode = TM_FINISHED; /* Continue normally */ } } then = wall_clock(NULL); then2 = wall_clock(NULL); then3 = wall_clock(NULL); #pragma omp parallel default(shared) { #ifdef _OPENMP int i, thread_num = omp_get_thread_num(); #else int i, thread_num = 0; #endif while (tm->active_node_num > 0 || tm->samephase_candnum > 0){ /*------------------------------------------------------------------*\ * while there are nodes being processed or while there are nodes * waiting to be processed, continue to execute this loop \*------------------------------------------------------------------*/ i = NEW_NODE__STARTED; while (tm->lp.free_num > 0 && (tm->par.time_limit >= 0.0 ? (wall_clock(NULL) - start_time < tm->par.time_limit) : TRUE) && (tm->par.node_limit >= 0 ? tm->stat.analyzed < tm->par.node_limit : TRUE) && ((tm->has_ub && (tm->par.gap_limit >= 0.0)) ? fabs(100*(tm->ub-tm->lb)/tm->ub) > tm->par.gap_limit : TRUE) && !(tm->par.find_first_feasible && tm->has_ub) && c_count <= 0){ if (tm->samephase_candnum > 0){ #pragma omp critical (tree_update) i = start_node(tm, thread_num); }else{ i = NEW_NODE__NONE; } if (i != NEW_NODE__STARTED) break; if (ramp_up){ ramp_up_tm += (wall_clock(NULL) - no_work_start) * (tm->lp.free_num + 1); } if (ramp_down){ ramp_down_time += (wall_clock(NULL) - no_work_start) * (tm->lp.free_num + 1); } if (!tm->lp.free_num){ ramp_down = FALSE; ramp_up = FALSE; }else if (ramp_up){ no_work_start = wall_clock(NULL); }else{ ramp_down = TRUE; no_work_start = wall_clock(NULL); } #ifdef COMPILE_IN_LP #ifdef _OPENMP if (tm->par.verbosity > 0) printf("Thread %i now processing node %i\n", thread_num, tm->lpp[thread_num]->bc_index); #endif if(tm->par.node_selection_rule == DEPTH_FIRST_THEN_BEST_FIRST && tm->has_ub){ tm->par.node_selection_rule = LOWEST_LP_FIRST; } switch(process_chain(tm->lpp[thread_num])){ case FUNCTION_TERMINATED_NORMALLY: break; case ERROR__NO_BRANCHING_CANDIDATE: termcode = TM_ERROR__NO_BRANCHING_CANDIDATE; break; case ERROR__ILLEGAL_RETURN_CODE: termcode = TM_ERROR__ILLEGAL_RETURN_CODE; break; case ERROR__NUMERICAL_INSTABILITY: termcode = TM_ERROR__NUMERICAL_INSTABILITY; break; case ERROR__COMM_ERROR: termcode = TM_ERROR__COMM_ERROR; case ERROR__USER: termcode = TM_ERROR__USER; break; case ERROR__DUAL_INFEASIBLE: if(tm->lpp[thread_num]->bc_index < 1 ) { termcode = TM_UNBOUNDED; }else{ termcode = TM_ERROR__NUMERICAL_INSTABILITY; } break; } #endif #pragma omp master { now = wall_clock(NULL); if (now - then2 > timeout2){ if(tm->par.verbosity >= -1 ){ print_tree_status(tm); } then2 = now; } if (now - then3 > timeout3){ write_log_files(tm); then3 = now; } } } if (c_count > 0){ termcode = TM_SIGNAL_CAUGHT; c_count = 0; break; } if (tm->par.time_limit >= 0.0 && wall_clock(NULL) - start_time > tm->par.time_limit && termcode != TM_FINISHED){ termcode = TM_TIME_LIMIT_EXCEEDED; break; } if (tm->par.node_limit >= 0 && tm->stat.analyzed >= tm->par.node_limit && termcode != TM_FINISHED){ if (tm->active_node_num + tm->samephase_candnum > 0){ termcode = TM_NODE_LIMIT_EXCEEDED; }else{ termcode = TM_FINISHED; } break; } if (tm->par.find_first_feasible && tm->has_ub){ termcode = TM_FINISHED; break; } if (i == NEW_NODE__ERROR){ termcode = SOMETHING_DIED; break; } if (tm->has_ub && (tm->par.gap_limit >= 0.0)){ find_tree_lb(tm); if (fabs(100*(tm->ub-tm->lb)/tm->ub) <= tm->par.gap_limit){ if (tm->lb < tm->ub){ termcode = TM_TARGET_GAP_ACHIEVED; }else{ termcode = TM_FINISHED; } break; } } if (i == NEW_NODE__NONE && tm->active_node_num == 0) break; #ifndef COMPILE_IN_LP struct timeval timeout = {5, 0}; r_bufid = treceive_msg(ANYONE, ANYTHING, &timeout); if (r_bufid && !process_messages(tm, r_bufid)){ find_tree_lb(tm); termcode = SOMETHING_DIED; break; } #endif now = wall_clock(NULL); if (now - then > timeout4){ if (!processes_alive(tm)){ find_tree_lb(tm); termcode = SOMETHING_DIED; break; } then = now; } #pragma omp master { for (i = 0; i < tm->par.max_active_nodes; i++){ if (tm->active_nodes[i]){ break; } } if (i == tm->par.max_active_nodes){ tm->active_node_num = 0; } if (now - then2 > timeout2){ if(tm->par.verbosity >=0 ){ print_tree_status(tm); } then2 = now; } if (now - then3 > timeout3){ write_log_files(tm); then3 = now; } } } } if(termcode == TM_UNBOUNDED) break; if (tm->samephase_candnum + tm->active_node_num == 0){ termcode = TM_FINISHED; } if (tm->nextphase_candnum == 0) break; if (termcode != TM_UNFINISHED) break; } find_tree_lb(tm); tm->comp_times.ramp_up_tm = ramp_up_tm; tm->comp_times.ramp_down_time = ramp_down_time; write_log_files(tm); return(termcode); } /*===========================================================================*/ /*==========================================================================*\ * Write out the log files \*==========================================================================*/ void write_log_files(tm_prob *tm) { #if !defined(COMPILE_IN_LP) || !defined(COMPILE_IN_CP) int s_bufid; #endif if (tm->par.logging){ write_tm_info(tm, tm->par.tree_log_file_name, NULL, FALSE); write_subtree(tm->rootnode, tm->par.tree_log_file_name, NULL, TRUE, tm->par.logging); if (tm->par.logging != VBC_TOOL) write_tm_cut_list(tm, tm->par.cut_log_file_name, FALSE); } if (tm->par.max_cp_num > 0 && tm->par.cp_logging){ #if defined(COMPILE_IN_LP) && defined(COMPILE_IN_CP) write_cp_cut_list(tm->cpp[0], tm->cpp[0]->par.log_file_name, FALSE); #else s_bufid = init_send(DataInPlace); send_msg(tm->cp.procs[0], WRITE_LOG_FILE); #endif } } /*===========================================================================*/ /*==========================================================================*\ * Prints out the current size of the tree and the gap * \*==========================================================================*/ void print_tree_status(tm_prob *tm) { double elapsed_time; double obj_ub = SYM_INFINITY, obj_lb = -SYM_INFINITY; #ifdef SHOULD_SHOW_MEMORY_USAGE int i; int pid; int tmp_int; long unsigned vsize; char tmp_str[100], proc_filename[100]; FILE *proc_file; double vsize_in_mb; #endif #if 0 int *widths; double *gamma; int last_full_level = 0, max_width = 0, num_nodes_estimate = 1; int first_waist_level = 0, last_waist_level = 0, waist_level = 0; double average_node_time, estimated_time_remaining, user_time = 0.0; widths = (int *) calloc (tm->stat.max_depth + 1, ISIZE); gamma = (double *) calloc (tm->stat.max_depth + 1, DSIZE); calculate_widths(tm->rootnode, widths); last_full_level = tm->stat.max_depth; for (i = tm->stat.max_depth - 1; i > 0; i--){ if ((double)(widths[i])/(double)(widths[i - 1]) < 2){ last_full_level = i - 1; } if (widths[i] > max_width){ max_width = widths[i]; last_waist_level = i; first_waist_level = i; } if (widths[i] == max_width){ first_waist_level = i; } } waist_level = (first_waist_level + last_waist_level)/2; for (i = 0; i < tm->stat.max_depth; i++){ if (i < last_full_level){ gamma[i] = 2.0; }else if (i < waist_level){ gamma[i] = 2.0 - (double)((i - last_full_level + 1))/ (double)((waist_level - last_full_level + 1)); }else{ gamma[i] = 1.0 - (double)(i - waist_level + 1)/ (double)(tm->stat.max_depth - waist_level + 1); } } for (i = 1; i < tm->stat.max_depth; i++){ gamma[i] *= gamma[i - 1]; num_nodes_estimate += (int)(gamma[i] + 0.5); } elapsed_time = wall_clock(NULL) - tm->start_time; average_node_time = elapsed_time/tm->stat.analyzed; estimated_time_remaining = MAX(average_node_time*(num_nodes_estimate - tm->stat.analyzed), 0); #else elapsed_time = wall_clock(NULL) - tm->start_time; #endif #ifdef SHOULD_SHOW_MEMORY_USAGE pid = getpid(); //printf("process id = %d\n",pid); sprintf(proc_filename,"/proc/%d/stat",pid); proc_file = fopen (proc_filename, "r"); fscanf (proc_file, "%d %s %s", &tmp_int, tmp_str, tmp_str); for (i=0; i<19;i++) { fscanf (proc_file, "%d", &tmp_int); } fscanf (proc_file, "%lu", &vsize); fclose(proc_file); //printf("vsize = %lu\n",vsize); vsize_in_mb = vsize/1024.0/1024.0; if (tm->stat.max_vsize<vsize_in_mb) { tm->stat.max_vsize = vsize_in_mb; } printf("memory: %.2f MB ", vsize_in_mb); #endif printf("done: %i ", tm->stat.analyzed-tm->active_node_num); printf("left: %i ", tm->samephase_candnum+tm->active_node_num); if (tm->has_ub) { if (tm->obj_sense == SYM_MAXIMIZE){ obj_lb = -tm->ub + tm->obj_offset; printf("lb: %.2f ", obj_lb); }else{ obj_ub = tm->ub + tm->obj_offset; printf("ub: %.2f ", obj_ub); } } else { if (tm->obj_sense == SYM_MAXIMIZE){ printf("lb: ?? "); }else{ printf("ub: ?? "); } } find_tree_lb(tm); if(tm->lb > -SYM_INFINITY){ if (tm->obj_sense == SYM_MAXIMIZE){ obj_ub = -tm->lb + tm->obj_offset; printf("ub: %.2f ", obj_ub); }else{ obj_lb = tm->lb + tm->obj_offset; printf("lb: %.2f ", obj_lb); } }else{ if (tm->obj_sense == SYM_MAXIMIZE){ printf("ub: ?? "); }else{ printf("lb: ?? "); } } if (tm->has_ub && tm->ub && tm->lb > -SYM_INFINITY){ printf("gap: %.2f ", fabs(100*(obj_ub-obj_lb)/obj_ub)); } printf("time: %i\n", (int)(elapsed_time)); #if 0 printf("Estimated nodes remaining: %i\n", num_nodes_estimate); printf("Estimated time remaining: %i\n", (int)(estimated_time_remaining)); #endif if (tm->par.vbc_emulation == VBC_EMULATION_FILE){ FILE *f; #pragma omp critical(write_vbc_emulation_file) if (!(f = fopen(tm->par.vbc_emulation_file_name, "a"))){ printf("\nError opening vbc emulation file\n\n"); }else{ PRINT_TIME(tm, f); fprintf(f, "L %.2f \n", tm->lb); fclose(f); } }else if (tm->par.vbc_emulation == VBC_EMULATION_LIVE){ printf("$L %.2f\n", tm->lb); } #if 0 FREE(widths); FREE(gamma); #endif } /*===========================================================================*/ void calculate_widths(bc_node *node, int* widths) { int i; widths[node->bc_level] += 1; for (i = 0; i < node->bobj.child_num; i ++){ calculate_widths(node->children[i], widths); } } /*===========================================================================*/ /*===========================================================================*\ * This function picks the "best" node off the active node list \*===========================================================================*/ int start_node(tm_prob *tm, int thread_num) { int lp_ind, get_next, ind; bc_node *best_node = NULL; double time; time = wall_clock(NULL); /*------------------------------------------------------------------------*\ * First choose the "best" node from the list of candidate nodes. * If the list for the current phase is empty then we return NEW_NODE__NONE. * Also, if the lower bound on the "best" node is above the current UB then * we just move that node the list of next phase candidates. \*------------------------------------------------------------------------*/ get_next = TRUE; while (get_next){ if ((best_node = del_best_node(tm)) == NULL) return(NEW_NODE__NONE); if (best_node->node_status == NODE_STATUS__WARM_STARTED){ if(best_node->lower_bound >= MAXDOUBLE) break; } /* if no UB yet or lb is lower than UB then go ahead */ if (!tm->has_ub || (tm->has_ub && best_node->lower_bound < tm->ub-tm->par.granularity)) break; /* ok, so we do have an UB and lb is higher than the UB. */ /* in this switch we assume that there are only two phases! */ switch (((best_node->desc.nf_status) << 8) + tm->phase){ case (NF_CHECK_NOTHING << 8) + 0: /* prune these */ case (NF_CHECK_NOTHING << 8) + 1: if(!tm->par.sensitivity_analysis){ if (tm->par.max_cp_num > 0 && best_node->cp){ #ifdef COMPILE_IN_CP ind = best_node->cp; #else ind = find_process_index(&tm->cp, best_node->cp); #endif tm->nodes_per_cp[ind]--; if (tm->nodes_per_cp[ind] + tm->active_nodes_per_cp[ind] == 0) tm->cp.free_ind[tm->cp.free_num++] = ind; } best_node->node_status = NODE_STATUS__PRUNED; best_node->feasibility_status = OVER_UB_PRUNED; if (tm->par.verbosity > 0){ printf("++++++++++++++++++++++++++++++++++++++++++++++++++\n"); printf("+ TM: Pruning NODE %i LEVEL %i instead of sending it.\n", best_node->bc_index, best_node->bc_level); printf("++++++++++++++++++++++++++++++++++++++++++++++++++\n"); } if (tm->par.keep_description_of_pruned == KEEP_ON_DISK_VBC_TOOL || tm->par.keep_description_of_pruned == KEEP_ON_DISK_FULL || tm->par.keep_description_of_pruned == DISCARD){ if (tm->par.keep_description_of_pruned == KEEP_ON_DISK_VBC_TOOL || tm->par.keep_description_of_pruned == KEEP_ON_DISK_FULL){ #pragma omp critical (write_pruned_node_file) write_pruned_nodes(tm, best_node); } #if 0 if (tm->par.vbc_emulation == VBC_EMULATION_FILE_NEW) { purge_pruned_nodes(tm, best_node, VBC_PRUNED_FATHOMED); } else { purge_pruned_nodes(tm, best_node, VBC_PRUNED); } #else purge_pruned_nodes(tm, best_node, VBC_PRUNED); #endif } break; } case (NF_CHECK_ALL << 8) + 1: /* work on these */ case (NF_CHECK_UNTIL_LAST << 8) + 1: case (NF_CHECK_AFTER_LAST << 8) + 1: get_next = FALSE; break; default: /* i.e., phase == 0 and nf_status != NF_CHECK_NOTHING */ if (!(tm->par.colgen_strat[0] & FATHOM__GENERATE_COLS__RESOLVE)){ REALLOC(tm->nextphase_cand, bc_node *, tm->nextphase_cand_size, tm->nextphase_candnum+1, BB_BUNCH); tm->nextphase_cand[tm->nextphase_candnum++] = best_node; }else{ get_next = FALSE; } break; } } /* Assign a free lp process */ #ifdef COMPILE_IN_LP lp_ind = thread_num; #else lp_ind = tm->lp.free_ind[--tm->lp.free_num]; best_node->lp = tm->lp.procs[lp_ind]; best_node->cg = tm->par.use_cg ? tm->cg.procs[lp_ind] : 0; #endif /* assign pools, too */ best_node->cp = assign_pool(tm, best_node->cp, &tm->cp, tm->active_nodes_per_cp, tm->nodes_per_cp); if (best_node->cp < 0) return(NEW_NODE__ERROR); /* It's time to put together the node and send it out */ tm->active_nodes[lp_ind] = best_node; tm->active_node_num++; tm->stat.analyzed++; send_active_node(tm,best_node,tm->par.colgen_strat[tm->phase],thread_num); tm->comp_times.start_node += wall_clock(NULL) - time; return(NEW_NODE__STARTED); } /*===========================================================================*/ /*===========================================================================*\ * Returns the "best" active node and deletes it from the list \*===========================================================================*/ bc_node *del_best_node(tm_prob *tm) { bc_node **list = tm->samephase_cand; int size = tm->samephase_candnum; bc_node *temp = NULL, *best_node; int pos, ch; int rule = tm->par.node_selection_rule; if (size == 0) return(NULL); best_node = list[1]; temp = list[1] = list[size]; tm->samephase_candnum = --size; if (tm->par.verbosity > 10) if (tm->samephase_candnum % 10 == 0) printf("\nTM: tree size: %i , %i\n\n", tm->samephase_candnum, tm->nextphase_candnum); pos = 1; while ((ch=2*pos) < size){ if (node_compar(rule, list[ch], list[ch+1])) ch++; if (node_compar(rule, list[ch], temp)){ list[pos] = temp; return(best_node); } list[pos] = list[ch]; pos = ch; } if (ch == size){ if (node_compar(rule, temp, list[ch])){ list[pos] = list[ch]; pos = ch; } } list[pos] = temp; return(best_node); } /*===========================================================================*/ /*===========================================================================*\ * Insert a new active node into the active node list (kept as a binary tree) \*===========================================================================*/ void insert_new_node(tm_prob *tm, bc_node *node) { int pos, ch, size = tm->samephase_candnum; bc_node **list; int rule = tm->par.node_selection_rule; tm->samephase_candnum = pos = ++size; if (tm->par.verbosity > 10) if (tm->samephase_candnum % 10 == 0) printf("\nTM: tree size: %i , %i\n\n", tm->samephase_candnum, tm->nextphase_candnum); REALLOC(tm->samephase_cand, bc_node *, tm->samephase_cand_size, size + 1, BB_BUNCH); list = tm->samephase_cand; while ((ch=pos>>1) != 0){ if (node_compar(rule, list[ch], node)){ list[pos] = list[ch]; pos = ch; }else{ break; } } list[pos] = node; } /*===========================================================================*/ /*===========================================================================*\ * This is the node comparison function used to order the list of active * Nodes are ordered differently depending on what the comparison rule is \*===========================================================================*/ int node_compar(int rule, bc_node *node0, bc_node *node1) { switch(rule){ case LOWEST_LP_FIRST: return(node1->lower_bound < node0->lower_bound ? 1:0); case HIGHEST_LP_FIRST: return(node1->lower_bound > node0->lower_bound ? 1:0); case BREADTH_FIRST_SEARCH: return(node1->bc_level < node0->bc_level ? 1:0); case DEPTH_FIRST_SEARCH: case DEPTH_FIRST_THEN_BEST_FIRST: return(node1->bc_level > node0->bc_level ? 1:0); } return(0); /* fake return */ } /*===========================================================================*/ /*===========================================================================*\ * Nodes by default inherit their parent's pools. However if there is a free * pool then the node is moved over to the free pool. \*===========================================================================*/ int assign_pool(tm_prob *tm, int oldpool, process_set *pools, int *active_nodes_per_pool, int *nodes_per_pool) { int oldind = -1, ind, pool; #ifndef COMPILE_IN_CP int s_bufid, r_bufid; struct timeval timeout = {5, 0}; #endif if (pools->free_num == 0){ /* No change in the pool assigned to this node */ return(oldpool); } if (oldpool > 0){ #ifdef COMPILE_IN_CP oldind = oldpool; #else oldind = find_process_index(pools, oldpool); #endif if (nodes_per_pool[oldind] == 1){ nodes_per_pool[oldind]--; active_nodes_per_pool[oldind]++; return(oldpool); } } ind = pools->free_ind[--pools->free_num]; #ifdef COMPILE_IN_CP pool = ind; #else pool = pools->procs[ind]; #endif if (! oldpool){ /* If no pool is assigned yet then just assign the free one */ active_nodes_per_pool[ind] = 1; return(pool); } /* finally when we really move the node from one pool to another */ nodes_per_pool[oldind]--; active_nodes_per_pool[ind] = 1; #ifdef COMPILE_IN_CP /*FIXME: Multiple Pools won't work in shared memory mode until I fill this in.*/ #else s_bufid = init_send(DataInPlace); send_int_array(&oldpool, 1); send_msg(pool, POOL_YOU_ARE_USELESS); s_bufid = init_send(DataInPlace); send_int_array(&pool, 1); send_msg(oldpool, POOL_COPY_YOURSELF); freebuf(s_bufid); do{ r_bufid = treceive_msg(pool, POOL_USELESSNESS_ACKNOWLEDGED, &timeout); if (r_bufid == 0) if (pstat(pool) != PROCESS_OK) return(NEW_NODE__ERROR); }while (r_bufid == 0); freebuf(r_bufid); #endif return(pool); } /*===========================================================================*/ /*===========================================================================*\ * Takes the branching object description and sets up data structures * for the resulting children and adds them to the list of candidates. \*===========================================================================*/ int generate_children(tm_prob *tm, bc_node *node, branch_obj *bobj, double *objval, int *feasible, char *action, int olddive, int *keep, int new_branching_cut) { node_desc *desc; int np_cp = 0, np_sp = 0; int dive = DO_NOT_DIVE, i; bc_node *child; int child_num; #ifdef TRACE_PATH int optimal_path = -1; #endif /* before we start to generate the children we must figure out if we'll * dive so that we can put the kept child into the right location */ if (*keep >= 0 && (olddive == CHECK_BEFORE_DIVE || olddive == DO_DIVE)) dive = olddive == DO_DIVE ? DO_DIVE : shall_we_dive(tm, objval[*keep]); node->children = (bc_node **) calloc(bobj->child_num, sizeof(bc_node *)); if (node->bc_level == tm->stat.max_depth) tm->stat.max_depth++; child_num = bobj->child_num; #ifdef TRACE_PATH if (node->optimal_path && tm->feas_sol_size){ for (i = 0; i < tm->feas_sol_size; i++) if (tm->feas_sol[i] == bobj->name) break; if (i < tm->feas_sol_size) optimal_path = 1; else optimal_path = 0; printf("\n\nNode %i is on the optimal path\n\n", tm->stat.tree_size + optimal_path); } #endif for (i = 0; i < child_num; i++){ child = node->children[i] = (bc_node *) calloc(1, sizeof(bc_node)); child->bc_index = tm->stat.tree_size++; child->bc_level = node->bc_level + 1; child->lower_bound = objval[i]; #ifdef COMPILE_IN_LP child->update_pc = bobj->is_est[i] ? TRUE : FALSE; #endif child->parent = node; if (tm->par.verbosity > 10){ printf("Generating node %i from %i...\n", child->bc_index, node->bc_index); } if (tm->par.vbc_emulation == VBC_EMULATION_FILE){ FILE *f; #pragma omp critical(write_vbc_emulation_file) if (!(f = fopen(tm->par.vbc_emulation_file_name, "a"))){ printf("\nError opening vbc emulation file\n\n"); }else{ PRINT_TIME(tm, f); fprintf(f, "N %i %i %i\n", node->bc_index+1, child->bc_index+1, feasible[i] ? VBC_FEAS_SOL_FOUND : ((dive != DO_NOT_DIVE && *keep == i) ? VBC_ACTIVE_NODE : VBC_CAND_NODE)); fclose(f); } } else if (tm->par.vbc_emulation == VBC_EMULATION_FILE_NEW) { FILE *f; #pragma omp critical(write_vbc_emulation_file) if (!(f = fopen(tm->par.vbc_emulation_file_name, "a"))){ printf("\nError opening vbc emulation file\n\n"); }else{ PRINT_TIME2(tm, f); char reason[50]; char branch_dir = 'M'; sprintf (reason, "%s %i %i", "candidate", child->bc_index+1, node->bc_index+1); if (child->bc_index>0){ if (node->children[0]==child) { branch_dir = node->bobj.sense[0]; /*branch_dir = 'L';*/ } else { branch_dir = node->bobj.sense[1]; /*branch_dir = 'R';*/ } if (branch_dir == 'G') { branch_dir = 'R'; } } if (action[i] == PRUNE_THIS_CHILD_FATHOMABLE || action[i] == PRUNE_THIS_CHILD_INFEASIBLE){ sprintf(reason,"%s %c", reason, branch_dir); }else{ sprintf(reason,"%s %c %f", reason, branch_dir, child->lower_bound); } fprintf(f,"%s\n",reason); fclose(f); } }else if (tm->par.vbc_emulation == VBC_EMULATION_LIVE){ printf("$N %i %i %i\n", node->bc_index+1, child->bc_index+1, feasible[i] ? VBC_FEAS_SOL_FOUND : ((dive != DO_NOT_DIVE && *keep == i) ? VBC_ACTIVE_NODE: VBC_CAND_NODE)); } #ifdef TRACE_PATH if (optimal_path == i) child->optimal_path = TRUE; #endif tm->stat.created++; #ifndef ROOT_NODE_ONLY if (action[i] == PRUNE_THIS_CHILD || action[i] == PRUNE_THIS_CHILD_FATHOMABLE || action[i] == PRUNE_THIS_CHILD_INFEASIBLE || (tm->has_ub && tm->ub - tm->par.granularity < objval[i] && node->desc.nf_status == NF_CHECK_NOTHING)){ /* this last can happen if the TM got the new bound but it hasn't * been propagated to the LP yet */ #else /*We only want to process the root node in this case - discard others*/ if (TRUE){ #endif if (tm->par.verbosity > 0){ printf("++++++++++++++++++++++++++++++++++++++++++++++++++++\n"); printf("+ TM: Pruning NODE %i LEVEL %i while generating it.\n", child->bc_index, child->bc_level); printf("++++++++++++++++++++++++++++++++++++++++++++++++++++\n"); } child->node_status = NODE_STATUS__PRUNED; #ifdef TRACE_PATH if (child->optimal_path){ printf("\n\nAttempting to prune the optimal path!!!!!!!!!\n\n"); sleep(600); if (tm->par.logging){ write_tm_info(tm, tm->par.tree_log_file_name, NULL, FALSE); write_subtree(tm->rootnode, tm->par.tree_log_file_name, NULL, TRUE, tm->par.logging); write_tm_cut_list(tm, tm->par.cut_log_file_name, FALSE); } exit(1); } #endif if (tm->par.keep_description_of_pruned == DISCARD || tm->par.keep_description_of_pruned == KEEP_ON_DISK_VBC_TOOL){ child->parent = node; if (tm->par.keep_description_of_pruned == KEEP_ON_DISK_VBC_TOOL) #pragma omp critical (write_pruned_node_file) write_pruned_nodes(tm, child); if (tm->par.vbc_emulation == VBC_EMULATION_FILE_NEW) { int vbc_node_pr_reason; switch (action[i]) { case PRUNE_THIS_CHILD_INFEASIBLE: vbc_node_pr_reason = VBC_PRUNED_INFEASIBLE; break; case PRUNE_THIS_CHILD_FATHOMABLE: vbc_node_pr_reason = VBC_PRUNED_FATHOMED; break; default: vbc_node_pr_reason = VBC_PRUNED; } /* following is no longer needed because this care is taken * care of in install_new_ub */ /* if (feasible[i]) { vbc_node_pr_reason = VBC_FEAS_SOL_FOUND; } */ #pragma omp critical (tree_update) purge_pruned_nodes(tm, child, vbc_node_pr_reason); } else { #pragma omp critical (tree_update) purge_pruned_nodes(tm, child, feasible[i] ? VBC_FEAS_SOL_FOUND : VBC_PRUNED); } if (--child_num == 0){ *keep = -1; return(DO_NOT_DIVE); } if (*keep == child_num) *keep = i; #ifdef TRACE_PATH if (optimal_path == child_num) optimal_path = i; #endif action[i] = action[child_num]; objval[i] = objval[child_num]; feasible[i--] = feasible[child_num]; continue; } }else{ child->node_status = NODE_STATUS__CANDIDATE; /* child->lp = child->cg = 0; zeroed out by calloc */ child->cp = node->cp; } #ifdef DO_TESTS if (child->lower_bound < child->parent->lower_bound - .01){ printf("#######Error: Child's lower bound (%.3f) is less than ", child->lower_bound); printf("parent's (%.3f)\n", child->parent->lower_bound); } if (child->lower_bound < tm->rootnode->lower_bound - .01){ printf("#######Error: Node's lower bound (%.3f) is less than ", child->lower_bound); printf("root's (%.3f)\n", tm->rootnode->lower_bound); } #endif /* child->children = NULL; zeroed out by calloc */ /* child->child_num = 0; zeroed out by calloc */ /* child->died = 0; zeroed out by calloc */ desc = &child->desc; /* all this is set by calloc * desc->uind.type = 0; WRT_PARENT and no change * desc->uind.size = 0; * desc->uind.added = 0; * desc->uind.list = NULL; * desc->not_fixed.type = 0; WRT_PARENT and no change * desc->not_fixed.size = 0; * desc->not_fixed.added = 0; * desc->not_fixed.list = NULL; * desc->cutind.type = 0; WRT_PARENT and no change * desc->cutind.size = 0; * desc->cutind.added = 0; * desc->cutind.list = NULL; * desc->basis.basis_exists = FALSE; This has to be validated!!! * desc->basis.{[base,extra][rows,vars]} .type = 0; WRT_PARENT and no change .size = 0; .list = NULL; .stat = NULL; */ if (node->desc.basis.basis_exists){ desc->basis.basis_exists = TRUE; } /* If we have a non-base, new branching cut then few more things might have to be fixed */ if (new_branching_cut && bobj->name >= 0){ /* Fix cutind and the basis description */ desc->cutind.size = 1; desc->cutind.added = 1; desc->cutind.list = (int *) malloc(ISIZE); desc->cutind.list[0] = bobj->name; if (desc->basis.basis_exists){ desc->basis.extrarows.size = 1; desc->basis.extrarows.list = (int *) malloc(ISIZE); desc->basis.extrarows.list[0] = bobj->name; desc->basis.extrarows.stat = (int *) malloc(ISIZE); desc->basis.extrarows.stat[0] = SLACK_BASIC; } } desc->desc_size = node->desc.desc_size; desc->desc = node->desc.desc; desc->nf_status = node->desc.nf_status; #ifdef SENSITIVITY_ANALYSIS if (tm->par.sensitivity_analysis && action[i] != PRUNE_THIS_CHILD_INFEASIBLE){ child->duals = bobj->duals[i]; bobj->duals[i] = 0; } #endif if (child->node_status != NODE_STATUS__PRUNED && feasible[i]){ if(tm->par.keep_description_of_pruned == KEEP_IN_MEMORY){ child->sol_size = bobj->sol_sizes[i]; child->sol_ind = bobj->sol_inds[i]; bobj->sol_inds[i]=0; child->sol = bobj->solutions[i]; bobj->solutions[i] = 0; child->feasibility_status = NOT_PRUNED_HAS_CAN_SOLUTION; } } if (child->node_status == NODE_STATUS__PRUNED){ if(tm->par.keep_description_of_pruned == KEEP_IN_MEMORY){ child->feasibility_status = OVER_UB_PRUNED; if (feasible[i]){ child->sol_size = bobj->sol_sizes[i]; child->sol_ind = bobj->sol_inds[i]; bobj->sol_inds[i] = 0; child->sol = bobj->solutions[i]; bobj->solutions[i] = 0; child->feasibility_status = FEASIBLE_PRUNED; } if (action[i] == PRUNE_THIS_CHILD_INFEASIBLE){ child->feasibility_status = INFEASIBLE_PRUNED; } } #ifdef TRACE_PATH if (child->optimal_path){ printf("\n\nAttempting to prune the optimal path!!!!!!!!!\n\n"); sleep(600); if (tm->par.logging){ write_tm_info(tm, tm->par.tree_log_file_name, NULL, FALSE); write_subtree(tm->rootnode, tm->par.tree_log_file_name, NULL, TRUE, tm->par.logging); write_tm_cut_list(tm, tm->par.cut_log_file_name, FALSE); } exit(1); } #endif if (tm->par.keep_description_of_pruned == KEEP_ON_DISK_FULL || tm->par.keep_description_of_pruned == KEEP_ON_DISK_VBC_TOOL){ #pragma omp critical (write_pruned_node_file) write_pruned_nodes(tm, child); #pragma omp critical (tree_update) if (tm->par.vbc_emulation== VBC_EMULATION_FILE_NEW) { int vbc_node_pr_reason; switch (action[i]) { case PRUNE_THIS_CHILD_INFEASIBLE: vbc_node_pr_reason = VBC_PRUNED_INFEASIBLE; break; case PRUNE_THIS_CHILD_FATHOMABLE: vbc_node_pr_reason = VBC_PRUNED_FATHOMED; break; default: vbc_node_pr_reason = VBC_PRUNED; } /* following is no longer needed because this care is taken * care of in install_new_ub */ /* if (feasible[i]) { vbc_node_pr_reason = VBC_FEAS_SOL_FOUND; } */ purge_pruned_nodes(tm, child, vbc_node_pr_reason); } else { purge_pruned_nodes(tm, child, feasible[i] ? VBC_FEAS_SOL_FOUND : VBC_PRUNED); } if (--child_num == 0){ *keep = -1; return(DO_NOT_DIVE); } if (*keep == child_num) *keep = i; #ifdef TRACE_PATH if (optimal_path == child_num) optimal_path = i; #endif action[i] = action[child_num]; objval[i] = objval[child_num]; feasible[i--] = feasible[child_num]; } continue; } if (tm->phase == 0 && !(tm->par.colgen_strat[0] & FATHOM__GENERATE_COLS__RESOLVE) && (feasible[i] == LP_D_UNBOUNDED || (tm->has_ub && tm->ub - tm->par.granularity < child->lower_bound))){ /* it is kept for the next phase (==> do not dive) */ if (*keep == i) dive = DO_NOT_DIVE; REALLOC(tm->nextphase_cand, bc_node *, tm->nextphase_cand_size, tm->nextphase_candnum+1, BB_BUNCH); tm->nextphase_cand[tm->nextphase_candnum++] = child; np_cp++; np_sp++; }else{ /* it will be processed in this phase (==> insert it if not kept) */ if (*keep != i || dive == DO_NOT_DIVE){ #pragma omp critical (tree_update) insert_new_node(tm, child); np_cp++; np_sp++; } } } if (node->cp) #ifdef COMPILE_IN_CP tm->nodes_per_cp[node->cp] += np_cp; #else tm->nodes_per_cp[find_process_index(&tm->cp, node->cp)] += np_cp; #endif return(dive); } /*===========================================================================*/ /*===========================================================================*\ * Determines whether or not the LP process should keep one of the * children resulting from branching or whether it should get a new node * from the candidate list. \*===========================================================================*/ char shall_we_dive(tm_prob *tm, double objval) { char dive; int i, k; double rand_num, average_lb; double cutoff = 0; double etol = 1e-3; if (tm->par.time_limit >= 0.0 && wall_clock(NULL) - tm->start_time >= tm->par.time_limit){ return(FALSE); } if (tm->par.node_limit >= 0 && tm->stat.analyzed >= tm->par.node_limit){ return(FALSE); } if (tm->has_ub && (tm->par.gap_limit >= 0.0)){ find_tree_lb(tm); if (100*(tm->ub-tm->lb)/(fabs(tm->ub)+etol) <= tm->par.gap_limit){ return(FALSE); } } rand_num = ((double)(RANDOM()))/((double)(MAXINT)); if (tm->par.unconditional_dive_frac > 1 - rand_num){ dive = CHECK_BEFORE_DIVE; }else{ switch(tm->par.diving_strategy){ case BEST_ESTIMATE: if (tm->has_ub_estimate){ if (objval > tm->ub_estimate){ dive = DO_NOT_DIVE; tm->stat.diving_halts++; }else{ dive = CHECK_BEFORE_DIVE; } break; } case COMP_BEST_K: average_lb = 0; #pragma omp critical (tree_update) for (k = 0, i = MIN(tm->samephase_candnum, tm->par.diving_k); i > 0; i--) if (tm->samephase_cand[i]->lower_bound < MAXDOUBLE/2){ average_lb += tm->samephase_cand[i]->lower_bound; k++; } if (k){ average_lb /= k; }else{ dive = CHECK_BEFORE_DIVE; break; } if (fabs(average_lb) < etol) { average_lb = (average_lb > 0) ? etol : -etol; if (fabs(objval) < etol) { objval = (objval > 0) ? etol : -etol; } } if (fabs((objval/average_lb)-1) > tm->par.diving_threshold){ dive = DO_NOT_DIVE; tm->stat.diving_halts++; }else{ dive = CHECK_BEFORE_DIVE; } break; case COMP_BEST_K_GAP: average_lb = 0; for (k = 0, i = MIN(tm->samephase_candnum, tm->par.diving_k); i > 0; i--) if (tm->samephase_cand[i]->lower_bound < MAXDOUBLE/2){ average_lb += tm->samephase_cand[i]->lower_bound; k++; } if (k){ average_lb /= k; }else{ dive = CHECK_BEFORE_DIVE; break; } if (tm->has_ub) cutoff = tm->par.diving_threshold*(tm->ub - average_lb); else cutoff = (1 + tm->par.diving_threshold)*average_lb; if (objval > average_lb + cutoff){ dive = DO_NOT_DIVE; tm->stat.diving_halts++; }else{ dive = CHECK_BEFORE_DIVE; } break; default: printf("Unknown diving strategy -- diving by default\n"); dive = DO_DIVE; break; } } return(dive); } /*===========================================================================*/ /*===========================================================================*\ * This routine is entirely for saving memory. If there is no need to * keep the description of the pruned nodes in memory, they are freed as * soon as they are no longer needed. This can set off a chain reaction * of other nodes that are no longer needed. \*===========================================================================*/ int purge_pruned_nodes(tm_prob *tm, bc_node *node, int category) { int i, new_child_num; branch_obj *bobj = &node->parent->bobj; char reason[30]; char branch_dir = 'M'; if (tm->par.vbc_emulation != VBC_EMULATION_FILE_NEW && (category == VBC_PRUNED_INFEASIBLE || category == VBC_PRUNED_FATHOMED || category == VBC_IGNORE)) { printf("Error in purge_pruned_nodes."); printf("category refers to VBC_EMULATION_FILE_NEW"); printf("when it is not used.\n"); exit(456); } if (tm->par.vbc_emulation == VBC_EMULATION_FILE_NEW) { switch (category) { case VBC_PRUNED_INFEASIBLE: sprintf(reason,"%s","infeasible"); sprintf(reason,"%s %i %i",reason, node->bc_index+1, node->parent->bc_index+1); if (node->bc_index>0) { if (node->parent->children[0]==node) { branch_dir = node->parent->bobj.sense[0]; /*branch_dir = 'L';*/ } else { branch_dir = node->parent->bobj.sense[1]; /*branch_dir = 'R';*/ } if (branch_dir == 'G') { branch_dir = 'R'; } } sprintf(reason,"%s %c %s", reason, branch_dir, "\n"); break; case VBC_PRUNED_FATHOMED: sprintf(reason,"%s","fathomed"); sprintf(reason,"%s %i %i",reason, node->bc_index+1, node->parent->bc_index+1); if (node->bc_index>0) { if (node->parent->children[0]==node) { branch_dir = node->parent->bobj.sense[0]; /*branch_dir = 'L';*/ } else { branch_dir = node->parent->bobj.sense[1]; /*branch_dir = 'R';*/ } if (branch_dir == 'G') { branch_dir = 'R'; } } sprintf(reason,"%s %c %s", reason, branch_dir, "\n"); break; case VBC_FEAS_SOL_FOUND: /* This case has already been dealt in install_new_ub(), hence * commented out */ /* sprintf(reason,"%s","integer"); sprintf(reason,"%s %i %i",reason, node->bc_index+1, node->parent->bc_index+1); if (node->parent->children[0]==node) { branch_dir = 'L'; } else { branch_dir = 'R'; } sprintf(reason,"%s %c %f\n", reason, branch_dir, tm->ub); break; */ default: category = VBC_IGNORE; break; } } if (node->parent == NULL){ return(1); } if (category == VBC_IGNORE) { #if 0 PRINT(tm->par.verbosity, 1, ("ignoring vbc update in purge_pruned_nodes")); #endif } else if (tm->par.vbc_emulation == VBC_EMULATION_FILE){ FILE *f; #pragma omp critical(write_vbc_emulation_file) if (!(f = fopen(tm->par.vbc_emulation_file_name, "a"))){ printf("\nError opening vbc emulation file\n\n"); }else{ PRINT_TIME(tm, f); fprintf(f, "P %i %i\n", node->bc_index+1, category); fclose(f); } } else if (tm->par.vbc_emulation == VBC_EMULATION_LIVE){ printf("$P %i %i\n", node->bc_index+1, category); } else if (tm->par.vbc_emulation == VBC_EMULATION_FILE_NEW) { FILE *f; #pragma omp critical(write_vbc_emulation_file) if (!(f = fopen(tm->par.vbc_emulation_file_name, "a"))){ printf("\nError opening vbc emulation file\n\n"); }else{ PRINT_TIME2(tm, f); fprintf(f, "%s", reason); fclose(f); } } if ((new_child_num = --bobj->child_num) == 0){ if (tm->par.vbc_emulation == VBC_EMULATION_FILE_NEW) { purge_pruned_nodes(tm, node->parent, VBC_IGNORE); } else { purge_pruned_nodes(tm, node->parent, category); } }else{ for (i = 0; i <= bobj->child_num; i++){ if (node->parent->children[i] == node){ if (i == new_child_num){ node->parent->children[i] = NULL; }else{ node->parent->children[i]=node->parent->children[new_child_num]; bobj->sense[i] = bobj->sense[new_child_num]; bobj->rhs[i] = bobj->rhs[new_child_num]; bobj->range[i] = bobj->range[new_child_num]; bobj->branch[i] = bobj->branch[new_child_num]; } } } } free_tree_node(node); return(1); } /*===========================================================================*\ * This routine is for writing the pruned nodes to disk before deleting them * from memory. \*===========================================================================*/ int write_pruned_nodes(tm_prob *tm, bc_node *node) { FILE *f = NULL; branch_obj *bobj = &node->parent->bobj; if (tm->par.keep_description_of_pruned == KEEP_ON_DISK_FULL || tm->par.keep_description_of_pruned == KEEP_ON_DISK_VBC_TOOL){ if (!(f = fopen(tm->par.pruned_node_file_name, "a"))){ printf("\nError opening pruned node file\n\n"); return(0); } } if (node->parent == NULL){ return(1); } if (bobj->child_num == 1){ write_pruned_nodes(tm, node->parent); } if (tm->par.keep_description_of_pruned == KEEP_ON_DISK_VBC_TOOL){ if (node->parent) fprintf(f, "%i %i\n", node->parent->bc_index + 1, node->bc_index + 1); fclose(f); }else if (tm->par.keep_description_of_pruned == KEEP_ON_DISK_FULL){ write_node(node, tm->par.pruned_node_file_name, f, TRUE); fclose(f); } return(1); } /*===========================================================================*/ /*===========================================================================*\ * Find the index of a particular process in a list \*===========================================================================*/ int find_process_index(process_set *pset, int tid) { int i = pset->procnum-1, *procs = pset->procs; for ( ; i >= 0 && procs[i] != tid; i--); #ifdef DO_TESTS if (i == -1){ printf("TM: process index not found !!!\n\n"); exit(-5); } #endif return(i); } /*===========================================================================*/ void mark_lp_process_free(tm_prob *tm, int lp, int cp) { int ind; if (tm->cp.procnum > 0){ #ifdef COMPILE_IN_CP ind = cp; #else ind = find_process_index(&tm->cp, cp); #endif tm->active_nodes_per_cp[ind]--; if (tm->nodes_per_cp[ind] + tm->active_nodes_per_cp[ind] == 0) tm->cp.free_ind[tm->cp.free_num++] = ind; } tm->active_nodes[lp] = NULL; tm->lp.free_ind[tm->lp.free_num++] = lp; tm->active_node_num--; } /*===========================================================================*/ int add_cut_to_list(tm_prob *tm, cut_data *cut) { #pragma omp critical (cut_pool) { REALLOC(tm->cuts, cut_data *, tm->allocated_cut_num, tm->cut_num + 1, (tm->cut_num / tm->stat.created + 5) * BB_BUNCH); cut->name = tm->cut_num; tm->cuts[tm->cut_num++] = cut; } return(cut->name); } /*===========================================================================*/ /*===========================================================================*\ * Installs a new upper bound and cleans up the candidate list \*===========================================================================*/ void install_new_ub(tm_prob *tm, double new_ub, int opt_thread_num, int bc_index, char branching, int feasible){ bc_node *node, *temp, **list; int rule, pos, prev_pos, last, i; tm->has_ub = TRUE; tm->ub = new_ub; #ifdef COMPILE_IN_LP tm->opt_thread_num = opt_thread_num; #endif if (tm->par.vbc_emulation == VBC_EMULATION_FILE){ FILE *f; #pragma omp critical(write_vbc_emulation_file) if (!(f = fopen(tm->par.vbc_emulation_file_name, "a"))){ printf("\nError opening vbc emulation file\n\n"); }else{ PRINT_TIME(tm, f); fprintf(f, "U %.2f\n", new_ub); fclose(f); } }else if (tm->par.vbc_emulation == VBC_EMULATION_LIVE){ printf("$U %.2f\n", new_ub); }else if (tm->par.vbc_emulation == VBC_EMULATION_FILE_NEW && (feasible == IP_FEASIBLE || feasible == IP_HEUR_FEASIBLE)){ FILE *f; // char reason[30]; char branch_dir = 'M'; if (!(f = fopen(tm->par.vbc_emulation_file_name, "a"))){ printf("\nError opening vbc emulation file\n\n"); }else if ((feasible == IP_FEASIBLE && branching) || (feasible == IP_HEUR_FEASIBLE)) { #pragma omp critical(write_vbc_emulation_file) PRINT_TIME2(tm, f); fprintf(f, "%s %f %i\n", "heuristic", new_ub, bc_index+1); }else if (feasible == IP_FEASIBLE && !branching){ node = tm->active_nodes[opt_thread_num]; if (node->bc_index>0) { if (node->parent->children[0]==node) { branch_dir = node->parent->bobj.sense[0]; /*branch_dir = 'L';*/ } else { branch_dir = node->parent->bobj.sense[1]; /*branch_dir = 'R';*/ } if (branch_dir == 'G') { branch_dir = 'R'; } } PRINT_TIME2(tm, f); if (node->bc_index){ fprintf (f, "%s %i %i %c %f\n", "integer", node->bc_index+1, node->parent->bc_index+1, branch_dir, new_ub); }else{ fprintf (f, "%s %i %i %c %f\n", "integer", 1, 0, 'M', new_ub); } } if (f){ fclose(f); } } /* Remove nodes that can now be fathomed from the list */ #pragma omp critical (tree_update) { rule = tm->par.node_selection_rule; list = tm->samephase_cand; char has_exchanged = FALSE; for (last = i = tm->samephase_candnum; i > 0; i--){ has_exchanged = FALSE; node = list[i]; if (tm->has_ub && node->lower_bound >= tm->ub-tm->par.granularity){ if (i != last){ list[i] = list[last]; for (prev_pos = i, pos = i/2; pos >= 1; prev_pos = pos, pos /= 2){ if (node_compar(rule, list[pos], list[prev_pos])){ temp = list[prev_pos]; list[prev_pos] = list[pos]; list[pos] = temp; has_exchanged = TRUE; }else{ break; } } } tm->samephase_cand[last] = NULL; last--; if (tm->par.verbosity > 0){ printf("+++++++++++++++++++++++++++++++++++++++++++++++++++\n"); printf("+ TM: Pruning NODE %i LEVEL %i after new incumbent.\n", node->bc_index, node->bc_level); printf("+++++++++++++++++++++++++++++++++++++++++++++++++++\n"); } if (tm->par.keep_description_of_pruned == DISCARD || tm->par.keep_description_of_pruned == KEEP_ON_DISK_VBC_TOOL){ if (tm->par.keep_description_of_pruned == KEEP_ON_DISK_VBC_TOOL) #pragma omp critical (write_pruned_node_file) write_pruned_nodes(tm, node); if (tm->par.vbc_emulation == VBC_EMULATION_FILE_NEW) { purge_pruned_nodes(tm, node, VBC_PRUNED_FATHOMED); } else { purge_pruned_nodes(tm, node, VBC_PRUNED); } } } if (has_exchanged) { /* * if exchanges have taken place, node[i] should be * checked again for pruning */ i++; } } tm->samephase_candnum = last; } } /*===========================================================================*/ /*===========================================================================*\ * This routine takes the description of the node after processing and * compares it to the description before processing. Then it updates * data structures appropriately. The other functions below are all * related to this one. \*===========================================================================*/ void merge_descriptions(node_desc *old_node, node_desc *new_node) { if (old_node->basis.basis_exists && new_node->basis.basis_exists){ merge_base_stat(&old_node->basis.basevars, &new_node->basis.basevars); merge_extra_array_and_stat(&old_node->uind, &old_node->basis.extravars, &new_node->uind, &new_node->basis.extravars); merge_base_stat(&old_node->basis.baserows, &new_node->basis.baserows); merge_extra_array_and_stat(&old_node->cutind,&old_node->basis.extrarows, &new_node->cutind,&new_node->basis.extrarows); }else{ old_node->basis = new_node->basis; merge_arrays(&old_node->uind, &new_node->uind); merge_arrays(&old_node->cutind, &new_node->cutind); #ifdef COMPILE_IN_LP memset((char *)&(new_node->basis), 0, sizeof(basis_desc)); #endif } old_node->nf_status = new_node->nf_status; if (new_node->nf_status == NF_CHECK_AFTER_LAST || new_node->nf_status == NF_CHECK_UNTIL_LAST){ merge_arrays(&old_node->not_fixed, &new_node->not_fixed); }else{ FREE(old_node->not_fixed.list); } } /*===========================================================================*/ void merge_base_stat(double_array_desc *dad, double_array_desc *moddad) { if (moddad->type == EXPLICIT_LIST){ FREE(dad->list); FREE(dad->stat); *dad = *moddad; #ifdef COMPILE_IN_LP moddad->stat = NULL; #endif return; } /* we've got a diff list against the old list */ if (moddad->size > 0) { /* if there is a change */ if (dad->type == EXPLICIT_LIST){ /* just overwrite the changes */ int i; int *oldstat = dad->stat; int newsize = moddad->size; int *newlist = moddad->list; int *newstat = moddad->stat; for (i = newsize - 1; i >= 0; i--) oldstat[newlist[i]] = newstat[i]; }else{ merge_double_array_descs(dad, moddad); } } } /*===========================================================================*/ void merge_extra_array_and_stat(array_desc *ad, double_array_desc *dad, array_desc *modad, double_array_desc *moddad) { if (moddad->type != WRT_PARENT){ /* If moddad is explicit then just use it */ FREE(dad->list); FREE(dad->stat); *dad = *moddad; #ifdef COMPILE_IN_LP moddad->stat = NULL; #endif }else{ /* So moddad is WRT. Then dad must be WRT, too!! */ /* First throw out from dad everything that's just been deleted */ int newdeled = modad->size - modad->added; int *newtodel = modad->list + modad->added; int i, j, k, nextdel; if (newdeled > 0 && dad->size > 0){ int dsize = dad->size; int *dlist = dad->list; int *dstat = dad->stat; k = j = 0; for (i = 0; i < newdeled; ){ nextdel = newtodel[i]; for (; j < dsize && dlist[j] < nextdel; ){ dlist[k] = dlist[j]; dstat[k++] = dstat[j++]; } if (j == dsize){ break; }else{ /* in this case dlist[j] >= nextdel */ i++; if (dlist[j] == nextdel) j++; } } while (j < dsize){ dlist[k] = dlist[j]; dstat[k++] = dstat[j++]; } dad->size = k; } /* Now merge the remaining dad and moddad together */ merge_double_array_descs(dad, moddad); } /* dad is fine now. Update ad */ merge_arrays(ad, modad); } /*===========================================================================*/ /*===========================================================================*\ * Merge the old and new changes together, in case of identical * userindices the newer value overrides the older \*===========================================================================*/ void merge_double_array_descs(double_array_desc *dad, double_array_desc *moddad) { if (moddad->size != 0){ if (dad->size == 0){ *dad = *moddad; #ifdef COMPILE_IN_LP moddad->stat = moddad->list = NULL; #endif }else{ int i, j, k; int oldsize = dad->size; int *oldlist = dad->list; int *oldstat = dad->stat; int newsize = moddad->size; int *newlist = moddad->list; int *newstat = moddad->stat; int *dlist = dad->list = (int *) malloc((oldsize+newsize) * ISIZE); int *dstat = dad->stat = (int *) malloc((oldsize+newsize) * ISIZE); for (k = 0, i = j = 0; i < oldsize && j < newsize; ){ if (oldlist[i] < newlist[j]){ dlist[k] = oldlist[i]; dstat[k++] = oldstat[i++]; }else{ if (oldlist[i] == newlist[j]) i++; dlist[k] = newlist[j]; dstat[k++] = newstat[j++]; } } while (i < oldsize){ dlist[k] = oldlist[i]; dstat[k++] = oldstat[i++]; } while (j < newsize){ dlist[k] = newlist[j]; dstat[k++] = newstat[j++]; } dad->size = k; FREE(oldlist); FREE(oldstat); FREE(moddad->list); FREE(moddad->stat); } } } /*===========================================================================*/ void merge_arrays(array_desc *array, array_desc *adesc) { if (adesc->type != WRT_PARENT){ /* Replace the old with the new one */ FREE(array->list); *array = *adesc; #ifdef COMPILE_IN_LP adesc->list = NULL; #endif return; } if (adesc->size == 0){ /* No change, leave the old description alone. */ return; } if (array->size == 0){ /* The old size is 0 (the new type is still WRT_PARENT). If the old type was WRT_PARENT then we can simply replace it with the new WRT_PARENT data. If it was EXPLICIT_LIST with nothing in it, then... contradiction! it would be shorter to explicitly list the new stuff then wrt an empty explicit list. */ *array = *adesc; #ifdef COMPILE_IN_LP adesc->list = NULL; #endif }else{ /* OK, array is either WRT or EXP. But!!! If array is EXP then array->added is set to array->size, so we can handle it exactly as if it were WRT! */ /* Now comes the ugly part... we had an old WRT list and got a new one wrt to the old (none of them is empty)... Create a correct one now. For extra vars/rows the basis status further complicates things. If we had the basis stati stored as EXP, then we don't have to worry about it, since we are going to receive an EXP. But if it was WRT then we must delete the from the basis stati list the extras to be deleted according to the new description! */ int i, j, k, *list; int newsize = adesc->size; int newadded = adesc->added; int *newtoadd = adesc->list; int newdeled = newsize - newadded; int *newtodel = newtoadd + newadded; int oldadded = array->added; int *oldtoadd = array->list; int olddeled = array->size - oldadded; int *oldtodel = oldtoadd + oldadded; /* cancel those both in oldtoadd and newdeled; also those both in newtoadd and olddeled. Then the unions of oldtoadd-newtodel and oldtodel-newtoadd will be the correct list. */ /* First count the number of collisions and mark the colliding ones */ k = 0; for (i = j = 0; i < oldadded && j < newdeled; ){ if (oldtoadd[i] < newtodel[j]) i++; else if (oldtoadd[i] > newtodel[j]) j++; else{ oldtoadd[i] = newtodel[j] = -1; i++; j++; k++; } } for (i = j = 0; i < newadded && j < olddeled; ){ if (newtoadd[i] < oldtodel[j]) i++; else if (newtoadd[i] > oldtodel[j]) j++; else{ newtoadd[i] = oldtodel[j] = -1; i++; j++; k++; } } array->size = array->size + newsize - 2 * k; if (array->size == 0){ /* Nothing is left, great! */ array->added = 0; FREE(adesc->list); FREE(array->list); }else{ array->list = list = (int *) malloc(array->size * ISIZE); for (i = j = k = 0; i < oldadded && j < newadded; ){ if (oldtoadd[i] == -1) i++; else if (newtoadd[j] == -1) j++; else if (oldtoadd[i] < newtoadd[j]) list[k++] = oldtoadd[i++]; else /* can't be == */ list[k++] = newtoadd[j++]; } for ( ; i < oldadded; i++) if (oldtoadd[i] != -1) list[k++] = oldtoadd[i]; for ( ; j < newadded; j++) if (newtoadd[j] != -1) list[k++] = newtoadd[j]; array->added = k; for (i = j = 0; i < olddeled && j < newdeled; ){ if (oldtodel[i] == -1) i++; else if (newtodel[j] == -1) j++; else if (oldtodel[i] < newtodel[j]) list[k++] = oldtodel[i++]; else /* can't be == */ list[k++] = newtodel[j++]; } for ( ; i < olddeled; i++) if (oldtodel[i] != -1) list[k++] = oldtodel[i]; for ( ; j < newdeled; j++) if (newtodel[j] != -1) list[k++] = newtodel[j]; FREE(adesc->list); /* adesc->list */ FREE(oldtoadd); /* the old array->list */ } } } /*===========================================================================*/ /*===========================================================================*\ * This routine modifies a list of integers, by deleting those listed in * todel and adding those listed in toadd. todel is a subset of iarray, * toadd has no common element with iarray. \*===========================================================================*/ void modify_list(array_desc *origad, array_desc *modad) { int j, k, l, nextdel; int added = modad->added; int *toadd = modad->list; int deled = modad->size - modad->added; int *todel = toadd + added; int size = origad->size; int *origlist = origad->list; if (deled){ /* l is the location where we copy to; and k is where we copy from */ l = k = 0; for (j = 0; j < deled; k++, j++){ nextdel = todel[j]; for (; origlist[k] != nextdel; origlist[l++] = origlist[k++]); } for (; k < size; origlist[l++] = origlist[k++]); size = l; } if (added){ /* add toadd to origlist */ for (l = size+added-1, k = added-1, j = size-1; k >= 0 && j >= 0; ){ if (origlist[j] > toadd[k]) origlist[l--] = origlist[j--]; else origlist[l--] = toadd[k--]; } if (k >= 0) memcpy(origlist, toadd, (k+1) * ISIZE); size += added; } origad->size = size; } /*===========================================================================*/ void modify_list_and_stat(array_desc *origad, int *origstat, array_desc *modad, double_array_desc *moddad) { int i, j, k, l, nextdel; int added = modad->added; int *toadd = modad->list; int deled = modad->size - modad->added; int *todel = toadd + added; int size = origad->size; int *origlist = origad->list; /* First modify origad, and at the same time delete the appropriate entries from origstat as well as insert phony ones where needed */ if (deled){ /* l is the location where we copy to; and k is where we copy from */ l = k = 0; for (j = 0; j < deled; k++, j++){ nextdel = todel[j]; for (; origlist[k] != nextdel; ){ origstat[l] = origstat[k]; origlist[l++] = origlist[k++]; } } for (; k < size; ){ origstat[l] = origstat[k]; origlist[l++] = origlist[k++]; } size = l; } if (added){ /* add toadd to origlist */ for (l = size+added-1, k = added-1, j = size-1; k >= 0 && j >= 0; ) if (origlist[j] > toadd[k]){ origstat[l] = origstat[j]; origlist[l--] = origlist[j--]; }else{ origstat[l] = INVALID_BASIS_STATUS; origlist[l--] = toadd[k--]; } if (k >= 0){ for ( ; k >= 0; ){ origstat[l] = INVALID_BASIS_STATUS; origlist[l--] = toadd[k--]; } } size += added; } origad->size = size; #ifdef DO_TM_BASIS_TESTS if (origad->size == 0 && moddad->size > 0){ printf("TM: Problem with storing the basis!!\n\n"); exit(990); } #endif /* Now adjust the basis stati */ if (origad->size > 0 && moddad->size > 0){ int *modlist = moddad->list; int *modstat = moddad->stat; for (i = moddad->size - 1, j = origad->size - 1; i >= 0 && j >= 0; j--){ if (origlist[j] == modlist[i]) origstat[j] = modstat[i--]; #ifdef DO_TM_BASIS_TESTS else if (origlist[j] < modlist[i]){ printf("TM: Problem with storing the basis!!\n\n"); exit(990); } #endif } #ifdef DO_TM_BASIS_TESTS if (i >= 0){ printf("TM: Problem with storing the basis!!\n\n"); exit(990); } #endif } #ifdef DO_TM_BASIS_TESTS for (j = origad->size - 1; j >= 0; j--){ if (origstat[j] == INVALID_BASIS_STATUS){ printf("TM: Problem with storing the basis!!\n\n"); exit(990); } } #endif } /*===========================================================================*/ /*===========================================================================*\ * Do some tasks before phase 2. Thes are: * - price out variables in the root if requested * - build up the samephase_cand binary tree * - inform everyone about it \*===========================================================================*/ int tasks_before_phase_two(tm_prob *tm) { #if !defined(COMPILE_IN_TM)||(defined(COMPILE_IN_TM)&&!defined(COMPILE_IN_LP)) int s_bufid; #endif #ifdef COMPILE_IN_LP int num_threads = 1; #else int r_bufid, msgtag, bytes, sender, not_fixed_size; #endif int i; bc_node *n; int termcode = 0; #ifdef COMPILE_IN_LP #ifdef _OPENMP num_threads = omp_get_num_threads(); #endif for (i = 0; i < num_threads; i++){ free_node_desc(&tm->lpp[i]->desc); tm->lpp[i]->phase = 1; } #else /* Notify the LPs about the start of the second phase and get back the timing data for the first phase */ s_bufid = init_send(DataInPlace); msend_msg(tm->lp.procs, tm->lp.procnum, LP__SECOND_PHASE_STARTS); #endif if (tm->par.price_in_root && tm->has_ub){ /* put together a message and send it out to an LP process. At this point tm->rootnode->{lp,cg,cp,sp} should still be set to wherever it was first processed */ #ifdef DO_TESTS if ((!tm->rootnode->lp) || (!tm->rootnode->cg && tm->par.use_cg) || (!tm->rootnode->cp && tm->cp.procnum > 0)){ printf("When trying to send root for repricing, the root doesn't\n"); printf(" have some process id correctly set!\n\n"); exit(-100); } #endif send_active_node(tm, tm->rootnode, COLGEN_REPRICING, 0); } /* trim the tree */ tm->stat.leaves_before_trimming = tm->nextphase_candnum; if (tm->par.trim_search_tree && tm->has_ub) tm->stat.tree_size -= trim_subtree(tm, tm->rootnode); /* while the LP is working, build up the samephase_cand binary tree */ REALLOC(tm->samephase_cand, bc_node *, tm->samephase_cand_size, tm->nextphase_candnum + 1, BB_BUNCH); for (i = 0; i < tm->nextphase_candnum; i++){ if ((n = tm->nextphase_cand[i])){ if (n->bc_index >= 0){ insert_new_node(tm, n); }else{ free_tree_node(n); } } } tm->stat.leaves_after_trimming = tm->samephase_candnum; if ((termcode = receive_lp_timing(tm)) < 0) return(SOMETHING_DIED); if (tm->par.price_in_root && tm->has_ub){ /* receive what the LP has to say, what is the new not_fixed list. * also, incorporate that list into the not_fixed field of everything */ #ifdef COMPILE_IN_LP switch(process_chain(tm->lpp[0])){ case FUNCTION_TERMINATED_NORMALLY: break; case ERROR__NO_BRANCHING_CANDIDATE: return(TM_ERROR__NO_BRANCHING_CANDIDATE); case ERROR__ILLEGAL_RETURN_CODE: return(TM_ERROR__ILLEGAL_RETURN_CODE); case ERROR__NUMERICAL_INSTABILITY: return(TM_ERROR__NUMERICAL_INSTABILITY); case ERROR__USER: return(TM_ERROR__USER); } #else char go_on; int nsize, nf_status; do{ r_bufid = receive_msg(tm->rootnode->lp, ANYTHING); bufinfo(r_bufid, &bytes, &msgtag, &sender); switch (msgtag){ case LP__NODE_DESCRIPTION: n = (bc_node *) calloc(1, sizeof(bc_node)); receive_node_desc(tm, n); tm->stat.root_lb = n->lower_bound; if (n->node_status == NODE_STATUS__PRUNED){ /* Field day! Proved optimality! */ free_subtree(tm->rootnode); tm->rootnode = n; tm->samephase_candnum = tm->nextphase_candnum = 0; return (FUNCTION_TERMINATED_NORMALLY); } /* Otherwise in 'n' we have the new description of the root node. We don't care about the cuts, just the not fixed variables. We got to pay attention to changes in uind and not_fixed. We won't change the uind in root but put every change into not_fixed. The new not_fixed list will comprise of the vars added to uind and whatever is in the new not_fixed. */ if (n->desc.uind.size > 0){ array_desc *uind = &n->desc.uind; array_desc *ruind = &tm->rootnode->desc.uind; int usize = uind->size; int rusize = ruind->size; int *ulist = uind->list; int *rulist = ruind->list; int j, k; /* Kick out from uind those in root's uind */ for (i = 0, j = 0, k = 0; i < usize && j < rusize; ){ if (ulist[i] < rulist[j]){ /* a new element in uind */ ulist[k++] = ulist[i++]; }else if (ulist[i] < rulist[j]){ /* something got kicked out of ruind */ j++; }else{ /* ulist[i] == rulist[j] */ /* It just stayed there peacefully */ i++; j++; } } if (i < usize){ /* The rest are new */ for ( ; i < usize; i++, k++) ulist[k] = ulist[i]; } if ((usize = k) > 0){ if ((nsize = n->desc.not_fixed.size) == 0){ /* All we got is from uind */ n->desc.not_fixed.size = usize; n->desc.not_fixed.list = ulist; uind->list = NULL; }else{ /* Now merge whatever is left in ulist with not_fixed. Note that the two lists are disjoint. */ int *not_fixed = (int *) malloc((usize + nsize) * ISIZE); int *nlist = n->desc.not_fixed.list; for (not_fixed_size=i=j=k=0; i < usize && j < nsize; not_fixed_size++){ if (ulist[i] < nlist[j]){ not_fixed[k++] = ulist[i++]; }else if (ulist[i] > nlist[j]){ not_fixed[k++] = nlist[j++]; }else{ not_fixed[k++] = nlist[j++]; i++; } } if (i < usize) memcpy(not_fixed+k, ulist+i, (usize-i)*ISIZE); if (j < nsize) memcpy(not_fixed+k, nlist+j, (nsize-j)*ISIZE); FREE(nlist); n->desc.not_fixed.size = not_fixed_size; n->desc.not_fixed.list = not_fixed; } } } /* OK, now every new thingy is in n->desc.not_fixed */ nsize = n->desc.not_fixed.size; if (nsize == 0){ /* Field day! Proved optimality! Caveats: This proves optimality, but the current tree may not contain this proof, since the cuts used in pricing out might be different from those originally in the root. For now just accept this sad fact and report optimality. Later, when the tree could be written out on disk, take care of writing out BOTH root descriptions to prove optimality. FIXME */ if (tm->par.keep_description_of_pruned){ /* We got to write it out here. */ } free_tree_node(n); tm->samephase_candnum = tm->nextphase_candnum = 0; return(FUNCTION_TERMINATED_NORMALLY); }else{ tm->rootnode->desc.not_fixed.list = n->desc.not_fixed.list; n->desc.not_fixed.list = NULL; if (nsize > tm->par.not_fixed_storage_size){ tm->rootnode->desc.not_fixed.size = tm->par.not_fixed_storage_size; nf_status = NF_CHECK_AFTER_LAST; }else{ tm->rootnode->desc.not_fixed.size = nsize; nf_status = NF_CHECK_UNTIL_LAST; } } propagate_nf_status(tm->rootnode, nf_status); tm->stat.nf_status = nf_status; tm->stat.vars_not_priced = tm->rootnode->desc.not_fixed.size; free_tree_node(n); go_on = FALSE; break; case UPPER_BOUND: process_ub_message(tm); go_on = TRUE; break; case LP__CUT_NAMES_REQUESTED: unpack_cut_set(tm, sender, 0, NULL); go_on = TRUE; break; default: /* We shouldn't get anything else */ printf("Unexpected message at repricing! (%i)\n\n", msgtag); return(ERROR__COMM_ERROR); } }while (go_on); #endif } #ifdef COMPILE_IN_TM if (tm->samephase_candnum > 0){ printf( "\n"); printf( "**********************************************\n"); printf( "* Branch and Cut First Phase Finished!!!! *\n"); printf( "* Now displaying stats and best solution... *\n"); printf( "**********************************************\n\n"); print_statistics(&(tm->comp_times), &(tm->stat), &(tm->lp_stat), tm->ub, tm->lb, 0, tm->start_time, wall_clock(NULL), tm->obj_offset, tm->obj_sense, tm->has_ub,NULL); } #else /* Report to the master all kind of statistics */ s_bufid = init_send(DataInPlace); send_char_array((char *)&tm->comp_times, sizeof(node_times)); send_char_array((char *)&tm->lp_stat, sizeof(lp_stat_desc)); send_dbl_array(&tm->lb, 1); send_char_array((char *)&tm->stat, sizeof(tm_stat)); send_msg(tm->master, TM_FIRST_PHASE_FINISHED); #endif tm->nextphase_candnum = 0; return(FUNCTION_TERMINATED_NORMALLY); } /*===========================================================================*/ /*===========================================================================*\ * For now we'll trim the tree only between phases when nothing is processed. * Reason: It's kinda ugly to cut off a subtree when several of its nodes * might be processed. Nevertheless, this should be done sooner or later. * * FIXME! * \*===========================================================================*/ int trim_subtree(tm_prob *tm, bc_node *n) { int i, deleted = 0, not_pruned = 0; /* Theer isn't anything to do if this is a leaf. */ if (n->bobj.child_num == 0) return(0); /* There isn't anything to do if all children are pruned, and we are better off to go down if only one is not pruned. */ for (i = n->bobj.child_num - 1; i >= 0; i--) if (n->children[i]->node_status != NODE_STATUS__PRUNED) if (++not_pruned > 1) break; if (not_pruned == 0) return(0); if (not_pruned == 1){ for (i = n->bobj.child_num - 1; i >= 0; i--) if (n->children[i]->node_status != NODE_STATUS__PRUNED){ deleted = trim_subtree(tm, n->children[i]); break; } return(deleted); } /* So there are at least two not pruned. */ for (i = n->bobj.child_num - 1; i >= 0; i--) if (n->children[i]->lower_bound + tm->par.granularity < tm->ub) break; /* if all children have high objval */ if (i < 0){ /* put back this node into the nodes_per_... stuff */ if (tm->par.max_cp_num > 0 && n->cp) #ifdef COMPILE_IN_CP tm->nodes_per_cp[n->cp]++; #else tm->nodes_per_cp[find_process_index(&tm->cp, n->cp)]++; #endif /* also put the node on the nextphase list */ REALLOC(tm->nextphase_cand, bc_node *, tm->nextphase_cand_size, tm->nextphase_candnum+1, BB_BUNCH); tm->nextphase_cand[tm->nextphase_candnum++] = n; /* get rid of the children */ for (i = n->bobj.child_num - 1; i >= 0; i--) deleted += mark_subtree(tm, n->children[i]); /* free the children description */ FREE(n->children); n->bobj.child_num = 0; #ifndef MAX_CHILDREN_NUM FREE(n->bobj.sense); FREE(n->bobj.rhs); FREE(n->bobj.range); FREE(n->bobj.branch); #endif FREE(n->bobj.solutions); //added by asm4 }else{ /* try to trim every child */ for (i = n->bobj.child_num - 1; i >= 0; i--) deleted += trim_subtree(tm, n->children[i]); } return(deleted); } /*===========================================================================*/ int mark_subtree(tm_prob *tm, bc_node *n) { int i, deleted = 0; /* mark the node trimmed */ if (n->bobj.child_num == 0){ /* if this was a leaf and it is not pruned, delete it from the nodes_per_... stuff */ if (n->node_status != NODE_STATUS__PRUNED){ if (tm->par.max_cp_num > 0 && n->cp){ #ifdef COMPILE_IN_CP i = n->cp; #else i = find_process_index(&tm->cp, n->cp); #endif tm->nodes_per_cp[i]--; if (tm->nodes_per_cp[i] + tm->active_nodes_per_cp[i] == 0) tm->cp.free_ind[tm->cp.free_num++] = i; } n->bc_index = -1; }else{ /* if it was pruned already the free it now */ free_tree_node(n); } }else{ /* if non-leaf then process the children recursively and then free the node */ for (i = n->bobj.child_num - 1; i >= 0; i--) deleted += mark_subtree(tm, n->children[i]); free_tree_node(n); } return(++deleted); } /*===========================================================================*/ void propagate_nf_status(bc_node *n, int nf_status) { int i; for (i = n->bobj.child_num - 1; i >= 0; i--) propagate_nf_status(n->children[i], nf_status); n->desc.nf_status = nf_status; } /*===========================================================================*/ /*===========================================================================*\ * The functions below are for logging. They write out all necessary * data to a file so that a warmstart can be made. \*===========================================================================*/ int write_node(bc_node *node, char *file, FILE* f, char append) { int i; char close = FALSE; if (!f){ if (!(f = fopen(file, append ? "a" : "w"))){ printf("\nError opening node file\n\n"); return(0); } close = TRUE; } if (append) fprintf(f, "\n"); fprintf(f, "NODE INDEX: %i\n", node->bc_index); fprintf(f, "NODE LEVEL: %i\n", node->bc_level); fprintf(f, "LOWER BOUND: %f\n", node->lower_bound); fprintf(f, "NODE STATUS: %i\n", (int)node->node_status); #ifdef TRACE_PATH fprintf(f, "OPTIMAL PATH: %i\n", (int)node->optimal_path); #endif if (node->parent) fprintf(f, "PARENT INDEX: %i\n", node->parent->bc_index); else fprintf(f, "PARENT INDEX: -1\n"); fprintf(f, "CHILDREN: %i %i %i\n", (int)node->bobj.type, node->bobj.name, node->bobj.child_num); for (i = 0; i < node->bobj.child_num; i++) fprintf(f, "%i %c %f %f %i\n", node->children[i]->bc_index, node->bobj.sense[i], node->bobj.rhs[i], node->bobj.range[i], node->bobj.branch[i]); fprintf(f, "NODE DESCRIPTION: %i\n", node->desc.nf_status); fprintf(f, "USER INDICES: %i %i %i\n", (int)node->desc.uind.type, node->desc.uind.size, node->desc.uind.added); for (i = 0; i < node->desc.uind.size; i++) fprintf(f, "%i\n", node->desc.uind.list[i]); fprintf(f, "NOT FIXED: %i %i %i\n", (int)node->desc.not_fixed.type, node->desc.not_fixed.size, node->desc.not_fixed.added); for (i = 0; i < node->desc.not_fixed.size; i++) fprintf(f, "%i\n", node->desc.not_fixed.list[i]); fprintf(f, "CUT INDICES: %i %i %i\n", (int)node->desc.cutind.type, node->desc.cutind.size, node->desc.cutind.added); for (i = 0; i < node->desc.cutind.size; i++) fprintf(f, "%i\n", node->desc.cutind.list[i]); fprintf(f, "BASIS: %i\n", (int)node->desc.basis.basis_exists); fprintf(f, "BASE VARIABLES: %i %i\n", (int)node->desc.basis.basevars.type, node->desc.basis.basevars.size); if (node->desc.basis.basevars.type == WRT_PARENT) for (i = 0; i < node->desc.basis.basevars.size; i++) fprintf(f, "%i %i\n", node->desc.basis.basevars.list[i], node->desc.basis.basevars.stat[i]); else for (i = 0; i < node->desc.basis.basevars.size; i++) fprintf(f, "%i\n", node->desc.basis.basevars.stat[i]); fprintf(f, "EXTRA VARIABLES: %i %i\n", (int)node->desc.basis.extravars.type, node->desc.basis.extravars.size); if (node->desc.basis.extravars.type == WRT_PARENT) for (i = 0; i < node->desc.basis.extravars.size; i++) fprintf(f, "%i %i\n", node->desc.basis.extravars.list[i], node->desc.basis.extravars.stat[i]); else for (i = 0; i < node->desc.basis.extravars.size; i++) fprintf(f, "%i\n", node->desc.basis.extravars.stat[i]); fprintf(f, "BASE ROWS: %i %i\n", (int)node->desc.basis.baserows.type, node->desc.basis.baserows.size); if (node->desc.basis.baserows.type == WRT_PARENT) for (i = 0; i < node->desc.basis.baserows.size; i++) fprintf(f, "%i %i\n", node->desc.basis.baserows.list[i], node->desc.basis.baserows.stat[i]); else for (i = 0; i < node->desc.basis.baserows.size; i++) fprintf(f, "%i\n", node->desc.basis.baserows.stat[i]); fprintf(f, "EXTRA ROWS: %i %i\n", (int)node->desc.basis.extrarows.type, node->desc.basis.extrarows.size); if (node->desc.basis.extrarows.type == WRT_PARENT) for (i = 0; i < node->desc.basis.extrarows.size; i++) fprintf(f, "%i %i\n", node->desc.basis.extrarows.list[i], node->desc.basis.extrarows.stat[i]); else for (i = 0; i < node->desc.basis.extrarows.size; i++) fprintf(f, "%i\n", node->desc.basis.extrarows.stat[i]); if (close) fclose(f); return(1); } /*===========================================================================*/ int read_node(tm_prob *tm, bc_node *node, FILE *f, int **children) { int i, parent = 0, tmp = 0; char str1[10], str2[10]; if (f){ fscanf(f, "%s %s %i", str1, str2, &node->bc_index); fscanf(f, "%s %s %i", str1, str2, &node->bc_level); fscanf(f, "%s %s %lf", str1, str2, &node->lower_bound); fscanf(f, "%s %s %i", str1, str2, &tmp); node->node_status = (char)tmp; #ifdef TRACE_PATH fscanf(f, "%s %s %i\n", str1, str2, &tmp); node->optimal_path = (char)tmp; #endif fscanf(f, "%s %s %i", str1, str2, &parent); fscanf(f, "%s %i %i %i", str1, &tmp, &node->bobj.name, &node->bobj.child_num); node->bobj.type = (char)tmp; if (node->bobj.child_num){ #ifndef MAX_CHILDREN_NUM node->bobj.sense = malloc(node->bobj.child_num*sizeof(char)); node->bobj.rhs = (double *) malloc(node->bobj.child_num*DSIZE); node->bobj.range = (double *) malloc(node->bobj.child_num*DSIZE); node->bobj.branch = (int *) malloc(node->bobj.child_num*ISIZE); #endif *children = (int *) malloc(node->bobj.child_num*ISIZE); for (i = 0; i < node->bobj.child_num; i++) fscanf(f, "%i %c %lf %lf %i", *children+i, node->bobj.sense+i, node->bobj.rhs+i, node->bobj.range+i, node->bobj.branch+i); } fscanf(f, "%s %s %i", str1, str2, &node->desc.nf_status); fscanf(f, "%s %s %i %i %i", str1, str2, &tmp, &node->desc.uind.size, &node->desc.uind.added); node->desc.uind.type = (char)tmp; if (node->desc.uind.size){ node->desc.uind.list = (int *) malloc(node->desc.uind.size*ISIZE); for (i = 0; i < node->desc.uind.size; i++) fscanf(f, "%i", node->desc.uind.list+i); } fscanf(f, "%s %s %i %i %i", str1, str2, &tmp, &node->desc.not_fixed.size, &node->desc.not_fixed.added); node->desc.not_fixed.type = (char)tmp; if (node->desc.not_fixed.size){ node->desc.not_fixed.list = (int *) malloc(node->desc.not_fixed.size*ISIZE); for (i = 0; i < node->desc.not_fixed.size; i++) fscanf(f, "%i", node->desc.not_fixed.list+i); } fscanf(f, "%s %s %i %i %i", str1, str2, &tmp, &node->desc.cutind.size, &node->desc.cutind.added); node->desc.cutind.type = (char)tmp; if (node->desc.cutind.size){ node->desc.cutind.list = (int *) malloc(node->desc.cutind.size*ISIZE); for (i = 0; i < node->desc.cutind.size; i++) fscanf(f, "%i", node->desc.cutind.list+i); } fscanf(f, "%s %i", str1, &tmp); node->desc.basis.basis_exists = (char)tmp; fscanf(f, "%s %s %i %i", str1, str2, &tmp, &node->desc.basis.basevars.size); node->desc.basis.basevars.type = (char)tmp; if (node->desc.basis.basevars.size){ node->desc.basis.basevars.stat = (int *) malloc(node->desc.basis.basevars.size*ISIZE); if (node->desc.basis.basevars.type == WRT_PARENT){ node->desc.basis.basevars.list = (int *) malloc(node->desc.basis.basevars.size*ISIZE); for (i = 0; i < node->desc.basis.basevars.size; i++) fscanf(f, "%i %i", node->desc.basis.basevars.list+i, node->desc.basis.basevars.stat+i); }else{ for (i = 0; i < node->desc.basis.basevars.size; i++) fscanf(f, "%i", node->desc.basis.basevars.stat+i); } } fscanf(f, "%s %s %i %i", str1, str2, &tmp, &node->desc.basis.extravars.size); node->desc.basis.extravars.type = (char)tmp; if (node->desc.basis.extravars.size){ node->desc.basis.extravars.stat = (int *) malloc(node->desc.basis.extravars.size*ISIZE); if (node->desc.basis.extravars.type == WRT_PARENT){ node->desc.basis.extravars.list = (int *) malloc(node->desc.basis.extravars.size*ISIZE); for (i = 0; i < node->desc.basis.extravars.size; i++) fscanf(f, "%i %i", node->desc.basis.extravars.list+i, node->desc.basis.extravars.stat+i); }else{ for (i = 0; i < node->desc.basis.extravars.size; i++) fscanf(f, "%i", node->desc.basis.extravars.stat+i); } } fscanf(f, "%s %s %i %i", str1, str2, &tmp, &node->desc.basis.baserows.size); node->desc.basis.baserows.type = (char)tmp; if (node->desc.basis.baserows.size){ node->desc.basis.baserows.stat = (int *) malloc(node->desc.basis.baserows.size*ISIZE); if (node->desc.basis.baserows.type == WRT_PARENT){ node->desc.basis.baserows.list = (int *) malloc(node->desc.basis.baserows.size*ISIZE); for (i = 0; i < node->desc.basis.baserows.size; i++) fscanf(f, "%i %i", node->desc.basis.baserows.list+i, node->desc.basis.baserows.stat+i); }else{ for (i = 0; i < node->desc.basis.baserows.size; i++) fscanf(f, "%i", node->desc.basis.baserows.stat+i); } } fscanf(f, "%s %s %i %i", str1, str2, &tmp, &node->desc.basis.extrarows.size); node->desc.basis.extrarows.type = (char)tmp; if (node->desc.basis.extrarows.size){ node->desc.basis.extrarows.stat = (int *) malloc(node->desc.basis.extrarows.size*ISIZE); if (node->desc.basis.extrarows.type == WRT_PARENT){ node->desc.basis.extrarows.list = (int *) malloc(node->desc.basis.extrarows.size*ISIZE); for (i = 0; i < node->desc.basis.extrarows.size; i++) fscanf(f, "%i %i", node->desc.basis.extrarows.list+i, node->desc.basis.extrarows.stat+i); }else{ for (i = 0; i < node->desc.basis.extrarows.size; i++) fscanf(f, "%i", node->desc.basis.extrarows.stat+i); } } } switch (node->node_status){ case NODE_STATUS__HELD: REALLOC(tm->nextphase_cand, bc_node *, tm->nextphase_cand_size, tm->nextphase_candnum+1, BB_BUNCH); tm->nextphase_cand[tm->nextphase_candnum++] = node; /* update the nodes_per_... stuff */ /* the active_nodes_per_... will be updated when the LP__IS_FREE message comes */ if (node->cp) #ifdef COMPILE_IN_CP tm->nodes_per_cp[node->cp]++; #else tm->nodes_per_cp[find_process_index(&tm->cp, node->cp)]++; #endif break; case NODE_STATUS__ROOT: tm->rootnode = node; break; case NODE_STATUS__WARM_STARTED: case NODE_STATUS__CANDIDATE: #pragma omp critical (tree_update) insert_new_node(tm, node); break; } return(parent); } /*===========================================================================*/ int write_subtree(bc_node *root, char *file, FILE *f, char append, int logging) { int i; char close = FALSE; if (!f){ if (!(f = fopen(file, append ? "a" : "w"))){ printf("\nError opening subtree file\n\n"); return(0); } close = TRUE; } if (logging == VBC_TOOL){ if (root->parent) fprintf(f, "%i %i\n", root->parent->bc_index + 1, root->bc_index + 1); }else{ write_node(root, file, f, append); } for (i = 0; i < root->bobj.child_num; i++) write_subtree(root->children[i], file, f, TRUE, logging); if (close) fclose(f); return(1); } /*===========================================================================*/ int read_subtree(tm_prob *tm, bc_node *root, FILE *f) { int parent, i; int *children; parent = read_node(tm, root, f, &children); if (f && root->bobj.child_num){ root->children = (bc_node **) malloc(root->bobj.child_num*sizeof(bc_node *)); for (i = 0; i < root->bobj.child_num; i++){ root->children[i] = (bc_node *) calloc(1, sizeof(bc_node)); root->children[i]->parent = root; } } for (i = 0; i < root->bobj.child_num; i++){ read_subtree(tm, root->children[i], f); } return(parent); } /*===========================================================================*/ int write_tm_cut_list(tm_prob *tm, char *file, char append) { FILE *f; int i, j; if (!(f = fopen(file, append ? "a" : "w"))){ printf("\nError opening cut file\n\n"); return(0); } fprintf(f, "CUTNUM: %i %i\n", tm->cut_num, tm->allocated_cut_num); for (i = 0; i < tm->cut_num; i++){ fprintf(f, "%i %i %i %c %i %f %f\n", tm->cuts[i]->name, tm->cuts[i]->size, (int)tm->cuts[i]->type, tm->cuts[i]->sense, (int)tm->cuts[i]->branch, tm->cuts[i]->rhs, tm->cuts[i]->range); for (j = 0; j < tm->cuts[i]->size; j++) fprintf(f, "%i ", (int)tm->cuts[i]->coef[j]); fprintf(f, "\n"); } fclose(f); return(1); } /*===========================================================================*/ int read_tm_cut_list(tm_prob *tm, char *file) { FILE *f; int i, j, tmp1 = 0, tmp2 = 0; char str[20]; if (!(f = fopen(file, "r"))){ printf("\nError opening cut file\n\n"); return(0); } fscanf(f, "%s %i %i", str, &tm->cut_num, &tm->allocated_cut_num); tm->cuts = (cut_data **) malloc(tm->allocated_cut_num*sizeof(cut_data *)); for (i = 0; i < tm->cut_num; i++){ tm->cuts[i] = (cut_data *) malloc(sizeof(cut_data)); fscanf(f, "%i %i %i %c %i %lf %lf", &tm->cuts[i]->name, &tm->cuts[i]->size, &tmp1, &tm->cuts[i]->sense, &tmp2, &tm->cuts[i]->rhs, &tm->cuts[i]->range); tm->cuts[i]->type = (char)tmp1; tm->cuts[i]->branch = (char)tmp2; tm->cuts[i]->coef = (char *) malloc(tm->cuts[i]->size*sizeof(char)); for (j = 0; j < tm->cuts[i]->size; j++){ fscanf(f, "%i ", &tmp1); tm->cuts[i]->coef[j] = (char)tmp1; } } fclose(f); return(1); } /*===========================================================================*/ int write_tm_info(tm_prob *tm, char *file, FILE* f, char append) { char close = FALSE; if (!f){ if (!(f = fopen(file, append ? "a" : "w"))){ printf("\nError opening TM info file\n\n"); return(0); } close = TRUE; } if (tm->par.logging == VBC_TOOL){ fprintf(f, "#TYPE: COMPLETE TREE\n"); fprintf(f, "#TIME: NOT\n"); fprintf(f, "#BOUNDS: NONE\n"); fprintf(f, "#INFORMATION: EXCEPTION\n"); fprintf(f, "#NODE_NUMBER: NONE\n"); if (close) fclose(f); return(1); } fprintf(f, "UPPER BOUND: "); if (tm->has_ub) fprintf(f, " %f\n", tm->ub); else fprintf(f, "\n"); fprintf(f, "LOWER BOUND: %f\n", tm->lb); fprintf(f, "PHASE: %i\n", tm->phase); fprintf(f, "ROOT LB: %f\n", tm->stat.root_lb); fprintf(f, "MAX DEPTH: %i\n", tm->stat.max_depth); fprintf(f, "CHAINS: %i\n", tm->stat.chains); fprintf(f, "DIVING HALTS: %i\n", tm->stat.diving_halts); fprintf(f, "TREE SIZE: %i\n", tm->stat.tree_size); fprintf(f, "NODES CREATED: %i\n", tm->stat.created); fprintf(f, "NODES ANALYZED: %i\n", tm->stat.analyzed); fprintf(f, "LEAVES BEFORE: %i\n", tm->stat.leaves_before_trimming); fprintf(f, "LEAVES AFTER: %i\n", tm->stat.leaves_after_trimming); fprintf(f, "NF STATUS: %i\n", (int)tm->stat.nf_status); fprintf(f, "TIMING:\n"); fprintf(f, " COMM: %f\n", tm->comp_times.communication); fprintf(f, " LP: %f\n", tm->comp_times.lp); fprintf(f, " SEPARATION: %f\n", tm->comp_times.separation); fprintf(f, " FIXING: %f\n", tm->comp_times.fixing); fprintf(f, " PRICING: %f\n", tm->comp_times.pricing); fprintf(f, " BRANCHING: %f\n", tm->comp_times.strong_branching); fprintf(f, " CUT POOL: %f\n", tm->comp_times.cut_pool); fprintf(f, " REAL TIME: %f\n", wall_clock(NULL) - tm->start_time); if (close) fclose(f); return(1); } /*===========================================================================*/ int read_tm_info(tm_prob *tm, FILE *f) { char str1[20], str2[20]; int tmp = 0; double previous_elapsed_time = 0; if (!f) return(0); fscanf(f, "%s %s", str1, str2); if (fscanf(f, "%lf", &tm->ub) != 0) tm->has_ub = TRUE; fscanf(f, "%s %s %lf", str1, str2, &tm->lb); fscanf(f, "%s %i", str1, &tm->phase); fscanf(f, "%s %s %lf", str1, str2, &tm->stat.root_lb); fscanf(f, "%s %s %i", str1, str2, &tm->stat.max_depth); fscanf(f, "%s %i", str1, &tm->stat.chains); fscanf(f, "%s %s %i", str1, str2, &tm->stat.diving_halts); fscanf(f, "%s %s %i", str1, str2, &tm->stat.tree_size); fscanf(f, "%s %s %i", str1, str2, &tm->stat.created); fscanf(f, "%s %s %i", str1, str2, &tm->stat.analyzed); fscanf(f, "%s %s %i", str1, str2, &tm->stat.leaves_before_trimming); fscanf(f, "%s %s %i", str1, str2, &tm->stat.leaves_after_trimming); fscanf(f, "%s %s %i", str1, str2, &tmp); tm->stat.nf_status = (char)tmp; fscanf(f, "%s", str1); fscanf(f, "%s %lf", str1, &tm->comp_times.communication); fscanf(f, "%s %lf", str1, &tm->comp_times.lp); fscanf(f, "%s %lf", str1, &tm->comp_times.separation); fscanf(f, "%s %lf", str1, &tm->comp_times.fixing); fscanf(f, "%s %lf", str1, &tm->comp_times.pricing); fscanf(f, "%s %lf", str1, &tm->comp_times.strong_branching); fscanf(f, "%s %s %lf", str1, str2, &tm->comp_times.cut_pool); fscanf(f, "%s %s %lf\n", str1, str2, &previous_elapsed_time); tm->start_time -= previous_elapsed_time; return(1); } /*===========================================================================*/ int write_base(base_desc *base, char *file, FILE *f, char append) { int i; char close = FALSE; if (!f){ if (!(f = fopen(file, append ? "a" : "w"))){ printf("\nError opening base file\n\n"); return(0); } close = TRUE; } fprintf(f, "BASE DESCRIPTION: %i %i\n", base->varnum, base->cutnum); for (i = 0; i < base->varnum; i++) fprintf(f, "%i\n", base->userind[i]); if (close) fclose(f); return(1); } /*===========================================================================*/ int read_base(base_desc *base, FILE *f) { char str1[20], str2[20]; int i; fscanf(f, "%s %s %i %i", str1, str2, &base->varnum, &base->cutnum); base->userind = (int *) malloc(base->varnum*ISIZE); for (i = 0; i < base->varnum; i++) fscanf(f, "%i", base->userind+i); return(1); } /*===========================================================================*/ /*===========================================================================*\ * Cleanup. Free the datastructure. \*===========================================================================*/ void free_tm(tm_prob *tm) { int i; cut_data **cuts = tm->cuts; #ifdef _OPENMP int num_threads = tm->par.max_active_nodes; #else int num_threads = 1; #endif #if defined(COMPILE_IN_TM) && defined(COMPILE_IN_LP) for (i = 0; i < num_threads; i++) free_lp(tm->lpp[i]); FREE(tm->lpp); #ifdef COMPILE_IN_CG FREE(tm->cgp); #endif #endif if (tm->par.lp_machs){ FREE(tm->par.lp_machs[0]); FREE(tm->par.lp_machs); } if (tm->par.cg_machs){ FREE(tm->par.cg_machs[0]); FREE(tm->par.cg_machs); } if (tm->par.cp_machs){ FREE(tm->par.cp_machs[0]); FREE(tm->par.cp_machs); } FREE(tm->lp.procs); FREE(tm->lp.free_ind); FREE(tm->cg.procs); FREE(tm->cg.free_ind); FREE(tm->cp.procs); FREE(tm->cp.free_ind); FREE(tm->nodes_per_cp); FREE(tm->active_nodes_per_cp); FREE(tm->active_nodes); FREE(tm->samephase_cand); FREE(tm->nextphase_cand); #ifndef COMPILE_IN_TM /* Go over the tree and free the nodes */ free_subtree(tm->rootnode); #endif /* Go over the cuts stored and free them all */ #pragma omp critical (cut_pool) if (cuts){ for (i = tm->cut_num - 1; i >= 0; i--) if (cuts[i]){ FREE(cuts[i]->coef); FREE(cuts[i]); } FREE(tm->cuts); } #pragma omp critical (tmp_memory) { FREE(tm->tmp.i); FREE(tm->tmp.c); FREE(tm->tmp.d); } /*get rid of the added pointers for sens.analysis*/ for (i = 0; i < num_threads; i++){ if(tm->rpath[i]) if(tm->rpath[i][0]) tm->rpath[i][0] = NULL; FREE(tm->bpath[i]); FREE(tm->rpath[i]); } FREE(tm->rpath); FREE(tm->rpath_size); FREE(tm->bpath); FREE(tm->bpath_size); if (tm->reduced_costs) { for (i=0; i<tm->reduced_costs->num_rcs; i++) { FREE(tm->reduced_costs->indices[i]); FREE(tm->reduced_costs->values[i]); FREE(tm->reduced_costs->lb[i]); FREE(tm->reduced_costs->ub[i]); } FREE(tm->reduced_costs->indices); FREE(tm->reduced_costs->values); FREE(tm->reduced_costs->lb); FREE(tm->reduced_costs->ub); FREE(tm->reduced_costs->cnt); FREE(tm->reduced_costs->obj); FREE(tm->reduced_costs); } if (tm->pcost_down) { FREE(tm->pcost_down); FREE(tm->pcost_up); FREE(tm->br_rel_down); FREE(tm->br_rel_up); FREE(tm->br_rel_cand_list); FREE(tm->br_rel_down_min_level); FREE(tm->br_rel_up_min_level); } FREE(tm); } /*===========================================================================*/ void free_subtree(bc_node *n) { int i; if (n == NULL) return; for (i = n->bobj.child_num - 1; i >= 0; i--) free_subtree(n->children[i]); free_tree_node(n); } /*===========================================================================*/ void free_tree_node(bc_node *n) { FREE(n->sol); FREE(n->sol_ind); #ifdef SENSITIVITY_ANALYSIS FREE(n->duals); #endif FREE(n->children); #ifndef MAX_CHILDREN_NUM FREE(n->bobj.sense); FREE(n->bobj.rhs); FREE(n->bobj.range); FREE(n->bobj.branch); #endif FREE(n->bobj.solutions); //added by asm4 FREE(n->desc.uind.list); free_basis(&n->desc.basis); FREE(n->desc.not_fixed.list); FREE(n->desc.cutind.list); FREE(n->desc.desc); if (n->desc.bnd_change) { FREE(n->desc.bnd_change->index); FREE(n->desc.bnd_change->lbub); FREE(n->desc.bnd_change->value); FREE(n->desc.bnd_change); } FREE(n); } /*===========================================================================*/ void free_basis(basis_desc *basis) { FREE(basis->basevars.list); FREE(basis->basevars.stat); FREE(basis->extravars.list); FREE(basis->extravars.stat); FREE(basis->baserows.list); FREE(basis->baserows.stat); FREE(basis->extrarows.list); FREE(basis->extrarows.stat); } /*===========================================================================*/ /*===========================================================================*\ * This function shuts down the treemanager \*===========================================================================*/ int tm_close(tm_prob *tm, int termcode) { #ifndef COMPILE_IN_TM int s_bufid; #endif #ifdef COMPILE_IN_LP lp_prob **lp = tm->lpp; #endif #ifndef COMPILE_IN_CP int r_bufid = 0, new_cuts; struct timeval timeout = {5, 0}; double new_time; #endif int i; #if defined(DO_TESTS) && 0 if (tm->cp.free_num != tm->cp.procnum) printf(" Something is fishy! tm->cp.freenum != tm->cp.procnum\n"); #endif if (tm->par.vbc_emulation == VBC_EMULATION_LIVE){ printf("$#END_OF_OUTPUT"); } /*------------------------------------------------------------------------*\ * Kill the processes. Some of them will send back statistics. \*------------------------------------------------------------------------*/ #ifndef COMPILE_IN_LP stop_processes(&tm->lp); #endif #ifndef COMPILE_IN_CG stop_processes(&tm->cg); #endif #ifndef COMPILE_IN_CP stop_processes(&tm->cp); #endif /*------------------------------------------------------------------------*\ * Receive statistics from the cutpools \*------------------------------------------------------------------------*/ #ifdef COMPILE_IN_CP if (tm->cpp){ for (i = 0; i < tm->par.max_cp_num; i++){ tm->comp_times.cut_pool += tm->cpp[i]->cut_pool_time; tm->stat.cuts_in_pool += tm->cpp[i]->cut_num; tm->cpp[i]->msgtag = YOU_CAN_DIE; cp_close(tm->cpp[i]); } FREE(tm->cpp); } #else for (i = 0; i < tm->par.max_cp_num;){ r_bufid = treceive_msg(tm->cp.procs[i], POOL_TIME, &timeout); if (r_bufid > 0){ receive_dbl_array(&new_time, 1); receive_int_array(&new_cuts, 1); tm->comp_times.cut_pool += new_time; tm->stat.cuts_in_pool += new_cuts; i++; }else{ if (pstat(tm->cp.procs[i]) != PROCESS_OK) i++; } } freebuf(r_bufid); #endif /* Receive timing from the LPs */ if (receive_lp_timing(tm) < 0){ printf("\nWarning: problem receiving LP timing. LP process is dead\n\n"); } #ifdef COMPILE_IN_LP for (i = 0; i < tm->par.max_active_nodes; i ++){ lp_close(lp[i]); } #endif tm->stat.root_lb = tm->rootnode->lower_bound; find_tree_lb(tm); return(termcode); #ifndef COMPILE_IN_TM /*------------------------------------------------------------------------*\ * Send back the statistics to the master \*------------------------------------------------------------------------*/ s_bufid = init_send(DataInPlace); send_char_array((char *)&tm->comp_times, sizeof(node_times)); send_char_array((char *)&tm->lp_stat, sizeof(lp_stat_desc)); send_dbl_array(&tm->lb, 1); send_char_array((char *)&tm->stat, sizeof(tm_stat)); send_msg(tm->master, termcode); freebuf(s_bufid); free_tm(tm); #endif return(termcode); } /*===========================================================================*/ /*===========================================================================*/ #if !defined(_MSC_VER) && !defined(__MNO_CYGWIN) && defined(SIGHANDLER) void sym_catch_c(int num) { sigset_t mask_set; sigset_t old_set; /* SIGTSTP ? */ signal(SIGINT, sym_catch_c); char temp [MAX_LINE_LENGTH + 1]; sigfillset(&mask_set); sigprocmask(SIG_SETMASK, &mask_set, &old_set); strcpy(temp, ""); printf("\nDo you want to abort immediately, exit gracefully (from the current solve call only), or continue? [a/e/c]: "); fflush(stdout); fgets(temp, MAX_LINE_LENGTH, stdin); if(temp[1] == '\n' && (temp[0] == 'a' || temp[0] == 'A')){ printf("\nTerminating...\n"); fflush(stdout); exit(0); }else if(temp[1] == '\n' && (temp[0] == 'e' || temp[0] == 'E')){ c_count++; } else{ printf("\nContinuing...\n"); fflush(stdout); c_count = 0; } } #endif /*===========================================================================*/ /* * Find the lowerbound of the current branch-and-cut tree and save it in * tm->lb */ int find_tree_lb(tm_prob *tm) { double lb = MAXDOUBLE; bc_node **samephase_cand; if (tm->samephase_candnum > 0 || tm->active_node_num > 0) { if (tm->par.node_selection_rule == LOWEST_LP_FIRST) { lb = tm->samephase_cand[1]->lower_bound; /* [0] is a dummy */ } else { samephase_cand = tm->samephase_cand; for (int i = tm->samephase_candnum; i >= 1; i--){ if (samephase_cand[i]->lower_bound < lb) { lb = samephase_cand[i]->lower_bound; } } } } else { /* there are no more nodes left. */ lb = tm->ub; } /* if (lb >= MAXDOUBLE / 2){ lb = tm->ub; } */ tm->lb = lb; return 0; } /*===========================================================================*/
30.908336
124
0.549655
shahnidhi
90f2dca9d6b11de4df1169bed10f4969e9e66b68
1,231
cpp
C++
avs_dx/DxVisuals/Effects/Common/EffectListBase.factory.cpp
Const-me/vis_avs_dx
da1fd9f4323d7891dea233147e6ae16790ad9ada
[ "MIT" ]
33
2019-01-28T03:32:17.000Z
2022-02-12T18:17:26.000Z
avs_dx/DxVisuals/Effects/Common/EffectListBase.factory.cpp
visbot/vis_avs_dx
03e55f8932a97ad845ff223d3602ff2300c3d1d4
[ "MIT" ]
2
2019-11-18T17:54:58.000Z
2020-07-21T18:11:21.000Z
avs_dx/DxVisuals/Effects/Common/EffectListBase.factory.cpp
Const-me/vis_avs_dx
da1fd9f4323d7891dea233147e6ae16790ad9ada
[ "MIT" ]
5
2019-02-16T23:00:11.000Z
2022-03-27T15:22:10.000Z
#include "stdafx.h" #include <RootEffect.h> #include "../List/EffectList.h" class C_RenderListClass; // Class factory is slightly more complex here: creating different classes depending on whether this effect is the root or just a list inside the preset. template<> HRESULT createDxEffect<C_RenderListClass>( void* pState, const C_RBASE* pRBase ) { const EffectListBase::AvsState* pStateBase = ( EffectListBase::AvsState* )pState; if( pStateBase->isroot ) return EffectImpl<RootEffect>::create( pState, pRBase ); return EffectImpl<EffectList>::create( pState, pRBase ); }; // Similarly, need to implement two copies of metadata() method. const char* const EffectImpl<RootEffect>::s_effectName = "RootEffect"; static const EffectBase::Metadata s_root{ "RootEffect", true }; const EffectBase::Metadata& RootEffect::metadata() { return s_root; } const char* const EffectImpl<EffectList>::s_effectName = "EffectList"; static const EffectBase::Metadata s_list{ "EffectList", true }; const EffectBase::Metadata& EffectList::metadata() { return s_list; } void clearListRenderers( const C_RBASE* pThis ) { auto pl = dynamic_cast<EffectListBase*>( getDxEffect( pThis ) ); if( nullptr == pl ) return; pl->clearRenders(); }
31.564103
153
0.753859
Const-me
90f4f719a45d230d38cb5086c765c04a18c45838
12,944
cpp
C++
NPlan/NPlan/view/TaskView.cpp
Avens666/NPlan
726411b053ded26ce6c1b8c280c994d4c1bac71a
[ "Apache-2.0" ]
16
2018-08-30T11:27:14.000Z
2021-12-17T02:05:45.000Z
NPlan/NPlan/view/TaskView.cpp
Avens666/NPlan
726411b053ded26ce6c1b8c280c994d4c1bac71a
[ "Apache-2.0" ]
null
null
null
NPlan/NPlan/view/TaskView.cpp
Avens666/NPlan
726411b053ded26ce6c1b8c280c994d4c1bac71a
[ "Apache-2.0" ]
14
2018-08-30T12:13:56.000Z
2021-02-06T11:07:44.000Z
// File: TaskView.cpp // Copyright: Copyright(C) 2013-2017 Wuhan KOTEI Informatics Co., Ltd. All rights reserved. // Website: http://www.nuiengine.com // Description: This code is part of NPlan Project (Powered by NUI Engine) // Comments: // Rev: 1 // Created: 2018/8/27 // Last edit: 2015/9/16 // Author: Chen Zhi and his team // E-mail: cz_666@qq.com // License: APACHE V2.0 (see license file) #include "TimeBarView.h" #include "boost/lexical_cast.hpp" #include "AnimationThread.h" #include "KSurfaceManager.h" #include "KFontManager.h" #include "TaskView.h" #include "KTextMultiLineDrawable.h" #include "boost/lexical_cast.hpp" #include "MilestoneEditView.h" #include "NMenu.h" #include "KScreen.h" #include "../NPlan.h" using namespace std; using namespace boost; const static kn_int click_area_value = 10; #ifdef WIN32 //句柄 extern HWND g_hWnd; #endif CTaskView::CTaskView(void) { m_p_task = NULL; m_b_click = true; m_b_move = true; SetShieldMsg(false); } CTaskView::~CTaskView() { } void CTaskView::setTaskBar(CTaskBarView_WEAK_PTR p) { m_p_taskbar = p; } CTaskBarView_PTR CTaskView::getTaskBar() { return m_p_taskbar.lock(); } void CTaskView::OnDown(kn_int iScreenX, kn_int iScreenY, KMessageMouse* pMsg) { if (!m_p_parent.expired()) { m_down_point.set(iScreenX, iScreenY); m_down_point_offset.set(iScreenX - m_rect.left(), iScreenY - m_rect.top()); m_b_mouse_picked = true; m_b_click = true; setViewFocus(); } } void CTaskView::OnMove(kn_int iScreenX, kn_int iScreenY, KMessageMouse* pMsg) { if(m_b_mouse_picked && m_b_move) { kn_int move_x_offset = iScreenX - m_down_point.x(); kn_int move_y_offset = iScreenY -m_down_point.y(); if ((abs(move_x_offset) > click_area_value) || (abs(move_y_offset) > click_area_value)) { m_b_click = false; m_p_parent.lock()->changeViewLayerTop(shared_from_this()); KMessageDrag* msg = new KMessageDrag; msg->m_p_drag_view = shared_from_this(); msg->m_drag_type = TASK_VIEW_DRAG; msg->m_pos_x = iScreenX - m_down_point_offset.x(); msg->m_pos_y = iScreenY - m_down_point_offset.y(); if (move_y_offset > 0) { msg->m_wParam = DRAG_DOWNWARD; } else { msg->m_wParam = DRAG_UPWARD; } msg->m_lParam = move_y_offset; GetScreen()->sendNUIMessage( KMSG_DRAG, msg ); m_down_point.set(iScreenX, iScreenY); } } } void CTaskView::OnUp(kn_int iScreenX, kn_int iScreenY, KMessageMouse* pMsg) { if(m_b_mouse_picked) { if (m_b_click) { m_task_click_sign.emit(shared_from_this()); } else { kn_int m_move_lengthY = iScreenY - m_down_point.y(); KMessageDrag* msg = new KMessageDrag; msg->m_p_drag_view = shared_from_this(); msg->m_drag_type = TASK_VIEW_DRAG_UP; msg->m_pos_x = iScreenX; msg->m_pos_y = iScreenY; msg->m_lParam = m_move_lengthY; GetScreen()->sendNUIMessage( KMSG_DRAG_UP, msg ); } } } CNProjectTask* CTaskView::GetTask() { return m_p_task; } void CTaskView::init(CNProjectTask* task) { m_p_task = task; //////背景 kn_string bk_file = _T("./resource/0"); int color = m_p_task->getColorType() ; if (color >= 1 && color <=9) { bk_file += boost::lexical_cast<kn_string>( color); } else {//不合法自动分配 kn_int color_type = (task->getVectorId() + 1)%9 + 1; bk_file += boost::lexical_cast<kn_string>(color_type); m_p_task->setColorType(color_type); } bk_file += _T(".9.png"); K9PatchImageDrawable_PTR bk_drawable(new K9PatchImageDrawable( getSurfaceManager()->GetSurface( bk_file), TRUE )); // ((K9PatchImageDrawable_PTR)bk_drawable)->SizeToImage(); bk_drawable->SetRect(RERect::MakeXYWH(0, 0, m_rect.width(), m_rect.height()) ); setIconDrawable(bk_drawable); /////icon //kn_string icon_file = _T("./resource/task_icon"); //icon_file += boost::lexical_cast<kn_string>( (task->getVectorId() + 1)%8 +1); //icon_file += _T(".png"); //KImageDrawable_PTR icon_da (new KImageDrawable( getSurfaceManager()->GetSurface( icon_file), TRUE ) ); //icon_da->SizeToImage(); //icon_da->SetRect(RERect::MakeXYWH(6, 6, icon_da->GetRect().width(), icon_da->GetRect().height()) ); //setIconDrawable(icon_da); m_text_name = KTextMultiLineDrawable_PTR(new KTextMultiLineDrawable(RE_ColorWHITE, 16, REPaint::kLeft_Align) ); // m_text_name->SetRect(RERect::MakeXYWH(10 +icon_da->GetRect().width() , 10, m_rect.width() - 14 - icon_da->GetRect().width(), m_rect.height() ) ); // m_text_name->setBold(TRUE); m_text_name->SetRect(RERect::MakeXYWH(36 , 12, m_rect.width() - 55, m_rect.height() - 32 ) ); m_text_name->setFont(GetFontManagerSingleton()->GetFontFromName("Microsoft YaHei")); m_text_name->setMaxLine(3); setTextDrawable(m_text_name); // SetTextColor(SkColorSetARGBMacro(255,0,0,0), SkColorSetARGBMacro(255, 255, 255, 255), SkColorSetARGBMacro(255,0,0, 0), SkColorSetARGBMacro(255,0,0,0)); m_text_id = KTextDrawable_PTR(new KTextDrawable(_T(""), RE_ColorWHITE, 16, REPaint::kCenter_Align) ); //m_text_id->setBold(TRUE); m_text_id->setFont(GetFontManagerSingleton()->GetFontFromName("Microsoft YaHei")); m_text_id->SetRect(RERect::MakeXYWH(5 , 14, 20, 20 ) ); addDrawable(m_text_id); //REPoint p1, p2; //p1.set( ) //KLineShape* shape = new KLineShape(m_rect.width(), ) refreshInfo(); } void CTaskView::setMode(bool b) { //if (m_mode == b) //{ // return; //} if (b == MODE_BIG) {//大模式 m_text_name->SetFontSize(16); m_text_name->setMaxLine(3); } else { m_text_name->SetFontSize(12); m_text_name->setMaxLine(2); } if (m_text_name->isOverroad()) { setTip(m_text_name->GetText(),NO_TIMER,4000); } else { enableTip(FALSE); } } void CTaskView::refreshInfo() { if (m_p_task) { kn_string str = m_p_task->getName(); m_text_name->SetText(str.c_str() ); m_text_name->autoMLine(); if (m_text_name->isOverroad()) { setTip(m_text_name->GetText(),NO_TIMER,4000); } else { enableTip(FALSE); } if (m_p_task->getVectorId() < 9) { str = _T("0"); str += boost::lexical_cast<kn_string>(m_p_task->getVectorId() + 1); } else { str = boost::lexical_cast<kn_string>(m_p_task->getVectorId() + 1); } m_text_id->SetText(str.c_str() ); } } void CTaskView::OnRUp(kn_int iScreenX, kn_int iScreenY, KMessageMouse* pMsg) { //if ( m_p_task) //{ // CMenuColor_PTR menu = CMenuColor_PTR(new CMenuColor ); // menu->Create(0,0, 38*3+12, 38*4+12); // menu->init(this ); // menu->m_sign_menu_click.connect(this, &CTaskView::onMenu); // //showmenu 传入view自身的相对坐标,这里取鼠标点击位置 // showMenu(menu, iScreenX - m_rect.x(), iScreenY - m_rect.y()); // InvalidateView(); //} } void CTaskView::onMenu(kn_int n) { //if (n>=1 && n <=9) //{//换颜色 // kn_string bk_file = _T("./resource/0"); // bk_file += boost::lexical_cast<kn_string>( n ); // bk_file += _T(".9.png"); // K9PatchImageDrawable_PTR bk_drawable(new K9PatchImageDrawable( getSurfaceManager()->GetSurface( bk_file), TRUE )); // // ((K9PatchImageDrawable_PTR)bk_drawable)->SizeToImage(); // bk_drawable->SetRect(RERect::MakeXYWH(0, 0, m_rect.width(), m_rect.height()) ); // setIconDrawable(bk_drawable); //} } kn_int CTaskView::getTaskID() { return m_p_task->getVectorId(); } void CTaskView::setNameText( const kn_string& name_text ) { m_text_name->SetText(name_text); } REColor CTaskView::getBkColor() { kn_int color_type = m_p_task->getColorType(); switch (color_type) { case 1: m_bk_color = ColorSetARGB(255, 63, 177, 225); break; case 2: m_bk_color = ColorSetARGB(255, 104, 167, 155); break; case 3: m_bk_color = ColorSetARGB(255, 201, 107, 107); break; case 4: m_bk_color = ColorSetARGB(255, 203, 144, 68); break; case 5: m_bk_color = ColorSetARGB(255, 95, 121, 184); break; case 6: m_bk_color = ColorSetARGB(255, 63, 141, 163); break; case 7: m_bk_color = ColorSetARGB(255, 177, 116, 85); break; case 8: m_bk_color = ColorSetARGB(255, 115, 163, 107); break; case 9: m_bk_color = ColorSetARGB(255, 174, 128, 187); break; default: m_bk_color = ColorSetARGB(0, 0, 0, 0); break; } return m_bk_color; } void CTaskView::setBMove( kn_bool bMove ) { m_b_move = bMove; } kn_string CTaskView::getNameText() { return m_text_name->GetText(); } ///////////////////// CEventView //////////////////////////// CEventView::CEventView(void) { m_p_data = NULL; m_b_move = FALSE; m_w = 25; checkAlpha(TRUE); } CEventView::~CEventView() { } CNProjectMileStone* CEventView::getMileStone() { return m_p_data; } void CEventView::init(CNProjectMileStone* data, CTimeBarView_PTR timebar) { //////背景 //K9PatchImageDrawable_PTR bk_drawable(new K9PatchImageDrawable( getSurfaceManager()->GetSurface( _T("./resource/task_btn_bk.9.png")), TRUE )); //((K9PatchImageDrawable_PTR)bk_drawable)->SizeToImage(); //bk_drawable->SetRect(RERect::MakeXYWH(0, 0, m_rect.width(), m_rect.height()) ); //setBKDrawable(bk_drawable); /////icon //kn_string icon_file = _T("./resource/task_icon"); //icon_file += boost::lexical_cast<kn_string>( (task->getVectorId() + 1)%8 +1); //icon_file += _T(".png"); K9PatchImageDrawable_PTR icon_da (new K9PatchImageDrawable( getSurfaceManager()->GetSurface( _T("./resource/event.9.png")), TRUE ) ); icon_da->SizeToImage(); RERect rect = icon_da->GetRect(); m_w = rect.width(); icon_da->SetRect(RERect::MakeXYWH(0, 0, rect.width(), m_rect.height()) ); setBKDrawable(icon_da); checkAlpha(TRUE); setCheckAlphaDrawable(icon_da); m_info = KTextMultiLineDrawable_PTR(new KTextMultiLineDrawable( RE_ColorBLACK, 12, REPaint::kLeft_Align) ); // int line = m_info->getLine(); m_info->SetRect(RERect::MakeXYWH(rect.width()/2+3 + m_w/2, 15, 100, 14*2 ) ); m_info->setTextFrame(TRUE); setTextDrawable(m_info); m_time = KTextDrawable_PTR(new KTextDrawable(_T(""), RE_ColorBLACK, 12, REPaint::kLeft_Align) ); m_time->SetRect(RERect::MakeXYWH(rect.width()/2+3 + m_w/2, 1, 100, 14 ) ); m_time->setTextFrame(TRUE); addDrawable(m_time); m_event_id = KTextDrawable_PTR(new KTextDrawable(_T(""), ARGB(255,255,255,255), 12, REPaint::kLeft_Align) ); m_event_id->SetRect(RERect::MakeXYWH(10, 10, 16, 12 ) ); m_event_id->setBold(TRUE); m_event_id->setFont(GetFontManagerSingleton()->GetFontFromName("Microsoft YaHei")); // m_event_id->setTextFrame(TRUE); addDrawable(m_event_id); m_p_data = data; m_timebar = timebar; refreshInfo(); // enableMessage(TRUE); } void CEventView::refreshInfo() { if (m_p_data) { writeLock lock(m_lst_drawable_mutex); kn_string str = m_p_data->getName(); m_info->SetText(str); // m_info->autoMLine(); str = getTimeString(m_p_data->getTime(), FALSE); m_time->SetText(str); str = boost::lexical_cast<kn_string>(m_p_data->getId()); m_event_id->SetText(str); } } void CEventView::syncTimeline(CTimeBarView_PTR tl) { if (m_p_data) { float x1; x1 = tl->getTimePosition( m_p_data->getTime() ); RERect rect = tl->GetRect(); RERect rect2 = RERect::MakeXYWH(rect.left()+x1 - m_w/2, m_rect.top(), m_rect.width(), m_rect.height()); SetRect( rect2 ); } } void CEventView::OnMove(kn_int x, kn_int y, KMessageMouse* pMsg) { kn_bool b_update = FALSE; if(m_b_mouse_picked) { if(m_b_move ) { m_p_data->setTime( m_timebar->getPositisonTimeInt( x - m_timebar->GetRect().left() + m_mouse_x_offset, 10 ) ); b_update = TRUE; } } if (b_update) { refreshInfo(); syncTimeline(m_timebar); InvalidateView(); pMsg->setIdle(KMSG_RETURN_DILE); } } void CEventView::OnDown(kn_int iScreenX, kn_int iScreenY, KMessageMouse* pMsg) { if ( iScreenX - m_rect.left() <m_w && iScreenY - m_rect.top() < m_w) {//拖移 m_b_move = TRUE; //m_mouse_x_offset 在于使bar和鼠标相对位置不动 m_mouse_x_offset = m_rect.left() + m_w/2 - iScreenX; pMsg->setIdle(KMSG_RETURN_DILE); } } void CEventView::OnUp(kn_int iScreenX, kn_int iScreenY, KMessageMouse* pMsg) { m_b_move = FALSE; } void CEventView::OnDClick(kn_int iScreenX, kn_int iScreenY, KMessageMouse* pMsg) { //tagRECT rect; //GetWindowRect(g_hWnd,&rect); //RERect rect; int w = GetScreen()->GetWidth(); int h = GetScreen()->GetHeight(); MilestoneEditView_PTR pView = MilestoneEditView_PTR( new MilestoneEditView); pView->Create(RERect::MakeXYWH((w-400)/2, (h-250)/2 , 400, 250)); pView->init(m_p_data ); GetParent()->AddView( pView ); InvalidateView(); kn_int i_result = pView->doModal(); if (i_result == KN_REUSLT_OK) { refreshInfo(); } else if (i_result == KN_REUSLT_USER_DEL) { m_sign_btn_del.emit( shared_from_this() ); } }
25.991968
155
0.663473
Avens666
90f53d4655f7c319ad41dda208f87542ea045213
1,599
cc
C++
shill/upstart/upstart_test.cc
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
4
2020-07-24T06:54:16.000Z
2021-06-16T17:13:53.000Z
shill/upstart/upstart_test.cc
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2021-04-02T17:35:07.000Z
2021-04-02T17:35:07.000Z
shill/upstart/upstart_test.cc
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2020-11-04T22:31:45.000Z
2020-11-04T22:31:45.000Z
// Copyright 2018 The Chromium OS 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 "shill/upstart/upstart.h" #include <utility> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "shill/mock_control.h" #include "shill/upstart/mock_upstart_proxy.h" #include "shill/upstart/upstart_proxy_interface.h" using testing::_; using testing::Test; namespace shill { namespace { class FakeControl : public MockControl { public: FakeControl() : upstart_proxy_raw_(new MockUpstartProxy), upstart_proxy_(upstart_proxy_raw_) {} std::unique_ptr<UpstartProxyInterface> CreateUpstartProxy() override { CHECK(upstart_proxy_); return std::move(upstart_proxy_); } // Can not guarantee that the returned object is alive. MockUpstartProxy* upstart_proxy() const { return upstart_proxy_raw_; } private: MockUpstartProxy* const upstart_proxy_raw_; std::unique_ptr<MockUpstartProxy> upstart_proxy_; }; } // namespace class UpstartTest : public Test { public: UpstartTest() : upstart_(&control_), upstart_proxy_(control_.upstart_proxy()) {} protected: FakeControl control_; Upstart upstart_; MockUpstartProxy* const upstart_proxy_; }; TEST_F(UpstartTest, NotifyDisconnected) { EXPECT_CALL(*upstart_proxy_, EmitEvent("shill-disconnected", _, false)); upstart_.NotifyDisconnected(); } TEST_F(UpstartTest, NotifyConnected) { EXPECT_CALL(*upstart_proxy_, EmitEvent("shill-connected", _, false)); upstart_.NotifyConnected(); } } // namespace shill
24.227273
74
0.749844
strassek
90f6e6e7114705c60666c2713ba0172f4cf0b149
986
cpp
C++
BallCollision/Plane.cpp
Baeonex/BehavioursCollisions
c78cd1d5911b0caf632a11120686a09666526021
[ "MIT" ]
null
null
null
BallCollision/Plane.cpp
Baeonex/BehavioursCollisions
c78cd1d5911b0caf632a11120686a09666526021
[ "MIT" ]
null
null
null
BallCollision/Plane.cpp
Baeonex/BehavioursCollisions
c78cd1d5911b0caf632a11120686a09666526021
[ "MIT" ]
null
null
null
#include "Plane.h" Plane::Plane() { } Plane::~Plane() { } Plane::Plane(Vector2& p1, Vector2& p2) { auto v = p2 - p1; v.normalise(); m_normal.x = -v.y; m_normal.y = v.x; m_d = -p1.dot(m_normal); } float Plane::distanceTo(const Vector2& p) { return p.dot(m_normal) + m_d; } Vector2 Plane::closestPoint(Vector2& p) { return p - m_normal * distanceTo(p); } ePlaneResult Plane::testSide(const Vector2& p) { float t = p.dot(m_normal) + m_d; if (t < 0) return ePlaneResult::BACK; else if (t > 0) return ePlaneResult::FRONT; return ePlaneResult::INTERSECTS; } void Plane::collRes(Circle& circle) { Vector2 reflected; reflected = 2 * m_normal * (m_normal.dot(circle.m_velocity)); circle.m_velocity -= reflected; } ePlaneResult Plane::testSide(const Circle& circle) { float t = distanceTo(circle.m_center); if (t > circle.m_radius) return ePlaneResult::FRONT; else if (t < -circle.m_radius) return ePlaneResult::BACK; else return ePlaneResult::INTERSECTS; }
16.711864
62
0.684584
Baeonex
90f70620efe79b78697816e51e45dbbabb10b94f
15,520
cpp
C++
mod/bear/bear.cpp
littlegao233/bdlauncher
d765f1cd2bffed37e7f773f8120599f6e7cec732
[ "MIT" ]
1
2020-01-12T11:40:30.000Z
2020-01-12T11:40:30.000Z
mod/bear/bear.cpp
mclauncherlinux/bdlauncher
9d7482786ba8be1e06fc7c81b448c5862e970870
[ "MIT" ]
null
null
null
mod/bear/bear.cpp
mclauncherlinux/bdlauncher
9d7482786ba8be1e06fc7c81b448c5862e970870
[ "MIT" ]
null
null
null
#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include"aux.h" #include<cstdio> #include<list> #include<forward_list> #include<string> #include<unordered_map> #include<unordered_set> #include"../cmdhelper.h" #include<vector> #include<Loader.h> #include<MC.h> #include"seral.hpp" #include<unistd.h> #include<cstdarg> #include"base.h" #include"../gui/gui.h" #include<cmath> #include<deque> #include<dlfcn.h> #include<string> #include<aio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> using std::string; using std::unordered_map; using std::unordered_set; #define min(a,b) ((a)<(b)?(a):(b)) #define max(a,b) ((a)>(b)?(a):(b)) #define dbg_printf(...) {} //#define dbg_printf printf extern "C" { BDL_EXPORT void bear_init(std::list<string>& modlist); } extern void load_helper(std::list<string>& modlist); static unordered_map<string,int> banlist; static unordered_map<string,string> xuid_name; static void save() { char* bf; int sz=maptomem(banlist,&bf,h_str2str,h_int2str); mem2file("ban.db",bf,sz); } static void load() { char* buf; int sz; struct stat tmp; if(stat("ban.db",&tmp)==-1) { save(); } file2mem("ban.db",&buf,sz); memtomap(banlist,buf,h_str2str_load,h_str2int); } static void save2() { char* bf; int sz=maptomem(xuid_name,&bf,h_str2str,h_str2str); mem2file("banxuid.db",bf,sz); } static void load2() { char* buf; int sz; struct stat tmp; if(stat("banxuid.db",&tmp)==-1) { save2(); } file2mem("banxuid.db",&buf,sz); memtomap(xuid_name,buf,h_str2str_load,h_str2str_load); } bool isBanned(const string& name) { if(banlist.count(name)) { int tm=banlist[name]; if(tm==0) return 1; if(time(0)>tm) { banlist.erase(name); save(); return 0; } return 1; } return 0; } static int logfd; static int logsz; static void initlog() { logfd=open("player.log",O_WRONLY|O_APPEND|O_CREAT,S_IRWXU); logsz=lseek(logfd,0,SEEK_END); } static void async_log(const char* fmt,...) { char buf[10240]; auto x=time(0); va_list vl; va_start(vl,fmt); auto tim=strftime(buf,128,"[%Y-%m-%d %H:%M:%S] ",localtime(&x)); int s=vsprintf(buf+tim,fmt,vl)+tim; write(1,buf,s); write(logfd,buf,s); va_end(vl); } THook(void*,_ZN20ServerNetworkHandler22_onClientAuthenticatedERK17NetworkIdentifierRK11Certificate,u64 t,NetworkIdentifier& a, Certificate& b){ string pn=ExtendedCertificate::getIdentityName(b); string xuid=ExtendedCertificate::getXuid(b); async_log("[JOIN]%s joined game with xuid <%s>\n",pn.c_str(),xuid.c_str()); if(!xuid_name.count(xuid)){ xuid_name[xuid]=pn; save2(); } if(isBanned(pn) || (xuid_name.count(xuid) && isBanned(xuid_name[xuid]))) { string ban("§c你在当前服务器的黑名单内!"); getMC()->getNetEventCallback()->disconnectClient(a,ban,false); return nullptr; } return original(t,a,b); } static bool hkc(ServerPlayer const * b,string& c) { async_log("[CHAT]%s: %s\n",b->getName().c_str(),c.c_str()); return 1; } #include <sys/socket.h> #include <arpa/inet.h> ssize_t (*rori)(int socket, void * buffer, size_t length, int flags, struct sockaddr * address, socklen_t * address_len); static ssize_t recvfrom_hook(int socket, void * buffer, size_t length, int flags, struct sockaddr * address, socklen_t * address_len) { int rt=rori(socket,buffer,length,flags,address,address_len); if(rt && ((char*)buffer)[0]==0x5) { char buf[1024]; inet_ntop(AF_INET,&(((sockaddr_in*)address)->sin_addr),buf,*address_len); async_log("[NETWORK] %s send conn\n",buf); } return rt; } static void oncmd(std::vector<string>& a,CommandOrigin const & b,CommandOutput &outp) { ARGSZ(1) if((int)b.getPermissionsLevel()>0) { banlist[a[0]]=a.size()==1?0:(time(0)+atoi(a[1].c_str())); runcmd(string("skick \"")+a[0]+"\" §c你号没了"); save(); auto x=getuser_byname(a[0]); if(x){ xuid_name[x->getXUID()]=x->getName(); save2(); } outp.success("§e玩家已封禁: "+a[0]); } } static void oncmd2(std::vector<string>& a,CommandOrigin const & b,CommandOutput &outp) { ARGSZ(1) if((int)b.getPermissionsLevel()>0) { banlist.erase(a[0]); save(); outp.success("§e玩家已解封: "+a[0]); } } //add custom using std::unordered_set; unordered_set<short> banitems,warnitems; bool dbg_player; int LOG_CHEST; static bool handle_u(GameMode* a0,ItemStack * a1,BlockPos const* a2,BlockPos const* dstPos,Block const* a5) { if(dbg_player){ sendText(a0->getPlayer(),"you use id "+std::to_string(a1->getId())); } if(LOG_CHEST && a5->getLegacyBlock()->getBlockItemId()==54){ async_log("[CHEST] %s open chest pos: %d %d %d\n",a0->getPlayer()->getName().c_str(),a2->x,a2->y,a2->z); } //printf("dbg use %s\n",a0->getPlayer()->getCarriedItem().toString().c_str()); if(a0->getPlayer()->getPlayerPermissionLevel()>1) return 1; string sn=a0->getPlayer()->getName(); if(banitems.count(a1->getId())){ async_log("[ITEM] %s 使用高危物品(banned) %s pos: %d %d %d\n",sn.c_str(),a1->toString().c_str(),a2->x,a2->y,a2->z); sendText(a0->getPlayer(),"§c无法使用违禁物品",JUKEBOX_POPUP); return 0; } if(warnitems.count(a1->getId())){ async_log("[ITEM] %s 使用危险物品(warn) %s pos: %d %d %d\n",sn.c_str(),a1->toString().c_str(),a2->x,a2->y,a2->z); return 1; } return 1; } static void handle_left(ServerPlayer* a1){ async_log("[LEFT] %s left game\n",a1->getName().c_str()); } #include"rapidjson/document.h" int FPushBlock,FExpOrb,FDest; enum CheatType{ FLY,NOCLIP,INV,MOVE }; static void notifyCheat(const string& name,CheatType x){ const char* CName[]={"FLY","NOCLIP","Creative","Teleport"}; async_log("[%s] detected for %s\n",CName[x],name.c_str()); string kick=string("skick \"")+name+"\" §c你号没了"; switch(x){ case FLY: runcmd(kick); break; case NOCLIP: runcmd(kick); break; case INV: runcmd(kick); break; case MOVE: runcmd(kick); break; } } THook(void*,_ZN5BlockC2EtR7WeakPtrI11BlockLegacyE,Block* a,unsigned short x,void* c){ auto ret=original(a,x,c); if(FPushBlock){ auto* leg=a->getLegacyBlock(); if(a->isContainerBlock()) leg->addBlockProperty({0x1000000LL}); } return ret; } unordered_map<string,clock_t> lastchat; int FChatLimit; static bool ChatLimit(ServerPlayer* p){ if(!FChatLimit || p->getPlayerPermissionLevel()>1) return true; auto last=lastchat.find(p->getRealNameTag()); if(last!=lastchat.end()){ auto old=last->second; auto now=clock(); last->second=now; if(now-old<CLOCKS_PER_SEC*0.25) return false; return true; }else{ lastchat.insert({p->getRealNameTag(),clock()}); return true; } } THook(void*,_ZN20ServerNetworkHandler6handleERK17NetworkIdentifierRK10TextPacket,ServerNetworkHandler* sh,NetworkIdentifier const& iden,Packet* pk){ ServerPlayer* p=sh->_getServerPlayer(iden,pk->getClientSubId()); if(p){ if(ChatLimit(p)) return original(sh,iden,pk); } return nullptr; } THook(void*,_ZN20ServerNetworkHandler6handleERK17NetworkIdentifierRK20CommandRequestPacket,ServerNetworkHandler* sh,NetworkIdentifier const& iden,Packet* pk){ ServerPlayer* p=sh->_getServerPlayer(iden,pk->getClientSubId()); if(p){ if(ChatLimit(p)) return original(sh,iden,pk); } return nullptr; } THook(void*,_ZN20ServerNetworkHandler6handleERK17NetworkIdentifierRK24SpawnExperienceOrbPacket,ServerNetworkHandler* sh,NetworkIdentifier const& iden,Packet* pk){ if(FExpOrb){ return nullptr; } return original(sh,iden,pk); } THook(void*,_ZNK15StartGamePacket5writeER12BinaryStream,void* this_,void* a){ //dirty patch to hide seed access(this_,uint,40)=114514; return original(this_,a); } static int limitLevel(int input, int max) { if (input < 0) return 0; else if (input > max) return 0; return input; } struct Enchant { enum Type : int {}; static std::vector<std::unique_ptr<Enchant>> mEnchants; virtual ~Enchant(); virtual bool isCompatibleWith(Enchant::Type type); virtual int getMinCost(int); virtual int getMaxCost(int); virtual int getMinLevel(); virtual int getMaxLevel(); virtual bool canEnchant(int) const; }; struct EnchantmentInstance { enum Enchant::Type type; int level; int getEnchantType() const; int getEnchantLevel() const; void setEnchantLevel(int); }; //将外挂附魔无效 THook(int, _ZNK19EnchantmentInstance15getEnchantLevelEv, EnchantmentInstance* thi) { int level2 = thi->level; auto &enchant = Enchant::mEnchants[thi->type]; auto max = enchant->getMaxLevel(); auto result = limitLevel(level2, max); if (result != level2) thi->level = result; return result; } typedef unsigned long IHash; static IHash MAKE_IHASH(ItemStack* a){ IHash res= a->getIdAuxEnchanted(); if(*a->getUserData()){ res^=(*(a->getUserData()))->hash()<<28; } return res; } struct VirtInv{ unordered_map<IHash,int> items; bool bad; VirtInv(Player& p){ bad=0; } void setBad(){ bad=1; } void addItem(IHash item,int count){ if(item==0) return; int prev=items[item]; items[item]=prev+count; } void takeItem(IHash item,int count){ addItem(item,-count); } bool checkup(){ if(bad) return 1; for(auto &i:items){ if(i.second<0){ return false; } } return true; } void clear(){ items.clear(); bad=false; } }; //unordered_map<string,IHash> lastitem; THook(unsigned long,_ZNK20InventoryTransaction11executeFullER6Playerb,void* _thi,Player &player, bool b){ if(player.getPlayerPermissionLevel()>1) return original(_thi,player,b); const string& name=player.getName(); auto& a=*((unordered_map<InventorySource,vector<InventoryAction> >*)_thi); for(auto& i:a){ for(auto& j:i.second){ if(i.first.getContainerId()==119){ //offhand chk if((!j.getToItem()->isNull() && !j.getToItem()->isOffhandItem()) || (!j.getFromItem()->isNull() && !j.getFromItem()->isOffhandItem())){ notifyCheat(name,INV); return 6; } } if(banitems.count(j.getFromItem()->getId()) || banitems.count(j.getToItem()->getId())){ async_log("[ITEM] %s 使用高危物品(banned) %s %s\n",name.c_str(),j.getFromItem()->toString().c_str(),j.getToItem()->toString().c_str()); sendText(&player,"§c无法使用违禁物品",JUKEBOX_POPUP); return 6; } /* if(j.getSlot()==50 && i.first.getContainerId()==124){ //track this auto hashf=MAKE_IHASH(j.getFromItem()),hasht=MAKE_IHASH(j.getToItem()); auto it=lastitem.find(name); if(it==lastitem.end()){ lastitem[name]=hasht; continue; }else{ if(it->second!=hashf){ async_log("[ITEM] crafting hack detected for %s , %s\n",name.c_str(),j.getFromItem()->toString().c_str()); notifyCheat(name,INV); return 6; } it->second=hasht; } }*/ //printf("cid %d flg %d src %d slot %u get %d %s %s hash %ld %ld\n",j.getSource().getContainerId(),j.getSource().getFlags(),j.getSource().getType(),j.getSlot(),i.first.getContainerId(),j.getFromItem()->toString().c_str(),j.getToItem()->toString().c_str(),MAKE_IHASH(j.getFromItem()),MAKE_IHASH(j.getToItem())); } } return original(_thi,player,b); } using namespace rapidjson; static void load_config(){ char buf[96*1024]; banitems.clear();warnitems.clear(); int fd=open("config/bear.json",O_RDONLY); if(fd==-1){ printf("[BEAR] Cannot load config file!check your configs folder\n"); exit(0); } buf[read(fd,buf,96*1024-1)]=0; close(fd); Document d; if(d.ParseInsitu(buf).HasParseError()){ printf("[ANTIBEAR] JSON ERROR!\n"); exit(1); } FPushBlock=d["FPushChest"].GetBool(); FExpOrb=d["FSpwanExp"].GetBool(); FDest=d["FDestroyCheck"].GetBool(); FChatLimit=d["FChatLimit"].GetBool(); LOG_CHEST=d.HasMember("LogChest")?d["LogChest"].GetBool():false; auto&& x=d["banitems"].GetArray(); for(auto& i:x){ banitems.insert((short)i.GetInt()); } auto&& y=d["warnitems"].GetArray(); for(auto& i:y){ warnitems.insert((short)i.GetInt()); } } string lastn; clock_t lastcl; int fd_count; #include<ctime> static int handle_dest(GameMode* a0,BlockPos const& a1,unsigned char a2) { if(!FDest) return 1; int pl=a0->getPlayer()->getPlayerPermissionLevel(); if(pl>1 || a0->getPlayer()->isCreative()) { return 1; } const string& name=a0->getPlayer()->getName(); int x(a1.x),y(a1.y),z(a1.z); Block& bk=*a0->getPlayer()->getBlockSource()->getBlock(a1); int id=bk.getLegacyBlock()->getBlockItemId(); if(id==7 || id==416){ notifyCheat(name,CheatType::INV); return 0; } if(name==lastn && clock()-lastcl<CLOCKS_PER_SEC*(10.0/1000)/*10ms*/) { lastcl=clock(); fd_count++; if(fd_count>=5){ fd_count=3; return 0; } }else{ lastn=name; lastcl=clock(); fd_count=0; } const Vec3& fk=a0->getPlayer()->getPos(); #define abs(x) ((x)<0?-(x):(x)) int dx=fk.x-x; int dy=fk.y-y; int dz=fk.z-z; int d2=dx*dx+dy*dy+dz*dz; if(d2>45) { return 0; } return 1; } static void toggle_dbg(){ dbg_player=!dbg_player; } static void kick_cmd(std::vector<string>& a,CommandOrigin const & b,CommandOutput &outp) { ARGSZ(1) if((int)b.getPermissionsLevel()>0) { if(a.size()==1) a.push_back("Kicked"); runcmd("kick \""+a[0]+"\" "+a[1]); auto x=getuser_byname(a[0]); if(x){ forceKickPlayer(*x); outp.success("okay!"); }else{ outp.error("not found!"); } } } static void bangui_cmd(std::vector<string>& a,CommandOrigin const & b,CommandOutput &outp) { string nm=b.getName(); gui_ChoosePlayer((ServerPlayer*)b.getEntity(),"ban","ban",[nm](const string& dst){ auto sp=getplayer_byname(nm); if(sp) runcmdAs("ban \""+dst+"\"",sp); }); } void bear_init(std::list<string>& modlist) { if(getenv("LOGCHEST")) LOG_CHEST=1; load(); load2(); initlog(); register_cmd("ban",fp(oncmd),"封禁玩家",1); register_cmd("unban",fp(oncmd2),"解除封禁",1); register_cmd("reload_bear",fp(load_config),"Reload Configs for antibear",1); register_cmd("bear_dbg",fp(toggle_dbg),"toggle debug item",1); register_cmd("skick",fp(kick_cmd),"force kick",1); register_cmd("bangui",fp(bangui_cmd),"封禁玩家GUI",1); reg_useitemon(handle_u); reg_player_left(handle_left); reg_chat(hkc); load_config(); rori=(typeof(rori))(MyHook(fp(recvfrom),fp(recvfrom_hook))); printf("[ANTI-BEAR] Loaded V2019-11-25\n"); load_helper(modlist); }
30.431373
318
0.611856
littlegao233
90f72a9dd022e250b6a9e1f2a7f37d170ee7ea44
6,059
cpp
C++
src/BasicRSVD.cpp
djanekovic/librsvd
83c626c749f2924ca6d7d49d3625c53c1f93a2c1
[ "MIT" ]
null
null
null
src/BasicRSVD.cpp
djanekovic/librsvd
83c626c749f2924ca6d7d49d3625c53c1f93a2c1
[ "MIT" ]
null
null
null
src/BasicRSVD.cpp
djanekovic/librsvd
83c626c749f2924ca6d7d49d3625c53c1f93a2c1
[ "MIT" ]
null
null
null
#include <random> #include <iostream> #include <algorithm> #include "Eigen/SVD" // forward declaration for Eigen::internal::traits namespace rsvd { template<typename _MatrixType> class BasicRSVD; } namespace Eigen { namespace internal { template <typename _MatrixType> struct traits<rsvd::BasicRSVD<_MatrixType>>: traits<_MatrixType> { using MatrixType = _MatrixType; }; } // end namespace internal } // end namespace Eigen namespace rsvd { using Matrix = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>; using Vector = Eigen::Matrix<double, Eigen::Dynamic, 1>; template<typename ScalarType> struct normal_distribution_functor { private: ScalarType mean_, stddev_; public: normal_distribution_functor(ScalarType mean=0, ScalarType stddev=1): mean_{mean}, stddev_{stddev} {} ScalarType operator() () const { static thread_local std::mt19937 generator; std::normal_distribution<ScalarType> distribution(mean_, stddev_); return distribution(generator); } }; /** * Generate random matrix with full rank */ Matrix GenerateRandomMatrix(std::size_t m, std::size_t n) { return Matrix::Random(m, n); } /** * Generate random matrix with rank k */ Matrix GenerateRandomMatrix(std::size_t m, std::size_t n, std::size_t k) { Matrix A = GenerateRandomMatrix(m, n); Eigen::BDCSVD<Matrix> svd(A, Eigen::ComputeThinU | Eigen::ComputeThinV); Vector singular_values = svd.singularValues(); singular_values.tail(std::min(m, n) - k).setZero(); return svd.matrixU() * singular_values.asDiagonal() * svd.matrixV().adjoint(); } /** * Generate symmetric random matrix with full rank */ Matrix GenerateRandomSymmetricMatrix(std::size_t m, std::size_t n) { Matrix A = GenerateRandomMatrix(m, n); return A * A.adjoint(); } /** * Generate symmetric random matrix with rank k */ Matrix GenerateRandomSymmetricMatrix(std::size_t m, std::size_t n, std::size_t k) { Matrix A = GenerateRandomMatrix(m, n, k); return A * A.adjoint(); } template<typename _MatrixType> class BasicRSVD: public Eigen::SVDBase<BasicRSVD<_MatrixType>> { using Base = Eigen::SVDBase<BasicRSVD>; using MatrixType = _MatrixType; using Scalar = typename MatrixType::Scalar; using RealScalar = typename Eigen::NumTraits<Scalar>::Real; // real matrix using MatrixXr = Eigen::Matrix<RealScalar, Eigen::Dynamic, Eigen::Dynamic>; // complex matrix using MatrixXc = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>; MatrixXc Y, Q, B; MatrixXr I; Eigen::BDCSVD<MatrixType> small_svd; Eigen::HouseholderQR<MatrixType> qr; public: BasicRSVD() {} BasicRSVD(Eigen::Index rows, Eigen::Index cols, size_t target_rank, size_t oversampling) { allocate(rows, cols, target_rank, oversampling); } BasicRSVD(const MatrixType &matrix, size_t target_rank, size_t oversampling, size_t num_steps=1) { compute(matrix, target_rank, oversampling, num_steps); } BasicRSVD& compute(const MatrixType &matrix, size_t target_rank, size_t oversampling, size_t num_steps); private: void allocate(Eigen::Index rows, Eigen::Index cols, size_t target_rank, size_t oversampling); }; template<typename MatrixType> void BasicRSVD<MatrixType>::allocate(Eigen::Index rows, Eigen::Index cols, size_t target_rank, size_t oversampling) { // allocate is called before and we have nothing else to do if ((Base::m_isAllocated) && Base::m_rows == rows && Base::m_cols == cols) { return; } Base::m_rows = rows; Base::m_cols = cols; Base::m_isInitialized = false; Base::m_isAllocated = true; Base::m_computeThinU = true; Base::m_computeThinV = true; // we don't need V or singular values since we get those using small SVD Base::m_matrixU.resize(rows, target_rank + oversampling); Q = MatrixXc::Zero(rows, target_rank + oversampling); Y = MatrixXc::Zero(rows, target_rank + oversampling); B = MatrixXc::Zero(target_rank + oversampling, cols); I = MatrixXr::Identity(rows, target_rank + oversampling); small_svd = Eigen::BDCSVD<MatrixType>(target_rank + oversampling, cols, Eigen::ComputeThinU | Eigen::ComputeThinV); qr = Eigen::HouseholderQR<MatrixType>(rows, target_rank + oversampling); } /** * Compute randomized SVD of matrix A with target rank, oversampling and num_steps of power iterations. */ template<typename MatrixType> BasicRSVD<MatrixType>& BasicRSVD<MatrixType>::compute(const MatrixType &A, size_t target_rank, size_t oversampling, size_t num_steps) { allocate(A.rows(), A.cols(), target_rank, oversampling); //Input matrix is mxn (m - num_rows, n - num_cols) // form sample matrix Y with size (m x (k+p)) Y.noalias() = A * MatrixXr::NullaryExpr(A.cols(), target_rank + oversampling, normal_distribution_functor<RealScalar>());; for (auto i = 0u; i < num_steps; i++) { Y = (A * A.adjoint()) * Y; } // QR decomposition of matrix Y: // - (m x k+p), (k+p, k+p) // NOTE: we are computing this inplace qr.compute(Y); // generate thin Q Q.noalias() = qr.householderQ() * I; // Matrix B is (k+p x n) B.noalias() = Q.adjoint() * A; small_svd.compute(B); Base::m_matrixU.noalias() = Q * small_svd.matrixU(); // TODO: it would be great if we could just use the memory from small_svd but we need // to allocate here since SVDBase::matrixV() returns reference which we can't move. Base::m_matrixV = small_svd.matrixV(); Base::m_singularValues = small_svd.singularValues(); Base::m_isInitialized = true; return *this; } } // end namespace rsvd void test_rsvd(const rsvd::Matrix &A) { rsvd::BasicRSVD<rsvd::Matrix> rsvd(A, 45, 0, 1); rsvd::Matrix A_ = rsvd.matrixU() * rsvd.singularValues().asDiagonal() * rsvd.matrixV().adjoint(); std::cout << (A - A_).norm() << std::endl; } int main(void) { rsvd::Matrix A = rsvd::GenerateRandomMatrix(1000, 100, 50); test_rsvd(A); }
28.852381
126
0.684271
djanekovic
90f8557d5a28f9b3b125147539f84c20ad8e8f1d
3,123
cpp
C++
GLEANKernel/GLEANLib/Utility Classes/Symbol_memory.cpp
dekieras/GLEANKernel
fac01f025b65273be96c5ea677c0ce192c570799
[ "MIT" ]
1
2018-06-22T23:01:13.000Z
2018-06-22T23:01:13.000Z
GLEANKernel/GLEANLib/Utility Classes/Symbol_memory.cpp
dekieras/GLEANKernel
fac01f025b65273be96c5ea677c0ce192c570799
[ "MIT" ]
null
null
null
GLEANKernel/GLEANLib/Utility Classes/Symbol_memory.cpp
dekieras/GLEANKernel
fac01f025b65273be96c5ea677c0ce192c570799
[ "MIT" ]
null
null
null
#include "Symbol_memory.h" #include "Utility_templates.h" #include "Assert_throw.h" #include <cstddef> using std::vector; using std::set; using std::strcpy; using std::size_t; Symbol_memory * Symbol_memory::Symbol_memory_ptr = 0; // A Meyers singleton would get automatically destructed, which is not // a good idea because the individual Symbols might get destructed afterwards // everything should get freed except for the final empty container Symbol_memory& Symbol_memory::get_instance() { if(!Symbol_memory_ptr) Symbol_memory_ptr = new Symbol_memory; return *Symbol_memory_ptr; } // deallocate the memory for the c-strings and the vectors void Symbol_memory::clear() { for_each(vec_rep_ptr_set.begin(), vec_rep_ptr_set.end(), Delete()); vec_rep_ptr_set.clear(); for(Str_rep_ptr_set_t::iterator it = str_rep_ptr_set.begin(); it != str_rep_ptr_set.end(); it++) { Symbol_memory_Str_rep * p = *it; delete[] p->cstr; delete p; } // deallocate the set contents str_rep_ptr_set.clear(); } // return the pointer to the Symbol_memory_Str_rep if the cstring is already present, // add the Symbol_memory_Str_rep if it isn't, and return the pointer // len is supplied because it is already computed - to save time Symbol_memory_Str_rep * Symbol_memory::find_or_insert(const char * p, int len) { Symbol_memory_Str_rep sr(0, p, 0); Str_rep_ptr_set_t::iterator it = str_rep_ptr_set.find(&sr); if (it == str_rep_ptr_set.end()) { char * cp = new char[len + 1]; strcpy(cp, p); Symbol_memory_Str_rep * str_rep_ptr = new Symbol_memory_Str_rep(1, cp, len); str_rep_ptr_set.insert(str_rep_ptr); return str_rep_ptr; } else { Symbol_memory_Str_rep * str_rep_ptr = *it; // increment the count (str_rep_ptr->count)++; return str_rep_ptr; } } Symbol_memory_Vec_rep * Symbol_memory::find_or_insert(bool single_, const std::vector<GU::Point>& v_) { Symbol_memory_Vec_rep vr(0, single_, v_); Vec_rep_ptr_set_t::iterator it = vec_rep_ptr_set.find(&vr); if (it == vec_rep_ptr_set.end()) { Symbol_memory_Vec_rep * vec_rep_ptr = new Symbol_memory_Vec_rep(1, single_, v_); vec_rep_ptr_set.insert(vec_rep_ptr); return vec_rep_ptr; } else { Symbol_memory_Vec_rep * vec_rep_ptr = *it; // increment the count (vec_rep_ptr->count)++; return vec_rep_ptr; } } // decrement the reference count; remove it and free the memory if it was the last use void Symbol_memory::remove_if_last(Symbol_memory_Str_rep * str_rep_ptr) { (str_rep_ptr->count)--; if(str_rep_ptr->count == 0) { // remove it from the set Str_rep_ptr_set_t::iterator it = str_rep_ptr_set.find(str_rep_ptr); Assert(it != str_rep_ptr_set.end()); str_rep_ptr_set.erase(it); delete str_rep_ptr; } } // decrement the reference count; remove it and free the memory if it was the last use void Symbol_memory::remove_if_last(Symbol_memory_Vec_rep * vec_rep_ptr) { (vec_rep_ptr->count)--; if(vec_rep_ptr->count == 0) { // remove it from the set Vec_rep_ptr_set_t::iterator it = vec_rep_ptr_set.find(vec_rep_ptr); Assert(it != vec_rep_ptr_set.end()); vec_rep_ptr_set.erase(it); delete vec_rep_ptr; } }
30.028846
101
0.742875
dekieras
90f9617cb98f3e9abfcd92e1b289eb640849219d
368
cpp
C++
ObjectOrientedProgrammingCodes-CPP/CPPWorkspace/AnagramDiff/main.cpp
srinivasamaringanti/ObjectOrientedProgrammingCodes
84a11cf63d852aa4537bdde3bd0867b9a0725d66
[ "MIT" ]
null
null
null
ObjectOrientedProgrammingCodes-CPP/CPPWorkspace/AnagramDiff/main.cpp
srinivasamaringanti/ObjectOrientedProgrammingCodes
84a11cf63d852aa4537bdde3bd0867b9a0725d66
[ "MIT" ]
null
null
null
ObjectOrientedProgrammingCodes-CPP/CPPWorkspace/AnagramDiff/main.cpp
srinivasamaringanti/ObjectOrientedProgrammingCodes
84a11cf63d852aa4537bdde3bd0867b9a0725d66
[ "MIT" ]
null
null
null
#include <conio.h> #include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; int main() { cout<< "Hello,World"<< std::endl; string a{"btoe"}; string b{"aeeg"}; sort(a.begin(),a.end()); sort(b.begin(), b.end()); cout<<"A: "<<a<<endl; cout<<"B: "<<b<<endl; getch(); return 0; }
16.727273
37
0.535326
srinivasamaringanti
90fd35a75b5da54e0b9fc346755bc13f376d0f33
713
cpp
C++
src/static_search/generic_search.cpp
ParBLiSS/cao-reptile
bb807b0578396f3ffe156a95e612ef16d5da167c
[ "Apache-2.0" ]
null
null
null
src/static_search/generic_search.cpp
ParBLiSS/cao-reptile
bb807b0578396f3ffe156a95e612ef16d5da167c
[ "Apache-2.0" ]
null
null
null
src/static_search/generic_search.cpp
ParBLiSS/cao-reptile
bb807b0578396f3ffe156a95e612ef16d5da167c
[ "Apache-2.0" ]
null
null
null
/******************************************************************** * * Generic Search program * * Frederik Rønn, June 2003, University of Copenhagen. * *********************************************************************/ #ifndef __GENERIC_SEARCH_CPP__ #define __GENERIC_SEARCH_CPP__ template <typename RandomIterator, typename T, typename LayoutPolicy> bool generic_search(RandomIterator begin, RandomIterator beyond, LayoutPolicy policy, const T& value) { policy.initialize(begin, beyond); while(policy.not_finished()) { if (policy.node_contains(value)) { return true; } else policy.descend_tree(value); } return false; } #endif //__GENERIC_SEARCH_CPP__
24.586207
70
0.580645
ParBLiSS
29088612d5e6fc4de2a5d7458e3f5d91d05e94c9
14,145
cpp
C++
gui/MyCanvas.cpp
myirci/3d_circle_estimation
7161005ab14d510503310e0bb028fea5ad2a1389
[ "MIT" ]
5
2020-07-16T18:59:05.000Z
2022-03-04T01:25:54.000Z
gui/MyCanvas.cpp
myirci/3d_circle_estimation
7161005ab14d510503310e0bb028fea5ad2a1389
[ "MIT" ]
null
null
null
gui/MyCanvas.cpp
myirci/3d_circle_estimation
7161005ab14d510503310e0bb028fea5ad2a1389
[ "MIT" ]
1
2021-04-08T13:49:32.000Z
2021-04-08T13:49:32.000Z
#include "MyCanvas.hpp" #include "MyFrame.hpp" #include "../geometry/Segment3D.hpp" #include "../geometry/Circle3D.hpp" #include "../data/teapot.hpp" #include "../algorithm/algorithm.hpp" #include "../utility/utility.hpp" #include <sstream> BEGIN_EVENT_TABLE(MyCanvas, wxScrolledWindow) EVT_PAINT(MyCanvas::OnPaint) EVT_LEFT_DOWN(MyCanvas::OnMouseLeftClick) EVT_RIGHT_DOWN(MyCanvas::OnMouseRightClick) EVT_MOTION(MyCanvas::OnMouseMove) EVT_KEY_DOWN(MyCanvas::OnKeyDown) EVT_SIZE(MyCanvas::OnResize) END_EVENT_TABLE() MyCanvas::MyCanvas(MyFrame* parent) : wxScrolledWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxHSCROLL | wxVSCROLL | wxFULL_REPAINT_ON_RESIZE), m_parent(parent) { wxSize size = m_parent->GetClientSize(); m_renderer.set_screen_width_and_height(size.GetWidth(), size.GetHeight()); m_render_mode = render_mode::two_dim; m_renderer.gluPerspective(45.0, 1.0, 100.0); SetBackgroundColour(wxColour(*wxWHITE)); Eigen::Vector3d normal(-1, 2, -3); normal.normalize(); Circle3D circ(Eigen::Vector3d(1, 2, -8), // center normal, // normal 1.0); // radius std::cout << "Ground truth circle normal:\n " << normal << std::endl; m_groud_truth_3DCircles.push_back(circ); std::cout << "Ground truth circle center:\n" << circ.center << std::endl; } void MyCanvas::Estimate_3DCircles(estimation_algorithm method) { if(method == estimation_algorithm::method_1) { estimate_3d_circles_1(); } else if(method == estimation_algorithm::method_2) { estimate_3d_circles_2(); } else if(method == estimation_algorithm::method_3) { estimate_3d_circles_3(); } else if(method == estimation_algorithm::method_4) { estimate_3d_circles_4(); } } void MyCanvas::estimate_3d_circles_1() { Eigen::Matrix4d mat = Eigen::Matrix4d::Identity(); m_renderer.get_projection_matrix(mat); Circle3D circles[2]; circles[0].radius = 1.0; circles[1].radius = 1.0; int h{0}, w{0}; this->GetSize(&w, &h); for(auto it = m_ellipses.begin(); it != m_ellipses.end(); ++it) { it->calculate_algebraic_equation_in_normalized_device_coordinates(w, h); // it->calculate_algebraic_equation_in_projected_coordinates(w, h, 1, deg2rad(45.0/2.0)); estimate_3D_circles_under_perspective_transformation_method_1(mat, *it, circles); m_3DCircles.push_back(circles[0]); m_3DCircles.push_back(circles[1]); } } void MyCanvas::estimate_3d_circles_2() { Circle3D circle[4]; circle[0].radius = 1.0; circle[1].radius = 1.0; circle[2].radius = 1.0; circle[3].radius = 1.0; int h{0}, w{0}; this->GetSize(&w, &h); for(auto it = m_ellipses.begin(); it != m_ellipses.end(); ++it) { it->calculate_algebraic_equation_in_projected_coordinates(w, h, 1, deg2rad(45.0/2.0)); estimate_3D_circles_under_perspective_transformation_method_2(*it, circle, -1); if(circle[0].center(2) <= -1) { m_3DCircles.push_back(circle[0]); std::cout << "Circle-1: Valid" << std::endl; } if(circle[1].center(2) <= -1) { m_3DCircles.push_back(circle[1]); std::cout << "Circle-2: Valid" << std::endl; } if(circle[2].center(2) <= -1) { m_3DCircles.push_back(circle[2]); std::cout << "Circle-3: Valid" << std::endl; } if(circle[3].center(2) <= -1) { m_3DCircles.push_back(circle[3]); std::cout << "Circle-4: Valid" << std::endl; } } } void MyCanvas::estimate_3d_circles_3() { Circle3D circle[8]; circle[0].radius = 1.0; circle[1].radius = 1.0; circle[2].radius = 1.0; circle[3].radius = 1.0; circle[4].radius = 1.0; circle[5].radius = 1.0; circle[6].radius = 1.0; circle[7].radius = 1.0; Eigen::Matrix4d mat = Eigen::Matrix4d::Identity(); m_renderer.get_pure_projection_matrix(mat); Eigen::Matrix3d mat2; mat2.row(0) = mat.block(0,0,1,3); mat2.row(1) = mat.block(1,0,1,3); mat2.row(2) = mat.block(3,0,1,3); int h{0}, w{0}; this->GetSize(&w, &h); for(auto it = m_ellipses.begin(); it != m_ellipses.end(); ++it) { it->calculate_algebraic_equation_in_projected_coordinates(w, h, 1, deg2rad(45.0/2.0)); estimate_3D_circles_under_perspective_transformation_method_3(mat2, *it, circle); m_3DCircles.push_back(circle[0]); m_3DCircles.push_back(circle[1]); m_3DCircles.push_back(circle[2]); m_3DCircles.push_back(circle[3]); m_3DCircles.push_back(circle[4]); m_3DCircles.push_back(circle[5]); m_3DCircles.push_back(circle[6]); m_3DCircles.push_back(circle[7]); } } void MyCanvas::estimate_3d_circles_4() { Circle3D circle[4]; circle[0].radius = 1.0; circle[1].radius = 1.0; circle[2].radius = 1.0; circle[3].radius = 1.0; int h{0}, w{0}; this->GetSize(&w, &h); for(auto it = m_ellipses.begin(); it != m_ellipses.end(); ++it) { it->calculate_algebraic_equation_in_projected_coordinates(w, h, 1, deg2rad(45.0/2.0)); int count = estimate_3D_circles_under_perspective_transformation_method_4(*it, circle, -1); if(count == 4) { if(circle[0].center(2) <= -1) { m_3DCircles.push_back(circle[0]); std::cout << "Circle-1: Valid" << std::endl; } if(circle[1].center(2) <= -1) { m_3DCircles.push_back(circle[1]); std::cout << "Circle-2: Valid" << std::endl; } if(circle[2].center(2) <= -1) { m_3DCircles.push_back(circle[2]); std::cout << "Circle-3: Valid" << std::endl; } if(circle[3].center(2) <= -1) { m_3DCircles.push_back(circle[3]); std::cout << "Circle-4: Valid" << std::endl; } } else if(count == 1) { if(circle[0].center(2) <= -1) { m_3DCircles.push_back(circle[0]); std::cout << "Circle-1: Valid" << std::endl; } } } } void MyCanvas::SetRenderingMode(render_mode mode) { m_render_mode = mode; Refresh(); } void MyCanvas::OnPaint(wxPaintEvent& event) { wxPaintDC dc(this); dc.SetBrush(*wxTRANSPARENT_BRUSH); SetupCoordinateFrame(dc); if(m_render_mode == render_mode::two_dim) { Render2D(dc); } else if(m_render_mode == render_mode::three_dim) { Render3D(dc); } else if(m_render_mode == render_mode::both) { Render2D(dc); Render3D(dc); } } void MyCanvas::Render2D(wxPaintDC& dc) { dc.SetPen(*wxBLUE_PEN); if(!m_ellipses.empty()) { RenderEllipses(dc); } if(!m_points.empty()) { RenderEllipse(dc); } } void MyCanvas::Render3D(wxPaintDC& dc) { dc.SetPen(wxPen(*wxRED, 3)); std::vector<Eigen::Vector3d> data; for(auto it = m_3DCircles.begin(); it != m_3DCircles.end(); ++it) { data.clear(); it->generate_data(data, 8); m_renderer.render(data, dc); } dc.SetPen(wxPen(*wxCYAN, 3)); for(auto it = m_groud_truth_3DCircles.begin(); it != m_groud_truth_3DCircles.end(); ++it) { data.clear(); it->generate_data(data, 100); m_renderer.render(data, dc); } } void MyCanvas::SetupCoordinateFrame(wxPaintDC& dc) { wxSize size = m_parent->GetClientSize(); dc.SetAxisOrientation(true, true); dc.SetDeviceOrigin(size.GetWidth()/2, size.GetHeight()/2); dc.DrawLine(-size.GetWidth()/2,0,size.GetWidth()/2,0); dc.DrawLine(0,-size.GetHeight()/2,0,size.GetHeight()/2); } void MyCanvas::RenderEllipse(wxPaintDC& dc) { if(m_points.size() == 1) { dc.DrawLine(m_points[0], m_mouse_pos); Point2D<double> p0(m_points[0].x, m_points[0].y); Point2D<double> center((m_points[0].x + m_mouse_pos.x)/2.0, (m_points[0].y + m_mouse_pos.y)/2.0); dc.DrawCircle(static_cast<int>(center.x), static_cast<int>(center.y), dist(p0, center)); } else if(m_points.size() == 2) { Point2D<double> p0(m_points[0].x, m_points[0].y); Point2D<double> p1(m_points[1].x, m_points[1].y); Point2D<double> center((p0.x + p1.x)/2, (p0.y + p1.y)/2); double smajor_axis = dist(p0, center); double sminor_axis = 0.0; Vector2D<double> vec_mj = p1 - p0; Vector2D<double> vec_mn(-vec_mj.y, vec_mj.x); Vector2D<double> minor_unit = vec_mn.normalized(); Point2D<double> p2 = center - smajor_axis*minor_unit; Point2D<double> p3 = center + smajor_axis*minor_unit; Point2D<double> mouse_pos(m_mouse_pos.x, m_mouse_pos.y); Vector2D<double> mouse_vec = mouse_pos - p2; double ratio = vec_mn.dot(mouse_vec) / vec_mn.dot(vec_mn); if(ratio >= 0.0 && ratio <= 1.0) { Vector2D<double> proj_vec = (2*ratio*smajor_axis) * minor_unit; Point2D<double> proj_point = p2 + proj_vec; sminor_axis = dist(center, proj_point); // draw a mini circle on the projection point dc.DrawCircle(static_cast<int>(proj_point.x), static_cast<int>(proj_point.y), 2); m_ellipse.center = Point2D<double>(center.x, center.y); m_ellipse.semi_major_axis = smajor_axis; m_ellipse.semi_minor_axis = sminor_axis; if(vec_mj.y > 0) { m_ellipse.rot_angle = std::acos(vec_mj.x/vec_mj.norm()); } else { m_ellipse.rot_angle = -std::acos(vec_mj.x/vec_mj.norm()); } double data[80]; m_ellipse.generate_points_on_the_ellipse(40, data); for(int i = 0; i < 78; i += 2) { dc.DrawLine(static_cast<int>(data[i]), static_cast<int>(data[i+1]), static_cast<int>(data[i+2]), static_cast<int>(data[i+3])); } dc.DrawLine(static_cast<int>(data[0]), static_cast<int>(data[1]), static_cast<int>(data[78]), static_cast<int>(data[79])); m_ellipse.points[2] = proj_point; DisplayAlgebraicEquation(); } // Draw the end points dc.DrawCircle(static_cast<int>(p0.x), static_cast<int>(p0.y), 2); dc.DrawCircle(static_cast<int>(p1.x), static_cast<int>(p1.y), 2); dc.DrawCircle(static_cast<int>(center.x), static_cast<int>(center.y), 2); dc.DrawCircle(static_cast<int>(p2.x), static_cast<int>(p2.y), 2); dc.DrawCircle(static_cast<int>(p3.x), static_cast<int>(p3.y), 2); // draw the major axis and minor axis guide line dc.DrawLine(static_cast<int>(p0.x), static_cast<int>(p0.y), static_cast<int>(p1.x), static_cast<int>(p1.y)); dc.SetPen(*wxBLACK_DASHED_PEN); dc.DrawLine(static_cast<int>(p2.x), static_cast<int>(p2.y), static_cast<int>(p3.x), static_cast<int>(p3.y)); } else { m_points.clear(); } } void MyCanvas::RenderEllipses(wxPaintDC& dc) { const int num = 80; const int size = num*2; double data[size]; for(auto it = m_ellipses.begin(); it != m_ellipses.end(); ++it){ it->generate_points_on_the_ellipse(num, data); for(int i = 0; i < size-2; i+= 2) { dc.DrawLine(static_cast<int>(data[i]), static_cast<int>(data[i+1]), static_cast<int>(data[i+2]), static_cast<int>(data[i+3])); } dc.DrawLine(static_cast<int>(data[0]), static_cast<int>(data[1]), static_cast<int>(data[size-2]), static_cast<int>(data[size-1])); } } void MyCanvas::DisplayAlgebraicEquation() { m_ellipse.calculate_algebraic_equation_in_wxWidget_coordinates(); wxString str; str << "(" << m_ellipse.coeff[0] << "xx) + " << "(" << m_ellipse.coeff[1] << "xy) + " << "(" << m_ellipse.coeff[2] << "yy) + " << "(" << m_ellipse.coeff[3] << "x) + " << "(" << m_ellipse.coeff[4] << "y) + " << "(" << m_ellipse.coeff[5] << ")"; m_parent->SetStatusText(str, 2); wxString str2; str2 << rad2deg(m_ellipse.rot_angle); m_parent->SetStatusText(str2, 1); } void MyCanvas::OnMouseLeftClick(wxMouseEvent& event) { m_points.push_back(DeviceToLogical(event.GetPosition())); Refresh(); } void MyCanvas::OnMouseRightClick(wxMouseEvent& event) { if(m_points.size() == 2) { m_ellipse.points[0] = Point2D<double>(m_points[0].x, m_points[0].y); m_ellipse.points[1] = Point2D<double>(m_points[1].x, m_points[1].y); m_ellipses.push_back(m_ellipse); } m_points.clear(); Refresh(); } void MyCanvas::OnMouseMove(wxMouseEvent& event) { m_mouse_pos = DeviceToLogical(event.GetPosition()); wxString str; str << "(" << m_mouse_pos.x << ", " << m_mouse_pos.y << ")"; m_parent->SetStatusText(str, 0); Refresh(); } void MyCanvas::OnKeyDown(wxKeyEvent &event) { if(event.GetKeyCode() == WXK_ESCAPE) { m_points.clear(); m_ellipses.clear(); m_3DCircles.clear(); Refresh(); } } void MyCanvas::OnResize(wxSizeEvent& event) { m_renderer.set_screen_width_and_height(event.GetSize().GetWidth(), event.GetSize().GetHeight()); } wxPoint MyCanvas::DeviceToLogical(const wxPoint& pt) { wxSize size = m_parent->GetClientSize(); return wxPoint(pt.x - (size.GetWidth()-1)/2, (size.GetHeight()-1)/2 - pt.y); } wxPoint MyCanvas::LogicalToDevice(const wxPoint& pt) { wxSize size = m_parent->GetClientSize(); return wxPoint(pt.x + (size.GetWidth()-1)/2, (size.GetHeight()-1)/2 - pt.y); }
36.645078
99
0.584305
myirci
29088db725c733564a3ab404aaadbd702b53dc0b
465
hpp
C++
SDKUsage6/VBMapViewer-SKT/VbNavKit-iOS/Classes/vbCamera/vbRotateCameraControl.hpp
longxingtianxiaShuai/specialView
42fbdb1ee94fc0bd0c903e3c72c23808ec608139
[ "MIT" ]
1
2020-11-21T03:54:34.000Z
2020-11-21T03:54:34.000Z
SDKUsage6/VBMapViewer-SKT/VbNavKit-iOS/Classes/vbCamera/vbRotateCameraControl.hpp
longxingtianxiaShuai/specialView
42fbdb1ee94fc0bd0c903e3c72c23808ec608139
[ "MIT" ]
null
null
null
SDKUsage6/VBMapViewer-SKT/VbNavKit-iOS/Classes/vbCamera/vbRotateCameraControl.hpp
longxingtianxiaShuai/specialView
42fbdb1ee94fc0bd0c903e3c72c23808ec608139
[ "MIT" ]
3
2017-12-14T00:52:03.000Z
2019-08-08T22:25:04.000Z
// // vbRotateCameraControl.h // VbNavKit-iOS // // Created by Dev4_Air on 13. 2. 7.. // Copyright (c) 2013년 dev4. All rights reserved. // #ifndef VbNavKit_iOS_vbRotateCameraControl_h #define VbNavKit_iOS_vbRotateCameraControl_h #include "vbCameraControl.hpp" class vbRotateCameraControl : public vbCameraControl { public: vbRotateCameraControl(); ~vbRotateCameraControl(); public: virtual Quaternion GetOrientation() = 0; }; #endif
17.222222
52
0.729032
longxingtianxiaShuai
2908a8e881420630cf31cd4c76ccbd2eae643da3
1,768
cpp
C++
BasicGameFramework/Util/CSound.cpp
dlwlxns4/WitchHouse
7b2fd8acead69baa9b0850e0ddcb7520b32ef47e
[ "BSD-3-Clause" ]
null
null
null
BasicGameFramework/Util/CSound.cpp
dlwlxns4/WitchHouse
7b2fd8acead69baa9b0850e0ddcb7520b32ef47e
[ "BSD-3-Clause" ]
null
null
null
BasicGameFramework/Util/CSound.cpp
dlwlxns4/WitchHouse
7b2fd8acead69baa9b0850e0ddcb7520b32ef47e
[ "BSD-3-Clause" ]
null
null
null
#include "CSound.h" FMOD_SYSTEM* CSound::g_sound_system; CSound::CSound(const char* path, bool loop) { if (loop) { FMOD_System_CreateSound(g_sound_system, path, FMOD_LOOP_NORMAL, 0, &m_sound); } else { FMOD_System_CreateSound(g_sound_system, path, FMOD_DEFAULT, 0, &m_sound); } m_channel = nullptr; m_volume = SOUND_DEFAULT; } CSound::~CSound() { FMOD_Sound_Release(m_sound); } void CSound::Init() { FMOD_System_Create(&g_sound_system); FMOD_System_Init(g_sound_system, 32, FMOD_INIT_NORMAL, nullptr); } void CSound::Release() { FMOD_System_Close(g_sound_system); FMOD_System_Release(g_sound_system); } bool CSound::play() { if (isPlay == false) { isPlay = true; FMOD_System_PlaySound(g_sound_system, m_sound, nullptr, false, &m_channel); return true; } return false; } void CSound::InfPlay() { FMOD_System_PlaySound(g_sound_system, m_sound, nullptr, false, &m_channel); } void CSound::pause() { FMOD_Channel_SetPaused(m_channel, true); } void CSound::resume() { isPlay = true; FMOD_Channel_SetPaused(m_channel, false); } void CSound::stop() { isPlay = false; FMOD_Channel_Stop(m_channel); } void CSound::volumeUp() { if (m_volume < SOUND_MAX) { m_volume += SOUND_WEIGHT; } FMOD_Channel_SetVolume(m_channel, m_volume); } void CSound::volumeDown() { if (m_volume > SOUND_MIN) { m_volume -= SOUND_WEIGHT; } FMOD_Channel_SetVolume(m_channel, m_volume); } void CSound::volumeFadeUp() { isVolumeUp = true; } void CSound::SetVolume(float volume) { this->m_volume = volume; } void CSound::Update() { FMOD_Channel_IsPlaying(m_channel, &m_bool); if (m_bool) { FMOD_System_Update(g_sound_system); } if (isVolumeUp) { volumeUp(); if (m_volume >= 1.0f) { isVolumeUp = false; } } }
14.857143
79
0.70871
dlwlxns4
290a0054e7be1cf8c2404752c65901ae15016fb0
66,168
cc
C++
Validation/MtdValidation/plugins/Primary4DVertexValidation.cc
wonpoint4/cmssw
4095d8106ef881c8b3be12b696bc364ae911d01f
[ "Apache-2.0" ]
2
2020-10-26T18:40:32.000Z
2021-04-10T16:33:25.000Z
Validation/MtdValidation/plugins/Primary4DVertexValidation.cc
gartung/cmssw
3072dde3ce94dcd1791d778988198a44cde02162
[ "Apache-2.0" ]
30
2015-11-04T11:42:27.000Z
2021-12-01T07:56:34.000Z
Validation/MtdValidation/plugins/Primary4DVertexValidation.cc
gartung/cmssw
3072dde3ce94dcd1791d778988198a44cde02162
[ "Apache-2.0" ]
8
2016-03-25T07:17:43.000Z
2021-07-08T17:11:21.000Z
#include <numeric> #include <string> #include <vector> #include <map> #include <algorithm> #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Framework/interface/ESHandle.h" #include "DataFormats/Common/interface/ValidHandle.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "DataFormats/Math/interface/LorentzVector.h" #include "DataFormats/Math/interface/Point3D.h" // reco track and vertex #include "DataFormats/TrackReco/interface/Track.h" #include "DataFormats/TrackReco/interface/TrackFwd.h" #include "DataFormats/VertexReco/interface/Vertex.h" #include "DataFormats/VertexReco/interface/VertexFwd.h" #include "RecoVertex/VertexPrimitives/interface/TransientVertex.h" // TrackingParticle #include "SimDataFormats/TrackingAnalysis/interface/TrackingParticle.h" #include "SimDataFormats/Associations/interface/TrackToTrackingParticleAssociator.h" #include "SimDataFormats/TrackingAnalysis/interface/TrackingParticleFwd.h" #include "SimDataFormats/TrackingAnalysis/interface/TrackingVertexContainer.h" // pile-up #include "SimDataFormats/PileupSummaryInfo/interface/PileupSummaryInfo.h" // associator #include "SimTracker/VertexAssociation/interface/calculateVertexSharedTracks.h" // vertexing #include "RecoVertex/PrimaryVertexProducer/interface/TrackFilterForPVFinding.h" // simulated vertex #include "SimDataFormats/Associations/interface/VertexToTrackingVertexAssociator.h" // DQM #include "DQMServices/Core/interface/DQMEDAnalyzer.h" #include "DQMServices/Core/interface/DQMStore.h" #include "DataFormats/Math/interface/deltaR.h" //class declaration class Primary4DVertexValidation : public DQMEDAnalyzer { typedef math::XYZTLorentzVector LorentzVector; // auxiliary class holding simulated vertices struct simPrimaryVertex { simPrimaryVertex(double x1, double y1, double z1, double t1) : x(x1), y(y1), z(z1), t(t1), ptsq(0), closest_vertex_distance_z(-1.), nGenTrk(0), num_matched_reco_tracks(0), average_match_quality(0.0) { ptot.setPx(0); ptot.setPy(0); ptot.setPz(0); ptot.setE(0); p4 = LorentzVector(0, 0, 0, 0); r = sqrt(x * x + y * y); }; double x, y, z, r, t; HepMC::FourVector ptot; LorentzVector p4; double ptsq; double closest_vertex_distance_z; int nGenTrk; int num_matched_reco_tracks; float average_match_quality; EncodedEventId eventId; TrackingVertexRef sim_vertex; int OriginalIndex = -1; unsigned int nwosmatch = 0; // number of recvertices dominated by this simevt (by wos) unsigned int nwntmatch = 0; // number of recvertices dominated by this simevt (by nt) std::vector<unsigned int> wos_dominated_recv; // list of dominated recv (by wos, size==nwosmatch) std::map<unsigned int, double> wnt; // weighted number of tracks in recvtx (by index) std::map<unsigned int, double> wos; // sum of wos in recvtx (by index) // oops -> this was int before 04-22 double sumwos = 0; // sum of wos in any recvtx double sumwnt = 0; // sum of weighted tracks unsigned int rec = NOT_MATCHED; // best match (NO_MATCH if not matched) unsigned int matchQuality = 0; // quality flag void addTrack(unsigned int irecv, double twos, double twt) { sumwnt += twt; if (wnt.find(irecv) == wnt.end()) { wnt[irecv] = twt; } else { wnt[irecv] += twt; } sumwos += twos; if (wos.find(irecv) == wos.end()) { wos[irecv] = twos; } else { wos[irecv] += twos; } } }; // auxiliary class holding reconstructed vertices struct recoPrimaryVertex { recoPrimaryVertex(double x1, double y1, double z1) : x(x1), y(y1), z(z1), pt(0), ptsq(0), closest_vertex_distance_z(-1.), nRecoTrk(0), num_matched_sim_tracks(0), recVtx(nullptr) { r = sqrt(x * x + y * y); }; double x, y, z, r; double pt; double ptsq; double closest_vertex_distance_z; int nRecoTrk; int num_matched_sim_tracks; const reco::Vertex* recVtx; reco::VertexBaseRef recVtxRef; int OriginalIndex = -1; std::map<unsigned int, double> wos; // simevent -> wos std::map<unsigned int, double> wnt; // simevent -> weighted number of truth matched tracks unsigned int wosmatch; // index of the simevent providing the largest contribution to wos unsigned int wntmatch; // index of the simevent providing the highest number of tracks double sumwos = 0; // total sum of wos of all truth matched tracks double sumwnt = 0; // total weighted number of truth matchted tracks double maxwos = 0; // largest wos sum from one sim event (wosmatch) double maxwnt = 0; // largest weighted number of tracks from one sim event (ntmatch) int maxwosnt = 0; // number of tracks from the simevt with highest wos unsigned int sim = NOT_MATCHED; // best match (NO_MATCH if not matched) unsigned int matchQuality = 0; // quality flag bool is_real() { return (matchQuality > 0) && (matchQuality < 99); } bool is_fake() { return (matchQuality <= 0) || (matchQuality >= 99); } bool is_signal() { return (sim == 0); } int split_from() { if (is_real()) return -1; if ((maxwos > 0) && (maxwos > 0.3 * sumwos)) return wosmatch; return -1; } bool other_fake() { return (is_fake() & (split_from() < 0)); } void addTrack(unsigned int iev, double twos, double wt) { sumwnt += wt; if (wnt.find(iev) == wnt.end()) { wnt[iev] = wt; } else { wnt[iev] += wt; } sumwos += twos; if (wos.find(iev) == wos.end()) { wos[iev] = twos; } else { wos[iev] += twos; } } }; public: explicit Primary4DVertexValidation(const edm::ParameterSet&); ~Primary4DVertexValidation() override; static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); void analyze(const edm::Event&, const edm::EventSetup&) override; void bookHistograms(DQMStore::IBooker& i, edm::Run const&, edm::EventSetup const&) override; private: void matchReco2Sim(std::vector<recoPrimaryVertex>&, std::vector<simPrimaryVertex>&, const edm::ValueMap<float>&, const edm::ValueMap<float>&, const edm::Handle<reco::BeamSpot>&); bool matchRecoTrack2SimSignal(const reco::TrackBaseRef&); const edm::Ref<std::vector<TrackingParticle>>* getMatchedTP(const reco::TrackBaseRef&, const TrackingVertexRef&); double timeFromTrueMass(double, double, double, double); bool select(const reco::Vertex&, int level = 0); std::vector<Primary4DVertexValidation::simPrimaryVertex> getSimPVs(const edm::Handle<TrackingVertexCollection>&); std::vector<Primary4DVertexValidation::recoPrimaryVertex> getRecoPVs(const edm::Handle<edm::View<reco::Vertex>>&); const bool mvaTPSel(const TrackingParticle&); const bool mvaRecSel(const reco::TrackBase&, const reco::Vertex&, const double&, const double&); // ----------member data --------------------------- const std::string folder_; static constexpr unsigned int NOT_MATCHED = 66666; static constexpr double simUnit_ = 1e9; //sim time in s while reco time in ns static constexpr double c_ = 2.99792458e1; //c in cm/ns static constexpr double mvaL_ = 0.5; //MVA cuts for MVA categories static constexpr double mvaH_ = 0.8; static constexpr double selNdof_ = 4.; static constexpr double maxRank_ = 8.; static constexpr double maxTry_ = 10.; static constexpr double zWosMatchMax_ = 1.; static constexpr double etacutGEN_ = 4.; // |eta| < 4; static constexpr double etacutREC_ = 3.; // |eta| < 3; static constexpr double pTcut_ = 0.7; // PT > 0.7 GeV static constexpr double deltaZcut_ = 0.1; // dz separation 1 mm const double trackweightTh_; const double mvaTh_; const std::vector<double> lineDensityPar_; const reco::RecoToSimCollection* r2s_; const reco::SimToRecoCollection* s2r_; edm::EDGetTokenT<reco::TrackCollection> RecTrackToken_; edm::EDGetTokenT<std::vector<PileupSummaryInfo>> vecPileupSummaryInfoToken_; edm::EDGetTokenT<TrackingParticleCollection> trackingParticleCollectionToken_; edm::EDGetTokenT<TrackingVertexCollection> trackingVertexCollectionToken_; edm::EDGetTokenT<reco::SimToRecoCollection> simToRecoAssociationToken_; edm::EDGetTokenT<reco::RecoToSimCollection> recoToSimAssociationToken_; edm::EDGetTokenT<reco::BeamSpot> RecBeamSpotToken_; edm::EDGetTokenT<edm::View<reco::Vertex>> Rec4DVerToken_; edm::EDGetTokenT<edm::ValueMap<int>> trackAssocToken_; edm::EDGetTokenT<edm::ValueMap<float>> pathLengthToken_; edm::EDGetTokenT<edm::ValueMap<float>> momentumToken_; edm::EDGetTokenT<edm::ValueMap<float>> timeToken_; edm::EDGetTokenT<edm::ValueMap<float>> t0SafePidToken_; edm::EDGetTokenT<edm::ValueMap<float>> sigmat0SafePidToken_; edm::EDGetTokenT<edm::ValueMap<float>> trackMVAQualToken_; bool use_only_charged_tracks_; bool debug_; bool optionalPlots_; //histogram declaration MonitorElement* meMVATrackEffPtTot_; MonitorElement* meMVATrackMatchedEffPtTot_; MonitorElement* meMVATrackMatchedEffPtMtd_; MonitorElement* meMVATrackEffEtaTot_; MonitorElement* meMVATrackMatchedEffEtaTot_; MonitorElement* meMVATrackMatchedEffEtaMtd_; MonitorElement* meMVATrackResTot_; MonitorElement* meMVATrackPullTot_; MonitorElement* meTrackResTot_; MonitorElement* meTrackPullTot_; MonitorElement* meTrackRes_[3]; MonitorElement* meTrackPull_[3]; MonitorElement* meTrackResMass_[3]; MonitorElement* meTrackResMassTrue_[3]; MonitorElement* meMVATrackZposResTot_; MonitorElement* meTrackZposResTot_; MonitorElement* meTrackZposRes_[3]; MonitorElement* meTrack3DposRes_[3]; MonitorElement* meTimeRes_; MonitorElement* meTimePull_; MonitorElement* meTimeSignalRes_; MonitorElement* meTimeSignalPull_; MonitorElement* mePUvsRealV_; MonitorElement* mePUvsOtherFakeV_; MonitorElement* mePUvsSplitV_; MonitorElement* meMatchQual_; MonitorElement* meDeltaZrealreal_; MonitorElement* meDeltaZfakefake_; MonitorElement* meDeltaZfakereal_; MonitorElement* meDeltaTrealreal_; MonitorElement* meDeltaTfakefake_; MonitorElement* meDeltaTfakereal_; MonitorElement* meRecoPosInSimCollection_; MonitorElement* meRecoPosInRecoOrigCollection_; MonitorElement* meSimPosInSimOrigCollection_; MonitorElement* meRecoPVPosSignal_; MonitorElement* meRecoPVPosSignalNotHighestPt_; MonitorElement* meRecoVtxVsLineDensity_; MonitorElement* meRecVerNumber_; MonitorElement* meRecPVZ_; MonitorElement* meRecPVT_; MonitorElement* meSimPVZ_; //some tests MonitorElement* meTrackResLowPTot_; MonitorElement* meTrackResHighPTot_; MonitorElement* meTrackPullLowPTot_; MonitorElement* meTrackPullHighPTot_; MonitorElement* meTrackResLowP_[3]; MonitorElement* meTrackResHighP_[3]; MonitorElement* meTrackPullLowP_[3]; MonitorElement* meTrackPullHighP_[3]; MonitorElement* meTrackResMassProtons_[3]; MonitorElement* meTrackResMassTrueProtons_[3]; MonitorElement* meTrackResMassPions_[3]; MonitorElement* meTrackResMassTruePions_[3]; }; // constructors and destructor Primary4DVertexValidation::Primary4DVertexValidation(const edm::ParameterSet& iConfig) : folder_(iConfig.getParameter<std::string>("folder")), trackweightTh_(iConfig.getParameter<double>("trackweightTh")), mvaTh_(iConfig.getParameter<double>("mvaTh")), lineDensityPar_(iConfig.getParameter<std::vector<double>>("lineDensityPar")), use_only_charged_tracks_(iConfig.getParameter<bool>("useOnlyChargedTracks")), debug_(iConfig.getUntrackedParameter<bool>("debug")), optionalPlots_(iConfig.getUntrackedParameter<bool>("optionalPlots")) { vecPileupSummaryInfoToken_ = consumes<std::vector<PileupSummaryInfo>>(edm::InputTag(std::string("addPileupInfo"))); trackingParticleCollectionToken_ = consumes<TrackingParticleCollection>(iConfig.getParameter<edm::InputTag>("SimTag")); trackingVertexCollectionToken_ = consumes<TrackingVertexCollection>(iConfig.getParameter<edm::InputTag>("SimTag")); simToRecoAssociationToken_ = consumes<reco::SimToRecoCollection>(iConfig.getParameter<edm::InputTag>("TPtoRecoTrackAssoc")); recoToSimAssociationToken_ = consumes<reco::RecoToSimCollection>(iConfig.getParameter<edm::InputTag>("TPtoRecoTrackAssoc")); RecTrackToken_ = consumes<reco::TrackCollection>(iConfig.getParameter<edm::InputTag>("mtdTracks")); RecBeamSpotToken_ = consumes<reco::BeamSpot>(iConfig.getParameter<edm::InputTag>("offlineBS")); Rec4DVerToken_ = consumes<edm::View<reco::Vertex>>(iConfig.getParameter<edm::InputTag>("offline4DPV")); trackAssocToken_ = consumes<edm::ValueMap<int>>(iConfig.getParameter<edm::InputTag>("trackAssocSrc")); pathLengthToken_ = consumes<edm::ValueMap<float>>(iConfig.getParameter<edm::InputTag>("pathLengthSrc")); momentumToken_ = consumes<edm::ValueMap<float>>(iConfig.getParameter<edm::InputTag>("momentumSrc")); timeToken_ = consumes<edm::ValueMap<float>>(iConfig.getParameter<edm::InputTag>("timeSrc")); t0SafePidToken_ = consumes<edm::ValueMap<float>>(iConfig.getParameter<edm::InputTag>("t0SafePID")); sigmat0SafePidToken_ = consumes<edm::ValueMap<float>>(iConfig.getParameter<edm::InputTag>("sigmat0SafePID")); trackMVAQualToken_ = consumes<edm::ValueMap<float>>(iConfig.getParameter<edm::InputTag>("trackMVAQual")); } Primary4DVertexValidation::~Primary4DVertexValidation() {} // // member functions // void Primary4DVertexValidation::bookHistograms(DQMStore::IBooker& ibook, edm::Run const& iRun, edm::EventSetup const& iSetup) { ibook.setCurrentFolder(folder_); // --- histograms booking meMVATrackEffPtTot_ = ibook.book1D("MVAEffPtTot", "Pt of tracks associated to LV; track pt [GeV] ", 110, 0., 11.); meMVATrackEffEtaTot_ = ibook.book1D("MVAEffEtaTot", "Pt of tracks associated to LV; track eta ", 66, 0., 3.3); meMVATrackMatchedEffPtTot_ = ibook.book1D("MVAMatchedEffPtTot", "Pt of tracks associated to LV matched to TP; track pt [GeV] ", 110, 0., 11.); meMVATrackMatchedEffPtMtd_ = ibook.book1D( "MVAMatchedEffPtMtd", "Pt of tracks associated to LV matched to TP with time; track pt [GeV] ", 110, 0., 11.); meMVATrackMatchedEffEtaTot_ = ibook.book1D("MVAMatchedEffEtaTot", "Pt of tracks associated to LV matched to TP; track eta ", 66, 0., 3.3); meMVATrackMatchedEffEtaMtd_ = ibook.book1D( "MVAMatchedEffEtaMtd", "Pt of tracks associated to LV matched to TP with time; track eta ", 66, 0., 3.3); meMVATrackResTot_ = ibook.book1D( "MVATrackRes", "t_{rec} - t_{sim} for tracks from LV MVA sel.; t_{rec} - t_{sim} [ns] ", 120, -0.15, 0.15); meTrackResTot_ = ibook.book1D("TrackRes", "t_{rec} - t_{sim} for tracks; t_{rec} - t_{sim} [ns] ", 120, -0.15, 0.15); meTrackRes_[0] = ibook.book1D( "TrackRes-LowMVA", "t_{rec} - t_{sim} for tracks with MVA < 0.5; t_{rec} - t_{sim} [ns] ", 100, -1., 1.); meTrackRes_[1] = ibook.book1D( "TrackRes-MediumMVA", "t_{rec} - t_{sim} for tracks with 0.5 < MVA < 0.8; t_{rec} - t_{sim} [ns] ", 100, -1., 1.); meTrackRes_[2] = ibook.book1D( "TrackRes-HighMVA", "t_{rec} - t_{sim} for tracks with MVA > 0.8; t_{rec} - t_{sim} [ns] ", 100, -1., 1.); if (optionalPlots_) { meTrackResMass_[0] = ibook.book1D( "TrackResMass-LowMVA", "t_{rec} - t_{est} for tracks with MVA < 0.5; t_{rec} - t_{est} [ns] ", 100, -1., 1.); meTrackResMass_[1] = ibook.book1D("TrackResMass-MediumMVA", "t_{rec} - t_{est} for tracks with 0.5 < MVA < 0.8; t_{rec} - t_{est} [ns] ", 100, -1., 1.); meTrackResMass_[2] = ibook.book1D( "TrackResMass-HighMVA", "t_{rec} - t_{est} for tracks with MVA > 0.8; t_{rec} - t_{est} [ns] ", 100, -1., 1.); meTrackResMassTrue_[0] = ibook.book1D( "TrackResMassTrue-LowMVA", "t_{est} - t_{sim} for tracks with MVA < 0.5; t_{est} - t_{sim} [ns] ", 100, -1., 1.); meTrackResMassTrue_[1] = ibook.book1D("TrackResMassTrue-MediumMVA", "t_{est} - t_{sim} for tracks with 0.5 < MVA < 0.8; t_{est} - t_{sim} [ns] ", 100, -1., 1.); meTrackResMassTrue_[2] = ibook.book1D("TrackResMassTrue-HighMVA", "t_{est} - t_{sim} for tracks with MVA > 0.8; t_{est} - t_{sim} [ns] ", 100, -1., 1.); } meMVATrackPullTot_ = ibook.book1D("MVATrackPull", "Pull for tracks from LV MAV sel.; (t_{rec}-t_{sim})/#sigma_{t}", 50, -5., 5.); meTrackPullTot_ = ibook.book1D("TrackPull", "Pull for tracks; (t_{rec}-t_{sim})/#sigma_{t}", 100, -10., 10.); meTrackPull_[0] = ibook.book1D("TrackPull-LowMVA", "Pull for tracks with MVA < 0.5; (t_{rec}-t_{sim})/#sigma_{t}", 100, -10., 10.); meTrackPull_[1] = ibook.book1D( "TrackPull-MediumMVA", "Pull for tracks with 0.5 < MVA < 0.8; (t_{rec}-t_{sim})/#sigma_{t}", 100, -10., 10.); meTrackPull_[2] = ibook.book1D("TrackPull-HighMVA", "Pull for tracks with MVA > 0.8; (t_{rec}-t_{sim})/#sigma_{t}", 100, -10., 10.); meMVATrackZposResTot_ = ibook.book1D( "MVATrackZposResTot", "Z_{PCA} - Z_{sim} for tracks from LV MVA sel.;Z_{PCA} - Z_{sim} [cm] ", 50, -0.1, 0.1); meTrackZposResTot_ = ibook.book1D("TrackZposResTot", "Z_{PCA} - Z_{sim} for tracks;Z_{PCA} - Z_{sim} [cm] ", 50, -0.5, 0.5); meTrackZposRes_[0] = ibook.book1D( "TrackZposRes-LowMVA", "Z_{PCA} - Z_{sim} for tracks with MVA < 0.5;Z_{PCA} - Z_{sim} [cm] ", 50, -0.5, 0.5); meTrackZposRes_[1] = ibook.book1D("TrackZposRes-MediumMVA", "Z_{PCA} - Z_{sim} for tracks with 0.5 < MVA < 0.8 ;Z_{PCA} - Z_{sim} [cm] ", 50, -0.5, 0.5); meTrackZposRes_[2] = ibook.book1D( "TrackZposRes-HighMVA", "Z_{PCA} - Z_{sim} for tracks with MVA > 0.8 ;Z_{PCA} - Z_{sim} [cm] ", 50, -0.5, 0.5); meTrack3DposRes_[0] = ibook.book1D("Track3DposRes-LowMVA", "3dPos_{PCA} - 3dPos_{sim} for tracks with MVA < 0.5 ;3dPos_{PCA} - 3dPos_{sim} [cm] ", 50, -0.5, 0.5); meTrack3DposRes_[1] = ibook.book1D("Track3DposRes-MediumMVA", "3dPos_{PCA} - 3dPos_{sim} for tracks with 0.5 < MVA < 0.8 ;3dPos_{PCA} - 3dPos_{sim} [cm] ", 50, -0.5, 0.5); meTrack3DposRes_[2] = ibook.book1D("Track3DposRes-HighMVA", "3dPos_{PCA} - 3dPos_{sim} for tracks with MVA > 0.8;3dPos_{PCA} - 3dPos_{sim} [cm] ", 50, -0.5, 0.5); meTimeRes_ = ibook.book1D("TimeRes", "t_{rec} - t_{sim} ;t_{rec} - t_{sim} [ns] ", 40, -0.2, 0.2); meTimePull_ = ibook.book1D("TimePull", "Pull; t_{rec} - t_{sim}/#sigma_{t rec}", 100, -10., 10.); meTimeSignalRes_ = ibook.book1D("TimeSignalRes", "t_{rec} - t_{sim} for signal ;t_{rec} - t_{sim} [ns] ", 40, -0.2, 0.2); meTimeSignalPull_ = ibook.book1D("TimeSignalPull", "Pull for signal; t_{rec} - t_{sim}/#sigma_{t rec}", 100, -10., 10.); mePUvsRealV_ = ibook.bookProfile("PUvsReal", "#PU vertices vs #real matched vertices;#PU;#real ", 100, 0, 300, 100, 0, 200); mePUvsOtherFakeV_ = ibook.bookProfile( "PUvsOtherFake", "#PU vertices vs #other fake matched vertices;#PU;#other fake ", 100, 0, 300, 100, 0, 20); mePUvsSplitV_ = ibook.bookProfile("PUvsSplit", "#PU vertices vs #split matched vertices;#PU;#split ", 100, 0, 300, 100, 0, 20); meMatchQual_ = ibook.book1D("MatchQuality", "RECO-SIM vertex match quality; ", 8, 0, 8.); meDeltaZrealreal_ = ibook.book1D("DeltaZrealreal", "#Delta Z real-real; |#Delta Z (r-r)| [cm]", 100, 0, 0.5); meDeltaZfakefake_ = ibook.book1D("DeltaZfakefake", "#Delta Z fake-fake; |#Delta Z (f-f)| [cm]", 100, 0, 0.5); meDeltaZfakereal_ = ibook.book1D("DeltaZfakereal", "#Delta Z fake-real; |#Delta Z (f-r)| [cm]", 100, 0, 0.5); meDeltaTrealreal_ = ibook.book1D("DeltaTrealreal", "#Delta T real-real; |#Delta T (r-r)| [sigma]", 60, 0., 30.); meDeltaTfakefake_ = ibook.book1D("DeltaTfakefake", "#Delta T fake-fake; |#Delta T (f-f)| [sigma]", 60, 0., 30.); meDeltaTfakereal_ = ibook.book1D("DeltaTfakereal", "#Delta T fake-real; |#Delta T (f-r)| [sigma]", 60, 0., 30.); if (optionalPlots_) { meRecoPosInSimCollection_ = ibook.book1D( "RecoPosInSimCollection", "Sim signal vertex index associated to Reco signal vertex; Sim PV index", 200, 0, 200); meRecoPosInRecoOrigCollection_ = ibook.book1D("RecoPosInRecoOrigCollection", "Reco signal index in OrigCollection; Reco index", 200, 0, 200); meSimPosInSimOrigCollection_ = ibook.book1D("SimPosInSimOrigCollection", "Sim signal index in OrigCollection; Sim index", 200, 0, 200); } meRecoPVPosSignal_ = ibook.book1D("RecoPVPosSignal", "Position in reco collection of PV associated to sim signal", 200, 0, 200); meRecoPVPosSignalNotHighestPt_ = ibook.book1D("RecoPVPosSignalNotHighestPt", "Position in reco collection of PV associated to sim signal not highest Pt", 200, 0, 200); meRecoVtxVsLineDensity_ = ibook.book1D("RecoVtxVsLineDensity", "#Reco vertices/mm/event; line density [#vtx/mm/event]", 160, 0., 4.); meRecVerNumber_ = ibook.book1D("RecVerNumber", "RECO Vertex Number: Number of vertices", 50, 0, 250); meRecPVZ_ = ibook.book1D("recPVZ", "Weighted #Rec vertices/mm", 400, -20., 20.); meRecPVT_ = ibook.book1D("recPVT", "#Rec vertices/10 ps", 200, -1., 1.); meSimPVZ_ = ibook.book1D("simPVZ", "Weighted #Sim vertices/mm", 400, -20., 20.); //some tests meTrackResLowPTot_ = ibook.book1D( "TrackResLowP", "t_{rec} - t_{sim} for tracks with p < 2 GeV; t_{rec} - t_{sim} [ns] ", 70, -0.15, 0.15); meTrackResLowP_[0] = ibook.book1D("TrackResLowP-LowMVA", "t_{rec} - t_{sim} for tracks with MVA < 0.5 and p < 2 GeV; t_{rec} - t_{sim} [ns] ", 100, -1., 1.); meTrackResLowP_[1] = ibook.book1D("TrackResLowP-MediumMVA", "t_{rec} - t_{sim} for tracks with 0.5 < MVA < 0.8 and p < 2 GeV; t_{rec} - t_{sim} [ns] ", 100, -1., 1.); meTrackResLowP_[2] = ibook.book1D("TrackResLowP-HighMVA", "t_{rec} - t_{sim} for tracks with MVA > 0.8 and p < 2 GeV; t_{rec} - t_{sim} [ns] ", 100, -1., 1.); meTrackResHighPTot_ = ibook.book1D( "TrackResHighP", "t_{rec} - t_{sim} for tracks with p > 2 GeV; t_{rec} - t_{sim} [ns] ", 70, -0.15, 0.15); meTrackResHighP_[0] = ibook.book1D("TrackResHighP-LowMVA", "t_{rec} - t_{sim} for tracks with MVA < 0.5 and p > 2 GeV; t_{rec} - t_{sim} [ns] ", 100, -1., 1.); meTrackResHighP_[1] = ibook.book1D("TrackResHighP-MediumMVA", "t_{rec} - t_{sim} for tracks with 0.5 < MVA < 0.8 and p > 2 GeV; t_{rec} - t_{sim} [ns] ", 100, -1., 1.); meTrackResHighP_[2] = ibook.book1D("TrackResHighP-HighMVA", "t_{rec} - t_{sim} for tracks with MVA > 0.8 and p > 2 GeV; t_{rec} - t_{sim} [ns] ", 100, -1., 1.); meTrackPullLowPTot_ = ibook.book1D("TrackPullLowP", "Pull for tracks with p < 2 GeV; (t_{rec}-t_{sim})/#sigma_{t}", 100, -10., 10.); meTrackPullLowP_[0] = ibook.book1D("TrackPullLowP-LowMVA", "Pull for tracks with MVA < 0.5 and p < 2 GeV; (t_{rec}-t_{sim})/#sigma_{t}", 100, -10., 10.); meTrackPullLowP_[1] = ibook.book1D("TrackPullLowP-MediumMVA", "Pull for tracks with 0.5 < MVA < 0.8 and p < 2 GeV; (t_{rec}-t_{sim})/#sigma_{t}", 100, -10., 10.); meTrackPullLowP_[2] = ibook.book1D("TrackPullLowP-HighMVA", "Pull for tracks with MVA > 0.8 and p < 2 GeV; (t_{rec}-t_{sim})/#sigma_{t}", 100, -10., 10.); meTrackPullHighPTot_ = ibook.book1D("TrackPullHighP", "Pull for tracks with p > 2 GeV; (t_{rec}-t_{sim})/#sigma_{t}", 100, -10., 10.); meTrackPullHighP_[0] = ibook.book1D("TrackPullHighP-LowMVA", "Pull for tracks with MVA < 0.5 and p > 2 GeV; (t_{rec}-t_{sim})/#sigma_{t}", 100, -10., 10.); meTrackPullHighP_[1] = ibook.book1D("TrackPullHighP-MediumMVA", "Pull for tracks with 0.5 < MVA < 0.8 and p > 2 GeV; (t_{rec}-t_{sim})/#sigma_{t}", 100, -10., 10.); meTrackPullHighP_[2] = ibook.book1D("TrackPullHighP-HighMVA", "Pull for tracks with MVA > 0.8 and p > 2 GeV; (t_{rec}-t_{sim})/#sigma_{t}", 100, -10., 10.); if (optionalPlots_) { meTrackResMassProtons_[0] = ibook.book1D("TrackResMass-Protons-LowMVA", "t_{rec} - t_{est} for proton tracks with MVA < 0.5; t_{rec} - t_{est} [ns] ", 100, -1., 1.); meTrackResMassProtons_[1] = ibook.book1D("TrackResMass-Protons-MediumMVA", "t_{rec} - t_{est} for proton tracks with 0.5 < MVA < 0.8; t_{rec} - t_{est} [ns] ", 100, -1., 1.); meTrackResMassProtons_[2] = ibook.book1D("TrackResMass-Protons-HighMVA", "t_{rec} - t_{est} for proton tracks with MVA > 0.8; t_{rec} - t_{est} [ns] ", 100, -1., 1.); meTrackResMassTrueProtons_[0] = ibook.book1D("TrackResMassTrue-Protons-LowMVA", "t_{est} - t_{sim} for proton tracks with MVA < 0.5; t_{est} - t_{sim} [ns] ", 100, -1., 1.); meTrackResMassTrueProtons_[1] = ibook.book1D("TrackResMassTrue-Protons-MediumMVA", "t_{est} - t_{sim} for proton tracks with 0.5 < MVA < 0.8; t_{est} - t_{sim} [ns] ", 100, -1., 1.); meTrackResMassTrueProtons_[2] = ibook.book1D("TrackResMassTrue-Protons-HighMVA", "t_{est} - t_{sim} for proton tracks with MVA > 0.8; t_{est} - t_{sim} [ns] ", 100, -1., 1.); meTrackResMassPions_[0] = ibook.book1D("TrackResMass-Pions-LowMVA", "t_{rec} - t_{est} for pion tracks with MVA < 0.5; t_{rec} - t_{est} [ns] ", 100, -1., 1.); meTrackResMassPions_[1] = ibook.book1D("TrackResMass-Pions-MediumMVA", "t_{rec} - t_{est} for pion tracks with 0.5 < MVA < 0.8; t_{rec} - t_{est} [ns] ", 100, -1., 1.); meTrackResMassPions_[2] = ibook.book1D("TrackResMass-Pions-HighMVA", "t_{rec} - t_{est} for pion tracks with MVA > 0.8; t_{rec} - t_{est} [ns] ", 100, -1., 1.); meTrackResMassTruePions_[0] = ibook.book1D("TrackResMassTrue-Pions-LowMVA", "t_{est} - t_{sim} for pion tracks with MVA < 0.5; t_{est} - t_{sim} [ns] ", 100, -1., 1.); meTrackResMassTruePions_[1] = ibook.book1D("TrackResMassTrue-Pions-MediumMVA", "t_{est} - t_{sim} for pion tracks with 0.5 < MVA < 0.8; t_{est} - t_{sim} [ns] ", 100, -1., 1.); meTrackResMassTruePions_[2] = ibook.book1D("TrackResMassTrue-Pions-HighMVA", "t_{est} - t_{sim} for pion tracks with MVA > 0.8; t_{est} - t_{sim} [ns] ", 100, -1., 1.); } } bool Primary4DVertexValidation::matchRecoTrack2SimSignal(const reco::TrackBaseRef& recoTrack) { auto found = r2s_->find(recoTrack); // reco track not matched to any TP if (found == r2s_->end()) return false; //// reco track matched to some TP from signal vertex for (const auto& tp : found->val) { if (tp.first->eventId().bunchCrossing() == 0 && tp.first->eventId().event() == 0) return true; } // reco track not matched to any TP from signal vertex return false; } const edm::Ref<std::vector<TrackingParticle>>* Primary4DVertexValidation::getMatchedTP( const reco::TrackBaseRef& recoTrack, const TrackingVertexRef& vsim) { auto found = r2s_->find(recoTrack); // reco track not matched to any TP if (found == r2s_->end()) return nullptr; //matched TP equal to any TP of sim vertex for (const auto& tp : found->val) { if (std::find_if(vsim->daughterTracks_begin(), vsim->daughterTracks_end(), [&](const TrackingParticleRef& vtp) { return tp.first == vtp; }) != vsim->daughterTracks_end()) return &tp.first; } // reco track not matched to any TP from vertex return nullptr; } double Primary4DVertexValidation::timeFromTrueMass(double mass, double pathlength, double momentum, double time) { if (time > 0 && pathlength > 0 && mass > 0) { double gammasq = 1. + momentum * momentum / (mass * mass); double v = c_ * std::sqrt(1. - 1. / gammasq); // cm / ns double t_est = time - (pathlength / v); return t_est; } else { return -1; } } bool Primary4DVertexValidation::select(const reco::Vertex& v, int level) { /* level 0 !isFake && ndof>4 (default) 1 !isFake && ndof>4 && prob > 0.01 2 !isFake && ndof>4 && prob > 0.01 && ptmax2 > 0.4 */ if (v.isFake()) return false; if ((level == 0) && (v.ndof() > selNdof_)) return true; /*if ((level == 1) && (v.ndof() > selNdof_) && (vertex_pxy(v) > 0.01)) return true; if ((level == 2) && (v.ndof() > selNdof_) && (vertex_pxy(v) > 0.01) && (vertex_ptmax2(v) > 0.4)) return true; if ((level == 3) && (v.ndof() > selNdof_) && (vertex_ptmax2(v) < 0.4)) return true;*/ return false; } /* Extract information form TrackingParticles/TrackingVertex and fill * the helper class simPrimaryVertex with proper generation-level * information */ std::vector<Primary4DVertexValidation::simPrimaryVertex> Primary4DVertexValidation::getSimPVs( const edm::Handle<TrackingVertexCollection>& tVC) { std::vector<Primary4DVertexValidation::simPrimaryVertex> simpv; int current_event = -1; int s = -1; for (TrackingVertexCollection::const_iterator v = tVC->begin(); v != tVC->end(); ++v) { //We keep only the first vertex from all the events at BX=0. if (v->eventId().bunchCrossing() != 0) continue; if (v->eventId().event() != current_event) { current_event = v->eventId().event(); } else { continue; } s++; if (std::abs(v->position().z()) > 1000) continue; // skip junk vertices // could be a new vertex, check all primaries found so far to avoid multiple entries simPrimaryVertex sv(v->position().x(), v->position().y(), v->position().z(), v->position().t()); sv.eventId = v->eventId(); sv.sim_vertex = TrackingVertexRef(tVC, std::distance(tVC->begin(), v)); sv.OriginalIndex = s; for (TrackingParticleRefVector::iterator iTrack = v->daughterTracks_begin(); iTrack != v->daughterTracks_end(); ++iTrack) { assert((**iTrack).eventId().bunchCrossing() == 0); } simPrimaryVertex* vp = nullptr; // will become non-NULL if a vertex is found and then point to it for (std::vector<simPrimaryVertex>::iterator v0 = simpv.begin(); v0 != simpv.end(); v0++) { if ((sv.eventId == v0->eventId) && (std::abs(sv.x - v0->x) < 1e-5) && (std::abs(sv.y - v0->y) < 1e-5) && (std::abs(sv.z - v0->z) < 1e-5)) { vp = &(*v0); break; } } if (!vp) { // this is a new vertex, add it to the list of sim-vertices simpv.push_back(sv); vp = &simpv.back(); } // Loop over daughter track(s) as Tracking Particles for (TrackingVertex::tp_iterator iTP = v->daughterTracks_begin(); iTP != v->daughterTracks_end(); ++iTP) { auto momentum = (*(*iTP)).momentum(); const reco::Track* matched_best_reco_track = nullptr; double match_quality = -1; if (use_only_charged_tracks_ && (**iTP).charge() == 0) continue; if (s2r_->find(*iTP) != s2r_->end()) { matched_best_reco_track = (*s2r_)[*iTP][0].first.get(); match_quality = (*s2r_)[*iTP][0].second; } vp->ptot.setPx(vp->ptot.x() + momentum.x()); vp->ptot.setPy(vp->ptot.y() + momentum.y()); vp->ptot.setPz(vp->ptot.z() + momentum.z()); vp->ptot.setE(vp->ptot.e() + (**iTP).energy()); vp->ptsq += ((**iTP).pt() * (**iTP).pt()); if (matched_best_reco_track) { vp->num_matched_reco_tracks++; vp->average_match_quality += match_quality; } } // End of for loop on daughters sim-particles if (vp->num_matched_reco_tracks) vp->average_match_quality /= static_cast<float>(vp->num_matched_reco_tracks); if (debug_) { edm::LogPrint("Primary4DVertexValidation") << "average number of associated tracks: " << vp->num_matched_reco_tracks / static_cast<float>(vp->nGenTrk) << " with average quality: " << vp->average_match_quality; } } // End of for loop on tracking vertices // In case of no simulated vertices, break here if (simpv.empty()) return simpv; // Now compute the closest distance in z between all simulated vertex // first initialize auto prev_z = simpv.back().z; for (simPrimaryVertex& vsim : simpv) { vsim.closest_vertex_distance_z = std::abs(vsim.z - prev_z); prev_z = vsim.z; } // then calculate for (std::vector<simPrimaryVertex>::iterator vsim = simpv.begin(); vsim != simpv.end(); vsim++) { std::vector<simPrimaryVertex>::iterator vsim2 = vsim; vsim2++; for (; vsim2 != simpv.end(); vsim2++) { double distance = std::abs(vsim->z - vsim2->z); // need both to be complete vsim->closest_vertex_distance_z = std::min(vsim->closest_vertex_distance_z, distance); vsim2->closest_vertex_distance_z = std::min(vsim2->closest_vertex_distance_z, distance); } } return simpv; } /* Extract information form recoVertex and fill the helper class * recoPrimaryVertex with proper reco-level information */ std::vector<Primary4DVertexValidation::recoPrimaryVertex> Primary4DVertexValidation::getRecoPVs( const edm::Handle<edm::View<reco::Vertex>>& tVC) { std::vector<Primary4DVertexValidation::recoPrimaryVertex> recopv; int r = -1; for (auto v = tVC->begin(); v != tVC->end(); ++v) { r++; // Skip junk vertices if (std::abs(v->z()) > 1000) continue; if (v->isFake() || !v->isValid()) continue; recoPrimaryVertex sv(v->position().x(), v->position().y(), v->position().z()); sv.recVtx = &(*v); sv.recVtxRef = reco::VertexBaseRef(tVC, std::distance(tVC->begin(), v)); sv.OriginalIndex = r; // this is a new vertex, add it to the list of reco-vertices recopv.push_back(sv); Primary4DVertexValidation::recoPrimaryVertex* vp = &recopv.back(); // Loop over daughter track(s) for (auto iTrack = v->tracks_begin(); iTrack != v->tracks_end(); ++iTrack) { auto momentum = (*(*iTrack)).innerMomentum(); if (momentum.mag2() == 0) momentum = (*(*iTrack)).momentum(); vp->pt += std::sqrt(momentum.perp2()); vp->ptsq += (momentum.perp2()); vp->nRecoTrk++; auto matched = r2s_->find(*iTrack); if (matched != r2s_->end()) { vp->num_matched_sim_tracks++; } } // End of for loop on daughters reconstructed tracks } // End of for loop on tracking vertices // In case of no reco vertices, break here if (recopv.empty()) return recopv; // Now compute the closest distance in z between all reconstructed vertex // first initialize auto prev_z = recopv.back().z; for (recoPrimaryVertex& vreco : recopv) { vreco.closest_vertex_distance_z = std::abs(vreco.z - prev_z); prev_z = vreco.z; } for (std::vector<recoPrimaryVertex>::iterator vreco = recopv.begin(); vreco != recopv.end(); vreco++) { std::vector<recoPrimaryVertex>::iterator vreco2 = vreco; vreco2++; for (; vreco2 != recopv.end(); vreco2++) { double distance = std::abs(vreco->z - vreco2->z); // need both to be complete vreco->closest_vertex_distance_z = std::min(vreco->closest_vertex_distance_z, distance); vreco2->closest_vertex_distance_z = std::min(vreco2->closest_vertex_distance_z, distance); } } return recopv; } // ------------ method called to produce the data ------------ void Primary4DVertexValidation::matchReco2Sim(std::vector<recoPrimaryVertex>& recopv, std::vector<simPrimaryVertex>& simpv, const edm::ValueMap<float>& sigmat0, const edm::ValueMap<float>& MVA, const edm::Handle<reco::BeamSpot>& BS) { for (auto vv : simpv) { vv.wnt.clear(); vv.wos.clear(); } for (auto rv : recopv) { rv.wnt.clear(); rv.wos.clear(); } for (unsigned int iv = 0; iv < recopv.size(); iv++) { const reco::Vertex* vertex = recopv.at(iv).recVtx; for (unsigned int iev = 0; iev < simpv.size(); iev++) { double wnt = 0; double wos = 0; double evwnt = 0; double evwos = 0; double evnt = 0; for (auto iTrack = vertex->tracks_begin(); iTrack != vertex->tracks_end(); ++iTrack) { double pt = (*iTrack)->pt(); if (vertex->trackWeight(*iTrack) < trackweightTh_) continue; if (MVA[(*iTrack)] < mvaTh_) continue; auto tp_info = getMatchedTP(*iTrack, simpv.at(iev).sim_vertex); if (tp_info != nullptr) { double dz2_beam = pow((*BS).BeamWidthX() * cos((*iTrack)->phi()) / tan((*iTrack)->theta()), 2) + pow((*BS).BeamWidthY() * sin((*iTrack)->phi()) / tan((*iTrack)->theta()), 2); double dz2 = pow((*iTrack)->dzError(), 2) + dz2_beam + pow(0.0020, 2); // added 20 um, some tracks have crazy small resolutions wos = vertex->trackWeight(*iTrack) / dz2; wnt = vertex->trackWeight(*iTrack) * std::min(pt, 1.0); if (sigmat0[(*iTrack)] > 0) { double sigmaZ = (*BS).sigmaZ(); double sigmaT = sigmaZ / c_; // c in cm/ns wos = wos / erf(sigmat0[(*iTrack)] / sigmaT); } simpv.at(iev).addTrack(iv, wos, wnt); recopv.at(iv).addTrack(iev, wos, wnt); evwos += wos; evwnt += wnt; evnt++; } } //RecoTracks loop // require 2 tracks for a wos-match if ((evwos > 0) && (evwos > recopv.at(iv).maxwos) && (evnt > 1)) { recopv.at(iv).wosmatch = iev; recopv.at(iv).maxwos = evwos; recopv.at(iv).maxwosnt = evnt; simpv.at(iev).wos_dominated_recv.push_back(iv); simpv.at(iev).nwosmatch++; } // weighted track counting match, require at least one track if ((evnt > 0) && (evwnt > recopv.at(iv).maxwnt)) { recopv.at(iv).wntmatch = iev; recopv.at(iv).maxwnt = evwnt; } } //TrackingVertex loop } //RecoPrimaryVertex //after filling infos, goes for the sim-reco match for (auto& vrec : recopv) { vrec.sim = NOT_MATCHED; vrec.matchQuality = 0; } unsigned int iev = 0; for (auto& vv : simpv) { if (debug_) { edm::LogPrint("Primary4DVertexValidation") << "iev: " << iev; edm::LogPrint("Primary4DVertexValidation") << "wos_dominated_recv.size: " << vv.wos_dominated_recv.size(); } for (unsigned int i = 0; i < vv.wos_dominated_recv.size(); i++) { auto recov = vv.wos_dominated_recv.at(i); if (debug_) { edm::LogPrint("Primary4DVertexValidation") << "index of reco vertex: " << recov << " that has a wos: " << vv.wos.at(recov) << " at position " << i; } } vv.rec = NOT_MATCHED; vv.matchQuality = 0; iev++; } //this tries a one-to-one match, taking simPV with highest wos if there are > 1 simPV candidates for (unsigned int rank = 1; rank < maxRank_; rank++) { for (unsigned int iev = 0; iev < simpv.size(); iev++) { //loop on SimPV if (simpv.at(iev).rec != NOT_MATCHED) continue; if (simpv.at(iev).nwosmatch == 0) continue; if (simpv.at(iev).nwosmatch > rank) continue; unsigned int iv = NOT_MATCHED; for (unsigned int k = 0; k < simpv.at(iev).wos_dominated_recv.size(); k++) { unsigned int rec = simpv.at(iev).wos_dominated_recv.at(k); auto vrec = recopv.at(rec); if (vrec.sim != NOT_MATCHED) continue; // already matched if (std::abs(simpv.at(iev).z - vrec.z) > zWosMatchMax_) continue; // insanely far away if ((iv == NOT_MATCHED) || simpv.at(iev).wos.at(rec) > simpv.at(iev).wos.at(iv)) { iv = rec; } } if (iv != NOT_MATCHED) { //if the rec vertex has already been associated is possible that iv remains NOT_MATCHED at this point recopv.at(iv).sim = iev; simpv.at(iev).rec = iv; recopv.at(iv).matchQuality = rank; simpv.at(iev).matchQuality = rank; } } } //give vertices a chance that have a lot of overlap, but are still recognizably //caused by a specific simvertex (without being classified as dominating) //like a small peak sitting on the flank of a larger nearby peak unsigned int ntry = 0; while (ntry++ < maxTry_) { unsigned nmatch = 0; for (unsigned int iev = 0; iev < simpv.size(); iev++) { if ((simpv.at(iev).rec != NOT_MATCHED) || (simpv.at(iev).wos.empty())) continue; // find a rec vertex for the NOT_MATCHED sim vertex unsigned int rec = NOT_MATCHED; for (auto rv : simpv.at(iev).wos) { if ((rec == NOT_MATCHED) || (rv.second > simpv.at(iev).wos.at(rec))) { rec = rv.first; } } if (rec == NOT_MATCHED) { //try with wnt match for (auto rv : simpv.at(iev).wnt) { if ((rec == NOT_MATCHED) || (rv.second > simpv.at(iev).wnt.at(rec))) { rec = rv.first; } } } if (rec == NOT_MATCHED) continue; if (recopv.at(rec).sim != NOT_MATCHED) continue; // already gone // check if the recvertex can be matched unsigned int rec2sim = NOT_MATCHED; for (auto sv : recopv.at(rec).wos) { if (simpv.at(sv.first).rec != NOT_MATCHED) continue; // already used if ((rec2sim == NOT_MATCHED) || (sv.second > recopv.at(rec).wos.at(rec2sim))) { rec2sim = sv.first; } } if (iev == rec2sim) { // do the match and assign lowest quality (i.e. max rank) recopv.at(rec).sim = iev; recopv.at(rec).matchQuality = maxRank_; simpv.at(iev).rec = rec; simpv.at(iev).matchQuality = maxRank_; nmatch++; } } //sim loop if (nmatch == 0) { break; } } // ntry } void Primary4DVertexValidation::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { using edm::Handle; using edm::View; using std::cout; using std::endl; using std::vector; using namespace reco; std::vector<float> pileUpInfo_z; // get the pileup information edm::Handle<std::vector<PileupSummaryInfo>> puinfoH; if (iEvent.getByToken(vecPileupSummaryInfoToken_, puinfoH)) { for (auto const& pu_info : *puinfoH.product()) { if (pu_info.getBunchCrossing() == 0) { pileUpInfo_z = pu_info.getPU_zpositions(); break; } } } edm::Handle<TrackingParticleCollection> TPCollectionH; iEvent.getByToken(trackingParticleCollectionToken_, TPCollectionH); if (!TPCollectionH.isValid()) edm::LogWarning("Primary4DVertexValidation") << "TPCollectionH is not valid"; edm::Handle<TrackingVertexCollection> TVCollectionH; iEvent.getByToken(trackingVertexCollectionToken_, TVCollectionH); if (!TVCollectionH.isValid()) edm::LogWarning("Primary4DVertexValidation") << "TVCollectionH is not valid"; edm::Handle<reco::SimToRecoCollection> simToRecoH; iEvent.getByToken(simToRecoAssociationToken_, simToRecoH); if (simToRecoH.isValid()) s2r_ = simToRecoH.product(); else edm::LogWarning("Primary4DVertexValidation") << "simToRecoH is not valid"; edm::Handle<reco::RecoToSimCollection> recoToSimH; iEvent.getByToken(recoToSimAssociationToken_, recoToSimH); if (recoToSimH.isValid()) r2s_ = recoToSimH.product(); else edm::LogWarning("Primary4DVertexValidation") << "recoToSimH is not valid"; edm::Handle<reco::BeamSpot> BeamSpotH; iEvent.getByToken(RecBeamSpotToken_, BeamSpotH); if (!BeamSpotH.isValid()) edm::LogWarning("Primary4DVertexValidation") << "BeamSpotH is not valid"; std::vector<simPrimaryVertex> simpv; // a list of simulated primary MC vertices simpv = getSimPVs(TVCollectionH); //this bool check if first vertex in that with highest pT bool signal_is_highest_pt = std::max_element(simpv.begin(), simpv.end(), [](const simPrimaryVertex& lhs, const simPrimaryVertex& rhs) { return lhs.ptsq < rhs.ptsq; }) == simpv.begin(); std::vector<recoPrimaryVertex> recopv; // a list of reconstructed primary MC vertices edm::Handle<edm::View<reco::Vertex>> recVtxs; iEvent.getByToken(Rec4DVerToken_, recVtxs); if (!recVtxs.isValid()) edm::LogWarning("Primary4DVertexValidation") << "recVtxs is not valid"; recopv = getRecoPVs(recVtxs); const auto& trackAssoc = iEvent.get(trackAssocToken_); const auto& pathLength = iEvent.get(pathLengthToken_); const auto& momentum = iEvent.get(momentumToken_); const auto& time = iEvent.get(timeToken_); const auto& t0Safe = iEvent.get(t0SafePidToken_); const auto& sigmat0Safe = iEvent.get(sigmat0SafePidToken_); const auto& mtdQualMVA = iEvent.get(trackMVAQualToken_); //I have simPV and recoPV collections matchReco2Sim(recopv, simpv, sigmat0Safe, mtdQualMVA, BeamSpotH); //Loop on tracks for (unsigned int iv = 0; iv < recopv.size(); iv++) { const reco::Vertex* vertex = recopv.at(iv).recVtx; for (unsigned int iev = 0; iev < simpv.size(); iev++) { auto vsim = simpv.at(iev).sim_vertex; bool selectedVtxMatching = recopv.at(iv).sim == iev && simpv.at(iev).rec == iv && simpv.at(iev).eventId.bunchCrossing() == 0 && simpv.at(iev).eventId.event() == 0 && recopv.at(iv).OriginalIndex == 0; if (selectedVtxMatching && !recopv.at(iv).is_signal()) { edm::LogWarning("Primary4DVertexValidation") << "Reco vtx leading match inconsistent: BX/ID " << simpv.at(iev).eventId.bunchCrossing() << " " << simpv.at(iev).eventId.event(); } double vzsim = simpv.at(iev).z; double vtsim = simpv.at(iev).t * simUnit_; for (auto iTrack = vertex->tracks_begin(); iTrack != vertex->tracks_end(); ++iTrack) { if (trackAssoc[*iTrack] == -1) { LogTrace("mtdTracks") << "Extended track not associated"; continue; } if (vertex->trackWeight(*iTrack) < trackweightTh_) continue; bool selectRecoTrk = mvaRecSel(**iTrack, *vertex, t0Safe[*iTrack], sigmat0Safe[*iTrack]); if (selectedVtxMatching && selectRecoTrk) { meMVATrackEffPtTot_->Fill((*iTrack)->pt()); meMVATrackEffEtaTot_->Fill(std::abs((*iTrack)->eta())); } auto tp_info = getMatchedTP(*iTrack, vsim); if (tp_info != nullptr) { double mass = (*tp_info)->mass(); double tsim = (*tp_info)->parentVertex()->position().t() * simUnit_; double tEst = timeFromTrueMass(mass, pathLength[*iTrack], momentum[*iTrack], time[*iTrack]); double xsim = (*tp_info)->parentVertex()->position().x(); double ysim = (*tp_info)->parentVertex()->position().y(); double zsim = (*tp_info)->parentVertex()->position().z(); double xPCA = (*iTrack)->vx(); double yPCA = (*iTrack)->vy(); double zPCA = (*iTrack)->vz(); double dZ = zPCA - zsim; double d3D = std::sqrt((xPCA - xsim) * (xPCA - xsim) + (yPCA - ysim) * (yPCA - ysim) + dZ * dZ); // orient d3D according to the projection of RECO - SIM onto simulated momentum if ((xPCA - xsim) * ((*tp_info)->px()) + (yPCA - ysim) * ((*tp_info)->py()) + dZ * ((*tp_info)->pz()) < 0.) { d3D = -d3D; } bool selectTP = mvaTPSel(**tp_info); if (selectedVtxMatching && selectRecoTrk && selectTP) { meMVATrackZposResTot_->Fill((*iTrack)->vz() - vzsim); meMVATrackMatchedEffPtTot_->Fill((*iTrack)->pt()); meMVATrackMatchedEffEtaTot_->Fill(std::abs((*iTrack)->eta())); } if (sigmat0Safe[*iTrack] == -1) continue; if (selectedVtxMatching && selectRecoTrk && selectTP) { meMVATrackResTot_->Fill(t0Safe[*iTrack] - vtsim); meMVATrackPullTot_->Fill((t0Safe[*iTrack] - vtsim) / sigmat0Safe[*iTrack]); meMVATrackMatchedEffPtMtd_->Fill((*iTrack)->pt()); meMVATrackMatchedEffEtaMtd_->Fill(std::abs((*iTrack)->eta())); } meTrackResTot_->Fill(t0Safe[*iTrack] - tsim); meTrackPullTot_->Fill((t0Safe[*iTrack] - tsim) / sigmat0Safe[*iTrack]); meTrackZposResTot_->Fill(dZ); if ((*iTrack)->p() <= 2) { meTrackResLowPTot_->Fill(t0Safe[*iTrack] - tsim); meTrackPullLowPTot_->Fill((t0Safe[*iTrack] - tsim) / sigmat0Safe[*iTrack]); } else { meTrackResHighPTot_->Fill(t0Safe[*iTrack] - tsim); meTrackPullHighPTot_->Fill((t0Safe[*iTrack] - tsim) / sigmat0Safe[*iTrack]); } if (mtdQualMVA[(*iTrack)] < mvaL_) { meTrackZposRes_[0]->Fill(dZ); meTrack3DposRes_[0]->Fill(d3D); meTrackRes_[0]->Fill(t0Safe[*iTrack] - tsim); meTrackPull_[0]->Fill((t0Safe[*iTrack] - tsim) / sigmat0Safe[*iTrack]); if (optionalPlots_) { meTrackResMass_[0]->Fill(t0Safe[*iTrack] - tEst); meTrackResMassTrue_[0]->Fill(tEst - tsim); } if ((*iTrack)->p() <= 2) { meTrackResLowP_[0]->Fill(t0Safe[*iTrack] - tsim); meTrackPullLowP_[0]->Fill((t0Safe[*iTrack] - tsim) / sigmat0Safe[*iTrack]); } else if ((*iTrack)->p() > 2) { meTrackResHighP_[0]->Fill(t0Safe[*iTrack] - tsim); meTrackPullHighP_[0]->Fill((t0Safe[*iTrack] - tsim) / sigmat0Safe[*iTrack]); } if (optionalPlots_) { if (std::abs((*tp_info)->pdgId()) == 2212) { meTrackResMassProtons_[0]->Fill(t0Safe[*iTrack] - tEst); meTrackResMassTrueProtons_[0]->Fill(tEst - tsim); } else if (std::abs((*tp_info)->pdgId()) == 211) { meTrackResMassPions_[0]->Fill(t0Safe[*iTrack] - tEst); meTrackResMassTruePions_[0]->Fill(tEst - tsim); } } } else if (mtdQualMVA[(*iTrack)] > mvaL_ && mtdQualMVA[(*iTrack)] < mvaH_) { meTrackZposRes_[1]->Fill(dZ); meTrack3DposRes_[1]->Fill(d3D); meTrackRes_[1]->Fill(t0Safe[*iTrack] - tsim); meTrackPull_[1]->Fill((t0Safe[*iTrack] - tsim) / sigmat0Safe[*iTrack]); if (optionalPlots_) { meTrackResMass_[1]->Fill(t0Safe[*iTrack] - tEst); meTrackResMassTrue_[1]->Fill(tEst - tsim); } if ((*iTrack)->p() <= 2) { meTrackResLowP_[1]->Fill(t0Safe[*iTrack] - tsim); meTrackPullLowP_[1]->Fill((t0Safe[*iTrack] - tsim) / sigmat0Safe[*iTrack]); } else if ((*iTrack)->p() > 2) { meTrackResHighP_[1]->Fill(t0Safe[*iTrack] - tsim); meTrackPullHighP_[1]->Fill((t0Safe[*iTrack] - tsim) / sigmat0Safe[*iTrack]); } if (optionalPlots_) { if (std::abs((*tp_info)->pdgId()) == 2212) { meTrackResMassProtons_[1]->Fill(t0Safe[*iTrack] - tEst); meTrackResMassTrueProtons_[1]->Fill(tEst - tsim); } else if (std::abs((*tp_info)->pdgId()) == 211) { meTrackResMassPions_[1]->Fill(t0Safe[*iTrack] - tEst); meTrackResMassTruePions_[1]->Fill(tEst - tsim); } } } else if (mtdQualMVA[(*iTrack)] > mvaH_) { meTrackZposRes_[2]->Fill(dZ); meTrack3DposRes_[2]->Fill(d3D); meTrackRes_[2]->Fill(t0Safe[*iTrack] - tsim); meTrackPull_[2]->Fill((t0Safe[*iTrack] - tsim) / sigmat0Safe[*iTrack]); if (optionalPlots_) { meTrackResMass_[2]->Fill(t0Safe[*iTrack] - tEst); meTrackResMassTrue_[2]->Fill(tEst - tsim); } if ((*iTrack)->p() <= 2) { meTrackResLowP_[2]->Fill(t0Safe[*iTrack] - tsim); meTrackPullLowP_[2]->Fill((t0Safe[*iTrack] - tsim) / sigmat0Safe[*iTrack]); } else if ((*iTrack)->p() > 2) { meTrackResHighP_[2]->Fill(t0Safe[*iTrack] - tsim); meTrackPullHighP_[2]->Fill((t0Safe[*iTrack] - tsim) / sigmat0Safe[*iTrack]); } if (optionalPlots_) { if (std::abs((*tp_info)->pdgId()) == 2212) { meTrackResMassProtons_[2]->Fill(t0Safe[*iTrack] - tEst); meTrackResMassTrueProtons_[2]->Fill(tEst - tsim); } else if (std::abs((*tp_info)->pdgId()) == 211) { meTrackResMassPions_[2]->Fill(t0Safe[*iTrack] - tEst); meTrackResMassTruePions_[2]->Fill(tEst - tsim); } } } } //if tp_info != nullptr } } } int real = 0; int fake = 0; int other_fake = 0; int split = 0; auto puLineDensity = [&](double z) { // gaussian parameterization of line density vs z, z in cm, parameters in mm double argl = (z * 10. - lineDensityPar_[1]) / lineDensityPar_[2]; return lineDensityPar_[0] * exp(-0.5 * argl * argl); }; meRecVerNumber_->Fill(recopv.size()); for (unsigned int ir = 0; ir < recopv.size(); ir++) { meRecoVtxVsLineDensity_->Fill(puLineDensity(recopv.at(ir).z)); meRecPVZ_->Fill(recopv.at(ir).z, 1. / puLineDensity(recopv.at(ir).z)); if (recopv.at(ir).recVtx->tError() > 0.) { meRecPVT_->Fill(recopv.at(ir).recVtx->t()); } if (debug_) { edm::LogPrint("Primary4DVertexValidation") << "************* IR: " << ir; edm::LogPrint("Primary4DVertexValidation") << "z: " << recopv.at(ir).z << " corresponding to line density: " << puLineDensity(recopv.at(ir).z); edm::LogPrint("Primary4DVertexValidation") << "is_real: " << recopv.at(ir).is_real(); edm::LogPrint("Primary4DVertexValidation") << "is_fake: " << recopv.at(ir).is_fake(); edm::LogPrint("Primary4DVertexValidation") << "is_signal: " << recopv.at(ir).is_signal(); edm::LogPrint("Primary4DVertexValidation") << "split_from: " << recopv.at(ir).split_from(); edm::LogPrint("Primary4DVertexValidation") << "other fake: " << recopv.at(ir).other_fake(); } if (recopv.at(ir).is_real()) real++; if (recopv.at(ir).is_fake()) fake++; if (recopv.at(ir).other_fake()) other_fake++; if (recopv.at(ir).split_from() != -1) { split++; } } if (debug_) { edm::LogPrint("Primary4DVertexValidation") << "is_real: " << real; edm::LogPrint("Primary4DVertexValidation") << "is_fake: " << fake; edm::LogPrint("Primary4DVertexValidation") << "split_from: " << split; edm::LogPrint("Primary4DVertexValidation") << "other fake: " << other_fake; } //fill vertices histograms here in a new loop for (unsigned int is = 0; is < simpv.size(); is++) { meSimPVZ_->Fill(simpv.at(is).z, 1. / puLineDensity(simpv.at(is).z)); if (is == 0 && optionalPlots_) { meSimPosInSimOrigCollection_->Fill(simpv.at(is).OriginalIndex); } if (simpv.at(is).rec == NOT_MATCHED) { if (debug_) { edm::LogPrint("Primary4DVertexValidation") << "sim vertex: " << is << " is not matched with any reco"; } continue; } for (unsigned int ir = 0; ir < recopv.size(); ir++) { if (recopv.at(ir).sim == is && simpv.at(is).rec == ir) { meTimeRes_->Fill(recopv.at(ir).recVtx->t() - simpv.at(is).t * simUnit_); meTimePull_->Fill((recopv.at(ir).recVtx->t() - simpv.at(is).t * simUnit_) / recopv.at(ir).recVtx->tError()); mePUvsRealV_->Fill(simpv.size(), real); mePUvsOtherFakeV_->Fill(simpv.size(), other_fake); mePUvsSplitV_->Fill(simpv.size(), split); meMatchQual_->Fill(recopv.at(ir).matchQuality - 0.5); if (ir == 0) { //signal vertex plots meTimeSignalRes_->Fill(recopv.at(ir).recVtx->t() - simpv.at(is).t * simUnit_); meTimeSignalPull_->Fill((recopv.at(ir).recVtx->t() - simpv.at(is).t * simUnit_) / recopv.at(ir).recVtx->tError()); if (optionalPlots_) { meRecoPosInSimCollection_->Fill(recopv.at(ir).sim); meRecoPosInRecoOrigCollection_->Fill(recopv.at(ir).OriginalIndex); } } if (simpv.at(is).eventId.bunchCrossing() == 0 && simpv.at(is).eventId.event() == 0) { if (!recopv.at(ir).is_signal()) { edm::LogWarning("Primary4DVertexValidation") << "Reco vtx leading match inconsistent: BX/ID " << simpv.at(is).eventId.bunchCrossing() << " " << simpv.at(is).eventId.event(); } meRecoPVPosSignal_->Fill( recopv.at(ir).OriginalIndex); // position in reco vtx correction associated to sim signal if (!signal_is_highest_pt) { meRecoPVPosSignalNotHighestPt_->Fill( recopv.at(ir).OriginalIndex); // position in reco vtx correction associated to sim signal } } if (debug_) { edm::LogPrint("Primary4DVertexValidation") << "*** Matching RECO: " << ir << "with SIM: " << is << " ***"; edm::LogPrint("Primary4DVertexValidation") << "Match Quality is " << recopv.at(ir).matchQuality; edm::LogPrint("Primary4DVertexValidation") << "****"; } } } } //dz histos for (unsigned int iv = 0; iv < recVtxs->size() - 1; iv++) { if (recVtxs->at(iv).ndof() > selNdof_) { double mindistance_realreal = 1e10; for (unsigned int jv = iv; jv < recVtxs->size(); jv++) { if ((!(jv == iv)) && select(recVtxs->at(jv))) { double dz = recVtxs->at(iv).z() - recVtxs->at(jv).z(); double dtsigma = std::sqrt(recVtxs->at(iv).covariance(3, 3) + recVtxs->at(jv).covariance(3, 3)); double dt = (std::abs(dz) <= deltaZcut_ && dtsigma > 0.) ? (recVtxs->at(iv).t() - recVtxs->at(jv).t()) / dtsigma : -9999.; if (recopv.at(iv).is_real() && recopv.at(jv).is_real()) { meDeltaZrealreal_->Fill(std::abs(dz)); if (dt != -9999.) { meDeltaTrealreal_->Fill(std::abs(dt)); } if (std::abs(dz) < std::abs(mindistance_realreal)) { mindistance_realreal = dz; } } else if (recopv.at(iv).is_fake() && recopv.at(jv).is_fake()) { meDeltaZfakefake_->Fill(std::abs(dz)); if (dt != -9999.) { meDeltaTfakefake_->Fill(std::abs(dt)); } } } } double mindistance_fakereal = 1e10; double mindistance_realfake = 1e10; for (unsigned int jv = 0; jv < recVtxs->size(); jv++) { if ((!(jv == iv)) && select(recVtxs->at(jv))) { double dz = recVtxs->at(iv).z() - recVtxs->at(jv).z(); double dtsigma = std::sqrt(recVtxs->at(iv).covariance(3, 3) + recVtxs->at(jv).covariance(3, 3)); double dt = (std::abs(dz) <= deltaZcut_ && dtsigma > 0.) ? (recVtxs->at(iv).t() - recVtxs->at(jv).t()) / dtsigma : -9999.; if (recopv.at(iv).is_fake() && recopv.at(jv).is_real()) { meDeltaZfakereal_->Fill(std::abs(dz)); if (dt != -9999.) { meDeltaTfakereal_->Fill(std::abs(dt)); } if (std::abs(dz) < std::abs(mindistance_fakereal)) { mindistance_fakereal = dz; } } if (recopv.at(iv).is_real() && recopv.at(jv).is_fake() && (std::abs(dz) < std::abs(mindistance_realfake))) { mindistance_realfake = dz; } } } } //ndof } } // end of analyze void Primary4DVertexValidation::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; desc.add<std::string>("folder", "MTD/Vertices"); desc.add<edm::InputTag>("TPtoRecoTrackAssoc", edm::InputTag("trackingParticleRecoTrackAsssociation")); desc.add<edm::InputTag>("mtdTracks", edm::InputTag("trackExtenderWithMTD")); desc.add<edm::InputTag>("SimTag", edm::InputTag("mix", "MergedTrackTruth")); desc.add<edm::InputTag>("offlineBS", edm::InputTag("offlineBeamSpot")); desc.add<edm::InputTag>("offline4DPV", edm::InputTag("offlinePrimaryVertices4D")); desc.add<edm::InputTag>("trackAssocSrc", edm::InputTag("trackExtenderWithMTD:generalTrackassoc")) ->setComment("Association between General and MTD Extended tracks"); desc.add<edm::InputTag>("pathLengthSrc", edm::InputTag("trackExtenderWithMTD:generalTrackPathLength")); desc.add<edm::InputTag>("momentumSrc", edm::InputTag("trackExtenderWithMTD:generalTrackp")); desc.add<edm::InputTag>("timeSrc", edm::InputTag("trackExtenderWithMTD:generalTracktmtd")); desc.add<edm::InputTag>("sigmaSrc", edm::InputTag("trackExtenderWithMTD:generalTracksigmatmtd")); desc.add<edm::InputTag>("t0SafePID", edm::InputTag("tofPID:t0safe")); desc.add<edm::InputTag>("sigmat0SafePID", edm::InputTag("tofPID:sigmat0safe")); desc.add<edm::InputTag>("trackMVAQual", edm::InputTag("mtdTrackQualityMVA:mtdQualMVA")); desc.add<bool>("useOnlyChargedTracks", true); desc.addUntracked<bool>("debug", false); desc.addUntracked<bool>("optionalPlots", false); desc.add<double>("trackweightTh", 0.5); desc.add<double>("mvaTh", 0.01); //lineDensity parameters have been obtained by fitting the distribution of the z position of the vertices, //using a 200k single mu ptGun sample (gaussian fit) std::vector<double> lDP; lDP.push_back(1.87); lDP.push_back(0.); lDP.push_back(42.5); desc.add<std::vector<double>>("lineDensityPar", lDP); descriptions.add("vertices4D", desc); } const bool Primary4DVertexValidation::mvaTPSel(const TrackingParticle& tp) { bool match = false; if (tp.status() != 1) { return match; } match = tp.charge() != 0 && tp.pt() > pTcut_ && std::abs(tp.eta()) < etacutGEN_; return match; } const bool Primary4DVertexValidation::mvaRecSel(const reco::TrackBase& trk, const reco::Vertex& vtx, const double& t0, const double& st0) { bool match = false; match = trk.pt() > pTcut_ && std::abs(trk.eta()) < etacutREC_ && std::abs(trk.vz() - vtx.z()) <= deltaZcut_; if (st0 > 0.) { match = match && std::abs(t0 - vtx.t()) < 3. * st0; } return match; } DEFINE_FWK_MODULE(Primary4DVertexValidation);
43.936255
127
0.594683
wonpoint4
290a5c08e62159e11c2d077221dcb20eb0d8bc94
4,928
cc
C++
src/devices/tests/libdriver-integration-test/action-list.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
210
2019-02-05T12:45:09.000Z
2022-03-28T07:59:06.000Z
src/devices/tests/libdriver-integration-test/action-list.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
5
2019-12-04T15:13:37.000Z
2020-02-19T08:11:38.000Z
src/devices/tests/libdriver-integration-test/action-list.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
73
2019-03-06T18:55:23.000Z
2022-03-26T12:04:51.000Z
// Copyright 2019 The Fuchsia 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 "action-list.h" #include <gtest/gtest.h> #include "mock-device-thread.h" #include "mock-device.h" namespace libdriver_integration_test { ActionList::ActionList() = default; ActionList::~ActionList() = default; void ActionList::AppendAction(Action action) { actions_.push_back(std::move(action)); } void ActionList::AppendAddMockDevice(async_dispatcher_t* dispatcher, const std::string& parent_path, std::string name, std::vector<zx_device_prop_t> props, zx_status_t expect_status, std::unique_ptr<MockDevice>* new_device_out, fpromise::promise<void, std::string>* add_done_out) { fpromise::bridge<void, std::string> bridge; AppendAddMockDevice(dispatcher, parent_path, std::move(name), std::move(props), expect_status, std::move(bridge.completer), new_device_out); *add_done_out = bridge.consumer.promise_or(::fpromise::error("add device abandoned")).box(); } void ActionList::AppendAddMockDevice(async_dispatcher_t* dispatcher, const std::string& parent_path, std::string name, std::vector<zx_device_prop_t> props, zx_status_t expect_status, fpromise::completer<void, std::string> add_done, std::unique_ptr<MockDevice>* new_device_out) { fidl::InterfaceHandle<fuchsia::device::mock::MockDevice> client; fidl::InterfaceRequest<fuchsia::device::mock::MockDevice> server(client.NewRequest()); if (!server.is_valid()) { EXPECT_TRUE(server.is_valid()); return; } std::string path(parent_path + "/" + name); *new_device_out = std::make_unique<MockDevice>(std::move(server), dispatcher, std::move(path)); fuchsia::device::mock::Action action; auto& add_device = action.add_device(); add_device.do_bind = false; add_device.controller = std::move(client); add_device.name = std::move(name); add_device.expect_status = expect_status; static_assert(sizeof(uint64_t) == sizeof(props[0])); for (zx_device_prop_t prop : props) { add_device.properties.push_back(*reinterpret_cast<uint64_t*>(&prop)); } add_device.action_id = next_action_id_++; local_action_map_[add_device.action_id] = std::move(add_done); return AppendAction(std::move(action)); } void ActionList::AppendUnbindReply(fpromise::promise<void, std::string>* unbind_reply_done_out) { fpromise::bridge<void, std::string> bridge; AppendUnbindReply(std::move(bridge.completer)); *unbind_reply_done_out = bridge.consumer.promise_or(::fpromise::error("unbind reply abandoned")).box(); } void ActionList::AppendUnbindReply(fpromise::completer<void, std::string> unbind_reply_done) { Action action; auto& unbind_reply = action.unbind_reply(); unbind_reply.action_id = next_action_id_++; fpromise::bridge<void, std::string> bridge; local_action_map_[unbind_reply.action_id] = std::move(unbind_reply_done); return AppendAction(std::move(action)); } void ActionList::AppendAsyncRemoveDevice() { Action action; action.set_async_remove_device(true); return AppendAction(std::move(action)); } void ActionList::AppendCreateThread(async_dispatcher_t* dispatcher, std::unique_ptr<MockDeviceThread>* out) { fidl::InterfacePtr<MockDeviceThread::Interface> interface; Action action; action.set_create_thread(interface.NewRequest(dispatcher)); AppendAction(std::move(action)); *out = std::make_unique<MockDeviceThread>(std::move(interface)); } void ActionList::AppendReturnStatus(zx_status_t status) { Action action; action.set_return_status(status); return AppendAction(std::move(action)); } // Consume this action list, updating the given |map| and action counter. std::vector<ActionList::Action> ActionList::FinalizeActionList(CompleterMap* map, uint64_t* next_action_id) { CompleterMap local_ids; for (auto& action : actions_) { uint64_t* action_id = nullptr; if (action.is_add_device()) { action_id = &action.add_device().action_id; } else if (action.is_unbind_reply()) { action_id = &action.unbind_reply().action_id; } else { continue; } uint64_t local_action_id = *action_id; auto itr = local_action_map_.find(local_action_id); ZX_ASSERT(itr != local_action_map_.end()); uint64_t remote_action_id = (*next_action_id)++; (*map)[remote_action_id] = std::move(itr->second); local_action_map_.erase(itr); *action_id = remote_action_id; } return std::move(actions_); } } // namespace libdriver_integration_test
39.111111
100
0.685065
allansrc
290e6516a16472fd5303512fa1ae05e5dc760046
11,382
cpp
C++
boost/libs/range/test/join.cpp
randolphwong/mcsema
eb5b376736e7f57ff0a61f7e4e5a436bbb874720
[ "BSD-3-Clause" ]
11
2016-04-12T16:29:29.000Z
2021-06-28T11:01:57.000Z
boost/libs/range/test/join.cpp
randolphwong/mcsema
eb5b376736e7f57ff0a61f7e4e5a436bbb874720
[ "BSD-3-Clause" ]
3
2018-10-31T19:35:14.000Z
2019-06-04T17:11:27.000Z
boost/libs/range/test/join.cpp
randolphwong/mcsema
eb5b376736e7f57ff0a61f7e4e5a436bbb874720
[ "BSD-3-Clause" ]
9
2015-09-09T02:38:32.000Z
2021-01-30T00:24:24.000Z
// Boost.Range library // // Copyright Neil Groves 2010. Use, modification and // distribution is subject to the Boost Software License, Version // 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // // For more information, see http://www.boost.org/libs/range/ // #include <boost/range/join.hpp> #include <boost/foreach.hpp> #include <boost/test/test_tools.hpp> #include <boost/test/unit_test.hpp> #include <boost/assign.hpp> #include <boost/range/algorithm_ext.hpp> #include <boost/range/irange.hpp> #include <boost/iterator/iterator_facade.hpp> #include <algorithm> #include <deque> #include <list> #include <vector> namespace boost { namespace { // This function is a helper function that writes integers // of increasing value into a range. It is used to test // that joined ranged may be written to. // // Requires: // - Range uses shallow copy semantics. template< typename Range > void fill_with_ints(Range rng) { typedef typename range_iterator<Range>::type iterator; iterator target = boost::begin(rng); const int count = boost::distance(rng); for (int i = 0; i < count; ++i) { *target = i; ++target; } } // The test_join_traversal function is used to provide additional // tests based upon the underlying join iterator traversal. // The join iterator takes care of the appropriate demotion, and // this demotion. // test_join_traversal - additional tests for input and forward // traversal iterators. This is of course a no-op. template< typename Range1, typename Range2, typename TraversalTag > void test_join_traversal(Range1& rng1, Range2& rng2, TraversalTag) { } // test_join_traversal - additional tests for bidirectional // traversal iterators. template< typename Range1, typename Range2 > void test_join_traversal(Range1& rng1, Range2& rng2, boost::bidirectional_traversal_tag) { typedef typename range_value<Range1>::type value_type; std::vector<value_type> reference(boost::begin(rng1), boost::end(rng1)); boost::push_back(reference, rng2); std::reverse(reference.begin(), reference.end()); std::vector<value_type> test_result; BOOST_REVERSE_FOREACH( value_type x, join(rng1, rng2) ) { test_result.push_back(x); } BOOST_CHECK_EQUAL_COLLECTIONS( reference.begin(), reference.end(), test_result.begin(), test_result.end() ); } // Test helper function to implement the additional tests for random // access traversal iterators. This is used by the test_join_traversal // function for random access iterators. The reason that the test // implementation is put into this function is to utilise // template parameter type deduction for the joined range type. template< typename Range1, typename Range2, typename JoinedRange > void test_random_access_join(Range1& rng1, Range2& rng2, JoinedRange joined) { BOOST_CHECK_EQUAL( boost::end(joined) - boost::begin(joined), boost::distance(joined) ); BOOST_CHECK( boost::end(joined) <= boost::begin(joined) ); BOOST_CHECK( boost::begin(joined) >= boost::end(joined) ); if (boost::empty(joined)) { BOOST_CHECK(!(boost::begin(joined) < boost::end(joined))); BOOST_CHECK(!(boost::end(joined) > boost::begin(joined))); } else { BOOST_CHECK(boost::begin(joined) < boost::end(joined)); BOOST_CHECK(boost::end(joined) < boost::begin(joined)); } typedef typename boost::range_difference<JoinedRange>::type difference_t; const difference_t count = boost::distance(joined); BOOST_CHECK( boost::begin(joined) + count == boost::end(joined) ); BOOST_CHECK( boost::end(joined) - count == boost::begin(joined) ); typedef typename boost::range_iterator<JoinedRange>::type iterator_t; iterator_t it = boost::begin(joined); it += count; BOOST_CHECK( it == boost::end(joined) ); it = boost::end(joined); it -= count; BOOST_CHECK( it == boost::begin(joined) ); } // test_join_traversal function for random access traversal joined // ranges. template< typename Range1, typename Range2 > void test_join_traversal(Range1& rng1, Range2& rng2, boost::random_access_traversal_tag) { test_join_traversal(rng1, rng2, boost::bidirectional_traversal_tag()); test_random_access_join(rng1, rng2, join(rng1, rng2)); } // Test the ability to write values into a joined range. This is // achieved by copying the constant collections, altering them // and then checking the result. Hence this relies upon both // rng1 and rng2 having value copy semantics. template< typename Collection1, typename Collection2 > void test_write_to_joined_range(const Collection1& rng1, const Collection2& rng2) { Collection1 c1(rng1); Collection2 c2(rng2); typedef typename boost::range_value<Collection1>::type value_t; fill_with_ints(boost::join(c1,c2)); // Ensure that the size of the written range has not been // altered. BOOST_CHECK_EQUAL( boost::distance(c1), boost::distance(rng1) ); BOOST_CHECK_EQUAL( boost::distance(c2), boost::distance(rng2) ); // For each element x, in c1 ensure that it has been written to // with incrementing integers int x = 0; typedef typename range_iterator<Collection1>::type iterator1; iterator1 it1 = boost::begin(c1); for (; it1 != boost::end(c1); ++it1) { BOOST_CHECK_EQUAL( x, *it1 ); ++x; } // For each element y, in c2 ensure that it has been written to // with incrementing integers typedef typename range_iterator<Collection2>::type iterator2; iterator2 it2 = boost::begin(c2); for (; it2 != boost::end(c2); ++it2) { BOOST_CHECK_EQUAL( x, *it2 ); ++x; } } // Perform a unit test of a Boost.Range join() comparing // it to a reference that is populated by appending // elements from both source ranges into a vector. template< typename Collection1, typename Collection2 > void test_join_impl(Collection1& rng1, Collection2& rng2) { typedef typename range_value<Collection1>::type value_type; std::vector<value_type> reference(boost::begin(rng1), boost::end(rng1)); boost::push_back(reference, rng2); std::vector<value_type> test_result; boost::push_back(test_result, join(rng1, rng2)); BOOST_CHECK_EQUAL_COLLECTIONS( reference.begin(), reference.end(), test_result.begin(), test_result.end() ); typedef boost::range_detail::join_iterator< typename boost::range_iterator<Collection1>::type, typename boost::range_iterator<Collection2>::type > join_iterator_t; typedef boost::iterator_traversal< join_iterator_t > tag_t; test_join_traversal(rng1, rng2, tag_t()); test_write_to_joined_range(rng1, rng2); } // Make a collection filling it with items from the source // range. This is used to build collections of various // sizes populated with various values designed to optimize // the code coverage exercised by the core test function // test_join_impl. template<typename Collection, typename Range> boost::shared_ptr<Collection> makeCollection(const Range& source) { boost::shared_ptr<Collection> c(new Collection); c->insert(c->end(), boost::begin(source), boost::end(source)); return c; } // This templatised version of the test_join_impl function // generates and populates collections which are later // used as input to the core test function. // The caller of this function explicitly provides the // template parameters. This supports the generation // of testing a large combination of range types to be // joined. It is of particular importance to remember // to combine a random_access range with a bidirectional // range to determine that the correct demotion of // types occurs in the join_iterator. template< typename Collection1, typename Collection2 > void test_join_impl() { typedef boost::shared_ptr<Collection1> collection1_ptr; typedef boost::shared_ptr<Collection2> collection2_ptr; typedef boost::shared_ptr<const Collection1> collection1_cptr; typedef boost::shared_ptr<const Collection2> collection2_cptr; std::vector< collection1_cptr > left_containers; std::vector< collection2_cptr > right_containers; left_containers.push_back(collection1_ptr(new Collection1)); left_containers.push_back(makeCollection<Collection1>(irange(0,1))); left_containers.push_back(makeCollection<Collection1>(irange(0,100))); right_containers.push_back(collection2_ptr(new Collection2)); right_containers.push_back(makeCollection<Collection2>(irange(0,1))); right_containers.push_back(makeCollection<Collection2>(irange(0,100))); BOOST_FOREACH( collection1_cptr left_container, left_containers ) { BOOST_FOREACH( collection2_cptr right_container, right_containers ) { test_join_impl(*left_container, *right_container); } } } // entry-point into the unit test for the join() function // this tests a representative sample of combinations of // source range type. void join_test() { test_join_impl< std::vector<int>, std::vector<int> >(); test_join_impl< std::list<int>, std::list<int> >(); test_join_impl< std::deque<int>, std::deque<int> >(); test_join_impl< std::vector<int>, std::list<int> >(); test_join_impl< std::list<int>, std::vector<int> >(); test_join_impl< std::vector<int>, std::deque<int> >(); test_join_impl< std::deque<int>, std::vector<int> >(); } } } boost::unit_test::test_suite* init_unit_test_suite(int argc, char* argv[]) { boost::unit_test::test_suite* test = BOOST_TEST_SUITE( "RangeTestSuite.adaptor.joined" ); test->add( BOOST_TEST_CASE( &boost::join_test ) ); return test; }
41.540146
100
0.613864
randolphwong
2910b48c65c0d930885115dfcc8110717ade834b
2,106
cpp
C++
src/async/streamsocket.cpp
abbyssoul/libcadence
c9a49d95df608497e9551f7d62169d0c78a48737
[ "Apache-2.0" ]
2
2020-04-24T15:07:33.000Z
2020-06-12T07:01:53.000Z
src/async/streamsocket.cpp
abbyssoul/libcadence
c9a49d95df608497e9551f7d62169d0c78a48737
[ "Apache-2.0" ]
null
null
null
src/async/streamsocket.cpp
abbyssoul/libcadence
c9a49d95df608497e9551f7d62169d0c78a48737
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) Ivan Ryabov - All Rights Reserved * * Unauthorized copying of this file, via any medium is strictly prohibited. * Proprietary and confidential. * * Written by Ivan Ryabov <abbyssoul@gmail.com> */ /******************************************************************************* * @file: async/streamsocket.cpp *******************************************************************************/ #include "cadence/async/streamsocket.hpp" #include "streamsocket_impl.hpp" using namespace Solace; using namespace cadence; using namespace cadence::async; StreamSocket::StreamSocketImpl::~StreamSocketImpl() = default; StreamSocket::~StreamSocket() = default; StreamSocket::StreamSocket(EventLoop& ioContext, std::unique_ptr<StreamSocketImpl> impl) : Channel(ioContext), _pimpl(std::move(impl)) { } Future<void> StreamSocket::asyncRead(ByteWriter& dest, size_type bytesToRead) { return _pimpl->asyncRead(dest, bytesToRead); } Future<void> StreamSocket::asyncWrite(ByteReader& src, size_type bytesToWrite) { return _pimpl->asyncWrite(src, bytesToWrite); } Result<void, Error> StreamSocket::read(ByteWriter& dest, size_type bytesToRead) { return _pimpl->read(dest, bytesToRead); } Result<void, Error> StreamSocket::write(ByteReader& src, size_type bytesToWrite) { return _pimpl->write(src, bytesToWrite); } void StreamSocket::cancel() { _pimpl->cancel(); } void StreamSocket::close() { _pimpl->close(); } bool StreamSocket::isOpen() const { return _pimpl->isOpen(); } bool StreamSocket::isClosed() const{ return _pimpl->isClosed(); } NetworkEndpoint StreamSocket::getLocalEndpoint() const { return _pimpl->getLocalEndpoint(); } NetworkEndpoint StreamSocket::getRemoteEndpoint() const { return _pimpl->getRemoteEndpoint(); } void StreamSocket::shutdown() { _pimpl->shutdown(); } Future<void> StreamSocket::asyncConnect(NetworkEndpoint const& endpoint) { return _pimpl->asyncConnect(endpoint); } Result<void, Error> StreamSocket::connect(NetworkEndpoint const& endpoint) { return _pimpl->connect(endpoint); }
22.404255
90
0.681387
abbyssoul
2910d0bbe140a2abddcab117ae649081e429c159
1,915
cpp
C++
workshop 2020/Stl algorithms/3sum/main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
workshop 2020/Stl algorithms/3sum/main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
workshop 2020/Stl algorithms/3sum/main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <map> #include <limits> #include <algorithm> #define int long long using namespace std; signed main() { int n; cin >> n; cin.tie(0); ios_base::sync_with_stdio(false); vector<int> tmpInput(n); map<int, int>occurences; for (int i = 0; i < n; ++i) { cin >> tmpInput[i]; occurences[tmpInput[i]]++; } sort(tmpInput.begin(), tmpInput.end()); vector<pair<int, int>>input;//Value, occurences input.push_back(make_pair(tmpInput[0], 1)); int offSet = 0; for (int i = 1; i < n+offSet; ++i) { if(input[i-1-offSet].first == tmpInput[i]){ input[i-1-offSet].second++; offSet++; n--; } else{ input.push_back(make_pair(tmpInput[i], 1)); } } int combinationSum = 0; for (int i = 0; i < n - 2; ++i) { int curCombinations = 0; int headIndex = i + 2; for (int bIndex = i + 1; bIndex < n - 1; ++bIndex) { if(headIndex==n){ break; } while (input[headIndex].first < input[i].first + input[bIndex].first && headIndex!=n-1) { headIndex++; } if(headIndex==n){ break; } while (input[headIndex].first == input[i].first + input[bIndex].first) { if(headIndex==n){ break; } curCombinations+=input[headIndex].second*input[bIndex].second*input[i].second; headIndex++; } } combinationSum += curCombinations; } for (int i = 0; i < n; ++i) { if(input[i].second >= 2 && occurences[2*input[i].first]){ combinationSum+=occurences[2*input[i].first]*((input[i].second)*(input[i].second-1)/2); } } cout << combinationSum << "\n"; }
24.551282
101
0.49295
wdjpng
2911155dca15a375accd81c489513c54a8c827c8
1,573
hpp
C++
doc/quickbook/oglplus/quickref/images/image.hpp
highfidelity/oglplus
c5fb7cc21869cb9555cfa2a7e28ea6bc6491d11e
[ "BSL-1.0" ]
2
2017-06-09T00:28:35.000Z
2017-06-09T00:28:43.000Z
doc/quickbook/oglplus/quickref/images/image.hpp
highfidelity/oglplus
c5fb7cc21869cb9555cfa2a7e28ea6bc6491d11e
[ "BSL-1.0" ]
null
null
null
doc/quickbook/oglplus/quickref/images/image.hpp
highfidelity/oglplus
c5fb7cc21869cb9555cfa2a7e28ea6bc6491d11e
[ "BSL-1.0" ]
8
2017-01-30T22:06:41.000Z
2020-01-14T17:24:36.000Z
/* * Copyright 2014-2015 Matus Chochlik. 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) */ //[oglplus_images_Image namespace oglplus { namespace images { class Image { public: Image(const Image& that); Image(Image&& tmp) noexcept; Image& operator = (Image&& tmp) noexcept; template <typename T> Image( GLsizei width, GLsizei height, GLsizei depth, GLsizei channels, const T* data ); template <typename T> Image( GLsizei width, GLsizei height, GLsizei depth, GLsizei channels, const T* data, __PixelDataFormat format, __PixelDataInternalFormat internal ); GLsizei Dimension(std::size_t i) const noexcept; /*< Returns the size of the i-th dimension of the image. >*/ GLsizei Width(void) const noexcept; /*< Returns the width of the image. >*/ GLsizei Height(void) const noexcept; /*< Returns the height of the image. >*/ GLsizei Depth(void) const noexcept; /*< Returns the depth of the image. >*/ GLsizei Channels(void) const noexcept; /*< Returns the number of channels. >*/ __PixelDataType Type(void) const noexcept; __PixelDataFormat Format(void) const noexcept; __PixelDataInternalFormat InternalFormat(void) const noexcept; template <typename T> const T* Data(void) const noexcept; const void* RawData(void) const noexcept; std::size_t DataSize(void) const noexcept; /*< Returns the size of data in bytes. >*/ //TODO }; } // namespace images } // namespace oglplus //]
16.557895
68
0.708837
highfidelity
291135aab35acc814617da41479d58d2ea8d9adb
299
cpp
C++
src/ast/Import.cpp
denisw/soyac
2531e16e8dfbfa966931b774f9d79af528d16ff9
[ "MIT" ]
1
2019-06-17T07:16:01.000Z
2019-06-17T07:16:01.000Z
src/ast/Import.cpp
denisw/soyac
2531e16e8dfbfa966931b774f9d79af528d16ff9
[ "MIT" ]
null
null
null
src/ast/Import.cpp
denisw/soyac
2531e16e8dfbfa966931b774f9d79af528d16ff9
[ "MIT" ]
null
null
null
/* * soyac - Soya Programming Language compiler * Copyright (c) 2009 Denis Washington <dwashington@gmx.net> * * This file is distributed under the terms of the MIT license. * See LICENSE.txt for details. */ #include "Import.hpp" namespace soyac { namespace ast { Import::Import() { } }}
13.590909
63
0.695652
denisw
2911ba4bcd0e1dbf50934f958c59da2234e4ea66
520
cpp
C++
Hackerrank/apple-and-orange.cpp
ronayumik/Learning-c-
b754d5e6ce92f091f1175a866c99c49561e87f22
[ "MIT" ]
null
null
null
Hackerrank/apple-and-orange.cpp
ronayumik/Learning-c-
b754d5e6ce92f091f1175a866c99c49561e87f22
[ "MIT" ]
3
2019-04-13T16:27:37.000Z
2019-04-13T16:52:57.000Z
Hackerrank/apple-and-orange.cpp
ronayumik/Learning-c-
b754d5e6ce92f091f1175a866c99c49561e87f22
[ "MIT" ]
1
2018-12-05T23:17:35.000Z
2018-12-05T23:17:35.000Z
#include<bits/stdc++.h> using namespace std; int s,t,b,a,m,n; int apple, orange; int temp; void countApple(int pos){ if(pos+a<= t && pos+a >= s) apple++; } void countOrange(int pos){ if(pos+b<= t && pos+b >= s) orange++; } int main(){ cin >> s >> t >> a >> b >> m >> n; apple=0; orange=0; for(int x=0;x<m;x++) { cin >> temp; countApple(temp); } for(int x=0;x<n;x++) { cin >> temp; countOrange(temp); } cout << apple << " " << orange << endl; return 0; }
14.444444
41
0.498077
ronayumik
29124957a1301654529a161d64a0868e67fea641
322
hpp
C++
openstudiocore/src/isomodel/ISOModelAPI.hpp
OpenStudioThailand/OpenStudio
4e2173955e687ef1b934904acc10939ac0bed52f
[ "MIT" ]
1
2017-10-13T09:23:04.000Z
2017-10-13T09:23:04.000Z
openstudiocore/src/isomodel/ISOModelAPI.hpp
OpenStudioThailand/OpenStudio
4e2173955e687ef1b934904acc10939ac0bed52f
[ "MIT" ]
null
null
null
openstudiocore/src/isomodel/ISOModelAPI.hpp
OpenStudioThailand/OpenStudio
4e2173955e687ef1b934904acc10939ac0bed52f
[ "MIT" ]
1
2022-03-20T13:19:42.000Z
2022-03-20T13:19:42.000Z
#ifndef ISOMODEL_ISOMODELAPI_HPP #define ISOMODEL_ISOMODELAPI_HPP #if (_WIN32 || _MSC_VER) && SHARED_OS_LIBS #ifdef openstudio_isomodel_EXPORTS #define ISOMODEL_API __declspec(dllexport) #else #define ISOMODEL_API __declspec(dllimport) #endif #else #define ISOMODEL_API #endif #endif
21.466667
48
0.736025
OpenStudioThailand
291259dc263c23a49a8ce47a2547998b869f75e9
11,197
cxx
C++
Testing/TU/Code/Core/Data/IO/vnsImageFileReaderTest.cxx
spacebel/MAJA
3e5d20bc9c744c610e608cfcf1f4c5c738d4de9e
[ "Apache-2.0" ]
57
2020-09-30T08:51:22.000Z
2021-12-19T20:28:30.000Z
Testing/TU/Code/Core/Data/IO/vnsImageFileReaderTest.cxx
spacebel/MAJA
3e5d20bc9c744c610e608cfcf1f4c5c738d4de9e
[ "Apache-2.0" ]
34
2020-09-29T21:27:22.000Z
2022-02-03T09:56:45.000Z
Testing/TU/Code/Core/Data/IO/vnsImageFileReaderTest.cxx
spacebel/MAJA
3e5d20bc9c744c610e608cfcf1f4c5c738d4de9e
[ "Apache-2.0" ]
14
2020-10-11T13:17:59.000Z
2022-03-09T15:58:19.000Z
/* * Copyright (C) 2020 Centre National d'Etudes Spatiales (CNES) * * 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. * */ /************************************************************************************************************ * * * ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo * * o * * o * * o * * o * * o ooooooo ooooooo o o oo * * o o o o o o o o o o * * o o o o o o o o o o * * o o o o o o o o o o * * o o o oooo o o o o o o * * o o o o o o o o o * * o o o o o o o o o o * * oo oooooooo o o o oooooo o oooo * * o * * o * * o o * * o o oooo o o oooo * * o o o o o o * * o o ooo o o ooo * * o o o o o * * ooooo oooo o ooooo oooo * * o * * * ************************************************************************************************************ * * * Author: CS Systemes d'Information (France) * * * ************************************************************************************************************ * HISTORIQUE * * * * VERSION : 1-0-0 : <TypeFT> : <NumFT> : 18 mars 2010 : Creation * * * FIN-HISTORIQUE * * * * $Id$ * * ************************************************************************************************************/ #include "otbImage.h" #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" #include "otbCommandLineArgumentParser.h" #include "itkMultiThreader.h" #include "vnsMacro.h" #include "vnsGRIBImageIOFactory.h" #include "itkObjectFactoryBase.h" #include "itkMetaImageIOFactory.h" template<typename ImageType> void copy_image(const std::string & inputFilename, const std::string & outputFilename, const unsigned int mode, const unsigned long nbtile) { typedef otb::ImageFileReader<ImageType> ReaderType; typedef otb::ImageFileWriter<ImageType> WriterType; typename ReaderType::Pointer reader = ReaderType::New(); typename WriterType::Pointer writer = WriterType::New(); reader->SetFileName(inputFilename); writer->SetFileName(outputFilename); writer->SetInput(reader->GetOutput()); switch (mode) { case vns::NUMBER_OF_LINES_STRIPPED_STREAMING: std::cout << "Mode division: SetNumberOfLinesStrippedStreaming" << std::endl; writer->SetNumberOfLinesStrippedStreaming(nbtile); break; case vns::NUMBER_OF_DIVISIONS_STRIPPED_STREAMING: std::cout << "Mode division: SetNumberOfDivisionsStrippedStreaming" << std::endl; writer->SetNumberOfDivisionsStrippedStreaming(nbtile); break; case vns::NUMBER_OF_DIVISIONS_TILED_STREAMING: std::cout << "Mode division: SetNumberOfDivisionsTiledStreaming" << std::endl; writer->SetNumberOfDivisionsTiledStreaming(nbtile); break; case vns::AUTOMATIC_STRIPPED_STREAMING: std::cout << "Mode division: SetAutomaticStrippedStreaming" << std::endl; writer->SetAutomaticStrippedStreaming(); break; case vns::AUTOMATIC_TILED_STREAMING: std::cout << "Mode division:SetAutomaticTiledStreaming " << std::endl; writer->SetAutomaticTiledStreaming(); break; case vns::AUTOMATIC_ADAPTATIVE_STREAMING: std::cout << "Mode division: SetAutomaticAdaptativeStreaming" << std::endl; writer->SetAutomaticAdaptativeStreaming(); break; } writer->Update(); } int otbImageFileReaderTest(int argc, char* argv[]) { // ------------------------------------------------------------------------------------------------------- // Register the MACCS ImageIO itk::ObjectFactoryBase::RegisterFactory( vns::GRIBImageIOFactory::New() ); itk::ObjectFactoryBase::RegisterFactory( itk::MetaImageIOFactory::New() ); // Parse command line parameters typedef otb::CommandLineArgumentParser ParserType; ParserType::Pointer parser = ParserType::New(); parser->SetProgramDescription("Copy image."); parser->AddInputImage(); parser->AddOutputImage(); parser->AddOption("--ImageType", "ImageType: VI(VectoreImage)_D(dboule)_2D(Dimensions)", "-i", 1, true); parser->AddOption("--ModeStreamDivisions", "ModeStreamDivisions", "-m", 1, true); parser->AddOption("--TilingStreamDivisions", "TilingStreamDivisions", "-t", 1, true); parser->AddOption("--NbThreads", "NbThreads", "-n", 1, true); typedef otb::CommandLineArgumentParseResult ParserResultType; ParserResultType::Pointer parseResult = ParserResultType::New(); try { parser->ParseCommandLine(argc, argv, parseResult); } catch (itk::ExceptionObject & err) { std::string descriptionException = err.GetDescription(); if (descriptionException.find("ParseCommandLine(): Help Parser") != std::string::npos) { std::cout << "WARNING : output file pixels are converted in 'unsigned char'" << std::endl; return EXIT_SUCCESS; } if (descriptionException.find("ParseCommandLine(): Version Parser") != std::string::npos) { return EXIT_SUCCESS; } return EXIT_FAILURE; } const std::string TYPE = parseResult->GetParameterString("--ImageType"); const unsigned long nbtile = parseResult->GetParameterULong("--TilingStreamDivisions"); const int nbthreads = parseResult->GetParameterInt("--NbThreads"); const unsigned int mode = parseResult->GetParameterULong("--ModeStreamDivisions"); std::cout << "parseResult->GetInputImage() :" << parseResult->GetInputImage() << std::endl; std::cout << "parseResult->GetOutputImage() :" << parseResult->GetOutputImage() << std::endl; std::cout << "TYPE : " << TYPE << std::endl; std::cout << "nbtile : " << nbtile << std::endl; std::cout << "nbthreads : " << nbthreads << std::endl; std::cout << "Input filename : " << parseResult->GetInputImage().c_str() << std::endl; std::cout << "Output filename: " << parseResult->GetOutputImage().c_str() << std::endl; itk::MultiThreader::SetGlobalDefaultNumberOfThreads(nbthreads); const int checkNumberOfThreads = itk::MultiThreader::GetGlobalDefaultNumberOfThreads(); if (nbthreads != checkNumberOfThreads) { std::cout << "Impossible to affect "<<nbthreads<<" number of threads for the test. The number of threads use is "<<checkNumberOfThreads<<" !"; return EXIT_FAILURE; } if (TYPE == "VI_D_2D") copy_image<otb::VectorImage<double, 2> >(parseResult->GetInputImage().c_str(), parseResult->GetOutputImage().c_str(), mode, nbtile); else if (TYPE == "VI_F_2D") copy_image<otb::VectorImage<float, 2> >(parseResult->GetInputImage().c_str(), parseResult->GetOutputImage().c_str(), mode, nbtile); else if (TYPE == "VI_S_2D") copy_image<otb::VectorImage<short, 2> >(parseResult->GetInputImage().c_str(), parseResult->GetOutputImage().c_str(), mode, nbtile); else if (TYPE == "VI_UC_2D") copy_image<otb::VectorImage<unsigned char, 2> >(parseResult->GetInputImage().c_str(), parseResult->GetOutputImage().c_str(), mode, nbtile); else if (TYPE == "I_D_2D") copy_image<otb::Image<double, 2> >(parseResult->GetInputImage().c_str(), parseResult->GetOutputImage().c_str(), mode, nbtile); else if (TYPE == "I_UC_2D") copy_image<otb::Image<unsigned char, 2> >(parseResult->GetInputImage().c_str(), parseResult->GetOutputImage().c_str(), mode, nbtile); return EXIT_SUCCESS; }
57.420513
150
0.442797
spacebel
291384cb483441cff73b50373db6157e280152f1
12,672
cc
C++
caffe2/core/plan_executor_test.cc
Gamrix/pytorch
b5b158a6c6de94dfb983b447fa33fea062358844
[ "Intel" ]
null
null
null
caffe2/core/plan_executor_test.cc
Gamrix/pytorch
b5b158a6c6de94dfb983b447fa33fea062358844
[ "Intel" ]
null
null
null
caffe2/core/plan_executor_test.cc
Gamrix/pytorch
b5b158a6c6de94dfb983b447fa33fea062358844
[ "Intel" ]
null
null
null
#ifndef ANDROID #include <gtest/gtest.h> #include "caffe2/core/init.h" #include "caffe2/core/operator.h" #include "caffe2/core/plan_executor.h" namespace caffe2 { // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) TEST(PlanExecutorTest, EmptyPlan) { PlanDef plan_def; Workspace ws; EXPECT_TRUE(ws.RunPlan(plan_def)); } namespace { // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) static std::atomic<int> cancelCount{0}; // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) static std::atomic<bool> stuckRun{false}; } // namespace class StuckBlockingOp final : public Operator<CPUContext> { public: StuckBlockingOp(const OperatorDef& operator_def, Workspace* ws) : Operator<CPUContext>(operator_def, ws) {} bool RunOnDevice() override { // StuckBlockingOp runs and notifies ErrorOp. stuckRun = true; while (!cancelled_) { // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) std::this_thread::sleep_for(std::chrono::milliseconds(10)); } return true; } void Cancel() override { LOG(INFO) << "cancelled StuckBlockingOp."; cancelCount += 1; cancelled_ = true; } private: std::atomic<bool> cancelled_{false}; }; // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) REGISTER_CPU_OPERATOR(StuckBlocking, StuckBlockingOp); // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) OPERATOR_SCHEMA(StuckBlocking).NumInputs(0).NumOutputs(0); class NoopOp final : public Operator<CPUContext> { public: NoopOp(const OperatorDef& operator_def, Workspace* ws) : Operator<CPUContext>(operator_def, ws) {} bool RunOnDevice() override { // notify Error op we've ran. stuckRun = true; return true; } }; // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) REGISTER_CPU_OPERATOR(Noop, NoopOp); // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) OPERATOR_SCHEMA(Noop).NumInputs(0).NumOutputs(0); class StuckAsyncOp final : public Operator<CPUContext> { public: StuckAsyncOp(const OperatorDef& operator_def, Workspace* ws) : Operator<CPUContext>(operator_def, ws) {} bool RunOnDevice() override { // notify Error op we've ran. stuckRun = true; // explicitly don't call SetFinished so this gets stuck return true; } void CancelAsyncCallback() override { LOG(INFO) << "cancelled"; cancelCount += 1; } bool HasAsyncPart() const override { return true; } }; // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) REGISTER_CPU_OPERATOR(StuckAsync, StuckAsyncOp); // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) OPERATOR_SCHEMA(StuckAsync).NumInputs(0).NumOutputs(0); class TestError : public std::exception { const char* what() const noexcept override { return "test error"; } }; class ErrorOp final : public Operator<CPUContext> { public: ErrorOp(const OperatorDef& operator_def, Workspace* ws) : Operator<CPUContext>(operator_def, ws) {} bool RunOnDevice() override { // Wait for StuckAsyncOp or StuckBlockingOp to run first. while (!stuckRun) { // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) std::this_thread::sleep_for(std::chrono::milliseconds(10)); } throw TestError(); return true; } }; // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) REGISTER_CPU_OPERATOR(Error, ErrorOp); // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) OPERATOR_SCHEMA(Error).NumInputs(0).NumOutputs(0); // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) static std::atomic<int> blockingErrorRuns{0}; class BlockingErrorOp final : public Operator<CPUContext> { public: BlockingErrorOp(const OperatorDef& operator_def, Workspace* ws) : Operator<CPUContext>(operator_def, ws) {} bool RunOnDevice() override { // First n op executions should block and then start throwing errors. if (blockingErrorRuns.fetch_sub(1) >= 1) { LOG(INFO) << "blocking"; while (true) { // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) std::this_thread::sleep_for(std::chrono::hours(10)); } } else { LOG(INFO) << "throwing"; throw TestError(); } } }; // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) REGISTER_CPU_OPERATOR(BlockingError, BlockingErrorOp); // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) OPERATOR_SCHEMA(BlockingError).NumInputs(0).NumOutputs(0); PlanDef parallelErrorPlan() { PlanDef plan_def; auto* stuck_net = plan_def.add_network(); stuck_net->set_name("stuck_net"); stuck_net->set_type("async_scheduling"); { auto* op = stuck_net->add_op(); op->set_type("StuckAsync"); } auto* error_net = plan_def.add_network(); error_net->set_name("error_net"); error_net->set_type("async_scheduling"); { auto op = error_net->add_op(); op->set_type("Error"); } auto* execution_step = plan_def.add_execution_step(); execution_step->set_concurrent_substeps(true); { auto* substep = execution_step->add_substep(); substep->add_network(stuck_net->name()); } { auto* substep = execution_step->add_substep(); substep->add_network(error_net->name()); } return plan_def; } PlanDef parallelErrorPlanWithCancellableStuckNet() { // Set a plan with two nets: one stuck net with blocking operator that never // returns; one error net with error op that throws. PlanDef plan_def; auto* stuck_blocking_net = plan_def.add_network(); stuck_blocking_net->set_name("stuck_blocking_net"); { auto* op = stuck_blocking_net->add_op(); op->set_type("StuckBlocking"); } auto* error_net = plan_def.add_network(); error_net->set_name("error_net"); { auto* op = error_net->add_op(); op->set_type("Error"); } auto* execution_step = plan_def.add_execution_step(); execution_step->set_concurrent_substeps(true); { auto* substep = execution_step->add_substep(); substep->add_network(stuck_blocking_net->name()); } { auto* substep = execution_step->add_substep(); substep->add_network(error_net->name()); } return plan_def; } PlanDef reporterErrorPlanWithCancellableStuckNet() { // Set a plan with a concurrent net and a reporter net: one stuck net with // blocking operator that never returns; one reporter net with error op // that throws. PlanDef plan_def; auto* stuck_blocking_net = plan_def.add_network(); stuck_blocking_net->set_name("stuck_blocking_net"); { auto* op = stuck_blocking_net->add_op(); op->set_type("StuckBlocking"); } auto* error_net = plan_def.add_network(); error_net->set_name("error_net"); { auto* op = error_net->add_op(); op->set_type("Error"); } auto* execution_step = plan_def.add_execution_step(); execution_step->set_concurrent_substeps(true); { auto* substep = execution_step->add_substep(); substep->add_network(stuck_blocking_net->name()); } { auto* substep = execution_step->add_substep(); substep->set_run_every_ms(1); substep->add_network(error_net->name()); } return plan_def; } struct HandleExecutorThreadExceptionsGuard { // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) HandleExecutorThreadExceptionsGuard(int timeout = 60) { globalInit({ "caffe2", "--caffe2_handle_executor_threads_exceptions=1", "--caffe2_plan_executor_exception_timeout=" + caffe2::to_string(timeout), }); } ~HandleExecutorThreadExceptionsGuard() { globalInit({ "caffe2", }); } HandleExecutorThreadExceptionsGuard( const HandleExecutorThreadExceptionsGuard&) = delete; void operator=(const HandleExecutorThreadExceptionsGuard&) = delete; private: void globalInit(std::vector<std::string> args) { std::vector<char*> args_ptrs; for (auto& arg : args) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast,performance-inefficient-vector-operation) args_ptrs.push_back(const_cast<char*>(arg.data())); } char** new_argv = args_ptrs.data(); int new_argc = args.size(); CAFFE_ENFORCE(GlobalInit(&new_argc, &new_argv)); } }; // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) TEST(PlanExecutorTest, ErrorAsyncPlan) { HandleExecutorThreadExceptionsGuard guard; cancelCount = 0; PlanDef plan_def = parallelErrorPlan(); Workspace ws; // NOLINTNEXTLINE(cppcoreguidelines-avoid-goto,hicpp-avoid-goto) ASSERT_THROW(ws.RunPlan(plan_def), TestError); ASSERT_EQ(cancelCount, 1); } // death tests not supported on mobile #if !defined(CAFFE2_IS_XPLAT_BUILD) && !defined(C10_MOBILE) // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) TEST(PlanExecutorTest, BlockingErrorPlan) { // TSAN doesn't play nicely with death tests #if defined(__has_feature) #if __has_feature(thread_sanitizer) return; #endif #endif // NOLINTNEXTLINE(cppcoreguidelines-avoid-goto,hicpp-avoid-goto) ASSERT_DEATH( [] { HandleExecutorThreadExceptionsGuard guard(/*timeout=*/1); PlanDef plan_def; std::string plan_def_template = R"DOC( network { name: "net" op { type: "BlockingError" } } execution_step { num_concurrent_instances: 2 substep { network: "net" } } )DOC"; CAFFE_ENFORCE( TextFormat::ParseFromString(plan_def_template, &plan_def)); Workspace ws; blockingErrorRuns = 1; ws.RunPlan(plan_def); FAIL() << "shouldn't have reached this point"; }(), "failed to stop concurrent workers after exception: test error"); } #endif // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) TEST(PlanExecutorTest, ErrorPlanWithCancellableStuckNet) { HandleExecutorThreadExceptionsGuard guard; cancelCount = 0; PlanDef plan_def = parallelErrorPlanWithCancellableStuckNet(); Workspace ws; // NOLINTNEXTLINE(cppcoreguidelines-avoid-goto,hicpp-avoid-goto) ASSERT_THROW(ws.RunPlan(plan_def), TestError); ASSERT_EQ(cancelCount, 1); } // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) TEST(PlanExecutorTest, ReporterErrorPlanWithCancellableStuckNet) { HandleExecutorThreadExceptionsGuard guard; cancelCount = 0; PlanDef plan_def = reporterErrorPlanWithCancellableStuckNet(); Workspace ws; // NOLINTNEXTLINE(cppcoreguidelines-avoid-goto,hicpp-avoid-goto) ASSERT_THROW(ws.RunPlan(plan_def), TestError); ASSERT_EQ(cancelCount, 1); } PlanDef shouldStopWithCancelPlan() { // Set a plan with a looping net with should_stop_blob set and a concurrent // net that throws an error. The error should cause should_stop to return // false and end the concurrent net. PlanDef plan_def; auto* should_stop_net = plan_def.add_network(); { auto* op = should_stop_net->add_op(); op->set_type("Noop"); } should_stop_net->set_name("should_stop_net"); should_stop_net->set_type("async_scheduling"); auto* error_net = plan_def.add_network(); error_net->set_name("error_net"); { auto* op = error_net->add_op(); op->set_type("Error"); } auto* execution_step = plan_def.add_execution_step(); execution_step->set_concurrent_substeps(true); { auto* substep = execution_step->add_substep(); execution_step->set_concurrent_substeps(true); substep->set_name("concurrent_should_stop"); substep->set_should_stop_blob("should_stop_blob"); auto* substep2 = substep->add_substep(); substep2->set_name("should_stop_net"); substep2->add_network(should_stop_net->name()); // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) substep2->set_num_iter(10); } { auto* substep = execution_step->add_substep(); substep->set_name("error_step"); substep->add_network(error_net->name()); } return plan_def; } // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) TEST(PlanExecutorTest, ShouldStopWithCancel) { HandleExecutorThreadExceptionsGuard guard; stuckRun = false; PlanDef plan_def = shouldStopWithCancelPlan(); Workspace ws; Blob* blob = ws.CreateBlob("should_stop_blob"); Tensor* tensor = BlobGetMutableTensor(blob, CPU); const vector<int64_t>& shape{1}; tensor->Resize(shape); tensor->mutable_data<bool>()[0] = false; // NOLINTNEXTLINE(cppcoreguidelines-avoid-goto,hicpp-avoid-goto) ASSERT_THROW(ws.RunPlan(plan_def), TestError); ASSERT_TRUE(stuckRun); } } // namespace caffe2 #endif
28.997712
103
0.716619
Gamrix
2917b33362c13ad0847284d08e72c8e4ff6a3eb9
652
hpp
C++
Spades Game/Game/Avatar/AvatarComponent.hpp
jmasterx/StemwaterSpades
05e5d7c6d380d2f5986bd91269887f16c3e71962
[ "Unlicense" ]
6
2017-01-04T22:40:50.000Z
2019-11-24T15:37:46.000Z
Spades Game/Game/Avatar/AvatarComponent.hpp
jmasterx/StemwaterSpades
05e5d7c6d380d2f5986bd91269887f16c3e71962
[ "Unlicense" ]
1
2016-09-18T19:10:01.000Z
2017-08-04T23:53:38.000Z
Spades Game/Game/Avatar/AvatarComponent.hpp
jmasterx/StemwaterSpades
05e5d7c6d380d2f5986bd91269887f16c3e71962
[ "Unlicense" ]
2
2015-11-21T16:42:18.000Z
2019-04-21T20:41:39.000Z
#ifndef CGE_AVATAR_COMPONENT_HPP #define CGE_AVATAR_COMPONENT_HPP #include "Game/Resource/Sprite.hpp" #include <stdlib.h> #include <string> namespace cge { //not really used... part of original avatar system class AvatarComponent { float m_scale; float m_x; float m_y; std::string m_imgPath; Sprite* m_sprite; public: AvatarComponent(std::string imgPath, float scale,float x,float y); float getX() const; float getY() const; float getScale() const; const std::string& getImgPath() const; void setSprite(Sprite* sprite); Sprite* getSprite(); const Sprite* getSprite() const; virtual ~AvatarComponent(void); }; } #endif
21.733333
68
0.730061
jmasterx
291affa8207c5a57f516bcad95855135a6ee153c
8,772
cc
C++
src/drivers/devices/ascend/flowunit/inference/atc_inference_flowunit_test.cc
yamal-shang/modelbox
b2785568f4acd56d4922a793aa25516f883edc26
[ "Apache-2.0" ]
51
2021-09-24T08:57:44.000Z
2022-03-31T09:12:46.000Z
src/drivers/devices/ascend/flowunit/inference/atc_inference_flowunit_test.cc
yamal-shang/modelbox
b2785568f4acd56d4922a793aa25516f883edc26
[ "Apache-2.0" ]
3
2022-02-22T07:13:02.000Z
2022-03-30T02:03:40.000Z
src/drivers/devices/ascend/flowunit/inference/atc_inference_flowunit_test.cc
yamal-shang/modelbox
b2785568f4acd56d4922a793aa25516f883edc26
[ "Apache-2.0" ]
31
2021-11-29T02:22:39.000Z
2022-03-15T03:05:24.000Z
/* * Copyright 2021 The Modelbox Project Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <dsmi_common_interface.h> #include <functional> #include <future> #include <random> #include <thread> #include "modelbox/base/log.h" #include "modelbox/base/utils.h" #include "modelbox/buffer.h" #include "driver_flow_test.h" #include "flowunit_mockflowunit/flowunit_mockflowunit.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "test/mock/minimodelbox/mockflow.h" using ::testing::_; namespace modelbox { class InferenceAscendFlowUnitTest : public testing::Test { public: InferenceAscendFlowUnitTest() : driver_flow_(std::make_shared<MockFlow>()) {} protected: virtual void SetUp() { // Test ascend runtime int32_t count = 0; auto dsmi_ret = dsmi_get_device_count(&count); if (dsmi_ret != 0) { MBLOG_INFO << "no ascend device, skip test suit"; GTEST_SKIP(); } auto ret = AddMockFlowUnit(); EXPECT_EQ(ret, STATUS_OK); const std::string src_file = test_assets + "/atc_inference/" + test_model_file; const std::string src_toml = test_data_dir + "/" + test_toml_file; atc_inference_path = test_data_dir + "/atc_inference"; mkdir(atc_inference_path.c_str(), 0700); dest_model_file = atc_inference_path + "/" + test_model_file; dest_toml_file = atc_inference_path + "/" + test_toml_file; CopyFile(src_file, dest_model_file, true); CopyFile(src_toml, dest_toml_file, true); const std::string src_file_en = test_assets + "/atc_inference/" + test_model_file_en; const std::string src_toml_en = test_data_dir + "/" + test_toml_file_en; dest_model_file_en = atc_inference_path + "/" + test_model_file_en; dest_toml_file_en = atc_inference_path + "/" + test_toml_file_en; CopyFile(src_file_en, dest_model_file_en, true); CopyFile(src_toml_en, dest_toml_file_en, true); } virtual void TearDown() { remove(dest_model_file.c_str()); remove(dest_toml_file.c_str()); remove(dest_model_file_en.c_str()); remove(dest_toml_file_en.c_str()); remove(atc_inference_path.c_str()); driver_flow_ = nullptr; }; std::shared_ptr<MockFlow> GetDriverFlow(); const std::string test_lib_dir = TEST_DRIVER_DIR, test_data_dir = TEST_DATA_DIR, test_assets = TEST_ASSETS, test_model_file = "2d_2048_w_stage1_pad0.om", test_toml_file = "virtual_atc_infer_test.toml", test_model_file_en = "2d_2048_w_stage1_pad0_en.om", test_toml_file_en = "virtual_atc_infer_test_en.toml"; std::string atc_inference_path, dest_model_file, dest_toml_file, dest_model_file_en, dest_toml_file_en; private: Status AddMockFlowUnit(); std::shared_ptr<MockFlow> driver_flow_; }; Status InferenceAscendFlowUnitTest::AddMockFlowUnit() { { auto mock_desc = GenerateFlowunitDesc("prepare_infer_data", {}, {"out"}); mock_desc->SetFlowType(STREAM); auto open_func = [=](const std::shared_ptr<modelbox::Configuration>& flow_option, std::shared_ptr<MockFlowUnit> mock_flowunit) { auto ext_data = mock_flowunit->CreateExternalData(); if (!ext_data) { MBLOG_ERROR << "can not get external data."; } auto buffer_list = ext_data->CreateBufferList(); buffer_list->Build({10}); auto status = ext_data->Send(buffer_list); if (!status) { MBLOG_ERROR << "external data send buffer list failed:" << status; } status = ext_data->Close(); if (!status) { MBLOG_ERROR << "external data close failed:" << status; } return modelbox::STATUS_OK; }; auto process_func = [=](std::shared_ptr<DataContext> op_ctx, std::shared_ptr<MockFlowUnit> mock_flowunit) { MBLOG_INFO << "prepare_infer_data Process"; auto output_buf_1 = op_ctx->Output("out"); const size_t len = 2048; std::vector<size_t> shape_vector(1, len * sizeof(float)); modelbox::ModelBoxDataType type = MODELBOX_FLOAT; output_buf_1->Build(shape_vector); output_buf_1->Set("type", type); std::vector<size_t> shape{len}; output_buf_1->Set("shape", shape); auto dev_data = (float*)(output_buf_1->MutableData()); for (size_t i = 0; i < output_buf_1->Size(); ++i) { for (size_t j = 0; j < len; ++j) { dev_data[i * len + j] = 0.0; } } return modelbox::STATUS_OK; }; auto mock_functions = std::make_shared<MockFunctionCollection>(); mock_functions->RegisterOpenFunc(open_func); mock_functions->RegisterProcessFunc(process_func); driver_flow_->AddFlowUnitDesc( mock_desc, mock_functions->GenerateCreateFunc(), TEST_DRIVER_DIR); } { auto mock_desc = GenerateFlowunitDesc("check_infer_result", {"in"}, {}); mock_desc->SetFlowType(STREAM); auto process_func = [=](std::shared_ptr<DataContext> op_ctx, std::shared_ptr<MockFlowUnit> mock_flowunit) { std::shared_ptr<BufferList> input_bufs = op_ctx->Input("in"); EXPECT_EQ(input_bufs->Size(), 1); std::vector<size_t> input_shape; auto result = input_bufs->At(0)->Get("shape", input_shape); EXPECT_TRUE(result); EXPECT_EQ(input_shape.size(), 4); EXPECT_EQ(input_shape[0], 1); EXPECT_EQ(input_shape[1], 256); EXPECT_EQ(input_shape[2], 1); EXPECT_EQ(input_shape[3], 2048); auto ptr = (const float*)input_bufs->ConstData(); for (size_t i = 0; i < 200; ++i) { EXPECT_TRUE(std::abs(ptr[i]) < 1e-7); } return modelbox::STATUS_OK; }; auto mock_functions = std::make_shared<MockFunctionCollection>(); mock_functions->RegisterProcessFunc(process_func); driver_flow_->AddFlowUnitDesc( mock_desc, mock_functions->GenerateCreateFunc(), TEST_DRIVER_DIR); } return STATUS_OK; } std::shared_ptr<MockFlow> InferenceAscendFlowUnitTest::GetDriverFlow() { return driver_flow_; } TEST_F(InferenceAscendFlowUnitTest, RunUnit) { std::string toml_content = R"( [driver] skip-default=true dir=[")" + test_lib_dir + "\",\"" + test_data_dir + "\"]\n " + R"([graph] graphconf = '''digraph demo { prepare_infer_data[type=flowunit, flowunit=prepare_infer_data, device=cpu, deviceid=0, label="<out>"] atc_inference[type=flowunit, flowunit=atc_inference, device=ascend, deviceid=0, label="<input> | <output:0>", batch_size=1] check_infer_result[type=flowunit, flowunit=check_infer_result, device=cpu, deviceid=0, label="<in>", batch_size=1] prepare_infer_data:out -> atc_inference:input atc_inference:output:0 -> check_infer_result:in }''' format = "graphviz" )"; auto driver_flow = GetDriverFlow(); driver_flow->BuildAndRun("RunUnit", toml_content, 3 * 1000); } TEST_F(InferenceAscendFlowUnitTest, RunUnitEncrypt) { std::string toml_content = R"( [driver] skip-default=true dir=[")" + test_lib_dir + "\",\"" + test_data_dir + "\"]\n " + R"([graph] graphconf = '''digraph demo { prepare_infer_data[type=flowunit, flowunit=prepare_infer_data, device=cpu, deviceid=0, label="<out>"] atc_inference[type=flowunit, flowunit=acl_inference_encrypt, device=ascend, deviceid=0, label="<input> | <output:0>", batch_size=1] check_infer_result[type=flowunit, flowunit=check_infer_result, device=cpu, deviceid=0, label="<in>", batch_size=1] prepare_infer_data:out -> atc_inference:input atc_inference:output:0 -> check_infer_result:in }''' format = "graphviz" )"; auto driver_flow = GetDriverFlow(); driver_flow->BuildAndRun("RunUnit", toml_content, 3 * 1000); } } // namespace modelbox
37.32766
141
0.641245
yamal-shang
291b9569ec1e3ad6d74d23236f7d049a6baf08c1
7,609
cpp
C++
server/core/src/irods_server_negotiation.cpp
JustinKyleJames/irods
59e9db75200e95796ec51ec20eb3b185d9e4b5f5
[ "BSD-3-Clause" ]
333
2015-01-15T15:42:29.000Z
2022-03-19T19:16:15.000Z
server/core/src/irods_server_negotiation.cpp
JustinKyleJames/irods
59e9db75200e95796ec51ec20eb3b185d9e4b5f5
[ "BSD-3-Clause" ]
3,551
2015-01-02T19:55:40.000Z
2022-03-31T21:24:56.000Z
server/core/src/irods_server_negotiation.cpp
JustinKyleJames/irods
59e9db75200e95796ec51ec20eb3b185d9e4b5f5
[ "BSD-3-Clause" ]
148
2015-01-31T16:13:46.000Z
2022-03-23T20:23:43.000Z
// =-=-=-=-=-=-=- #include "irods_client_server_negotiation.hpp" #include "irods_configuration_keywords.hpp" #include "irods_kvp_string_parser.hpp" #include "irods_server_properties.hpp" // =-=-=-=-=-=-=- // irods includes #include "rodsDef.h" #include "rsGlobalExtern.hpp" #include <list> #include "fmt/format.h" namespace irods { error check_sent_sid(const std::string& _zone_key) { if (_zone_key.empty()) { return ERROR(SYS_INVALID_INPUT_PARAM, "incoming zone_key is empty"); } // Check local zone keys for a match with the sent zone key. try { const auto& neg_key = irods::get_server_property<const std::string>(CFG_NEGOTIATION_KEY_KW); if (!negotiation_key_is_valid(neg_key)) { irods::log(LOG_WARNING, fmt::format( "[{}:{}] - negotiation_key in server_config is invalid", __func__, __LINE__)); } const auto& zone_key = irods::get_server_property<const std::string>(CFG_ZONE_KEY_KW); std::string signed_zone_key; if (const auto err = sign_server_sid(zone_key, neg_key, signed_zone_key); !err.ok()) { return PASS(err); } if (_zone_key == signed_zone_key) { irods::log(LOG_DEBUG8, fmt::format( "[{}:{}] - signed zone_key matches input signed zone_key", __func__, __LINE__)); return SUCCESS(); } } catch (const irods::exception& e) { return irods::error(e); } // Check zone and negotiation keys defined for remote zones (i.e. federation) for // a match. for (const auto& entry : remote_SID_key_map) { const auto& [zone_key, neg_key] = entry.second; std::string signed_zone_key; if (const auto err = sign_server_sid(zone_key, neg_key, signed_zone_key); !err.ok()) { return PASS(err); } if (_zone_key == signed_zone_key) { return SUCCESS(); } } return ERROR(SYS_SIGNED_SID_NOT_MATCHED, "signed zone_keys do not match"); } // check_sent_sid /// =-=-=-=-=-=-=- /// @brief function which manages the TLS and Auth negotiations with the client error client_server_negotiation_for_server( irods::network_object_ptr _ptr, std::string& _result ) { // =-=-=-=-=-=-=- // manufacture an rei for the applyRule ruleExecInfo_t rei; memset( ( char* )&rei, 0, sizeof( ruleExecInfo_t ) ); std::string rule_result; std::list<boost::any> params; params.push_back(&rule_result); // =-=-=-=-=-=-=- // if it is, then call the pre PEP and get the result int status = applyRuleWithInOutVars( "acPreConnect", params, &rei ); if ( 0 != status ) { return ERROR( status, "failed in call to applyRuleUpdateParams" ); } // =-=-=-=-=-=-=- // check to see if a negotiation was requested if ( !do_client_server_negotiation_for_server() ) { // =-=-=-=-=-=-=- // if it was not but we require SSL then error out if ( CS_NEG_REQUIRE == rule_result ) { std::stringstream msg; msg << "SSL is required by the server but not requested by the client"; return ERROR( SYS_INVALID_INPUT_PARAM, msg.str() ); } else { // =-=-=-=-=-=-=- // a negotiation was not requested and we do not require SSL - we good return SUCCESS(); } } // =-=-=-=-=-=-=- // pass the PEP result to the client, send CS_NEG_SVR_1_MSG irods::cs_neg_t cs_neg; cs_neg.status_ = CS_NEG_STATUS_SUCCESS; snprintf( cs_neg.result_, sizeof( cs_neg.result_ ), "%s", rule_result.c_str() ); error err = send_client_server_negotiation_message( _ptr, cs_neg ); if ( !err.ok() ) { std::stringstream msg; msg << "failed with PEP value of [" << rule_result << "]"; return PASSMSG( msg.str(), err ); } // =-=-=-=-=-=-=- // get the response from CS_NEG_CLI_1_MSG boost::shared_ptr< cs_neg_t > read_cs_neg; err = read_client_server_negotiation_message( _ptr, read_cs_neg ); if ( !err.ok() ) { return PASS( err ); } // =-=-=-=-=-=-=- // get the result from the key val pair if ( strlen( read_cs_neg->result_ ) != 0 ) { irods::kvp_map_t kvp; err = irods::parse_kvp_string(read_cs_neg->result_, kvp); if (err.ok()) { if (kvp.find(CS_NEG_SID_KW) != kvp.end()) { // If the zone_key is empty, return immediately because the server sent the // appropriate keyword but did not send a value. This indicates that the // other server is able to perform the negotiation but did not send a value // which is bad. const std::string& zone_key = kvp.at(CS_NEG_SID_KW); if (zone_key.empty()) { return ERROR(REMOTE_SERVER_SID_NOT_DEFINED, fmt::format( "[{}:{}] - received empty zone_key", __func__, __LINE__)); } // Make sure that the zone_key was signed using the correct negotiation_key // and matches the signed zone_key for this zone. If it does not match, the // server should end communications. if (const auto err = check_sent_sid(zone_key); !err.ok()) { return err; } // Store property that states this is an Agent-Agent connection, as opposed // to a Client-Agent connection. try { irods::set_server_property<std::string>(AGENT_CONN_KW, zone_key); } catch (const irods::exception& e) { return irods::error(e); } } // check to see if the result string has the SSL negotiation results _result = kvp.at(CS_NEG_RESULT_KW); if ( _result.empty() ) { return ERROR(UNMATCHED_KEY_OR_INDEX, "SSL result string missing from response"); } } else { // support 4.0 client-server negotiation which did not use key-val pairs _result = read_cs_neg->result_; } } // if result strlen > 0 if ( CS_NEG_REQUIRE == rule_result && CS_NEG_USE_TCP == _result ) { return ERROR( SERVER_NEGOTIATION_ERROR, "request to use TCP refused"); } else if ( CS_NEG_STATUS_SUCCESS == read_cs_neg->status_ ) { return SUCCESS(); } // =-=-=-=-=-=-=- // else, return a failure std::stringstream msg; msg << "failure detected from client for result [" << read_cs_neg->result_ << "]"; return ERROR( SERVER_NEGOTIATION_ERROR, msg.str() ); } // client_server_negotiation_for_server }; // namespace irods
37.855721
104
0.520568
JustinKyleJames
291c94d55a604ff92a165408f3d5568a16cb5ba9
3,053
cc
C++
chromeos/network/network_event_log.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chromeos/network/network_event_log.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chromeos/network/network_event_log.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/network/network_event_log.h" #include "base/strings/string_util.h" #include "chromeos/network/network_handler.h" #include "chromeos/network/network_state.h" #include "chromeos/network/network_state_handler.h" #include "chromeos/network/tether_constants.h" #include "third_party/cros_system_api/dbus/service_constants.h" namespace { constexpr char kServicePrefix[] = "/service/"; constexpr char kUnknownId[] = "<none>"; chromeos::NetworkStateHandler* GetNetworkStateHandler() { if (!chromeos::NetworkHandler::IsInitialized()) return nullptr; return chromeos::NetworkHandler::Get()->network_state_handler(); } } // namespace namespace chromeos { // Returns a descriptive unique id for |network| // e.g.: ethernet_0, wifi_psk_1, cellular_lte_2, vpn_openvpn_3. std::string NetworkId(const NetworkState* network) { if (!network) return kUnknownId; const std::string& type = network->type(); if (type == kTypeTether) { // Tether uses a GUID for its service path. Use the first 8 digits. return type + "_" + network->path().substr(0, 8); } // Test networks may not follow the Shill pattern, just use the path. if (!base::StartsWith(network->path(), kServicePrefix, base::CompareCase::SENSITIVE)) { return network->path(); } std::string id = network->path().substr(strlen(kServicePrefix)); if (type.empty()) return "service_" + id; std::string result = type + "_"; if (type == shill::kTypeWifi) { result += network->security_class() + "_"; } else if (type == shill::kTypeCellular) { result += network->network_technology() + "_"; } else if (type == shill::kTypeVPN) { result += network->GetVpnProviderType() + "_"; } return result + id; } // Calls NetworkId() if a NetworkState for |service_path| exists, otherwise // returns service_{id}. If |service_path| does not represent a valid service // path (e.g. in tests), returns |service_path|. std::string NetworkPathId(const std::string& service_path) { NetworkStateHandler* handler = GetNetworkStateHandler(); if (handler) { const NetworkState* network = handler->GetNetworkState(service_path); if (network) return NetworkId(network); } if (!base::StartsWith(service_path, kServicePrefix, base::CompareCase::SENSITIVE)) { return service_path; } std::string id = service_path.substr(strlen(kServicePrefix)); return "service_" + id; } // Calls NetworkId() if a NetworkState exists for |guid|, otherwise // returns |guid|. std::string NetworkGuidId(const std::string& guid) { if (guid.empty()) return kUnknownId; NetworkStateHandler* handler = GetNetworkStateHandler(); if (handler) { const NetworkState* network = handler->GetNetworkStateFromGuid(guid); if (network) return NetworkId(network); } return guid; } } // namespace chromeos
32.478723
77
0.69964
zealoussnow
291f66c1a11ea1d00b7755300b31946c36e2775a
2,631
cpp
C++
Script/src/StardustScript.cpp
IridescentRose/Stardust-Engine
ee6a6b5841c16dddf367564a92eb263827631200
[ "MIT" ]
55
2020-10-07T01:54:49.000Z
2022-03-26T11:39:11.000Z
Script/src/StardustScript.cpp
IridescentRose/Ionia
ee6a6b5841c16dddf367564a92eb263827631200
[ "MIT" ]
15
2020-05-30T18:22:50.000Z
2020-08-08T11:01:36.000Z
Script/src/StardustScript.cpp
IridescentRose/Ionia
ee6a6b5841c16dddf367564a92eb263827631200
[ "MIT" ]
6
2020-10-22T11:09:47.000Z
2022-01-07T13:10:09.000Z
#include <StardustScript.h> #include <Platform/Platform.h> #if CURRENT_PLATFORM == PLATFORM_PSP #include <pspdebug.h> #define pspDebugScreenPrintf printf #else #include <stdio.h> #endif #include <iostream> namespace Stardust::Scripting { static int lua_plat_init(lua_State* L) { int argc = lua_gettop(L); if (argc != 0) return luaL_error(L, "Argument error: Platform.init() takes no argument."); Platform::initPlatform(); return 0; } static int lua_plat_exit(lua_State* L) { int argc = lua_gettop(L); if (argc != 0) return luaL_error(L, "Argument error: Platform.exit() takes no argument."); Platform::exitPlatform(); return 0; } #if CURRENT_PLATFORM == PLATFORM_PSP static int lua_print(lua_State* L) { pspDebugScreenInit(); pspDebugScreenSetXY(0, 0); int argc = lua_gettop(L); int n; for (n = 1; n <= argc; n++) pspDebugScreenPrintf("%s\n", lua_tostring(L, n)); return 0; } #endif static int lua_plat_update(lua_State* L) { int argc = lua_gettop(L); if (argc != 0) return luaL_error(L, "Argument error: Platform.update() takes no argument."); Platform::platformUpdate(); return 0; } static int lua_plat_delay(lua_State* L) { int argc = lua_gettop(L); if (argc != 1) return luaL_error(L, "Argument error: Platform.delay() takes 1 argument (millis)."); int x = static_cast<int>(luaL_checkinteger(L, 1)); Platform::delayForMS(x); return 0; } static const luaL_Reg platformLib[] { {"init", lua_plat_init}, {"update", lua_plat_update}, {"exit", lua_plat_exit}, {"delay", lua_plat_delay}, {0, 0} }; void initPlatformLib(lua_State* L) { lua_getglobal(L, "Platform"); if (lua_isnil(L, -1)) { lua_pop(L, 1); lua_newtable(L); } luaL_setfuncs(L, platformLib, 0); lua_setglobal(L, "Platform"); } int status; lua_State* L; void initScripting() { status = 0; L = luaL_newstate(); luaL_openlibs(L); #if CURRENT_PLATFORM == PLATFORM_PSP lua_register(L, "print", lua_print); #endif initPlatformLib(L); initScriptInputLib(L); initScriptLoggingLib(L); initScriptRenderLib(L); initScriptTextureLib(L); initScriptNetDriverLib(L); } void loadScript(std::string path) { status = luaL_loadfile(L, path.c_str()); } void callScript() { status = lua_pcall(L, 0, LUA_MULTRET, 0); if (status != 0) { printf("error: %s\n", lua_tostring(L, -1)); #if CURRENT_PLATFORM == PLATFORM_PSP pspDebugScreenInit(); pspDebugScreenSetXY(0, 0); pspDebugScreenPrintf("error: %s\n", lua_tostring(L, -1)); #endif lua_pop(L, 1); // remove error message } } void cleanupScripting() { lua_close(L); } }
21.743802
87
0.675789
IridescentRose
2920dec61d7fc68cbbf9f9327b0a59a9f3361896
33,833
cc
C++
components/password_manager/core/browser/password_manager.cc
xzhan96/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-01-07T18:51:03.000Z
2021-01-07T18:51:03.000Z
components/password_manager/core/browser/password_manager.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/password_manager/core/browser/password_manager.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/password_manager/core/browser/password_manager.h" #include <stddef.h> #include <map> #include <utility> #include "base/memory/ptr_util.h" #include "base/metrics/field_trial.h" #include "base/metrics/histogram_macros.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/platform_thread.h" #include "build/build_config.h" #include "components/autofill/core/browser/autofill_field.h" #include "components/autofill/core/browser/form_structure.h" #include "components/autofill/core/common/form_data_predictions.h" #include "components/autofill/core/common/password_form_field_prediction_map.h" #include "components/password_manager/core/browser/affiliation_utils.h" #include "components/password_manager/core/browser/browser_save_password_progress_logger.h" #include "components/password_manager/core/browser/form_saver_impl.h" #include "components/password_manager/core/browser/keychain_migration_status_mac.h" #include "components/password_manager/core/browser/log_manager.h" #include "components/password_manager/core/browser/password_autofill_manager.h" #include "components/password_manager/core/browser/password_form_manager.h" #include "components/password_manager/core/browser/password_manager_client.h" #include "components/password_manager/core/browser/password_manager_driver.h" #include "components/password_manager/core/browser/password_manager_metrics_util.h" #include "components/password_manager/core/browser/password_manager_util.h" #include "components/password_manager/core/common/password_manager_features.h" #include "components/password_manager/core/common/password_manager_pref_names.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_service.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" #if defined(OS_WIN) #include "components/prefs/pref_registry_simple.h" #endif using autofill::PasswordForm; namespace password_manager { namespace { const char kSpdyProxyRealm[] = "/SpdyProxy"; // Shorten the name to spare line breaks. The code provides enough context // already. typedef autofill::SavePasswordProgressLogger Logger; bool URLsEqualUpToScheme(const GURL& a, const GURL& b) { return (a.GetContent() == b.GetContent()); } bool URLsEqualUpToHttpHttpsSubstitution(const GURL& a, const GURL& b) { if (a == b) return true; // The first-time and retry login forms action URLs sometimes differ in // switching from HTTP to HTTPS, see http://crbug.com/400769. if (a.SchemeIsHTTPOrHTTPS() && b.SchemeIsHTTPOrHTTPS()) return URLsEqualUpToScheme(a, b); return false; } // Helper UMA reporting function for differences in URLs during form submission. void RecordWhetherTargetDomainDiffers(const GURL& src, const GURL& target) { bool target_domain_differs = !net::registry_controlled_domains::SameDomainOrHost( src, target, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); UMA_HISTOGRAM_BOOLEAN("PasswordManager.SubmitNavigatesToDifferentDomain", target_domain_differs); } bool IsSignupForm(const PasswordForm& form) { return !form.new_password_element.empty() && form.password_element.empty(); } // Tries to convert the |server_field_type| to a PasswordFormFieldPredictionType // stored in |type|. Returns true if the conversion was made. bool ServerTypeToPrediction(autofill::ServerFieldType server_field_type, autofill::PasswordFormFieldPredictionType* type) { switch (server_field_type) { case autofill::USERNAME: case autofill::USERNAME_AND_EMAIL_ADDRESS: *type = autofill::PREDICTION_USERNAME; return true; case autofill::PASSWORD: *type = autofill::PREDICTION_CURRENT_PASSWORD; return true; case autofill::ACCOUNT_CREATION_PASSWORD: *type = autofill::PREDICTION_NEW_PASSWORD; return true; default: return false; } } // Returns true if the |field_type| is known to be possibly // misinterpreted as a password by the Password Manager. bool IsPredictedTypeNotPasswordPrediction( autofill::ServerFieldType field_type) { return field_type == autofill::CREDIT_CARD_NUMBER || field_type == autofill::CREDIT_CARD_VERIFICATION_CODE; } bool PreferredRealmIsFromAndroid( const autofill::PasswordFormFillData& fill_data) { return FacetURI::FromPotentiallyInvalidSpec( fill_data.preferred_realm).IsValidAndroidFacetURI(); } bool ContainsAndroidCredentials( const autofill::PasswordFormFillData& fill_data) { for (const auto& login : fill_data.additional_logins) { if (FacetURI::FromPotentiallyInvalidSpec( login.second.realm).IsValidAndroidFacetURI()) { return true; } } return PreferredRealmIsFromAndroid(fill_data); } } // namespace // static void PasswordManager::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { #if defined(OS_IOS) || defined(OS_ANDROID) uint32_t flags = PrefRegistry::NO_REGISTRATION_FLAGS; #else uint32_t flags = user_prefs::PrefRegistrySyncable::SYNCABLE_PREF; #endif registry->RegisterBooleanPref(prefs::kPasswordManagerSavingEnabled, true, flags); registry->RegisterBooleanPref( prefs::kCredentialsEnableService, true, user_prefs::PrefRegistrySyncable::SYNCABLE_PRIORITY_PREF); registry->RegisterBooleanPref( prefs::kCredentialsEnableAutosignin, true, user_prefs::PrefRegistrySyncable::SYNCABLE_PRIORITY_PREF); #if defined(OS_MACOSX) registry->RegisterIntegerPref( prefs::kKeychainMigrationStatus, static_cast<int>(MigrationStatus::MIGRATED_DELETED)); #endif } #if defined(OS_WIN) // static void PasswordManager::RegisterLocalPrefs(PrefRegistrySimple* registry) { registry->RegisterInt64Pref(prefs::kOsPasswordLastChanged, 0); registry->RegisterBooleanPref(prefs::kOsPasswordBlank, false); } #endif PasswordManager::PasswordManager(PasswordManagerClient* client) : client_(client) { DCHECK(client_); } PasswordManager::~PasswordManager() { for (LoginModelObserver& observer : observers_) observer.OnLoginModelDestroying(); } void PasswordManager::GenerationAvailableForForm(const PasswordForm& form) { DCHECK(client_->IsSavingAndFillingEnabledForCurrentPage()); PasswordFormManager* form_manager = GetMatchingPendingManager(form); if (form_manager) { form_manager->MarkGenerationAvailable(); return; } } void PasswordManager::OnPresaveGeneratedPassword( const autofill::PasswordForm& form) { DCHECK(client_->IsSavingAndFillingEnabledForCurrentPage()); PasswordFormManager* form_manager = GetMatchingPendingManager(form); if (form_manager) { form_manager->form_saver()->PresaveGeneratedPassword(form); return; } } void PasswordManager::SetHasGeneratedPasswordForForm( password_manager::PasswordManagerDriver* driver, const PasswordForm& form, bool password_is_generated) { DCHECK(client_->IsSavingAndFillingEnabledForCurrentPage()); PasswordFormManager* form_manager = GetMatchingPendingManager(form); if (form_manager) { if (!password_is_generated) form_manager->form_saver()->RemovePresavedPassword(); form_manager->set_has_generated_password(password_is_generated); return; } UMA_HISTOGRAM_BOOLEAN("PasswordManager.GeneratedFormHasNoFormManager", password_is_generated); } void PasswordManager::SetGenerationElementAndReasonForForm( password_manager::PasswordManagerDriver* driver, const autofill::PasswordForm& form, const base::string16& generation_element, bool is_manually_triggered) { DCHECK(client_->IsSavingAndFillingEnabledForCurrentPage()); PasswordFormManager* form_manager = GetMatchingPendingManager(form); if (form_manager) { form_manager->set_generation_element(generation_element); form_manager->set_is_manual_generation(is_manually_triggered); form_manager->set_generation_popup_was_shown(true); return; } // If there is no corresponding PasswordFormManager, we create one. This is // not the common case, and should only happen when there is a bug in our // ability to detect forms. auto manager = base::MakeUnique<PasswordFormManager>( this, client_, driver->AsWeakPtr(), form, base::WrapUnique(new FormSaverImpl(client_->GetPasswordStore()))); pending_login_managers_.push_back(std::move(manager)); } void PasswordManager::SaveGenerationFieldDetectedByClassifier( const autofill::PasswordForm& form, const base::string16& generation_field) { if (!client_->IsSavingAndFillingEnabledForCurrentPage()) return; PasswordFormManager* form_manager = GetMatchingPendingManager(form); if (form_manager) form_manager->SaveGenerationFieldDetectedByClassifier(generation_field); } void PasswordManager::ProvisionallySavePassword(const PasswordForm& form) { bool is_saving_and_filling_enabled = client_->IsSavingAndFillingEnabledForCurrentPage(); std::unique_ptr<BrowserSavePasswordProgressLogger> logger; if (password_manager_util::IsLoggingActive(client_)) { logger.reset( new BrowserSavePasswordProgressLogger(client_->GetLogManager())); logger->LogMessage(Logger::STRING_PROVISIONALLY_SAVE_PASSWORD_METHOD); logger->LogPasswordForm(Logger::STRING_PROVISIONALLY_SAVE_PASSWORD_FORM, form); } if (!is_saving_and_filling_enabled) { RecordFailure(SAVING_DISABLED, form.origin, logger.get()); return; } // No password to save? Then don't. if (PasswordFormManager::PasswordToSave(form).empty()) { RecordFailure(EMPTY_PASSWORD, form.origin, logger.get()); return; } auto matched_manager_it = pending_login_managers_.end(); PasswordFormManager::MatchResultMask current_match_result = PasswordFormManager::RESULT_NO_MATCH; // Below, "matching" is in DoesManage-sense and "not ready" in // !HasCompletedMatching sense. We keep track of such PasswordFormManager // instances for UMA. for (auto iter = pending_login_managers_.begin(); iter != pending_login_managers_.end(); ++iter) { PasswordFormManager::MatchResultMask result = (*iter)->DoesManage(form); if (result == PasswordFormManager::RESULT_NO_MATCH) continue; (*iter)->SetSubmittedForm(form); if (result == PasswordFormManager::RESULT_COMPLETE_MATCH) { // If we find a manager that exactly matches the submitted form including // the action URL, exit the loop. if (logger) logger->LogMessage(Logger::STRING_EXACT_MATCH); matched_manager_it = iter; break; } else if (result == (PasswordFormManager::RESULT_COMPLETE_MATCH & ~PasswordFormManager::RESULT_ACTION_MATCH) && result > current_match_result) { // If the current manager matches the submitted form excluding the action // URL, remember it as a candidate and continue searching for an exact // match. See http://crbug.com/27246 for an example where actions can // change. if (logger) logger->LogMessage(Logger::STRING_MATCH_WITHOUT_ACTION); matched_manager_it = iter; current_match_result = result; } else if (IsSignupForm(form) && result > current_match_result) { // Signup forms don't require HTML attributes to match because we don't // need to fill these saved passwords on the same form in the future. // Prefer the best possible match (e.g. action and origins match instead // or just origin matching). Don't break in case there exists a better // match. // TODO(gcasto): Matching in this way is very imprecise. Having some // better way to match the same form when the HTML elements change (e.g. // text element changed to password element) would be useful. if (logger) logger->LogMessage(Logger::STRING_ORIGINS_MATCH); matched_manager_it = iter; current_match_result = result; } } // If we didn't find a manager, this means a form was submitted without // first loading the page containing the form. Don't offer to save // passwords in this case. if (matched_manager_it == pending_login_managers_.end()) { RecordFailure(NO_MATCHING_FORM, form.origin, logger.get()); return; } std::unique_ptr<PasswordFormManager> manager; // Transfer ownership of the manager from |pending_login_managers_| to // |manager|. manager.swap(*matched_manager_it); pending_login_managers_.erase(matched_manager_it); PasswordForm provisionally_saved_form(form); provisionally_saved_form.preferred = true; if (logger) { logger->LogPasswordForm(Logger::STRING_PROVISIONALLY_SAVED_FORM, provisionally_saved_form); } PasswordFormManager::OtherPossibleUsernamesAction action = PasswordFormManager::IGNORE_OTHER_POSSIBLE_USERNAMES; if (OtherPossibleUsernamesEnabled()) action = PasswordFormManager::ALLOW_OTHER_POSSIBLE_USERNAMES; if (logger) { logger->LogBoolean( Logger::STRING_IGNORE_POSSIBLE_USERNAMES, action == PasswordFormManager::IGNORE_OTHER_POSSIBLE_USERNAMES); } manager->ProvisionallySave(provisionally_saved_form, action); provisional_save_manager_.swap(manager); // Cache the user-visible URL (i.e., the one seen in the omnibox). Once the // post-submit navigation concludes, we compare the landing URL against the // cached and report the difference through UMA. main_frame_url_ = client_->GetMainFrameURL(); } void PasswordManager::UpdateFormManagers() { for (const auto& form_manager : pending_login_managers_) { form_manager->FetchDataFromPasswordStore(); } } void PasswordManager::DropFormManagers() { pending_login_managers_.clear(); provisional_save_manager_.reset(); all_visible_forms_.clear(); } void PasswordManager::RecordFailure(ProvisionalSaveFailure failure, const GURL& form_origin, BrowserSavePasswordProgressLogger* logger) { UMA_HISTOGRAM_ENUMERATION( "PasswordManager.ProvisionalSaveFailure", failure, MAX_FAILURE_VALUE); if (logger) { switch (failure) { case SAVING_DISABLED: logger->LogMessage(Logger::STRING_SAVING_DISABLED); break; case EMPTY_PASSWORD: logger->LogMessage(Logger::STRING_EMPTY_PASSWORD); break; case MATCHING_NOT_COMPLETE: logger->LogMessage(Logger::STRING_MATCHING_NOT_COMPLETE); break; case NO_MATCHING_FORM: logger->LogMessage(Logger::STRING_NO_MATCHING_FORM); break; case FORM_BLACKLISTED: logger->LogMessage(Logger::STRING_FORM_BLACKLISTED); break; case INVALID_FORM: logger->LogMessage(Logger::STRING_INVALID_FORM); break; case SYNC_CREDENTIAL: logger->LogMessage(Logger::STRING_SYNC_CREDENTIAL); break; case MAX_FAILURE_VALUE: NOTREACHED(); return; } logger->LogMessage(Logger::STRING_DECISION_DROP); } } void PasswordManager::AddSubmissionCallback( const PasswordSubmittedCallback& callback) { submission_callbacks_.push_back(callback); } void PasswordManager::AddObserverAndDeliverCredentials( LoginModelObserver* observer, const PasswordForm& observed_form) { observers_.AddObserver(observer); observer->set_signon_realm(observed_form.signon_realm); // TODO(vabr): Even though the observers do the realm check, this mechanism // will still result in every observer being notified about every form. We // could perhaps do better by registering an observer call-back instead. std::vector<PasswordForm> observed_forms; observed_forms.push_back(observed_form); OnPasswordFormsParsed(nullptr, observed_forms); } void PasswordManager::RemoveObserver(LoginModelObserver* observer) { observers_.RemoveObserver(observer); } void PasswordManager::DidNavigateMainFrame() { pending_login_managers_.clear(); } void PasswordManager::OnPasswordFormSubmitted( password_manager::PasswordManagerDriver* driver, const PasswordForm& password_form) { ProvisionallySavePassword(password_form); for (size_t i = 0; i < submission_callbacks_.size(); ++i) { submission_callbacks_[i].Run(password_form); } pending_login_managers_.clear(); } void PasswordManager::OnPasswordFormForceSaveRequested( password_manager::PasswordManagerDriver* driver, const PasswordForm& password_form) { // TODO(msramek): This is just a sketch. We will need to show a custom bubble, // mark the form as force saved, and recreate the pending login managers, // because the password store might have changed. ProvisionallySavePassword(password_form); if (provisional_save_manager_) OnLoginSuccessful(); } void PasswordManager::OnPasswordFormsParsed( password_manager::PasswordManagerDriver* driver, const std::vector<PasswordForm>& forms) { CreatePendingLoginManagers(driver, forms); } void PasswordManager::CreatePendingLoginManagers( password_manager::PasswordManagerDriver* driver, const std::vector<PasswordForm>& forms) { std::unique_ptr<BrowserSavePasswordProgressLogger> logger; if (password_manager_util::IsLoggingActive(client_)) { logger.reset( new BrowserSavePasswordProgressLogger(client_->GetLogManager())); logger->LogMessage(Logger::STRING_CREATE_LOGIN_MANAGERS_METHOD); } // Record whether or not this top-level URL has at least one password field. client_->AnnotateNavigationEntry(!forms.empty()); if (!client_->IsFillingEnabledForCurrentPage()) return; if (logger) { logger->LogNumber(Logger::STRING_OLD_NUMBER_LOGIN_MANAGERS, pending_login_managers_.size()); } for (std::vector<PasswordForm>::const_iterator iter = forms.begin(); iter != forms.end(); ++iter) { // Don't involve the password manager if this form corresponds to // SpdyProxy authentication, as indicated by the realm. if (base::EndsWith(iter->signon_realm, kSpdyProxyRealm, base::CompareCase::SENSITIVE)) continue; bool old_manager_found = false; for (const auto& old_manager : pending_login_managers_) { if (old_manager->DoesManage(*iter) != PasswordFormManager::RESULT_COMPLETE_MATCH) { continue; } old_manager_found = true; if (driver) old_manager->ProcessFrame(driver->AsWeakPtr()); break; } if (old_manager_found) continue; // The current form is already managed. UMA_HISTOGRAM_BOOLEAN("PasswordManager.EmptyUsernames.ParsedUsernameField", iter->username_element.empty()); // Out of the forms not containing a username field, determine how many // are password change forms. if (iter->username_element.empty()) { UMA_HISTOGRAM_BOOLEAN( "PasswordManager.EmptyUsernames." "FormWithoutUsernameFieldIsPasswordChangeForm", !iter->new_password_element.empty()); } if (logger) logger->LogFormSignatures(Logger::STRING_ADDING_SIGNATURE, *iter); auto manager = base::MakeUnique<PasswordFormManager>( this, client_, (driver ? driver->AsWeakPtr() : base::WeakPtr<PasswordManagerDriver>()), *iter, base::WrapUnique(new FormSaverImpl(client_->GetPasswordStore()))); pending_login_managers_.push_back(std::move(manager)); } if (logger) { logger->LogNumber(Logger::STRING_NEW_NUMBER_LOGIN_MANAGERS, pending_login_managers_.size()); } } bool PasswordManager::CanProvisionalManagerSave() { std::unique_ptr<BrowserSavePasswordProgressLogger> logger; if (password_manager_util::IsLoggingActive(client_)) { logger.reset( new BrowserSavePasswordProgressLogger(client_->GetLogManager())); logger->LogMessage(Logger::STRING_CAN_PROVISIONAL_MANAGER_SAVE_METHOD); } if (!provisional_save_manager_) { if (logger) { logger->LogMessage(Logger::STRING_NO_PROVISIONAL_SAVE_MANAGER); } return false; } if (!provisional_save_manager_->HasCompletedMatching()) { // We have a provisional save manager, but it didn't finish matching yet. // We just give up. RecordFailure(MATCHING_NOT_COMPLETE, provisional_save_manager_->observed_form().origin, logger.get()); provisional_save_manager_.reset(); return false; } return true; } bool PasswordManager::ShouldPromptUserToSavePassword() const { return !client_->IsAutomaticPasswordSavingEnabled() && (provisional_save_manager_->IsNewLogin() || provisional_save_manager_ ->is_possible_change_password_form_without_username() || provisional_save_manager_->retry_password_form_password_update() || provisional_save_manager_->password_overridden()) && !(provisional_save_manager_->has_generated_password() && provisional_save_manager_->IsNewLogin()) && !provisional_save_manager_->IsPendingCredentialsPublicSuffixMatch(); } void PasswordManager::OnPasswordFormsRendered( password_manager::PasswordManagerDriver* driver, const std::vector<PasswordForm>& visible_forms, bool did_stop_loading) { CreatePendingLoginManagers(driver, visible_forms); std::unique_ptr<BrowserSavePasswordProgressLogger> logger; if (password_manager_util::IsLoggingActive(client_)) { logger.reset( new BrowserSavePasswordProgressLogger(client_->GetLogManager())); logger->LogMessage(Logger::STRING_ON_PASSWORD_FORMS_RENDERED_METHOD); } if (!CanProvisionalManagerSave()) return; // If the server throws an internal error, access denied page, page not // found etc. after a login attempt, we do not save the credentials. if (client_->WasLastNavigationHTTPError()) { if (logger) logger->LogMessage(Logger::STRING_DECISION_DROP); provisional_save_manager_->LogSubmitFailed(); provisional_save_manager_.reset(); return; } if (logger) { logger->LogNumber(Logger::STRING_NUMBER_OF_VISIBLE_FORMS, visible_forms.size()); } // Record all visible forms from the frame. all_visible_forms_.insert(all_visible_forms_.end(), visible_forms.begin(), visible_forms.end()); // If we see the login form again, then the login failed. if (did_stop_loading) { if (provisional_save_manager_->pending_credentials().scheme == PasswordForm::SCHEME_HTML) { for (size_t i = 0; i < all_visible_forms_.size(); ++i) { // TODO(vabr): The similarity check is just action equality up to // HTTP<->HTTPS substitution for now. If it becomes more complex, it may // make sense to consider modifying and using // PasswordFormManager::DoesManage for it. if (all_visible_forms_[i].action.is_valid() && URLsEqualUpToHttpHttpsSubstitution( provisional_save_manager_->pending_credentials().action, all_visible_forms_[i].action)) { provisional_save_manager_->LogSubmitFailed(); if (logger) { logger->LogPasswordForm(Logger::STRING_PASSWORD_FORM_REAPPEARED, all_visible_forms_[i]); logger->LogMessage(Logger::STRING_DECISION_DROP); } provisional_save_manager_.reset(); // Clear all_visible_forms_ once we found the match. all_visible_forms_.clear(); return; } } } else { if (logger) logger->LogMessage(Logger::STRING_PROVISIONALLY_SAVED_FORM_IS_NOT_HTML); } // Clear all_visible_forms_ after checking all the visible forms. all_visible_forms_.clear(); // Looks like a successful login attempt. Either show an infobar or // automatically save the login data. We prompt when the user hasn't // already given consent, either through previously accepting the infobar // or by having the browser generate the password. OnLoginSuccessful(); } } void PasswordManager::OnInPageNavigation( password_manager::PasswordManagerDriver* driver, const PasswordForm& password_form) { std::unique_ptr<BrowserSavePasswordProgressLogger> logger; if (password_manager_util::IsLoggingActive(client_)) { logger.reset( new BrowserSavePasswordProgressLogger(client_->GetLogManager())); logger->LogMessage(Logger::STRING_ON_IN_PAGE_NAVIGATION); } ProvisionallySavePassword(password_form); if (!CanProvisionalManagerSave()) return; OnLoginSuccessful(); } void PasswordManager::OnLoginSuccessful() { std::unique_ptr<BrowserSavePasswordProgressLogger> logger; if (password_manager_util::IsLoggingActive(client_)) { logger.reset( new BrowserSavePasswordProgressLogger(client_->GetLogManager())); logger->LogMessage(Logger::STRING_ON_ASK_USER_OR_SAVE_PASSWORD); } client_->GetStoreResultFilter()->ReportFormLoginSuccess( *provisional_save_manager_); if (base::FeatureList::IsEnabled(features::kDropSyncCredential) && !client_->GetStoreResultFilter()->ShouldSave( provisional_save_manager_->pending_credentials())) { provisional_save_manager_->WipeStoreCopyIfOutdated(); RecordFailure(SYNC_CREDENTIAL, provisional_save_manager_->observed_form().origin, logger.get()); provisional_save_manager_.reset(); return; } provisional_save_manager_->LogSubmitPassed(); RecordWhetherTargetDomainDiffers(main_frame_url_, client_->GetMainFrameURL()); if (ShouldPromptUserToSavePassword()) { bool empty_password = provisional_save_manager_->pending_credentials().username_value.empty(); UMA_HISTOGRAM_BOOLEAN("PasswordManager.EmptyUsernames.OfferedToSave", empty_password); if (logger) logger->LogMessage(Logger::STRING_DECISION_ASK); bool update_password = (!provisional_save_manager_->best_matches().empty() && provisional_save_manager_ ->is_possible_change_password_form_without_username()) || provisional_save_manager_->password_overridden() || provisional_save_manager_->retry_password_form_password_update(); if (client_->PromptUserToSaveOrUpdatePassword( std::move(provisional_save_manager_), CredentialSourceType::CREDENTIAL_SOURCE_PASSWORD_MANAGER, update_password)) { if (logger) logger->LogMessage(Logger::STRING_SHOW_PASSWORD_PROMPT); } } else { if (logger) logger->LogMessage(Logger::STRING_DECISION_SAVE); provisional_save_manager_->Save(); if (!provisional_save_manager_->IsNewLogin()) { client_->NotifySuccessfulLoginWithExistingPassword( provisional_save_manager_->pending_credentials()); } if (provisional_save_manager_->has_generated_password()) { client_->AutomaticPasswordSave(std::move(provisional_save_manager_)); } else { provisional_save_manager_.reset(); } } } bool PasswordManager::OtherPossibleUsernamesEnabled() const { return false; } void PasswordManager::Autofill( password_manager::PasswordManagerDriver* driver, const PasswordForm& form_for_autofill, const std::map<base::string16, const PasswordForm*>& best_matches, const std::vector<const PasswordForm*>& federated_matches, const PasswordForm& preferred_match, bool wait_for_username) const { DCHECK_EQ(PasswordForm::SCHEME_HTML, preferred_match.scheme); std::unique_ptr<BrowserSavePasswordProgressLogger> logger; if (password_manager_util::IsLoggingActive(client_)) { logger.reset( new BrowserSavePasswordProgressLogger(client_->GetLogManager())); logger->LogMessage(Logger::STRING_PASSWORDMANAGER_AUTOFILL); } autofill::PasswordFormFillData fill_data; InitPasswordFormFillData(form_for_autofill, best_matches, &preferred_match, wait_for_username, OtherPossibleUsernamesEnabled(), &fill_data); if (logger) logger->LogBoolean(Logger::STRING_WAIT_FOR_USERNAME, wait_for_username); UMA_HISTOGRAM_BOOLEAN( "PasswordManager.FillSuggestionsIncludeAndroidAppCredentials", ContainsAndroidCredentials(fill_data)); metrics_util::LogFilledCredentialIsFromAndroidApp( PreferredRealmIsFromAndroid(fill_data)); driver->FillPasswordForm(fill_data); client_->PasswordWasAutofilled(best_matches, form_for_autofill.origin, &federated_matches); } void PasswordManager::ShowInitialPasswordAccountSuggestions( password_manager::PasswordManagerDriver* driver, const PasswordForm& form_for_autofill, const std::map<base::string16, const PasswordForm*>& best_matches, const PasswordForm& preferred_match, bool wait_for_username) const { DCHECK_EQ(PasswordForm::SCHEME_HTML, preferred_match.scheme); std::unique_ptr<BrowserSavePasswordProgressLogger> logger; if (password_manager_util::IsLoggingActive(client_)) { logger.reset( new BrowserSavePasswordProgressLogger(client_->GetLogManager())); logger->LogMessage( Logger:: STRING_PASSWORDMANAGER_SHOW_INITIAL_PASSWORD_ACCOUNT_SUGGESTIONS); } autofill::PasswordFormFillData fill_data; InitPasswordFormFillData(form_for_autofill, best_matches, &preferred_match, wait_for_username, OtherPossibleUsernamesEnabled(), &fill_data); if (logger) logger->LogBoolean(Logger::STRING_WAIT_FOR_USERNAME, wait_for_username); driver->ShowInitialPasswordAccountSuggestions(fill_data); } void PasswordManager::AutofillHttpAuth( const std::map<base::string16, const PasswordForm*>& best_matches, const PasswordForm& preferred_match) const { DCHECK_NE(PasswordForm::SCHEME_HTML, preferred_match.scheme); std::unique_ptr<BrowserSavePasswordProgressLogger> logger; if (password_manager_util::IsLoggingActive(client_)) { logger.reset( new BrowserSavePasswordProgressLogger(client_->GetLogManager())); logger->LogMessage(Logger::STRING_PASSWORDMANAGER_AUTOFILLHTTPAUTH); logger->LogBoolean(Logger::STRING_LOGINMODELOBSERVER_PRESENT, observers_.might_have_observers()); } for (LoginModelObserver& observer : observers_) observer.OnAutofillDataAvailable(preferred_match); DCHECK(!best_matches.empty()); client_->PasswordWasAutofilled(best_matches, best_matches.begin()->second->origin, nullptr); } void PasswordManager::ProcessAutofillPredictions( password_manager::PasswordManagerDriver* driver, const std::vector<autofill::FormStructure*>& forms) { std::unique_ptr<BrowserSavePasswordProgressLogger> logger; if (password_manager_util::IsLoggingActive(client_)) logger.reset( new BrowserSavePasswordProgressLogger(client_->GetLogManager())); // Leave only forms that contain fields that are useful for password manager. std::map<autofill::FormData, autofill::PasswordFormFieldPredictionMap> predictions; for (const autofill::FormStructure* form : forms) { if (logger) logger->LogFormStructure(Logger::STRING_SERVER_PREDICTIONS, *form); for (std::vector<autofill::AutofillField*>::const_iterator field = form->begin(); field != form->end(); ++field) { autofill::PasswordFormFieldPredictionType prediction_type; if (ServerTypeToPrediction((*field)->server_type(), &prediction_type)) { predictions[form->ToFormData()][*(*field)] = prediction_type; } // Certain fields are annotated by the browsers as "not passwords" i.e. // they should not be treated as passwords by the Password Manager. if ((*field)->form_control_type == "password" && IsPredictedTypeNotPasswordPrediction( (*field)->Type().GetStorableType())) { predictions[form->ToFormData()][*(*field)] = autofill::PREDICTION_NOT_PASSWORD; } } } if (predictions.empty()) return; driver->AutofillDataReceived(predictions); } PasswordFormManager* PasswordManager::GetMatchingPendingManager( const PasswordForm& form) { PasswordFormManager* matched_manager = nullptr; PasswordFormManager::MatchResultMask current_match_result = PasswordFormManager::RESULT_NO_MATCH; for (auto& login_manager : pending_login_managers_) { PasswordFormManager::MatchResultMask result = login_manager->DoesManage(form); if (result == PasswordFormManager::RESULT_NO_MATCH) continue; if (result == PasswordFormManager::RESULT_COMPLETE_MATCH) { // If we find a manager that exactly matches the submitted form including // the action URL, exit the loop. matched_manager = login_manager.get(); break; } else if (result == (PasswordFormManager::RESULT_COMPLETE_MATCH & ~PasswordFormManager::RESULT_ACTION_MATCH) && result > current_match_result) { // If the current manager matches the submitted form excluding the action // URL, remember it as a candidate and continue searching for an exact // match. See http://crbug.com/27246 for an example where actions can // change. matched_manager = login_manager.get(); current_match_result = result; } else if (result > current_match_result) { matched_manager = login_manager.get(); current_match_result = result; } } return matched_manager; } } // namespace password_manager
38.18623
91
0.732007
xzhan96
292213e9f206445c7583d299e36938a70f06dccb
887
cpp
C++
dp/lis_seg/lis.cpp
Takumi1122/data-structure-algorithm
6b9f26e4dbba981f034518a972ecfc698b86d837
[ "MIT" ]
null
null
null
dp/lis_seg/lis.cpp
Takumi1122/data-structure-algorithm
6b9f26e4dbba981f034518a972ecfc698b86d837
[ "MIT" ]
null
null
null
dp/lis_seg/lis.cpp
Takumi1122/data-structure-algorithm
6b9f26e4dbba981f034518a972ecfc698b86d837
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define rep(i, n) for (int i = 0; i < (n); ++i) using namespace std; using ll = long long; using P = pair<int, int>; // 最長増加部分列 // 計算量 o(nlog(n)) /* 参考リンク AIZU ONLINE JUDGE https://onlinejudge.u-aizu.ac.jp/problems/DPL_1_D LIS でも大活躍! DP の配列使いまわしテクニックを特集 https://qiita.com/drken/items/68b8503ad4ffb469624c */ const ll INF = 1LL << 60; // 最長増加部分列の長さを求める int LIS(const vector<ll> &a) { int n = (int)a.size(); vector<ll> dp(n, INF); rep(i, n) { // dp[k] >= a[i] となる最小のイテレータを見つける auto it = lower_bound(dp.begin(), dp.end(), a[i]); // そこを a[i] で書き換える *it = a[i]; } // dp[k] < INF となる最大の k に対して k+1 が答え // それは dp[k] >= INF となる最小の k に一致する return lower_bound(dp.begin(), dp.end(), INF) - dp.begin(); } int main() { int n; cin >> n; vector<ll> a(n); rep(i, n) cin >> a[i]; cout << LIS(a) << endl; }
19.282609
61
0.57159
Takumi1122
2924fcd702a37f927efc9d3d452ce60b7c8a1f5d
2,085
cpp
C++
Socket/Communication.cpp
Kaptnik/CIS-687-RemoteTestHarness
3a1466d4b71cef7bee2791020a2902d3e658fb64
[ "MIT" ]
null
null
null
Socket/Communication.cpp
Kaptnik/CIS-687-RemoteTestHarness
3a1466d4b71cef7bee2791020a2902d3e658fb64
[ "MIT" ]
null
null
null
Socket/Communication.cpp
Kaptnik/CIS-687-RemoteTestHarness
3a1466d4b71cef7bee2791020a2902d3e658fb64
[ "MIT" ]
null
null
null
///////////////////////////////////////////////////////////////////////////// // Communication.cpp - A class that encapsulates both a Sender and Receiver// // ver 1.0 // // Karthik Umashankar, CSE687 - Object Oriented Design, Summer 2018 // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Communication.h" #include "IncomingMessageHandler.h" using namespace Sockets; // Constructor to set port to listen on Communication::Communication(size_t port) : _receiver(port) { ProcessContext = Sockets::CONTEXT::SERVER; } // Constructor to set port to listen on & the context Communication::Communication(size_t port, Sockets::CONTEXT context) : _receiver(port) { this->ProcessContext = context; } // Start the sender and the receiver void Communication::Start() { IncomingMessageHandler *handler = new IncomingMessageHandler(); handler->SetContext(ProcessContext); handler->SetSendMessageQueue(_sender.GetQueue()); handler->SetRecvMessageQueue(_receiver.GetQueue()); handler->SetTestRequestQueue(_testRequestQPtr); handler->SetReadyWorkerQueue(_readyWorkerQPtr); _sender.Start(); _receiver.Start(*handler); } // Stop the sender and the receiver void Communication::Stop() { _receiver.Stop(); _sender.Stop(); } // Set the test request queue void Communication::SetTestRequestQueue(BlockingQueue<Message>* queuePointer) { _testRequestQPtr = queuePointer; } // Set the ready worker queue void Communication::SetReadyWorkerQueue(BlockingQueue<Message>* queuePointer) { _readyWorkerQPtr = queuePointer; } // Fetch a pointer to the receiver queue BlockingQueue<Message>* Communication::GetReceiverQueue() { return _receiver.GetQueue(); } // Queue up a message in the sender's blocking queue void Communication::DeliverMessage(Message message) { _sender.DeliverMessage(message); } // DeQueue a message from the receiver's blocking queue Message Communication::CollectMessage() { return _receiver.CollectMessage(); }
28.561644
86
0.680576
Kaptnik
2928397d2e86bffa04762af04590ce062eda3c21
758
hpp
C++
src/editor_controls/property_mouse_events.hpp
acidicMercury8/xray-1.6
52fba7348a93a52ff9694f2c9dd40c0d090e791e
[ "Linux-OpenIB" ]
10
2021-05-04T06:40:27.000Z
2022-01-20T20:24:28.000Z
src/editor_controls/property_mouse_events.hpp
Samsuper12/ixray-1.5
8070f833f8216d4ead294a9f19b7cd123bb76ba3
[ "Linux-OpenIB" ]
null
null
null
src/editor_controls/property_mouse_events.hpp
Samsuper12/ixray-1.5
8070f833f8216d4ead294a9f19b7cd123bb76ba3
[ "Linux-OpenIB" ]
2
2021-11-07T16:57:19.000Z
2021-12-05T13:17:12.000Z
//////////////////////////////////////////////////////////////////////////// // Module : property_mouse_events.hpp // Created : 23.01.2008 // Modified : 23.01.2008 // Author : Dmitriy Iassenev // Description : property mouse events //////////////////////////////////////////////////////////////////////////// #ifndef PROPERTY_MOUSE_EVENTS_HPP_INCLUDED #define PROPERTY_MOUSE_EVENTS_HPP_INCLUDED namespace editor { namespace controls { ref class property_grid; public interface class property_mouse_events { public: virtual void on_double_click (property_grid^ property_grid) = 0; }; // interface class property_mouse_events } // namespace controls } // namespace editor #endif // ifndef PROPERTY_MOUSE_EVENTS_HPP_INCLUDED
30.32
77
0.602902
acidicMercury8
29286c1d6014c8c05b9951746e2f0781c259ccb7
5,274
cpp
C++
example/cluster.cpp
apppur/canna
bdcce4f16be56da40445fec79959b6bc90003573
[ "MIT" ]
null
null
null
example/cluster.cpp
apppur/canna
bdcce4f16be56da40445fec79959b6bc90003573
[ "MIT" ]
null
null
null
example/cluster.cpp
apppur/canna
bdcce4f16be56da40445fec79959b6bc90003573
[ "MIT" ]
null
null
null
#include <pthread.h> #include <stdio.h> #include <string> #include <vector> #include <queue> #include "canna_core.h" #include "canna_random.h" #include "zmq.hpp" #define CLIENTS_NUM 10 #define WORKERS_NUM 5 #define WORKER_READY "READY" static char *self; static int serial = 0; static void * client_task(void *args) { zmq::context_t context(1); zmq::socket_t client(context, ZMQ_REQ); char client_ipc[64] = {0}; sprintf(client_ipc, "ipc://%s-localfe.ipc", self); client.connect(client_ipc); zmq::socket_t monitor(context, ZMQ_PUSH); char monitor_ipc[64] = {0}; sprintf(monitor_ipc, "ipc://%s-monitor.ipc", self); monitor.connect(monitor_ipc); while (true) { canna_sleep(CANNA_RAND(5)); int burst = CANNA_RAND(15); while (burst--) { canna_send(client, "WORK"); zmq::pollitem_t pollset[1] = {{(void *)client, 0, ZMQ_POLLIN, 0}}; zmq::poll(pollset, 1, -1); if (pollset[0].revents & ZMQ_POLLIN) { std::string reply = canna_recv(client); canna_send(monitor, reply); } else { canna_send(monitor, "E: CLIENT EXIT - lost task"); } } } return nullptr; } static void * worker_task(void *args) { zmq::context_t context(1); zmq::socket_t work(context, ZMQ_REQ); //char uuid[16] = {0}; //sprintf(uuid, "work:%d", serial++); //work.setsockopt(ZMQ_IDENTITY, uuid, 16); char work_ipc[64] = {0}; sprintf(work_ipc, "ipc://%s-localbe.ipc", self); work.connect(work_ipc); canna_send(work, WORKER_READY); while (true) { std::string msg = canna_recv(work); canna_sleep(CANNA_RAND(2)); } return nullptr; } int main(int argc, char **argv) { if (argc < 2) { printf("usage: cluster me {you} \n"); return 0; } self = argv[1]; printf("I: preparing broker at %s...\n", self); zmq::context_t context(1); zmq::socket_t localfe(context, ZMQ_ROUTER); char localfe_ipc[64] = {0}; sprintf(localfe_ipc, "ipc://%s-localfe.ipc", self); localfe.bind(localfe_ipc); zmq::socket_t localbe(context, ZMQ_ROUTER); char localbe_ipc[64] = {0}; sprintf(localbe_ipc, "ipc://%s-localbe.ipc", self); localbe.bind(localbe_ipc); zmq::socket_t cloudfe(context, ZMQ_ROUTER); cloudfe.setsockopt(ZMQ_IDENTITY, self, strlen(self)); char cloudfe_ipc[64] = {0}; sprintf(cloudfe_ipc, "ipc://%s-cloud.ipc", self); cloudfe.bind(cloudfe_ipc); zmq::socket_t cloudbe(context, ZMQ_ROUTER); cloudbe.setsockopt(ZMQ_IDENTITY, self, strlen(self)); char cloudbe_ipc[64] = {0}; sprintf(cloudbe_ipc, "ipc://%s-cloudbe.ipc", self); for (int i = 2; i < argc; i++) { char *peer = argv[i]; char peer_ipc[64] = {0}; sprintf(peer_ipc, "ipc://%s-cloud.ipc", peer); printf("I: connecting to cloud frontend at '%s'\n", peer); cloudbe.connect(peer_ipc); } zmq::socket_t statebe(context, ZMQ_PUB); char statebe_ipc[64] = {0}; sprintf(statebe_ipc, "ipc://%s-state.ipc", self); statebe.bind(statebe_ipc); zmq::socket_t statefe(context, ZMQ_SUB); const char *filter = ""; statefe.setsockopt(ZMQ_SUBSCRIBE, filter, strlen(filter)); for (int i = 2; i < argc; i++) { char *peer = argv[i]; char peer_ipc[64] = {0}; sprintf(peer_ipc, "ipc://%s-state.ipc", peer); statefe.connect(peer_ipc); } zmq::socket_t monitor(context, ZMQ_PULL); char monitor_ipc[64] = {0}; sprintf(monitor_ipc, "ipc://%s-monitor.ipc", self); monitor.bind(monitor_ipc); for (int i = 0; i < WORKERS_NUM; i++) { pthread_t pid; pthread_create(&pid, nullptr, worker_task, nullptr); } for (int i = 0; i < CLIENTS_NUM; i++) { pthread_t pid; pthread_create(&pid, nullptr, client_task, nullptr); } std::queue<std::string> worker_queue; while (true) { zmq::pollitem_t pollset[] = { {(void *)localbe, 0, ZMQ_POLLIN, 0}, {(void *)cloudbe, 0, ZMQ_POLLIN, 0}, {(void *)statefe, 0, ZMQ_POLLIN, 0}, {(void *)monitor, 0, ZMQ_POLLIN, 0}, }; if (worker_queue.size()) { zmq::poll(pollset, 4, -1); } else { zmq::poll(pollset, 4, 1000); } if (pollset[0].revents & ZMQ_POLLIN) { canna_dump(localbe); std::string identity = canna_recv(localbe); worker_queue.push(identity); std::string empty = canna_recv(localbe); std::string msg = canna_recv(localbe); /* if (msg == "READY") { canna_sendmore(localbe, identity); canna_sendmore(localbe, ""); canna_send(localbe, "GO"); } */ } else if (pollset[1].revents & ZMQ_POLLIN) { canna_dump(cloudbe); } if (pollset[2].revents & ZMQ_POLLIN) { } if (pollset[3].revents & ZMQ_POLLIN) { std::string status = canna_recv(monitor); printf("%s\n", status.c_str()); } canna_sleep(5000); canna_send(cloudbe, "CLOUD"); } }
28.354839
78
0.569776
apppur
2929d38f9a77d4eac67e50c5c8ca24b3d587cc12
3,007
cpp
C++
big-sort-lib/src/visualm.cpp
mvodya/BigSortCollection
d7b217d3ba8d712629c3b856bfb3e426525ca8b2
[ "MIT" ]
null
null
null
big-sort-lib/src/visualm.cpp
mvodya/BigSortCollection
d7b217d3ba8d712629c3b856bfb3e426525ca8b2
[ "MIT" ]
null
null
null
big-sort-lib/src/visualm.cpp
mvodya/BigSortCollection
d7b217d3ba8d712629c3b856bfb3e426525ca8b2
[ "MIT" ]
null
null
null
#include "bigsortlib/visualm.h" using namespace sortlib; // Error callback for GLFW void VisualModule::error_callback(int error, const char* description) { printf("Error: %s\n", description); } // Key events callback from GLFW void VisualModule::key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GLFW_TRUE); } // Main loop void VisualModule::loop() { while (!glfwWindowShouldClose(window)) { int width, height; glfwGetFramebufferSize(window, &width, &height); glViewport(0, 0, width, height); glClear(GL_COLOR_BUFFER_BIT); // Draw circle drawCircle(); glfwSwapBuffers(window); glfwPollEvents(); } // If loop end - remove this object delete this; } // Color function Color VisualModule::toColor(int& value) { float r, g, b; Color c; // Calculate 3 color chanels by simple integer value if (value > RT * 6) { c.r = 1.0f; c.b = 0; c.g = 1.0f - (float)std::clamp(value - RT * 6, 0, RT) / RT; } else if (value > RT * 4) { c.r = (float)std::clamp(value - RT * 4, 0, RT) / RT; c.b = 0; c.g = 1.0f; } else if (value > RT * 3) { c.r = 0; c.b = 1.0f - (float)std::clamp(value - RT * 3, 0, RT) / RT; c.g = 1.0f; } else if (value > RT * 2) { c.r = 0; c.b = 1.0f; c.g = (float)std::clamp(value - RT * 2, 0, RT) / RT; } else if (value > RT) { c.r = 1.0f - (float)std::clamp(value - RT, 0, RT) / RT; c.b = 1.0f; c.g = 0; } else if (value >= 0) { c.r = 1.0f; c.b = (float)std::clamp(value, 0, RT) / RT; c.g = 0; } return c; } // Draw color circle void VisualModule::drawCircle() { // Crawling all items in a circle for (int i = 0; i < size_; i++) { glLineWidth(2.5); // Set color Color color = toColor(arr_[i]); glColor3f(color.r, color.g, color.b); // Draw line from center glBegin(GL_LINES); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(cos((float)i * PI / (size_ / 2)), sin((float)i * PI / (size_ / 2)), 0.0); glEnd(); } } VisualModule::VisualModule(std::string title, Function f, int* arr, int size) { // Write pointer to function function = f; // Set array arr_ = arr; // Set size size_ = size; // Set GLFW error callback glfwSetErrorCallback(error_callback); // Init GLFW if (!glfwInit()) exit(EXIT_FAILURE); // Create window window = glfwCreateWindow(640, 640, title.c_str(), NULL, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } // Set GLFW key events callback glfwSetKeyCallback(window, key_callback); glfwMakeContextCurrent(window); glfwSwapInterval(1); // Start function thread thrFunction = new std::thread(function); thrFunction->detach(); // Start main loop loop(); } VisualModule::~VisualModule() { // Remove windows glfwDestroyWindow(window); // Stop GLFW glfwTerminate(); }
24.25
79
0.602594
mvodya
292b3422a52f93c9ea6792ab9719c1bea791a071
55,831
cpp
C++
modules/gles31/functional/es31fVertexAttributeBindingTests.cpp
omegaphora/external_deqp
8460b8642f48b81894c3cc6fc6d423811da60648
[ "Apache-2.0" ]
2
2016-12-27T00:57:00.000Z
2020-07-13T13:02:45.000Z
modules/gles31/functional/es31fVertexAttributeBindingTests.cpp
omegaphora/external_deqp
8460b8642f48b81894c3cc6fc6d423811da60648
[ "Apache-2.0" ]
null
null
null
modules/gles31/functional/es31fVertexAttributeBindingTests.cpp
omegaphora/external_deqp
8460b8642f48b81894c3cc6fc6d423811da60648
[ "Apache-2.0" ]
4
2016-04-27T21:12:29.000Z
2020-07-13T13:02:48.000Z
/*------------------------------------------------------------------------- * drawElements Quality Program OpenGL ES 3.1 Module * ------------------------------------------------- * * Copyright 2014 The Android Open Source Project * * 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. * *//*! * \file * \brief Vertex attribute binding tests. *//*--------------------------------------------------------------------*/ #include "es31fVertexAttributeBindingTests.hpp" #include "tcuRenderTarget.hpp" #include "tcuSurface.hpp" #include "gluCallLogWrapper.hpp" #include "gluRenderContext.hpp" #include "gluPixelTransfer.hpp" #include "gluShaderProgram.hpp" #include "gluObjectWrapper.hpp" #include "gluStrUtil.hpp" #include "glwFunctions.hpp" #include "glwEnums.hpp" #include "deStringUtil.hpp" #include "deInt32.h" namespace deqp { namespace gles31 { namespace Functional { namespace { static const char* const s_colorFragmentShader = "#version 310 es\n" "in mediump vec4 v_color;\n" "layout(location = 0) out mediump vec4 fragColor;\n" "void main (void)\n" "{\n" " fragColor = v_color;\n" "}\n"; static const char* const s_positionColorShader = "#version 310 es\n" "in highp vec4 a_position;\n" "in highp vec4 a_color;\n" "out highp vec4 v_color;\n" "void main (void)\n" "{\n" " gl_Position = a_position;\n" " v_color = a_color;\n" "}\n"; static const char* const s_positionColorOffsetShader = "#version 310 es\n" "in highp vec4 a_position;\n" "in highp vec4 a_offset;\n" "in highp vec4 a_color;\n" "out highp vec4 v_color;\n" "void main (void)\n" "{\n" " gl_Position = a_position + a_offset;\n" " v_color = a_color;\n" "}\n"; // Verifies image contains only yellow or greeen, or a linear combination // of these colors. static bool verifyImageYellowGreen (const tcu::Surface& image, tcu::TestLog& log, bool logImageOnSuccess) { using tcu::TestLog; const tcu::RGBA green (0, 255, 0, 255); const tcu::RGBA yellow (255, 255, 0, 255); const int colorThreshold = 20; tcu::Surface error (image.getWidth(), image.getHeight()); bool isOk = true; log << TestLog::Message << "Verifying image contents." << TestLog::EndMessage; for (int y = 0; y < image.getHeight(); y++) for (int x = 0; x < image.getWidth(); x++) { const tcu::RGBA pixel = image.getPixel(x, y); bool pixelOk = true; // Any pixel with !(G ~= 255) is faulty (not a linear combinations of green and yellow) if (de::abs(pixel.getGreen() - 255) > colorThreshold) pixelOk = false; // Any pixel with !(B ~= 0) is faulty (not a linear combinations of green and yellow) if (de::abs(pixel.getBlue() - 0) > colorThreshold) pixelOk = false; error.setPixel(x, y, (pixelOk) ? (tcu::RGBA(0, 255, 0, 255)) : (tcu::RGBA(255, 0, 0, 255))); isOk = isOk && pixelOk; } if (!isOk) { log << TestLog::Message << "Image verification failed." << TestLog::EndMessage; log << TestLog::ImageSet("Verfication result", "Result of rendering") << TestLog::Image("Result", "Result", image) << TestLog::Image("ErrorMask", "Error mask", error) << TestLog::EndImageSet; } else { log << TestLog::Message << "Image verification passed." << TestLog::EndMessage; if (logImageOnSuccess) log << TestLog::ImageSet("Verfication result", "Result of rendering") << TestLog::Image("Result", "Result", image) << TestLog::EndImageSet; } return isOk; } class BindingRenderCase : public TestCase { public: enum { TEST_RENDER_SIZE = 64 }; BindingRenderCase (Context& ctx, const char* name, const char* desc, bool unalignedData); virtual ~BindingRenderCase (void); virtual void init (void); virtual void deinit (void); IterateResult iterate (void); private: virtual void renderTo (tcu::Surface& dst) = 0; virtual void createBuffers (void) = 0; virtual void createShader (void) = 0; protected: const bool m_unalignedData; glw::GLuint m_vao; glu::ShaderProgram* m_program; }; BindingRenderCase::BindingRenderCase (Context& ctx, const char* name, const char* desc, bool unalignedData) : TestCase (ctx, name, desc) , m_unalignedData (unalignedData) , m_vao (0) , m_program (DE_NULL) { } BindingRenderCase::~BindingRenderCase (void) { deinit(); } void BindingRenderCase::init (void) { // check requirements if (m_context.getRenderTarget().getWidth() < TEST_RENDER_SIZE || m_context.getRenderTarget().getHeight() < TEST_RENDER_SIZE) throw tcu::NotSupportedError("Test requires at least " + de::toString<int>(TEST_RENDER_SIZE) + "x" + de::toString<int>(TEST_RENDER_SIZE) + " render target"); // resources m_context.getRenderContext().getFunctions().genVertexArrays(1, &m_vao); if (m_context.getRenderContext().getFunctions().getError() != GL_NO_ERROR) throw tcu::TestError("could not gen vao"); createBuffers(); createShader(); } void BindingRenderCase::deinit (void) { if (m_vao) { m_context.getRenderContext().getFunctions().deleteVertexArrays(1, &m_vao); m_vao = 0; } delete m_program; m_program = DE_NULL; } BindingRenderCase::IterateResult BindingRenderCase::iterate (void) { tcu::Surface surface(TEST_RENDER_SIZE, TEST_RENDER_SIZE); // draw pattern renderTo(surface); // verify results if (verifyImageYellowGreen(surface, m_testCtx.getLog(), false)) m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); else if (m_unalignedData) m_testCtx.setTestResult(QP_TEST_RESULT_COMPATIBILITY_WARNING, "Failed to draw with unaligned data"); else m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Image verification failed"); return STOP; } class SingleBindingCase : public BindingRenderCase { public: enum CaseFlag { FLAG_ATTRIB_UNALIGNED = (1<<0), // !< unalign attributes with relativeOffset FLAG_ATTRIB_ALIGNED = (1<<1), // !< align attributes with relativeOffset to the buffer begin (and not buffer offset) FLAG_ATTRIBS_MULTIPLE_ELEMS = (1<<2), // !< use multiple attribute elements FLAG_ATTRIBS_SHARED_ELEMS = (1<<3), // !< use multiple shared attribute elements. xyzw & rgba stored as (x, y, zr, wg, b, a) FLAG_BUF_ALIGNED_OFFSET = (1<<4), // !< use aligned offset to the buffer object FLAG_BUF_UNALIGNED_OFFSET = (1<<5), // !< use unaligned offset to the buffer object FLAG_BUF_UNALIGNED_STRIDE = (1<<6), // !< unalign buffer elements }; SingleBindingCase (Context& ctx, const char* name, int flags); ~SingleBindingCase (void); void init (void); void deinit (void); private: struct TestSpec { int bufferOffset; int bufferStride; int positionAttrOffset; int colorAttrOffset; bool hasColorAttr; }; enum { GRID_SIZE = 20 }; void renderTo (tcu::Surface& dst); static TestSpec genTestSpec (int flags); static std::string genTestDescription (int flags); static bool isDataUnaligned (int flags); void createBuffers (void); void createShader (void); std::string genVertexSource (void); const TestSpec m_spec; glw::GLuint m_buf; }; SingleBindingCase::SingleBindingCase (Context& ctx, const char* name, int flags) : BindingRenderCase (ctx, name, genTestDescription(flags).c_str(), isDataUnaligned(flags)) , m_spec (genTestSpec(flags)) , m_buf (0) { DE_ASSERT(!((flags & FLAG_ATTRIB_UNALIGNED) && (flags & FLAG_ATTRIB_ALIGNED))); DE_ASSERT(!((flags & FLAG_ATTRIB_ALIGNED) && (flags & FLAG_BUF_UNALIGNED_STRIDE))); DE_ASSERT(!isDataUnaligned(flags)); } SingleBindingCase::~SingleBindingCase (void) { deinit(); } void SingleBindingCase::init (void) { // log what we are trying to do m_testCtx.getLog() << tcu::TestLog::Message << "Rendering " << (int)GRID_SIZE << "x" << (int)GRID_SIZE << " grid.\n" << "Buffer format:\n" << " bufferOffset: " << m_spec.bufferOffset << "\n" << " bufferStride: " << m_spec.bufferStride << "\n" << "Vertex position format:\n" << " type: float4\n" << " offset: " << m_spec.positionAttrOffset << "\n" << " total offset: " << m_spec.bufferOffset + m_spec.positionAttrOffset << "\n" << tcu::TestLog::EndMessage; if (m_spec.hasColorAttr) m_testCtx.getLog() << tcu::TestLog::Message << "Color:\n" << " type: float4\n" << " offset: " << m_spec.colorAttrOffset << "\n" << " total offset: " << m_spec.bufferOffset + m_spec.colorAttrOffset << "\n" << tcu::TestLog::EndMessage; // init BindingRenderCase::init(); } void SingleBindingCase::deinit (void) { if (m_buf) { m_context.getRenderContext().getFunctions().deleteBuffers(1, &m_buf); m_buf = 0; } BindingRenderCase::deinit(); } void SingleBindingCase::renderTo (tcu::Surface& dst) { glu::CallLogWrapper gl (m_context.getRenderContext().getFunctions(), m_testCtx.getLog()); const int positionLoc = gl.glGetAttribLocation(m_program->getProgram(), "a_position"); const int colorLoc = gl.glGetAttribLocation(m_program->getProgram(), "a_color"); const int colorUniformLoc = gl.glGetUniformLocation(m_program->getProgram(), "u_color"); gl.enableLogging(true); gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f); gl.glClear(GL_COLOR_BUFFER_BIT); gl.glViewport(0, 0, dst.getWidth(), dst.getHeight()); gl.glBindVertexArray(m_vao); GLU_EXPECT_NO_ERROR(gl.glGetError(), "set vao"); gl.glUseProgram(m_program->getProgram()); GLU_EXPECT_NO_ERROR(gl.glGetError(), "use program"); if (m_spec.hasColorAttr) { gl.glBindVertexBuffer(3, m_buf, m_spec.bufferOffset, m_spec.bufferStride); gl.glVertexAttribBinding(positionLoc, 3); gl.glVertexAttribFormat(positionLoc, 4, GL_FLOAT, GL_FALSE, m_spec.positionAttrOffset); gl.glEnableVertexAttribArray(positionLoc); gl.glVertexAttribBinding(colorLoc, 3); gl.glVertexAttribFormat(colorLoc, 4, GL_FLOAT, GL_FALSE, m_spec.colorAttrOffset); gl.glEnableVertexAttribArray(colorLoc); GLU_EXPECT_NO_ERROR(gl.glGetError(), "set va"); gl.glDrawArrays(GL_TRIANGLES, 0, GRID_SIZE*GRID_SIZE*6); GLU_EXPECT_NO_ERROR(gl.glGetError(), "draw"); } else { gl.glBindVertexBuffer(3, m_buf, m_spec.bufferOffset, m_spec.bufferStride); gl.glVertexAttribBinding(positionLoc, 3); gl.glVertexAttribFormat(positionLoc, 4, GL_FLOAT, GL_FALSE, m_spec.positionAttrOffset); gl.glEnableVertexAttribArray(positionLoc); GLU_EXPECT_NO_ERROR(gl.glGetError(), "set va"); gl.glUniform4f(colorUniformLoc, 0.0f, 1.0f, 0.0f, 1.0f); gl.glDrawArrays(GL_TRIANGLES, 0, GRID_SIZE*GRID_SIZE*6); GLU_EXPECT_NO_ERROR(gl.glGetError(), "draw"); } gl.glFinish(); gl.glBindVertexArray(0); gl.glUseProgram(0); GLU_EXPECT_NO_ERROR(gl.glGetError(), "clean"); glu::readPixels(m_context.getRenderContext(), 0, 0, dst.getAccess()); } SingleBindingCase::TestSpec SingleBindingCase::genTestSpec (int flags) { const int datumSize = 4; const int bufferOffset = (flags & FLAG_BUF_ALIGNED_OFFSET) ? (32) : (flags & FLAG_BUF_UNALIGNED_OFFSET) ? (19) : (0); const int attrBufAlignment = ((bufferOffset % datumSize) == 0) ? (0) : (datumSize - (bufferOffset % datumSize)); const int positionAttrOffset = (flags & FLAG_ATTRIB_UNALIGNED) ? (3) : (flags & FLAG_ATTRIB_ALIGNED) ? (attrBufAlignment) : (0); const bool hasColorAttr = (flags & FLAG_ATTRIBS_SHARED_ELEMS) || (flags & FLAG_ATTRIBS_MULTIPLE_ELEMS); const int colorAttrOffset = (flags & FLAG_ATTRIBS_SHARED_ELEMS) ? (2 * datumSize) : (flags & FLAG_ATTRIBS_MULTIPLE_ELEMS) ? (4 * datumSize) : (-1); const int bufferStrideBase = de::max(positionAttrOffset + 4 * datumSize, colorAttrOffset + 4 * datumSize); const int bufferStrideAlignment = ((bufferStrideBase % datumSize) == 0) ? (0) : (datumSize - (bufferStrideBase % datumSize)); const int bufferStridePadding = ((flags & FLAG_BUF_UNALIGNED_STRIDE) && deIsAligned32(bufferStrideBase, datumSize)) ? (13) : (!(flags & FLAG_BUF_UNALIGNED_STRIDE) && !deIsAligned32(bufferStrideBase, datumSize)) ? (bufferStrideAlignment) : (0); TestSpec spec; spec.bufferOffset = bufferOffset; spec.bufferStride = bufferStrideBase + bufferStridePadding; spec.positionAttrOffset = positionAttrOffset; spec.colorAttrOffset = colorAttrOffset; spec.hasColorAttr = hasColorAttr; if (flags & FLAG_ATTRIB_UNALIGNED) DE_ASSERT(!deIsAligned32(spec.bufferOffset + spec.positionAttrOffset, datumSize)); else if (flags & FLAG_ATTRIB_ALIGNED) DE_ASSERT(deIsAligned32(spec.bufferOffset + spec.positionAttrOffset, datumSize)); if (flags & FLAG_BUF_UNALIGNED_STRIDE) DE_ASSERT(!deIsAligned32(spec.bufferStride, datumSize)); else DE_ASSERT(deIsAligned32(spec.bufferStride, datumSize)); return spec; } std::string SingleBindingCase::genTestDescription (int flags) { std::ostringstream buf; buf << "draw test pattern"; if (flags & FLAG_ATTRIB_UNALIGNED) buf << ", attribute offset (unaligned)"; if (flags & FLAG_ATTRIB_ALIGNED) buf << ", attribute offset (aligned)"; if (flags & FLAG_ATTRIBS_MULTIPLE_ELEMS) buf << ", 2 attributes"; if (flags & FLAG_ATTRIBS_SHARED_ELEMS) buf << ", 2 attributes (some components shared)"; if (flags & FLAG_BUF_ALIGNED_OFFSET) buf << ", buffer offset aligned"; if (flags & FLAG_BUF_UNALIGNED_OFFSET) buf << ", buffer offset unaligned"; if (flags & FLAG_BUF_UNALIGNED_STRIDE) buf << ", buffer stride unaligned"; return buf.str(); } bool SingleBindingCase::isDataUnaligned (int flags) { if (flags & FLAG_ATTRIB_UNALIGNED) return true; if (flags & FLAG_ATTRIB_ALIGNED) return false; return (flags & FLAG_BUF_UNALIGNED_OFFSET) || (flags & FLAG_BUF_UNALIGNED_STRIDE); } void SingleBindingCase::createBuffers (void) { const glw::Functions& gl = m_context.getRenderContext().getFunctions(); std::vector<deUint8> dataBuf (m_spec.bufferOffset + m_spec.bufferStride * GRID_SIZE * GRID_SIZE * 6); // In interleaved mode color rg and position zw are the same. Select "good" values for r and g const tcu::Vec4 colorA (0.0f, 1.0f, 0.0f, 1.0f); const tcu::Vec4 colorB (0.5f, 1.0f, 0.0f, 1.0f); for (int y = 0; y < GRID_SIZE; ++y) for (int x = 0; x < GRID_SIZE; ++x) { const tcu::Vec4& color = ((x + y) % 2 == 0) ? (colorA) : (colorB); const tcu::Vec4 positions[6] = { tcu::Vec4((x+0) / float(GRID_SIZE) * 2.0f - 1.0f, (y+0) / float(GRID_SIZE) * 2.0f - 1.0f, 0.0f, 1.0f), tcu::Vec4((x+0) / float(GRID_SIZE) * 2.0f - 1.0f, (y+1) / float(GRID_SIZE) * 2.0f - 1.0f, 0.0f, 1.0f), tcu::Vec4((x+1) / float(GRID_SIZE) * 2.0f - 1.0f, (y+1) / float(GRID_SIZE) * 2.0f - 1.0f, 0.0f, 1.0f), tcu::Vec4((x+0) / float(GRID_SIZE) * 2.0f - 1.0f, (y+0) / float(GRID_SIZE) * 2.0f - 1.0f, 0.0f, 1.0f), tcu::Vec4((x+1) / float(GRID_SIZE) * 2.0f - 1.0f, (y+1) / float(GRID_SIZE) * 2.0f - 1.0f, 0.0f, 1.0f), tcu::Vec4((x+1) / float(GRID_SIZE) * 2.0f - 1.0f, (y+0) / float(GRID_SIZE) * 2.0f - 1.0f, 0.0f, 1.0f), }; // copy cell vertices to the buffer. for (int v = 0; v < 6; ++v) memcpy(&dataBuf[m_spec.bufferOffset + m_spec.positionAttrOffset + m_spec.bufferStride * ((y * GRID_SIZE + x) * 6 + v)], positions[v].getPtr(), sizeof(positions[v])); // copy color to buffer if (m_spec.hasColorAttr) for (int v = 0; v < 6; ++v) memcpy(&dataBuf[m_spec.bufferOffset + m_spec.colorAttrOffset + m_spec.bufferStride * ((y * GRID_SIZE + x) * 6 + v)], color.getPtr(), sizeof(color)); } gl.genBuffers(1, &m_buf); gl.bindBuffer(GL_ARRAY_BUFFER, m_buf); gl.bufferData(GL_ARRAY_BUFFER, (glw::GLsizeiptr)dataBuf.size(), &dataBuf[0], GL_STATIC_DRAW); gl.bindBuffer(GL_ARRAY_BUFFER, 0); if (gl.getError() != GL_NO_ERROR) throw tcu::TestError("could not init buffer"); } void SingleBindingCase::createShader (void) { m_program = new glu::ShaderProgram(m_context.getRenderContext(), glu::ProgramSources() << glu::VertexSource(genVertexSource()) << glu::FragmentSource(s_colorFragmentShader)); m_testCtx.getLog() << *m_program; if (!m_program->isOk()) throw tcu::TestError("could not build shader"); } std::string SingleBindingCase::genVertexSource (void) { const bool useUniformColor = !m_spec.hasColorAttr; std::ostringstream buf; buf << "#version 310 es\n" "in highp vec4 a_position;\n"; if (!useUniformColor) buf << "in highp vec4 a_color;\n"; else buf << "uniform highp vec4 u_color;\n"; buf << "out highp vec4 v_color;\n" "void main (void)\n" "{\n" " gl_Position = a_position;\n" " v_color = " << ((useUniformColor) ? ("u_color") : ("a_color")) << ";\n" "}\n"; return buf.str(); } class MultipleBindingCase : public BindingRenderCase { public: enum CaseFlag { FLAG_ZERO_STRIDE = (1<<0), // !< set a buffer stride to zero FLAG_INSTANCED = (1<<1), // !< set a buffer instance divisor to non-zero FLAG_ALIASING_BUFFERS = (1<<2), // !< bind buffer to multiple binding points }; MultipleBindingCase (Context& ctx, const char* name, int flags); ~MultipleBindingCase (void); void init (void); void deinit (void); private: struct TestSpec { bool zeroStride; bool instanced; bool aliasingBuffers; }; enum { GRID_SIZE = 20 }; void renderTo (tcu::Surface& dst); TestSpec genTestSpec (int flags) const; std::string genTestDescription (int flags) const; void createBuffers (void); void createShader (void); const TestSpec m_spec; glw::GLuint m_primitiveBuf; glw::GLuint m_colorOffsetBuf; }; MultipleBindingCase::MultipleBindingCase (Context& ctx, const char* name, int flags) : BindingRenderCase (ctx, name, genTestDescription(flags).c_str(), false) , m_spec (genTestSpec(flags)) , m_primitiveBuf (0) , m_colorOffsetBuf (0) { DE_ASSERT(!(m_spec.instanced && m_spec.zeroStride)); } MultipleBindingCase::~MultipleBindingCase (void) { deinit(); } void MultipleBindingCase::init (void) { BindingRenderCase::init(); // log what we are trying to do m_testCtx.getLog() << tcu::TestLog::Message << "Rendering " << (int)GRID_SIZE << "x" << (int)GRID_SIZE << " grid.\n" << "Vertex positions:\n" << " binding point: 1\n" << "Vertex offsets:\n" << " binding point: 2\n" << "Vertex colors:\n" << " binding point: 2\n" << "Binding point 1:\n" << " buffer object: " << m_primitiveBuf << "\n" << "Binding point 2:\n" << " buffer object: " << ((m_spec.aliasingBuffers) ? (m_primitiveBuf) : (m_colorOffsetBuf)) << "\n" << " instance divisor: " << ((m_spec.instanced) ? (1) : (0)) << "\n" << " stride: " << ((m_spec.zeroStride) ? (0) : (4*4*2)) << "\n" << tcu::TestLog::EndMessage; } void MultipleBindingCase::deinit (void) { if (m_primitiveBuf) { m_context.getRenderContext().getFunctions().deleteBuffers(1, &m_primitiveBuf); m_primitiveBuf = DE_NULL; } if (m_colorOffsetBuf) { m_context.getRenderContext().getFunctions().deleteBuffers(1, &m_colorOffsetBuf); m_colorOffsetBuf = DE_NULL; } BindingRenderCase::deinit(); } void MultipleBindingCase::renderTo (tcu::Surface& dst) { glu::CallLogWrapper gl (m_context.getRenderContext().getFunctions(), m_testCtx.getLog()); const int positionLoc = gl.glGetAttribLocation(m_program->getProgram(), "a_position"); const int colorLoc = gl.glGetAttribLocation(m_program->getProgram(), "a_color"); const int offsetLoc = gl.glGetAttribLocation(m_program->getProgram(), "a_offset"); const int positionBinding = 1; const int colorOffsetBinding = 2; gl.enableLogging(true); gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f); gl.glClear(GL_COLOR_BUFFER_BIT); gl.glViewport(0, 0, dst.getWidth(), dst.getHeight()); gl.glBindVertexArray(m_vao); GLU_EXPECT_NO_ERROR(gl.glGetError(), "set vao"); gl.glUseProgram(m_program->getProgram()); GLU_EXPECT_NO_ERROR(gl.glGetError(), "use program"); // Setup format & binding gl.glEnableVertexAttribArray(positionLoc); gl.glEnableVertexAttribArray(colorLoc); gl.glEnableVertexAttribArray(offsetLoc); gl.glVertexAttribFormat(positionLoc, 4, GL_FLOAT, GL_FALSE, 0); gl.glVertexAttribFormat(colorLoc, 4, GL_FLOAT, GL_FALSE, 0); gl.glVertexAttribFormat(offsetLoc, 4, GL_FLOAT, GL_FALSE, sizeof(tcu::Vec4)); gl.glVertexAttribBinding(positionLoc, positionBinding); gl.glVertexAttribBinding(colorLoc, colorOffsetBinding); gl.glVertexAttribBinding(offsetLoc, colorOffsetBinding); GLU_EXPECT_NO_ERROR(gl.glGetError(), "setup attribs"); // setup binding points gl.glVertexBindingDivisor(positionBinding, 0); gl.glBindVertexBuffer(positionBinding, m_primitiveBuf, 0, sizeof(tcu::Vec4)); { const int stride = (m_spec.zeroStride) ? (0) : (2 * (int)sizeof(tcu::Vec4)); const int offset = (!m_spec.aliasingBuffers) ? (0) : (m_spec.instanced) ? (6 * (int)sizeof(tcu::Vec4)) : (6 * GRID_SIZE * GRID_SIZE * (int)sizeof(tcu::Vec4)); const glw::GLuint buffer = (m_spec.aliasingBuffers) ? (m_primitiveBuf) : (m_colorOffsetBuf); const int divisor = (m_spec.instanced) ? (1) : (0); gl.glVertexBindingDivisor(colorOffsetBinding, divisor); gl.glBindVertexBuffer(colorOffsetBinding, buffer, offset, (glw::GLsizei)stride); } GLU_EXPECT_NO_ERROR(gl.glGetError(), "set binding points"); if (m_spec.instanced) gl.glDrawArraysInstanced(GL_TRIANGLES, 0, 6, GRID_SIZE*GRID_SIZE); else gl.glDrawArrays(GL_TRIANGLES, 0, GRID_SIZE*GRID_SIZE*6); GLU_EXPECT_NO_ERROR(gl.glGetError(), "draw"); gl.glFinish(); gl.glBindVertexArray(0); gl.glUseProgram(0); GLU_EXPECT_NO_ERROR(gl.glGetError(), "clean"); glu::readPixels(m_context.getRenderContext(), 0, 0, dst.getAccess()); } MultipleBindingCase::TestSpec MultipleBindingCase::genTestSpec (int flags) const { MultipleBindingCase::TestSpec spec; spec.zeroStride = !!(flags & FLAG_ZERO_STRIDE); spec.instanced = !!(flags & FLAG_INSTANCED); spec.aliasingBuffers = !!(flags & FLAG_ALIASING_BUFFERS); return spec; } std::string MultipleBindingCase::genTestDescription (int flags) const { std::ostringstream buf; buf << "draw test pattern"; if (flags & FLAG_ZERO_STRIDE) buf << ", zero stride"; if (flags & FLAG_INSTANCED) buf << ", instanced binding point"; if (flags & FLAG_ALIASING_BUFFERS) buf << ", binding points share buffer object"; return buf.str(); } void MultipleBindingCase::createBuffers (void) { const glw::Functions& gl = m_context.getRenderContext().getFunctions(); const tcu::Vec4 green = tcu::Vec4(0.0f, 1.0f, 0.0f, 1.0f); const tcu::Vec4 yellow = tcu::Vec4(1.0f, 1.0f, 0.0f, 1.0f); const int vertexDataSize = (m_spec.instanced) ? (6) : (6 * GRID_SIZE * GRID_SIZE); const int offsetColorSize = (m_spec.zeroStride) ? (2) : (m_spec.instanced) ? (2 * GRID_SIZE * GRID_SIZE) : (2 * 6 * GRID_SIZE * GRID_SIZE); const int primitiveBufSize = (m_spec.aliasingBuffers) ? (vertexDataSize + offsetColorSize) : (vertexDataSize); const int colorOffsetBufSize = (m_spec.aliasingBuffers) ? (0) : (offsetColorSize); std::vector<tcu::Vec4> primitiveData (primitiveBufSize); std::vector<tcu::Vec4> colorOffsetData (colorOffsetBufSize); tcu::Vec4* colorOffsetWritePtr = DE_NULL; if (m_spec.aliasingBuffers) { if (m_spec.instanced) colorOffsetWritePtr = &primitiveData[6]; else colorOffsetWritePtr = &primitiveData[GRID_SIZE*GRID_SIZE*6]; } else colorOffsetWritePtr = &colorOffsetData[0]; // write vertex position if (m_spec.instanced) { // store single basic primitive primitiveData[0] = tcu::Vec4(0.0f, 0.0f, 0.0f, 1.0f); primitiveData[1] = tcu::Vec4(0.0f, 2.0f / GRID_SIZE, 0.0f, 1.0f); primitiveData[2] = tcu::Vec4(2.0f / GRID_SIZE, 2.0f / GRID_SIZE, 0.0f, 1.0f); primitiveData[3] = tcu::Vec4(0.0f, 0.0f, 0.0f, 1.0f); primitiveData[4] = tcu::Vec4(2.0f / GRID_SIZE, 2.0f / GRID_SIZE, 0.0f, 1.0f); primitiveData[5] = tcu::Vec4(2.0f / GRID_SIZE, 0.0f, 0.0f, 1.0f); } else { // store whole grid for (int y = 0; y < GRID_SIZE; ++y) for (int x = 0; x < GRID_SIZE; ++x) { primitiveData[(y * GRID_SIZE + x) * 6 + 0] = tcu::Vec4((x+0) / float(GRID_SIZE) * 2.0f - 1.0f, (y+0) / float(GRID_SIZE) * 2.0f - 1.0f, 0.0f, 1.0f); primitiveData[(y * GRID_SIZE + x) * 6 + 1] = tcu::Vec4((x+0) / float(GRID_SIZE) * 2.0f - 1.0f, (y+1) / float(GRID_SIZE) * 2.0f - 1.0f, 0.0f, 1.0f); primitiveData[(y * GRID_SIZE + x) * 6 + 2] = tcu::Vec4((x+1) / float(GRID_SIZE) * 2.0f - 1.0f, (y+1) / float(GRID_SIZE) * 2.0f - 1.0f, 0.0f, 1.0f); primitiveData[(y * GRID_SIZE + x) * 6 + 3] = tcu::Vec4((x+0) / float(GRID_SIZE) * 2.0f - 1.0f, (y+0) / float(GRID_SIZE) * 2.0f - 1.0f, 0.0f, 1.0f); primitiveData[(y * GRID_SIZE + x) * 6 + 4] = tcu::Vec4((x+1) / float(GRID_SIZE) * 2.0f - 1.0f, (y+1) / float(GRID_SIZE) * 2.0f - 1.0f, 0.0f, 1.0f); primitiveData[(y * GRID_SIZE + x) * 6 + 5] = tcu::Vec4((x+1) / float(GRID_SIZE) * 2.0f - 1.0f, (y+0) / float(GRID_SIZE) * 2.0f - 1.0f, 0.0f, 1.0f); } } // store color&offset if (m_spec.zeroStride) { colorOffsetWritePtr[0] = green; colorOffsetWritePtr[1] = tcu::Vec4(0.0f); } else if (m_spec.instanced) { for (int y = 0; y < GRID_SIZE; ++y) for (int x = 0; x < GRID_SIZE; ++x) { const tcu::Vec4& color = ((x + y) % 2 == 0) ? (green) : (yellow); colorOffsetWritePtr[(y * GRID_SIZE + x) * 2 + 0] = color; colorOffsetWritePtr[(y * GRID_SIZE + x) * 2 + 1] = tcu::Vec4(x / float(GRID_SIZE) * 2.0f - 1.0f, y / float(GRID_SIZE) * 2.0f - 1.0f, 0.0f, 0.0f); } } else { for (int y = 0; y < GRID_SIZE; ++y) for (int x = 0; x < GRID_SIZE; ++x) for (int v = 0; v < 6; ++v) { const tcu::Vec4& color = ((x + y) % 2 == 0) ? (green) : (yellow); colorOffsetWritePtr[((y * GRID_SIZE + x) * 6 + v) * 2 + 0] = color; colorOffsetWritePtr[((y * GRID_SIZE + x) * 6 + v) * 2 + 1] = tcu::Vec4(0.0f); } } // upload vertex data gl.genBuffers(1, &m_primitiveBuf); gl.bindBuffer(GL_ARRAY_BUFFER, m_primitiveBuf); gl.bufferData(GL_ARRAY_BUFFER, (int)(primitiveData.size() * sizeof(tcu::Vec4)), primitiveData[0].getPtr(), GL_STATIC_DRAW); GLU_EXPECT_NO_ERROR(gl.getError(), "upload data"); if (!m_spec.aliasingBuffers) { // upload color & offset data gl.genBuffers(1, &m_colorOffsetBuf); gl.bindBuffer(GL_ARRAY_BUFFER, m_colorOffsetBuf); gl.bufferData(GL_ARRAY_BUFFER, (int)(colorOffsetData.size() * sizeof(tcu::Vec4)), colorOffsetData[0].getPtr(), GL_STATIC_DRAW); GLU_EXPECT_NO_ERROR(gl.getError(), "upload colordata"); } } void MultipleBindingCase::createShader (void) { m_program = new glu::ShaderProgram(m_context.getRenderContext(), glu::ProgramSources() << glu::VertexSource(s_positionColorOffsetShader) << glu::FragmentSource(s_colorFragmentShader)); m_testCtx.getLog() << *m_program; if (!m_program->isOk()) throw tcu::TestError("could not build shader"); } class MixedBindingCase : public BindingRenderCase { public: enum CaseType { CASE_BASIC = 0, CASE_INSTANCED_BINDING, CASE_INSTANCED_ATTRIB, CASE_LAST }; MixedBindingCase (Context& ctx, const char* name, const char* desc, CaseType caseType); ~MixedBindingCase (void); void init (void); void deinit (void); private: enum { GRID_SIZE = 20 }; void renderTo (tcu::Surface& dst); void createBuffers (void); void createShader (void); const CaseType m_case; glw::GLuint m_posBuffer; glw::GLuint m_colorOffsetBuffer; }; MixedBindingCase::MixedBindingCase (Context& ctx, const char* name, const char* desc, CaseType caseType) : BindingRenderCase (ctx, name, desc, false) , m_case (caseType) , m_posBuffer (0) , m_colorOffsetBuffer (0) { DE_ASSERT(caseType < CASE_LAST); } MixedBindingCase::~MixedBindingCase (void) { deinit(); } void MixedBindingCase::init (void) { BindingRenderCase::init(); } void MixedBindingCase::deinit (void) { if (m_posBuffer) { m_context.getRenderContext().getFunctions().deleteBuffers(1, &m_posBuffer); m_posBuffer = DE_NULL; } if (m_colorOffsetBuffer) { m_context.getRenderContext().getFunctions().deleteBuffers(1, &m_colorOffsetBuffer); m_colorOffsetBuffer = DE_NULL; } BindingRenderCase::deinit(); } void MixedBindingCase::renderTo (tcu::Surface& dst) { glu::CallLogWrapper gl (m_context.getRenderContext().getFunctions(), m_testCtx.getLog()); const int positionLoc = gl.glGetAttribLocation(m_program->getProgram(), "a_position"); const int colorLoc = gl.glGetAttribLocation(m_program->getProgram(), "a_color"); const int offsetLoc = gl.glGetAttribLocation(m_program->getProgram(), "a_offset"); gl.enableLogging(true); gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f); gl.glClear(GL_COLOR_BUFFER_BIT); gl.glViewport(0, 0, dst.getWidth(), dst.getHeight()); gl.glBindVertexArray(m_vao); GLU_EXPECT_NO_ERROR(gl.glGetError(), "set vao"); gl.glUseProgram(m_program->getProgram()); GLU_EXPECT_NO_ERROR(gl.glGetError(), "use program"); switch (m_case) { case CASE_BASIC: { // bind position using vertex_attrib_binding api gl.glBindVertexBuffer(positionLoc, m_posBuffer, 0, (glw::GLsizei)sizeof(tcu::Vec4)); gl.glVertexAttribBinding(positionLoc, positionLoc); gl.glVertexAttribFormat(positionLoc, 4, GL_FLOAT, GL_FALSE, 0); GLU_EXPECT_NO_ERROR(gl.glGetError(), "set binding"); // bind color using old api gl.glBindBuffer(GL_ARRAY_BUFFER, m_colorOffsetBuffer); gl.glVertexAttribPointer(colorLoc, 4, GL_FLOAT, GL_FALSE, glw::GLsizei(2 * sizeof(tcu::Vec4)), DE_NULL); gl.glVertexAttribPointer(offsetLoc, 4, GL_FLOAT, GL_FALSE, glw::GLsizei(2 * sizeof(tcu::Vec4)), (deUint8*)DE_NULL + sizeof(tcu::Vec4)); GLU_EXPECT_NO_ERROR(gl.glGetError(), "set va"); // draw gl.glEnableVertexAttribArray(positionLoc); gl.glEnableVertexAttribArray(colorLoc); gl.glEnableVertexAttribArray(offsetLoc); gl.glDrawArrays(GL_TRIANGLES, 0, 6*GRID_SIZE*GRID_SIZE); break; } case CASE_INSTANCED_BINDING: { // bind position using old api gl.glBindBuffer(GL_ARRAY_BUFFER, m_posBuffer); gl.glVertexAttribPointer(positionLoc, 4, GL_FLOAT, GL_FALSE, 0, DE_NULL); GLU_EXPECT_NO_ERROR(gl.glGetError(), "set va"); // bind color using vertex_attrib_binding api gl.glBindVertexBuffer(colorLoc, m_colorOffsetBuffer, 0, (glw::GLsizei)(2 * sizeof(tcu::Vec4))); gl.glVertexBindingDivisor(colorLoc, 1); gl.glVertexAttribBinding(colorLoc, colorLoc); gl.glVertexAttribBinding(offsetLoc, colorLoc); gl.glVertexAttribFormat(colorLoc, 4, GL_FLOAT, GL_FALSE, 0); gl.glVertexAttribFormat(offsetLoc, 4, GL_FLOAT, GL_FALSE, sizeof(tcu::Vec4)); GLU_EXPECT_NO_ERROR(gl.glGetError(), "set binding"); // draw gl.glEnableVertexAttribArray(positionLoc); gl.glEnableVertexAttribArray(colorLoc); gl.glEnableVertexAttribArray(offsetLoc); gl.glDrawArraysInstanced(GL_TRIANGLES, 0, 6, GRID_SIZE*GRID_SIZE); break; } case CASE_INSTANCED_ATTRIB: { // bind position using vertex_attrib_binding api gl.glBindVertexBuffer(positionLoc, m_posBuffer, 0, (glw::GLsizei)sizeof(tcu::Vec4)); gl.glVertexAttribBinding(positionLoc, positionLoc); gl.glVertexAttribFormat(positionLoc, 4, GL_FLOAT, GL_FALSE, 0); GLU_EXPECT_NO_ERROR(gl.glGetError(), "set binding"); // bind color using old api gl.glBindBuffer(GL_ARRAY_BUFFER, m_colorOffsetBuffer); gl.glVertexAttribPointer(colorLoc, 4, GL_FLOAT, GL_FALSE, glw::GLsizei(2 * sizeof(tcu::Vec4)), DE_NULL); gl.glVertexAttribPointer(offsetLoc, 4, GL_FLOAT, GL_FALSE, glw::GLsizei(2 * sizeof(tcu::Vec4)), (deUint8*)DE_NULL + sizeof(tcu::Vec4)); gl.glVertexAttribDivisor(colorLoc, 1); gl.glVertexAttribDivisor(offsetLoc, 1); GLU_EXPECT_NO_ERROR(gl.glGetError(), "set va"); // draw gl.glEnableVertexAttribArray(positionLoc); gl.glEnableVertexAttribArray(colorLoc); gl.glEnableVertexAttribArray(offsetLoc); gl.glDrawArraysInstanced(GL_TRIANGLES, 0, 6, GRID_SIZE*GRID_SIZE); break; } default: DE_ASSERT(DE_FALSE); } gl.glFinish(); gl.glBindVertexArray(0); gl.glUseProgram(0); GLU_EXPECT_NO_ERROR(gl.glGetError(), "clean"); glu::readPixels(m_context.getRenderContext(), 0, 0, dst.getAccess()); } void MixedBindingCase::createBuffers (void) { const glw::Functions& gl = m_context.getRenderContext().getFunctions(); const tcu::Vec4 green = tcu::Vec4(0.0f, 1.0f, 0.0f, 1.0f); const tcu::Vec4 yellow = tcu::Vec4(1.0f, 1.0f, 0.0f, 1.0f); // draw grid. In instanced mode, each cell is an instance const bool instanced = (m_case == CASE_INSTANCED_BINDING) || (m_case == CASE_INSTANCED_ATTRIB); const int numCells = GRID_SIZE*GRID_SIZE; const int numPositionCells = (instanced) ? (1) : (numCells); const int numPositionElements = 6 * numPositionCells; const int numInstanceElementsPerCell = (instanced) ? (1) : (6); const int numColorOffsetElements = numInstanceElementsPerCell * numCells; std::vector<tcu::Vec4> positionData (numPositionElements); std::vector<tcu::Vec4> colorOffsetData (2 * numColorOffsetElements); // positions for (int primNdx = 0; primNdx < numPositionCells; ++primNdx) { positionData[primNdx*6 + 0] = tcu::Vec4(0.0f, 0.0f, 0.0f, 1.0f); positionData[primNdx*6 + 1] = tcu::Vec4(0.0f, 2.0f / GRID_SIZE, 0.0f, 1.0f); positionData[primNdx*6 + 2] = tcu::Vec4(2.0f / GRID_SIZE, 2.0f / GRID_SIZE, 0.0f, 1.0f); positionData[primNdx*6 + 3] = tcu::Vec4(0.0f, 0.0f, 0.0f, 1.0f); positionData[primNdx*6 + 4] = tcu::Vec4(2.0f / GRID_SIZE, 2.0f / GRID_SIZE, 0.0f, 1.0f); positionData[primNdx*6 + 5] = tcu::Vec4(2.0f / GRID_SIZE, 0.0f, 0.0f, 1.0f); } // color & offset for (int y = 0; y < GRID_SIZE; ++y) for (int x = 0; x < GRID_SIZE; ++x) { for (int v = 0; v < numInstanceElementsPerCell; ++v) { const tcu::Vec4& color = ((x + y) % 2 == 0) ? (green) : (yellow); colorOffsetData[((y * GRID_SIZE + x) * numInstanceElementsPerCell + v) * 2 + 0] = color; colorOffsetData[((y * GRID_SIZE + x) * numInstanceElementsPerCell + v) * 2 + 1] = tcu::Vec4(x / float(GRID_SIZE) * 2.0f - 1.0f, y / float(GRID_SIZE) * 2.0f - 1.0f, 0.0f, 0.0f); } } // upload vertex data gl.genBuffers(1, &m_posBuffer); gl.bindBuffer(GL_ARRAY_BUFFER, m_posBuffer); gl.bufferData(GL_ARRAY_BUFFER, (int)(positionData.size() * sizeof(tcu::Vec4)), positionData[0].getPtr(), GL_STATIC_DRAW); GLU_EXPECT_NO_ERROR(gl.getError(), "upload position data"); gl.genBuffers(1, &m_colorOffsetBuffer); gl.bindBuffer(GL_ARRAY_BUFFER, m_colorOffsetBuffer); gl.bufferData(GL_ARRAY_BUFFER, (int)(colorOffsetData.size() * sizeof(tcu::Vec4)), colorOffsetData[0].getPtr(), GL_STATIC_DRAW); GLU_EXPECT_NO_ERROR(gl.getError(), "upload position data"); } void MixedBindingCase::createShader (void) { m_program = new glu::ShaderProgram(m_context.getRenderContext(), glu::ProgramSources() << glu::VertexSource(s_positionColorOffsetShader) << glu::FragmentSource(s_colorFragmentShader)); m_testCtx.getLog() << *m_program; if (!m_program->isOk()) throw tcu::TestError("could not build shader"); } class MixedApiCase : public BindingRenderCase { public: enum CaseType { CASE_CHANGE_BUFFER = 0, CASE_CHANGE_BUFFER_OFFSET, CASE_CHANGE_BUFFER_STRIDE, CASE_CHANGE_BINDING_POINT, CASE_LAST }; MixedApiCase (Context& ctx, const char* name, const char* desc, CaseType caseType); ~MixedApiCase (void); void init (void); void deinit (void); private: enum { GRID_SIZE = 20 }; void renderTo (tcu::Surface& dst); void createBuffers (void); void createShader (void); const CaseType m_case; glw::GLuint m_buffer; }; MixedApiCase::MixedApiCase (Context& ctx, const char* name, const char* desc, CaseType caseType) : BindingRenderCase (ctx, name, desc, false) , m_case (caseType) , m_buffer (0) { DE_ASSERT(caseType < CASE_LAST); } MixedApiCase::~MixedApiCase (void) { deinit(); } void MixedApiCase::init (void) { BindingRenderCase::init(); } void MixedApiCase::deinit (void) { if (m_buffer) { m_context.getRenderContext().getFunctions().deleteBuffers(1, &m_buffer); m_buffer = DE_NULL; } BindingRenderCase::deinit(); } void MixedApiCase::renderTo (tcu::Surface& dst) { glu::CallLogWrapper gl (m_context.getRenderContext().getFunctions(), m_testCtx.getLog()); const int positionLoc = gl.glGetAttribLocation(m_program->getProgram(), "a_position"); const int colorLoc = gl.glGetAttribLocation(m_program->getProgram(), "a_color"); glu::Buffer dummyBuffer (m_context.getRenderContext()); gl.enableLogging(true); gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f); gl.glClear(GL_COLOR_BUFFER_BIT); gl.glViewport(0, 0, dst.getWidth(), dst.getHeight()); gl.glBindVertexArray(m_vao); GLU_EXPECT_NO_ERROR(gl.glGetError(), "set vao"); gl.glUseProgram(m_program->getProgram()); GLU_EXPECT_NO_ERROR(gl.glGetError(), "use program"); switch (m_case) { case CASE_CHANGE_BUFFER: { // bind data using old api gl.glBindBuffer(GL_ARRAY_BUFFER, *dummyBuffer); gl.glVertexAttribPointer(positionLoc, 4, GL_FLOAT, GL_FALSE, (glw::GLsizei)(2 * sizeof(tcu::Vec4)), (const deUint8*)DE_NULL); gl.glVertexAttribPointer(colorLoc, 4, GL_FLOAT, GL_FALSE, (glw::GLsizei)(2 * sizeof(tcu::Vec4)), (const deUint8*)DE_NULL + sizeof(tcu::Vec4)); // change buffer with vertex_attrib_binding gl.glBindVertexBuffer(positionLoc, m_buffer, 0, (glw::GLsizei)(2 * sizeof(tcu::Vec4))); gl.glBindVertexBuffer(colorLoc, m_buffer, sizeof(tcu::Vec4), (glw::GLsizei)(2 * sizeof(tcu::Vec4))); GLU_EXPECT_NO_ERROR(gl.glGetError(), ""); break; } case CASE_CHANGE_BUFFER_OFFSET: { // bind data using old api gl.glBindBuffer(GL_ARRAY_BUFFER, m_buffer); gl.glVertexAttribPointer(positionLoc, 4, GL_FLOAT, GL_FALSE, (glw::GLsizei)(2 * sizeof(tcu::Vec4)), (const deUint8*)DE_NULL); gl.glVertexAttribPointer(colorLoc, 4, GL_FLOAT, GL_FALSE, (glw::GLsizei)(2 * sizeof(tcu::Vec4)), (const deUint8*)DE_NULL); // change buffer offset with vertex_attrib_binding gl.glBindVertexBuffer(positionLoc, m_buffer, 0, (glw::GLsizei)(2 * sizeof(tcu::Vec4))); gl.glBindVertexBuffer(colorLoc, m_buffer, sizeof(tcu::Vec4), (glw::GLsizei)(2 * sizeof(tcu::Vec4))); GLU_EXPECT_NO_ERROR(gl.glGetError(), ""); break; } case CASE_CHANGE_BUFFER_STRIDE: { // bind data using old api gl.glBindBuffer(GL_ARRAY_BUFFER, m_buffer); gl.glVertexAttribPointer(positionLoc, 4, GL_FLOAT, GL_FALSE, 8, (const deUint8*)DE_NULL); gl.glVertexAttribPointer(colorLoc, 4, GL_FLOAT, GL_FALSE, 4, (const deUint8*)DE_NULL); // change buffer stride with vertex_attrib_binding gl.glBindVertexBuffer(positionLoc, m_buffer, 0, (glw::GLsizei)(2 * sizeof(tcu::Vec4))); gl.glBindVertexBuffer(colorLoc, m_buffer, sizeof(tcu::Vec4), (glw::GLsizei)(2 * sizeof(tcu::Vec4))); GLU_EXPECT_NO_ERROR(gl.glGetError(), ""); break; } case CASE_CHANGE_BINDING_POINT: { const int maxUsedLocation = de::max(positionLoc, colorLoc); const int bindingPoint1 = maxUsedLocation + 1; const int bindingPoint2 = maxUsedLocation + 2; // bind data using old api gl.glBindBuffer(GL_ARRAY_BUFFER, m_buffer); gl.glVertexAttribPointer(bindingPoint1, 4, GL_FLOAT, GL_FALSE, (glw::GLsizei)(2 * sizeof(tcu::Vec4)), (const deUint8*)DE_NULL); gl.glVertexAttribPointer(bindingPoint2, 4, GL_FLOAT, GL_FALSE, (glw::GLsizei)(2 * sizeof(tcu::Vec4)), (const deUint8*)DE_NULL + sizeof(tcu::Vec4)); // change buffer binding point with vertex_attrib_binding gl.glVertexAttribFormat(positionLoc, 4, GL_FLOAT, GL_FALSE, 0); gl.glVertexAttribFormat(colorLoc, 4, GL_FLOAT, GL_FALSE, 0); gl.glVertexAttribBinding(positionLoc, bindingPoint1); gl.glVertexAttribBinding(colorLoc, bindingPoint2); GLU_EXPECT_NO_ERROR(gl.glGetError(), ""); break; } default: DE_ASSERT(DE_FALSE); } // draw gl.glEnableVertexAttribArray(positionLoc); gl.glEnableVertexAttribArray(colorLoc); gl.glDrawArrays(GL_TRIANGLES, 0, 6*GRID_SIZE*GRID_SIZE); gl.glFinish(); gl.glBindVertexArray(0); gl.glUseProgram(0); GLU_EXPECT_NO_ERROR(gl.glGetError(), "clean"); glu::readPixels(m_context.getRenderContext(), 0, 0, dst.getAccess()); } void MixedApiCase::createBuffers (void) { const tcu::Vec4 green = tcu::Vec4(0.0f, 1.0f, 0.0f, 1.0f); const tcu::Vec4 yellow = tcu::Vec4(1.0f, 1.0f, 0.0f, 1.0f); const glw::Functions& gl = m_context.getRenderContext().getFunctions(); std::vector<tcu::Vec4> vertexData (12 * GRID_SIZE * GRID_SIZE); for (int y = 0; y < GRID_SIZE; ++y) for (int x = 0; x < GRID_SIZE; ++x) { const tcu::Vec4& color = ((x + y) % 2 == 0) ? (green) : (yellow); vertexData[(y * GRID_SIZE + x) * 12 + 0] = tcu::Vec4((x+0) / float(GRID_SIZE) * 2.0f - 1.0f, (y+0) / float(GRID_SIZE) * 2.0f - 1.0f, 0.0f, 1.0f); vertexData[(y * GRID_SIZE + x) * 12 + 1] = color; vertexData[(y * GRID_SIZE + x) * 12 + 2] = tcu::Vec4((x+0) / float(GRID_SIZE) * 2.0f - 1.0f, (y+1) / float(GRID_SIZE) * 2.0f - 1.0f, 0.0f, 1.0f); vertexData[(y * GRID_SIZE + x) * 12 + 3] = color; vertexData[(y * GRID_SIZE + x) * 12 + 4] = tcu::Vec4((x+1) / float(GRID_SIZE) * 2.0f - 1.0f, (y+1) / float(GRID_SIZE) * 2.0f - 1.0f, 0.0f, 1.0f); vertexData[(y * GRID_SIZE + x) * 12 + 5] = color; vertexData[(y * GRID_SIZE + x) * 12 + 6] = tcu::Vec4((x+0) / float(GRID_SIZE) * 2.0f - 1.0f, (y+0) / float(GRID_SIZE) * 2.0f - 1.0f, 0.0f, 1.0f); vertexData[(y * GRID_SIZE + x) * 12 + 7] = color; vertexData[(y * GRID_SIZE + x) * 12 + 8] = tcu::Vec4((x+1) / float(GRID_SIZE) * 2.0f - 1.0f, (y+1) / float(GRID_SIZE) * 2.0f - 1.0f, 0.0f, 1.0f); vertexData[(y * GRID_SIZE + x) * 12 + 9] = color; vertexData[(y * GRID_SIZE + x) * 12 + 10] = tcu::Vec4((x+1) / float(GRID_SIZE) * 2.0f - 1.0f, (y+0) / float(GRID_SIZE) * 2.0f - 1.0f, 0.0f, 1.0f); vertexData[(y * GRID_SIZE + x) * 12 + 11] = color; } // upload vertex data gl.genBuffers(1, &m_buffer); gl.bindBuffer(GL_ARRAY_BUFFER, m_buffer); gl.bufferData(GL_ARRAY_BUFFER, (int)(vertexData.size() * sizeof(tcu::Vec4)), vertexData[0].getPtr(), GL_STATIC_DRAW); GLU_EXPECT_NO_ERROR(gl.getError(), "upload data"); } void MixedApiCase::createShader (void) { m_program = new glu::ShaderProgram(m_context.getRenderContext(), glu::ProgramSources() << glu::VertexSource(s_positionColorShader) << glu::FragmentSource(s_colorFragmentShader)); m_testCtx.getLog() << *m_program; if (!m_program->isOk()) throw tcu::TestError("could not build shader"); } class DefaultVAOCase : public TestCase { public: enum CaseType { CASE_BIND_VERTEX_BUFFER, CASE_VERTEX_ATTRIB_FORMAT, CASE_VERTEX_ATTRIB_I_FORMAT, CASE_VERTEX_ATTRIB_BINDING, CASE_VERTEX_BINDING_DIVISOR, CASE_LAST }; DefaultVAOCase (Context& ctx, const char* name, const char* desc, CaseType caseType); ~DefaultVAOCase (void); IterateResult iterate (void); private: const CaseType m_caseType; }; DefaultVAOCase::DefaultVAOCase (Context& ctx, const char* name, const char* desc, CaseType caseType) : TestCase (ctx, name, desc) , m_caseType (caseType) { DE_ASSERT(caseType < CASE_LAST); } DefaultVAOCase::~DefaultVAOCase (void) { } DefaultVAOCase::IterateResult DefaultVAOCase::iterate (void) { glw::GLenum error = 0; glu::CallLogWrapper gl (m_context.getRenderContext().getFunctions(), m_context.getTestContext().getLog()); gl.enableLogging(true); switch (m_caseType) { case CASE_BIND_VERTEX_BUFFER: { glu::Buffer buffer(m_context.getRenderContext()); gl.glBindVertexBuffer(0, *buffer, 0, 0); break; } case CASE_VERTEX_ATTRIB_FORMAT: gl.glVertexAttribFormat(0, 4, GL_FLOAT, GL_FALSE, 0); break; case CASE_VERTEX_ATTRIB_I_FORMAT: gl.glVertexAttribIFormat(0, 4, GL_INT, 0); break; case CASE_VERTEX_ATTRIB_BINDING: gl.glVertexAttribBinding(0, 0); break; case CASE_VERTEX_BINDING_DIVISOR: gl.glVertexBindingDivisor(0, 1); break; default: DE_ASSERT(false); } error = gl.glGetError(); if (error != GL_INVALID_OPERATION) { m_testCtx.getLog() << tcu::TestLog::Message << "ERROR! Expected GL_INVALID_OPERATION, got " << glu::getErrorStr(error) << tcu::TestLog::EndMessage; m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Invalid error"); } else m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); return STOP; } class BindToCreateCase : public TestCase { public: BindToCreateCase (Context& ctx, const char* name, const char* desc); ~BindToCreateCase (void); IterateResult iterate (void); }; BindToCreateCase::BindToCreateCase (Context& ctx, const char* name, const char* desc) : TestCase(ctx, name, desc) { } BindToCreateCase::~BindToCreateCase (void) { } BindToCreateCase::IterateResult BindToCreateCase::iterate (void) { glw::GLuint buffer = 0; glw::GLenum error; glu::CallLogWrapper gl (m_context.getRenderContext().getFunctions(), m_context.getTestContext().getLog()); glu::VertexArray vao (m_context.getRenderContext()); gl.enableLogging(true); gl.glGenBuffers(1, &buffer); gl.glDeleteBuffers(1, &buffer); GLU_EXPECT_NO_ERROR(gl.glGetError(), ""); gl.glBindVertexArray(*vao); gl.glBindVertexBuffer(0, buffer, 0, 0); error = gl.glGetError(); if (error != GL_INVALID_OPERATION) { m_testCtx.getLog() << tcu::TestLog::Message << "ERROR! Expected GL_INVALID_OPERATION, got " << glu::getErrorStr(error) << tcu::TestLog::EndMessage; m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Invalid error"); } else m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); return STOP; } class NegativeApiCase : public TestCase { public: enum CaseType { CASE_LARGE_OFFSET, CASE_LARGE_STRIDE, CASE_NEGATIVE_STRIDE, CASE_NEGATIVE_OFFSET, CASE_INVALID_ATTR, CASE_INVALID_BINDING, CASE_LAST }; NegativeApiCase (Context& ctx, const char* name, const char* desc, CaseType caseType); ~NegativeApiCase (void); IterateResult iterate (void); private: const CaseType m_caseType; }; NegativeApiCase::NegativeApiCase (Context& ctx, const char* name, const char* desc, CaseType caseType) : TestCase (ctx, name, desc) , m_caseType (caseType) { } NegativeApiCase::~NegativeApiCase (void) { } NegativeApiCase::IterateResult NegativeApiCase::iterate (void) { glw::GLenum error; glu::CallLogWrapper gl (m_context.getRenderContext().getFunctions(), m_context.getTestContext().getLog()); glu::VertexArray vao (m_context.getRenderContext()); gl.enableLogging(true); gl.glBindVertexArray(*vao); switch (m_caseType) { case CASE_LARGE_OFFSET: { glw::GLint maxOffset = -1; glw::GLint largeOffset; gl.glGetIntegerv(GL_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET, &maxOffset); GLU_EXPECT_NO_ERROR(gl.glGetError(), ""); largeOffset = maxOffset + 1; // skip if maximum unsigned or signed values if (maxOffset == -1 || maxOffset == 0x7FFFFFFF) throw tcu::NotSupportedError("Implementation supports all offsets"); gl.glVertexAttribFormat(0, 4, GL_FLOAT, GL_FALSE, largeOffset); break; } case CASE_LARGE_STRIDE: { glu::Buffer buffer (m_context.getRenderContext()); glw::GLint maxStride = -1; glw::GLint largeStride; gl.glGetIntegerv(GL_MAX_VERTEX_ATTRIB_STRIDE, &maxStride); GLU_EXPECT_NO_ERROR(gl.glGetError(), ""); largeStride = maxStride + 1; // skip if maximum unsigned or signed values if (maxStride == -1 || maxStride == 0x7FFFFFFF) throw tcu::NotSupportedError("Implementation supports all strides"); gl.glBindVertexBuffer(0, *buffer, 0, largeStride); break; } case CASE_NEGATIVE_STRIDE: { glu::Buffer buffer(m_context.getRenderContext()); gl.glBindVertexBuffer(0, *buffer, 0, -20); break; } case CASE_NEGATIVE_OFFSET: { glu::Buffer buffer(m_context.getRenderContext()); gl.glBindVertexBuffer(0, *buffer, -20, 0); break; } case CASE_INVALID_ATTR: { glw::GLint maxIndex = -1; glw::GLint largeIndex; gl.glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &maxIndex); GLU_EXPECT_NO_ERROR(gl.glGetError(), ""); largeIndex = maxIndex + 1; // skip if maximum unsigned or signed values if (maxIndex == -1 || maxIndex == 0x7FFFFFFF) throw tcu::NotSupportedError("Implementation supports any attribute index"); gl.glVertexAttribBinding(largeIndex, 0); break; } case CASE_INVALID_BINDING: { glw::GLint maxBindings = -1; glw::GLint largeBinding; gl.glGetIntegerv(GL_MAX_VERTEX_ATTRIB_BINDINGS, &maxBindings); GLU_EXPECT_NO_ERROR(gl.glGetError(), ""); largeBinding = maxBindings + 1; // skip if maximum unsigned or signed values if (maxBindings == -1 || maxBindings == 0x7FFFFFFF) throw tcu::NotSupportedError("Implementation supports any binding"); gl.glVertexAttribBinding(0, largeBinding); break; } default: DE_ASSERT(false); } error = gl.glGetError(); if (error != GL_INVALID_VALUE) { m_testCtx.getLog() << tcu::TestLog::Message << "ERROR! Expected GL_INVALID_VALUE, got " << glu::getErrorStr(error) << tcu::TestLog::EndMessage; m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Invalid error"); } else m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); return STOP; } } // anonymous VertexAttributeBindingTests::VertexAttributeBindingTests (Context& context) : TestCaseGroup(context, "vertex_attribute_binding", "Test vertex attribute binding") { } VertexAttributeBindingTests::~VertexAttributeBindingTests (void) { } void VertexAttributeBindingTests::init (void) { tcu::TestCaseGroup* const usageGroup = new tcu::TestCaseGroup(m_testCtx, "usage", "Test using binding points"); tcu::TestCaseGroup* const negativeGroup = new tcu::TestCaseGroup(m_testCtx, "negative", "Negative test"); addChild(usageGroup); addChild(negativeGroup); // .usage { tcu::TestCaseGroup* const singleGroup = new tcu::TestCaseGroup(m_testCtx, "single_binding", "Test using single binding point"); tcu::TestCaseGroup* const multipleGroup = new tcu::TestCaseGroup(m_testCtx, "multiple_bindings", "Test using multiple binding points"); tcu::TestCaseGroup* const mixedGroup = new tcu::TestCaseGroup(m_testCtx, "mixed_usage", "Test using binding point and non binding point api variants"); usageGroup->addChild(singleGroup); usageGroup->addChild(multipleGroup); usageGroup->addChild(mixedGroup); // single binding singleGroup->addChild(new SingleBindingCase(m_context, "elements_1", 0)); singleGroup->addChild(new SingleBindingCase(m_context, "elements_2", SingleBindingCase::FLAG_ATTRIBS_MULTIPLE_ELEMS)); singleGroup->addChild(new SingleBindingCase(m_context, "elements_2_share_elements", SingleBindingCase::FLAG_ATTRIBS_SHARED_ELEMS)); singleGroup->addChild(new SingleBindingCase(m_context, "offset_elements_1", SingleBindingCase::FLAG_BUF_ALIGNED_OFFSET | 0)); singleGroup->addChild(new SingleBindingCase(m_context, "offset_elements_2", SingleBindingCase::FLAG_BUF_ALIGNED_OFFSET | SingleBindingCase::FLAG_ATTRIBS_MULTIPLE_ELEMS)); singleGroup->addChild(new SingleBindingCase(m_context, "offset_elements_2_share_elements", SingleBindingCase::FLAG_BUF_ALIGNED_OFFSET | SingleBindingCase::FLAG_ATTRIBS_SHARED_ELEMS)); singleGroup->addChild(new SingleBindingCase(m_context, "unaligned_offset_elements_1_aligned_elements", SingleBindingCase::FLAG_BUF_UNALIGNED_OFFSET | SingleBindingCase::FLAG_ATTRIB_ALIGNED)); // !< total offset is aligned // multiple bindings multipleGroup->addChild(new MultipleBindingCase(m_context, "basic", 0)); multipleGroup->addChild(new MultipleBindingCase(m_context, "zero_stride", MultipleBindingCase::FLAG_ZERO_STRIDE)); multipleGroup->addChild(new MultipleBindingCase(m_context, "instanced", MultipleBindingCase::FLAG_INSTANCED)); multipleGroup->addChild(new MultipleBindingCase(m_context, "aliasing_buffer_zero_stride", MultipleBindingCase::FLAG_ALIASING_BUFFERS | MultipleBindingCase::FLAG_ZERO_STRIDE)); multipleGroup->addChild(new MultipleBindingCase(m_context, "aliasing_buffer_instanced", MultipleBindingCase::FLAG_ALIASING_BUFFERS | MultipleBindingCase::FLAG_INSTANCED)); // mixed cases mixedGroup->addChild(new MixedBindingCase(m_context, "mixed_attribs_basic", "Use different api for different attributes", MixedBindingCase::CASE_BASIC)); mixedGroup->addChild(new MixedBindingCase(m_context, "mixed_attribs_instanced_binding", "Use different api for different attributes", MixedBindingCase::CASE_INSTANCED_BINDING)); mixedGroup->addChild(new MixedBindingCase(m_context, "mixed_attribs_instanced_attrib", "Use different api for different attributes", MixedBindingCase::CASE_INSTANCED_ATTRIB)); mixedGroup->addChild(new MixedApiCase(m_context, "mixed_api_change_buffer", "change buffer with vertex_attrib_binding api", MixedApiCase::CASE_CHANGE_BUFFER)); mixedGroup->addChild(new MixedApiCase(m_context, "mixed_api_change_buffer_offset", "change buffer offset with vertex_attrib_binding api", MixedApiCase::CASE_CHANGE_BUFFER_OFFSET)); mixedGroup->addChild(new MixedApiCase(m_context, "mixed_api_change_buffer_stride", "change buffer stride with vertex_attrib_binding api", MixedApiCase::CASE_CHANGE_BUFFER_STRIDE)); mixedGroup->addChild(new MixedApiCase(m_context, "mixed_api_change_binding_point", "change binding point with vertex_attrib_binding api", MixedApiCase::CASE_CHANGE_BINDING_POINT)); } // negative { negativeGroup->addChild(new DefaultVAOCase(m_context, "default_vao_bind_vertex_buffer", "use with default vao", DefaultVAOCase::CASE_BIND_VERTEX_BUFFER)); negativeGroup->addChild(new DefaultVAOCase(m_context, "default_vao_vertex_attrib_format", "use with default vao", DefaultVAOCase::CASE_VERTEX_ATTRIB_FORMAT)); negativeGroup->addChild(new DefaultVAOCase(m_context, "default_vao_vertex_attrib_i_format", "use with default vao", DefaultVAOCase::CASE_VERTEX_ATTRIB_I_FORMAT)); negativeGroup->addChild(new DefaultVAOCase(m_context, "default_vao_vertex_attrib_binding", "use with default vao", DefaultVAOCase::CASE_VERTEX_ATTRIB_BINDING)); negativeGroup->addChild(new DefaultVAOCase(m_context, "default_vao_vertex_binding_divisor", "use with default vao", DefaultVAOCase::CASE_VERTEX_BINDING_DIVISOR)); negativeGroup->addChild(new BindToCreateCase(m_context, "bind_create_new_buffer", "bind not existing buffer")); negativeGroup->addChild(new NegativeApiCase(m_context, "vertex_attrib_format_large_offset", "large relative offset", NegativeApiCase::CASE_LARGE_OFFSET)); negativeGroup->addChild(new NegativeApiCase(m_context, "bind_vertex_buffer_large_stride", "large stride", NegativeApiCase::CASE_LARGE_STRIDE)); negativeGroup->addChild(new NegativeApiCase(m_context, "bind_vertex_buffer_negative_stride", "negative stride", NegativeApiCase::CASE_NEGATIVE_STRIDE)); negativeGroup->addChild(new NegativeApiCase(m_context, "bind_vertex_buffer_negative_offset", "negative offset", NegativeApiCase::CASE_NEGATIVE_OFFSET)); negativeGroup->addChild(new NegativeApiCase(m_context, "vertex_attrib_binding_invalid_attr", "bind invalid attr", NegativeApiCase::CASE_INVALID_ATTR)); negativeGroup->addChild(new NegativeApiCase(m_context, "vertex_attrib_binding_invalid_binding", "bind invalid binding", NegativeApiCase::CASE_INVALID_BINDING)); } } } // Functional } // gles31 } // deqp
34.043293
245
0.698913
omegaphora
29314c05f43ced8bb37ef5c5e05c2e3be6232407
13,126
hpp
C++
include/thread_pool.hpp
diharaw/dwThreadPool
cc21bf479f305897cd7e41ffc5c8968abb05455e
[ "MIT" ]
25
2017-01-25T05:57:24.000Z
2021-11-21T18:29:27.000Z
include/thread_pool.hpp
diharaw/dwThreadPool
cc21bf479f305897cd7e41ffc5c8968abb05455e
[ "MIT" ]
null
null
null
include/thread_pool.hpp
diharaw/dwThreadPool
cc21bf479f305897cd7e41ffc5c8968abb05455e
[ "MIT" ]
5
2017-05-02T22:32:40.000Z
2021-09-21T19:42:59.000Z
#pragma once #include <functional> #include <thread> #include <vector> #include <atomic> #include <algorithm> #include <condition_variable> #define MAX_TASKS 1024u #define MAX_DEPENDENCIES 16u #define MAX_CONTINUATIONS 16u #define MASK MAX_TASKS - 1u #define TASK_SIZE_BYTES 128 namespace dw { // ----------------------------------------------------------------------------------------------------------------------------------- class Semaphore { public: Semaphore() : m_signal(false) {} inline void notify() { std::unique_lock<std::mutex> lock(m_mutex); m_signal = true; m_condition.notify_all(); } inline void wait() { std::unique_lock<std::mutex> lock(m_mutex); m_condition.wait(lock, [&] { return m_signal; }); m_signal = false; } private: Semaphore(const Semaphore &); Semaphore & operator = (const Semaphore &); std::mutex m_mutex; std::condition_variable m_condition; bool m_signal; }; // ----------------------------------------------------------------------------------------------------------------------------------- struct Task { std::function<void(void*)> function; char data[TASK_SIZE_BYTES]; std::atomic<uint16_t> num_pending; uint16_t num_continuations; uint16_t num_dependencies; Task* dependencies[MAX_DEPENDENCIES]; Task* continuations[MAX_CONTINUATIONS]; }; // ----------------------------------------------------------------------------------------------------------------------------------- template <typename T> inline T* task_data(Task* task) { return (T*)(&task->data[0]); } // ----------------------------------------------------------------------------------------------------------------------------------- struct WorkQueue { std::mutex m_critical_section; Task m_task_pool[MAX_TASKS]; Task* m_task_queue[MAX_TASKS]; uint32_t m_front; uint32_t m_back; uint32_t m_num_tasks; std::atomic<uint32_t> m_num_pending_tasks; // ----------------------------------------------------------------------------------------------------------------------------------- WorkQueue() { m_num_tasks = 0; m_num_pending_tasks = 0; m_front = 0; m_back = 0; } // ----------------------------------------------------------------------------------------------------------------------------------- ~WorkQueue() {} // ----------------------------------------------------------------------------------------------------------------------------------- Task* allocate() { uint32_t task_index = m_num_tasks++; return &m_task_pool[task_index & (MAX_TASKS - 1u)]; } // ----------------------------------------------------------------------------------------------------------------------------------- void push(Task* task) { std::lock_guard<std::mutex> lock(m_critical_section); m_task_queue[m_back & MASK] = task; ++m_back; m_num_pending_tasks++; } // ----------------------------------------------------------------------------------------------------------------------------------- Task* pop() { std::lock_guard<std::mutex> lock(m_critical_section); const uint32_t job_count = m_back - m_front; if (job_count <= 0) return nullptr; --m_back; return m_task_queue[m_back & MASK]; } // ----------------------------------------------------------------------------------------------------------------------------------- bool has_pending_tasks() { return (m_num_pending_tasks != 0); } // ----------------------------------------------------------------------------------------------------------------------------------- bool empty() { return (m_front == 0 && m_back == 0); } }; // ----------------------------------------------------------------------------------------------------------------------------------- struct WorkerThread { Semaphore m_wakeup; Semaphore m_done; std::thread m_thread; // ----------------------------------------------------------------------------------------------------------------------------------- WorkerThread() {} // ----------------------------------------------------------------------------------------------------------------------------------- WorkerThread(const WorkerThread &) {} // ----------------------------------------------------------------------------------------------------------------------------------- ~WorkerThread() { wakeup(); m_thread.join(); } // ----------------------------------------------------------------------------------------------------------------------------------- void wakeup() { m_wakeup.notify(); } }; // ----------------------------------------------------------------------------------------------------------------------------------- class ThreadPool { public: // ----------------------------------------------------------------------------------------------------------------------------------- ThreadPool() { m_shutdown = false; // get number of logical threads on CPU m_num_logical_threads = std::thread::hardware_concurrency(); m_num_worker_threads = m_num_logical_threads; initialize_workers(); } // ----------------------------------------------------------------------------------------------------------------------------------- ThreadPool(uint32_t workers) { m_shutdown = false; // get number of logical threads on CPU m_num_logical_threads = std::thread::hardware_concurrency(); m_num_worker_threads = std::min(workers, m_num_logical_threads); initialize_workers(); } // ----------------------------------------------------------------------------------------------------------------------------------- ~ThreadPool() { m_shutdown = true; m_worker_threads.clear(); } // ----------------------------------------------------------------------------------------------------------------------------------- inline Task* allocate() { Task* task_ptr = m_queue.allocate(); task_ptr->num_pending = 1; task_ptr->num_continuations = 0; task_ptr->num_dependencies = 0; return task_ptr; } // ----------------------------------------------------------------------------------------------------------------------------------- inline void define_dependency(Task* child, Task* parent) { if (parent && child) child->dependencies[child->num_dependencies++] = parent; } // ----------------------------------------------------------------------------------------------------------------------------------- inline void define_continuation(Task* parent, Task* continuation) { if (parent && continuation) { if (parent->num_continuations < MAX_CONTINUATIONS) { parent->continuations[parent->num_continuations] = continuation; parent->num_continuations++; } } } // ----------------------------------------------------------------------------------------------------------------------------------- inline void enqueue(Task* task) { if (task) { m_queue.push(task); for(uint32_t i = 0; i < m_num_worker_threads; i++) { WorkerThread& thread = m_worker_threads[i]; thread.wakeup(); } } } // ----------------------------------------------------------------------------------------------------------------------------------- inline bool is_done(Task* task) { return task->num_pending == 0; } // ----------------------------------------------------------------------------------------------------------------------------------- inline void wait_for_all() { while (m_queue.has_pending_tasks()) { Task* task = m_queue.pop(); if (task) run_task(task); } } // ----------------------------------------------------------------------------------------------------------------------------------- inline void wait_for_one(Task* pending_task) { while (pending_task->num_pending > 0) { Task* task = m_queue.pop(); if (task) run_task(task); } } // ----------------------------------------------------------------------------------------------------------------------------------- inline uint32_t num_logical_threads() { return m_num_logical_threads; } // ----------------------------------------------------------------------------------------------------------------------------------- inline uint32_t num_worker_threads() { return m_num_worker_threads; } // ----------------------------------------------------------------------------------------------------------------------------------- private: // ----------------------------------------------------------------------------------------------------------------------------------- inline void initialize_workers() { // spawn worker threads m_worker_threads.resize(m_num_worker_threads); for (uint32_t i = 0; i < m_num_worker_threads; i++) m_worker_threads[i].m_thread = std::thread(&ThreadPool::worker, this, i); } // ----------------------------------------------------------------------------------------------------------------------------------- inline void worker(uint32_t index) { WorkerThread& worker_thread = m_worker_threads[index]; while (!m_shutdown) { Task* task = m_queue.pop(); if (!task) { worker_thread.m_done.notify(); worker_thread.m_wakeup.wait(); } else run_task(task); } } // ----------------------------------------------------------------------------------------------------------------------------------- inline void run_task(Task* task) { // Wait untill all of dependent tasks are done wait_for_dependencies(task); // Execute the current task task->function(task->data); // Submit continuation tasks. for (uint32_t i = 0; i < task->num_continuations; i++) enqueue(task->continuations[i]); if (task->num_pending > 0) task->num_pending--; if (m_queue.m_num_pending_tasks > 0) m_queue.m_num_pending_tasks--; } // ----------------------------------------------------------------------------------------------------------------------------------- inline void wait_for_dependencies(Task* task) { if (task->num_dependencies > 0) { for (uint32_t i = 0; i < task->num_dependencies; i++) { while (task->dependencies[i]->num_pending > 0) { Task* wait_task = m_queue.pop(); if (wait_task) run_task(wait_task); } } } } // ----------------------------------------------------------------------------------------------------------------------------------- private: bool m_shutdown; uint32_t m_num_logical_threads; WorkQueue m_queue; std::vector<WorkerThread> m_worker_threads; uint32_t m_num_worker_threads; }; } // namespace dw
32.897243
135
0.30192
diharaw
29340a3806fd99227c1b736d933ca66be931a0de
4,428
cc
C++
pw_rpc/nanopb/method_lookup_test.cc
ffzwadd/pigweed
75e038f0d852b310d135b93061bc769cb8bf90c4
[ "Apache-2.0" ]
null
null
null
pw_rpc/nanopb/method_lookup_test.cc
ffzwadd/pigweed
75e038f0d852b310d135b93061bc769cb8bf90c4
[ "Apache-2.0" ]
null
null
null
pw_rpc/nanopb/method_lookup_test.cc
ffzwadd/pigweed
75e038f0d852b310d135b93061bc769cb8bf90c4
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 The Pigweed Authors // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // https://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 "gtest/gtest.h" #include "pw_rpc/nanopb/test_method_context.h" #include "pw_rpc/raw/test_method_context.h" #include "pw_rpc_test_protos/test.rpc.pb.h" namespace pw::rpc { namespace { class MixedService1 : public test::generated::TestService<MixedService1> { public: StatusWithSize TestUnaryRpc(ServerContext&, ConstByteSpan, ByteSpan) { return StatusWithSize(123); } void TestServerStreamRpc(ServerContext&, const pw_rpc_test_TestRequest&, ServerWriter<pw_rpc_test_TestStreamResponse>&) { called_server_streaming_method = true; } void TestClientStreamRpc(ServerContext&, RawServerReader&) { called_client_streaming_method = true; } void TestBidirectionalStreamRpc( ServerContext&, ServerReaderWriter<pw_rpc_test_TestRequest, pw_rpc_test_TestStreamResponse>&) { called_bidirectional_streaming_method = true; } bool called_server_streaming_method = false; bool called_client_streaming_method = false; bool called_bidirectional_streaming_method = false; }; class MixedService2 : public test::generated::TestService<MixedService2> { public: Status TestUnaryRpc(ServerContext&, const pw_rpc_test_TestRequest&, pw_rpc_test_TestResponse&) { return Status::Unauthenticated(); } void TestServerStreamRpc(ServerContext&, ConstByteSpan, RawServerWriter&) { called_server_streaming_method = true; } void TestClientStreamRpc( ServerContext&, ServerReader<pw_rpc_test_TestRequest, pw_rpc_test_TestStreamResponse>&) { called_client_streaming_method = true; } void TestBidirectionalStreamRpc(ServerContext&, RawServerReaderWriter&) { called_bidirectional_streaming_method = true; } bool called_server_streaming_method = false; bool called_client_streaming_method = false; bool called_bidirectional_streaming_method = false; }; TEST(MixedService1, CallRawMethod_Unary) { PW_RAW_TEST_METHOD_CONTEXT(MixedService1, TestUnaryRpc) context; StatusWithSize sws = context.call({}); EXPECT_TRUE(sws.ok()); EXPECT_EQ(123u, sws.size()); } TEST(MixedService1, CallNanopbMethod_ServerStreaming) { PW_NANOPB_TEST_METHOD_CONTEXT(MixedService1, TestServerStreamRpc) context; ASSERT_FALSE(context.service().called_server_streaming_method); context.call({}); EXPECT_TRUE(context.service().called_server_streaming_method); } TEST(MixedService1, CallRawMethod_ClientStreaming) { PW_RAW_TEST_METHOD_CONTEXT(MixedService1, TestClientStreamRpc) context; ASSERT_FALSE(context.service().called_client_streaming_method); context.call(); EXPECT_TRUE(context.service().called_client_streaming_method); } TEST(MixedService1, CallNanopbMethod_BidirectionalStreaming) { // TODO(pwbug/428): Test Nanopb bidirectional streaming when supported. } TEST(MixedService2, CallNanopbMethod_Unary) { PW_NANOPB_TEST_METHOD_CONTEXT(MixedService2, TestUnaryRpc) context; Status status = context.call({}); EXPECT_EQ(Status::Unauthenticated(), status); } TEST(MixedService2, CallRawMethod_ServerStreaming) { PW_RAW_TEST_METHOD_CONTEXT(MixedService2, TestServerStreamRpc) context; ASSERT_FALSE(context.service().called_server_streaming_method); context.call({}); EXPECT_TRUE(context.service().called_server_streaming_method); } TEST(MixedService2, CallNanopbMethod_ClientStreaming) { // TODO(pwbug/428): Test Nanopb client streaming when supported. } TEST(MixedService2, CallRawMethod_BidirectionalStreaming) { PW_RAW_TEST_METHOD_CONTEXT(MixedService2, TestBidirectionalStreamRpc) context; ASSERT_FALSE(context.service().called_bidirectional_streaming_method); context.call(); EXPECT_TRUE(context.service().called_bidirectional_streaming_method); } } // namespace } // namespace pw::rpc
34.325581
80
0.769874
ffzwadd
a09599afe4816fdb13c6ccd94d5cc5f7c097eb16
3,229
cpp
C++
example/decomp/main.cpp
pdobrowo/libcs2
25d8bfeadcf3eff6be34caa85000a00e41b3b57e
[ "MIT" ]
null
null
null
example/decomp/main.cpp
pdobrowo/libcs2
25d8bfeadcf3eff6be34caa85000a00e41b3b57e
[ "MIT" ]
null
null
null
example/decomp/main.cpp
pdobrowo/libcs2
25d8bfeadcf3eff6be34caa85000a00e41b3b57e
[ "MIT" ]
null
null
null
/** * Copyright (c) 2015-2019 Przemysław Dobrowolski * * This file is part of the Configuration Space Library (libcs2), a library * for creating configuration spaces of various motion planning problems. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "../../plugin/decomp/decomp3f.h" #include "cs2/plugin.h" #include "cs2/timer.h" #include <cstdio> #include <cstdlib> void load_mesh(struct decompmesh3f_s *m, const char *fp) { int vs, fs, i, j; FILE *f = fopen(fp, "r"); if (!f) return; if (fscanf(f, "%*s%d%d%*d",&vs,&fs) != 2) return; m->v = (struct cs2_vec3f_s *)malloc(sizeof(struct cs2_vec3f_s) * vs); m->vs = vs; for (i = 0; i < vs; ++i) if (fscanf(f, "%lf%lf%lf", &m->v[i].x, &m->v[i].y, &m->v[i].z) != 3) return; m->f = (struct decompface3f_s *)malloc(sizeof(struct decompface3f_s) * fs); m->fs = fs; for (i = 0; i < fs; ++i) { int is; if (fscanf(f, "%d", &is) != 1) return; m->f[i].i = (size_t *)malloc(sizeof(size_t) * is); m->f[i].is = is; for (j = 0; j < is; ++j) { double x; if (fscanf(f, "%lf", &x) != 1) return; m->f[i].i[j] = x; } } fclose(f); } int main() { // decomp cs2_plugin_ldpath("."); void *pl = cs2_plugin_load("libdecomp.so"); if (!pl) { printf("missing plugin\n"); return 1; } decomp3f_init_f pl_init = (decomp3f_init_f)cs2_plugin_func(pl, DECOMP3F_INIT_F_SYM); decomp3f_make_f pl_make = (decomp3f_make_f)cs2_plugin_func(pl, DECOMP3F_MAKE_F_SYM); decomp3f_clear_f pl_clear = (decomp3f_clear_f)cs2_plugin_func(pl, DECOMP3F_CLEAR_F_SYM); struct decomp3f_s d; struct decompmesh3f_s dm; load_mesh(&dm, "../data/mushroom.off"); pl_init(&d); uint64_t start = cs2_timer_usec(); pl_make(&d, &dm); uint64_t end = cs2_timer_usec(); printf("decomposition took %lu usecs; sub-meshes: %d\n", static_cast<unsigned long>(end - start), static_cast<int>(d.ms)); pl_clear(&d); cs2_plugin_unload(pl); free(dm.f); free(dm.v); return 0; }
27.598291
126
0.631155
pdobrowo
a09719e6e27cd69a7d37181d29ea9ed037e9205f
2,866
cpp
C++
src/scan.cpp
Licmeth/pixiple
1871124ef2d9d2384cb384095f14d71c5664f62b
[ "MIT" ]
50
2019-01-24T16:23:05.000Z
2021-12-29T17:38:07.000Z
src/scan.cpp
Licmeth/pixiple
1871124ef2d9d2384cb384095f14d71c5664f62b
[ "MIT" ]
5
2016-12-26T16:54:38.000Z
2018-09-28T23:59:26.000Z
src/scan.cpp
Licmeth/pixiple
1871124ef2d9d2384cb384095f14d71c5664f62b
[ "MIT" ]
13
2019-08-03T07:41:02.000Z
2022-03-10T05:59:40.000Z
#include "shared.h" #include "image.h" #include "window.h" #include "shared/com.h" #include <filesystem> #include <string> #include <vector> #include <ShlObj.h> static bool is_image(const std::wstring& filename) { const std::wstring extensions[] { L".jpg", L".jpe", L".jpeg", L".png", L".gif", L".bmp" L".tif", L".tiff", L".jxr", L".hdp", L".wdp"}; for (const auto& e : extensions) { if (filename.length() >= e.length()) { auto filename_e = filename.substr(filename.length() - e.length(), e.length()); if (_wcsicmp(filename_e.c_str(), e.c_str()) == 0) return true; } } return false; } std::vector<std::filesystem::path> scan(Window& window, const std::vector<ComPtr<IShellItem>>& shell_items) { window.add_edge(0); window.add_edge(0); window.add_edge(1); window.add_edge(1); window.add_edge(0.5f); window.add_edge(); window.add_edge(); window.add_edge(); const auto mx = 12.0f; const auto my = 8.0f; const auto margin = D2D1::RectF(mx, my, mx, my); const auto background = Colour{0xfff8f8f8}; window.add_pane(0, 5, 2, 4, margin, false, true, background); window.set_progressbar_progress(0, -1.0f); window.add_pane(0, 4, 2, 6, margin, false, true, background); window.set_text(1, L"Scanning folders for images", {}, true); window.add_pane(0, 6, 2, 7, margin, false, true, background); window.add_button(2, 0, L"Cancel"); window.add_pane(0, 1, 2, 5, margin, false, false, background); window.add_pane(0, 7, 2, 3, margin, false, false, background); std::vector<std::filesystem::path> paths; auto items = shell_items; while (!items.empty()) { auto item = items.back(); items.pop_back(); SFGAOF a; er = item->GetAttributes( SFGAO_HIDDEN | SFGAO_FILESYSANCESTOR | SFGAO_FOLDER | SFGAO_FILESYSTEM, &a); // skip if not file or folder or if hidden if (!(a & SFGAO_FILESYSTEM || a & SFGAO_FILESYSANCESTOR) || a & SFGAO_HIDDEN) continue; if (a & SFGAO_FOLDER) { // folder ComPtr<IEnumShellItems> item_enum; er = item->BindToHandler(nullptr, BHID_EnumItems, IID_PPV_ARGS(&item_enum)); ComPtr<IShellItem> i; while (item_enum->Next(1, &i, nullptr) == S_OK) items.push_back(i); } else { // file LPWSTR path; er = item->GetDisplayName(SIGDN_FILESYSPATH, &path); if (is_image(path)) paths.push_back(path); CoTaskMemFree(path); } while (window.has_event()) { auto e = window.get_event(); if (e.type == Event::Type::quit || e.type == Event::Type::button) return {}; } } window.set_text(1, L"Removing duplicate paths", {}, true); window.has_event(); std::sort(paths.begin(), paths.end()); paths.erase(std::unique(paths.begin(), paths.end()), paths.end()); window.set_text(1, L"", {}, true); window.has_event(); return paths; }
27.037736
110
0.634682
Licmeth
a097b30738eabcde75b2e3ca52a2a82f1a19db38
4,051
hpp
C++
Contrib-Intel/RSD-PSME-RMM/common/agent-framework/include/agent-framework/module/requests/psme/attach.hpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
5
2019-11-11T07:57:26.000Z
2022-03-28T08:26:53.000Z
Contrib-Intel/RSD-PSME-RMM/common/agent-framework/include/agent-framework/module/requests/psme/attach.hpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
3
2019-09-05T21:47:07.000Z
2019-09-17T18:10:45.000Z
Contrib-Intel/RSD-PSME-RMM/common/agent-framework/include/agent-framework/module/requests/psme/attach.hpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
11
2019-07-20T00:16:32.000Z
2022-01-11T14:17:48.000Z
/*! * @copyright * Copyright (c) 2017-2019 Intel Corporation * * @copyright * 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 * * @copyright * http://www.apache.org/licenses/LICENSE-2.0 * * @copyright * 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. * * * @file command/psme/attach.hpp * @brief Generic PSME Attach command * */ #pragma once #include "agent-framework/module/constants/psme.hpp" #include "agent-framework/module/constants/command.hpp" #include "agent-framework/validators/procedure_validator.hpp" #include "agent-framework/module/model/attributes/array.hpp" namespace agent_framework { namespace model { namespace requests { /*! Attach request */ class Attach { public: explicit Attach(); using Capabilities = attribute::Array<std::string>; /*! * @brief Get command name * @return Command name * */ static std::string get_command() { return literals::Command::ATTACH; } /*! * @brief Get agent identifier from request * @return agent identifier * */ const std::string& get_gami_id() const { return m_gami_id; } /*! * @brief Get agent version from request * @return agent version * */ const std::string& get_version() const { return m_version; } /*! * @brief Get agent`s RPC Server IPv4 address from request * @return IPv4 address * */ const std::string& get_ipv4_address() const { return m_ipv4_address; } /*! * @brief Get agent`s RPC Server TCP port from request * @return access port * */ int get_port() const { return m_port; } /*! * @brief Get agent vendor from request * @return agent vendor * */ const std::string& get_vendor() const { return m_vendor; } /*! * @brief Get agent capabilities from request * @return agent capabilities */ const Capabilities& get_capabilities() const { return m_capabilities; } /*! * @brief Check is request is valid * @return On successed true is returned, otherwise false */ bool is_valid() const { if (m_gami_id.empty() || m_capabilities.size() <= 0 || m_ipv4_address.empty() || m_version.empty() || m_vendor.empty() || m_port <= 0) { return false; } return true; } /*! * @brief Transform request to Json * @return created Json value */ json::Json to_json() const; /*! * @brief create Attach form Json * @param[in] json the input argument * @return new Attach */ static Attach from_json(const json::Json& json); /*! * @brief Returns procedure scheme * @return Procedure scheme */ static const jsonrpc::ProcedureValidator& get_procedure() { static const jsonrpc::ProcedureValidator procedure{ get_command(), jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, literals::Attach::GAMI_ID, jsonrpc::JSON_STRING, literals::Attach::VERSION, jsonrpc::JSON_STRING, literals::Attach::VENDOR, jsonrpc::JSON_STRING, literals::Attach::IPV4_ADDRESS, jsonrpc::JSON_STRING, literals::Attach::PORT, jsonrpc::JSON_INTEGER, literals::Attach::CAPABILITIES, jsonrpc::JSON_ARRAY, nullptr}; return procedure; } private: std::string m_gami_id{}; std::string m_version{}; std::string m_vendor{}; std::string m_ipv4_address{}; int m_port{}; Capabilities m_capabilities{}; }; } } }
25.802548
75
0.620834
opencomputeproject
a09c5e5ab17b7915eb06d1deb8d64f65d0b08380
937
cpp
C++
examples/reverse/example-reverse-hessian-derivatives-using-eigen.cpp
jargonzombies/autodiff
2309fe03528f44ce58a44b0c388527b7d3c3aeef
[ "MIT" ]
991
2018-08-12T11:59:15.000Z
2022-03-28T22:27:59.000Z
examples/reverse/example-reverse-hessian-derivatives-using-eigen.cpp
jargonzombies/autodiff
2309fe03528f44ce58a44b0c388527b7d3c3aeef
[ "MIT" ]
166
2019-01-16T16:31:31.000Z
2022-03-30T04:18:13.000Z
examples/reverse/example-reverse-hessian-derivatives-using-eigen.cpp
jargonzombies/autodiff
2309fe03528f44ce58a44b0c388527b7d3c3aeef
[ "MIT" ]
123
2019-01-20T21:40:46.000Z
2022-03-23T16:07:50.000Z
// C++ includes #include <iostream> using namespace std; // autodiff include #include <autodiff/reverse/var.hpp> #include <autodiff/reverse/var/eigen.hpp> using namespace autodiff; // The scalar function for which the gradient is needed var f(const ArrayXvar& x) { return sqrt((x * x).sum()); // sqrt(sum([xi * xi for i = 1:5])) } int main() { VectorXvar x(5); // the input vector x with 5 variables x << 1, 2, 3, 4, 5; // x = [1, 2, 3, 4, 5] var u = f(x); // the output variable u Eigen::VectorXd g; // the gradient vector to be computed in method `hessian` Eigen::MatrixXd H = hessian(u, x, g); // evaluate the Hessian matrix H and the gradient vector g of u cout << "u = " << u << endl; // print the evaluated output variable u cout << "g = \n" << g << endl; // print the evaluated gradient vector of u cout << "H = \n" << H << endl; // print the evaluated Hessian matrix of u }
31.233333
106
0.618997
jargonzombies
a09e6a684f171a522b6ef7ff7a937818c93e8a0c
2,524
cpp
C++
libs/SysmelCompiler/Environment/Fraction.cpp
ronsaldo/sysmel-beta
14237d780527c6ca1bb34f74195838f78f0c6acc
[ "MIT" ]
2
2021-10-30T15:31:43.000Z
2021-11-08T09:45:15.000Z
libs/SysmelCompiler/Environment/Fraction.cpp
ronsaldo/sysmel-beta
14237d780527c6ca1bb34f74195838f78f0c6acc
[ "MIT" ]
null
null
null
libs/SysmelCompiler/Environment/Fraction.cpp
ronsaldo/sysmel-beta
14237d780527c6ca1bb34f74195838f78f0c6acc
[ "MIT" ]
null
null
null
#include "Environment/Fraction.hpp" #include "Environment/DivisionByZeroError.hpp" #include "Environment/Assert.hpp" namespace Sysmel { namespace Environment { Fraction Fraction::reduced() const { if(numerator.isZero()) return Fraction{LargeInteger{0}, LargeInteger{1}}; auto gcd = LargeInteger::gcd(numerator, denominator); auto result = Fraction{numerator / gcd, denominator / gcd}; result.numerator.signBit = result.numerator.signBit ^ result.denominator.signBit; result.denominator.signBit = false; sysmelAssert(result.numerator.isNormalized()); sysmelAssert(result.denominator.isNormalized()); return result; } Fraction Fraction::operator-() const { return Fraction{-numerator, denominator}; } Fraction Fraction::operator+(const Fraction &other) const { return Fraction{numerator * other.denominator + denominator*other.numerator, denominator * other.denominator}.reduced(); } Fraction Fraction::operator-(const Fraction &other) const { return Fraction{numerator * other.denominator - denominator*other.numerator, denominator * other.denominator}.reduced(); } Fraction Fraction::operator*(const Fraction &other) const { return Fraction{numerator * other.numerator, denominator * other.denominator}.reduced(); } Fraction Fraction::operator/(const Fraction &other) const { if(other.numerator.isZero()) signalNew<DivisionByZeroError> (); return Fraction{numerator * other.denominator, denominator * other.numerator}.reduced(); } bool Fraction::operator==(const Fraction &other) const { return numerator*other.denominator == denominator*other.numerator; } bool Fraction::operator!=(const Fraction &other) const { return numerator*other.denominator != denominator*other.numerator; } bool Fraction::operator<(const Fraction &other) const { return numerator*other.denominator < denominator*other.numerator; } bool Fraction::operator<=(const Fraction &other) const { return numerator*other.denominator <= denominator*other.numerator; } bool Fraction::operator>(const Fraction &other) const { return numerator*other.denominator > denominator*other.numerator; } bool Fraction::operator>=(const Fraction &other) const { return numerator*other.denominator >= denominator*other.numerator; } double Fraction::asDouble() const { return numerator.asDouble() / denominator.asDouble(); } float Fraction::asFloat() const { return float(asDouble()); } } // End of namespace Environment } // End of namespace Sysmel
27.434783
124
0.745642
ronsaldo
a0a146e2ea796883df57f49876eed2eb8fc153e3
480
cpp
C++
CS Academy/CS Academy - Travel Distance.cpp
akash246/Competitive-Programming-Solutions
68db69ba8a771a433e5338bc4e837a02d3f89823
[ "MIT" ]
28
2017-11-08T11:52:11.000Z
2021-07-16T06:30:02.000Z
CS Academy/CS Academy - Travel Distance.cpp
akash246/Competitive-Programming-Solutions
68db69ba8a771a433e5338bc4e837a02d3f89823
[ "MIT" ]
null
null
null
CS Academy/CS Academy - Travel Distance.cpp
akash246/Competitive-Programming-Solutions
68db69ba8a771a433e5338bc4e837a02d3f89823
[ "MIT" ]
30
2017-09-01T09:14:27.000Z
2021-04-12T12:08:56.000Z
#include <iostream> #include <string> using namespace std; int ABS(int n){ return n < 0 ? -1*n : n; } int main() { string s; cin>>s; int r = 0; int c = 0; for(char ch : s){ if(ch == 'W'){ c--; } else if(ch == 'E'){ c++; } else if(ch == 'S'){ r++; } else{ r--; } } cout<< ABS(r)+ABS(c) <<endl; return 0; }
13.333333
32
0.329167
akash246
a0a943b6d751922662c9f8c8d73eeba4399918b4
5,461
cpp
C++
src/game_api/script/usertypes/entities_activefloors_lua.cpp
jaythebusinessgoose/overlunky
12d8ee353fda01a53d2aa753b539319ed41d940e
[ "MIT" ]
56
2020-11-17T06:13:55.000Z
2022-03-05T19:21:25.000Z
src/game_api/script/usertypes/entities_activefloors_lua.cpp
jaythebusinessgoose/overlunky
12d8ee353fda01a53d2aa753b539319ed41d940e
[ "MIT" ]
99
2020-11-19T15:29:59.000Z
2022-03-28T21:12:50.000Z
src/game_api/script/usertypes/entities_activefloors_lua.cpp
jaythebusinessgoose/overlunky
12d8ee353fda01a53d2aa753b539319ed41d940e
[ "MIT" ]
47
2020-11-20T03:34:52.000Z
2022-02-22T17:48:02.000Z
#include "entities_activefloors_lua.hpp" #include "entities_activefloors.hpp" #include <sol/sol.hpp> namespace NEntitiesActiveFloors { void register_usertypes(sol::state& lua) { lua["Entity"]["as_crushtrap"] = &Entity::as<Crushtrap>; lua["Entity"]["as_olmec"] = &Entity::as<Olmec>; lua["Entity"]["as_woodenlogtrap"] = &Entity::as<WoodenlogTrap>; lua["Entity"]["as_boulder"] = &Entity::as<Boulder>; lua["Entity"]["as_pushblock"] = &Entity::as<PushBlock>; lua["Entity"]["as_boneblock"] = &Entity::as<BoneBlock>; lua["Entity"]["as_chainedpushblock"] = &Entity::as<ChainedPushBlock>; lua["Entity"]["as_lightarrowplatform"] = &Entity::as<LightArrowPlatform>; lua["Entity"]["as_fallingplatform"] = &Entity::as<FallingPlatform>; lua["Entity"]["as_unchainedspikeball"] = &Entity::as<UnchainedSpikeBall>; lua["Entity"]["as_drill"] = &Entity::as<Drill>; lua["Entity"]["as_thinice"] = &Entity::as<ThinIce>; lua["Entity"]["as_elevator"] = &Entity::as<Elevator>; lua["Entity"]["as_clambase"] = &Entity::as<ClamBase>; lua["Entity"]["as_regenblock"] = &Entity::as<RegenBlock>; lua["Entity"]["as_timedpowderkeg"] = &Entity::as<TimedPowderkeg>; lua.new_usertype<Crushtrap>( "Crushtrap", "dirx", &Crushtrap::dirx, "diry", &Crushtrap::diry, "timer", &Crushtrap::timer, "bounce_back_timer", &Crushtrap::bounce_back_timer, sol::base_classes, sol::bases<Entity, Movable>()); lua.new_usertype<Olmec>( "Olmec", "target_uid", &Olmec::target_uid, "attack_phase", &Olmec::attack_phase, "attack_timer", &Olmec::attack_timer, "ai_timer", &Olmec::ai_timer, "move_direction", &Olmec::move_direction, "jump_timer", &Olmec::jump_timer, "phase1_amount_of_bomb_salvos", &Olmec::phase1_amount_of_bomb_salvos, "unknown_attack_state", &Olmec::unknown_attack_state, "broken_floaters", &Olmec::broken_floaters, sol::base_classes, sol::bases<Entity, Movable>()); lua.new_usertype<WoodenlogTrap>( "WoodenlogTrap", "ceiling_1_uid", &WoodenlogTrap::ceiling_1_uid, "ceiling_2_uid", &WoodenlogTrap::ceiling_2_uid, "falling_speed", &WoodenlogTrap::falling_speed, sol::base_classes, sol::bases<Entity, Movable>()); lua.new_usertype<Boulder>( "Boulder", "is_rolling", &Boulder::is_rolling, sol::base_classes, sol::bases<Entity, Movable>()); lua.new_usertype<PushBlock>( "PushBlock", "dust_particle", &PushBlock::dust_particle, "dest_pos_x", &PushBlock::dest_pos_x, sol::base_classes, sol::bases<Entity, Movable>()); lua.new_usertype<BoneBlock>( "BoneBlock", sol::base_classes, sol::bases<Entity, Movable>()); lua.new_usertype<ChainedPushBlock>( "ChainedPushBlock", "is_chained", &ChainedPushBlock::is_chained, sol::base_classes, sol::bases<Entity, Movable, PushBlock>()); lua.new_usertype<LightArrowPlatform>( "LightArrowPlatform", "emitted_light", &LightArrowPlatform::emitted_light, sol::base_classes, sol::bases<Entity, Movable>()); lua.new_usertype<FallingPlatform>( "FallingPlatform", "emitted_light", &FallingPlatform::timer, "timer", &FallingPlatform::timer, "shaking_factor", &FallingPlatform::shaking_factor, "y_pos", &FallingPlatform::y_pos, sol::base_classes, sol::bases<Entity, Movable>()); lua.new_usertype<UnchainedSpikeBall>( "UnchainedSpikeBall", "bounce", &UnchainedSpikeBall::bounce, sol::base_classes, sol::bases<Entity, Movable>()); lua.new_usertype<Drill>( "Drill", "top_chain_piece", &Drill::top_chain_piece, "trigger", &Drill::trigger, sol::base_classes, sol::bases<Entity, Movable>()); lua.new_usertype<ThinIce>( "ThinIce", "strength", &ThinIce::strength, sol::base_classes, sol::bases<Entity, Movable>()); lua.new_usertype<Elevator>( "Elevator", "emitted_light", &Elevator::emitted_light, "timer", &Elevator::timer, "moving_up", &Elevator::moving_up, sol::base_classes, sol::bases<Entity, Movable>()); lua.new_usertype<ClamBase>( "ClamBase", "treasure_type", &ClamBase::treasure_type, "treasure_uid", &ClamBase::treasure_uid, "treasure_x_pos", &ClamBase::treasure_x_pos, "treasure_y_pos", &ClamBase::treasure_y_pos, "top_part_uid", &ClamBase::top_part_uid, sol::base_classes, sol::bases<Entity, Movable>()); lua.new_usertype<RegenBlock>( "RegenBlock", "on_breaking", &RegenBlock::on_breaking, sol::base_classes, sol::bases<Entity, Movable>()); lua.new_usertype<TimedPowderkeg>( "TimedPowderkeg", "timer", &TimedPowderkeg::timer, sol::base_classes, sol::bases<Entity, Movable, PushBlock>()); } } // namespace NEntitiesActiveFloors
29.203209
77
0.592749
jaythebusinessgoose
a0a9a49fb7cee4cc982a83c5c96147b1ce9a9eeb
7,121
cpp
C++
GameEngineArchitecture/source/Model.cpp
Cubes58/Team_NoName_GameEngine
5b1f75a61c43a1e1649b5a34a799aab65af70afd
[ "MIT" ]
null
null
null
GameEngineArchitecture/source/Model.cpp
Cubes58/Team_NoName_GameEngine
5b1f75a61c43a1e1649b5a34a799aab65af70afd
[ "MIT" ]
null
null
null
GameEngineArchitecture/source/Model.cpp
Cubes58/Team_NoName_GameEngine
5b1f75a61c43a1e1649b5a34a799aab65af70afd
[ "MIT" ]
null
null
null
#include "Model.h" #include <assimp/postprocess.h> #include <stb_image/stb_image.h> #include <iostream> Model::Model(std::string p_FilePath) { LoadModel(p_FilePath); } Model::Model(const std::string &p_FilePath, bool &p_ModelLoaded) { p_ModelLoaded = LoadModel(p_FilePath); } void Model::Render(const unsigned int p_ShaderProgram) { for (auto mesh : m_Meshes) { mesh.Render(p_ShaderProgram); } } bool Model::LoadModel(std::string p_FilePath) { Assimp::Importer import; const aiScene *scene = import.ReadFile(p_FilePath, aiProcess_Triangulate | aiProcess_FlipUVs); if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) { std::cout << "ERROR::ASSIMP::" << import.GetErrorString() << std::endl; return false; } m_Directory = p_FilePath.substr(0, p_FilePath.find_last_of('/')); ProcessNode(scene->mRootNode, scene); return true; } void Model::ProcessNode(aiNode *p_Node, const aiScene *p_Scene) { // Get the meshes of the node and add them to our vector. for (int i = 0; i < p_Node->mNumMeshes; i++) { int sceneMeshIndex = p_Node->mMeshes[i]; aiMesh* mesh = p_Scene->mMeshes[sceneMeshIndex]; m_Meshes.push_back(ProcessMesh(mesh, p_Scene)); } // Recursively process the nodes of any children. for (int i = 0; i < p_Node->mNumChildren; i++) { ProcessNode(p_Node->mChildren[i], p_Scene); } } Mesh Model::ProcessMesh(aiMesh *p_Mesh, const aiScene *p_Scene) { // Data to fill. std::vector<Vertex> vertices; std::vector<unsigned int> indices; std::vector<Texture> textures; // Create enough space for the vertices and indices. vertices.resize(p_Mesh->mNumVertices); indices.resize(p_Mesh->mNumFaces * 3); // Imported as triangles. // For each vertex of the mesh copy the data to out own mesh format. for (unsigned int i = 0; i < p_Mesh->mNumVertices; i++) { // All meshes should have vertices and normals. vertices[i].m_Position = glm::vec3(p_Mesh->mVertices[i].x, p_Mesh->mVertices[i].y, p_Mesh->mVertices[i].z); vertices[i].m_Normal = glm::vec3(p_Mesh->mNormals[i].x, p_Mesh->mNormals[i].y, p_Mesh->mNormals[i].z); // Check if the mesh has texture coordinates. if (p_Mesh->mTextureCoords[0]) { vertices[i].m_TextureCoordinates = glm::vec2(p_Mesh->mTextureCoords[0][i].x, p_Mesh->mTextureCoords[0][i].y); } else { vertices[i].m_TextureCoordinates = glm::vec2(0.0f, 0.0f); } } // Save all the vertex indices in the indices vector. for (int i = 0; i < p_Mesh->mNumFaces; i++) { // Retrieve all indices of the face and store them in the indices vector. for (int j = 0; j < p_Mesh->mFaces[i].mNumIndices; j++) indices[3 * i + j] = p_Mesh->mFaces[i].mIndices[j]; } // Get material textures (if there are any). if (p_Mesh->mMaterialIndex >= 0) { aiMaterial* material = p_Scene->mMaterials[p_Mesh->mMaterialIndex]; std::vector<Texture> diffuseMaps = LoadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse"); std::vector<Texture> specularMaps = LoadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular"); std::vector<Texture> normalMaps = LoadMaterialTextures(material, aiTextureType_NORMALS, "texture_normal"); std::vector<Texture> heightMaps = LoadMaterialTextures(material, aiTextureType_HEIGHT, "texture_height"); // Put all the textures together in a single vector. textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end()); textures.insert(textures.end(), specularMaps.begin(), specularMaps.end()); textures.insert(textures.end(), normalMaps.begin(), normalMaps.end()); textures.insert(textures.end(), heightMaps.begin(), heightMaps.end()); } // Return the mesh data. return Mesh(vertices, indices, textures); } std::vector<Texture> Model::LoadMaterialTextures(aiMaterial *p_Material, aiTextureType p_Type, std::string p_TypeName) { std::vector<Texture> textures; for (int i = 0; i < p_Material->GetTextureCount(p_Type); i++) { aiString str; p_Material->GetTexture(p_Type, i, &str); bool b_loadedTexture = false; for (auto texture : m_Textures) { if (std::strcmp(texture.p_FilePath.C_Str(), str.C_Str()) == 0) { textures.push_back(texture); b_loadedTexture = true; break; } } if (!b_loadedTexture) { // Setup a new texture. Texture texture; texture.m_ID = TextureFromFile(str.C_Str(), m_Directory); texture.m_Type = p_TypeName; texture.p_FilePath = str; textures.push_back(texture); m_Textures.push_back(texture); // Add to loaded textures. } } return textures; } // Static function to load a texture using lightweight stb_image library. unsigned int Model::TextureFromFile(const char *p_FilePath, const std::string &p_Directory, bool p_Gamma) { std::string filename = std::string(p_FilePath); filename = p_Directory + '/' + filename; unsigned int textureID; glGenTextures(1, &textureID); int width, height, nrComponents; unsigned char* textureData = stbi_load(filename.c_str(), &width, &height, &nrComponents, 0); if (textureData) { GLenum format; if (nrComponents == 1) format = GL_RED; else if (nrComponents == 3) format = GL_RGB; else if (nrComponents == 4) format = GL_RGBA; glBindTexture(GL_TEXTURE_2D, textureID); glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, textureData); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(textureData); } else { std::cout << "Texture failed to load from: " << p_FilePath << std::endl; stbi_image_free(textureData); } return textureID; } unsigned int Model::TextureCubeFromFile(std::vector<const char*> p_FilePath, const std::string & p_Directory, bool p_Gamma) { unsigned int l_textureID; glGenTextures(1, &l_textureID); glBindTexture(GL_TEXTURE_CUBE_MAP, l_textureID); int l_ImageWidth, l_ImageHeight, l_NrComponents; unsigned char* l_TextureData; for (GLuint i = 0; i < p_FilePath.size(); i++) { l_TextureData = stbi_load(p_FilePath[i], &l_ImageWidth, &l_ImageHeight, &l_NrComponents, 0); if (l_TextureData) { GLenum format; if (l_NrComponents == 1) format = GL_RED; else if (l_NrComponents == 3) format = GL_RGB; else if (l_NrComponents == 4) format = GL_RGBA; glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, format, l_ImageWidth, l_ImageHeight, 0, format, GL_UNSIGNED_BYTE, l_TextureData); } else { std::cout << "Texture failed to load from: " << p_FilePath[i] << std::endl; } stbi_image_free(l_TextureData); } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); return l_textureID; }
35.078818
136
0.728409
Cubes58
a0ab9189b149658c98ac880cfd7f32e3c8c1c797
901
cpp
C++
src/rogue_game/display/player_display.cpp
tanacchi/rogue_game
fd8f655f95932513f6aa63e0c413bbe110a4418a
[ "MIT" ]
10
2018-09-13T14:47:07.000Z
2022-01-10T11:46:12.000Z
src/rogue_game/display/player_display.cpp
tanacchi/rogue_game
fd8f655f95932513f6aa63e0c413bbe110a4418a
[ "MIT" ]
13
2018-09-18T19:36:32.000Z
2020-11-12T16:26:22.000Z
src/rogue_game/display/player_display.cpp
tanacchi/rogue_game
fd8f655f95932513f6aa63e0c413bbe110a4418a
[ "MIT" ]
null
null
null
#include <display/player_display.hpp> #include <utility/point.hpp> #include <character/player.hpp> PlayerDisplay::PlayerDisplay(std::size_t x, std::size_t y, std::size_t width, std::size_t height) : DisplayPanel(x, y, width, height) { } void PlayerDisplay::show(const Player& player) { werase(win_.get()); const auto& pos{player.position_}; const auto& dir{player.direction_}; mvwprintw(win_.get(), 0, 0, "Position: "); mvwprintw(win_.get(), 1, 2, "x: %d", pos.get_x()); mvwprintw(win_.get(), 2, 2, "y: %d", pos.get_y()); mvwprintw(win_.get(), 3, 0, "Direction: "); mvwprintw(win_.get(), 4, 2, "dx: %d", dir.get_x()); mvwprintw(win_.get(), 5, 2, "dy: %d", dir.get_y()); mvwprintw(win_.get(), 6, 0, "money: %d", player.money_); mvwprintw(win_.get(), 7, 0, "HP: %d (max: %d)", player.hit_point_, player.max_hit_point_); wrefresh(win_.get()); }
32.178571
92
0.624861
tanacchi
a0adcd5d80d3cdbf399e4ef4d8bd61402090d5a1
1,380
cpp
C++
pnc/whole_body_controllers/managers/task_hierarchy_manager.cpp
junhyeokahn/PnC
388440f7db7b2aedf1e397d0130d806090865c35
[ "MIT" ]
25
2019-01-31T13:51:34.000Z
2022-02-08T13:19:01.000Z
pnc/whole_body_controllers/managers/task_hierarchy_manager.cpp
junhyeokahn/PnC
388440f7db7b2aedf1e397d0130d806090865c35
[ "MIT" ]
5
2020-06-01T20:48:46.000Z
2022-02-08T11:42:02.000Z
pnc/whole_body_controllers/managers/task_hierarchy_manager.cpp
junhyeokahn/PnC
388440f7db7b2aedf1e397d0130d806090865c35
[ "MIT" ]
9
2018-11-20T22:37:50.000Z
2021-09-14T17:17:27.000Z
#include <pnc/whole_body_controllers/managers/task_hierarchy_manager.hpp> TaskHierarchyManager::TaskHierarchyManager(Task *_task, double _w_max, double _w_min) { util::PrettyConstructor(2, "TaskHierarchyManager"); task_ = _task; w_max_ = _w_max; w_min_ = _w_min; w_starting_ = task_->w_hierarchy; start_time_ = 0.; duration_ = 0.; } TaskHierarchyManager::~TaskHierarchyManager() {} void TaskHierarchyManager::InitializeRampToMin(double _start_time, double _duration) { start_time_ = _start_time; duration_ = _duration; w_starting_ = task_->w_hierarchy; } void TaskHierarchyManager::InitializeRampToMax(double _start_time, double _duration) { start_time_ = _start_time; duration_ = _duration; w_starting_ = task_->w_hierarchy; } void TaskHierarchyManager::UpdateRampToMin(double _curr_time) { double t = util::Clamp(_curr_time, start_time_, start_time_ + duration_); task_->w_hierarchy = (w_min_ - w_starting_) / duration_ * (t - start_time_) + w_starting_; } void TaskHierarchyManager::UpdateRampToMax(double _curr_time) { double t = util::Clamp(_curr_time, start_time_, start_time_ + duration_); task_->w_hierarchy = (w_max_ - w_starting_) / duration_ * (t - start_time_) + w_starting_; }
32.857143
75
0.681884
junhyeokahn
a0af6839fa011564f3d40775503e46db2bb146b4
26,887
cpp
C++
projects/tech-demo-particle/SceneJesusCross.cpp
A-Ribeiro/OpenGLStarter
0552513f24ce3820b4957b1e453e615a9b77c8ff
[ "MIT" ]
15
2019-01-13T16:07:27.000Z
2021-09-27T15:18:58.000Z
projects/tech-demo-particle/SceneJesusCross.cpp
A-Ribeiro/OpenGLStarter
0552513f24ce3820b4957b1e453e615a9b77c8ff
[ "MIT" ]
1
2019-03-14T00:36:35.000Z
2020-12-29T11:48:09.000Z
projects/tech-demo-particle/SceneJesusCross.cpp
A-Ribeiro/OpenGLStarter
0552513f24ce3820b4957b1e453e615a9b77c8ff
[ "MIT" ]
3
2020-03-02T21:28:56.000Z
2021-09-27T15:18:50.000Z
#include "SceneJesusCross.h" #include <mini-gl-engine/mini-gl-engine.h> #include "App.h" using namespace aRibeiro; using namespace GLEngine; using namespace GLEngine::Components; Transform* loadSceneroot(); bool ReplaceMaterial(Transform *element, void* userData) { ComponentMaterial *material = (ComponentMaterial *)element->findComponent(Components::ComponentMaterial::Type); if ( material != NULL ){ ComponentMaterial *newMaterial = (ComponentMaterial *)userData; ReferenceCounter<Component*> *compRefCount = &GLEngine::Engine::Instance()->componentReferenceCounter; Component * componentMaterial = element->removeComponent(material); compRefCount->remove(componentMaterial); element->addComponent(compRefCount->add(newMaterial)); //little optimization element->makeFirstComponent(newMaterial); } return true; } //to load skybox, textures, cubemaps, 3DModels and setup materials void SceneJesusCross::loadResources() { GLEngine::Engine *engine = GLEngine::Engine::Instance(); particleTexture = resourceHelper->createTextureFromFile("resources/smoke.png",true && engine->sRGBCapable); //diffuse + normal JesusTextures[0] = resourceHelper->createTextureFromFile("resources/Jesus/UVJesus.jpg",true && engine->sRGBCapable); JesusTextures[1] = NULL;//resourceHelper->defaultNormalTexture; //diffuse + normal Rock02Textures[0] = resourceHelper->createTextureFromFile("resources/Rocks/rock02_diffuse.jpg",true && engine->sRGBCapable); Rock02Textures[1] = resourceHelper->createTextureFromFile("resources/Rocks/rock02_normal.jpg",false); //diffuse + normal Rock03Textures[0] = resourceHelper->createTextureFromFile("resources/Rocks/rock03_diffuse.jpg",true && engine->sRGBCapable); Rock03Textures[1] = resourceHelper->createTextureFromFile("resources/Rocks/rock03_normal.jpg",false); Jesus3DModel = resourceHelper->createTransformFromModel("resources/Jesus/JesusOnCross.bams"); Rocks02_3DModel = resourceHelper->createTransformFromModel("resources/Rocks/Rocks02.bams"); Rocks03_3DModel = resourceHelper->createTransformFromModel("resources/Rocks/Rocks03.bams"); ReferenceCounter<openglWrapper::GLTexture*> *texRefCount = &GLEngine::Engine::Instance()->textureReferenceCounter; ComponentMaterial * newMaterial; newMaterial = new ComponentMaterial(); newMaterial->type = Components::MaterialPBR; newMaterial->pbr.albedoColor = aRibeiro::vec4(1, 1, 1, 1); newMaterial->pbr.metallic = 0.0f; newMaterial->pbr.roughness = 1.0f; newMaterial->pbr.texAlbedo = texRefCount->add(JesusTextures[0]); newMaterial->pbr.texNormal = NULL;//texRefCount->add(JesusTextures[1]); Jesus3DModel->traversePreOrder_DepthFirst(ReplaceMaterial, newMaterial); newMaterial = new ComponentMaterial(); newMaterial->type = Components::MaterialPBR; newMaterial->pbr.albedoColor = aRibeiro::vec4(1, 1, 1, 1); newMaterial->pbr.metallic = 0.0f; newMaterial->pbr.roughness = 1.0f; newMaterial->pbr.texAlbedo = texRefCount->add(Rock02Textures[0]); newMaterial->pbr.texNormal = texRefCount->add(Rock02Textures[1]); Rocks02_3DModel->traversePreOrder_DepthFirst(ReplaceMaterial, newMaterial); newMaterial = new ComponentMaterial(); newMaterial->type = Components::MaterialPBR; newMaterial->pbr.albedoColor = aRibeiro::vec4(1, 1, 1, 1); newMaterial->pbr.metallic = 0.0f; newMaterial->pbr.roughness = 1.0f; newMaterial->pbr.texAlbedo = texRefCount->add(Rock03Textures[0]); newMaterial->pbr.texNormal = texRefCount->add(Rock03Textures[1]); Rocks03_3DModel->traversePreOrder_DepthFirst(ReplaceMaterial, newMaterial); } //to load the scene graph void SceneJesusCross::loadGraph() { root = loadSceneroot(); } //to bind the resources to the current graph void SceneJesusCross::bindResourcesToGraph() { GLEngine::Engine *engine = GLEngine::Engine::Instance(); //setup ambient color { GLRenderState *renderState = GLRenderState::Instance(); //setup renderstate renderState->ClearColor = vec4(0.1607843f, 0.1568628f, 0.1568628f,1.0f); renderPipeline->ambientLight.color = vec3(0.2641509f,0.2641509f,0.2641509f); /* ResourceHelper::vec3ColorLinearToGamma( //global ambient light ResourceHelper::vec3ColorGammaToLinear(vec3(0.2641509f,0.2641509f,0.2641509f)) + //light0 global light ResourceHelper::vec3ColorGammaToLinear(vec3(0.2705882f,0.2901961f,0.3098039f)) ); */ if (engine->sRGBCapable) { //renderState->ClearColor = ResourceHelper::vec4ColorGammaToLinear(renderState->ClearColor); //renderPipeline->ambientLight.color = ResourceHelper::vec3ColorLinearToGamma(renderPipeline->ambientLight.color); } } //setup camera { Transform *mainCamera = root->findTransformByName("Main Camera"); mainCamera->addComponent(camera = new ComponentCameraPerspective()); ((ComponentCameraPerspective*)camera)->fovDegrees = 60.0f; //((ComponentCameraPerspective*)camera)->nearPlane = 5.0f; ((ComponentCameraPerspective*)camera)->farPlane = 50.0f; Transform *toLookNode = root->findTransformByName("ToLookNode"); mainCamera->lookAtLeftHanded(toLookNode); //componentCameraRotateOnTarget { mainCamera->addComponent(componentCameraRotateOnTarget = new ComponentCameraRotateOnTarget()); componentCameraRotateOnTarget->Target = toLookNode; } /* //setup rotation { distanceRotation = ::distance(mainCamera->Position, toLookNode->Position); //convert the transform camera to camera move euler angles... vec3 forward = toVec3(mainCamera->getMatrix()[2]); vec3 proj_y = vec3(forward.x, 0, forward.z); float length_proj_y = length(proj_y); proj_y = normalize(proj_y); vec3 cone_proj_x = normalize(vec3(length_proj_y, forward.y, 0)); euler.x = -atan2(cone_proj_x.y, cone_proj_x.x); euler.y = atan2(proj_y.x, proj_y.z); euler.z = 0; while (euler.x < -DEG2RAD(90.0f)) euler.x += DEG2RAD(360.0f); while (euler.x > DEG2RAD(90.0f)) euler.x -= DEG2RAD(360.0f); }*/ } //light { Transform *lightTransform = root->findTransformByName("Directional Light"); ComponentLight *light = (ComponentLight *)lightTransform->addComponent(new ComponentLight()); light->type = LightSun; light->sun.color = aRibeiro::vec3(1, 0.9568627f, 0.8392157f); light->sun.intensity = 0.5f + 0.5f; //if (engine->sRGBCapable) //light->sun.color = ResourceHelper::vec3ColorLinearToGamma(light->sun.color); } //Jesus 3DModel { Transform *node = root->findTransformByName("JesusCross1")->findTransformByName("ToInsertModel"); node->addChild(ResourceHelper::cloneTransformRecursive(Jesus3DModel)); } //rocks { std::vector<Transform*> nodes; nodes = root->findTransformsByName("rock02"); for(size_t i=0;i<nodes.size();i++) nodes[i]->addChild( ResourceHelper::cloneTransformRecursive(Rocks02_3DModel) ); nodes = root->findTransformsByName("rock03"); for(size_t i=0;i<nodes.size();i++) nodes[i]->addChild( ResourceHelper::cloneTransformRecursive(Rocks03_3DModel) ); } //Particle System { ComponentParticleSystem *particleSystem = new ComponentParticleSystem(); Transform *node = root->findTransformByName("Particle System"); node->addComponent(particleSystem); // duration: 25 // prewarm: True // startLifeTime: 25 // startSpeed: 1 // startSize: 8 // rateOverTime: 1.5 // time -> Color // 0 -> 1, 1, 1 // 1 -> 1, 1, 1 // time -> Alpha // 0 -> 0 // 0.05000382 -> 1 // 0.9499962 -> 1 // 1 -> 0 particleSystem->duration_sec = 25.0f; particleSystem->loop = true; particleSystem->setLifetime(25.0f); particleSystem->Speed.addKey(Key<float>(0.0f, 1.0f)); particleSystem->Size.addKey(Key<float>(0.0f, 8.0f)); particleSystem->setRateOverTime(1.5f); particleSystem->Color.addKey(Key<vec3>(0.0f, vec3(1,1,1))); particleSystem->Alpha.addKey(Key<float>(0.0f, 0.0f)); particleSystem->Alpha.addKey(Key<float>(0.05f, 1.0f)); particleSystem->Alpha.addKey(Key<float>(0.95f, 1.0f)); particleSystem->Alpha.addKey(Key<float>(1.0f, 0.0f)); //sample some values /* printf("-1.0f = %f\n", particleSystem->Alpha.getValue(-1.0f)); printf("0.0f = %f\n",particleSystem->Alpha.getValue(0.0f)); printf("0.025f = %f\n",particleSystem->Alpha.getValue(0.025f)); printf("0.05f = %f\n",particleSystem->Alpha.getValue(0.05f)); printf("0.5f = %f\n",particleSystem->Alpha.getValue(0.5f)); printf("0.95f = %f\n",particleSystem->Alpha.getValue(0.95f)); printf("0.975f = %f\n",particleSystem->Alpha.getValue(0.975f)); printf("1.0f = %f\n",particleSystem->Alpha.getValue(1.0f)); printf("2.0f = %f\n", particleSystem->Alpha.getValue(2.0f)); */ particleSystem->boxEmmiter = node->findTransformByName("ParticleBox"); ResourceHelper::setTexture(&particleSystem->texture,particleTexture); particleSystem->textureColor = aRibeiro::vec4(0.3584906f, 0.3584906f, 0.3584906f, 0.6039216f); particleSystem->prewarmStart(); //particleSystem->emmitStart(); } /* { Transform *node = root->findTransformByName("rock03 (test)"); node->addChild(ResourceHelper::cloneTransformRecursive(Rocks03_3DModel)); } */ } //clear all loaded scene void SceneJesusCross::unloadAll() { ResourceHelper::releaseTransformRecursive(&root); ResourceHelper::releaseTransformRecursive(&Jesus3DModel); ResourceHelper::releaseTransformRecursive(&Rocks02_3DModel); ResourceHelper::releaseTransformRecursive(&Rocks03_3DModel); } SceneJesusCross::SceneJesusCross( aRibeiro::PlatformTime *_time, GLEngine::RenderPipeline *_renderPipeline, GLEngine::ResourceHelper *_resourceHelper) : GLEngine::SceneBase(_time, _renderPipeline, _resourceHelper) { Jesus3DModel = NULL; Rocks02_3DModel = NULL; Rocks03_3DModel = NULL; // mouseMoving = false; } SceneJesusCross::~SceneJesusCross() { unload(); } void SceneJesusCross::draw(){ //Transform *node = root->findTransformByName("rock03 (test)"); //node->LocalRotation = (quat)node->LocalRotation * quatFromEuler(0, time->deltaTime * DEG2RAD(30.0f), 0); //Transform *node = root->findTransformByName("Directional Light"); //node->LocalRotation = (quat)node->LocalRotation * quatFromEuler(0, time->deltaTime * DEG2RAD(30.0f), 0); App* app = (App*)GLEngine::Engine::Instance()->app; keyP.setState(sf::Keyboard::isKeyPressed(sf::Keyboard::P)); if (keyP.down) time->timeScale = 1.0f - time->timeScale; mouseBtn1.setState(app->mousePressed); if (mouseBtn1.down) { if (app->sceneGUI->button_SoftParticles->selected) { componentCameraRotateOnTarget->enabled = false; Transform *node = root->findTransformByName("Particle System"); ComponentParticleSystem *particleSystem = (ComponentParticleSystem*)node->findComponent(ComponentParticleSystem::Type); particleSystem->soft = !particleSystem->soft; if (particleSystem->soft) app->sceneGUI->button_SoftParticles->updateText("Soft Particles ON"); else app->sceneGUI->button_SoftParticles->updateText("Soft Particles OFF"); } else { componentCameraRotateOnTarget->enabled = true; } } SceneBase::draw(); } Transform* loadSceneroot() { Transform* _0 = new Transform(); _0->Name = std::string("root"); _0->LocalPosition = vec3(0,0,0); _0->LocalRotation = quat(0,0,0,1); _0->LocalScale = vec3(1,1,1); { Transform* _1 = _0->addChild(new Transform()); _1->Name = std::string("Main Camera"); //_1->LocalPosition = vec3(0,3.45,-7.37); //_1->LocalPosition = vec3(0,3.45,-17.37); _1->LocalPosition = vec3(3.736165, 6.254054, -5.700460); _1->LocalRotation = quat(0,0,0,1); _1->LocalScale = vec3(1,1,1); } { Transform* _2 = _0->addChild(new Transform()); _2->Name = std::string("Directional Light"); _2->LocalPosition = vec3(0,3,0); _2->LocalRotation = quat(-0.4886241,0.4844012,0.06177928,-0.723039); _2->LocalScale = vec3(1,1,1); } { Transform* _3 = _0->addChild(new Transform()); _3->Name = std::string("JesusCross1"); _3->LocalPosition = vec3(0,0,0); _3->LocalRotation = quat(0,1,0,0); _3->LocalScale = vec3(0.4457346,0.4457346,0.4457346); { Transform* _4 = _3->addChild(new Transform()); _4->Name = std::string("ToInsertModel"); _4->LocalPosition = vec3(-11.63,6.67,0.12); _4->LocalRotation = quat(0,0,0,1); _4->LocalScale = vec3(1,1,1); } } { Transform* _5 = _0->addChild(new Transform()); _5->Name = std::string("props"); _5->LocalPosition = vec3(0,0,0); _5->LocalRotation = quat(0,0,0,1); _5->LocalScale = vec3(1,1,1); { Transform* _6 = _5->addChild(new Transform()); _6->Name = std::string("Base"); _6->LocalPosition = vec3(0,-0.75,0); _6->LocalRotation = quat(0,0,0,1); _6->LocalScale = vec3(1,1,1); { Transform* _7 = _6->addChild(new Transform()); _7->Name = std::string("rock03"); _7->LocalPosition = vec3(1,0,0); _7->LocalRotation = quat(0,0,0,1); _7->LocalScale = vec3(1,1,1); } { Transform* _8 = _6->addChild(new Transform()); _8->Name = std::string("rock03"); _8->LocalPosition = vec3(-1,0,0); _8->LocalRotation = quat(0,0,0,1); _8->LocalScale = vec3(1,1,1); } { Transform* _9 = _6->addChild(new Transform()); _9->Name = std::string("rock03"); _9->LocalPosition = vec3(0.03594612,-1.080334E-07,1.001629); _9->LocalRotation = quat(3.723534E-18,0.7121994,8.490078E-08,0.7019773); _9->LocalScale = vec3(1,1,1); } { Transform* _10 = _6->addChild(new Transform()); _10->Name = std::string("rock03"); _10->LocalPosition = vec3(0.00703415,1.071021E-07,-0.9981615); _10->LocalRotation = quat(3.723534E-18,0.7121994,8.490078E-08,0.7019773); _10->LocalScale = vec3(1,1,1); } } { Transform* _11 = _5->addChild(new Transform()); _11->Name = std::string("Top"); _11->LocalPosition = vec3(0,-0.337,0); _11->LocalRotation = quat(0,0,0,1); _11->LocalScale = vec3(1,1,1); { Transform* _12 = _11->addChild(new Transform()); _12->Name = std::string("rock02"); _12->LocalPosition = vec3(-0.276,0,-0.192); _12->LocalRotation = quat(0,0,0,1); _12->LocalScale = vec3(1,1,1); } { Transform* _13 = _11->addChild(new Transform()); _13->Name = std::string("rock02"); _13->LocalPosition = vec3(0.527,0,-0.192); _13->LocalRotation = quat(0,0,0,1); _13->LocalScale = vec3(1,1,1); } { Transform* _14 = _11->addChild(new Transform()); _14->Name = std::string("rock02"); _14->LocalPosition = vec3(0.527,0,0.571); _14->LocalRotation = quat(0,0,0,1); _14->LocalScale = vec3(1,1,1); } { Transform* _15 = _11->addChild(new Transform()); _15->Name = std::string("rock02"); _15->LocalPosition = vec3(-0.276,0,0.571); _15->LocalRotation = quat(0,0,0,1); _15->LocalScale = vec3(1,1,1); } } { Transform* _16 = _5->addChild(new Transform()); _16->Name = std::string("Ground"); _16->LocalPosition = vec3(0,-1.98,-8); _16->LocalRotation = quat(0,0,0,1); _16->LocalScale = vec3(1.3,1.3,1.3); { Transform* _17 = _16->addChild(new Transform()); _17->Name = std::string("rock03"); _17->LocalPosition = vec3(0.98,-0.02,0.013366); _17->LocalRotation = quat(-0.03860917,-0.03860917,0.7060519,0.7060519); _17->LocalScale = vec3(2.374482,2.374482,2.374482); } { Transform* _18 = _16->addChild(new Transform()); _18->Name = std::string("rock03"); _18->LocalPosition = vec3(-0.98,-0.02,0.013366); _18->LocalRotation = quat(0.03287782,0.03287782,0.706342,0.706342); _18->LocalScale = vec3(2.374482,2.374482,2.374482); } { Transform* _19 = _16->addChild(new Transform()); _19->Name = std::string("rock03"); _19->LocalPosition = vec3(3.23,-0.02,0.013366); _19->LocalRotation = quat(0.05547897,0.05547897,0.704927,0.704927); _19->LocalScale = vec3(2.374482,2.374482,2.374482); } { Transform* _20 = _16->addChild(new Transform()); _20->Name = std::string("rock03"); _20->LocalPosition = vec3(-3.23,-0.02,0.013366); _20->LocalRotation = quat(-0.06138256,-0.06138256,0.7044375,0.7044375); _20->LocalScale = vec3(2.374482,2.374482,2.374482); } { Transform* _21 = _16->addChild(new Transform()); _21->Name = std::string("rock03"); _21->LocalPosition = vec3(5.73,-0.02,0.013366); _21->LocalRotation = quat(0.05394091,0.05394091,0.7050464,0.7050464); _21->LocalScale = vec3(2.374482,2.374482,2.374482); } { Transform* _22 = _16->addChild(new Transform()); _22->Name = std::string("rock03"); _22->LocalPosition = vec3(-5.73,-0.02,0.013366); _22->LocalRotation = quat(-0.04556966,-0.04556966,0.7056369,0.7056369); _22->LocalScale = vec3(2.374482,2.374482,2.374482); } { Transform* _23 = _16->addChild(new Transform()); _23->Name = std::string("rock03"); _23->LocalPosition = vec3(7.98,-0.02,0.013366); _23->LocalRotation = quat(0.04452279,0.04452279,0.7057037,0.7057037); _23->LocalScale = vec3(2.374482,2.374482,2.374482); } { Transform* _24 = _16->addChild(new Transform()); _24->Name = std::string("rock03"); _24->LocalPosition = vec3(-7.98,-0.02,0.013366); _24->LocalRotation = quat(-0.03669898,-0.03669898,0.7061538,0.7061538); _24->LocalScale = vec3(2.374482,2.374482,2.374482); } } { Transform* _25 = _5->addChild(new Transform()); _25->Name = std::string("Ground (1)"); _25->LocalPosition = vec3(0,-1.98,8); _25->LocalRotation = quat(0,0,0,1); _25->LocalScale = vec3(1.3,1.3,1.3); { Transform* _26 = _25->addChild(new Transform()); _26->Name = std::string("rock03"); _26->LocalPosition = vec3(0.98,-0.02,0.013366); _26->LocalRotation = quat(0.1083799,0.1083799,0.6987516,0.6987516); _26->LocalScale = vec3(2.374482,2.374482,2.374482); } { Transform* _27 = _25->addChild(new Transform()); _27->Name = std::string("rock03"); _27->LocalPosition = vec3(-0.98,-0.02,0.013366); _27->LocalRotation = quat(-0.07996473,-0.07996473,0.7025707,0.7025707); _27->LocalScale = vec3(2.374482,2.374482,2.374482); } { Transform* _28 = _25->addChild(new Transform()); _28->Name = std::string("rock03"); _28->LocalPosition = vec3(3.23,-0.02,0.013366); _28->LocalRotation = quat(0.1067489,0.1067489,0.6990026,0.6990026); _28->LocalScale = vec3(2.374482,2.374482,2.374482); } { Transform* _29 = _25->addChild(new Transform()); _29->Name = std::string("rock03"); _29->LocalPosition = vec3(-3.23,-0.02,0.013366); _29->LocalRotation = quat(-0.111026,-0.111026,0.6983361,0.6983361); _29->LocalScale = vec3(2.374482,2.374482,2.374482); } { Transform* _30 = _25->addChild(new Transform()); _30->Name = std::string("rock03"); _30->LocalPosition = vec3(5.73,-0.02,0.013366); _30->LocalRotation = quat(-0.093238,-0.093238,0.7009327,0.7009327); _30->LocalScale = vec3(2.374482,2.374482,2.374482); } { Transform* _31 = _25->addChild(new Transform()); _31->Name = std::string("rock03"); _31->LocalPosition = vec3(-5.73,-0.02,0.013366); _31->LocalRotation = quat(0.09847496,0.09847496,0.7002162,0.7002162); _31->LocalScale = vec3(2.374482,2.374482,2.374482); } { Transform* _32 = _25->addChild(new Transform()); _32->Name = std::string("rock03"); _32->LocalPosition = vec3(7.98,-0.02,0.013366); _32->LocalRotation = quat(-0.06915998,-0.06915998,0.7037165,0.7037165); _32->LocalScale = vec3(2.374482,2.374482,2.374482); } { Transform* _33 = _25->addChild(new Transform()); _33->Name = std::string("rock03"); _33->LocalPosition = vec3(-7.98,-0.02,0.013366); _33->LocalRotation = quat(-0.07008335,-0.07008335,0.7036251,0.7036251); _33->LocalScale = vec3(2.374482,2.374482,2.374482); } } { Transform* _34 = _5->addChild(new Transform()); _34->Name = std::string("Ground (2)"); _34->LocalPosition = vec3(0,-1.98,2.5); _34->LocalRotation = quat(0,0,0,1); _34->LocalScale = vec3(1.3,1.3,1.3); { Transform* _35 = _34->addChild(new Transform()); _35->Name = std::string("rock03"); _35->LocalPosition = vec3(0.98,-0.02,0.013366); _35->LocalRotation = quat(-0.0393486,-0.0393486,0.7060111,0.7060111); _35->LocalScale = vec3(2.374482,2.374482,2.374482); } { Transform* _36 = _34->addChild(new Transform()); _36->Name = std::string("rock03"); _36->LocalPosition = vec3(-0.98,-0.02,0.013366); _36->LocalRotation = quat(0.0432294,0.0432294,0.7057841,0.7057841); _36->LocalScale = vec3(2.374482,2.374482,2.374482); } { Transform* _37 = _34->addChild(new Transform()); _37->Name = std::string("rock03"); _37->LocalPosition = vec3(3.23,-0.02,0.013366); _37->LocalRotation = quat(-0.04107346,-0.04107346,0.7059129,0.7059129); _37->LocalScale = vec3(2.374482,2.374482,2.374482); } { Transform* _38 = _34->addChild(new Transform()); _38->Name = std::string("rock03"); _38->LocalPosition = vec3(-3.23,-0.02,0.013366); _38->LocalRotation = quat(-0.02251909,-0.02251909,0.7067481,0.7067481); _38->LocalScale = vec3(2.374482,2.374482,2.374482); } { Transform* _39 = _34->addChild(new Transform()); _39->Name = std::string("rock03"); _39->LocalPosition = vec3(5.73,-0.02,0.013366); _39->LocalRotation = quat(-0.03170656,-0.03170656,0.7063956,0.7063956); _39->LocalScale = vec3(2.374482,2.374482,2.374482); } { Transform* _40 = _34->addChild(new Transform()); _40->Name = std::string("rock03"); _40->LocalPosition = vec3(-5.73,-0.02,0.013366); _40->LocalRotation = quat(-0.04107346,-0.04107346,0.7059129,0.7059129); _40->LocalScale = vec3(2.374482,2.374482,2.374482); } { Transform* _41 = _34->addChild(new Transform()); _41->Name = std::string("rock03"); _41->LocalPosition = vec3(7.98,-0.02,0.013366); _41->LocalRotation = quat(0.0432294,0.0432294,0.7057841,0.7057841); _41->LocalScale = vec3(2.374482,2.374482,2.374482); } { Transform* _42 = _34->addChild(new Transform()); _42->Name = std::string("rock03"); _42->LocalPosition = vec3(-7.98,-0.02,0.013366); _42->LocalRotation = quat(-0.0393486,-0.0393486,0.7060111,0.7060111); _42->LocalScale = vec3(2.374482,2.374482,2.374482); } } { Transform* _43 = _5->addChild(new Transform()); _43->Name = std::string("Ground (3)"); _43->LocalPosition = vec3(0,-1.98,-2.5); _43->LocalRotation = quat(0,0,0,1); _43->LocalScale = vec3(1.3,1.3,1.3); { Transform* _44 = _43->addChild(new Transform()); _44->Name = std::string("rock03"); _44->LocalPosition = vec3(0.98,-0.02,0.013366); _44->LocalRotation = quat(0.0447691,0.0447691,0.7056881,0.7056881); _44->LocalScale = vec3(2.374482,2.374482,2.374482); } { Transform* _45 = _43->addChild(new Transform()); _45->Name = std::string("rock03"); _45->LocalPosition = vec3(-0.98,-0.02,0.013366); _45->LocalRotation = quat(0.01850988,0.01850988,0.7068645,0.7068645); _45->LocalScale = vec3(2.374482,2.374482,2.374482); } { Transform* _46 = _43->addChild(new Transform()); _46->Name = std::string("rock03"); _46->LocalPosition = vec3(3.23,-0.02,0.013366); _46->LocalRotation = quat(-0.03873239,-0.03873239,0.7060452,0.7060452); _46->LocalScale = vec3(2.374482,2.374482,2.374482); } { Transform* _47 = _43->addChild(new Transform()); _47->Name = std::string("rock03"); _47->LocalPosition = vec3(-3.23,-0.02,0.013366); _47->LocalRotation = quat(-0.01918836,-0.01918836,0.7068464,0.7068464); _47->LocalScale = vec3(2.374482,2.374482,2.374482); } { Transform* _48 = _43->addChild(new Transform()); _48->Name = std::string("rock03"); _48->LocalPosition = vec3(5.73,-0.02,0.013366); _48->LocalRotation = quat(-0.01918836,-0.01918836,0.7068464,0.7068464); _48->LocalScale = vec3(2.374482,2.374482,2.374482); } { Transform* _49 = _43->addChild(new Transform()); _49->Name = std::string("rock03"); _49->LocalPosition = vec3(-5.73,-0.02,0.013366); _49->LocalRotation = quat(-0.03873239,-0.03873239,0.7060452,0.7060452); _49->LocalScale = vec3(2.374482,2.374482,2.374482); } { Transform* _50 = _43->addChild(new Transform()); _50->Name = std::string("rock03"); _50->LocalPosition = vec3(7.98,-0.02,0.013366); _50->LocalRotation = quat(0.01850988,0.01850988,0.7068645,0.7068645); _50->LocalScale = vec3(2.374482,2.374482,2.374482); } { Transform* _51 = _43->addChild(new Transform()); _51->Name = std::string("rock03"); _51->LocalPosition = vec3(-7.98,-0.02,0.013366); _51->LocalRotation = quat(0.0447691,0.0447691,0.7056881,0.7056881); _51->LocalScale = vec3(2.374482,2.374482,2.374482); } } } { Transform* _52 = _0->addChild(new Transform()); _52->Name = std::string("ToLookNode"); _52->LocalPosition = vec3(0,3.45,0); _52->LocalRotation = quat(0,0,0,1); _52->LocalScale = vec3(1,1,1); } { Transform* _53 = _0->addChild(new Transform()); _53->Name = std::string("Particle System"); _53->LocalPosition = vec3(0,3.5,-12.97); _53->LocalRotation = quat(0,0,0,1); _53->LocalScale = vec3(1,1,1); // duration: 25 // prewarm: True // startLifeTime: 25 // startSpeed: 1 // startSize: 8 // rateOverTime: 1.5 // time -> Color // 0 -> 1, 1, 1 // 1 -> 1, 1, 1 // time -> Alpha // 0 -> 0 // 0.05000382 -> 1 // 0.9499962 -> 1 // 1 -> 0 { Transform* ParticleBox = _53->addChild(new Transform()); ParticleBox->Name = std::string("ParticleBox"); ParticleBox->LocalPosition = vec3(0,0,0); ParticleBox->LocalRotation = quat(0,0,0,1); ParticleBox->LocalScale = vec3(25.5,10.05,1); } } { Transform* _54 = _0->addChild(new Transform()); _54->Name = std::string("rock03 (test)"); _54->LocalPosition = vec3(0,3.45,-4.37); _54->LocalRotation = quat(0,0,0,1); _54->LocalScale = vec3(1,1,1); } return _0; }
35.706507
128
0.643843
A-Ribeiro
a0b27076fdee24d494744cc2179e5a8c898e82bf
1,958
cpp
C++
src/base/resource_tracker.cpp
eido5/cubrid
f32dbe7cb90f096035c255d7b5f348438bbb5830
[ "Apache-2.0", "BSD-3-Clause" ]
253
2016-03-12T01:03:42.000Z
2022-03-14T08:24:39.000Z
src/base/resource_tracker.cpp
eido5/cubrid
f32dbe7cb90f096035c255d7b5f348438bbb5830
[ "Apache-2.0", "BSD-3-Clause" ]
1,124
2016-03-31T03:48:58.000Z
2022-03-31T23:44:04.000Z
src/base/resource_tracker.cpp
eido5/cubrid
f32dbe7cb90f096035c255d7b5f348438bbb5830
[ "Apache-2.0", "BSD-3-Clause" ]
268
2016-03-02T06:48:44.000Z
2022-03-04T05:17:24.000Z
/* * Copyright 2008 Search Solution Corporation * Copyright 2016 CUBRID Corporation * * 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. * */ /* * resource_tracker.cpp - implementation to track resource usage (allocations, page fixes) and detect leaks */ #include "resource_tracker.hpp" #include "error_manager.h" namespace cubbase { resource_tracker_item::resource_tracker_item (const char *fn_arg, int l_arg, unsigned reuse) : m_first_location (fn_arg, l_arg) , m_reuse_count (reuse) { // } std::ostream & operator<< (std::ostream &os, const resource_tracker_item &item) { os << "amount=" << item.m_reuse_count << " | first_caller=" << item.m_first_location; return os; } ////////////////////////////////////////////////////////////////////////// // debugging bool Restrack_has_error = false; bool Restrack_suppress_assert = false; bool restrack_pop_error (void) { bool ret = Restrack_has_error; Restrack_has_error = false; return ret; } void restrack_set_error (bool error) { Restrack_has_error = Restrack_has_error || error; } void restrack_set_suppress_assert (bool suppress) { Restrack_suppress_assert = suppress; } bool restrack_is_assert_suppressed (void) { return Restrack_suppress_assert; } void restrack_log (const std::string &str) { _er_log_debug (ARG_FILE_LINE, str.c_str ()); } } // namespace cubbase
24.17284
107
0.680286
eido5
a0b3efc0567d853a1c4a45b3551140878fcc8554
44,404
cpp
C++
nao_dcm_robot/nao_dcm_driver/src/nao.cpp
costashatz/nao_dcm
b3fc8656e5e8cc4cd354effa203a8cdfd926bf7c
[ "BSD-3-Clause" ]
10
2015-02-14T04:42:48.000Z
2022-02-28T17:35:38.000Z
nao_dcm_robot/nao_dcm_driver/src/nao.cpp
costashatz/nao_dcm
b3fc8656e5e8cc4cd354effa203a8cdfd926bf7c
[ "BSD-3-Clause" ]
2
2015-03-09T14:59:00.000Z
2016-04-08T16:50:50.000Z
nao_dcm_robot/nao_dcm_driver/src/nao.cpp
costashatz/nao_dcm
b3fc8656e5e8cc4cd354effa203a8cdfd926bf7c
[ "BSD-3-Clause" ]
6
2015-05-21T02:09:30.000Z
2021-04-27T14:26:58.000Z
/** Copyright (c) 2014-2015, Konstantinos Chatzilygeroudis 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. **/ #include <iostream> #include "nao_dcm_driver/nao.h" #include <alerror/alerror.h> #include <alcommon/albroker.h> #include <algorithm> Nao::Nao(boost::shared_ptr<AL::ALBroker> broker, const string &name) : AL::ALModule(broker,name),is_connected_(false) { setModuleDescription("Nao Robot Module"); functionName("brokerDisconnected", getName(), "Callback when broker disconnects!"); BIND_METHOD(Nao::brokerDisconnected); } Nao::~Nao() { if(is_connected_) disconnect(); } bool Nao::initialize() { // IMU Memory Keys const char* imu[] = {"Device/SubDeviceList/InertialSensor/AngleX/Sensor/Value", "Device/SubDeviceList/InertialSensor/AngleY/Sensor/Value", "Device/SubDeviceList/InertialSensor/AngleZ/Sensor/Value", "Device/SubDeviceList/InertialSensor/GyroscopeX/Sensor/Value", "Device/SubDeviceList/InertialSensor/GyroscopeY/Sensor/Value", "Device/SubDeviceList/InertialSensor/GyroscopeZ/Sensor/Value", "Device/SubDeviceList/InertialSensor/AccelerometerX/Sensor/Value", "Device/SubDeviceList/InertialSensor/AccelerometerY/Sensor/Value", "Device/SubDeviceList/InertialSensor/AccelerometerZ/Sensor/Value"}; imu_names_ = vector<string>(imu, end(imu)); // Sonar Memory Keys const char* sonar[] = {"Device/SubDeviceList/US/Left/Sensor/Value", "Device/SubDeviceList/US/Left/Sensor/Value1", "Device/SubDeviceList/US/Left/Sensor/Value2", "Device/SubDeviceList/US/Left/Sensor/Value3", "Device/SubDeviceList/US/Left/Sensor/Value4", "Device/SubDeviceList/US/Left/Sensor/Value5", "Device/SubDeviceList/US/Left/Sensor/Value6", "Device/SubDeviceList/US/Left/Sensor/Value7", "Device/SubDeviceList/US/Left/Sensor/Value8", "Device/SubDeviceList/US/Left/Sensor/Value9", "Device/SubDeviceList/US/Right/Sensor/Value", "Device/SubDeviceList/US/Right/Sensor/Value1", "Device/SubDeviceList/US/Right/Sensor/Value2", "Device/SubDeviceList/US/Right/Sensor/Value3", "Device/SubDeviceList/US/Right/Sensor/Value4", "Device/SubDeviceList/US/Right/Sensor/Value5", "Device/SubDeviceList/US/Right/Sensor/Value6", "Device/SubDeviceList/US/Right/Sensor/Value7", "Device/SubDeviceList/US/Right/Sensor/Value8", "Device/SubDeviceList/US/Right/Sensor/Value9"}; sonar_names_ = vector<string>(sonar, end(sonar)); // Foot Contact Memory Keys const char* fsr[] = {"Device/SubDeviceList/LFoot/FSR/FrontLeft/Sensor/Value", "Device/SubDeviceList/LFoot/FSR/FrontRight/Sensor/Value", "Device/SubDeviceList/LFoot/FSR/RearLeft/Sensor/Value", "Device/SubDeviceList/LFoot/FSR/RearRight/Sensor/Value", "Device/SubDeviceList/LFoot/FSR/TotalWeight/Sensor/Value", "Device/SubDeviceList/RFoot/FSR/FrontLeft/Sensor/Value", "Device/SubDeviceList/RFoot/FSR/FrontRight/Sensor/Value", "Device/SubDeviceList/RFoot/FSR/RearLeft/Sensor/Value", "Device/SubDeviceList/RFoot/FSR/RearRight/Sensor/Value", "Device/SubDeviceList/RFoot/FSR/TotalWeight/Sensor/Value", "Device/SubDeviceList/LFoot/FSR/CenterOfPressure/X/Sensor/Value", "Device/SubDeviceList/LFoot/FSR/CenterOfPressure/Y/Sensor/Value", "Device/SubDeviceList/RFoot/FSR/CenterOfPressure/X/Sensor/Value", "Device/SubDeviceList/RFoot/FSR/CenterOfPressure/Y/Sensor/Value"}; fsr_names_ = vector<string>(fsr, end(fsr)); // Tactile Memory Keys const char* tactile[] = {"Device/SubDeviceList/Head/Touch/Front/Sensor/Value", "Device/SubDeviceList/Head/Touch/Middle/Sensor/Value", "Device/SubDeviceList/Head/Touch/Rear/Sensor/Value", "Device/SubDeviceList/LHand/Touch/Back/Sensor/Value", "Device/SubDeviceList/LHand/Touch/Left/Sensor/Value", "Device/SubDeviceList/LHand/Touch/Right/Sensor/Value", "Device/SubDeviceList/RHand/Touch/Back/Sensor/Value", "Device/SubDeviceList/RHand/Touch/Left/Sensor/Value", "Device/SubDeviceList/RHand/Touch/Right/Sensor/Value"}; tactile_names_ = vector<string>(tactile, end(tactile)); // Bumper Memory Keys const char* bumper[] = {"Device/SubDeviceList/LFoot/Bumper/Left/Sensor/Value", "Device/SubDeviceList/LFoot/Bumper/Right/Sensor/Value", "Device/SubDeviceList/RFoot/Bumper/Left/Sensor/Value", "Device/SubDeviceList/RFoot/Bumper/Right/Sensor/Value"}; bumper_names_ = vector<string>(bumper, end(bumper)); // Battery Memory Keys const char* battery[] = {"Device/SubDeviceList/Battery/Charge/Sensor/Value", "Device/SubDeviceList/Battery/Temperature/Sensor/Value"}; battery_names_ = vector<string>(battery, end(battery)); // LED Memory Keys const char* led[] = {"Device/SubDeviceList/ChestBoard/Led/Blue/Actuator/Value", "Device/SubDeviceList/ChestBoard/Led/Green/Actuator/Value", "Device/SubDeviceList/ChestBoard/Led/Red/Actuator/Value", "Device/SubDeviceList/Ears/Led/Left/0Deg/Actuator/Value", "Device/SubDeviceList/Ears/Led/Left/108Deg/Actuator/Value", "Device/SubDeviceList/Ears/Led/Left/144Deg/Actuator/Value", "Device/SubDeviceList/Ears/Led/Left/180Deg/Actuator/Value", "Device/SubDeviceList/Ears/Led/Left/216Deg/Actuator/Value", "Device/SubDeviceList/Ears/Led/Left/252Deg/Actuator/Value", "Device/SubDeviceList/Ears/Led/Left/288Deg/Actuator/Value", "Device/SubDeviceList/Ears/Led/Left/324Deg/Actuator/Value", "Device/SubDeviceList/Ears/Led/Left/36Deg/Actuator/Value", "Device/SubDeviceList/Ears/Led/Left/72Deg/Actuator/Value", "Device/SubDeviceList/Ears/Led/Right/0Deg/Actuator/Value", "Device/SubDeviceList/Ears/Led/Right/108Deg/Actuator/Value", "Device/SubDeviceList/Ears/Led/Right/144Deg/Actuator/Value", "Device/SubDeviceList/Ears/Led/Right/180Deg/Actuator/Value", "Device/SubDeviceList/Ears/Led/Right/216Deg/Actuator/Value", "Device/SubDeviceList/Ears/Led/Right/252Deg/Actuator/Value", "Device/SubDeviceList/Ears/Led/Right/288Deg/Actuator/Value", "Device/SubDeviceList/Ears/Led/Right/324Deg/Actuator/Value", "Device/SubDeviceList/Ears/Led/Right/36Deg/Actuator/Value", "Device/SubDeviceList/Ears/Led/Right/72Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Blue/Left/0Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Blue/Left/135Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Blue/Left/180Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Blue/Left/225Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Blue/Left/270Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Blue/Left/315Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Blue/Left/45Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Blue/Left/90Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Blue/Right/0Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Blue/Right/135Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Blue/Right/180Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Blue/Right/225Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Blue/Right/270Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Blue/Right/315Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Blue/Right/45Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Blue/Right/90Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Green/Left/0Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Green/Left/135Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Green/Left/180Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Green/Left/225Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Green/Left/270Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Green/Left/315Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Green/Left/45Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Green/Left/90Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Green/Right/0Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Green/Right/135Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Green/Right/180Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Green/Right/225Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Green/Right/270Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Green/Right/315Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Green/Right/45Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Green/Right/90Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Red/Left/0Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Red/Left/135Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Red/Left/180Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Red/Left/225Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Red/Left/270Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Red/Left/315Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Red/Left/45Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Red/Left/90Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Red/Right/0Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Red/Right/135Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Red/Right/180Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Red/Right/225Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Red/Right/270Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Red/Right/315Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Red/Right/45Deg/Actuator/Value", "Device/SubDeviceList/Face/Led/Red/Right/90Deg/Actuator/Value", "Device/SubDeviceList/Head/Led/Front/Left/0/Actuator/Value", "Device/SubDeviceList/Head/Led/Front/Left/1/Actuator/Value", "Device/SubDeviceList/Head/Led/Front/Right/0/Actuator/Value", "Device/SubDeviceList/Head/Led/Front/Right/1/Actuator/Value", "Device/SubDeviceList/Head/Led/Middle/Left/0/Actuator/Value", "Device/SubDeviceList/Head/Led/Middle/Right/0/Actuator/Value", "Device/SubDeviceList/Head/Led/Rear/Left/0/Actuator/Value", "Device/SubDeviceList/Head/Led/Rear/Left/1/Actuator/Value", "Device/SubDeviceList/Head/Led/Rear/Left/2/Actuator/Value", "Device/SubDeviceList/Head/Led/Rear/Right/0/Actuator/Value", "Device/SubDeviceList/Head/Led/Rear/Right/1/Actuator/Value", "Device/SubDeviceList/Head/Led/Rear/Right/2/Actuator/Value", "Device/SubDeviceList/LFoot/Led/Blue/Actuator/Value", "Device/SubDeviceList/LFoot/Led/Green/Actuator/Value", "Device/SubDeviceList/LFoot/Led/Red/Actuator/Value", "Device/SubDeviceList/RFoot/Led/Blue/Actuator/Value", "Device/SubDeviceList/RFoot/Led/Green/Actuator/Value", "Device/SubDeviceList/RFoot/Led/Red/Actuator/Value"}; led_names_ = vector<string>(led, end(led)); // Joints Initialization const char* joint[] = {"HeadYaw", "HeadPitch", "LShoulderPitch", "LShoulderRoll", "LElbowYaw", "LElbowRoll", "LWristYaw", "LHand", "RShoulderPitch", "RShoulderRoll", "RElbowYaw", "RElbowRoll", "RWristYaw", "RHand", "LHipYawPitch", "RHipYawPitch", "LHipRoll", "LHipPitch", "LKneePitch", "LAnklePitch", "LAnkleRoll", "RHipRoll", "RHipPitch", "RKneePitch", "RAnklePitch", "RAnkleRoll"}; joint_names_ = vector<string>(joint, end(joint)); for(vector<string>::iterator it=joint_names_.begin();it!=joint_names_.end();it++) { if((*it=="RHand" || *it=="LHand" || *it == "RWristYaw" || *it == "LWristYaw") && (body_type_ == "H21")) { joint_names_.erase(it); it--; continue; } joints_names_.push_back("Device/SubDeviceList/"+(*it)+"/Position/Sensor/Value"); if(*it!="RHipYawPitch") { joint_temperature_names_.push_back("Device/SubDeviceList/"+(*it)+"/Temperature/Sensor/Value"); } } number_of_joints_ = joint_names_.size(); // DCM Motion Commands Initialization try { // Create Motion Command commands_.arraySetSize(4); commands_[0] = string("Joints"); commands_[1] = string("ClearAll"); commands_[2] = string("time-mixed"); commands_[3].arraySetSize(number_of_joints_); // Create Joints Actuators Alias AL::ALValue commandAlias; commandAlias.arraySetSize(2); commandAlias[0] = string("Joints"); commandAlias[1].arraySetSize(number_of_joints_); for(int i=0;i<number_of_joints_;i++) { commandAlias[1][i] = string("Device/SubDeviceList/"+joint_names_[i]+"/Position/Actuator/Value"); commands_[3][i].arraySetSize(1); commands_[3][i][0].arraySetSize(2); } dcm_proxy_.createAlias(commandAlias); // Create Joints Hardness Alias commandAlias[0] = string("JointsHardness"); commandAlias[1].arraySetSize(number_of_joints_-1); int k = 0; for(int i=0;i<number_of_joints_;i++) { if(joint_names_[i] == "RHipYawPitch") { k = -1; i++; } commandAlias[1][i+k] = string("Device/SubDeviceList/"+joint_names_[i]+"/Hardness/Actuator/Value"); } dcm_proxy_.createAlias(commandAlias); // Create LEDs Alias commandAlias[0] = string("Leds"); commandAlias[1].arraySetSize(89); for(int i=0;i<89;i++) { commandAlias[1][i] = led_names_[i]; } dcm_proxy_.createAlias(commandAlias); } catch(const AL::ALError& e) { ROS_ERROR("Could not initialize dcm aliases!\n\tTrace: %s",e.what()); return false; } // Turn Stiffness On vector<float> stiff = vector<float>(number_of_joints_-1,1.0f); vector<int> times = vector<int>(number_of_joints_-1,0); DCMAliasTimedCommand("JointsHardness",stiff, times); stiffnesses_enabled_ = true; // Add diagnostic functions diagnostic_.setHardwareID(string("Nao")+version_+body_type_); diagnostic_.add("Joints Temperature", this, &Nao::checkTemperature); diagnostic_.add("Battery", this, &Nao::checkBattery); return true; } bool Nao::initializeControllers(controller_manager::ControllerManager& cm) { if(!initialize()) { ROS_ERROR("Initialization method failed!"); return false; } // Initialize Controllers' Interfaces joint_angles_.resize(number_of_joints_); joint_velocities_.resize(number_of_joints_); joint_efforts_.resize(number_of_joints_); joint_commands_.resize(number_of_joints_); try { for(int i=0;i<number_of_joints_;i++) { hardware_interface::JointStateHandle state_handle(joint_names_[i], &joint_angles_[i], &joint_velocities_[i], &joint_efforts_[i]); jnt_state_interface_.registerHandle(state_handle); hardware_interface::JointHandle pos_handle(jnt_state_interface_.getHandle(joint_names_[i]), &joint_commands_[i]); jnt_pos_interface_.registerHandle(pos_handle); } registerInterface(&jnt_state_interface_); registerInterface(&jnt_pos_interface_); } catch(const ros::Exception& e) { ROS_ERROR("Could not initialize hardware interfaces!\n\tTrace: %s",e.what()); return false; } ROS_INFO("Nao Module initialized!"); return true; } bool Nao::connect(const ros::NodeHandle nh) { // Initialize ROS nodes node_handle_ = nh; is_connected_ = false; // Load ROS Parameters loadParams(); // Needed for Error Checking try { subscribeToMicroEvent("ClientDisconnected", "Nao", "brokerDisconnected"); } catch (const AL::ALError& e) { ROS_ERROR("Could not subscribe to brokerDisconnected!\n\tTrace: %s",e.what()); } // Initialize DCM Proxy try { dcm_proxy_ = AL::DCMProxy(getParentBroker()); } catch (const AL::ALError& e) { ROS_ERROR("Failed to connect to DCM Proxy!\n\tTrace: %s",e.what()); return false; } // Initialize Memory Proxy try { memory_proxy_ = AL::ALMemoryProxy(getParentBroker()); } catch (const AL::ALError& e) { ROS_ERROR("Failed to connect to Memory Proxy!\n\tTrace: %s",e.what()); return false; } is_connected_ = true; // Subscribe/Publish ROS Topics/Services subscribe(); // Initialize Controller Manager and Controllers manager_ = new controller_manager::ControllerManager(this,node_handle_); if(!initializeControllers(*manager_)) { ROS_ERROR("Could not load controllers!"); return false; } ROS_INFO("Controllers successfully loaded!"); return true; } void Nao::disconnect() { if(!is_connected_) return; try { unsubscribeFromMicroEvent("ClientDisconnected", "Nao"); } catch (const AL::ALError& e) { ROS_ERROR("Failed to unsubscribe from subscribed events!\n\tTrace: %s",e.what()); } is_connected_ = false; } void Nao::subscribe() { // Subscribe/Publish ROS Topics/Services cmd_vel_sub_ = node_handle_.subscribe(prefix_+"cmd_vel", topic_queue_, &Nao::commandVelocity, this); imu_pub_ = node_handle_.advertise<sensor_msgs::Imu>(prefix_+"imu_data", topic_queue_); sonar_left_pub_ = node_handle_.advertise<sensor_msgs::Range>(prefix_+"sonar_left", topic_queue_); sonar_left_.header.frame_id = "LSonar_frame"; sonar_left_.radiation_type = sensor_msgs::Range::ULTRASOUND; sonar_left_.field_of_view = 1.04719755f; sonar_left_.min_range = 0.25; sonar_left_.max_range = 2.55; sonar_right_pub_ = node_handle_.advertise<sensor_msgs::Range>(prefix_+"sonar_right", topic_queue_); sonar_right_.header.frame_id = "RSonar_frame"; sonar_right_.radiation_type = sensor_msgs::Range::ULTRASOUND; sonar_right_.field_of_view = 1.04719755f; sonar_right_.min_range = 0.25; sonar_right_.max_range = 2.55; sonar_switch_ = node_handle_.advertiseService<Nao, nao_dcm_msgs::BoolService::Request, nao_dcm_msgs::BoolService::Response>(prefix_+"Sonar/Enable", &Nao::switchSonar, this); fsrs_pub_ = node_handle_.advertise<nao_dcm_msgs::FSRs>(prefix_+"fsrs", topic_queue_); fsrs_switch_ = node_handle_.advertiseService<Nao, nao_dcm_msgs::BoolService::Request, nao_dcm_msgs::BoolService::Response>(prefix_+"FSRs/Enable", &Nao::switchFSR, this); bumpers_pub_ = node_handle_.advertise<nao_dcm_msgs::Bumper>(prefix_+"bumpers", topic_queue_); bumpers_switch_ = node_handle_.advertiseService<Nao, nao_dcm_msgs::BoolService::Request, nao_dcm_msgs::BoolService::Response>(prefix_+"Bumpers/Enable", &Nao::switchBumper, this); tactiles_pub_ = node_handle_.advertise<nao_dcm_msgs::Tactile>(prefix_+"tactiles", topic_queue_); tactiles_switch_ = node_handle_.advertiseService<Nao, nao_dcm_msgs::BoolService::Request, nao_dcm_msgs::BoolService::Response>(prefix_+"Tactiles/Enable", &Nao::switchTactile, this); stiffness_pub_ = node_handle_.advertise<std_msgs::Float32>(prefix_+"stiffnesses", topic_queue_); stiffness_.data = 1.0f; stiffness_switch_ = node_handle_.advertiseService<Nao, nao_dcm_msgs::BoolService::Request, nao_dcm_msgs::BoolService::Response>(prefix_+"Stiffnesses/Enable", &Nao::switchStiffnesses, this); } void Nao::loadParams() { ros::NodeHandle n_p("~"); // Load Server Parameters n_p.param("Version", version_, string("V4")); n_p.param("BodyType", body_type_, string("H25")); n_p.param("TactilesEnabled", tactiles_enabled_, true); n_p.param("BumpersEnabled", bumpers_enabled_, true); n_p.param("SonarEnabled", sonar_enabled_, true); n_p.param("FootContactsEnabled", foot_contacts_enabled_, true); n_p.param("PublishIMU", imu_published_, true); n_p.param("TopicQueue", topic_queue_, 50); n_p.param("Prefix", prefix_, string("nao_dcm")); prefix_ = prefix_+"/"; n_p.param("LowCommunicationFrequency", low_freq_, 10.0); n_p.param("HighCommunicationFrequency", high_freq_, 100.0); n_p.param("ControllerFrequency", controller_freq_, 15.0); n_p.param("JointPrecision", joint_precision_, 0.00174532925); n_p.param("OdomFrame", odom_frame_, string("odom")); } void Nao::brokerDisconnected(const string& event_name, const string &broker_name, const string& subscriber_identifier) { if(broker_name == "Nao Driver Broker") is_connected_ = false; } void Nao::DCMTimedCommand(const string &key, const AL::ALValue &value, const int &timeOffset, const string &type) { try { // Create timed-command AL::ALValue command; command.arraySetSize(3); command[0] = key; command[1] = type; command[2].arraySetSize(1); command[2][0].arraySetSize(2); command[2][0][0] = value; command[2][0][1] = dcm_proxy_.getTime(timeOffset); // Execute timed-command dcm_proxy_.set(command); } catch(const AL::ALError& e) { ROS_ERROR("Could not execute DCM timed-command!\n\t%s\n\n\tTrace: %s", key.c_str(), e.what()); } } void Nao::DCMAliasTimedCommand(const string &alias, const vector<float> &values, const vector<int> &timeOffsets, const string &type, const string &type2) { try { // Create Alias timed-command AL::ALValue command; command.arraySetSize(4); command[0] = alias; command[1] = type; command[2] = type2; command[3].arraySetSize(values.size()); int T = dcm_proxy_.getTime(0); for(int i=0;i<values.size();i++) { command[3][i].arraySetSize(1); command[3][i][0].arraySetSize(2); command[3][i][0][0] = values[i]; command[3][i][0][1] = T+timeOffsets[i]; } // Execute Alias timed-command dcm_proxy_.setAlias(command); } catch(const AL::ALError& e) { ROS_ERROR("Could not execute DCM timed-command!\n\t%s\n\n\tTrace: %s", alias.c_str(), e.what()); } } void Nao::insertDataToMemory(const string &key, const AL::ALValue &value) { memory_proxy_.insertData(key,value); } AL::ALValue Nao::getDataFromMemory(const string &key) { return memory_proxy_.getData(key); } void Nao::subscribeToEvent(const string &name, const string &callback_module, const string &callback_method) { try { memory_proxy_.subscribeToEvent(name,callback_module,"",callback_method); } catch(const AL::ALError& e) { ROS_ERROR("Could not subscribe to event '%s'.\n\tTrace: %s",name.c_str(),e.what()); } } void Nao::subscribeToMicroEvent(const string &name, const string &callback_module, const string &callback_method, const string &callback_message) { try { memory_proxy_.subscribeToMicroEvent(name,callback_module,callback_message,callback_method); } catch(const AL::ALError& e) { ROS_ERROR("Could not subscribe to micro-event '%s'.\n\tTrace: %s",name.c_str(),e.what()); } } void Nao::unsubscribeFromEvent(const string &name, const string &callback_module) { try { memory_proxy_.unsubscribeToEvent(name,callback_module); } catch(const AL::ALError& e) { ROS_ERROR("Could not unsubscribe from event '%s'.\n\tTrace: %s",name.c_str(),e.what()); } } void Nao::unsubscribeFromMicroEvent(const string &name, const string &callback_module) { try { memory_proxy_.unsubscribeToMicroEvent(name,callback_module); } catch(const AL::ALError& e) { ROS_ERROR("Could not unsubscribe from micro-event '%s'.\n\tTrace: %s",name.c_str(),e.what()); } } void Nao::raiseEvent(const string &name, const AL::ALValue &value) { try { memory_proxy_.raiseEvent(name,value); } catch(const AL::ALError& e) { ROS_ERROR("Could not raise event '%s'.\n\tTrace: %s",name.c_str(),e.what()); } } void Nao::raiseMicroEvent(const string &name, const AL::ALValue &value) { try { memory_proxy_.raiseMicroEvent(name,value); } catch(const AL::ALError& e) { ROS_ERROR("Could not raise micro-event '%s'.\n\tTrace: %s",name.c_str(),e.what()); } } void Nao::declareEvent(const string &name) { try { memory_proxy_.declareEvent(name); } catch(AL::ALError& e) { ROS_ERROR("Could not declare event '%s'.\n\tTrace: %s",name.c_str(),e.what()); } } void Nao::run() { boost::thread t1(&Nao::controllerLoop,this); boost::thread t2(&Nao::lowCommunicationLoop,this); boost::thread t3(&Nao::highCommunicationLoop,this); t1.join(); t2.join(); t3.join(); } void Nao::lowCommunicationLoop() { static ros::Rate rate(low_freq_); while(ros::ok()) { ros::Time time = ros::Time::now(); if(!is_connected_) break; publishBaseFootprint(time); if(sonar_enabled_) checkSonar(); if(foot_contacts_enabled_) checkFSR(); if(tactiles_enabled_) checkTactile(); if(bumpers_enabled_) checkBumper(); if(stiffnesses_enabled_) { stiffness_.data = 1.0f; } else { stiffness_.data = 0.0f; } stiffness_pub_.publish(stiffness_); diagnostic_.update(); rate.sleep(); } } void Nao::highCommunicationLoop() { static ros::Rate rate(high_freq_); while(ros::ok()) { ros::Time time = ros::Time::now(); if(!is_connected_) break; if(imu_published_) publishIMU(time); try { dcm_proxy_.ping(); } catch(const AL::ALError& e) { ROS_ERROR("Could not ping DCM proxy.\n\tTrace: %s",e.what()); is_connected_ = false; } rate.sleep(); } } void Nao::controllerLoop() { static ros::Rate rate(controller_freq_+10.0); while(ros::ok()) { ros::Time time = ros::Time::now(); if(!is_connected_) break; readJoints(); manager_->update(time,ros::Duration(1.0f/controller_freq_)); writeJoints(); rate.sleep(); } } bool Nao::connected() { return is_connected_; } void Nao::commandVelocity(const geometry_msgs::TwistConstPtr &msg) { ROS_WARN("This function does nothing at the moment.."); } void Nao::publishIMU(const ros::Time &ts) { vector<float> memData; try { memData = memory_proxy_.getListData(imu_names_); } catch(const AL::ALError& e) { ROS_ERROR("Could not get IMU data from Nao.\n\tTrace: %s",e.what()); return; } if (memData.size() != imu_names_.size()) { ROS_ERROR("IMU readings' size is not correct!"); return; } imu_.header.stamp = ts; imu_.header.frame_id = "torso"; float angleX = memData[0]; float angleY = memData[1]; float angleZ = memData[2]; float gyroX = memData[3]; float gyroY = memData[4]; float gyroZ = memData[5]; float accX = memData[6]; float accY = memData[7]; float accZ = memData[8]; imu_.orientation = tf::createQuaternionMsgFromRollPitchYaw(angleX,angleY,angleZ); imu_.angular_velocity.x = gyroX; imu_.angular_velocity.y = gyroY; imu_.angular_velocity.z = gyroZ; imu_.linear_acceleration.x = accX; imu_.linear_acceleration.y = accY; imu_.linear_acceleration.z = accZ; // covariances unknown imu_.orientation_covariance[0] = 0; imu_.angular_velocity_covariance[0] = 0; imu_.linear_acceleration_covariance[0] = 0; imu_pub_.publish(imu_); } void Nao::publishBaseFootprint(const ros::Time &ts) { string odom_frame, l_sole_frame, r_sole_frame, base_link_frame; try { odom_frame = base_footprint_listener_.resolve(odom_frame_); l_sole_frame = base_footprint_listener_.resolve("l_sole"); r_sole_frame = base_footprint_listener_.resolve("r_sole"); base_link_frame = base_footprint_listener_.resolve("base_link"); } catch(ros::Exception& e) { ROS_ERROR("%s",e.what()); return; } tf::StampedTransform tf_odom_to_base, tf_odom_to_left_foot, tf_odom_to_right_foot; double temp_freq = 1.0f/(10.0*high_freq_); if(!base_footprint_listener_.waitForTransform(odom_frame, l_sole_frame, ros::Time(0), ros::Duration(temp_freq))) return; try { base_footprint_listener_.lookupTransform(odom_frame, l_sole_frame, ros::Time(0), tf_odom_to_left_foot); base_footprint_listener_.lookupTransform(odom_frame, r_sole_frame, ros::Time(0), tf_odom_to_right_foot); base_footprint_listener_.lookupTransform(odom_frame, base_link_frame, ros::Time(0), tf_odom_to_base); } catch (const tf::TransformException& ex){ ROS_ERROR("%s",ex.what()); return ; } tf::Vector3 new_origin = (tf_odom_to_right_foot.getOrigin() + tf_odom_to_left_foot.getOrigin())/2.0; double height = std::min(tf_odom_to_left_foot.getOrigin().getZ(), tf_odom_to_right_foot.getOrigin().getZ()); new_origin.setZ(height); double roll, pitch, yaw; tf_odom_to_base.getBasis().getRPY(roll, pitch, yaw); tf::Transform tf_odom_to_footprint(tf::createQuaternionFromYaw(yaw), new_origin); tf::Transform tf_base_to_footprint = tf_odom_to_base.inverse() * tf_odom_to_footprint; base_footprint_broadcaster_.sendTransform(tf::StampedTransform(tf_base_to_footprint, ts, base_link_frame, "base_footprint")); } void Nao::readJoints() { vector<float> jointData; try { jointData = memory_proxy_.getListData(joints_names_); } catch(const AL::ALError& e) { ROS_ERROR("Could not get joint data from Nao.\n\tTrace: %s",e.what()); return; } for(short i = 0; i<jointData.size(); i++) { joint_angles_[i] = jointData[i]; // Set commands to the read angles for when no command specified joint_commands_[i] = jointData[i]; } } void Nao::writeJoints() { // Update joints only when actual command is issued bool changed = false; for(int i=0;i<number_of_joints_;i++) { if(fabs(joint_commands_[i]-joint_angles_[i])>joint_precision_) { changed = true; break; } } // Do not write joints if no change in joint values if(!changed) { return; } try { int T = dcm_proxy_.getTime(0); for(int i=0;i<number_of_joints_;i++) { commands_[3][i][0][0] = float(joint_commands_[i]); commands_[3][i][0][1] = T+(int)(800.0f/controller_freq_); } dcm_proxy_.setAlias(commands_); } catch(const AL::ALError& e) { ROS_ERROR("Could not send joint commands to Nao.\n\tTrace: %s",e.what()); return; } } bool Nao::switchSonar(nao_dcm_msgs::BoolService::Request &req, nao_dcm_msgs::BoolService::Response &res) { sonar_enabled_ = req.enable; return true; } bool Nao::switchFSR(nao_dcm_msgs::BoolService::Request &req, nao_dcm_msgs::BoolService::Response &res) { foot_contacts_enabled_ = req.enable; return true; } bool Nao::switchBumper(nao_dcm_msgs::BoolService::Request &req, nao_dcm_msgs::BoolService::Response &res) { bumpers_enabled_ = req.enable; return true; } bool Nao::switchTactile(nao_dcm_msgs::BoolService::Request &req, nao_dcm_msgs::BoolService::Response &res) { tactiles_enabled_ = req.enable; return true; } bool Nao::switchStiffnesses(nao_dcm_msgs::BoolService::Request &req, nao_dcm_msgs::BoolService::Response &res) { if(stiffnesses_enabled_!=req.enable && req.enable) { DCMAliasTimedCommand("JointsHardness",vector<float>(number_of_joints_,1.0f), vector<int>(number_of_joints_,0)); } else if(stiffnesses_enabled_!=req.enable) { DCMAliasTimedCommand("JointsHardness",vector<float>(number_of_joints_,0.0f), vector<int>(number_of_joints_,0)); } stiffnesses_enabled_ = req.enable; } void Nao::checkSonar() { // Send Sonar Wave DCMTimedCommand("Device/SubDeviceList/US/Actuator/Value",4.0f,0); // Read Sonar Values AL::ALValue sonars; try { sonars = memory_proxy_.getListData(sonar_names_); } catch(const AL::ALError& e) { ROS_ERROR("Could not get sonar values.\n\tTrace: %s",e.what()); return; } // Select closer object detected float sonar_left = float(sonars[0]), sonar_right = float(sonars[10]); for(short i=1;i<10;i++) { if(float(sonars[i])>=0.0f && float(sonars[i])<=2.55f && float(sonars[i])<sonar_left) { sonar_left = float(sonars[i]); } if(float(sonars[10+i])>=0.0f && float(sonars[10+i])<=2.55f && float(sonars[10+i])<sonar_right) { sonar_right = float(sonars[10+i]); } } sonar_left_.range = sonar_left; sonar_left_pub_.publish(sonar_left_); sonar_right_.range = sonar_right; sonar_right_pub_.publish(sonar_right_); } void Nao::checkFSR() { AL::ALValue fsrs; try { fsrs = memory_proxy_.getListData(fsr_names_); } catch(const AL::ALError& e) { ROS_ERROR("Could not get FSR values.\n\tTrace: %s",e.what()); return; } fsrs_.LeftFrontLeft = float(fsrs[0]); fsrs_.LeftFrontRight = float(fsrs[1]); fsrs_.LeftRearLeft = float(fsrs[2]); fsrs_.LeftRearRight = float(fsrs[3]); fsrs_.LeftTotalWeight = float(fsrs[4]); fsrs_.LeftCOPx = float(fsrs[10]); fsrs_.LeftCOPy = float(fsrs[11]); fsrs_.RightFrontLeft = float(fsrs[5]); fsrs_.RightFrontRight = float(fsrs[6]); fsrs_.RightRearLeft = float(fsrs[7]); fsrs_.RightRearRight = float(fsrs[8]); fsrs_.RightTotalWeight = float(fsrs[9]); fsrs_.RightCOPx = float(fsrs[12]); fsrs_.RightCOPy = float(fsrs[13]); fsrs_pub_.publish(fsrs_); } void Nao::checkTactile() { AL::ALValue tactiles; try { tactiles = memory_proxy_.getListData(tactile_names_); } catch(const AL::ALError& e) { ROS_ERROR("Could not get Tactile values.\n\tTrace: %s",e.what()); return; } tactiles_.HeadTouchFront = int(float(tactiles[0])); tactiles_.HeadTouchMiddle = int(float(tactiles[1])); tactiles_.HeadTouchRear = int(float(tactiles[2])); tactiles_.LeftTouchBack = int(float(tactiles[3])); tactiles_.LeftTouchLeft = int(float(tactiles[4])); tactiles_.LeftTouchRight = int(float(tactiles[5])); tactiles_.RightTouchBack = int(float(tactiles[6])); tactiles_.RightTouchLeft = int(float(tactiles[7])); tactiles_.RightTouchRight = int(float(tactiles[8])); tactiles_pub_.publish(tactiles_); } void Nao::checkBumper() { AL::ALValue bumpers; try { bumpers = memory_proxy_.getListData(bumper_names_); } catch(const AL::ALError& e) { ROS_ERROR("Could not get Tactile values.\n\tTrace: %s",e.what()); return; } bumpers_.LeftFootLeft = int(float(bumpers[0])); bumpers_.LeftFootRight = int(float(bumpers[1])); bumpers_.RightFootLeft = int(float(bumpers[2])); bumpers_.RightFootRight = int(float(bumpers[3])); bumpers_pub_.publish(bumpers_); } void Nao::checkTemperature(diagnostic_updater::DiagnosticStatusWrapper &stat) { AL::ALValue temps; try { temps = memory_proxy_.getListData(joint_temperature_names_); } catch(const AL::ALError& e) { ROS_ERROR("Could not get Temperature values.\n\tTrace: %s",e.what()); return; } stat.summary(diagnostic_msgs::DiagnosticStatus::OK, "Joints Temperature: OK!"); for(short i=0;i<temps.getSize();i++) { if(float(temps[i])>=70.0f) stat.summary(diagnostic_msgs::DiagnosticStatus::WARN, "Joints Temperature: WARNING!"); if(float(temps[i])>=85.0f) stat.summary(diagnostic_msgs::DiagnosticStatus::ERROR, "Joints Temperature: CRITICAL!"); string joint_name = string(joint_temperature_names_[i]).erase(0,21); short l = joint_name.find('/',joint_name.find('/')); joint_name.erase(l,25); stat.add(joint_name,temps[i]); } } void Nao::checkBattery(diagnostic_updater::DiagnosticStatusWrapper &stat) { AL::ALValue batt; try { batt = memory_proxy_.getListData(battery_names_); } catch(const AL::ALError& e) { ROS_ERROR("Could not get Battery values.\n\tTrace: %s",e.what()); return; } int status = 0; string message = "Battery: "+boost::lexical_cast<string>(float(batt[0])*100.0f)+"\% charged! "; if(float(batt[0])*100.0f<50.0f) status = 1; else if(float(batt[0])*100.0f<20.0f) status = 2; if(float(batt[1])>=60.0f) { status = 1; message += "Temperature: WARNING!"; } else if(float(batt[1])>=70.0f) { status = 2; message += "Temperature: CRITICAL!"; } else { message += "Temperature: OK!"; } stat.summary(status,message); stat.add("Battery Charge",float(batt[0])*100.0f); stat.add("Battery Temperature", float(batt[1])); }
38.848644
142
0.587064
costashatz
a0b4c2f1c8c4ede43931ff2b88bab70625ddb861
703
cpp
C++
sample-source/OPENCVBook/chapter03/3.6.1 Staturate Cast/saturate_cast.cpp
doukhee/opencv-study
b7e8a5c916070ebc762c33d7fe307b6fcf88abf4
[ "MIT" ]
null
null
null
sample-source/OPENCVBook/chapter03/3.6.1 Staturate Cast/saturate_cast.cpp
doukhee/opencv-study
b7e8a5c916070ebc762c33d7fe307b6fcf88abf4
[ "MIT" ]
null
null
null
sample-source/OPENCVBook/chapter03/3.6.1 Staturate Cast/saturate_cast.cpp
doukhee/opencv-study
b7e8a5c916070ebc762c33d7fe307b6fcf88abf4
[ "MIT" ]
null
null
null
#include <opencv2/opencv.hpp> using namespace std; using namespace cv; int main() { /** * I(x, t)= min(max(round(r), 0),255) * 포화 산술 연산 - 어떤 연산의 결과 값을 8비트로 저장을 한다고 할때, * 8비트 제한 범위를 넘으면 () 또는 255 가운데 가까운 값을 사용하는 것이다. * OpenCV에서는 행렬에 대해서 연산을 할 경우에는 기본적으로 포화 산술이 적용 된다. */ /* Matx 객체 선언 */ Matx<uchar, 2, 2> m1; Matx<ushort, 2, 2> m2; m1(0, 0) = -50; m1(0, 1) = 300; m1(1, 0) = saturate_cast<uchar>(-50); m1(1, 1) = saturate_cast<uchar>(300); m2(0, 0) = -50; m2(0, 1) = 80000; /* 포화 산술 연산을 적용 하는 것 */ m2(1, 0) = saturate_cast<unsigned short>(-50); m2(1, 1) = saturate_cast<unsigned short>(80000); cout<<"[m1]="<<endl<<m1<<endl; cout<<"[m2]="<<endl<<m2<<endl; return 0; }
20.085714
53
0.578947
doukhee
a0b4e74e9aae6ad8bc56ad444e3d61562465cb85
2,356
cpp
C++
fuzz-tests/primes.cpp
deadpool2794/Cp
26eab96ef8ea336615fa8d6fadaa8e4d7d6f3a3c
[ "MIT" ]
152
2019-04-09T18:26:41.000Z
2022-03-20T23:19:41.000Z
fuzz-tests/primes.cpp
deadpool2794/Cp
26eab96ef8ea336615fa8d6fadaa8e4d7d6f3a3c
[ "MIT" ]
1
2020-12-29T03:02:22.000Z
2020-12-29T03:02:22.000Z
fuzz-tests/primes.cpp
deadpool2794/Cp
26eab96ef8ea336615fa8d6fadaa8e4d7d6f3a3c
[ "MIT" ]
36
2019-11-28T09:27:01.000Z
2022-03-10T18:22:13.000Z
#include <bits/stdc++.h> using namespace std; #define rep(i, a, b) for(int i = a; i < int(b); ++i) #define trav(a, v) for(auto& a : v) #define all(x) x.begin(), x.end() #define sz(x) (int)(x).size() typedef long long ll; typedef pair<int, int> pii; typedef vector<int> vi; struct prime_sieve { typedef unsigned char uchar; typedef unsigned int uint; static const int pregen = 3*5*7*11*13; uint n, sqrtn; uchar *isprime; int *prime, primes; // prime[i] is i:th prime bool is_prime(int n) { // primality check if(n%2==0 || n<=2) return n==2; return isprime[(n-3)>>4] & 1 << ((n-3) >> 1&7); } prime_sieve(int _n) : n(_n), sqrtn((int)ceil(sqrt(1.0*n))) { int n0 = max(n>>4, (uint)pregen) + 1; prime = new int[max(2775, (int)(1.12*n/log(1.0*n)))]; prime[0]=2; prime[1]=3; prime[2]=5; prime[3]=7; prime[4]=11; prime[5]=13; primes=6; isprime = new uchar[n0]; memset(isprime, 255, n0); for(int j=1,p=prime[j];j<6;p=prime[++j]) for(int i=(p*p-3)>>4,s=(p*p-3)>>1&7; i<=pregen; i+= (s+=p)>>3, s&=7) isprime[i] &= (uchar)~(1<<s); for(int d=pregen, b=pregen+1; b<n0; b+=d,d<<=1) memcpy(isprime+b,isprime+1,(n0<b+d)?n0-b:d); for(uint p=17,i=0,s=7; p<n; p+=2, i+= ++s>>3, s&=7) if(isprime[i]&1<<s) { prime[primes++] = p; if(p<sqrtn) { int ii=i, ss=s+(p-1)*p/2; for(uint pp=p*p; pp<n; pp+=p<<1, ss+=p) { ii += ss>>3; ss &=7; isprime[ii] &= (uchar)~(1<<ss); } } } } }; const int MAX_PR = 100000000; #if 1 bitset<MAX_PR/2> isprime; vi eratosthenes_sieve(int lim) { isprime.set(); for (int i = 3; i*i < lim; i += 2) if (isprime[i >> 1]) for (int j = i*i; j < lim; j += 2*i) isprime[j >> 1] = 0; vi pr; if (lim >= 2) pr.push_back(2); for (int i = 3; i < lim; i += 2) if (isprime[i>>1]) pr.push_back(i); return pr; } #else bitset<MAX_PR> isprime; vi eratosthenes_sieve(int lim) { isprime.set(); isprime[0] = isprime[1] = 0; for (int i = 4; i < lim; i += 2) isprime[i] = 0; for (int i = 3; i*i < lim; i += 2) if (isprime[i]) for (int j = i*i; j < lim; j += i*2) isprime[j] = 0; vi pr; rep(i,2,lim) if (isprime[i]) pr.push_back(i); return pr; } #endif int main(int argc, char** argv) { ll s = 0, s2 = 0; prime_sieve ps(MAX_PR); rep(i,0,ps.primes) s += ps.prime[i]; vi r = eratosthenes_sieve(MAX_PR); trav(x, r) s2 += x; cout << s << ' ' << s2 << endl; }
25.89011
61
0.556452
deadpool2794
a0b58e750d7ea2bbcada23de261f787acfef5267
5,813
cpp
C++
digital/PreambleCorrelator.cpp
willcode/PothosComms
6c6ae8ccb6a9c996a67e2ca646aff79c74bb83fa
[ "BSL-1.0" ]
14
2017-10-28T08:40:08.000Z
2022-03-19T06:08:55.000Z
digital/PreambleCorrelator.cpp
BelmY/PothosComms
9aa48b827b3813b3ba2b98773f3359b30ebce346
[ "BSL-1.0" ]
22
2015-08-25T21:18:13.000Z
2016-12-31T02:23:47.000Z
digital/PreambleCorrelator.cpp
pothosware/pothos-comms
cff998cca2c9610d3e7e5480fd4fc692c13d3066
[ "BSL-1.0" ]
13
2018-01-03T15:29:44.000Z
2022-03-19T06:09:00.000Z
// Copyright (c) 2015-2017 Josh Blum // SPDX-License-Identifier: BSL-1.0 #include <Pothos/Framework.hpp> #include <cstdint> #include <complex> #include <cassert> #include <iostream> //provide __popcnt() #ifdef _MSC_VER # include <intrin.h> #elif __GNUC__ # define __popcnt __builtin_popcount #else # error "provide __popcnt() for this compiler" #endif /*********************************************************************** * |PothosDoc Preamble Correlator * * The Preamble Correlator searches an input symbol stream on port 0 * for a matching pattern and forwards the stream to output port 0 * with a label annotating the first symbol after the preamble match. * * This block supports operations on arbitrary symbol widths, * and therefore it may be used operationally on a bit-stream, * because a bit-stream is identically a symbol stream of N=1. * * http://en.wikipedia.org/wiki/Hamming_distance * * |category /Digital * |keywords bit symbol preamble correlate * |alias /blocks/preamble_correlator * * |param preamble A vector of symbols representing the preamble. * The width of each preamble symbol must the intended input stream. * |default [1] * * |param thresh[Threshold] The threshold hamming distance for preamble match detection. * |default 0 * * |param frameStartId[Frame Start ID] The label ID that marks the first symbol of a correlator match. * |default "frameStart" * |widget StringEntry() * * |factory /comms/preamble_correlator() * |setter setPreamble(preamble) * |setter setThreshold(thresh) * |setter setFrameStartId(frameStartId) **********************************************************************/ class PreambleCorrelator : public Pothos::Block { public: static Block *make(void) { return new PreambleCorrelator(); } PreambleCorrelator(void): _threshold(0) { this->setupInput(0, typeid(unsigned char)); this->setupOutput(0, typeid(unsigned char), this->uid()); //unique domain because of buffer forwarding //this->setupOutput(1, typeid(unsigned)); this->registerCall(this, POTHOS_FCN_TUPLE(PreambleCorrelator, setPreamble)); this->registerCall(this, POTHOS_FCN_TUPLE(PreambleCorrelator, getPreamble)); this->registerCall(this, POTHOS_FCN_TUPLE(PreambleCorrelator, setThreshold)); this->registerCall(this, POTHOS_FCN_TUPLE(PreambleCorrelator, getThreshold)); this->registerCall(this, POTHOS_FCN_TUPLE(PreambleCorrelator, setFrameStartId)); this->registerCall(this, POTHOS_FCN_TUPLE(PreambleCorrelator, getFrameStartId)); this->setPreamble(std::vector<unsigned char>(1, 1)); //initial update this->setThreshold(1); //initial update this->setFrameStartId("frameStart"); //initial update } void setPreamble(const std::vector<unsigned char> preamble) { if (preamble.empty()) throw Pothos::InvalidArgumentException("PreambleCorrelator::setPreamble()", "preamble cannot be empty"); _preamble = preamble; } std::vector<unsigned char> getPreamble(void) const { return _preamble; } void setThreshold(const unsigned threshold) { _threshold = threshold; } unsigned getThreshold(void) const { return _threshold; } void setFrameStartId(std::string id) { _frameStartId = id; } std::string getFrameStartId(void) const { return _frameStartId; } //! always use a circular buffer to avoid discontinuity over sliding window Pothos::BufferManager::Sptr getInputBufferManager(const std::string &, const std::string &) { return Pothos::BufferManager::make("circular"); } void work(void) { auto inputPort = this->input(0); auto outputPort = this->output(0); //auto outputDistance = this->output(1); //require preamble size + 1 elements to perform processing inputPort->setReserve(_preamble.size()+1); auto buffer = inputPort->takeBuffer(); if (buffer.length <= (size_t) _preamble.size()) return; //due to search window, the last preamble size elements are used //consume and forward all processable elements of the input buffer buffer.length -= _preamble.size(); inputPort->consume(buffer.length); // Calculate Hamming distance at each position looking for match // When a match is found a label is created after the preamble unsigned char *in = buffer; //auto distance = outputDistance->buffer().template as<unsigned *>(); for (size_t n = 0; n < buffer.length; n++) { unsigned dist = 0; // Count the number of bits set for (size_t i = 0; i < _preamble.size(); i++) { // A bit is set, so increment the distance dist += __popcnt(_preamble[i] ^ in[n+i]); } // Emit a label if within the distance threshold if (dist <= _threshold) { outputPort->postLabel(_frameStartId, Pothos::Object(), n + _preamble.size()); } //distance[n] = dist; } //outputDistance->produce(N); outputPort->postBuffer(std::move(buffer)); } private: unsigned _threshold; std::string _frameStartId; std::vector<unsigned char> _preamble; }; /*********************************************************************** * registration **********************************************************************/ static Pothos::BlockRegistry registerPreambleCorrelator( "/comms/preamble_correlator", &PreambleCorrelator::make); static Pothos::BlockRegistry registerPreambleCorrelatorOldPath( "/blocks/preamble_correlator", &PreambleCorrelator::make);
34.194118
134
0.63616
willcode
a0b8cbac81730c3695003a33d2a4827df1811a4b
481
cpp
C++
Language_Coder/문자열1/자가진단/BasicString107.cpp
NadanKim/CodingTest_JUNGOL
f1f448eb5a107b59bfa196c2682ba89e89431358
[ "MIT" ]
null
null
null
Language_Coder/문자열1/자가진단/BasicString107.cpp
NadanKim/CodingTest_JUNGOL
f1f448eb5a107b59bfa196c2682ba89e89431358
[ "MIT" ]
null
null
null
Language_Coder/문자열1/자가진단/BasicString107.cpp
NadanKim/CodingTest_JUNGOL
f1f448eb5a107b59bfa196c2682ba89e89431358
[ "MIT" ]
null
null
null
#include "BasicString107.h" /// <summary> /// 문제 /// 문자열을 입력받아 알파벳 문자만 모두 대문자로 출력하는 프로그램을 작성하시오. /// 문자열의 길이는 100이하이다. /// /// 입력 예 /// 1988-Seoul-Olympic!!! /// /// 출력 예 /// SEOULOLYMPIC /// /// http://www.jungol.co.kr/bbs/board.php?bo_table=pbank&wr_id=236&sca=10e0 /// </summary> void BasicString107::Code() { string str; std::cin >> str; for (size_t i = 0; i < str.size(); i++) { if (isalpha(str[i])) { std::cout << static_cast<char>(toupper(str[i])); } } }
16.586207
75
0.586279
NadanKim
a0b9fa305d85efdb7f2d6972fefd5660d3fba9ff
4,955
cc
C++
paddle/fluid/operators/save_combine_op.cc
bigo-sg/Paddle
bc16bcda4914d1af76d8192d35ee852a21e12d1c
[ "Apache-2.0" ]
null
null
null
paddle/fluid/operators/save_combine_op.cc
bigo-sg/Paddle
bc16bcda4914d1af76d8192d35ee852a21e12d1c
[ "Apache-2.0" ]
null
null
null
paddle/fluid/operators/save_combine_op.cc
bigo-sg/Paddle
bc16bcda4914d1af76d8192d35ee852a21e12d1c
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <stdint.h> #include <fstream> #include <numeric> #include <sstream> #include "paddle/fluid/framework/data_type.h" #include "paddle/fluid/framework/data_type_transform.h" #include "paddle/fluid/framework/framework.pb.h" #include "paddle/fluid/framework/lod_tensor.h" #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/platform/device_context.h" #include "paddle/fluid/platform/port.h" namespace paddle { namespace operators { class SaveCombineOp : public framework::OperatorBase { public: SaveCombineOp(const std::string &type, const framework::VariableNameMap &inputs, const framework::VariableNameMap &outputs, const framework::AttributeMap &attrs) : OperatorBase(type, inputs, outputs, attrs) {} private: void RunImpl(const framework::Scope &scope, const platform::Place &place) const override { auto filename = Attr<std::string>("file_path"); auto overwrite = Attr<bool>("overwrite"); auto save_as_fp16 = Attr<bool>("save_as_fp16"); bool is_present = FileExists(filename); if (is_present && !overwrite) { PADDLE_THROW("%s exists!, cannot save_combine to it when overwrite=false", filename, overwrite); } MkDirRecursively(DirName(filename).c_str()); std::ofstream fout(filename); PADDLE_ENFORCE(static_cast<bool>(fout), "Cannot open %s to write", filename); auto inp_var_names = Inputs("X"); PADDLE_ENFORCE_GT(static_cast<int>(inp_var_names.size()), 0, "The number of input variables should be greater than 0"); // get device context from pool platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance(); auto &dev_ctx = *pool.Get(place); for (size_t i = 0; i < inp_var_names.size(); i++) { auto *var = scope.FindVar(inp_var_names[i]); PADDLE_ENFORCE(var != nullptr, "Cannot find variable %s for save_combine_op", inp_var_names[i]); PADDLE_ENFORCE(var->IsType<framework::LoDTensor>(), "SaveCombineOp only supports LoDTensor, %s has wrong type", inp_var_names[i]); auto &tensor = var->Get<framework::LoDTensor>(); // Serialize tensors one by one // Check types to see if a fp16 transformation is required auto in_dtype = tensor.type(); auto out_dtype = save_as_fp16 ? framework::proto::VarType::FP16 : in_dtype; if (in_dtype != out_dtype) { auto in_kernel_type = framework::OpKernelType(in_dtype, place); auto out_kernel_type = framework::OpKernelType(out_dtype, place); framework::LoDTensor out; // copy LoD info to the new tensor out.set_lod(tensor.lod()); framework::TransDataType(in_kernel_type, out_kernel_type, tensor, &out); framework::SerializeToStream(fout, out, dev_ctx); } else { framework::SerializeToStream(fout, tensor, dev_ctx); } } fout.close(); } }; class SaveCombineOpProtoMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput( "X", "(vector) Input LoDTensors that need to be saved together in a file.") .AsDuplicable(); AddComment(R"DOC( SaveCombine operator This operator will serialize and write a list of input LoDTensor variables to a file on disk. )DOC"); AddAttr<bool>("overwrite", "(boolean, default true)" "Overwrite the output file if it exists.") .SetDefault(true); AddAttr<bool>("save_as_fp16", "(boolean, default false)" "If true, the tensor will be converted to float16 data " "type and then saved. Otherwise, the tensor will be " "directly saved without data type conversion.") .SetDefault(false); AddAttr<std::string>( "file_path", "(string)" "The \"file_path\" where the LoDTensor variables will be saved.") .AddCustomChecker( [](const std::string &path) { return !path.empty(); }); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(save_combine, ops::SaveCombineOp, ops::SaveCombineOpProtoMaker);
36.167883
80
0.658325
bigo-sg
a0bad0063e69e3863c1aa851d4a4bb70261e6ebc
1,209
cpp
C++
LeetCode/ThousandTwo/1417-reformat_the_string.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
LeetCode/ThousandTwo/1417-reformat_the_string.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
LeetCode/ThousandTwo/1417-reformat_the_string.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
#include "leetcode.hpp" /* 1417. 重新格式化字符串 给你一个混合了数字和字母的字符串 s,其中的字母均为小写英文字母。 请你将该字符串重新格式化,使得任意两个相邻字符的类型都不同。 也就是说,字母后面应该跟着数字,而数字后面应该跟着字母。 请你返回 重新格式化后 的字符串;如果无法按要求重新格式化,则返回一个 空字符串 。 示例 1: 输入:s = "a0b1c2" 输出:"0a1b2c" 解释:"0a1b2c" 中任意两个相邻字符的类型都不同。 "a0b1c2", "0a1b2c", "0c2a1b" 也是满足题目要求的答案。 示例 2: 输入:s = "leetcode" 输出:"" 解释:"leetcode" 中只有字母,所以无法满足重新格式化的条件。 示例 3: 输入:s = "1229857369" 输出:"" 解释:"1229857369" 中只有数字,所以无法满足重新格式化的条件。 示例 4: 输入:s = "covid2019" 输出:"c2o0v1i9d" 示例 5: 输入:s = "ab123" 输出:"1a2b3" 提示: 1 <= s.length <= 500 s 仅由小写英文字母和/或数字组成。 */ string reformat(string s) { vector<char> c, d; for (char i : s) { if (isdigit(i)) d.push_back(i); else c.push_back(i); } s.clear(); if ((c.size() > d.size() + 1) || (d.size() > c.size() + 1)) return s; if (c.size() > d.size()) { s.push_back(c.back()); c.pop_back(); } while (!d.empty() && !c.empty()) { s.push_back(d.back()); s.push_back(c.back()); d.pop_back(); c.pop_back(); } if (d.size()) s.push_back(d.back()); return s; } int main() { OutString(reformat("a0b1c2")); OutString(reformat("leetcode")); OutString(reformat("1229857369")); OutString(reformat("covid2019")); OutString(reformat("ab123")); }
14.925926
70
0.629446
Ginkgo-Biloba
a0bae5f8e647819e442ecbad5781a963abf5a134
1,425
cpp
C++
src/devices/notes/sequencer.cpp
aalin/synthz0r
ecf35b3fec39020e46732a15874b66f07a3e48e9
[ "MIT" ]
1
2021-12-23T21:14:37.000Z
2021-12-23T21:14:37.000Z
src/devices/notes/sequencer.cpp
aalin/synthz0r
ecf35b3fec39020e46732a15874b66f07a3e48e9
[ "MIT" ]
null
null
null
src/devices/notes/sequencer.cpp
aalin/synthz0r
ecf35b3fec39020e46732a15874b66f07a3e48e9
[ "MIT" ]
null
null
null
#include "sequencer.hpp" #include <cmath> constexpr static uint8_t INITIAL_STEPS = 8; constexpr static uint8_t INITIAL_VELOCITY = 100; constexpr static uint8_t INITIAL_BPM = 50; constexpr static uint8_t INITIAL_RATE = 0; namespace Devices::Notes { Sequencer::Sequencer() : NoteDevice("Sequencer") { setupParameters({ Parameter("numSteps", 0, 32, INITIAL_STEPS, _steps), Parameter("velocity", 0, 127, INITIAL_VELOCITY, _velocity), Parameter("rate", 0, 8, INITIAL_RATE, _rate) }); setupTables({ Table("notes", -1, 127, -1, INITIAL_STEPS, _notes) }); } void Sequencer::apply(const Transport &transport, NoteEventList &events) { if (_notes.empty()) { return; } const int step = Utils::mod(static_cast<size_t>(transport.position().total4ths() * std::pow(2, _rate)), _notes.size()); if (step != _lastStep) { std::cout << "Step:" << step << std::endl; if (_lastNote >= 0) { events.push_back(NoteEvent::noteOff(_lastNote)); std::cout << "Sequencer " << id() << " event at " << transport.position() << ": " << NoteEvent::noteOff(_lastNote) << std::endl; } if (_notes[step] >= 0) { std::cout << "Sequencer " << id() << " event at " << transport.position() << ": " << NoteEvent::noteOn(_notes[step], _velocity) << std::endl; events.push_back(NoteEvent::noteOn(_notes[step], _velocity)); } _lastNote = _notes[step]; _lastStep = step; } } }
30.319149
145
0.643509
aalin
a0bf18b000e56cb4262edb0f07438eb2f3455e64
3,353
cpp
C++
saber/funcs/impl/x86/saber_embedding.cpp
pangge/Anakin
f327267d1ee2038d92d8c704ec9f1a03cb800fc8
[ "Apache-2.0" ]
null
null
null
saber/funcs/impl/x86/saber_embedding.cpp
pangge/Anakin
f327267d1ee2038d92d8c704ec9f1a03cb800fc8
[ "Apache-2.0" ]
null
null
null
saber/funcs/impl/x86/saber_embedding.cpp
pangge/Anakin
f327267d1ee2038d92d8c704ec9f1a03cb800fc8
[ "Apache-2.0" ]
null
null
null
#include "saber/funcs/impl/x86/saber_embedding.h" #include "saber/funcs/impl/x86/x86_utils.h" namespace anakin{ namespace saber { template <DataType OpDtype> SaberStatus SaberEmbedding<X86, OpDtype>::init( const std::vector<Tensor<X86>*>& inputs, std::vector<Tensor<X86>*>& outputs, EmbeddingParam<X86> &param, Context<X86> &ctx) { // get context this->_ctx = &ctx; return create(inputs, outputs, param, ctx); } template <DataType OpDtype> SaberStatus SaberEmbedding<X86, OpDtype>::create( const std::vector<Tensor<X86>*>& inputs, std::vector<Tensor<X86>*>& outputs, EmbeddingParam<X86> &param, Context<X86> &ctx) { return SaberSuccess; } template <DataType OpDtype> SaberStatus SaberEmbedding<X86, OpDtype>::dispatch( const std::vector<Tensor<X86>*>& inputs, std::vector<Tensor<X86>*>& outputs, EmbeddingParam<X86> &param) { typedef typename DataTrait<X86, OpDtype>::Dtype DataType_out; CHECK_EQ(inputs.size(), (size_t)1); CHECK_EQ(outputs.size(), (size_t)param.num_direct); CHECK_EQ(inputs[0]->get_dtype(), AK_FLOAT) << "embedding only support float inputs!"; const int num_word = inputs[0]->valid_size(); //outputs: chose corresponding informations of words. //inputs: word_id [Its type maybe float or int] //outputs = weights[inputs[j]]. const float *in_data = (const float*)inputs[0]->data(); DataType_out *out_data = (DataType_out*)outputs[0]->mutable_data(); DataType_out *weight_data = (DataType_out*)param.weight()->data(); int emb_dim = param.emb_dim; /*positive direct*/ for (int i = 0; i < num_word; i++) { if (in_data[i] == param.padding_idx) { memset(out_data + i * emb_dim, 0, sizeof(DataType_out) * emb_dim); } else { CHECK_GE(in_data[i], 0); CHECK_LT(in_data[i], param.word_num); memcpy(out_data + i * emb_dim, weight_data + int(in_data[i]) * emb_dim, sizeof(DataType_out) * emb_dim); } } if (param.num_direct == 2) { DataType_out *out_data = (DataType_out*)outputs[1]->mutable_data(); auto seq_offset = inputs[0]->get_seq_offset(); CHECK_GE(seq_offset.size(), 1) << "embedding seq offset is not null"; auto cur_seq_offset = seq_offset[0]; for (int i = 0; i < cur_seq_offset.size() - 1; i++) { int cur_len = cur_seq_offset[i + 1] - cur_seq_offset[i]; for (int j = 0; j < cur_len; j++) { int src_index = cur_seq_offset[i] + j; int dst_index = cur_seq_offset[i + 1] - 1 - j; int index = in_data[src_index]; if (index == param.padding_idx) { memset(out_data + dst_index * emb_dim, 0, sizeof(DataType_out) * emb_dim); } else { CHECK_GE(index, 0); CHECK_LT(index, param.word_num); memcpy(out_data + dst_index * emb_dim, weight_data + int(index) * emb_dim, sizeof(DataType_out) * emb_dim); } } } } } template class SaberEmbedding<X86, AK_FLOAT>; DEFINE_OP_TEMPLATE(SaberEmbedding, EmbeddingParam, X86, AK_HALF); DEFINE_OP_TEMPLATE(SaberEmbedding, EmbeddingParam, X86, AK_INT8); } } // namespace anakin
35.294737
127
0.611095
pangge
a0bf2b12eb2dd41aa78058679c9ccd6cbaa4d2b1
11,173
hpp
C++
customlistview.hpp
pengrui2009/qt-admin-template
89ce3a9cac20d0caee52db8df97d584cd2246c22
[ "MIT" ]
1
2022-03-31T09:24:13.000Z
2022-03-31T09:24:13.000Z
customlistview.hpp
ciyeer/qt-admin-template
54d8219c096f7c05c90a9dd33ebbd68cd4e6cf23
[ "MIT" ]
null
null
null
customlistview.hpp
ciyeer/qt-admin-template
54d8219c096f7c05c90a9dd33ebbd68cd4e6cf23
[ "MIT" ]
2
2021-04-20T10:58:45.000Z
2022-03-30T11:02:58.000Z
#ifndef CUSTOMNAVDELEGATE_H #define CUSTOMNAVDELEGATE_H #include <QListView> #include <QStyledItemDelegate> //节点展开模式 enum ExpendMode { ExpendMode_SingleClick = 0, //单击模式 ExpendMode_DoubleClick = 1, //双击模式 ExpendMode_NoClick = 2, //不可单击双击 }; class CustomListView; class NavDelegate : public QStyledItemDelegate { Q_OBJECT public: NavDelegate(QObject *parent, CustomListView *nav); ~NavDelegate(); protected: QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const ; void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; private: CustomListView *nav; QFont iconFont; }; class NavModel : public QAbstractListModel { Q_OBJECT public: NavModel(QObject *parent); ~NavModel(); public: struct TreeNode { int level; //层级,父节点-1,子节点-2 bool expand; //是否打开子节点 bool last; //是否末尾元素 QChar icon; //左侧图标 QString text; //显示的节点文字 QString tip; //右侧描述文字 QString parentText; //父节点名称 QList<TreeNode *> children; //子节点集合 }; struct ListNode { QString text; //节点文字 TreeNode *treeNode; //节点指针 }; protected: int rowCount(const QModelIndex &parent) const; QVariant data(const QModelIndex &index, int role) const; private: QList<TreeNode *> treeNode; QList<ListNode> listNode; public Q_SLOTS: void setItems(const QStringList &items); void expand(const QModelIndex &index); private: void refreshList(); }; #ifdef quc #if (QT_VERSION < QT_VERSION_CHECK(5,7,0)) #include <QtDesigner/QDesignerExportWidget> #else #include <QtUiPlugin/QDesignerExportWidget> #endif class QDESIGNER_WIDGET_EXPORT CustomListView : public QListView #else class CustomListView : public QListView #endif { Q_OBJECT Q_ENUMS(ExpendMode) Q_PROPERTY(QString items READ getItems WRITE setItems) Q_PROPERTY(bool rightIconVisible READ getRightIconVisible WRITE setRightIconVisible) Q_PROPERTY(bool tipVisible READ getTipVisible WRITE setTipVisible) Q_PROPERTY(int tipWidth READ getTipWidth WRITE setTipWidth) Q_PROPERTY(bool separateVisible READ getSeparateVisible WRITE setSeparateVisible) Q_PROPERTY(int separateHeight READ getSeparateHeight WRITE setSeparateHeight) Q_PROPERTY(QColor separateColor READ getSeparateColor WRITE setSeparateColor) Q_PROPERTY(bool lineLeft READ getLineLeft WRITE setLineLeft) Q_PROPERTY(bool lineVisible READ getLineVisible WRITE setLineVisible) Q_PROPERTY(int lineWidth READ getLineWidth WRITE setLineWidth) Q_PROPERTY(QColor lineColor READ getLineColor WRITE setLineColor) Q_PROPERTY(bool triangleLeft READ getTriangleLeft WRITE setTriangleLeft) Q_PROPERTY(bool triangleVisible READ getTriangleVisible WRITE setTriangleVisible) Q_PROPERTY(int triangleWidth READ getTriangleWidth WRITE setTriangleWidth) Q_PROPERTY(QColor triangleColor READ getTriangleColor WRITE setTriangleColor) Q_PROPERTY(int parentIconMargin READ getParentIconMargin WRITE setParentIconMargin) Q_PROPERTY(int parentMargin READ getParentMargin WRITE setParentMargin) Q_PROPERTY(int parentFontSize READ getParentFontSize WRITE setParentFontSize) Q_PROPERTY(int parentHeight READ getParentHeight WRITE setParentHeight) Q_PROPERTY(QColor parentBgNormalColor READ getParentBgNormalColor WRITE setParentBgNormalColor) Q_PROPERTY(QColor parentBgSelectedColor READ getParentBgSelectedColor WRITE setParentBgSelectedColor) Q_PROPERTY(QColor parentBgHoverColor READ getParentBgHoverColor WRITE setParentBgHoverColor) Q_PROPERTY(QColor parentTextNormalColor READ getParentTextNormalColor WRITE setParentTextNormalColor) Q_PROPERTY(QColor parentTextSelectedColor READ getParentTextSelectedColor WRITE setParentTextSelectedColor) Q_PROPERTY(QColor parentTextHoverColor READ getParentTextHoverColor WRITE setParentTextHoverColor) Q_PROPERTY(int childIconMargin READ getChildIconMargin WRITE setChildIconMargin) Q_PROPERTY(int childMargin READ getChildMargin WRITE setChildMargin) Q_PROPERTY(int childFontSize READ getChildFontSize WRITE setChildFontSize) Q_PROPERTY(int childHeight READ getChildHeight WRITE setChildHeight) Q_PROPERTY(QColor childBgNormalColor READ getChildBgNormalColor WRITE setChildBgNormalColor) Q_PROPERTY(QColor childBgSelectedColor READ getChildBgSelectedColor WRITE setChildBgSelectedColor) Q_PROPERTY(QColor childBgHoverColor READ getChildBgHoverColor WRITE setChildBgHoverColor) Q_PROPERTY(QColor childTextNormalColor READ getChildTextNormalColor WRITE setChildTextNormalColor) Q_PROPERTY(QColor childTextSelectedColor READ getChildTextSelectedColor WRITE setChildTextSelectedColor) Q_PROPERTY(QColor childTextHoverColor READ getChildTextHoverColor WRITE setChildTextHoverColor) Q_PROPERTY(ExpendMode expendMode READ getExpendMode WRITE setExpendMode) public: CustomListView(QWidget *parent = 0); ~CustomListView(); private: NavModel *model; //数据模型 NavDelegate *delegate; //数据委托 QStringList parentItem; //父节点数据集合 QList<QStringList> childItem; //子节点数据 QString items; //节点集合 bool rightIconVisible; //右侧图标是否显示 bool tipVisible; //是否显示提示信息 int tipWidth; //提示信息宽度 bool separateVisible; //是否显示行分隔符 int separateHeight; //行分隔符高度 QColor separateColor; //行分隔符颜色 bool lineLeft; //是否显示在左侧 bool lineVisible; //是否显示线条 int lineWidth; //线条宽度 QColor lineColor; //线条颜色 bool triangleLeft; //是否显示在左侧 bool triangleVisible; //是否显示三角形 int triangleWidth; //三角形宽度 QColor triangleColor; //三角形颜色 int parentIconMargin; //父节点图标边距 int parentMargin; //父节点边距 int parentFontSize; //父节点字体大小 int parentHeight; //父节点高度 QColor parentBgNormalColor; //父节点正常背景色 QColor parentBgSelectedColor; //父节点选中背景色 QColor parentBgHoverColor; //父节点悬停背景色 QColor parentTextNormalColor; //父节点正常文字颜色 QColor parentTextSelectedColor; //父节点选中文字颜色 QColor parentTextHoverColor; //父节点悬停文字颜色 int childIconMargin; //子节点图标边距 int childMargin; //子节点边距 int childFontSize; //子节点字体大小 int childHeight; //子节点高度 QColor childBgNormalColor; //子节点正常背景色 QColor childBgSelectedColor; //子节点选中背景色 QColor childBgHoverColor; //子节点悬停背景色 QColor childTextNormalColor; //子节点正常文字颜色 QColor childTextSelectedColor; //子节点选中文字颜色 QColor childTextHoverColor; //子节点悬停文字颜色 ExpendMode expendMode; //节点展开模式 单击/双击/禁用 private slots: void pressed(const QModelIndex &data); void setData(const QStringList &listItems); public: QString getItems() const; bool getRightIconVisible() const; bool getTipVisible() const; int getTipWidth() const; bool getSeparateVisible() const; int getSeparateHeight() const; QColor getSeparateColor() const; bool getLineLeft() const; bool getLineVisible() const; int getLineWidth() const; QColor getLineColor() const; bool getTriangleLeft() const; bool getTriangleVisible() const; int getTriangleWidth() const; QColor getTriangleColor() const; int getParentIconMargin() const; int getParentMargin() const; int getParentFontSize() const; int getParentHeight() const; QColor getParentBgNormalColor() const; QColor getParentBgSelectedColor()const; QColor getParentBgHoverColor() const; QColor getParentTextNormalColor()const; QColor getParentTextSelectedColor()const; QColor getParentTextHoverColor()const; int getChildIconMargin() const; int getChildMargin() const; int getChildFontSize() const; int getChildHeight() const; QColor getChildBgNormalColor() const; QColor getChildBgSelectedColor()const; QColor getChildBgHoverColor() const; QColor getChildTextNormalColor()const; QColor getChildTextSelectedColor()const; QColor getChildTextHoverColor() const; ExpendMode getExpendMode() const; QSize sizeHint() const; QSize minimumSizeHint() const; public Q_SLOTS: //设置节点数据 void setItems(const QString &items); //设置选中指定行 void setCurrentRow(int row); //设置父节点右侧图标是否显示 void setRightIconVisible(bool rightIconVisible); //设置提示信息 是否显示+宽度 void setTipVisible(bool tipVisible); void setTipWidth(int tipWidth); //设置行分隔符 是否显示+高度+颜色 void setSeparateVisible(bool separateVisible); void setSeparateHeight(int separateHeight); void setSeparateColor(const QColor &separateColor); //设置线条 位置+可见+宽度+颜色 void setLineLeft(bool lineLeft); void setLineVisible(bool lineVisible); void setLineWidth(int lineWidth); void setLineColor(const QColor &lineColor); //设置三角形 位置+可见+宽度+颜色 void setTriangleLeft(bool triangleLeft); void setTriangleVisible(bool triangleVisible); void setTriangleWidth(int triangleWidth); void setTriangleColor(const QColor &triangleColor); //设置父节点 图标边距+左侧边距+字体大小+节点高度+颜色集合 void setParentIconMargin(int parentIconMargin); void setParentMargin(int parentMargin); void setParentFontSize(int parentFontSize); void setParentHeight(int parentHeight); void setParentBgNormalColor(const QColor &parentBgNormalColor); void setParentBgSelectedColor(const QColor &parentBgSelectedColor); void setParentBgHoverColor(const QColor &parentBgHoverColor); void setParentTextNormalColor(const QColor &parentTextNormalColor); void setParentTextSelectedColor(const QColor &parentTextSelectedColor); void setParentTextHoverColor(const QColor &parentTextHoverColor); //设置子节点 图标边距+左侧边距+字体大小+节点高度+颜色集合 void setChildIconMargin(int childIconMargin); void setChildMargin(int childMargin); void setChildFontSize(int childFontSize); void setChildHeight(int childHeight); void setChildBgNormalColor(const QColor &childBgNormalColor); void setChildBgSelectedColor(const QColor &childBgSelectedColor); void setChildBgHoverColor(const QColor &childBgHoverColor); void setChildTextNormalColor(const QColor &childTextNormalColor); void setChildTextSelectedColor(const QColor &childTextSelectedColor); void setChildTextHoverColor(const QColor &childTextHoverColor); //设置节点展开模式 void setExpendMode(const ExpendMode &expendMode); Q_SIGNALS: void pressed(const QString &text, const QString &parentText); void pressed(int index, int parentIndex); void pressed(int childIndex); }; #endif // CUSTOMNAVDELEGATE_H
37.243333
111
0.716907
pengrui2009
a0bfbd2c20128d11369bf5089da174dede576f8b
7,686
cpp
C++
Testing/Operations/albaOpEditNormalsTest.cpp
IOR-BIC/ALBA
b574968b05d9a3a2756dd2ac61d015a0d20232a4
[ "Apache-2.0", "BSD-3-Clause" ]
9
2018-11-19T10:15:29.000Z
2021-08-30T11:52:07.000Z
Testing/Operations/albaOpEditNormalsTest.cpp
IOR-BIC/ALBA
b574968b05d9a3a2756dd2ac61d015a0d20232a4
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Testing/Operations/albaOpEditNormalsTest.cpp
IOR-BIC/ALBA
b574968b05d9a3a2756dd2ac61d015a0d20232a4
[ "Apache-2.0", "BSD-3-Clause" ]
3
2018-06-10T22:56:29.000Z
2019-12-12T06:22:56.000Z
/*========================================================================= Program: ALBA (Agile Library for Biomedical Applications) Module: albaOpEditNormalsTest Authors: Daniele Giunchi - Matteo Giacomoni Copyright (c) BIC All rights reserved. See Copyright.txt or This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "albaDefines.h" //---------------------------------------------------------------------------- // NOTE: Every CPP file in the ALBA must include "albaDefines.h" as first. // This force to include Window,wxWidgets and VTK exactly in this order. // Failing in doing this will result in a run-time error saying: // "Failure#0: The value of ESP was not properly saved across a function call" //---------------------------------------------------------------------------- #include <cppunit/config/SourcePrefix.h> #include "albaOpEditNormalsTest.h" #include "albaOpEditNormals.h" #include "albaString.h" #include "albaVMESurface.h" #include "vtkALBASmartPointer.h" #include "vtkDataSet.h" #include "vtkPolyData.h" #include "vtkCellData.h" #include "vtkPointData.h" #include "vtkFloatArray.h" #include "vtkMath.h" #include "vtkSTLReader.h" #define EPSILON 0.00001 //----------------------------------------------------------- void albaOpEditNormalsTest::Test() //----------------------------------------------------------- { albaString filename=ALBA_DATA_ROOT; filename<<"/STL/normals.stl"; vtkALBASmartPointer<vtkSTLReader> reader; reader->SetFileName(filename.GetCStr()); reader->Update(); albaSmartPointer<albaVMESurface> surface; surface->SetData(reader->GetOutput(),0.0); surface->GetOutput()->GetVTKData()->Update(); surface->Update(); vtkALBASmartPointer<vtkPolyData>originalPolydata; originalPolydata->DeepCopy(vtkPolyData::SafeDownCast(surface->GetOutput()->GetVTKData())); originalPolydata->Update(); albaOpEditNormals *editNormals1 = new albaOpEditNormals(); editNormals1->TestModeOn(); editNormals1->SetInput(surface); editNormals1->OpRun(); editNormals1->OnGenerateNormals(); editNormals1->OpDo(); surface->GetOutput()->GetVTKData()->Update(); vtkALBASmartPointer<vtkPolyData> resultPolydata1; resultPolydata1->DeepCopy(vtkPolyData::SafeDownCast(surface->GetOutput()->GetVTKData())); resultPolydata1->Update(); vtkFloatArray *pointNormals1=vtkFloatArray::SafeDownCast(resultPolydata1->GetPointData()->GetNormals()); CPPUNIT_ASSERT(pointNormals1); albaOpEditNormals *editNormals2 = new albaOpEditNormals(); editNormals2->TestModeOn(); editNormals2->SetInput(surface); editNormals2->SetFlipNormalsOn(); editNormals2->OpRun(); editNormals2->OnGenerateNormals(); editNormals2->OpDo(); surface->GetOutput()->GetVTKData()->Update(); vtkALBASmartPointer<vtkPolyData> resultPolydata2; resultPolydata2->DeepCopy(vtkPolyData::SafeDownCast(surface->GetOutput()->GetVTKData())); resultPolydata2->Update(); vtkFloatArray *pointNormals2=vtkFloatArray::SafeDownCast(resultPolydata2->GetPointData()->GetNormals()); bool normalBetweenEpsilon=true; float *v1,*v2; for(int i=0; i< pointNormals1->GetSize(); i++) { v1=pointNormals1->GetPointer(i); v2=pointNormals2->GetPointer(i); float norm1[3],norm2[3]; norm1[0] = v1[0]; norm1[1] = v1[1]; norm1[2] = v1[2]; norm2[0] = v2[0]; norm2[1] = v2[1]; norm2[2] = v2[2]; vtkMath::Normalize(norm1); vtkMath::Normalize(norm2); double result = vtkMath::Dot(norm1,norm2); if( !(result+EPSILON >= -1 || result-EPSILON <= -1) ) { normalBetweenEpsilon=false; break; } } CPPUNIT_ASSERT( normalBetweenEpsilon); albaDEL(editNormals1); albaDEL(editNormals2); } //----------------------------------------------------------- void albaOpEditNormalsTest::TestUndo1() //----------------------------------------------------------- { albaString filename=ALBA_DATA_ROOT; filename<<"/STL/normals.stl"; vtkALBASmartPointer<vtkSTLReader> reader; reader->SetFileName(filename.GetCStr()); reader->Update(); albaSmartPointer<albaVMESurface> surface; surface->SetData(reader->GetOutput(),0.0); surface->GetOutput()->GetVTKData()->Update(); surface->Update(); vtkALBASmartPointer<vtkPolyData>originalPolydata; originalPolydata->DeepCopy(vtkPolyData::SafeDownCast(surface->GetOutput()->GetVTKData())); originalPolydata->Update(); albaOpEditNormals *editNormals = new albaOpEditNormals(); editNormals->TestModeOn(); editNormals->SetFlipNormalsOn(); editNormals->SetInput(surface); editNormals->OpRun(); editNormals->OnGenerateNormals(); editNormals->OpDo(); surface->GetOutput()->GetVTKData()->Update(); editNormals->OpUndo(); surface->GetOutput()->GetVTKData()->Update(); vtkALBASmartPointer<vtkPolyData>resultPolydata1; resultPolydata1->DeepCopy(vtkPolyData::SafeDownCast(surface->GetOutput()->GetVTKData())); resultPolydata1->Update(); vtkFloatArray *pointNormalsResult1=vtkFloatArray::SafeDownCast(resultPolydata1->GetPointData()->GetNormals()); vtkFloatArray *pointNormalsOriginal1=vtkFloatArray::SafeDownCast(originalPolydata->GetPointData()->GetNormals()); CPPUNIT_ASSERT(!pointNormalsResult1 && !pointNormalsOriginal1); albaDEL(editNormals); } //----------------------------------------------------------- void albaOpEditNormalsTest::TestUndo2() //----------------------------------------------------------- { albaString filename=ALBA_DATA_ROOT; filename<<"/STL/normals.stl"; vtkALBASmartPointer<vtkSTLReader> reader; reader->SetFileName(filename.GetCStr()); reader->Update(); albaSmartPointer<albaVMESurface> surface; surface->SetData(reader->GetOutput(),0.0); surface->GetOutput()->GetVTKData()->Update(); surface->Update(); albaOpEditNormals *editNormals1 = new albaOpEditNormals(); editNormals1->TestModeOn(); editNormals1->SetFlipNormalsOn(); editNormals1->SetInput(surface); editNormals1->OpRun(); editNormals1->OnGenerateNormals(); editNormals1->OpDo(); surface->GetOutput()->GetVTKData()->Update(); vtkALBASmartPointer<vtkPolyData>originalPolydata; originalPolydata->DeepCopy(vtkPolyData::SafeDownCast(surface->GetOutput()->GetVTKData())); originalPolydata->Update(); albaOpEditNormals *editNormals2 = new albaOpEditNormals(); editNormals2->TestModeOn(); editNormals2->SetInput(surface); editNormals2->SetFlipNormalsOn(); editNormals2->OpRun(); editNormals2->OnGenerateNormals(); editNormals2->OpDo(); surface->GetOutput()->GetVTKData()->Update(); editNormals2->OpUndo(); surface->GetOutput()->GetVTKData()->Update(); vtkALBASmartPointer<vtkPolyData>resultPolydata2; resultPolydata2->DeepCopy(vtkPolyData::SafeDownCast(surface->GetOutput()->GetVTKData())); resultPolydata2->Update(); resultPolydata2->GetPointData()->Update(); originalPolydata->GetPointData()->Update(); vtkFloatArray *pointNormalsResult2=vtkFloatArray::SafeDownCast(resultPolydata2->GetPointData()->GetNormals()); vtkFloatArray *pointNormalsOriginal2=vtkFloatArray::SafeDownCast(originalPolydata->GetPointData()->GetNormals()); float *v1,*v2; bool vectorEquals=true; for(int i=0; i< pointNormalsResult2->GetSize()-1; i++) { v1=pointNormalsResult2->GetPointer(i); v2=pointNormalsOriginal2->GetPointer(i); if(v1[0] != v2[0] || v1[1] != v2[1] || v1[2] != v2[2]) { albaLogMessage("Different vector num:%d/%d v1[%f,%f,%f] v2[%f,%f,%f]",i,pointNormalsResult2->GetSize(), v1[0],v1[1],v1[2], v2[0],v2[1],v2[2]); vectorEquals=false; break; } } CPPUNIT_ASSERT(vectorEquals); albaDEL(editNormals1); albaDEL(editNormals2); }
32.43038
148
0.688134
IOR-BIC
a0bfde6c347dad60c15fcaf3838192272d197618
526
cc
C++
src/abc130/enough_array.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/abc130/enough_array.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/abc130/enough_array.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> typedef long long ll; using namespace std; long long enough_array(ll a[], ll n, ll k) { ll ans = 0; ll sum = 0; int r = 0; for(int l=0;l<n;l++) { while(sum < k) { if(r >= n) { break; } sum += a[r]; r++; } if(sum >= k) { sum -= a[l]; ans += n - r + 1; } } return ans; } /* int main() { ll n; ll k; cin >> n; cin >> k; ll a[n]; for(ll i=0;i<n;i++) { cin >> a[i]; } cout << enough_array(a, n, k); } */
12.829268
44
0.43346
nryotaro
a0c250f11d5d956cb3259d3d72f6161a7f00fd81
1,483
cpp
C++
TallerProgra/problemas10Marzo/B_NotShading.cpp
CaDe27/Co-digos
9eea1dbf6ed06fd115391328c0a2481029c83fc0
[ "MIT" ]
null
null
null
TallerProgra/problemas10Marzo/B_NotShading.cpp
CaDe27/Co-digos
9eea1dbf6ed06fd115391328c0a2481029c83fc0
[ "MIT" ]
null
null
null
TallerProgra/problemas10Marzo/B_NotShading.cpp
CaDe27/Co-digos
9eea1dbf6ed06fd115391328c0a2481029c83fc0
[ "MIT" ]
null
null
null
//note that if there is a black cell in the grid, you can make it black // in at most 2 operations // we just need to see if we can do it in 0, 1 or 2. // 0: operations, it needs to be black already // 1: is in the same column or row as another black cell // 2: theres it one black cell // we print the first of this #include <iostream> using namespace std; char grid[55][55]; void solveTestCase(){ int n,m,r,c; cin>>n>>m>>r>>c; --r;--c; bool blackCell = false; for(int i = 0; i < n; ++i){ for(int j = 0; j < m; ++j){ cin>>grid[i][j]; if(grid[i][j] == 'B') blackCell = true; }} int resp; if(!blackCell) resp = -1; else if(grid[r][c] == 'B') resp = 0; else{ //we look in the same column and row //if there's not a black cell on them, the answer is two bool sameRowOrColumn = false; int i = 0; while(i < n && !sameRowOrColumn){ if(grid[i][c] == 'B') sameRowOrColumn = true; ++i; } i = 0; while(i < m && !sameRowOrColumn){ if(grid[r][i] == 'B') sameRowOrColumn = true; ++i; } if(sameRowOrColumn) resp = 1; else resp = 2; } cout<<resp<<"\n"; } int main(){ int testCases; cin>>testCases; for(int i = 0; i < testCases; ++i) solveTestCase(); return 0; }
23.539683
72
0.489548
CaDe27
a0c43e62763ff69ba8b66ddb40906873e7603d8d
16,539
cpp
C++
Raven.CppClient.Tests/CrudTest.cpp
maximburyak/ravendb-cpp-client
ab284d00bc659e8438c829f1b4a39aa78c31fa88
[ "MIT" ]
null
null
null
Raven.CppClient.Tests/CrudTest.cpp
maximburyak/ravendb-cpp-client
ab284d00bc659e8438c829f1b4a39aa78c31fa88
[ "MIT" ]
null
null
null
Raven.CppClient.Tests/CrudTest.cpp
maximburyak/ravendb-cpp-client
ab284d00bc659e8438c829f1b4a39aa78c31fa88
[ "MIT" ]
null
null
null
#include "pch.h" //#define __USE_FIDDLER__ #include "TestSuiteBase.h" #include "DocumentSession.h" #include "AdvancedSessionOperations.h" #include "RequestExecutor.h" #include "User.h" #include "Family.h" #include "NullableUser.h" #include "Arr.h" #include "Poc.h" namespace ravendb::client::tests::client { class CrudTest : public infrastructure::TestSuiteBase { protected: static void SetUpTestCase() { test_suite_store = definitions::GET_DOCUMENT_STORE(); } documents::session::DocumentInfo::ToJsonConverter arr2_to_json = [](std::shared_ptr<void> arr_param)->nlohmann::json { auto arr = std::static_pointer_cast<infrastructure::entities::Arr2>(arr_param); nlohmann::json json_array = nlohmann::json::array(); for(const auto& a : arr->arr1) { nlohmann::json temp = nlohmann::json::object(); temp["str"] = nlohmann::json(a.str); json_array.push_back(std::move(temp)); } nlohmann::json json; json["arr1"] = std::move(json_array); return json; }; documents::session::DocumentInfo::FromJsonConverter arr2_from_json = [](const nlohmann::json& json)->std::shared_ptr<void> { auto arr2 = std::make_shared<infrastructure::entities::Arr2>(); const auto& json_array = static_cast<const nlohmann::json::array_t&>(json["arr1"]); arr2->arr1.reserve(json_array.size()); for(const auto& str_arr : json_array) { infrastructure::entities::Arr1 arr1{}; arr1.str.reserve(str_arr.at("str").size()); for (const auto& str : str_arr.at("str")) { arr1.str.push_back(str.get<std::string>()); } arr2->arr1.push_back(std::move(arr1)); } return std::static_pointer_cast<void>(arr2); }; }; TEST_F(CrudTest, EntitiesAreSavedUsingLowerCase) { { auto session = test_suite_store->get().open_session(); auto user1 = std::make_shared<infrastructure::entities::User>(); user1->last_name = "user1"; session.store(user1, "users/1"); session.save_changes(); } auto documents_command = documents::commands::GetDocumentsCommand("users/1", {}, false); test_suite_store->get().get_request_executor()->execute(documents_command); auto result = documents_command.get_result(); auto user_json = result.results.at(0); ASSERT_TRUE(user_json.find("LastName") != user_json.end()); { auto session = test_suite_store->get().open_session(); auto users = session.advanced().raw_query<infrastructure::entities::User>("from Users where LastName = 'user1'")->to_list(); ASSERT_EQ(1, users.size()); } } //TODO implement TEST_F(CrudTest, CanCustomizePropertyNamingStrategy) { SUCCEED(); } TEST_F(CrudTest, CrudOperations) { auto session = test_suite_store->get().open_session(); auto user1 = std::make_shared<infrastructure::entities::User>(); user1->last_name = "user1"; session.store(user1, "users/1"); auto user2 = std::make_shared<infrastructure::entities::User>(); user2->name = "user2"; user1->age = 1; session.store(user2, "users/2"); auto user3 = std::make_shared<infrastructure::entities::User>(); user3->name = "user3"; user3->age = 1; session.store(user3, "users/3"); auto user4 = std::make_shared<infrastructure::entities::User>(); user4->name = "user4"; session.store(user4, "users/4"); session.delete_document(user2); user3->age = 3; session.save_changes(); auto temp_user = session.load<infrastructure::entities::User>("users/2"); ASSERT_FALSE(temp_user); temp_user = session.load<infrastructure::entities::User>("users/3"); ASSERT_EQ(3, temp_user->age); user1 = session.load<infrastructure::entities::User>("users/1"); user4 = session.load<infrastructure::entities::User>("users/4"); session.delete_document(user4); user1->age = 10; session.save_changes(); temp_user = session.load<infrastructure::entities::User>("users/4"); ASSERT_FALSE(temp_user); temp_user = session.load<infrastructure::entities::User>("users/1"); ASSERT_EQ(10, temp_user->age); } TEST_F(CrudTest, CrudOperationsWithWhatChanged) { auto session = test_suite_store->get().open_session(); auto user1 = std::make_shared<infrastructure::entities::User>(); user1->last_name = "user1"; session.store(user1, "users/1"); auto user2 = std::make_shared<infrastructure::entities::User>(); user2->name = "user2"; user1->age = 1; session.store(user2, "users/2"); auto user3 = std::make_shared<infrastructure::entities::User>(); user3->name = "user3"; user3->age = 1; session.store(user3, "users/3"); auto user4 = std::make_shared<infrastructure::entities::User>(); user4->name = "user4"; session.store(user4, "users/4"); session.delete_document(user2); user3->age = 3; ASSERT_EQ(4, session.advanced().what_changed().size()); session.save_changes(); auto temp_user = session.load<infrastructure::entities::User>("users/2"); ASSERT_FALSE(temp_user); temp_user = session.load<infrastructure::entities::User>("users/3"); ASSERT_EQ(3, temp_user->age); user1 = session.load<infrastructure::entities::User>("users/1"); user4 = session.load<infrastructure::entities::User>("users/4"); session.delete_document(user4); user1->age = 10; ASSERT_EQ(2, session.advanced().what_changed().size()); session.save_changes(); temp_user = session.load<infrastructure::entities::User>("users/4"); ASSERT_FALSE(temp_user); temp_user = session.load<infrastructure::entities::User>("users/1"); ASSERT_EQ(10, temp_user->age); } TEST_F(CrudTest, CrudOperationsWithArrayInObject) { auto session = test_suite_store->get().open_session(); auto family = std::make_shared<infrastructure::entities::Family>(); family->names = { "Hibernating Rhinos", "RavenDB" }; session.store(family, "family/1"); session.save_changes(); auto new_family = session.load<infrastructure::entities::Family>("family/1"); new_family->names = { "Toli", "Mitzi", "Boki" }; ASSERT_EQ(1, session.advanced().what_changed().size()); session.save_changes(); } TEST_F(CrudTest, CrudOperationsWithArrayInObject2) { auto session = test_suite_store->get().open_session(); auto family = std::make_shared<infrastructure::entities::Family>(); family->names = { "Hibernating Rhinos", "RavenDB" }; session.store(family, "family/1"); session.save_changes(); auto new_family = session.load<infrastructure::entities::Family>("family/1"); new_family->names = { "Hibernating Rhinos", "RavenDB" }; ASSERT_EQ(0, session.advanced().what_changed().size()); new_family->names = { "RavenDB","Hibernating Rhinos" }; ASSERT_EQ(1, session.advanced().what_changed().size()); session.save_changes(); } TEST_F(CrudTest, CrudOperationsWithArrayInObject3) { auto session = test_suite_store->get().open_session(); auto family = std::make_shared<infrastructure::entities::Family>(); family->names = { "Hibernating Rhinos", "RavenDB" }; session.store(family, "family/1"); session.save_changes(); auto new_family = session.load<infrastructure::entities::Family>("family/1"); new_family->names = { "RavenDB" }; ASSERT_EQ(1, session.advanced().what_changed().size()); session.save_changes(); } TEST_F(CrudTest, CrudOperationsWithArrayInObject4) { auto session = test_suite_store->get().open_session(); auto family = std::make_shared<infrastructure::entities::Family>(); family->names = { "Hibernating Rhinos", "RavenDB" }; session.store(family, "family/1"); session.save_changes(); auto new_family = session.load<infrastructure::entities::Family>("family/1"); new_family->names = { "RavenDB", "Hibernating Rhinos", "Toli", "Mitzi", "Boki" }; ASSERT_EQ(1, session.advanced().what_changed().size()); session.save_changes(); } TEST_F(CrudTest, CrudOperationsWithNull) { auto session = test_suite_store->get().open_session(); auto user = std::make_shared<infrastructure::entities::NullableUser>(); session.store(user, "n_users/1"); session.save_changes(); auto user2 = session.load<infrastructure::entities::NullableUser>("n_users/1"); ASSERT_TRUE(session.advanced().what_changed().empty()); user2->age = 3; ASSERT_EQ(1, session.advanced().what_changed().size()); } TEST_F(CrudTest, CrudOperationsWithArrayOfObjects) { auto session = test_suite_store->get().open_session(); auto member1 = std::make_shared<infrastructure::entities::Member>(); member1->name = "Hibernating Rhinos"; member1->age = 8; auto member2 = std::make_shared<infrastructure::entities::Member>(); member2->name = "RavenDB"; member2->age = 4; auto family = std::make_shared<infrastructure::entities::FamilyMembers>(); family->members = { member1, member2 }; session.store(family, "family_members/1"); session.save_changes(); member1 = std::make_shared<infrastructure::entities::Member>(); member1->name = "RavenDB"; member1->age = 4; member2 = std::make_shared<infrastructure::entities::Member>(); member2->name = "Hibernating Rhinos"; member2->age = 8; auto new_family = session.load<infrastructure::entities::FamilyMembers>("family_members/1"); new_family->members = { member1, member2 }; auto changes = session.advanced().what_changed(); ASSERT_EQ(1, changes.size()); ASSERT_EQ(4, changes.at("family_members/1").size()); ASSERT_EQ(std::string("Age"), changes.at("family_members/1").at(0).field_name); ASSERT_EQ(documents::session::DocumentsChanges::ChangeType::FIELD_CHANGED, changes.at("family_members/1").at(0).change); ASSERT_EQ(8, changes.at("family_members/1").at(0).field_old_value.get<int>()); ASSERT_EQ(4, changes.at("family_members/1").at(0).field_new_value.get<int>()); ASSERT_EQ(std::string("Name"), changes.at("family_members/1").at(1).field_name); ASSERT_EQ(documents::session::DocumentsChanges::ChangeType::FIELD_CHANGED, changes.at("family_members/1").at(1).change); ASSERT_EQ(std::string("Hibernating Rhinos"), changes.at("family_members/1").at(1).field_old_value.get<std::string>()); ASSERT_EQ(std::string("RavenDB"), changes.at("family_members/1").at(1).field_new_value.get<std::string>()); ASSERT_EQ(std::string("Age"), changes.at("family_members/1").at(2).field_name); ASSERT_EQ(documents::session::DocumentsChanges::ChangeType::FIELD_CHANGED, changes.at("family_members/1").at(2).change); ASSERT_EQ(4, changes.at("family_members/1").at(2).field_old_value.get<int>()); ASSERT_EQ(8, changes.at("family_members/1").at(2).field_new_value.get<int>()); ASSERT_EQ(std::string("Name"), changes.at("family_members/1").at(3).field_name); ASSERT_EQ(documents::session::DocumentsChanges::ChangeType::FIELD_CHANGED, changes.at("family_members/1").at(3).change); ASSERT_EQ(std::string("RavenDB"), changes.at("family_members/1").at(3).field_old_value.get<std::string>()); ASSERT_EQ(std::string("Hibernating Rhinos"), changes.at("family_members/1").at(3).field_new_value.get<std::string>()); member1 = std::make_shared<infrastructure::entities::Member>(); member1->name = "Toli"; member1->age = 5; member2 = std::make_shared<infrastructure::entities::Member>(); member2->name = "Boki"; member2->age = 15; new_family->members = { member1, member2 }; changes = session.advanced().what_changed(); ASSERT_EQ(1, changes.size()); ASSERT_EQ(4, changes.at("family_members/1").size()); ASSERT_EQ(std::string("Age"), changes.at("family_members/1").at(0).field_name); ASSERT_EQ(documents::session::DocumentsChanges::ChangeType::FIELD_CHANGED, changes.at("family_members/1").at(0).change); ASSERT_EQ(8, changes.at("family_members/1").at(0).field_old_value.get<int>()); ASSERT_EQ(5, changes.at("family_members/1").at(0).field_new_value.get<int>()); ASSERT_EQ(std::string("Name"), changes.at("family_members/1").at(1).field_name); ASSERT_EQ(documents::session::DocumentsChanges::ChangeType::FIELD_CHANGED, changes.at("family_members/1").at(1).change); ASSERT_EQ(std::string("Hibernating Rhinos"), changes.at("family_members/1").at(1).field_old_value.get<std::string>()); ASSERT_EQ(std::string("Toli"), changes.at("family_members/1").at(1).field_new_value.get<std::string>()); ASSERT_EQ(std::string("Age"), changes.at("family_members/1").at(2).field_name); ASSERT_EQ(documents::session::DocumentsChanges::ChangeType::FIELD_CHANGED, changes.at("family_members/1").at(2).change); ASSERT_EQ(4, changes.at("family_members/1").at(2).field_old_value.get<int>()); ASSERT_EQ(15, changes.at("family_members/1").at(2).field_new_value.get<int>()); ASSERT_EQ(std::string("Name"), changes.at("family_members/1").at(3).field_name); ASSERT_EQ(documents::session::DocumentsChanges::ChangeType::FIELD_CHANGED, changes.at("family_members/1").at(3).change); ASSERT_EQ(std::string("RavenDB"), changes.at("family_members/1").at(3).field_old_value.get<std::string>()); ASSERT_EQ(std::string("Boki"), changes.at("family_members/1").at(3).field_new_value.get<std::string>()); } TEST_F(CrudTest, CrudOperationsWithArrayOfArrays) { { auto session = test_suite_store->get().open_session(); infrastructure::entities::Arr1 a1 = { {"a", "b"} }; infrastructure::entities::Arr1 a2 = { {"c", "d"} }; auto arr = std::make_shared<infrastructure::entities::Arr2>(); arr->arr1 = { a1, a2 }; session.store(arr, "arr/1", arr2_to_json); session.save_changes(); auto new_arr = session.load<infrastructure::entities::Arr2>("arr/1"); a1.str = { "d", "c" }; a2.str = { "a", "b" }; new_arr->arr1 = { a1, a2 }; auto what_changed = session.advanced().what_changed(); ASSERT_EQ(1, what_changed.size()); auto change = what_changed.at("arr/1"); ASSERT_EQ(4, change.size()); ASSERT_EQ(std::string("a"), change.at(0).field_old_value.get<std::string>()); ASSERT_EQ(std::string("d"), change.at(0).field_new_value.get<std::string>()); ASSERT_EQ(std::string("b"), change.at(1).field_old_value.get<std::string>()); ASSERT_EQ(std::string("c"), change.at(1).field_new_value.get<std::string>()); ASSERT_EQ(std::string("c"), change.at(2).field_old_value.get<std::string>()); ASSERT_EQ(std::string("a"), change.at(2).field_new_value.get<std::string>()); ASSERT_EQ(std::string("d"), change.at(3).field_old_value.get<std::string>()); ASSERT_EQ(std::string("b"), change.at(3).field_new_value.get<std::string>()); session.save_changes(); } { auto session = test_suite_store->get().open_session(); auto new_arr = session.load<infrastructure::entities::Arr2>("arr/1", arr2_from_json, arr2_to_json); infrastructure::entities::Arr1 a1 = { {"q", "w"} }; infrastructure::entities::Arr1 a2 = { {"a", "b"} }; new_arr->arr1 = { a1, a2 }; auto what_changed = session.advanced().what_changed(); ASSERT_EQ(1, what_changed.size()); auto change = what_changed.at("arr/1"); ASSERT_EQ(2, change.size()); ASSERT_EQ(std::string("d"), change.at(0).field_old_value.get<std::string>()); ASSERT_EQ(std::string("q"), change.at(0).field_new_value.get<std::string>()); ASSERT_EQ(std::string("c"), change.at(1).field_old_value.get<std::string>()); ASSERT_EQ(std::string("w"), change.at(1).field_new_value.get<std::string>()); session.save_changes(); } } TEST_F(CrudTest, CrudCanUpdatePropertyToNull) { { auto session = test_suite_store->get().open_session(); auto user = std::make_shared<infrastructure::entities::NullableUser>(); user->first_name = "user1"; session.store(user, "n_users/1"); session.save_changes(); } { auto session = test_suite_store->get().open_session(); auto user = session.load<infrastructure::entities::NullableUser>("n_users/1"); user->first_name.reset(); session.save_changes(); } { auto session = test_suite_store->get().open_session(); auto user = session.load<infrastructure::entities::NullableUser>("n_users/1"); ASSERT_FALSE(user->first_name.has_value()); } } TEST_F(CrudTest, CrudCanUpdatePropertyFromNullToObject) { { auto session = test_suite_store->get().open_session(); auto poc = std::make_shared<infrastructure::entities::Poc>(); poc->name = "User"; poc->obj.reset(); session.store(poc, "pocs/1"); session.save_changes(); } { auto session = test_suite_store->get().open_session(); auto poc = session.load<infrastructure::entities::Poc>("pocs/1"); ASSERT_FALSE(poc->obj.has_value()); auto user = infrastructure::entities::User(); poc->obj = user; session.save_changes(); } { auto session = test_suite_store->get().open_session(); auto poc = session.load<infrastructure::entities::Poc>("pocs/1"); ASSERT_TRUE(poc->obj.has_value()); } } }
35.491416
127
0.698652
maximburyak
a0c4df6d4a4f0f86192fb526beffa7382aa7c5c8
1,843
hpp
C++
libs/boost_1_72_0/boost/qvm/detail/mat_assign.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/qvm/detail/mat_assign.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/qvm/detail/mat_assign.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2008-2016 Emil Dotchevski and Reverge Studios, Inc. // 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 UUID_47136D2C385411E7BA27D3B681262D2E #define UUID_47136D2C385411E7BA27D3B681262D2E #include <boost/qvm/gen/mat_assign2.hpp> #include <boost/qvm/gen/mat_assign3.hpp> #include <boost/qvm/gen/mat_assign4.hpp> namespace boost { namespace qvm { namespace qvm_detail { template <int M, int N> struct assign_mm_defined { static bool const value = false; }; template <int I, int N> struct copy_matrix_elements { template <class A, class B> static BOOST_QVM_INLINE_CRITICAL void f(A &a, B const &b) { mat_traits<A>::template write_element<I / mat_traits<A>::cols, I % mat_traits<A>::cols>(a) = mat_traits<B>::template read_element<I / mat_traits<B>::cols, I % mat_traits<B>::cols>(b); copy_matrix_elements<I + 1, N>::f(a, b); } }; template <int N> struct copy_matrix_elements<N, N> { template <class A, class B> static BOOST_QVM_INLINE_CRITICAL void f(A &, B const &) {} }; } // namespace qvm_detail template <class A, class B> BOOST_QVM_INLINE_TRIVIAL typename boost::enable_if_c< is_mat<A>::value && is_mat<B>::value && mat_traits<A>::rows == mat_traits<B>::rows && mat_traits<A>::cols == mat_traits<B>::cols && !qvm_detail::assign_mm_defined<mat_traits<A>::rows, mat_traits<A>::cols>::value, A &>::type assign(A &a, B const &b) { qvm_detail::copy_matrix_elements<0, mat_traits<A>::rows * mat_traits<A>::cols>::f(a, b); return a; } } // namespace qvm } // namespace boost #endif
34.12963
79
0.640803
henrywarhurst
a0c54230530a77482bd12ab47c0275ea014096ed
9,633
cpp
C++
src/jdk.hotspot.agent/linux/native/libsaproc/dwarf.cpp
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
1
2020-12-26T04:52:15.000Z
2020-12-26T04:52:15.000Z
src/jdk.hotspot.agent/linux/native/libsaproc/dwarf.cpp
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
1
2020-12-26T04:57:19.000Z
2020-12-26T04:57:19.000Z
src/jdk.hotspot.agent/linux/native/libsaproc/dwarf.cpp
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
1
2021-12-06T01:13:18.000Z
2021-12-06T01:13:18.000Z
/* * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2020, NTT DATA. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #include <cstring> #include "dwarf.hpp" #include "libproc_impl.h" /* from read_leb128() in dwarf.c in binutils */ uintptr_t DwarfParser::read_leb(bool sign) { uintptr_t result = 0L; unsigned char b; unsigned int shift = 0; while (true) { b = *_buf++; result |= static_cast<uintptr_t>(b & 0x7f) << shift; shift += 7; if ((b & 0x80) == 0) { break; } } if (sign && (shift < (8 * sizeof(result))) && (b & 0x40)) { result |= static_cast<uintptr_t>(-1L) << shift; } return result; } uint64_t DwarfParser::get_entry_length() { uint64_t length = *(reinterpret_cast<uint32_t *>(_buf)); _buf += 4; if (length == 0xffffffff) { length = *(reinterpret_cast<uint64_t *>(_buf)); _buf += 8; } return length; } bool DwarfParser::process_cie(unsigned char *start_of_entry, uint32_t id) { unsigned char *orig_pos = _buf; _buf = start_of_entry - id; uint64_t length = get_entry_length(); if (length == 0L) { return false; } unsigned char *end = _buf + length; _buf += 4; // Skip ID (This value of CIE would be always 0) _buf++; // Skip version (assume to be "1") char *augmentation_string = reinterpret_cast<char *>(_buf); bool has_ehdata = (strcmp("eh", augmentation_string) == 0); _buf += strlen(augmentation_string) + 1; // includes '\0' if (has_ehdata) { _buf += sizeof(void *); // Skip EH data } _code_factor = read_leb(false); _data_factor = static_cast<int>(read_leb(true)); _return_address_reg = static_cast<enum DWARF_Register>(*_buf++); if (strpbrk(augmentation_string, "LP") != NULL) { // Language personality routine (P) and Language Specific Data Area (LSDA:L) // are not supported because we need compliant Unwind Library Interface, // but we want to unwind without it. // // Unwind Library Interface (SysV ABI AMD64 6.2) // https://software.intel.com/sites/default/files/article/402129/mpx-linux64-abi.pdf return false; } else if (strchr(augmentation_string, 'R') != NULL) { read_leb(false); // augmentation length _encoding = *_buf++; } // Clear state _current_pc = 0L; _cfa_reg = RSP; _return_address_reg = RA; _cfa_offset = 0; _ra_cfa_offset = 0; _bp_cfa_offset = 0; _bp_offset_available = false; parse_dwarf_instructions(0L, static_cast<uintptr_t>(-1L), end); _buf = orig_pos; return true; } void DwarfParser::parse_dwarf_instructions(uintptr_t begin, uintptr_t pc, const unsigned char *end) { uintptr_t operand1; _current_pc = begin; /* for remember state */ enum DWARF_Register rem_cfa_reg = MAX_VALUE; int rem_cfa_offset = 0; int rem_ra_cfa_offset = 0; int rem_bp_cfa_offset = 0; while ((_buf < end) && (_current_pc < pc)) { unsigned char op = *_buf++; unsigned char opa = op & 0x3f; if (op & 0xc0) { op &= 0xc0; } switch (op) { case 0x0: // DW_CFA_nop return; case 0x01: // DW_CFA_set_loc operand1 = get_decoded_value(); if (_current_pc != 0L) { _current_pc = operand1; } break; case 0x0c: // DW_CFA_def_cfa _cfa_reg = static_cast<enum DWARF_Register>(read_leb(false)); _cfa_offset = read_leb(false); break; case 0x80: {// DW_CFA_offset operand1 = read_leb(false); enum DWARF_Register reg = static_cast<enum DWARF_Register>(opa); if (reg == RBP) { _bp_cfa_offset = operand1 * _data_factor; _bp_offset_available = true; } else if (reg == RA) { _ra_cfa_offset = operand1 * _data_factor; } break; } case 0xe: // DW_CFA_def_cfa_offset _cfa_offset = read_leb(false); break; case 0x40: // DW_CFA_advance_loc if (_current_pc != 0L) { _current_pc += opa * _code_factor; } break; case 0x02: { // DW_CFA_advance_loc1 unsigned char ofs = *_buf++; if (_current_pc != 0L) { _current_pc += ofs * _code_factor; } break; } case 0x03: { // DW_CFA_advance_loc2 unsigned short ofs = *(reinterpret_cast<unsigned short *>(_buf)); _buf += 2; if (_current_pc != 0L) { _current_pc += ofs * _code_factor; } break; } case 0x04: { // DW_CFA_advance_loc4 unsigned int ofs = *(reinterpret_cast<unsigned int *>(_buf)); _buf += 4; if (_current_pc != 0L) { _current_pc += ofs * _code_factor; } break; } case 0x0d: {// DW_CFA_def_cfa_register _cfa_reg = static_cast<enum DWARF_Register>(read_leb(false)); break; } case 0x0a: // DW_CFA_remember_state rem_cfa_reg = _cfa_reg; rem_cfa_offset = _cfa_offset; rem_ra_cfa_offset = _ra_cfa_offset; rem_bp_cfa_offset = _bp_cfa_offset; break; case 0x0b: // DW_CFA_restore_state _cfa_reg = rem_cfa_reg; _cfa_offset = rem_cfa_offset; _ra_cfa_offset = rem_ra_cfa_offset; _bp_cfa_offset = rem_bp_cfa_offset; break; default: print_debug("DWARF: Unknown opcode: 0x%x\n", op); return; } } } /* from dwarf.c in binutils */ uint32_t DwarfParser::get_decoded_value() { int size; uintptr_t result; switch (_encoding & 0x7) { case 0: // DW_EH_PE_absptr size = sizeof(void *); result = *(reinterpret_cast<uintptr_t *>(_buf)); break; case 2: // DW_EH_PE_udata2 size = 2; result = *(reinterpret_cast<unsigned int *>(_buf)); break; case 3: // DW_EH_PE_udata4 size = 4; result = *(reinterpret_cast<uint32_t *>(_buf)); break; case 4: // DW_EH_PE_udata8 size = 8; result = *(reinterpret_cast<uint64_t *>(_buf)); break; default: return 0; } // On x86-64, we have to handle it as 32 bit value, and it is PC relative. // https://gcc.gnu.org/ml/gcc-help/2010-09/msg00166.html #if defined(_LP64) if (size == 8) { result += _lib->eh_frame.v_addr + static_cast<uintptr_t>(_buf - _lib->eh_frame.data); size = 4; } else #endif if ((_encoding & 0x70) == 0x10) { // 0x10 = DW_EH_PE_pcrel result += _lib->eh_frame.v_addr + static_cast<uintptr_t>(_buf - _lib->eh_frame.data); } else if (size == 2) { result = static_cast<int>(result) + _lib->eh_frame.v_addr + static_cast<uintptr_t>(_buf - _lib->eh_frame.data); size = 4; } _buf += size; return static_cast<uint32_t>(result); } unsigned int DwarfParser::get_pc_range() { int size; uintptr_t result; switch (_encoding & 0x7) { case 0: // DW_EH_PE_absptr size = sizeof(void *); result = *(reinterpret_cast<uintptr_t *>(_buf)); break; case 2: // DW_EH_PE_udata2 size = 2; result = *(reinterpret_cast<unsigned int *>(_buf)); break; case 3: // DW_EH_PE_udata4 size = 4; result = *(reinterpret_cast<uint32_t *>(_buf)); break; case 4: // DW_EH_PE_udata8 size = 8; result = *(reinterpret_cast<uint64_t *>(_buf)); break; default: return 0; } // On x86-64, we have to handle it as 32 bit value, and it is PC relative. // https://gcc.gnu.org/ml/gcc-help/2010-09/msg00166.html #if defined(_LP64) if ((size == 8) || (size == 2)) { size = 4; } #endif _buf += size; return static_cast<unsigned int>(result); } bool DwarfParser::process_dwarf(const uintptr_t pc) { // https://refspecs.linuxfoundation.org/LSB_3.0.0/LSB-PDA/LSB-PDA/ehframechpt.html _buf = _lib->eh_frame.data; unsigned char *end = _lib->eh_frame.data + _lib->eh_frame.size; while (_buf <= end) { uint64_t length = get_entry_length(); if (length == 0L) { return false; } unsigned char *next_entry = _buf + length; unsigned char *start_of_entry = _buf; uint32_t id = *(reinterpret_cast<uint32_t *>(_buf)); _buf += 4; if (id != 0) { // FDE uintptr_t pc_begin = get_decoded_value() + _lib->eh_frame.library_base_addr; uintptr_t pc_end = pc_begin + get_pc_range(); if ((pc >= pc_begin) && (pc < pc_end)) { // Process CIE if (!process_cie(start_of_entry, id)) { return false; } // Skip Augumenation uintptr_t augmentation_length = read_leb(false); _buf += augmentation_length; // skip // Process FDE parse_dwarf_instructions(pc_begin, pc, next_entry); return true; } } _buf = next_entry; } return false; }
29.190909
115
0.624312
1690296356
a0c6fa4bf069a12fe5d38dc094816ca3add356f6
5,993
cxx
C++
madym/tools/tests/test_madym_DCE_lite.cxx
michaelberks/madym_cxx
647b6e59a3ef7aa6b3f3f58e16d23dc313b7dd16
[ "Apache-2.0" ]
1
2021-10-04T15:43:15.000Z
2021-10-04T15:43:15.000Z
madym/tools/tests/test_madym_DCE_lite.cxx
michaelberks/madym_cxx
647b6e59a3ef7aa6b3f3f58e16d23dc313b7dd16
[ "Apache-2.0" ]
null
null
null
madym/tools/tests/test_madym_DCE_lite.cxx
michaelberks/madym_cxx
647b6e59a3ef7aa6b3f3f58e16d23dc313b7dd16
[ "Apache-2.0" ]
null
null
null
#include <boost/test/unit_test.hpp> #include <boost/format.hpp> #include <fstream> #include <madym/tests/mdm_test_utils.h> #include <madym/t1_methods/mdm_T1FitterBase.h> #include <mdm_version.h> #include <madym/mdm_AIF.h> #include <madym/dce_models/mdm_DCEModelGenerator.h> namespace fs = boost::filesystem; BOOST_AUTO_TEST_SUITE(test_mdm_tools) BOOST_AUTO_TEST_CASE(test_madym_lite) { BOOST_TEST_MESSAGE("======= Testing tool: madym_DCE_lite ======="); //Need to generate input data files. To do this, load in calibration //data //Read in dyn times int nTimes; std::string timesFileName(mdm_test_utils::calibration_dir() + "dyn_times.dat"); std::ifstream timesFileStream(timesFileName, std::ios::in | std::ios::binary); timesFileStream.read(reinterpret_cast<char*>(&nTimes), sizeof(int)); std::vector<double> dynTimes(nTimes); for (double &t : dynTimes) timesFileStream.read(reinterpret_cast<char*>(&t), sizeof(double)); timesFileStream.close(); //Read in AIF parameters int injectionImage; double hct; double dose; std::string aifFileName(mdm_test_utils::calibration_dir() + "aif.dat"); std::ifstream aifFileStream(aifFileName, std::ios::in | std::ios::binary); aifFileStream.read(reinterpret_cast<char*>(&injectionImage), sizeof(int)); aifFileStream.read(reinterpret_cast<char*>(&hct), sizeof(double)); aifFileStream.read(reinterpret_cast<char*>(&dose), sizeof(double)); aifFileStream.close(); //Read (noisy) ETM times series from calibration data int nParams; std::vector<double> Ct(nTimes); std::string modelFileName = mdm_test_utils::calibration_dir() + "ETM_noise.dat"; std::ifstream modelFileStream(modelFileName, std::ios::in | std::ios::binary); modelFileStream.read(reinterpret_cast<char*>(&nParams), sizeof(int)); std::vector<double> trueParams(nParams); for (double &p : trueParams) modelFileStream.read(reinterpret_cast<char*>(&p), sizeof(double)); for (double &c : Ct) modelFileStream.read(reinterpret_cast<char*>(&c), sizeof(double)); modelFileStream.close(); //Read IAUC values int nIAUC; std::string iaucFileName = mdm_test_utils::calibration_dir() + "ETM_IAUC.dat"; std::ifstream iaucFileStream(iaucFileName, std::ios::in | std::ios::binary); iaucFileStream.read(reinterpret_cast<char*>(&nIAUC), sizeof(int)); std::vector<double> IAUCTimes(nIAUC); std::vector<double> IAUCVals(nIAUC); for (double &it : IAUCTimes) iaucFileStream.read(reinterpret_cast<char*>(&it), sizeof(double)); for (double &iv : IAUCVals) iaucFileStream.read(reinterpret_cast<char*>(&iv), sizeof(double)); iaucFileStream.close(); std::string IAUC_str = std::to_string((int)IAUCTimes[0]); for (int i = 1; i < nIAUC; i++) IAUC_str += ("," + std::to_string((int)IAUCTimes[i])); //Create a temporary directory where we'll run these tests, which we can then cleanup //easily at the end std::string test_dir = mdm_test_utils::temp_dir(); //Write out the concentration times std::string inputDataFile = test_dir + "/Ct_input.dat"; std::ofstream ifs(inputDataFile, std::ios::out); BOOST_REQUIRE_MESSAGE(ifs.is_open(), "Failed to write out Ct values for madym_DCE_lite"); for (const auto c : Ct) ifs << c << " "; ifs.close(); //Writeout the dynamic time std::string dynTimesFile = test_dir + "/dyn_times.dat"; std::ofstream dfs(dynTimesFile, std::ios::out); BOOST_REQUIRE_MESSAGE(dfs.is_open(), "Failed to write out dyn times values for madym_DCE_lite"); for (const auto t : dynTimes) dfs << t << " "; dfs.close(); //Call madym_lite to fit ETM std::string Ct_output_dir = test_dir + "/madym_DCE_lite/"; std::string outputName = "madym_analysis.dat"; std::stringstream cmd; cmd << mdm_test_utils::tools_exe_dir() << "madym_DCE_lite" << " -m ETM" << " --data " << inputDataFile << " -n " << nTimes << " -I " << IAUC_str << " -i " << injectionImage << " -o " << Ct_output_dir << " -O " << outputName << " --Ct" << " -t " << dynTimesFile; BOOST_TEST_MESSAGE("Command to run: " + cmd.str()); int error; try { error = std::system(cmd.str().c_str()); } catch (...) { BOOST_CHECK_MESSAGE(false, "Running madym_DCE_lite failed"); return; } BOOST_CHECK_MESSAGE(!error, "Error returned from madym_DCE_lite tool"); //Load in the fitted parameters from the output file std::string outputDataFile = Ct_output_dir + "ETM_" + outputName; std::ifstream ofs(outputDataFile, std::ios::in); BOOST_REQUIRE_MESSAGE(ofs.is_open(), "Failed to read in fitted values for ETM"); int fit_errors, enhancing; double model_fit, ktrans_fit, ve_fit, vp_fit, tau_fit; std::vector<double> IAUC_fit(nIAUC); ofs >> fit_errors; ofs >> enhancing; ofs >> model_fit; for (auto &i : IAUC_fit) ofs >> i; ofs >> ktrans_fit; ofs >> ve_fit; ofs >> vp_fit; ofs >> tau_fit; ofs.close(); //Check the model parameters have fitted correctly double tol = 1.0; BOOST_TEST_MESSAGE(boost::format("Fitted ktrans (%1.2f, %2.2f)") % ktrans_fit % trueParams[0]); BOOST_CHECK_CLOSE(ktrans_fit, trueParams[0], tol); BOOST_TEST_MESSAGE(boost::format("Fitted Ve (%1.2f, %2.2f)") % ve_fit % trueParams[1]); BOOST_CHECK_CLOSE(ve_fit, trueParams[1], tol); BOOST_TEST_MESSAGE(boost::format("Fitted Vp (%1.2f, %2.2f)") % vp_fit % trueParams[2]); BOOST_CHECK_CLOSE(vp_fit, trueParams[2], tol); BOOST_TEST_MESSAGE(boost::format("Fitted tau (%1.2f, %2.2f)") % tau_fit % trueParams[3]); BOOST_CHECK_CLOSE(tau_fit, trueParams[3], tol); //Check model fit, error codes and enhancing BOOST_TEST_MESSAGE(boost::format("Model residuals = %1%") % model_fit); BOOST_CHECK_SMALL(model_fit, 0.01); BOOST_TEST_MESSAGE("No error code"); BOOST_CHECK(!fit_errors); BOOST_TEST_MESSAGE("Enhancing"); BOOST_CHECK(enhancing); for (int i = 0; i < nIAUC; i++) { BOOST_TEST_MESSAGE("IAUC " + std::to_string(IAUCTimes[i])); BOOST_CHECK_CLOSE(IAUC_fit[i], IAUCVals[i], tol); } //Tidy up fs::remove(inputDataFile); fs::remove(dynTimesFile); fs::remove_all(Ct_output_dir); } BOOST_AUTO_TEST_SUITE_END() //
32.394595
97
0.710662
michaelberks
a0c911dbc210a025e45adbbeddc40432b92224ed
21,504
hpp
C++
srook/numeric/fixed_point/fixed_point.hpp
falgon/srookCppLibraries
ebcfacafa56026f6558bcd1c584ec774cc751e57
[ "MIT" ]
1
2018-07-01T07:54:37.000Z
2018-07-01T07:54:37.000Z
srook/numeric/fixed_point/fixed_point.hpp
falgon/srookCppLibraries
ebcfacafa56026f6558bcd1c584ec774cc751e57
[ "MIT" ]
null
null
null
srook/numeric/fixed_point/fixed_point.hpp
falgon/srookCppLibraries
ebcfacafa56026f6558bcd1c584ec774cc751e57
[ "MIT" ]
null
null
null
// Copyright (C) 2011-2020 Roki. Distributed under the MIT License #ifndef INCLUDED_SROOK_NUMERIC_FIXED_POINT_FIXED_POINT_HPP #define INCLUDED_SROOK_NUMERIC_FIXED_POINT_FIXED_POINT_HPP #ifdef _MSC_VER # if _MSC_VER > 1000 # pragma once # endif #endif #include <srook/numeric/fixed_point/detail/config.hpp> #include <srook/math/constants/algorithm/isnan.hpp> #include <srook/math/constants/algorithm/isinf.hpp> #include <srook/functional/op.hpp> #include <srook/algorithm/max.hpp> #include <srook/type_traits/is_arithmetic.hpp> #include <srook/bit/algorithm/nlz.hpp> #include <srook/tmpl/vt/compare/lt.hpp> #include <ostream> #include <stdexcept> #ifdef SROOK_FUNC_NAME # include <string> # define SROOK_FIXED_POINT_THROW_OVERFLOW(x) SROOK_THROW std::overflow_error(std::string("srook::numeric_limits::fixed_point::") + SROOK_FUNC_NAME + ": " + #x) # define SROOK_FIXED_POINT_THROW_UNDERFLOW(x) SROOK_THROW std::underflow_error(std::string("srook::numeric_limits::fixed_point::") + SROOK_FUNC_NAME + ": " + #x) #else # define SROOK_FIXED_POINT_THROW_OVERFLOW SROOK_THROW std::overflow_error("srook::numeric_limits::fixed_point: " #x) # define SROOK_FIXED_POINT_THROW_UNDERFLOW SROOK_THROW std::underflow_error("srook::numeric_limits::fixed_point: " #x) #endif SROOK_NESTED_NAMESPACE(srook, numeric) { SROOK_INLINE_NAMESPACE(v1) template <std::size_t I, std::size_t F> class fixed_point { public: struct fixed_point_tag {}; // composed only typedef detail::fixed_point_traits<I + F> traits_type; typedef SROOK_DEDUCED_TYPENAME traits_type::size_type size_type; typedef SROOK_DEDUCED_TYPENAME traits_type::value_type value_type; typedef SROOK_DEDUCED_TYPENAME traits_type::next_fixed_point::value_type next_value_type; typedef SROOK_DEDUCED_TYPENAME traits_type::unsigned_type unsigned_value_type; static SROOK_INLINE_VARIABLE SROOK_CONSTEXPR_OR_CONST size_type fractional_bits = F; static SROOK_INLINE_VARIABLE SROOK_CONSTEXPR_OR_CONST size_type integer_bits = I; static SROOK_INLINE_VARIABLE SROOK_CONSTEXPR_OR_CONST size_type total_bits = I + F; static SROOK_INLINE_VARIABLE const value_type fractional_mask = ~((~value_type(0)) << fractional_bits); static SROOK_INLINE_VARIABLE const value_type integer_mask = ~fractional_mask; static SROOK_INLINE_VARIABLE SROOK_CONSTEXPR_OR_CONST value_type one = value_type(1) << fractional_bits; SROOK_CONSTEXPR fixed_point() SROOK_DEFAULT SROOK_CONSTEXPR fixed_point(const fixed_point&) SROOK_DEFAULT template <typename ValueType, SROOK_REQUIRES(type_traits::detail::Land<type_traits::detail::Lnot<is_same<ValueType, fixed_point>>, is_integral<ValueType>>::value)> fixed_point(ValueType n) SROOK_NOEXCEPT(false) : data_(assert_integer(srook::move(n), SROOK_DEDUCED_TYPENAME compare<ValueType>::type())) {} template <typename ValueType, SROOK_REQUIRES(type_traits::detail::Land<type_traits::detail::Lnot<is_same<ValueType, fixed_point>>, is_floating_point<ValueType>>::value)> fixed_point(ValueType n) SROOK_NOEXCEPT(false) : data_(assert_floating(srook::move(n))) {} static SROOK_CONSTEXPR fixed_point from_value(value_type n) SROOK_NOEXCEPT(is_nothrow_constructible<value_type>::value) { return fixed_point(srook::move(n), noscale()); } #if 0 && SROOK_HAS_INCLUDE(<compare>) SROOK_CONSTEXPR std::strong_ordering operator<=>(const fixed_point& other) const SROOK_NOEXCEPT_TRUE { return data_ <=> other.data_; } #else SROOK_CONSTEXPR bool operator==(const fixed_point& other) const SROOK_NOEXCEPT_TRUE { return data_ == other.data_; } SROOK_CONSTEXPR bool operator!=(const fixed_point& other) const SROOK_NOEXCEPT_TRUE { return !(*this == other); } SROOK_CONSTEXPR bool operator<(const fixed_point& other) const SROOK_NOEXCEPT_TRUE { return data_ < other.data_; } SROOK_CONSTEXPR bool operator<=(const fixed_point& other) const SROOK_NOEXCEPT_TRUE { return *this == other || *this < other; } SROOK_CONSTEXPR bool operator>(const fixed_point& other) const SROOK_NOEXCEPT_TRUE { return !(*this <= other); } SROOK_CONSTEXPR bool operator>=(const fixed_point& other) const SROOK_NOEXCEPT_TRUE { return *this > other || *this == other; } #endif SROOK_CONSTEXPR bool operator!() const SROOK_NOEXCEPT_TRUE { return !data_; } SROOK_CXX14_CONSTEXPR fixed_point operator~() const SROOK_NOEXCEPT_TRUE { fixed_point t(*this); t.data_ = static_cast<value_type>(~t.data_); return t; } SROOK_CXX14_CONSTEXPR fixed_point operator-() const SROOK_NOEXCEPT_TRUE { fixed_point t(*this); t.data_ = static_cast<value_type>(-t.data_); return t; } SROOK_CONSTEXPR fixed_point operator+() const SROOK_NOEXCEPT_TRUE { return *this; } SROOK_FORCE_INLINE fixed_point& operator++() SROOK_NOEXCEPT_TRUE { data_ = static_cast<value_type>(data_ + one); return *this; } SROOK_FORCE_INLINE fixed_point& increment() { data_ = numeric_limits<value_type>::max() >= data_ + one ? static_cast<value_type>(data_ + one) : SROOK_FIXED_POINT_THROW_OVERFLOW(overflow); return *this; } SROOK_FORCE_INLINE fixed_point& operator--() SROOK_NOEXCEPT_TRUE { data_ = static_cast<value_type>(data_ - one); return *this; } SROOK_FORCE_INLINE fixed_point& decrement() { data_ = numeric_limits<value_type>::min() <= data_ - one ? static_cast<value_type>(data_ - one) : SROOK_FIXED_POINT_THROW_UNDERFLOW(underflow); return *this; } SROOK_FORCE_INLINE fixed_point operator++(int) SROOK_NOEXCEPT_TRUE { fixed_point t(*this); ++*this; return t; } SROOK_FORCE_INLINE fixed_point post_increment() { fixed_point t(*this); increment(); return t; } SROOK_FORCE_INLINE fixed_point operator--(int) SROOK_NOEXCEPT_TRUE { fixed_point t(*this); --*this; return t; } SROOK_FORCE_INLINE fixed_point post_decrement() { fixed_point t(*this); decrement(); return t; } #define SROOK_DEF_INPLACE_OPERATORS(OPERATOR)\ SROOK_FORCE_INLINE fixed_point& operator OPERATOR##=(const fixed_point& other) SROOK_NOEXCEPT_TRUE\ {\ data_ = static_cast<value_type>(data_ OPERATOR other.data_);\ return *this;\ } SROOK_DEF_INPLACE_OPERATORS(+) SROOK_DEF_INPLACE_OPERATORS(-) SROOK_DEF_INPLACE_OPERATORS(|) SROOK_DEF_INPLACE_OPERATORS(^) SROOK_DEF_INPLACE_OPERATORS(&) SROOK_FORCE_INLINE fixed_point& operator*=(const fixed_point& other) SROOK_NOEXCEPT_TRUE { return multiply(other); } SROOK_FORCE_INLINE fixed_point& operator/=(const fixed_point& other) SROOK_NOEXCEPT_TRUE { return divide(other); } SROOK_FORCE_INLINE fixed_point& operator>>=(const fixed_point& other) SROOK_NOEXCEPT_TRUE { data_ >>= static_cast<int>(other); return *this; } SROOK_FORCE_INLINE fixed_point& operator<<=(const fixed_point& other) SROOK_NOEXCEPT_TRUE { data_ <<= static_cast<int>(other); return *this; } #undef SROOK_DEF_INPLACE_OPERATORS SROOK_FORCE_INLINE fixed_point& iadd(const fixed_point& other) { data_ = numeric_limits<value_type>::max() >= data_ + other.data_ ? static_cast<value_type>(data_ + other.data_) : SROOK_FIXED_POINT_THROW_OVERFLOW(overflow); return *this; } SROOK_FORCE_INLINE fixed_point& isub(const fixed_point& other) { data_ = numeric_limits<value_type>::min() <= data_ - other.data_ ? static_cast<value_type>(data_ - other.data_) : SROOK_FIXED_POINT_THROW_UNDERFLOW(underflow); return *this; } SROOK_FORCE_INLINE fixed_point& imul(const fixed_point& other) { (numeric_limits<value_type>::max() >= (other.data_ * data_)) ? multiply(other) : SROOK_FIXED_POINT_THROW_OVERFLOW(overflow); return *this; } SROOK_FORCE_INLINE fixed_point& idiv(const fixed_point& other) { return divide(other); } template <typename T, SROOK_REQUIRES(is_integral<T>::value)> SROOK_EXPLICIT SROOK_CONSTEXPR operator T() const { return (data_ & integer_mask) >> fractional_bits; } template <typename T, SROOK_REQUIRES(is_floating_point<T>::value)> SROOK_EXPLICIT SROOK_CONSTEXPR operator T() const { return static_cast<T>(data_) / one; } SROOK_CXX14_CONSTEXPR void swap(fixed_point& other) SROOK_NOEXCEPT_TRUE { using std::swap; swap(data_, other.data_); } private: struct noscale {}; fixed_point(value_type n, const noscale&) : data_(srook::move(n)) {} template <class T> struct compare : conditional<is_signed<T>::value, std::greater<size_type>, std::greater_equal<size_type>> {}; template <typename ValueType, class Compare, SROOK_REQUIRES(is_integral<ValueType>::value)> SROOK_CONSTEXPR value_type assert_integer(ValueType x, Compare comp) { return comp(integer_bits, numeric_limits<ValueType>::digits - srook::bit::algorithm::nlz(x)) ? static_cast<value_type>(x << fractional_bits) : SROOK_FIXED_POINT_THROW_OVERFLOW(overflow); } template <typename ValueType, SROOK_REQUIRES(is_floating_point<ValueType>::value)> SROOK_CONSTEXPR value_type assert_floating(ValueType x) { return !srook::math::isnan(x) ? !srook::math::isinf(x) ? (numeric_limits<value_type>::max() >= x * one ? static_cast<value_type>(x * one) : SROOK_FIXED_POINT_THROW_OVERFLOW(overflow)) : SROOK_FIXED_POINT_THROW_OVERFLOW(Inf has been detected) : SROOK_FIXED_POINT_THROW_OVERFLOW(NaN has been detected); } template <class This, SROOK_REQUIRES(type_traits::detail::Land<is_same<This, fixed_point>, bool_constant<traits_type::next_fixed_point::is_specialized>>::value)> SROOK_FORCE_INLINE fixed_point& multiply(const This& other) { return *this = from_value( static_cast<value_type>( next_value_type(static_cast<next_value_type>((static_cast<next_value_type>(data_) * static_cast<next_value_type>(other.data_)) >> fractional_bits)) ) ); } template <class This, SROOK_REQUIRES(type_traits::detail::Land<is_same<This, fixed_point>, bool_constant<!traits_type::next_fixed_point::is_specialized>>::value)> SROOK_FORCE_INLINE fixed_point& multiply(const This& other) { const value_type ahi = (data_ & integer_mask) >> fractional_bits, bhi = (other.data_ & integer_mask) >> fractional_bits, alo = (data_ & fractional_mask), blo = (other.data_ & fractional_mask); const value_type x1 = ahi * bhi, x2 = ahi * blo, x3 = alo * bhi, x4 = alo * blo; return *this = from_value((x1 << fractional_bits) + (x3 + x2) + (x4 >> fractional_bits)); } // Ref: http://www.artist-embedded.org/docs/Events/2009/EmbeddedControl/SLIDES/FixPoint.pdf template <class This, SROOK_REQUIRES(type_traits::detail::Land<is_same<This, fixed_point>, bool_constant<traits_type::next_fixed_point::is_specialized>>::value)> SROOK_FORCE_INLINE fixed_point& divide(const This& other) { return *this = from_value(static_cast<value_type>((static_cast<next_value_type>(data_) << fractional_bits) / other.data_)); } //TODO: for bool_constant<!traits_type::next_fixed_point::is_specialized> implementation friend SROOK_FORCE_INLINE std::ostream& operator<<(std::ostream& os, const fixed_point& this_) { return os << static_cast<double>(this_); } // operator with over difference integer part #define SROOK_DEF_DIFF_INTEGER_OPERATION(OPERATOR)\ template <std::size_t I1>\ friend SROOK_FORCE_INLINE SROOK_CONSTEXPR fixed_point<srook::algorithm::max(I, I1), F> operator OPERATOR(const fixed_point& lhs, const fixed_point<I1, F>& rhs)\ {\ typedef fixed_point<srook::algorithm::max(I, I1), F> return_type;\ return return_type::from_value(lhs.data_ OPERATOR rhs.data_);\ } SROOK_DEF_DIFF_INTEGER_OPERATION(+) SROOK_DEF_DIFF_INTEGER_OPERATION(-) SROOK_DEF_DIFF_INTEGER_OPERATION(*) SROOK_DEF_DIFF_INTEGER_OPERATION(/) #undef SROOK_DEF_DIFF_INTEGER_OPERATION private: value_type data_; }; // compare operator with fundamental types template <std::size_t I, std::size_t F, class Arithmetic, SROOK_REQUIRES(is_arithmetic<Arithmetic>::value)> SROOK_CONSTEXPR bool operator==(const fixed_point<I, F>& f, Arithmetic x) SROOK_NOEXCEPT_TRUE { return static_cast<Arithmetic>(f) == x; } template <std::size_t I, std::size_t F, class Arithmetic, SROOK_REQUIRES(is_arithmetic<Arithmetic>::value)> SROOK_CONSTEXPR bool operator==(Arithmetic x, const fixed_point<I, F>& f) SROOK_NOEXCEPT_TRUE { return f == x; } template <std::size_t I, std::size_t F, class Arithmetic, SROOK_REQUIRES(is_arithmetic<Arithmetic>::value)> SROOK_CONSTEXPR bool operator!=(const fixed_point<I, F>& f, Arithmetic x) SROOK_NOEXCEPT_TRUE { return !(f == x); } template <std::size_t I, std::size_t F, class Arithmetic, SROOK_REQUIRES(is_arithmetic<Arithmetic>::value)> SROOK_CONSTEXPR bool operator!=(Arithmetic x, const fixed_point<I, F>& f) SROOK_NOEXCEPT_TRUE { return f != x; } template <std::size_t I, std::size_t F, class Arithmetic, SROOK_REQUIRES(is_arithmetic<Arithmetic>::value)> SROOK_CONSTEXPR bool operator<(const fixed_point<I, F>& f, Arithmetic x) SROOK_NOEXCEPT_TRUE { return static_cast<Arithmetic>(f) < x; } template <std::size_t I, std::size_t F, class Arithmetic, SROOK_REQUIRES(is_arithmetic<Arithmetic>::value)> SROOK_CONSTEXPR bool operator<(Arithmetic x, const fixed_point<I, F>& f) SROOK_NOEXCEPT_TRUE { return !(f < x) && x != f; } template <std::size_t I, std::size_t F, class Arithmetic, SROOK_REQUIRES(is_arithmetic<Arithmetic>::value)> SROOK_CONSTEXPR bool operator>(const fixed_point<I, F>& f, Arithmetic x) SROOK_NOEXCEPT_TRUE { return x < f; } template <std::size_t I, std::size_t F, class Arithmetic, SROOK_REQUIRES(is_arithmetic<Arithmetic>::value)> SROOK_CONSTEXPR bool operator>(Arithmetic x, const fixed_point<I, F>& f) SROOK_NOEXCEPT_TRUE { return f < x; } template <std::size_t I, std::size_t F, class Arithmetic, SROOK_REQUIRES(is_arithmetic<Arithmetic>::value)> SROOK_CONSTEXPR bool operator<=(Arithmetic x, const fixed_point<I, F>& f) SROOK_NOEXCEPT_TRUE { return x < f || x == f; } template <std::size_t I, std::size_t F, class Arithmetic, SROOK_REQUIRES(is_arithmetic<Arithmetic>::value)> SROOK_CONSTEXPR bool operator<=(const fixed_point<I, F>& f, Arithmetic x) SROOK_NOEXCEPT_TRUE { return f < x || x == f; } template <std::size_t I, std::size_t F, class Arithmetic, SROOK_REQUIRES(is_arithmetic<Arithmetic>::value)> SROOK_CONSTEXPR bool operator>=(Arithmetic x, const fixed_point<I, F>& f) SROOK_NOEXCEPT_TRUE { return x > f || x == f; } template <std::size_t I, std::size_t F, class Arithmetic, SROOK_REQUIRES(is_arithmetic<Arithmetic>::value)> SROOK_CONSTEXPR bool operator>=(const fixed_point<I, F>& f, Arithmetic x) SROOK_NOEXCEPT_TRUE { return f > x || x == f; } // arithmetic operator with fundamental types namespace detail { template <std::size_t I, std::size_t F, class Arithmetic, class Operator, SROOK_REQUIRES(srook::tmpl::vt::lt<SROOK_DEDUCED_TYPENAME fixed_point<I, F>::value_type, Arithmetic>::type::value)> SROOK_CONSTEXPR fixed_point<I, F> operation(const fixed_point<I, F>& f, Arithmetic x, Operator op) SROOK_NOEXCEPT_TRUE { return op(f, fixed_point<I, F>(x)); } template <std::size_t I, std::size_t F, class Arithmetic, class Operator, SROOK_REQUIRES(srook::tmpl::vt::lt<SROOK_DEDUCED_TYPENAME fixed_point<I, F>::value_type, Arithmetic>::type::value)> SROOK_CONSTEXPR fixed_point<I, F> operation(Arithmetic x, const fixed_point<I, F>& f, Operator op) SROOK_NOEXCEPT_TRUE { return op(fixed_point<I, F>(x), f); } template <std::size_t I, std::size_t F, class Arithmetic, class Operator, SROOK_REQUIRES(type_traits::detail::Lnot<SROOK_DEDUCED_TYPENAME srook::tmpl::vt::lt<SROOK_DEDUCED_TYPENAME fixed_point<I, F>::value_type, Arithmetic>::type>::value)> SROOK_CONSTEXPR Arithmetic operation(const fixed_point<I, F>& f, Arithmetic x, Operator op) SROOK_NOEXCEPT_TRUE { return op(static_cast<Arithmetic>(f), x); } template <std::size_t I, std::size_t F, class Arithmetic, class Operator, SROOK_REQUIRES(type_traits::detail::Lnot<SROOK_DEDUCED_TYPENAME srook::tmpl::vt::lt<SROOK_DEDUCED_TYPENAME fixed_point<I, F>::value_type, Arithmetic>::type>::value)> SROOK_CONSTEXPR Arithmetic operation(Arithmetic x, const fixed_point<I, F>& f, Operator op) SROOK_NOEXCEPT_TRUE { return op(x, static_cast<Arithmetic>(f)); } } // namespace detail template <std::size_t I, std::size_t F, class Arithmetic, SROOK_REQUIRES(is_arithmetic<Arithmetic>::value)> SROOK_CONSTEXPR auto operator+(const fixed_point<I, F>& f, Arithmetic x) SROOK_NOEXCEPT_TRUE -> SROOK_DECLTYPE(detail::operation(f, x, srook::functional::deduction_plus())) { return detail::operation(f, x, srook::functional::deduction_plus()); } template <std::size_t I, std::size_t F, class Arithmetic, SROOK_REQUIRES(is_arithmetic<Arithmetic>::value)> SROOK_CONSTEXPR auto operator+(Arithmetic x, const fixed_point<I, F>& f) SROOK_NOEXCEPT_TRUE -> SROOK_DECLTYPE(f + x) { return f + x; } template <std::size_t I, std::size_t F, class Arithmetic, SROOK_REQUIRES(is_arithmetic<Arithmetic>::value)> SROOK_CONSTEXPR auto operator*(const fixed_point<I, F>& f, Arithmetic x) SROOK_NOEXCEPT_TRUE -> SROOK_DECLTYPE(detail::operation(f, x, srook::functional::deduction_multiplies())) { return detail::operation(f, x, srook::functional::deduction_multiplies()); } template <std::size_t I, std::size_t F, class Arithmetic, SROOK_REQUIRES(is_arithmetic<Arithmetic>::value)> SROOK_CONSTEXPR auto operator*(Arithmetic x, const fixed_point<I, F>& f) SROOK_NOEXCEPT_TRUE -> SROOK_DECLTYPE(f * x) { return f * x; } template <std::size_t I, std::size_t F, class Arithmetic, SROOK_REQUIRES(is_arithmetic<Arithmetic>::value)> SROOK_CONSTEXPR auto operator-(const fixed_point<I, F>& f, Arithmetic x) SROOK_NOEXCEPT_TRUE -> SROOK_DECLTYPE(detail::operation(f, x, srook::functional::deduction_minus())) { return detail::operation(f, x, srook::functional::deduction_minus()); } template <std::size_t I, std::size_t F, class Arithmetic, SROOK_REQUIRES(is_arithmetic<Arithmetic>::value)> SROOK_CONSTEXPR auto operator-(Arithmetic x, const fixed_point<I, F>& f) SROOK_NOEXCEPT_TRUE -> SROOK_DECLTYPE(detail::operation(x, f, srook::functional::deduction_minus())) { return detail::operation(x, f, srook::functional::deduction_minus()); } template <std::size_t I, std::size_t F, class Arithmetic, SROOK_REQUIRES(is_arithmetic<Arithmetic>::value)> SROOK_CONSTEXPR auto operator/(const fixed_point<I, F>& f, Arithmetic x) SROOK_NOEXCEPT_TRUE -> SROOK_DECLTYPE(detail::operation(f, x, srook::functional::deduction_divides())) { return detail::operation(f, x, srook::functional::deduction_divides()); } template <std::size_t I, std::size_t F, class Arithmetic, SROOK_REQUIRES(is_arithmetic<Arithmetic>::value)> SROOK_CONSTEXPR auto operator/(Arithmetic x, const fixed_point<I, F>& f) SROOK_NOEXCEPT_TRUE -> SROOK_DECLTYPE(detail::operation(x, f, srook::functional::deduction_divides())) { return detail::operation(x, f, srook::functional::deduction_divides()); } SROOK_INLINE_NAMESPACE_END } SROOK_NESTED_NAMESPACE_END(numeric, srook) namespace srook { template <std::size_t I, std::size_t F> class numeric_limits<srook::numeric::fixed_point<I, F>> : numeric_limits<SROOK_DEDUCED_TYPENAME srook::numeric::fixed_point<I, F>::value_type> { private: typedef SROOK_DEDUCED_TYPENAME srook::numeric::fixed_point<I, F>::traits_type traits_type; public: SROOK_FORCE_INLINE static SROOK_CONSTEXPR_OR_CONST srook::numeric::fixed_point<I, F> max() SROOK_NOEXCEPT_TRUE { return srook::numeric::fixed_point<I, F>::from_value(numeric_limits<SROOK_DEDUCED_TYPENAME traits_type::value_type>::max()); } SROOK_FORCE_INLINE static SROOK_CONSTEXPR_OR_CONST srook::numeric::fixed_point<I, F> min() SROOK_NOEXCEPT_TRUE { return srook::numeric::fixed_point<I, F>::from_value(numeric_limits<SROOK_DEDUCED_TYPENAME traits_type::value_type>::min()); } }; } // namespace srook namespace std { template <std::size_t I, std::size_t F> class numeric_limits<srook::numeric::fixed_point<I, F>> : numeric_limits<SROOK_DEDUCED_TYPENAME srook::numeric::fixed_point<I, F>::value_type> { private: typedef SROOK_DEDUCED_TYPENAME srook::numeric::fixed_point<I, F>::traits_type traits_type; public: SROOK_FORCE_INLINE static SROOK_CONSTEXPR_OR_CONST srook::numeric::fixed_point<I, F> max() SROOK_NOEXCEPT_TRUE { return srook::numeric::fixed_point<I, F>::from_value(numeric_limits<SROOK_DEDUCED_TYPENAME traits_type::value_type>::max()); } SROOK_FORCE_INLINE static SROOK_CONSTEXPR_OR_CONST srook::numeric::fixed_point<I, F> min() SROOK_NOEXCEPT_TRUE { return srook::numeric::fixed_point<I, F>::from_value(numeric_limits<SROOK_DEDUCED_TYPENAME traits_type::value_type>::min()); } }; } // namespace std #undef SROOK_FIXED_POINT_THROW_OVERFLOW #endif
45.463002
194
0.727679
falgon
a0c9c4e4c8f09e7fc7daf6289cf7d0b374fd559e
1,700
cpp
C++
src/maple_me/src/me_ssa_tab.cpp
harmonyos-mirror/OpenArkCompiler-test
1755550ea22eb185cbef8cc5864fa273caebf95a
[ "MulanPSL-1.0" ]
796
2019-08-30T16:20:33.000Z
2021-12-25T14:45:06.000Z
src/maple_me/src/me_ssa_tab.cpp
harmonyos-mirror/OpenArkCompiler-test
1755550ea22eb185cbef8cc5864fa273caebf95a
[ "MulanPSL-1.0" ]
16
2019-08-30T18:04:08.000Z
2021-09-19T05:02:58.000Z
src/maple_me/src/me_ssa_tab.cpp
harmonyos-mirror/OpenArkCompiler-test
1755550ea22eb185cbef8cc5864fa273caebf95a
[ "MulanPSL-1.0" ]
326
2019-08-30T16:11:29.000Z
2021-11-26T12:31:17.000Z
/* * Copyright (c) [2019-2020] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under the Mulan PSL v1. * You can use this software according to the terms and conditions of the Mulan PSL v1. * You may obtain a copy of Mulan PSL v1 at: * * http://license.coscl.org.cn/MulanPSL * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR * FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v1 for more details. */ #include "me_ssa_tab.h" #include <cstdlib> #include "mpl_timer.h" // allocate the data structure to store SSA information namespace maple { AnalysisResult *MeDoSSATab::Run(MeFunction *func, MeFuncResultMgr*, ModuleResultMgr*) { MPLTimer timer; timer.Start(); if (DEBUGFUNC(func)) { LogInfo::MapleLogger() << "\n============== SSA and AA preparation =============" << '\n'; } MemPool *memPool = NewMemPool(); // allocate ssaTab including its SSAPart to store SSA information for statements auto *ssaTab = memPool->New<SSATab>(memPool, func->GetVersMp(), &func->GetMIRModule()); func->SetMeSSATab(ssaTab); #if DEBUG globalSSATab = ssaTab; #endif // pass through the program statements for (auto bIt = func->valid_begin(); bIt != func->valid_end(); ++bIt) { auto *bb = *bIt; for (auto &stmt : bb->GetStmtNodes()) { ssaTab->CreateSSAStmt(stmt); // this adds the SSANodes for exprs } } if (DEBUGFUNC(func)) { timer.Stop(); LogInfo::MapleLogger() << "ssaTab consumes cumulatively " << timer.Elapsed() << "seconds " << '\n'; } return ssaTab; } } // namespace maple
35.416667
103
0.679412
harmonyos-mirror
a0c9f7c00b6a7533b294d60e43d4be79416df491
566
cc
C++
src/cf16final/b.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/cf16final/b.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/cf16final/b.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long ll; #ifndef _debug int main() { ll n; cin >> n; ll k = 1; for(;;) { if((k + 1ll) * (k + 2ll) / 2ll <= n) k++; else break; } ll gap = (k + 1ll) * (k + 2ll) / 2ll - n; if(gap == 0) { for(int i = 1; i <= k; i++) { cout << i << endl; } return 0; } else { for(int i = 1; i <= k + 1; i++) { if(gap != i) cout << i << endl; } } return 0; } #endif
17.6875
45
0.353357
nryotaro
a0cbef7663edaf61a43eb7a7c94154bb6a57ff9f
446
cpp
C++
modules/animals/lib/animal-i.cpp
mitadel/sandbox
afbab121f7e0aea7c092ca0c0e9088f6f06ad180
[ "BSD-3-Clause" ]
2
2021-05-26T15:18:00.000Z
2022-03-24T06:25:39.000Z
modules/animals/lib/animal-i.cpp
mitadel/sandbox
afbab121f7e0aea7c092ca0c0e9088f6f06ad180
[ "BSD-3-Clause" ]
3
2021-04-24T08:53:25.000Z
2021-06-27T10:44:09.000Z
modules/animals/lib/animal-i.cpp
mitadel/sandbox
afbab121f7e0aea7c092ca0c0e9088f6f06ad180
[ "BSD-3-Clause" ]
null
null
null
// declare the module module; // declare the module and export it export module Animal; // we can have namespaces within modules namespace mito { // this class is exported, so it is visible outside, when we import this module export class Animal { public: Animal() {} ~Animal() {} virtual void hello() const = 0; virtual void aFunction() const; }; } // end of namespace // end of file
17.84
83
0.623318
mitadel
a0ce24a1d185a36abeeb2bfa290b55287a7aa77e
6,095
cpp
C++
lib/frtcpp/taskbase_status.cpp
jbarry510/me-405
f7f7d011794c23d751090de37fb47121d0e1811b
[ "MIT" ]
null
null
null
lib/frtcpp/taskbase_status.cpp
jbarry510/me-405
f7f7d011794c23d751090de37fb47121d0e1811b
[ "MIT" ]
null
null
null
lib/frtcpp/taskbase_status.cpp
jbarry510/me-405
f7f7d011794c23d751090de37fb47121d0e1811b
[ "MIT" ]
null
null
null
//************************************************************************************** /** \file taskbase_status.cpp * This file contains methods which print the status of each task, showing things * such as the task's name, its priority, and if enabled, stack usage and number of * times its loop has run. * * Revisions: * \li 12-02-2012 JRR Split off from time_stamp.cpp to save memory in machine file * \li 08-26-2014 JRR Changed file names and base task class name to TaskBase * \li 01-04-2015 JRR Moved items around for more efficient use of screen space * * License: * This file is copyright 2012 by JR Ridgely and released under the Lesser GNU * Public License, version 2. It intended for educational use only, but its use * is not limited thereto. */ /* 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 CONSEQUEN- * TIAL 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 <string.h> // For strlen() and Sparta (the Mean Kitty) #include "taskbase.h" // Pull in the base class header file //------------------------------------------------------------------------------------- /** This method prints task status information, then asks the next task in the list of * tasks to do so. The list is kept by the tasks, each having a pointer to another. * @param ser_device The serial device to which each task prints its status */ void TaskBase::print_status_in_list (emstream* ser_device) { *ser_device << *this << endl; if (prev_task_pointer != NULL) { prev_task_pointer->print_status_in_list (ser_device); } } //------------------------------------------------------------------------------------- /** This method prints information about the task. It is called by the overloaded "<<" * operator which is used by the task to print itself when asked to. This function is * declared virtual so that descendents can override it to print additional * information. * @param ser_dev A reference to the serial device to which to print the task status */ void TaskBase::print_status (emstream& ser_dev) { ser_dev.puts (pcTaskGetTaskName (handle)); ser_dev.putchar ('\t'); if (strlen ((const char*)(pcTaskGetTaskName (handle))) < 8) { ser_dev.putchar ('\t'); } ser_dev << (uint8_t)(uxTaskPriorityGet (handle)) << PMS ("\t") << get_state () #if (INCLUDE_uxTaskGetStackHighWaterMark == 1) << PMS ("\t") << uxTaskGetStackHighWaterMark(handle) << PMS ("/") << (size_t)(get_total_stack ()) << PMS ("\t") #endif << PMS ("\t") << runs; } //------------------------------------------------------------------------------------- /** This overloaded operator writes information about the task's status to the given * serial device. That information can be used for debugging or perhaps reliability * testing. Information written is: * \li The task's name * \li The priority * \li The amount of stack used and total available * @param ser_dev A reference to the serial device on which we're writing information * @param a_task A reference to the task whose information is to be written * @return A reference to the same serial device on which we write information. * This is used to string together things to write with "<<" operators */ emstream& operator << (emstream& ser_dev, TaskBase& a_task) { a_task.print_status (ser_dev); return (ser_dev); } //------------------------------------------------------------------------------------- /** This function prints information about how all the tasks are doing. Beginning with * the most recently created task, each task prints its status and then asks the next * task in the list to do the same until the end of the list is found. * WARNING: The display of memory remaining in the task stacks, which is found by * calls to FreeRTOS function uxTaskGetStackHighWaterMark(), seems to be suspicious. * The author isn't sure if it can always be trusted. * @param ser_dev Pointer to a serial device on which the information will be printed */ void print_task_list (emstream* ser_dev) { // Print the first line with the top of the headings *ser_dev << PMS ("Task\t\t \t ") #if (INCLUDE_uxTaskGetStackHighWaterMark == 1) << PMS ("\tStack") #endif << endl; // Print the second line with the rest of the headings *ser_dev << PMS ("Name\t\tPri.\tState") #if (INCLUDE_uxTaskGetStackHighWaterMark == 1) << PMS ("\tFree/Total") #endif << PMS ("\tRuns") << endl; // Print the third line which shows separators between headers and data *ser_dev << PMS ("----\t\t----\t-----") #if (INCLUDE_uxTaskGetStackHighWaterMark == 1) << PMS ("\t----------") #endif << PMS ("\t----") << endl; // Now have the tasks each print out their status. Tasks form a linked list, so // we only need to get the last task started and it will call the next, etc. if (last_created_task_pointer != NULL) { last_created_task_pointer->print_status_in_list (ser_dev); } // Have the idle task print out its information *ser_dev << PMS ("IDLE\t\t0\t-\t") #if (INCLUDE_uxTaskGetStackHighWaterMark == 1) << uxTaskGetStackHighWaterMark (xTaskGetIdleTaskHandle ()) << PMS ("/") << configMINIMAL_STACK_SIZE << PMS ("\t\t-") #endif << endl; }
42.326389
88
0.637244
jbarry510
a0cf910b2a7922e176c2c0a4d81f8da6ea3a3f73
48,175
cpp
C++
solid/frame/mprpc/src/mprpcrelayengine.cpp
vipalade/solidframe
cff130652127ca9607019b4db508bc67f8bbecff
[ "BSL-1.0" ]
26
2015-08-25T16:07:58.000Z
2019-07-05T15:21:22.000Z
solid/frame/mprpc/src/mprpcrelayengine.cpp
vipalade/solidframe
cff130652127ca9607019b4db508bc67f8bbecff
[ "BSL-1.0" ]
5
2016-10-15T22:55:15.000Z
2017-09-19T12:41:10.000Z
solid/frame/mprpc/src/mprpcrelayengine.cpp
vipalade/solidframe
cff130652127ca9607019b4db508bc67f8bbecff
[ "BSL-1.0" ]
5
2016-09-15T10:34:52.000Z
2018-10-30T11:46:46.000Z
// solid/frame/ipc/src/mprpcrelayengine.cpp // // Copyright (c) 2017 Valentin Palade (vipalade @ gmail . com) // // This file is part of SolidFrame framework. // // 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 "solid/frame/mprpc/mprpcrelayengine.hpp" #include "mprpcutility.hpp" #include "solid/system/log.hpp" #include "solid/utility/innerlist.hpp" #include "solid/utility/string.hpp" #include <deque> #include <mutex> #include <stack> #include <string> #include <unordered_map> using namespace std; namespace solid { namespace frame { namespace mprpc { namespace relay { //----------------------------------------------------------------------------- namespace { const LoggerT logger("solid::frame::mprpc::relay"); enum struct ConnectionStateE { Active, }; enum { InnerLinkRecv, InnerLinkSend, InnerLinkCount //add above }; /* NOTE: Message turning points: * sender connection closes * if the message was not completely received, receiver connection must send message cancel * if the message is waiting for response, receiver connection must send CancelRequest * - * * receiver connection closes * if the message was not completely received, sender connection must send CancelRequest and discard any incomming data * if message is waiting for response, sender connection must send CancelRequest * the connection must call EngineCore::doCompleteClose on all relayed messages in its writer * then EngineCore::connectionStop is called. - Ideas: - on doCompleteClose can add _prelay_data back to message list and add the message to the receiver connection message list - on connectionStop * sender connection receives a message canceled command * * receiver connection receives message cancel request command which should be forwarder up to the initial sender of the message W1---->RR-->RW---->R2 R1<----RW<--RR<----W2 W1 - Writer for connection 1 R1 - Reader for connection 1 RR - Relay reader RW - Relay writer R2 - Reader for connection 2 W2 - Writer for connection 2 */ enum struct MessageStateE { Cache, Relay, WaitResponse, WaitResponsePart, RecvCancel, SendCancel, }; struct MessageStub : inner::Node<InnerLinkCount> { using FlagsT = MessageFlagsValueT; MessageStateE state_; RelayData* pfront_; RelayData* pback_; uint32_t unique_; UniqueId sender_con_id_; UniqueId receiver_con_id_; MessageId receiver_msg_id_; MessageHeader header_; FlagsT last_message_flags_; MessageStub() : state_(MessageStateE::Relay) , pfront_(nullptr) , pback_(nullptr) , unique_(0) , last_message_flags_(0) { } void clear() { solid_assert_log(pfront_ == nullptr && pback_ == nullptr, logger); state_ = MessageStateE::Cache; pfront_ = nullptr; pback_ = nullptr; ++unique_; sender_con_id_.clear(); receiver_con_id_.clear(); receiver_msg_id_.clear(); last_message_flags_ = 0; } void push(RelayData* _prd) { if (pback_ != nullptr) { pback_->pnext_ = _prd; pback_ = _prd; } else { pfront_ = pback_ = _prd; pback_->pnext_ = nullptr; } pback_->pmessage_header_ = &header_; solid_log(logger, Verbose, "pushed relay_data " << pback_ << " size = " << pback_->data_size_ << " is_begin = " << pback_->isMessageBegin() << " is_end = " << pback_->isMessageEnd() << " is_last = " << pback_->isMessageLast()); } RelayData* pop() { RelayData* p = nullptr; if (pfront_ != nullptr) { p = pfront_; pfront_ = p->pnext_; if (pfront_ == nullptr) { pback_ = nullptr; } p->pnext_ = nullptr; } return p; } bool isCanceled() const { return state_ == MessageStateE::RecvCancel || state_ == MessageStateE::SendCancel; } bool hasData() const { return pback_ != nullptr || state_ == MessageStateE::SendCancel; } }; using MessageDequeT = std::deque<MessageStub>; using SendInnerListT = inner::List<MessageDequeT, InnerLinkSend>; using RecvInnerListT = inner::List<MessageDequeT, InnerLinkRecv>; std::ostream& operator<<(std::ostream& _ros, const SendInnerListT& _rlst) { size_t cnt = 0; _rlst.forEach( [&_ros, &cnt](size_t _idx, const MessageStub& _rmsg) { _ros << _idx << ' '; ++cnt; }); solid_assert_log(cnt == _rlst.size(), logger); return _ros; } std::ostream& operator<<(std::ostream& _ros, const RecvInnerListT& _rlst) { size_t cnt = 0; _rlst.forEach( [&_ros, &cnt](size_t _idx, const MessageStub& _rmsg) { _ros << _idx << ' '; ++cnt; }); solid_assert_log(cnt == _rlst.size(), logger); return _ros; } struct ConnectionStub : ConnectionStubBase { uint32_t unique_; RelayData* pdone_relay_data_top_; SendInnerListT send_msg_list_; RecvInnerListT recv_msg_list_; ConnectionStub(MessageDequeT& _rmsg_dq) : unique_(0) , pdone_relay_data_top_(nullptr) , send_msg_list_(_rmsg_dq) , recv_msg_list_(_rmsg_dq) { } ConnectionStub(MessageDequeT& _rmsg_dq, std::string&& _uname) : ConnectionStubBase(std::move(_uname)) , unique_(0) , pdone_relay_data_top_(nullptr) , send_msg_list_(_rmsg_dq) , recv_msg_list_(_rmsg_dq) { } void clear() { ++unique_; id_.clear(); ConnectionStubBase::clear(); pdone_relay_data_top_ = nullptr; solid_assert_log(send_msg_list_.empty() && recv_msg_list_.empty(), logger); } }; using RelayDataDequeT = std::deque<RelayData>; using RelayDataStackT = std::stack<RelayData*>; using SizeTStackT = std::stack<size_t>; using ConnectionDequeT = std::deque<ConnectionStub>; using ConnectionMapT = std::unordered_map<const char*, size_t, CStringHash, CStringEqual>; } //namespace std::ostream& operator<<(std::ostream& _ros, const ConnectionPrintStub& _rps) { return _rps.re_.print(_ros, _rps.rc_); } struct EngineCore::Data { Manager& rm_; mutex mtx_; MessageDequeT msg_dq_; RelayDataDequeT reldata_dq_; RelayData* prelay_data_cache_top_; SendInnerListT msg_cache_inner_list_; ConnectionDequeT con_dq_; ConnectionMapT con_umap_; SizeTStackT con_cache_; Data(Manager& _rm) : rm_(_rm) , prelay_data_cache_top_(nullptr) , msg_cache_inner_list_(msg_dq_) { } Manager& manager() const { return rm_; } RelayData* createRelayData(RelayData&& _urd) { RelayData* prd = nullptr; if (prelay_data_cache_top_ != nullptr) { prd = prelay_data_cache_top_; prelay_data_cache_top_ = prelay_data_cache_top_->pnext_; *prd = std::move(_urd); } else { reldata_dq_.emplace_back(std::move(_urd)); prd = &reldata_dq_.back(); } return prd; } RelayData* createSendCancelRelayData() { RelayData* prd = nullptr; if (prelay_data_cache_top_ != nullptr) { prd = prelay_data_cache_top_; prelay_data_cache_top_ = prelay_data_cache_top_->pnext_; prd->clear(); } else { reldata_dq_.emplace_back(); prd = &reldata_dq_.back(); } prd->flags_.set(RelayDataFlagsE::Last); return prd; } void eraseRelayData(RelayData*& _prd) { _prd->pnext_ = prelay_data_cache_top_; prelay_data_cache_top_ = _prd; _prd = nullptr; } size_t createMessage() { size_t idx; if (!msg_cache_inner_list_.empty()) { return msg_cache_inner_list_.popBack(); } idx = msg_dq_.size(); msg_dq_.emplace_back(); return idx; } void eraseMessage(const size_t _idx) { msg_cache_inner_list_.pushBack(_idx); } size_t createConnection() { size_t conidx; if (!con_cache_.empty()) { conidx = con_cache_.top(); con_cache_.pop(); } else { conidx = con_dq_.size(); con_dq_.emplace_back(msg_dq_); } return conidx; } void eraseConnection(const size_t _conidx) { con_dq_[_conidx].clear(); con_cache_.push(_conidx); } bool isValid(const UniqueId& _rrelay_con_uid) const { const size_t idx = static_cast<size_t>(_rrelay_con_uid.index); return idx < con_dq_.size() && con_dq_[idx].unique_ == _rrelay_con_uid.unique; } }; //----------------------------------------------------------------------------- EngineCore::EngineCore(Manager& _rm) : impl_(make_pimpl<Data>(_rm)) { solid_log(logger, Info, this); } //----------------------------------------------------------------------------- EngineCore::~EngineCore() { solid_log(logger, Info, this); } //----------------------------------------------------------------------------- Manager& EngineCore::manager() { return impl_->manager(); } //----------------------------------------------------------------------------- void EngineCore::stopConnection(const UniqueId& _rrelay_con_uid) { if (_rrelay_con_uid.isValid()) { lock_guard<mutex> lock(impl_->mtx_); doStopConnection(static_cast<size_t>(_rrelay_con_uid.index)); } } //----------------------------------------------------------------------------- void EngineCore::doStopConnection(const size_t _conidx) { solid_log(logger, Info, _conidx); ConnectionStub& rcon = impl_->con_dq_[_conidx]; { while (!rcon.recv_msg_list_.empty()) { MessageStub& rmsg = rcon.recv_msg_list_.front(); const size_t msgidx = rcon.recv_msg_list_.popFront(); const size_t snd_conidx = static_cast<size_t>(rmsg.sender_con_id_.index); rmsg.receiver_con_id_.clear(); //unlink from the receiver connection if (rmsg.sender_con_id_.isValid()) { switch (rmsg.state_) { case MessageStateE::Relay: case MessageStateE::WaitResponse: rmsg.state_ = MessageStateE::RecvCancel; solid_assert_log(snd_conidx < impl_->con_dq_.size() && impl_->con_dq_[snd_conidx].unique_ == rmsg.sender_con_id_.unique, logger); { ConnectionStub& rsndcon = impl_->con_dq_[snd_conidx]; bool should_notify_connection = msgidx == rsndcon.send_msg_list_.frontIndex() || rsndcon.send_msg_list_.front().state_ != MessageStateE::RecvCancel; rsndcon.send_msg_list_.erase(msgidx); rsndcon.send_msg_list_.pushFront(msgidx); solid_assert_log(rsndcon.send_msg_list_.check(), logger); if (should_notify_connection) { solid_check_log(notifyConnection(impl_->manager(), rsndcon.id_, RelayEngineNotification::DoneData), logger, "Connection should be alive"); } } continue; //case MessageStateE::SendCancel://rmsg.sender_con_id_ should be invalid //case MessageStateE::RecvCancel://message should not be in the recv_msg_list_ default: solid_check_log(false, logger, "Invalid message state " << static_cast<size_t>(rmsg.state_)); break; } //switch } //simply erase the message RelayData* prd; while ((prd = rmsg.pop()) != nullptr) { impl_->eraseRelayData(prd); } rmsg.clear(); impl_->eraseMessage(msgidx); } //while } { while (!rcon.send_msg_list_.empty()) { MessageStub& rmsg = rcon.send_msg_list_.front(); const size_t msgidx = rcon.send_msg_list_.popFront(); const size_t rcv_conidx = static_cast<size_t>(rmsg.receiver_con_id_.index); solid_assert_log(rcon.send_msg_list_.check(), logger); rmsg.sender_con_id_.clear(); //unlink from the sender connection //clean message relay data { RelayData* prd; while ((prd = rmsg.pop()) != nullptr) { impl_->eraseRelayData(prd); } } if (rmsg.receiver_con_id_.isValid() && impl_->con_dq_[rcv_conidx].id_.isValid()) { switch (rmsg.state_) { case MessageStateE::Relay: case MessageStateE::WaitResponse: rmsg.state_ = MessageStateE::SendCancel; solid_assert_log(rcv_conidx < impl_->con_dq_.size() && impl_->con_dq_[rcv_conidx].unique_ == rmsg.receiver_con_id_.unique, logger); rmsg.push(impl_->createSendCancelRelayData()); { ConnectionStub& rrcvcon = impl_->con_dq_[rcv_conidx]; bool should_notify_connection = (rrcvcon.recv_msg_list_.backIndex() == msgidx || !rrcvcon.recv_msg_list_.back().hasData()); rrcvcon.recv_msg_list_.erase(msgidx); rrcvcon.recv_msg_list_.pushBack(msgidx); if (should_notify_connection) { solid_check_log(notifyConnection(impl_->manager(), rrcvcon.id_, RelayEngineNotification::NewData), logger, "Connection should be alive"); } } continue; //case MessageStateE::SendCancel://rmsg.sender_con_id_ should be invalid //case MessageStateE::RecvCancel://message should not be in the recv_msg_list_ default: solid_check_log(false, logger, "Invalid message state " << static_cast<size_t>(rmsg.state_)); break; } //switch } //simply erase the message rmsg.clear(); impl_->eraseMessage(msgidx); } //while } { //clean-up done relay data RelayData* prd = rcon.pdone_relay_data_top_; solid_log(logger, Info, _conidx << ' ' << plot(rcon)); while (prd != nullptr) { RelayData* ptmprd = prd->pnext_; prd->clear(); impl_->eraseRelayData(prd); prd = ptmprd; } } { Proxy proxy(*this); unregisterConnectionName(proxy, _conidx); } impl_->eraseConnection(_conidx); } //----------------------------------------------------------------------------- void EngineCore::doExecute(ExecuteFunctionT& _rfnc) { Proxy proxy(*this); lock_guard<mutex> lock(impl_->mtx_); _rfnc(proxy); } //----------------------------------------------------------------------------- size_t EngineCore::doRegisterUnnamedConnection(const ActorIdT& _rcon_uid, UniqueId& _rrelay_con_uid) { if (_rrelay_con_uid.isValid()) { solid_assert_log(impl_->isValid(_rrelay_con_uid), logger); return static_cast<size_t>(_rrelay_con_uid.index); } size_t conidx = impl_->createConnection(); ConnectionStub& rcon = impl_->con_dq_[conidx]; rcon.id_ = _rcon_uid; _rrelay_con_uid.index = conidx; _rrelay_con_uid.unique = rcon.unique_; solid_log(logger, Info, _rrelay_con_uid << ' ' << plot(rcon)); return conidx; } //----------------------------------------------------------------------------- size_t EngineCore::doRegisterNamedConnection(std::string&& _uname) { Proxy proxy(*this); size_t conidx = registerConnection(proxy, std::move(_uname)); solid_log(logger, Info, conidx << ' ' << plot(impl_->con_dq_[conidx])); return conidx; } //----------------------------------------------------------------------------- // called by sending connection on new relayed message bool EngineCore::doRelayStart( const ActorIdT& _rcon_uid, UniqueId& _rrelay_con_uid, MessageHeader& _rmsghdr, RelayData&& _rrelmsg, MessageId& _rrelay_id, ErrorConditionT& /*_rerror*/) { size_t msgidx; lock_guard<mutex> lock(impl_->mtx_); solid_assert_log(_rcon_uid.isValid(), logger); size_t snd_conidx = static_cast<size_t>(_rrelay_con_uid.index); if (_rrelay_con_uid.isValid()) { solid_assert_log(impl_->isValid(_rrelay_con_uid), logger); snd_conidx = static_cast<size_t>(_rrelay_con_uid.index); } else { snd_conidx = doRegisterUnnamedConnection(_rcon_uid, _rrelay_con_uid); } msgidx = impl_->createMessage(); MessageStub& rmsg = impl_->msg_dq_[msgidx]; rmsg.header_ = std::move(_rmsghdr); rmsg.state_ = MessageStateE::Relay; rmsg.last_message_flags_ = rmsg.header_.flags_; //the request_ids are already swapped on deserialization std::swap(rmsg.header_.recipient_request_id_, rmsg.header_.sender_request_id_); _rrelay_id = MessageId(msgidx, rmsg.unique_); const size_t rcv_conidx = doRegisterNamedConnection(std::move(rmsg.header_.url_)); ConnectionStub& rrcvcon = impl_->con_dq_[rcv_conidx]; ConnectionStub& rsndcon = impl_->con_dq_[snd_conidx]; //also hold the in-engine connection id into msg rmsg.sender_con_id_ = ActorIdT(snd_conidx, impl_->con_dq_[snd_conidx].unique_); rmsg.receiver_con_id_ = ActorIdT(rcv_conidx, rrcvcon.unique_); //register message onto sender connection: rsndcon.send_msg_list_.pushBack(msgidx); _rrelmsg.flags_.set(RelayDataFlagsE::First); _rrelmsg.message_flags_ = rmsg.header_.flags_; solid_log(logger, Info, _rrelay_con_uid << " msgid = " << _rrelay_id << " size = " << _rrelmsg.data_size_ << " receiver_conidx " << rmsg.receiver_con_id_.index << " sender_conidx " << rmsg.sender_con_id_.index << " flags = " << _rrelmsg.flags_); solid_assert_log(rmsg.pfront_ == nullptr, logger); rmsg.push(impl_->createRelayData(std::move(_rrelmsg))); bool should_notify_connection = (rrcvcon.recv_msg_list_.empty() || !rrcvcon.recv_msg_list_.back().hasData()); rrcvcon.recv_msg_list_.pushBack(msgidx); if (should_notify_connection && rrcvcon.id_.isValid()) { solid_check_log(notifyConnection(impl_->manager(), rrcvcon.id_, RelayEngineNotification::NewData), logger, "Connection should be alive"); } return true; } //----------------------------------------------------------------------------- // called by sending connection on new relay data for an existing message bool EngineCore::doRelay( const UniqueId& _rrelay_con_uid, RelayData&& _rrelmsg, const MessageId& _rrelay_id, ErrorConditionT& /*_rerror*/) { lock_guard<mutex> lock(impl_->mtx_); solid_assert_log(_rrelay_id.isValid(), logger); solid_assert_log(_rrelay_con_uid.isValid(), logger); solid_assert_log(impl_->isValid(_rrelay_con_uid), logger); if (_rrelay_id.index < impl_->msg_dq_.size() && impl_->msg_dq_[_rrelay_id.index].unique_ == _rrelay_id.unique) { const size_t msgidx = _rrelay_id.index; MessageStub& rmsg = impl_->msg_dq_[msgidx]; bool is_msg_relay_data_queue_empty = (rmsg.pfront_ == nullptr); size_t data_size = _rrelmsg.data_size_; auto flags = rmsg.last_message_flags_; _rrelmsg.message_flags_ = rmsg.last_message_flags_; rmsg.push(impl_->createRelayData(std::move(_rrelmsg))); if (rmsg.state_ == MessageStateE::Relay || rmsg.state_ == MessageStateE::WaitResponsePart) { solid_log(logger, Verbose, _rrelay_con_uid << " msgid = " << _rrelay_id << " rcv_conidx " << rmsg.receiver_con_id_.index << " snd_conidx " << rmsg.sender_con_id_.index << " flags = " << flags << " is_mrq_empty = " << is_msg_relay_data_queue_empty << " dsz = " << data_size); if (is_msg_relay_data_queue_empty) { ConnectionStub& rrcvcon = impl_->con_dq_[static_cast<size_t>(rmsg.receiver_con_id_.index)]; bool should_notify_connection = (rrcvcon.recv_msg_list_.backIndex() == msgidx || !rrcvcon.recv_msg_list_.back().hasData()); solid_assert_log(!rrcvcon.recv_msg_list_.empty(), logger); //move the message at the back of the list so it get processed sooner - somewhat unfair //but this way we can keep using a single list for send messages rrcvcon.recv_msg_list_.erase(msgidx); rrcvcon.recv_msg_list_.pushBack(msgidx); solid_log(logger, Verbose, "rcv_lst = " << rrcvcon.recv_msg_list_ << " notify_conn = " << should_notify_connection); if (should_notify_connection) { //solid_log(logger, Verbose, _rrelay_con_uid <<" notify receiver connection"); solid_check_log(notifyConnection(impl_->manager(), rrcvcon.id_, RelayEngineNotification::NewData), logger, "Connection should be alive"); } } } else { //we do not return false because the connection is about to be notified //about message state change solid_log(logger, Warning, _rrelay_con_uid << " message not in relay state instead in " << static_cast<size_t>(rmsg.state_)); } return true; } solid_log(logger, Error, _rrelay_con_uid << " message not found " << _rrelay_id); return false; } //----------------------------------------------------------------------------- // called by receiving connection on relaying the message response // after this call, the receiving and sending connections, previously // associtate to the message are swapped (the receiving connection becomes the sending and // the sending one becomes receving) bool EngineCore::doRelayResponse( const UniqueId& _rrelay_con_uid, MessageHeader& _rmsghdr, RelayData&& _rrelmsg, const MessageId& _rrelay_id, ErrorConditionT& /*_rerror*/) { lock_guard<mutex> lock(impl_->mtx_); solid_assert_log(_rrelay_id.isValid(), logger); solid_assert_log(_rrelay_con_uid.isValid(), logger); solid_assert_log(impl_->isValid(_rrelay_con_uid), logger); if (_rrelay_id.index < impl_->msg_dq_.size() && impl_->msg_dq_[_rrelay_id.index].unique_ == _rrelay_id.unique) { const size_t msgidx = _rrelay_id.index; MessageStub& rmsg = impl_->msg_dq_[msgidx]; RequestId sender_request_id = rmsg.header_.recipient_request_id_; //the request ids were swapped on doRelayStart _rrelmsg.flags_.set(RelayDataFlagsE::First); _rrelmsg.message_flags_ = _rmsghdr.flags_; rmsg.last_message_flags_ = _rmsghdr.flags_; solid_log(logger, Info, _rrelay_con_uid << " msgid = " << _rrelay_id << " receiver_conidx " << rmsg.receiver_con_id_ << " sender_conidx " << rmsg.sender_con_id_ << " flags = " << _rrelmsg.flags_); if (rmsg.state_ == MessageStateE::WaitResponse) { solid_assert_log(rmsg.sender_con_id_.isValid(), logger); solid_assert_log(rmsg.receiver_con_id_.isValid(), logger); solid_assert_log(rmsg.pfront_ == nullptr, logger); rmsg.receiver_msg_id_.clear(); std::swap(rmsg.receiver_con_id_, rmsg.sender_con_id_); rmsg.header_ = std::move(_rmsghdr); std::swap(rmsg.header_.recipient_request_id_, rmsg.header_.sender_request_id_); //set the proper recipient_request_id_ rmsg.header_.sender_request_id_ = sender_request_id; rmsg.push(impl_->createRelayData(std::move(_rrelmsg))); rmsg.state_ = MessageStateE::Relay; const size_t rcv_conidx = static_cast<size_t>(rmsg.receiver_con_id_.index); const size_t snd_conidx = static_cast<size_t>(rmsg.sender_con_id_.index); solid_assert_log(rcv_conidx < impl_->con_dq_.size() && impl_->con_dq_[rcv_conidx].unique_ == rmsg.receiver_con_id_.unique, logger); solid_assert_log(snd_conidx < impl_->con_dq_.size() && impl_->con_dq_[snd_conidx].unique_ == rmsg.sender_con_id_.unique, logger); ConnectionStub& rrcvcon = impl_->con_dq_[rcv_conidx]; ConnectionStub& rsndcon = impl_->con_dq_[snd_conidx]; const bool should_notify_connection = rrcvcon.recv_msg_list_.empty() || !rrcvcon.recv_msg_list_.back().hasData(); rsndcon.recv_msg_list_.erase(msgidx); // rrcvcon.send_msg_list_.erase(msgidx); //MUST do the erase before push!!! rsndcon.send_msg_list_.pushBack(msgidx); // rrcvcon.recv_msg_list_.pushBack(msgidx); // solid_log(logger, Info, "rcv_lst = " << rrcvcon.recv_msg_list_ << " should notify connection = " << should_notify_connection); solid_assert_log(rsndcon.send_msg_list_.check(), logger); solid_assert_log(rrcvcon.send_msg_list_.check(), logger); if (should_notify_connection) { solid_check_log(notifyConnection(impl_->manager(), rrcvcon.id_, RelayEngineNotification::NewData), logger, "Connection should be alive"); } } else if (rmsg.state_ == MessageStateE::Relay || rmsg.state_ == MessageStateE::WaitResponsePart) { const bool is_msg_relay_data_queue_empty = (rmsg.pfront_ == nullptr); size_t data_size = _rrelmsg.data_size_; rmsg.state_ = MessageStateE::Relay; solid_log(logger, Info, _rrelay_con_uid << " msgid = " << _rrelay_id << " rcv_conidx " << rmsg.receiver_con_id_ << " snd_conidx " << rmsg.sender_con_id_ << " flags = " << _rrelmsg.flags_ << " is_mrq_empty = " << is_msg_relay_data_queue_empty << " dsz = " << data_size); rmsg.push(impl_->createRelayData(std::move(_rrelmsg))); if (is_msg_relay_data_queue_empty) { ConnectionStub& rrcvcon = impl_->con_dq_[static_cast<size_t>(rmsg.receiver_con_id_.index)]; bool should_notify_connection = (rrcvcon.recv_msg_list_.backIndex() == msgidx || !rrcvcon.recv_msg_list_.back().hasData()); solid_assert_log(!rrcvcon.recv_msg_list_.empty(), logger); //move the message at the back of the list so it get processed sooner - somewhat unfair //but this way we can keep using a single list for send messages rrcvcon.recv_msg_list_.erase(msgidx); rrcvcon.recv_msg_list_.pushBack(msgidx); solid_log(logger, Info, "rcv_lst = " << rrcvcon.recv_msg_list_ << " notify_conn = " << should_notify_connection); if (should_notify_connection) { //solid_log(logger, Info, _rrelay_con_uid <<" notify receiver connection"); solid_check_log(notifyConnection(impl_->manager(), rrcvcon.id_, RelayEngineNotification::NewData), logger, "Connection should be alive"); } } } return true; } solid_log(logger, Error, "message not found"); return false; } //----------------------------------------------------------------------------- // called by the receiver connection on new relay data void EngineCore::doPollNew(const UniqueId& _rrelay_con_uid, PushFunctionT& _try_push_fnc, bool& _rmore) { lock_guard<mutex> lock(impl_->mtx_); solid_assert_log(_rrelay_con_uid.isValid(), logger); solid_assert_log(impl_->isValid(_rrelay_con_uid), logger); const size_t conidx = static_cast<size_t>(_rrelay_con_uid.index); ConnectionStub& rcon = impl_->con_dq_[conidx]; bool can_retry = true; size_t msgidx = rcon.recv_msg_list_.backIndex(); solid_log(logger, Verbose, _rrelay_con_uid << ' ' << plot(rcon) << " msgidx " << msgidx); while (can_retry && msgidx != InvalidIndex() && impl_->msg_dq_[msgidx].hasData()) { MessageStub& rmsg = impl_->msg_dq_[msgidx]; const size_t prev_msgidx = rcon.recv_msg_list_.previousIndex(msgidx); RelayData* pnext = rmsg.pfront_ != nullptr ? rmsg.pfront_->pnext_ : nullptr; if (_try_push_fnc(rmsg.pfront_, MessageId(msgidx, rmsg.unique_), rmsg.receiver_msg_id_, can_retry)) { if (rmsg.pfront_ == nullptr) { solid_log(logger, Verbose, ""); rmsg.pfront_ = pnext; if (rmsg.pfront_ == nullptr) { rmsg.pback_ = nullptr; } //relay data accepted if (rmsg.pfront_ != nullptr) { //message has more data - leave it where it is on the list } else { //message has no more data, move it to front rcon.recv_msg_list_.erase(msgidx); rcon.recv_msg_list_.pushFront(msgidx); } } else { solid_log(logger, Verbose, ""); //the connection has received the SendCancel event for the message, //we can now safely delete the message solid_assert_log(!rmsg.pfront_->bufptr_, logger); solid_assert_log(pnext == nullptr, logger); if (rmsg.sender_con_id_.isValid()) { //we can safely unlink message from sender connection solid_assert_log(static_cast<size_t>(rmsg.sender_con_id_.index) < impl_->con_dq_.size() && impl_->con_dq_[static_cast<size_t>(rmsg.sender_con_id_.index)].unique_ == rmsg.sender_con_id_.unique, logger); ConnectionStub& rsndcon = impl_->con_dq_[static_cast<size_t>(rmsg.sender_con_id_.index)]; rsndcon.send_msg_list_.erase(msgidx); } rmsg.pfront_->clear(); impl_->eraseRelayData(rmsg.pfront_); rmsg.pback_ = nullptr; rcon.recv_msg_list_.erase(msgidx); rmsg.clear(); impl_->eraseMessage(msgidx); solid_log(logger, Error, _rrelay_con_uid << " erase msg " << msgidx << " rcv_lst = " << rcon.recv_msg_list_); } } else { solid_log(logger, Verbose, ""); } msgidx = prev_msgidx; } //while _rmore = !rcon.recv_msg_list_.empty() && rcon.recv_msg_list_.back().hasData(); solid_log(logger, Verbose, _rrelay_con_uid << " more = " << _rmore << " rcv_lst = " << rcon.recv_msg_list_); } //----------------------------------------------------------------------------- // called by sender connection when either // have completed relaydata (the receiving connections have sent the data) or // have messages canceled by receiving connections void EngineCore::doPollDone(const UniqueId& _rrelay_con_uid, DoneFunctionT& _done_fnc, CancelFunctionT& _cancel_fnc) { lock_guard<mutex> lock(impl_->mtx_); solid_assert_log(_rrelay_con_uid.isValid(), logger); solid_assert_log(impl_->isValid(_rrelay_con_uid), logger); const size_t conidx = static_cast<size_t>(_rrelay_con_uid.index); ConnectionStub& rcon = impl_->con_dq_[conidx]; solid_log(logger, Verbose, _rrelay_con_uid << ' ' << plot(rcon)); RelayData* prd = rcon.pdone_relay_data_top_; while (prd != nullptr) { _done_fnc(prd->bufptr_); RelayData* ptmprd = prd->pnext_; prd->clear(); impl_->eraseRelayData(prd); prd = ptmprd; } rcon.pdone_relay_data_top_ = nullptr; solid_log(logger, Verbose, _rrelay_con_uid << " send_msg_list.size = " << rcon.send_msg_list_.size() << " front idx = " << rcon.send_msg_list_.frontIndex()); solid_assert_log(rcon.send_msg_list_.check(), logger); while (!rcon.send_msg_list_.empty() && rcon.send_msg_list_.front().state_ == MessageStateE::RecvCancel) { MessageStub& rmsg = rcon.send_msg_list_.front(); const size_t msgidx = rcon.send_msg_list_.popFront(); solid_assert_log(rmsg.receiver_con_id_.isInvalid(), logger); while ((prd = rmsg.pop()) != nullptr) { _done_fnc(prd->bufptr_); prd->clear(); impl_->eraseRelayData(prd); } _cancel_fnc(rmsg.header_); rmsg.clear(); impl_->eraseMessage(msgidx); } } //----------------------------------------------------------------------------- // called by receiving connection after using the relay_data void EngineCore::doComplete( const UniqueId& _rrelay_con_uid, RelayData* _prelay_data, MessageId const& _rengine_msg_id, bool& _rmore) { lock_guard<mutex> lock(impl_->mtx_); solid_assert_log(_rrelay_con_uid.isValid(), logger); solid_assert_log(impl_->isValid(_rrelay_con_uid), logger); solid_log(logger, Verbose, _rrelay_con_uid << " try complete msg " << _rengine_msg_id); solid_assert_log(_prelay_data, logger); if (_rengine_msg_id.index < impl_->msg_dq_.size() && impl_->msg_dq_[_rengine_msg_id.index].unique_ == _rengine_msg_id.unique) { const size_t msgidx = _rengine_msg_id.index; MessageStub& rmsg = impl_->msg_dq_[msgidx]; ConnectionStub& rrcvcon = impl_->con_dq_[static_cast<size_t>(rmsg.receiver_con_id_.index)]; //the connection currently calling this method if (rmsg.sender_con_id_.isValid()) { solid_assert_log(static_cast<size_t>(rmsg.sender_con_id_.index) < impl_->con_dq_.size() && impl_->con_dq_[static_cast<size_t>(rmsg.sender_con_id_.index)].unique_ == rmsg.sender_con_id_.unique, logger); ConnectionStub& rsndcon = impl_->con_dq_[static_cast<size_t>(rmsg.sender_con_id_.index)]; bool should_notify_connection = rsndcon.pdone_relay_data_top_ == nullptr; _prelay_data->pnext_ = rsndcon.pdone_relay_data_top_; rsndcon.pdone_relay_data_top_ = _prelay_data; if (should_notify_connection) { solid_check_log(notifyConnection(impl_->manager(), rsndcon.id_, RelayEngineNotification::DoneData), logger, "Connection should be alive"); } if (_prelay_data->isMessageEnd() && !_prelay_data->isMessagePart()) { solid_assert_log(rmsg.pfront_ == nullptr, logger); if (rmsg.state_ == MessageStateE::Relay && _prelay_data->isRequest()) { rmsg.state_ = MessageStateE::WaitResponse; rrcvcon.recv_msg_list_.erase(msgidx); rrcvcon.recv_msg_list_.pushFront(msgidx); solid_log(logger, Info, _rrelay_con_uid << " WaitResponse " << msgidx << " rcv_lst = " << rrcvcon.recv_msg_list_); } else { rrcvcon.recv_msg_list_.erase(msgidx); rsndcon.send_msg_list_.erase(msgidx); solid_assert_log(rsndcon.send_msg_list_.check(), logger); rmsg.clear(); impl_->eraseMessage(msgidx); solid_log(logger, Info, _rrelay_con_uid << " erase message " << msgidx << " rcv_lst = " << rrcvcon.recv_msg_list_); } } else if (_prelay_data->isMessageEnd()) { //completed a partial response message //TODO:!!!! rmsg.state_ = MessageStateE::WaitResponsePart; solid_log(logger, Info, _rrelay_con_uid << " WaitResponsePart " << msgidx << " send snd_lst = " << rsndcon.send_msg_list_ << " send rcv_lst = " << rsndcon.recv_msg_list_ << " recv snd_lst = " << rrcvcon.send_msg_list_ << " recv rcv_lst = " << rrcvcon.recv_msg_list_); } _rmore = !rrcvcon.recv_msg_list_.empty() && rrcvcon.recv_msg_list_.back().hasData(); solid_log(logger, Info, _rrelay_con_uid << " " << _rengine_msg_id << " more " << _rmore << " rcv_lst = " << rrcvcon.recv_msg_list_ << " sender conn notified: " << should_notify_connection << " sender_con = " << rmsg.sender_con_id_ << " recv con = " << rmsg.receiver_con_id_); return; } _rmore = !rrcvcon.recv_msg_list_.empty() && rrcvcon.recv_msg_list_.back().hasData(); solid_log(logger, Verbose, _rrelay_con_uid << " " << _rengine_msg_id << " more " << _rmore << " rcv_lst = " << rrcvcon.recv_msg_list_); } //it happens for canceled relayed messages - see MessageWriter::doWriteRelayedCancelRequest _prelay_data->clear(); impl_->eraseRelayData(_prelay_data); solid_log(logger, Error, _rrelay_con_uid << " message not found " << _rengine_msg_id); } //----------------------------------------------------------------------------- // called by any of connection when either: // sending peer stops/cancels sending the message - MessageReader::Receiver::cancelRelayed // receiver side, request canceling the message - MessageWriter::Sender::cancelRelayed //TODO: add _rmore support as for doComplete //TODO:!!!! //NOTE: // * the following situations must be handled: // + Sender is disconnecting // - while sending Message/Request to receiver // - while sending Response to receiver // - while preparing the Response // - after sending partial Response // + Receiver disconnecting // - while receiving message from sender // - while sender preparing a Response // - while sender awaits Response void EngineCore::doCancel( const UniqueId& _rrelay_con_uid, RelayData* _prelay_data, MessageId const& _rengine_msg_id, DoneFunctionT& _done_fnc) { lock_guard<mutex> lock(impl_->mtx_); solid_assert_log(_rrelay_con_uid.isValid(), logger); solid_assert_log(impl_->isValid(_rrelay_con_uid), logger); solid_log(logger, Info, _rrelay_con_uid << " try complete cancel msg " << _rengine_msg_id); const size_t msgidx = _rengine_msg_id.index; if (msgidx < impl_->msg_dq_.size() && impl_->msg_dq_[msgidx].unique_ == _rengine_msg_id.unique) { MessageStub& rmsg = impl_->msg_dq_[msgidx]; //need to findout on which side we are - sender or receiver if (rmsg.sender_con_id_ == _rrelay_con_uid && rmsg.state_ != MessageStateE::WaitResponsePart) { ConnectionStub& rsndcon = impl_->con_dq_[static_cast<size_t>(rmsg.sender_con_id_.index)]; //cancels comes from the sender connection //Problem // we cannot unlink the connection from the sender connection, because the receiving connection // might have already captured a message buffer which MUST return to the sender connection RelayData* prd; while ((prd = rmsg.pop()) != nullptr) { prd->pnext_ = rsndcon.pdone_relay_data_top_; rsndcon.pdone_relay_data_top_ = prd; } prd = rsndcon.pdone_relay_data_top_; while (prd != nullptr) { _done_fnc(prd->bufptr_); RelayData* ptmprd = prd->pnext_; prd->clear(); impl_->eraseRelayData(prd); prd = ptmprd; } rsndcon.pdone_relay_data_top_ = nullptr; if (rmsg.receiver_con_id_.isValid()) { solid_assert_log(static_cast<size_t>(rmsg.receiver_con_id_.index) < impl_->con_dq_.size() && impl_->con_dq_[static_cast<size_t>(rmsg.receiver_con_id_.index)].unique_ == rmsg.receiver_con_id_.unique, logger); ConnectionStub& rrcvcon = impl_->con_dq_[static_cast<size_t>(rmsg.receiver_con_id_.index)]; rmsg.state_ = MessageStateE::SendCancel; rmsg.push(impl_->createSendCancelRelayData()); { bool should_notify_connection = (rrcvcon.recv_msg_list_.backIndex() == msgidx || !rrcvcon.recv_msg_list_.back().hasData()); rrcvcon.recv_msg_list_.erase(msgidx); rrcvcon.recv_msg_list_.pushBack(msgidx); if (should_notify_connection) { solid_log(logger, Info, _rrelay_con_uid << " notify recv connection of canceled message " << _rengine_msg_id << " sender_con = " << rmsg.sender_con_id_ << " recv con = " << rmsg.receiver_con_id_); solid_check_log(notifyConnection(impl_->manager(), rrcvcon.id_, RelayEngineNotification::NewData), logger, "Connection should be alive"); } else { solid_log(logger, Verbose, _rrelay_con_uid << " rcv con " << rrcvcon.id_ << " not notified for message " << _rengine_msg_id); } } } else { solid_log(logger, Verbose, _rrelay_con_uid << " simply erase the message " << _rengine_msg_id); //simply release the message rsndcon.send_msg_list_.erase(msgidx); rmsg.clear(); impl_->eraseMessage(_rengine_msg_id.index); } solid_assert_log(_prelay_data == nullptr, logger); return; } else if (rmsg.state_ == MessageStateE::WaitResponsePart && rmsg.receiver_con_id_ != _rrelay_con_uid) { solid_log(logger, Verbose, "WaitResponsePart for msg " << _rengine_msg_id << " with receiver_con_id_ " << rmsg.receiver_con_id_ << " while _rrelay_con_uid " << _rrelay_con_uid); ConnectionStub& rrcvcon = impl_->con_dq_[static_cast<size_t>(rmsg.receiver_con_id_.index)]; ConnectionStub& rsndcon = impl_->con_dq_[static_cast<size_t>(rmsg.sender_con_id_.index)]; std::swap(rmsg.receiver_con_id_, rmsg.sender_con_id_); std::swap(rmsg.header_.recipient_request_id_, rmsg.header_.sender_request_id_); rrcvcon.recv_msg_list_.erase(msgidx); // rsndcon.send_msg_list_.erase(msgidx); //MUST do the erase before push!!! rrcvcon.send_msg_list_.pushBack(msgidx); // rsndcon.recv_msg_list_.pushBack(msgidx); // } if (rmsg.receiver_con_id_.isValid()) { solid_assert_log(rmsg.receiver_con_id_ == _rrelay_con_uid, logger); ConnectionStub& rrcvcon = impl_->con_dq_[static_cast<size_t>(rmsg.receiver_con_id_.index)]; //cancel comes from receiving connection //_prelay_data, if not empty, contains the last relay data on the message //which should return to the sending connection rrcvcon.recv_msg_list_.erase(msgidx); rmsg.receiver_con_id_.clear(); //unlink from receiver connection rmsg.state_ = MessageStateE::RecvCancel; if (rmsg.sender_con_id_.isValid()) { solid_assert_log(static_cast<size_t>(rmsg.sender_con_id_.index) < impl_->con_dq_.size() && impl_->con_dq_[static_cast<size_t>(rmsg.sender_con_id_.index)].unique_ == rmsg.sender_con_id_.unique, logger); ConnectionStub& rsndcon = impl_->con_dq_[static_cast<size_t>(rmsg.sender_con_id_.index)]; bool should_notify_connection = rsndcon.pdone_relay_data_top_ == nullptr; if (_prelay_data != nullptr) { _prelay_data->pnext_ = rsndcon.pdone_relay_data_top_; rsndcon.pdone_relay_data_top_ = _prelay_data; _prelay_data = nullptr; } should_notify_connection = should_notify_connection || (msgidx == rsndcon.send_msg_list_.frontIndex() || rsndcon.send_msg_list_.front().state_ != MessageStateE::RecvCancel); rsndcon.send_msg_list_.erase(msgidx); rsndcon.send_msg_list_.pushFront(msgidx); solid_assert_log(rsndcon.send_msg_list_.check(), logger); if (should_notify_connection) { solid_log(logger, Info, _rrelay_con_uid << " notify sending connection of canceled message " << _rengine_msg_id << " sender_con = " << rmsg.sender_con_id_ << " recv con = " << rmsg.receiver_con_id_); solid_check_log(notifyConnection(impl_->manager(), rsndcon.id_, RelayEngineNotification::DoneData), logger, "Connection should be alive"); } else { solid_log(logger, Verbose, _rrelay_con_uid << " snd con not notified for message " << _rengine_msg_id); } } else { solid_log(logger, Verbose, _rrelay_con_uid << " simply erase the message " << _rengine_msg_id); //simply release the message rmsg.clear(); impl_->eraseMessage(_rengine_msg_id.index); } } } else { solid_log(logger, Error, _rrelay_con_uid << " message not found " << _rengine_msg_id); } if (_prelay_data != nullptr) { solid_assert_log(!_prelay_data->bufptr_, logger); _prelay_data->clear(); impl_->eraseRelayData(_prelay_data); } } //----------------------------------------------------------------------------- void EngineCore::doRegisterConnectionId(const ConnectionContext& _rconctx, const size_t _idx) { ConnectionStub& rcon = impl_->con_dq_[_idx]; rcon.id_ = _rconctx.connectionId(); _rconctx.relayId(UniqueId(_idx, rcon.unique_)); } //----------------------------------------------------------------------------- void EngineCore::debugDump() { lock_guard<mutex> lock(impl_->mtx_); int i = 0; for (const auto& msg : impl_->msg_dq_) { size_t datacnt = 0; { auto p = msg.pfront_; while (p != nullptr) { ++datacnt; p = p->pnext_; } } solid_log(logger, Error, "Msg " << (i++) << ": state " << (int)msg.state_ << " datacnt = " << datacnt << " hasData = " << msg.hasData() << " rcvcon = " << msg.receiver_con_id_ << " sndcon " << msg.sender_con_id_); } i = 0; for (const auto& con : impl_->con_dq_) { solid_log(logger, Error, "Con " << i++ << ": " << plot(con) << " done = " << con.pdone_relay_data_top_ << " rcvlst = " << con.recv_msg_list_ << " sndlst = " << con.send_msg_list_); } } //----------------------------------------------------------------------------- size_t EngineCore::Proxy::createConnection() { return re_.impl_->createConnection(); } //----------------------------------------------------------------------------- ConnectionStubBase& EngineCore::Proxy::connection(const size_t _idx) { return re_.impl_->con_dq_[_idx]; } //----------------------------------------------------------------------------- bool EngineCore::Proxy::notifyConnection(const ActorIdT& _rrelay_con_uid, const RelayEngineNotification _what) { return re_.notifyConnection(re_.manager(), _rrelay_con_uid, _what); } //----------------------------------------------------------------------------- void EngineCore::Proxy::stopConnection(const size_t _idx) { re_.doStopConnection(_idx); } //----------------------------------------------------------------------------- void EngineCore::Proxy::registerConnectionId(const ConnectionContext& _rconctx, const size_t _idx) { re_.doRegisterConnectionId(_rconctx, _idx); } //----------------------------------------------------------------------------- } //namespace relay } //namespace mprpc } //namespace frame } //namespace solid
42.370273
287
0.596679
vipalade
a0cfc4f4a033ebba4bd07815db33e1f257aa2b20
2,576
cpp
C++
rEFIt_UEFI/PlatformPOSIX/posix/abort.cpp
acidburn0zzz/CloverBootloader
0e91bcc0cd396f0f049d539a5d3ef516e574f1dd
[ "BSD-2-Clause" ]
1
2022-03-18T16:46:31.000Z
2022-03-18T16:46:31.000Z
rEFIt_UEFI/PlatformPOSIX/posix/abort.cpp
OlarilaHackintosh/CloverBootloader
103e3baaa353c32e05a0ac5f5acc1745667ef348
[ "BSD-2-Clause" ]
null
null
null
rEFIt_UEFI/PlatformPOSIX/posix/abort.cpp
OlarilaHackintosh/CloverBootloader
103e3baaa353c32e05a0ac5f5acc1745667ef348
[ "BSD-2-Clause" ]
null
null
null
#include <Platform.h> // Only use angled for Platform, else, xcode project won't compile #include <stdlib.h> // for abort() //#if defined(CLOVER_BUILD) || !defined(_MSC_VER) //void abort(void) //{ // printf("A fatal error happened. System halted\n"); // while (1) { // tis will avoid warning : Function declared 'noreturn' should not return // abort(); // } //} //#endif #ifdef PANIC_CAN_RETURN bool stop_at_panic = true; bool i_have_panicked = false; #endif /* * * Function panic_ seems useless. It's same as panic(). It's to be able to put a breakpoint in gdb with br panic_(). This is done in gdb_launch script in Qemu */ static void panic_(const char* format, VA_LIST va) #ifndef PANIC_CAN_RETURN __attribute__ ((noreturn)); #endif ; #define FATAL_ERROR_MSG "\nA fatal error happened. System halted.\n" static void panic_(const char* format, VA_LIST va) { if ( format ) { vprintf(format, va); } printf(FATAL_ERROR_MSG); abort(); } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-noreturn" void panic(const char* format, ...) { #ifdef PANIC_CAN_RETURN if ( stop_at_panic ) { VA_LIST va; VA_START(va, format); panic_(format, va); // panic doesn't return // VA_END(va); }else{ i_have_panicked = true; } #else VA_LIST va; VA_START(va, format); panic_(format, va); // panic doesn't return #endif } #pragma clang diagnostic pop /* * Future version to warn about problem but offer the possibility to try to continue * It's not done yes. So far, it's just panic * TODO: */ void panic_ask(const char* format, ...) { #ifdef PANIC_CAN_RETURN if ( stop_at_panic ) { VA_LIST va; VA_START(va, format); panic_(format, va); // panic doesn't return // VA_END(va); }else{ i_have_panicked = true; } #else VA_LIST va; VA_START(va, format); panic_(format, va); // panic doesn't return #endif } /* * Future version to log about pontential technical bugs * It's not done yes. So far, it's just panic * TODO: */ void log_technical_bug(const char* format, ...) { #ifdef PANIC_CAN_RETURN if ( stop_at_panic ) { VA_LIST va; VA_START(va, format); panic_(format, va); // panic doesn't return // VA_END(va); }else{ i_have_panicked = true; } #else VA_LIST va; VA_START(va, format); panic_(format, va); // panic doesn't return #endif } void panic(void) { panic(nullptr); } void _assert(bool b, const char* format, ...) { if ( !b ) { VA_LIST va; VA_START(va, format); panic_(format, va); // panic doesn't return } }
20.608
158
0.664596
acidburn0zzz
a0cfc9e87a63352b005d8785fdb4a961bb20e2d0
387
cpp
C++
09_lambda/09_08_usefulness/09_08_00_usefulness.cpp
pAbogn/cpp_courses
6ffa7da5cc440af3327139a38cfdefcfaae1ebed
[ "MIT" ]
13
2020-09-01T14:57:21.000Z
2021-11-24T06:00:26.000Z
09_lambda/09_08_usefulness/09_08_00_usefulness.cpp
pAbogn/cpp_courses
6ffa7da5cc440af3327139a38cfdefcfaae1ebed
[ "MIT" ]
5
2020-06-11T14:13:00.000Z
2021-07-14T05:27:53.000Z
09_lambda/09_08_usefulness/09_08_00_usefulness.cpp
pAbogn/cpp_courses
6ffa7da5cc440af3327139a38cfdefcfaae1ebed
[ "MIT" ]
10
2021-03-22T07:54:36.000Z
2021-09-15T04:03:32.000Z
// Lambda + unique // Remove zeros only + count zeros #include <iostream> #include <algorithm> #include <vector> int main() { std::vector<int> v{1,2,0,0,5,0,0,0,3,3,0}; auto it = std::unique(v.begin(), v.end()); v.erase(it, v.end()); for (auto& e : v) { std::cout << e << ' '; } // std::cout << std::endl << "Count: " << count << std::endl; }
16.125
65
0.509044
pAbogn
a0d31157daae88f6a9fdd1289f9dd2ca6104d3b0
999
cpp
C++
Source/Engine/Core/Modular/Platform/WindowsImportDLL.cpp
youngjunh98/Game-Engine
7ec6356bd2835ba7f7a1119e873acee3e60b35f5
[ "MIT" ]
null
null
null
Source/Engine/Core/Modular/Platform/WindowsImportDLL.cpp
youngjunh98/Game-Engine
7ec6356bd2835ba7f7a1119e873acee3e60b35f5
[ "MIT" ]
1
2020-11-21T10:05:14.000Z
2020-11-21T10:05:14.000Z
Source/Engine/Core/Modular/Platform/WindowsImportDLL.cpp
youngjunh98/GameEngine
7ec6356bd2835ba7f7a1119e873acee3e60b35f5
[ "MIT" ]
null
null
null
#include <Windows.h> #include <string> #include "Engine/Core/Modular/ModuleManager.h" namespace GameEngine { namespace Modular { ModuleHandle PlatformLoadModule (const PathString& path) { HINSTANCE hModule = LoadLibrary (path.c_str ()); if (hModule == NULL) { return nullptr; } return hModule; } bool PlatformUnloadMoudule (ModuleHandle moduleHandle) { bool bSucceed = false; if (moduleHandle != nullptr) { HMODULE hModule = reinterpret_cast<HMODULE> (moduleHandle); bSucceed = FreeLibrary (hModule) != 0; } return bSucceed; } ModuleCreateFunction PlatformFindModuleFunction (ModuleHandle moduleHandle, const std::string& functionName) { ModuleCreateFunction result = nullptr; if (moduleHandle != nullptr) { auto* functionAddress = GetProcAddress (reinterpret_cast<HMODULE> (moduleHandle), functionName.c_str ()); result = reinterpret_cast<ModuleCreateFunction> (functionAddress); } return result; } } }
20.8125
110
0.706707
youngjunh98
a0daebab932dd01a6b7df35f861939238e72465d
1,604
cpp
C++
problems/chapter12/miiitomi/005.cpp
tokuma09/algorithm_problems
58534620df73b230afbeb12de126174362625a78
[ "CC0-1.0" ]
1
2021-07-07T15:46:58.000Z
2021-07-07T15:46:58.000Z
problems/chapter12/miiitomi/005.cpp
tokuma09/algorithm_problems
58534620df73b230afbeb12de126174362625a78
[ "CC0-1.0" ]
5
2021-06-05T14:16:41.000Z
2021-07-10T07:08:28.000Z
problems/chapter12/miiitomi/005.cpp
tokuma09/algorithm_problems
58534620df73b230afbeb12de126174362625a78
[ "CC0-1.0" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> using namespace std; // 要素数 5 以下の配列の中央値を返す. int median5(vector<int> &c) { sort(c.begin(), c.end()); int idx = (int)c.size() / 2; return c[idx]; } // 配列 b の中央値の中央値を再帰的に返す. int medianOfMedians(vector<int> &b) { if ((int)b.size() <= 5) return median5(b); vector<int> b_new(((int)b.size() - 1) / 5 + 1); for (int i = 0; i < (int)b.size(); i += 5) { vector<int> c = vector<int>(b.begin() + i, b.begin() + min(i+5, (int)b.size())); b_new[i / 5] = median5(c); } return medianOfMedians(b_new); } // a[start:end] から適切な pivot の index を返す. int Pivot(vector<int> &a, int start, int end) { vector<int> b = vector<int>(a.begin()+start, a.begin()+end); int pivot = medianOfMedians(b); int pivot_idx = 0; for (;; pivot_idx++) { if (a[pivot_idx] == pivot) return pivot_idx; } } int Select(vector<int> &a, int k, int start, int end) { int pivot_index = Pivot(a, start, end); int pivot = a[pivot_index]; swap(a[pivot_index], a[end - 1]); int i = start; for (int j = start; j < end - 1; j++) { if (a[j] < pivot) { swap(a[i], a[j]); i++; } } swap(a[i], a[end - 1]); if (i == k) { return a[i]; } else if (i < k) { return Select(a, k, i + 1, end); } else { return Select(a, k, start, i); } } int main() { int N, k; cin >> N >> k; k--; vector<int> a(N); for (int i = 0; i < N; i++) cin >> a[i]; int ans = Select(a, k, 0, N); cout << ans << endl; }
23.588235
88
0.507481
tokuma09
a0db54a64f8c7047bf52501ae837ffb108b0c555
78
cpp
C++
Source/General/Interface/IDebugger.cpp
paintdream/paintsnow
3a1cbc9e571eaa2e62a3a2d60f75817b45f0c781
[ "MIT" ]
null
null
null
Source/General/Interface/IDebugger.cpp
paintdream/paintsnow
3a1cbc9e571eaa2e62a3a2d60f75817b45f0c781
[ "MIT" ]
null
null
null
Source/General/Interface/IDebugger.cpp
paintdream/paintsnow
3a1cbc9e571eaa2e62a3a2d60f75817b45f0c781
[ "MIT" ]
null
null
null
#include "IDebugger.h" using namespace PaintsNow; IDebugger::~IDebugger() {}
15.6
26
0.74359
paintdream
a0e6678c3ea06cdb114365cd8e481ab7684ed562
42,753
cc
C++
src/media/audio/tools/signal_generator/signal_generator.cc
DamieFC/fuchsia
f78a4a1326f4a4bb5834500918756173c01bab4f
[ "BSD-2-Clause" ]
1
2020-12-29T17:07:06.000Z
2020-12-29T17:07:06.000Z
src/media/audio/tools/signal_generator/signal_generator.cc
DamieFC/fuchsia
f78a4a1326f4a4bb5834500918756173c01bab4f
[ "BSD-2-Clause" ]
null
null
null
src/media/audio/tools/signal_generator/signal_generator.cc
DamieFC/fuchsia
f78a4a1326f4a4bb5834500918756173c01bab4f
[ "BSD-2-Clause" ]
null
null
null
// Copyright 2018 The Fuchsia 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 "src/media/audio/tools/signal_generator/signal_generator.h" #include <fuchsia/ultrasound/cpp/fidl.h> #include <zircon/syscalls.h> #include <zircon/syscalls/clock.h> #include <algorithm> #include <cmath> #include <iostream> #include <fbl/algorithm.h> #include <fbl/string_printf.h> #include "src/media/audio/lib/clock/clone_mono.h" #include "src/media/audio/lib/clock/utils.h" #include "src/media/audio/lib/logging/cli.h" namespace media::tools { // The signal's duration, in nanoseconds, must fit into an int64_t. (292 yrs: not a problem) constexpr double kMaxDurationSecs = std::numeric_limits<int64_t>::max() / ZX_SEC(1); constexpr auto kPlayStartupDelay = zx::msec(0); const char* SampleFormatToString(const fuchsia::media::AudioSampleFormat& format) { switch (format) { case fuchsia::media::AudioSampleFormat::FLOAT: return "float"; case fuchsia::media::AudioSampleFormat::SIGNED_24_IN_32: return "int24"; case fuchsia::media::AudioSampleFormat::SIGNED_16: return "int16"; default: return "(unknown)"; } } fbl::String RefTimeStrFromZxTime(zx::time zx_time) { auto time = zx_time.get(); if (time == fuchsia::media::NO_TIMESTAMP) { return fbl::String(" [NO_TIMESTAMP] "); } return fbl::StringPrintf("%07lu'%03lu'%03lu'%03lu", time / ZX_SEC(1), (time % ZX_SEC(1)) / ZX_MSEC(1), (time % ZX_MSEC(1)) / ZX_USEC(1), time % ZX_USEC(1)); } fbl::String RefTimeMsStrFromZxTime(zx::time zx_time) { auto time = zx_time.get(); if (time == fuchsia::media::NO_TIMESTAMP) { return fbl::String("[NO_TIMESTAMP] "); } return fbl::StringPrintf("%07lu'%03lu.%02lu ms", time / ZX_SEC(1), (time % ZX_SEC(1)) / ZX_MSEC(1), (time % ZX_MSEC(1)) / ZX_USEC(10)); } MediaApp::MediaApp(fit::closure quit_callback) : quit_callback_(std::move(quit_callback)) { CLI_CHECK(quit_callback_, "quit_callback must not be null"); } // Prepare for playback, submit initial data, start the presentation timeline. void MediaApp::Run(sys::ComponentContext* app_context) { // Calculate the frame size, number of packets, and shared-buffer size. SetupPayloadCoefficients(); // Check the cmdline flags; exit if any are invalid or out-of-range. ParameterRangeChecks(); SetAudioCoreSettings(app_context); AcquireAudioRenderer(app_context); // Show a summary of all our settings: exactly what we are about to do. DisplayConfigurationSettings(); // If requested, configure a WavWriter that will concurrently write this signal to a WAV file. InitializeWavWriter(); // Create VmoMapper(s) that Create+Map a VMO. Send these down via AudioRenderer::AddPayloadBuffer. CreateMemoryMapping(); // Retrieve the default reference clock for this renderer; once a device is ready, start playback. GetClockAndStart(); } // Based on the user-specified values for signal frequency and milliseconds per payload, calculate // the other related coefficients needed for our mapped memory section, and for our series of // payloads that reference that section. void MediaApp::SetupPayloadCoefficients() { // Max duration_secs_(2^33.1) and frame_rate_(192k: 2^17.6) ==> 2^50.7 frames: no overflow risk total_frames_to_send_ = static_cast<uint64_t>(duration_secs_ * frame_rate_); num_packets_to_send_ = total_frames_to_send_ / frames_per_packet_; if (num_packets_to_send_ * frames_per_packet_ < total_frames_to_send_) { ++num_packets_to_send_; } // Number of frames in each period of the recurring signal. frames_per_period_ = frame_rate_ / frequency_; amplitude_scalar_ = amplitude_; switch (sample_format_) { case fuchsia::media::AudioSampleFormat::SIGNED_24_IN_32: amplitude_scalar_ *= (std::numeric_limits<int32_t>::max() & 0xFFFFFF00); sample_size_ = sizeof(int32_t); break; case fuchsia::media::AudioSampleFormat::SIGNED_16: amplitude_scalar_ *= std::numeric_limits<int16_t>::max(); sample_size_ = sizeof(int16_t); break; case fuchsia::media::AudioSampleFormat::FLOAT: sample_size_ = sizeof(float); break; default: printf("Unknown AudioSampleFormat: %u\n", sample_format_); Shutdown(); return; } // As mentioned above, for 24-bit audio we use 32-bit samples (low byte 0). frame_size_ = num_channels_ * sample_size_; bytes_per_packet_ = frames_per_packet_ * frame_size_; // From the specified size|number of payload buffers, determine how many packets fit, then trim // the mapping to what will be used. This size will be split across |num_payload_buffers_| // buffers, e.g. 2 buffers of 48000 frames each will be large enough hold 200 480-frame packets. auto total_payload_buffer_space = num_payload_buffers_ * frames_per_payload_buffer_ * frame_size_; total_mappable_packets_ = total_payload_buffer_space / bytes_per_packet_; // Shard out the payloads across multiple buffers, ensuring we can hold at least 1 buffer. packets_per_payload_buffer_ = std::max(1u, total_mappable_packets_ / num_payload_buffers_); } void MediaApp::ParameterRangeChecks() { bool success = true; if (num_channels_ < fuchsia::media::MIN_PCM_CHANNEL_COUNT) { std::cerr << "Number of channels must be at least " << fuchsia::media::MIN_PCM_CHANNEL_COUNT << std::endl; success = false; } if (num_channels_ > fuchsia::media::MAX_PCM_CHANNEL_COUNT) { std::cerr << "Number of channels must be no greater than " << fuchsia::media::MAX_PCM_CHANNEL_COUNT << std::endl; success = false; } if (frame_rate_ < fuchsia::media::MIN_PCM_FRAMES_PER_SECOND) { std::cerr << "Frame rate must be at least " << fuchsia::media::MIN_PCM_FRAMES_PER_SECOND << std::endl; success = false; } if (frame_rate_ > fuchsia::media::MAX_PCM_FRAMES_PER_SECOND) { std::cerr << "Frame rate must be no greater than " << fuchsia::media::MAX_PCM_FRAMES_PER_SECOND << std::endl; success = false; } if (frequency_ < 0.0) { std::cerr << "Frequency cannot be negative" << std::endl; success = false; } if (amplitude_ > 1.0) { std::cerr << "Amplitude must be no greater than 1.0" << std::endl; success = false; } if (amplitude_ < -1.0) { std::cerr << "Amplitude must be no less than -1.0" << std::endl; success = false; } if (duration_secs_ < 0.0) { std::cerr << "Duration cannot be negative" << std::endl; success = false; } if (duration_secs_ > kMaxDurationSecs) { std::cerr << "Duration must not exceed " << kMaxDurationSecs << " seconds (" << (kMaxDurationSecs / 86400.0 / 365.25) << " years)" << std::endl; success = false; } if (frames_per_packet_ > (num_payload_buffers_ * frames_per_payload_buffer_ / 2) && frames_per_packet_ < num_payload_buffers_ * frames_per_payload_buffer_) { std::cerr << "Packet size cannot be larger than half the total payload space" << std::endl; success = false; } if (frames_per_packet_ < frame_rate_ / 1000) { std::cerr << "Packet size must be 1 millisecond or more" << std::endl; success = false; } if (static_cast<uint64_t>(frames_per_payload_buffer_) * frame_size_ > std::numeric_limits<uint32_t>::max()) { std::cerr << "Payload buffer cannot exceed " << std::numeric_limits<uint32_t>::max() << " bytes (" << (std::numeric_limits<uint32_t>::max() / frame_size_) << " frames, for this frame_size)" << std::endl; success = false; } if (clock_rate_adjustment_) { if (clock_type_ != ClockType::Monotonic) { clock_type_ = ClockType::Custom; } if (clock_rate_adjustment_.value() > ZX_CLOCK_UPDATE_MAX_RATE_ADJUST) { std::cerr << "Clock adjustment must be " << ZX_CLOCK_UPDATE_MAX_RATE_ADJUST << " parts-per-million or less" << std::endl; success = false; } if (clock_rate_adjustment_.value() < ZX_CLOCK_UPDATE_MIN_RATE_ADJUST) { std::cerr << "Clock rate adjustment must be " << ZX_CLOCK_UPDATE_MIN_RATE_ADJUST << " parts-per-million or more" << std::endl; success = false; } } if (stream_gain_db_) { stream_gain_db_ = std::clamp<float>(stream_gain_db_.value(), fuchsia::media::audio::MUTED_GAIN_DB, fuchsia::media::audio::MAX_GAIN_DB); } if (usage_gain_db_) { usage_gain_db_ = std::clamp<float>(usage_gain_db_.value(), fuchsia::media::audio::MUTED_GAIN_DB, kUnityGainDb); } if (usage_volume_) { usage_volume_ = std::clamp<float>(usage_volume_.value(), fuchsia::media::audio::MIN_VOLUME, fuchsia::media::audio::MAX_VOLUME); } CLI_CHECK(success, "Exiting."); } void MediaApp::DisplayConfigurationSettings() { auto it = std::find_if(kRenderUsageOptions.cbegin(), kRenderUsageOptions.cend(), [usage = usage_](auto usage_string_and_usage) { return usage == usage_string_and_usage.second; }); CLI_CHECK(it != kRenderUsageOptions.cend(), "no RenderUsage found"); auto usage_str = it->first; printf("\nAudioRenderer configured for %d-channel %s at %u Hz with the %s usage.", num_channels_, SampleFormatToString(sample_format_), frame_rate_, usage_str); printf("\nContent is "); if (output_signal_type_ == kOutputTypeNoise) { printf("white noise"); } else if (output_signal_type_ == kOutputTypePinkNoise) { printf("pink noise"); } else { printf("a %.3f Hz ", frequency_); if (output_signal_type_ == kOutputTypeSquare) { printf("square wave"); } else if (output_signal_type_ == kOutputTypeSine) { printf("sine wave"); } else if (output_signal_type_ == kOutputTypeSawtooth) { printf("rising sawtooth wave"); } else if (output_signal_type_ == kOutputTypeTriangle) { printf("isosceles triangle wave"); } } printf(" with amplitude %.4f", amplitude_); if (ramp_target_gain_db_) { printf(",\nramping stream gain from %.3f dB to %.3f dB over %.6lf seconds (%ld nanoseconds)", stream_gain_db_.value(), ramp_target_gain_db_.value(), static_cast<double>(ramp_duration_nsec_) / 1000000000, ramp_duration_nsec_); } else if (stream_gain_db_) { printf(",\nsetting stream gain to %.3f dB", stream_gain_db_.value()); } if (stream_mute_) { printf(",\n after explicitly %s this stream", stream_mute_.value() ? "muting" : "unmuting"); } if (usage_gain_db_ || usage_volume_) { printf(",\nafter setting "); if (usage_gain_db_) { printf("%s gain to %.3f dB%s", usage_str, usage_gain_db_.value(), (usage_volume_ ? " and " : "")); } if (usage_volume_) { printf("%s volume to %.1f", usage_str, usage_volume_.value()); } } printf(".\nThe generated signal will play for %.3f seconds", duration_secs_); if (file_name_) { printf(" and will be saved to '%s'", file_name_.value().c_str()); } printf(".\nThe stream's reference clock will be "); switch (clock_type_) { case ClockType::Default: printf("the default clock"); break; case ClockType::Flexible: printf("the AudioCore-provided 'flexible' clock"); break; case ClockType::Monotonic: printf("a clone of the MONOTONIC clock"); if (clock_rate_adjustment_) { printf(", rate-adjusted by %i ppm", clock_rate_adjustment_.value()); } break; case ClockType::Custom: printf("a custom clock"); if (clock_rate_adjustment_) { printf(", rate-adjusted by %i ppm", clock_rate_adjustment_.value()); } break; } printf(".\nThe renderer will transport data using %u %stimestamped buffer sections of %u frames", total_mappable_packets_, (timestamp_packets_ ? "" : "non-"), frames_per_packet_); if (pts_continuity_threshold_secs_) { printf(",\nhaving set the PTS continuity threshold to %f seconds", pts_continuity_threshold_secs_.value()); } if (online_) { printf(",\nusing strict timing for flow control (online mode)"); } else { printf(",\nusing previous packet completions for flow control (contiguous mode)"); } printf(".\n\n"); } // AudioCore interface is used to change the gain/volume of usages. void MediaApp::SetAudioCoreSettings(sys::ComponentContext* app_context) { if (usage_gain_db_ || usage_volume_) { fuchsia::media::AudioCorePtr audio_core; app_context->svc()->Connect(audio_core.NewRequest()); if (usage_gain_db_) { audio_core->SetRenderUsageGain(usage_, usage_gain_db_.value()); } if (usage_volume_) { fuchsia::media::Usage usage; usage.set_render_usage(usage_); audio_core->BindUsageVolumeControl(std::move(usage), usage_volume_control_.NewRequest()); usage_volume_control_.set_error_handler([this](zx_status_t status) { CLI_CHECK(Shutdown(), "Client connection to fuchsia.media.audio.VolumeControl failed: " << status); }); } // ... now just let the instance of audio_core go out of scope. } } // Use ComponentContext to acquire AudioPtr; use that to acquire AudioRendererPtr in turn. Set // AudioRenderer error handler, in case of channel closure. void MediaApp::AcquireAudioRenderer(sys::ComponentContext* app_context) { if (ultrasound_) { fuchsia::ultrasound::FactorySyncPtr ultrasound_factory; app_context->svc()->Connect(ultrasound_factory.NewRequest()); zx::clock reference_clock; fuchsia::media::AudioStreamType stream_type; ultrasound_factory->CreateRenderer(audio_renderer_.NewRequest(), &reference_clock, &stream_type); frame_rate_ = stream_type.frames_per_second; num_channels_ = stream_type.channels; sample_format_ = stream_type.sample_format; } else { // Audio interface is needed to create AudioRenderer and set routing policy. fuchsia::media::AudioPtr audio; app_context->svc()->Connect(audio.NewRequest()); audio->CreateAudioRenderer(audio_renderer_.NewRequest()); if (stream_mute_ || stream_gain_db_ || ramp_target_gain_db_) { audio_renderer_->BindGainControl(gain_control_.NewRequest()); gain_control_.set_error_handler([this](zx_status_t status) { CLI_CHECK(Shutdown(), "Client connection to fuchsia.media.audio.GainControl failed: " << status); }); } // Set our render stream format, plus other settings as needed: gain, clock, continuity // threshold InitializeAudibleRenderer(); // ... now just let the instance of audio go out of scope. // // Although we could technically call gain_control_'s SetMute|SetGain|SetGainWithRamp here, // then disconnect it (like we do for audio_core and audio), we instead maintain our // GainControl throughout playback, in case we someday want to change gain during playback. } if (online_) { online_send_packet_ref_period_ = (zx::sec(1) * frames_per_packet_) / frame_rate_; } SetAudioRendererEvents(); ConfigureAudioRendererPts(); } void MediaApp::ConfigureAudioRendererPts() { if (timestamp_packets_) { audio_renderer_->SetPtsUnits(frame_rate_, 1); } if (pts_continuity_threshold_secs_) { audio_renderer_->SetPtsContinuityThreshold(pts_continuity_threshold_secs_.value()); } } // Set the AudioRenderer's audio format, plus other settings requested by command line void MediaApp::InitializeAudibleRenderer() { CLI_CHECK(audio_renderer_, "audio_renderer must not be null"); fuchsia::media::AudioStreamType format; format.sample_format = sample_format_; format.channels = num_channels_; format.frames_per_second = frame_rate_; // To indicate we want a reference clock OTHER than the default, we'll call SetReferenceClock(). if (clock_type_ != ClockType::Default) { zx::clock reference_clock_to_set; if (clock_type_ == ClockType::Flexible) { // To select the Flexible clock maintained by audio_core, we effectively SetRefClock(NULL). reference_clock_to_set = zx::clock(ZX_HANDLE_INVALID); } else { // For Monotonic and Custom, we create and rights-reduce a clock to send to SetRefClock(). zx_status_t status; zx::clock::update_args args; args.reset(); if (clock_rate_adjustment_) { args.set_rate_adjust(clock_rate_adjustment_.value()); } if (clock_type_ == ClockType::Monotonic) { // This clock is already started, in lock-step with CLOCK_MONOTONIC. reference_clock_to_set = audio::clock::AdjustableCloneOfMonotonic(); CLI_CHECK(reference_clock_to_set.is_valid(), "Invalid clock; could not clone monotonic clock"); } else { // In custom clock case, set it to start at value zero. Rate-adjust it if specified. status = zx::clock::create(ZX_CLOCK_OPT_MONOTONIC | ZX_CLOCK_OPT_CONTINUOUS, nullptr, &reference_clock_to_set); CLI_CHECK_OK(status, "zx::clock::create failed"); args.set_value(zx::time(0)); } if (clock_rate_adjustment_ || clock_type_ == ClockType::Custom) { // update starts our clock status = reference_clock_to_set.update(args); CLI_CHECK_OK(status, "zx::clock::update failed"); } // The clock we send to AudioRenderer cannot have ZX_RIGHT_WRITE. Most clients would // retain their custom clocks for subsequent rate-adjustment, and thus would use // 'duplicate' to create the rights-reduced clock. This app doesn't yet allow // rate-adjustment during playback (we also don't need this clock to read the current ref // time: we call GetReferenceClock later), so we use 'replace' (not 'duplicate'). auto rights = ZX_RIGHT_DUPLICATE | ZX_RIGHT_TRANSFER | ZX_RIGHT_READ; status = reference_clock_to_set.replace(rights, &reference_clock_to_set); CLI_CHECK_OK(status, "zx::clock::duplicate failed"); } audio_renderer_->SetReferenceClock(std::move(reference_clock_to_set)); } audio_renderer_->SetUsage(usage_); audio_renderer_->SetPcmStreamType(format); // Set usage volume, if specified. if (usage_volume_) { usage_volume_control_->SetVolume(usage_volume_.value()); } // Set stream gain and mute, if specified. if (stream_mute_) { gain_control_->SetMute(stream_mute_.value()); } if (stream_gain_db_) { gain_control_->SetGain(stream_gain_db_.value()); } if (ramp_target_gain_db_) { gain_control_->SetGainWithRamp(ramp_target_gain_db_.value(), ramp_duration_nsec_, fuchsia::media::audio::RampType::SCALE_LINEAR); } } void MediaApp::InitializeWavWriter() { // 24-bit buffers use 32-bit samples (lowest byte zero), and when this particular utility saves to // .wav file, we save the entire 32 bits. if (file_name_) { wav_writer_initialized_ = wav_writer_.Initialize(file_name_.value().c_str(), sample_format_, num_channels_, frame_rate_, sample_size_ * 8); CLI_CHECK(wav_writer_initialized_, "WavWriter::Initialize() failed"); } } // We share a memory section with our AudioRenderer, divided into equally-sized payloads (size // specified by the user). For now, we trim the end of the memory section, rather than handle the // occasional irregularly-sized packet. // TODO(mpuryear): handle end-of-buffer wraparound; make it a true ring buffer. void MediaApp::CreateMemoryMapping() { for (uint32_t i = 0; i < num_payload_buffers_; ++i) { auto& payload_buffer = payload_buffers_.emplace_back(); zx::vmo payload_vmo; zx_status_t status = payload_buffer.CreateAndMap( bytes_per_packet_ * packets_per_payload_buffer_, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, nullptr, &payload_vmo, ZX_RIGHT_READ | ZX_RIGHT_MAP | ZX_RIGHT_TRANSFER); CLI_CHECK(status == ZX_OK || Shutdown(), "VmoMapper:::CreateAndMap failed: " << status); audio_renderer_->AddPayloadBuffer(i, std::move(payload_vmo)); } } void MediaApp::GetClockAndStart() { audio_renderer_->GetReferenceClock([this](zx::clock received_clock) { reference_clock_ = std::move(received_clock); if (verbose_) { audio::clock::GetAndDisplayClockDetails(reference_clock_); auto mono_now = zx::clock::get_monotonic(); printf("- Received ref clock at %lu. (%s sufficient min_lead_time)\n", mono_now.get(), (min_lead_time_ >= kRealDeviceMinLeadTime ? "Received" : "Awaiting")); } if (min_lead_time_ >= kRealDeviceMinLeadTime && !playing()) { Play(); } }); } // Prime (pre-submit) an initial set of packets, then start playback. // Called from the GetReferenceClock callback void MediaApp::Play() { if (num_packets_to_send_ == 0) { // No packets to send, so we're done! Shutdown will unwind everything and exit our loop. Shutdown(); return; } zx::time ref_now; auto status = reference_clock_.read(ref_now.get_address()); CLI_CHECK(status == ZX_OK || Shutdown(), "zx::clock::read failed during init: " << status); // read current time and use it as our rand48 seed ... srand48(ref_now.get()); // ... before generating random data to prime our pink noise generator if (output_signal_type_ == kOutputTypePinkNoise) { PrimePinkNoiseFilter(); } target_num_packets_outstanding_ = online_ ? (total_mappable_packets_ / 2) : total_mappable_packets_; // std::min must be done at the higher width, but the result is guaranteed to fit into int32 target_num_packets_outstanding_ = static_cast<uint32_t>( std::min<uint64_t>(target_num_packets_outstanding_, num_packets_to_send_)); auto target_duration_outstanding = (zx::sec(1) * target_num_packets_outstanding_ * frames_per_packet_) / frame_rate_; if (target_duration_outstanding < min_lead_time_ && target_duration_outstanding < zx::nsec(static_cast<int64_t>(duration_secs_ * ZX_SEC(1)))) { printf("\nPayload buffer space is too small for the minimum lead time and signal duration.\n"); Shutdown(); return; } // We "prime" the audio renderer by submitting an initial set of packets before starting playback. // We will subsequently send the rest one at a time -- either from a timer (if 'online'), or from // the completion of a previous packet (if not 'online'). // When priming, we send down only as many packets as concurrently fit into our payload buffer. // And if online, we send half that much, to provide leeway for the renderer to temporarily // complete packets too fast OR too slow, because of slight differences in clock rate. for (uint32_t packet_num = 0; packet_num < target_num_packets_outstanding_; ++packet_num) { SendPacket(); } status = reference_clock_.read(ref_now.get_address()); CLI_CHECK(status == ZX_OK || Shutdown(), "zx::clock::read failed during Play(): " << status); // Extrapolating backwards (to make future calculations easier), this represents when we would // have sent our first packet. This is our first approximation, we will update this when we // receive the actual start time. target_online_send_first_packet_ref_time_ = ref_now - target_duration_outstanding; reference_start_time_ = ref_now + kPlayStartupDelay + min_lead_time_; zx::time requested_ref_start_time = set_ref_start_time_ ? reference_start_time_ : zx::time(fuchsia::media::NO_TIMESTAMP); auto media_start_pts = media_start_pts_.value_or(fuchsia::media::NO_TIMESTAMP); if (verbose_) { auto mono_time_result = audio::clock::MonotonicTimeFromReferenceTime(reference_clock_, ref_now); CLI_CHECK(mono_time_result.is_ok(), "Could not convert ref_time to mono_time"); auto mono_now = mono_time_result.take_value(); auto requested_ref_str = RefTimeStrFromZxTime(requested_ref_start_time); auto requested_media_str = RefTimeStrFromZxTime(zx::time{media_start_pts}); auto ref_now_str = RefTimeMsStrFromZxTime(ref_now); auto mono_now_str = RefTimeMsStrFromZxTime(mono_now); printf("\nCalling Play (ref %s, media %s) at ref_now %s : mono_now %s\n", requested_ref_str.c_str(), requested_media_str.c_str(), ref_now_str.c_str(), mono_now_str.c_str()); } auto play_completion_func = [this](int64_t actual_ref_start, int64_t actual_media_start) { if (verbose_) { zx::time ref_now; auto status = reference_clock_.read(ref_now.get_address()); CLI_CHECK(status == ZX_OK || Shutdown(), "zx::clock::read failed during Play callback: " << status); auto mono_time_result = audio::clock::MonotonicTimeFromReferenceTime(reference_clock_, ref_now); CLI_CHECK(mono_time_result.is_ok(), "Could not convert ref_time to mono_time"); auto mono_now = mono_time_result.take_value(); auto actual_ref_str = RefTimeStrFromZxTime(zx::time{actual_ref_start}); auto actual_media_str = RefTimeStrFromZxTime(zx::time{actual_media_start}); auto ref_now_str = RefTimeMsStrFromZxTime(ref_now); auto mono_now_str = RefTimeMsStrFromZxTime(mono_now); printf("Play callback(ref %s, media %s) at ref_now %s : mono_now %s\n\n", actual_ref_str.c_str(), actual_media_str.c_str(), ref_now_str.c_str(), mono_now_str.c_str()); } // Now that we have the real start time, update our online "start" value. target_online_send_first_packet_ref_time_ = target_online_send_first_packet_ref_time_ + (zx::time(actual_ref_start) - reference_start_time_); reference_start_time_ = zx::time(actual_ref_start); }; audio_renderer_->Play(requested_ref_start_time.get(), media_start_pts, play_completion_func); set_playing(); if (online_) { ScheduleNextSendPacket(); } } // We have a set of buffers each backed by its own VMO, with each buffer sub-divided into // uniformly-sized zones, called payloads. // // We round robin packets across each buffer, wrapping around to the start of each buffer once // the end is encountered. For example, with 2 buffers that can each hold 2 payloads, we would // send audio packets in the following order: // // ------------------------ // | buffer_id | payload_id | // | (vmo) | (offset) | // |-----------|------------| // | buffer 0 | payload 0 | // | buffer 1 | payload 0 | // | buffer 0 | payload 1 | // | buffer 1 | payload 1 | // | buffer 0 | payload 0 | // | ... etc ... | // ------------------------ MediaApp::AudioPacket MediaApp::CreateAudioPacket(uint64_t packet_num) { fuchsia::media::StreamPacket packet; packet.payload_buffer_id = packet_num % num_payload_buffers_; auto buffer_payload_index = packet_num / num_payload_buffers_; packet.payload_offset = (buffer_payload_index % packets_per_payload_buffer_) * bytes_per_packet_; // If last payload, send exactly what remains (otherwise send a full payload). packet.payload_size = (packet_num + 1 == num_packets_to_send_) ? (total_frames_to_send_ - (packet_num * frames_per_packet_)) * frame_size_ : bytes_per_packet_; // packet.pts (media time) is NO_TIMESTAMP by default unless we override it. if (timestamp_packets_) { packet.pts = packet_num * frames_per_packet_; // assumes PTS units of "frames" if (media_start_pts_) { packet.pts += media_start_pts_.value(); } } return { .stream_packet = std::move(packet), .vmo = &payload_buffers_[packet.payload_buffer_id], }; } void MediaApp::GenerateAudioForPacket(const AudioPacket& audio_packet, uint64_t packet_num) { const auto& packet = audio_packet.stream_packet; auto audio_buff = reinterpret_cast<uint8_t*>(audio_packet.vmo->start()) + packet.payload_offset; // Recompute payload_frames each time, since the final packet may be 'short'. // // TODO(mpuryear): don't recompute this every time; use payload_frames_ (and pre-compute this) // except for last packet, which we either check for here or pass in as a boolean parameter. uint32_t payload_frames = static_cast<uint32_t>(packet.payload_size) / frame_size_; switch (sample_format_) { case fuchsia::media::AudioSampleFormat::SIGNED_24_IN_32: WriteAudioIntoBuffer<int32_t>(reinterpret_cast<int32_t*>(audio_buff), payload_frames, frames_per_packet_ * packet_num); break; case fuchsia::media::AudioSampleFormat::SIGNED_16: WriteAudioIntoBuffer<int16_t>(reinterpret_cast<int16_t*>(audio_buff), payload_frames, frames_per_packet_ * packet_num); break; case fuchsia::media::AudioSampleFormat::FLOAT: WriteAudioIntoBuffer<float>(reinterpret_cast<float*>(audio_buff), payload_frames, frames_per_packet_ * packet_num); break; default: CLI_CHECK(false, "Unknown AudioSampleFormat"); } } // Allocate memory for history values; advance the filter through its initial transient void MediaApp::PrimePinkNoiseFilter() { input_history_ = std::make_unique<HistoryBuffer[]>(num_channels_); output_history_ = std::make_unique<HistoryBuffer[]>(num_channels_); // Skip the filter's initial transient response by pre-generating 1430 frames, the filter's T60 // (-60 decay) interval, computed by "T60 = round(log(1000)/(1-max(abs(roots(kFeedBack)))))" for (auto i = 0u; i < 1430u; ++i) { AdvancePinkNoiseFrame(); } } // Generate a pink-noise frame, using a four-stage filter with kFeedFwd and kFeedBack coefficients. void MediaApp::AdvancePinkNoiseFrame() { // For each channel, calculate a new output based on cached vals plus a new random input value for (uint32_t chan = 0; chan < num_channels_; ++chan) { (void)NextPinkNoiseSample(chan); } } // Calculate and retrieve the new pink-noise sample value for this channel. double MediaApp::NextPinkNoiseSample(uint32_t chan) { // // First, shift our previous inputs and outputs into the past, by one frame for (size_t i = 3; i > 0; --i) { output_history_[chan][i] = output_history_[chan][i - 1]; input_history_[chan][i] = input_history_[chan][i - 1]; } // (both [chan][0] values are now stale, but we overwrite them immediately) // // Second, generate the initial white-noise input, boosting to normalize the result. input_history_[chan][0] = drand48() * 2.0 - 1.0; input_history_[chan][0] *= kPinkNoiseSignalBoostFactor; // // Finally, apply the filter to {input + cached input/output values} to get the new output val. output_history_[chan][0] = (input_history_[chan][0] * kFeedFwd[0] + input_history_[chan][1] * kFeedFwd[1] + input_history_[chan][2] * kFeedFwd[2] + input_history_[chan][3] * kFeedFwd[3]) - (output_history_[chan][1] * kFeedBack[1] + output_history_[chan][2] * kFeedBack[2] + output_history_[chan][3] * kFeedBack[3]); return output_history_[chan][0]; } // Write signal into the next section of our buffer. Track how many total frames since playback // started, to handle arbitrary frequencies of type double. Converting frames_since_start to a // double running_frame limits precision to 2^53 frames (1487 yrs @ 192kHz: more than adequate!). template <typename SampleType> void MediaApp::WriteAudioIntoBuffer(SampleType* audio_buffer, uint32_t num_frames, uint64_t frames_since_start) { const double rads_per_frame = 2.0 * M_PI / frames_per_period_; // Radians/Frame. for (uint32_t frame = 0; frame < num_frames; ++frame, ++frames_since_start) { double running_frame = static_cast<double>(frames_since_start); // Generated signal value, before applying amplitude scaling. double raw_val; for (auto chan_num = 0u; chan_num < num_channels_; ++chan_num) { switch (output_signal_type_) { case kOutputTypeSine: raw_val = sin(rads_per_frame * running_frame); break; case kOutputTypeSquare: raw_val = (fmod(running_frame, frames_per_period_) >= frames_per_period_ / 2) ? -1.0 : 1.0; break; case kOutputTypeSawtooth: raw_val = (fmod(running_frame / frames_per_period_, 1.0) * 2.0) - 1.0; break; case kOutputTypeTriangle: raw_val = (abs(fmod(running_frame / frames_per_period_, 1.0) - 0.5) * 4.0) - 1.0; break; case kOutputTypeNoise: raw_val = drand48() * 2.0 - 1.0; break; case kOutputTypePinkNoise: raw_val = NextPinkNoiseSample(chan_num); break; } // raw_val cannot exceed 1.0; amplitude_scalar_ cannot exceed the SampleType's max. // Thus, the below static_casts are safe. SampleType val; if constexpr (std::is_same_v<SampleType, float>) { val = static_cast<float>(raw_val * amplitude_scalar_); } else if constexpr (std::is_same_v<SampleType, int32_t>) { // 24-bit in 32-bit container: val = static_cast<int32_t>( lround(raw_val * amplitude_scalar_ / 256.0)); // round at bit 8, and val = val << 8; // leave bits 0-7 blank } else { val = static_cast<int16_t>(lround(raw_val * amplitude_scalar_)); } audio_buffer[frame * num_channels_ + chan_num] = val; } } } constexpr zx::duration kPktCompleteToleranceDuration = zx::msec(50); constexpr uint64_t kPktCompleteTolerance = 5; bool MediaApp::CheckPayloadSpace() { if (num_packets_completed_ > 0 && num_packets_sent_ <= num_packets_completed_) { printf("! Sending: packet %4lu; packet %4lu has already completed - did we underrun?\n", num_packets_sent_, num_packets_completed_); return false; } if (num_packets_sent_ >= num_packets_completed_ + total_mappable_packets_) { printf("! Sending: packet %4lu; only %4lu have completed - did we overrun?\n", num_packets_sent_, num_packets_completed_); return false; } target_num_packets_outstanding_ = std::min(static_cast<uint32_t>(num_packets_to_send_ - num_packets_completed_), target_num_packets_outstanding_); auto actual_packets_outstanding = num_packets_sent_ - num_packets_completed_; auto target_duration_outstanding = (zx::sec(1) * target_num_packets_outstanding_ * frames_per_packet_) / frame_rate_; auto actual_duration_outstanding = (zx::sec(1) * actual_packets_outstanding * frames_per_packet_) / frame_rate_; auto elapsed_time_sec = static_cast<double>(num_frames_completed_) / frame_rate_; // Check whether payload buffer is staying at approx the same fullness. if (num_packets_completed_ > 0 && actual_packets_outstanding + kPktCompleteTolerance <= target_num_packets_outstanding_ && actual_duration_outstanding + kPktCompleteToleranceDuration <= target_duration_outstanding) { printf( "\n? %4lu packets outstanding (%ld msec); expected %4u (%ld msec); total elapsed %f sec: " "are we completing faster than sending?\n\n", actual_packets_outstanding, (actual_duration_outstanding / ZX_MSEC(1)).get(), target_num_packets_outstanding_, (target_duration_outstanding / ZX_MSEC(1)).get(), elapsed_time_sec); return false; } if (num_packets_completed_ > 0 && target_num_packets_outstanding_ + kPktCompleteTolerance <= actual_packets_outstanding && target_duration_outstanding + kPktCompleteToleranceDuration <= actual_duration_outstanding) { printf( "\n? %4lu packets outstanding (%ld msec); expected %4u (%ld msec); total elapsed %f sec: " "are we sending faster than completing?\n\n", actual_packets_outstanding, (actual_duration_outstanding / ZX_MSEC(1)).get(), target_num_packets_outstanding_, (target_duration_outstanding / ZX_MSEC(1)).get(), elapsed_time_sec); return false; } return true; } // Calculate the next SendPacket ref_time and mono_time, and Post to our async::TaskClosureMethod void MediaApp::ScheduleNextSendPacket() { CLI_CHECK(online_, "Should only call NextSendPacket in online mode"); CLI_CHECK(online_send_packet_ref_period_ > zx::duration(0), "SendPacket period is not set"); if (num_packets_sent_ >= num_packets_to_send_) { return; } target_online_send_packet_ref_time_ = target_online_send_first_packet_ref_time_ + (online_send_packet_ref_period_ * num_packets_sent_); auto mono_time_result = audio::clock::MonotonicTimeFromReferenceTime( reference_clock_, target_online_send_packet_ref_time_); CLI_CHECK(mono_time_result.is_ok(), "Could not convert ref_time to mono_time"); auto target_mono_time = mono_time_result.take_value(); if (verbose_) { zx::time ref_now; auto status = reference_clock_.read(ref_now.get_address()); if (status != ZX_OK) { Shutdown(); CLI_CHECK_OK(status, "zx::clock::read failed during Play callback"); } auto mono_time_result = audio::clock::MonotonicTimeFromReferenceTime(reference_clock_, ref_now); CLI_CHECK(mono_time_result.is_ok(), "Could not convert ref_time to mono_time"); auto mono_now = mono_time_result.take_value(); auto target_ref_str = RefTimeStrFromZxTime(target_online_send_packet_ref_time_); auto ref_now_str = RefTimeMsStrFromZxTime(ref_now); auto mono_now_str = RefTimeMsStrFromZxTime(mono_now); printf("Scheduling packet %4lu (reference %s) : ref_now %s : mono_now %s\n", num_packets_sent_, target_ref_str.c_str(), ref_now_str.c_str(), mono_now_str.c_str()); } zx_status_t status = online_send_packet_timer_.PostForTime(audio_renderer_.dispatcher(), target_mono_time); if (status != ZX_OK) { Shutdown(); CLI_CHECK_OK(status, "Failed to schedule SendPacket"); } } void MediaApp::OnSendPacketTimer() { SendPacket(); ScheduleNextSendPacket(); } // Submit a packet, incrementing our count of packets sent. When it returns: // a. if there are more packets to send, create and send the next packet; // b. if all expected packets have completed, begin closing down the system. void MediaApp::SendPacket() { CLI_CHECK(CheckPayloadSpace(), "Insufficient payload buffer space -- synchronization issue?"); auto packet = CreateAudioPacket(num_packets_sent_); GenerateAudioForPacket(packet, num_packets_sent_); if (file_name_) { CLI_CHECK(packet.stream_packet.payload_size <= std::numeric_limits<uint32_t>::max(), "Packet payload too large"); CLI_CHECK(wav_writer_.Write(reinterpret_cast<char*>(packet.vmo->start()) + packet.stream_packet.payload_offset, static_cast<uint32_t>(packet.stream_packet.payload_size)) || Shutdown(), "WavWriter::Write() failed"); } if (verbose_) { zx::time ref_now; auto status = reference_clock_.read(ref_now.get_address()); CLI_CHECK((status == ZX_OK) || Shutdown(), "zx::clock::read failed during SendPacket(): " << status); auto mono_time_result = audio::clock::MonotonicTimeFromReferenceTime(reference_clock_, ref_now); CLI_CHECK(mono_time_result.is_ok(), "Could not convert ref_time to mono_time"); auto mono_now = mono_time_result.take_value(); auto pts_str = RefTimeStrFromZxTime(zx::time{packet.stream_packet.pts}); auto ref_now_str = RefTimeMsStrFromZxTime(ref_now); auto mono_now_str = RefTimeMsStrFromZxTime(mono_now); printf(" Sending: packet %4lu (media pts %s) : ref_now %s : mono_now %s\n", num_packets_sent_, pts_str.c_str(), ref_now_str.c_str(), mono_now_str.c_str()); } ++num_packets_sent_; uint64_t frames_completed = packet.stream_packet.payload_size / frame_size_; audio_renderer_->SendPacket( packet.stream_packet, [this, frames_completed]() { OnSendPacketComplete(frames_completed); }); } void MediaApp::OnSendPacketComplete(uint64_t frames_completed) { num_frames_completed_ += frames_completed; if (verbose_) { zx::time ref_now; auto status = reference_clock_.read(ref_now.get_address()); CLI_CHECK(status == ZX_OK || Shutdown(), "zx::clock::read failed during OnSendPacketComplete(): " << status); auto mono_time_result = audio::clock::MonotonicTimeFromReferenceTime(reference_clock_, ref_now); CLI_CHECK(mono_time_result.is_ok(), "Could not convert ref_time to mono_time"); auto mono_now = mono_time_result.take_value(); auto ref_now_str = RefTimeMsStrFromZxTime(ref_now); auto mono_now_str = RefTimeMsStrFromZxTime(mono_now); printf("Completed: packet %4lu (%5lu frames, up to %8lu ) : ref_now %s : mono_now %s\n", num_packets_completed_, frames_completed, num_frames_completed_, ref_now_str.c_str(), mono_now_str.c_str()); } ++num_packets_completed_; CLI_CHECK(num_packets_completed_ <= num_packets_to_send_, "packets_completed cannot exceed packets_to_send"); if (num_packets_completed_ >= num_packets_to_send_) { Shutdown(); } else if (num_packets_sent_ < num_packets_to_send_ && !online_) { SendPacket(); } } // Enable audio renderer callbacks void MediaApp::SetAudioRendererEvents() { audio_renderer_.set_error_handler([this](zx_status_t status) { CLI_CHECK(Shutdown(), "Client connection to fuchsia.media.AudioRenderer failed: " << status); }); audio_renderer_.events().OnMinLeadTimeChanged = [this](int64_t min_lead_time_nsec) { min_lead_time_ = zx::duration(min_lead_time_nsec); if (verbose_) { printf("- OnMinLeadTimeChanged: %lu at %lu: %s to start playback (%s ref clock)\n", min_lead_time_nsec, zx::clock::get_monotonic().get(), (min_lead_time_ >= kRealDeviceMinLeadTime ? "sufficient" : "insufficient"), (reference_clock_.is_valid() ? "Received" : "Awaiting")); } if (min_lead_time_ >= kRealDeviceMinLeadTime && reference_clock_.is_valid() && !playing()) { Play(); } }; audio_renderer_->EnableMinLeadTimeEvents(true); } // Unmap memory, quit message loop (FIDL interfaces auto-delete upon ~MediaApp). bool MediaApp::Shutdown() { online_send_packet_timer_.Cancel(); gain_control_.Unbind(); usage_volume_control_.Unbind(); audio_renderer_.Unbind(); if (wav_writer_initialized_) { CLI_CHECK(wav_writer_.Close(), "WavWriter::Close() failed"); } payload_buffers_.clear(); quit_callback_(); return false; } } // namespace media::tools
40.562619
100
0.693448
DamieFC
a0e686a58646629be15d60999450f436769a6059
559
cc
C++
poj/1/1458.cc
eagletmt/procon
adbe503eb3c1bbcc1538b2ee8988aa353937e8d4
[ "MIT" ]
1
2015-04-17T09:54:23.000Z
2015-04-17T09:54:23.000Z
poj/1/1458.cc
eagletmt/procon
adbe503eb3c1bbcc1538b2ee8988aa353937e8d4
[ "MIT" ]
null
null
null
poj/1/1458.cc
eagletmt/procon
adbe503eb3c1bbcc1538b2ee8988aa353937e8d4
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; int main(void) { string a, b; while (cin >> a >> b) { const int N = a.size(), M = b.size(); vector<vector<int> > lcs(N+1, vector<int>(M+1, 0)); for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) { if (a[i-1] == b[j-1]) { lcs[i][j] = max(lcs[i-1][j-1]+1, max(lcs[i-1][j], lcs[i][j-1])); } else { lcs[i][j] = max(lcs[i-1][j-1], max(lcs[i-1][j], lcs[i][j-1])); } } } cout << lcs[N][M] << endl; } return 0; }
22.36
74
0.431127
eagletmt
a0eaf0cf00462bb81d34dbe82e6c656d84fe1ce3
3,448
hpp
C++
include/rectojump/global/config.hpp
Malekblubb/rectojump
66c04e9a081bd1b830205bb0c515a42eeb4befb6
[ "MIT" ]
null
null
null
include/rectojump/global/config.hpp
Malekblubb/rectojump
66c04e9a081bd1b830205bb0c515a42eeb4befb6
[ "MIT" ]
null
null
null
include/rectojump/global/config.hpp
Malekblubb/rectojump
66c04e9a081bd1b830205bb0c515a42eeb4befb6
[ "MIT" ]
null
null
null
// // Copyright (c) 2013-2021 Christoph Malek // See LICENSE for more information. // #ifndef RJ_GLOBAL_CONFIG_HPP #define RJ_GLOBAL_CONFIG_HPP #include "common.hpp" #include "config_parser.hpp" #include "errors.hpp" #include <mlk/filesystem/fs_handle.h> #include <mlk/signals_slots/slot.h> namespace rj { class config { mlk::fs::fs_handle<mlk::fs::fs_type::file> m_file; config_entry_vec m_entrys; public: mlk::slot<> on_setting_changed; config(const std::string& path) : m_file{path} { this->init(); } ~config() { this->write_config(); } static config& get() { static config c{"config"}; return c; } template <typename T> T get_entry(const std::string& key) { auto iter{mlk::cnt::find_in_if( [&key](const std::pair<std::string, std::string>& p) { return p.first == key; }, m_entrys)}; if(iter == std::end(m_entrys)) return T{}; return mlk::type_utl::to_type<T>(iter->second); } template <typename T> void set_entry(const std::string& key, const T& value) { auto iter{mlk::cnt::find_in_if( [&key](const std::pair<std::string, std::string>& p) { return p.first == key; }, m_entrys)}; if(iter == std::end(m_entrys)) return; iter->second = std::to_string(value); } private: void init() { this->make_default(); if(!m_file.exists()) { if(!m_file.create()) { mlk::lerr(errors::io_create_file) << "filename=" << m_file.path(); return; } this->write_config(); return; } this->read_config(); } void make_default() { m_entrys.emplace_back("window_width", "1280"); m_entrys.emplace_back("window_height", "720"); m_entrys.emplace_back("fullscreen", "0"); m_entrys.emplace_back("sound_volume", "10"); m_entrys.emplace_back("color_light", "#f15ede"); m_entrys.emplace_back("color_dark", "#bf35ad"); m_entrys.emplace_back("color_default_dark", "#797979"); m_entrys.emplace_back("color_default_light", "#e3e3e3"); m_entrys.emplace_back("editor_scroll_step", "20"); m_entrys.emplace_back("editor_settings_expanded", "true"); m_entrys.emplace_back("main_menu_effects", "1"); } void write_config() noexcept { m_file.reopen(std::ios::out | std::ios::trunc); for(auto& a : m_entrys) m_file.write_line(a.first + "=" + a.second); m_file.close(); } void read_config() noexcept { m_file.reopen(std::ios::in); std::vector<std::string> lines; std::string buf; while(m_file.read_line(buf)) if(!buf.empty()) lines.push_back(buf); // file is empty if(lines.size() < 1) { this->write_config(); return; } // parse content config_parser parser{lines}; if(!parser.empty()) this->validate_entrys(parser.get_entrys()); } void validate_entrys(const config_entry_vec& entrys) noexcept { for(auto& a : entrys) { auto iter{mlk::cnt::find_in_if( [&](const std::pair<std::string, std::string>& p) { return p.first == a.first; }, m_entrys)}; if(iter != std::end(m_entrys)) *iter = a; } } }; template <> inline void config::set_entry<std::string>(const std::string& key, const std::string& value) { auto iter{mlk::cnt::find_in_if( [&key](const std::pair<std::string, std::string>& p) { return p.first == key; }, m_entrys)}; if(iter == std::end(m_entrys)) return; iter->second = value; } }// namespace rj #endif// RJ_GLOBAL_CONFIG_HPP
23.14094
71
0.634861
Malekblubb
a0eb22cf8560217ec185b491acacf29bb93326e3
427
hpp
C++
include/RED4ext/Scripting/Natives/Generated/PSODescDepthStencilModeStencilOpMode.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
42
2020-12-25T08:33:00.000Z
2022-03-22T14:47:07.000Z
include/RED4ext/Scripting/Natives/Generated/PSODescDepthStencilModeStencilOpMode.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
38
2020-12-28T22:36:06.000Z
2022-02-16T11:25:47.000Z
include/RED4ext/Scripting/Natives/Generated/PSODescDepthStencilModeStencilOpMode.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> namespace RED4ext { enum class PSODescDepthStencilModeStencilOpMode : uint8_t { STENCILOP_Keep = 0, STENCILOP_Zero = 1, STENCILOP_Replace = 2, STENCILOP_IncreaseSaturate = 3, STENCILOP_DecreaseSaturate = 4, STENCILOP_Invert = 5, STENCILOP_Increase = 6, STENCILOP_Decrease = 7, }; } // namespace RED4ext
21.35
57
0.725995
jackhumbert
a0f04a4e522a57fa04e06ca4c2d2cb329a712c54
2,369
cpp
C++
examples/math_expression/main.cpp
FrancoisChabot/abulafia
4aeefd8d388d68994f9d73bb0f586517737a5174
[ "BSL-1.0" ]
42
2017-09-21T16:51:12.000Z
2020-03-12T09:44:32.000Z
examples/math_expression/main.cpp
FrancoisChabot/abulafia
4aeefd8d388d68994f9d73bb0f586517737a5174
[ "BSL-1.0" ]
32
2017-09-21T06:31:08.000Z
2017-10-20T00:52:58.000Z
examples/math_expression/main.cpp
FrancoisChabot/abulafia
4aeefd8d388d68994f9d73bb0f586517737a5174
[ "BSL-1.0" ]
3
2018-10-30T11:29:18.000Z
2019-07-18T08:19:51.000Z
// Copyright 2017 Francois Chabot // (francois.chabot.dev@gmail.com) // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE or copy at // http://www.boost.org/LICENSE_1_0.txt) #include "abulafia/abulafia.h" #include <iostream> // This simple example shows how to build a simple operator precedence parser // using abulafia. // This parser will evaluate the expression as its being parsed, storing the // result directly in the dst. Building an AST is a very similar process, which // you can see in (insert example reference here) auto make_expr_pattern(abu::RecurMemoryPool& pool) { // Simply assign a bound dst's value to the child parser's result auto assign = [](int v, auto p) -> void { p.bound_dst.get() = v; }; // create a Binary operation, using the bound dst's current value // as lhs, the child's first value as operator // and the child's second value as rhs auto make_binop = [](std::tuple<char, int> v, auto p) -> void { auto lhs = p.bound_dst.get(); auto rhs = std::get<1>(v); switch (std::get<0>(v)) { case '+': p.bound_dst.get() = (int)lhs + rhs; break; case '-': p.bound_dst.get() = (int)lhs - rhs; break; case '*': p.bound_dst.get() = (int)lhs * rhs; break; case '/': p.bound_dst.get() = (int)lhs / rhs; break; } }; abu::Recur<struct expr_t, int> expr(pool); auto primary = abu::int_ | ('(' >> expr >> ')'); auto muldiv = abu::bind_dst(primary[assign] >> *(abu::char_("*/") >> primary)[make_binop]); auto addsub = abu::bind_dst(muldiv[assign] >> *(abu::char_("+-") >> muldiv)[make_binop]); ABU_Recur_define(expr, expr_t, addsub); return abu::apply_skipper(expr, abu::lit(' ')); } int main(int, const char* []) { abu::RecurMemoryPool pool; auto pattern = make_expr_pattern(pool); while (1) { std::cout << "enter a mathematical expression:\n"; std::string expr; std::getline(std::cin, expr); if (expr.empty()) { break; } int dst = 0; auto status = abu::parse(expr.begin(), expr.end(), pattern, dst); if (abu::Result::SUCCESS == status) { std::cout << dst << "\n"; } else { std::cout << "expression parse failure\n"; } } return 0; }
29.246914
79
0.597721
FrancoisChabot
a0f169a733654af4db90d342132b13ee77371fe9
3,434
cc
C++
extensions/shell/browser/system_logs/shell_system_logs_fetcher_unittest.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
extensions/shell/browser/system_logs/shell_system_logs_fetcher_unittest.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
extensions/shell/browser/system_logs/shell_system_logs_fetcher_unittest.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "extensions/shell/browser/system_logs/shell_system_logs_fetcher.h" #include <memory> #include <string> #include <vector> #include "base/memory/ref_counted.h" #include "base/run_loop.h" #include "base/strings/string_util.h" #include "base/values.h" #include "components/feedback/system_logs/system_logs_fetcher.h" #include "components/feedback/system_logs/system_logs_source.h" #include "content/public/browser/browser_context.h" #include "extensions/browser/extension_function.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extensions_test.h" #include "extensions/common/extension.h" #include "extensions/common/extension_builder.h" #include "extensions/common/manifest.h" #include "extensions/common/value_builder.h" namespace extensions { class ShellSystemLogsFetcherTest : public ExtensionsTest { public: ShellSystemLogsFetcherTest() = default; ~ShellSystemLogsFetcherTest() override = default; scoped_refptr<Extension> BuildExtension(const std::string& name, const std::string& version, const std::string& id) { return ExtensionBuilder(name) .SetManifestKey("version", version) .SetID(id) .Build(); } void OnSystemLogsResponse( std::unique_ptr<system_logs::SystemLogsResponse> response) { response_ = std::move(response); wait_for_logs_response_run_loop_.Quit(); } const system_logs::SystemLogsResponse* response() const { return response_.get(); } protected: base::RunLoop wait_for_logs_response_run_loop_; private: std::unique_ptr<system_logs::SystemLogsResponse> response_; }; // Tests that basic log source includes version tags and extensions. TEST_F(ShellSystemLogsFetcherTest, TestLogSources) { ExtensionRegistry* registry = ExtensionRegistry::Get(browser_context()); EXPECT_TRUE(registry); std::vector<scoped_refptr<Extension>> extensions{ BuildExtension("My First Extension", "1.1", std::string(32, 'a')), BuildExtension("My Second Extension", "1.2", std::string(32, 'b'))}; for (const scoped_refptr<Extension>& extension : extensions) registry->AddEnabled(extension); system_logs::SystemLogsFetcher* fetcher = system_logs::BuildShellSystemLogsFetcher(browser_context()); fetcher->Fetch(base::Bind(&ShellSystemLogsFetcherTest::OnSystemLogsResponse, base::Unretained(this))); wait_for_logs_response_run_loop_.Run(); ASSERT_TRUE(response()); EXPECT_LT(0u, response()->at("APPSHELL VERSION").size()); EXPECT_LT(0u, response()->at("OS VERSION").size()); const base::StringPiece fmt = "$1 : $2 : version $3\n"; std::string expected_extensions = ""; for (const scoped_refptr<Extension>& extension : extensions) { std::string version_mangled; base::ReplaceChars(extension->VersionString(), ".", "_", &version_mangled); expected_extensions += base::ReplaceStringPlaceholders( fmt, {extension->id(), extension->name(), version_mangled}, nullptr); } EXPECT_EQ(expected_extensions, response()->at("extensions")); for (const scoped_refptr<Extension>& extension : extensions) registry->RemoveEnabled(extension->id()); } } // namespace extensions
35.770833
79
0.723937
zipated
a0f1bc7fe907c3e1426f734767b4b6ff95d43422
1,133
cpp
C++
vijos/p1635.cpp
huanghongxun/ACM
b7595bbe6c0d82ceb271e81fca3e787dc4060a55
[ "Unlicense" ]
3
2018-06-05T13:57:13.000Z
2020-08-05T14:19:02.000Z
vijos/p1635.cpp
huanghongxun/ACM
b7595bbe6c0d82ceb271e81fca3e787dc4060a55
[ "Unlicense" ]
null
null
null
vijos/p1635.cpp
huanghongxun/ACM
b7595bbe6c0d82ceb271e81fca3e787dc4060a55
[ "Unlicense" ]
null
null
null
#include <iostream> #include <queue> #include <cstring> #define N 2005 using namespace std; struct Edge { int to, rp; Edge(){} Edge(int t, int r) { to = t; rp = r; } }; Edge graph[N][N]; int graphs[N]; int main() { int a, b, r, n; cin.sync_with_stdio(false); cin>>n; memset(graphs, 0, sizeof(graphs)); for(a = 1; a <= n; a++) for(b = 1; b <= n; b++) { cin>>r; if(r != 0) graph[a][graphs[a]++] = Edge(b, r); } int dist[N]; bool vis[N]; int pre[N]; memset(pre, -1, sizeof(pre)); memset(dist, 127, sizeof(dist)); memset(vis, 0, sizeof(vis)); queue<int> q; q.push(1); dist[1] = 0; vis[1] = 1; while(!q.empty()) { int u = q.front(); q.pop(); for(int i = 0; i < graphs[u]; i++) { if(dist[graph[u][i].to] > dist[u] + graph[u][i].rp) { dist[graph[u][i].to] = dist[u] + graph[u][i].rp; pre[graph[u][i].to] = u; if(!vis[graph[u][i].to]) { vis[graph[u][i].to] = 1; q.push(graph[u][i].to); } } } } for(r = n, a = 0; r != -1; r = pre[r], a++) graphs[a] = r; for(r = a - 1; r >= 0; r--) cout<<graph[r]<<' '; cout<<endl<<dist[n]; return 0; }
16.185714
54
0.496028
huanghongxun