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
a5eda7665398f3f945033b325a5aa8fcb2a15ea4
351
cpp
C++
Demo_04/main.cpp
vitahlin/VitahCmake
a5360ca9ce548fa16f40e98e2a7985d5fd6978cf
[ "MIT" ]
null
null
null
Demo_04/main.cpp
vitahlin/VitahCmake
a5360ca9ce548fa16f40e98e2a7985d5fd6978cf
[ "MIT" ]
null
null
null
Demo_04/main.cpp
vitahlin/VitahCmake
a5360ca9ce548fa16f40e98e2a7985d5fd6978cf
[ "MIT" ]
null
null
null
#include <iostream> #include "doubleNum.h" #include "powNum.h" using namespace std; #define MAX_NUM 4 int main(int argc, char *argv[]) { cout << "This is Demo_4 " << endl; cout << "Max Num is " << MAX_NUM << endl; cout << "Double is " << doubleNum(MAX_NUM) << endl; cout << "Power is " << powNum(MAX_NUM, 2) << endl; return 0; }
23.4
55
0.598291
vitahlin
a5edc3d70372b7962417edba21fe1dc2defc4ad1
134
cpp
C++
QtDemoApp/QtDemoApp.cpp
F474M0R64N4/license-system
982f1297948353b58d736009a08c697c3e15a41b
[ "MIT" ]
4
2020-10-13T19:57:16.000Z
2021-09-08T11:57:12.000Z
QtDemoApp/QtDemoApp.cpp
F474M0R64N4/license-system
982f1297948353b58d736009a08c697c3e15a41b
[ "MIT" ]
null
null
null
QtDemoApp/QtDemoApp.cpp
F474M0R64N4/license-system
982f1297948353b58d736009a08c697c3e15a41b
[ "MIT" ]
null
null
null
#include "QtDemoApp.h" #include "stdafx.h" QtDemoApp::QtDemoApp(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); }
14.888889
37
0.686567
F474M0R64N4
a5ee24b372e1247559f7273726575e2525659796
1,300
hpp
C++
source/common.hpp
ThatGuyMike7/masonc
43a3a69cd64f52fda8a629360c52a222549d6368
[ "BSL-1.0" ]
3
2020-08-10T13:37:48.000Z
2021-07-06T10:14:39.000Z
source/common.hpp
ThatGuyMike7/masonc
43a3a69cd64f52fda8a629360c52a222549d6368
[ "BSL-1.0" ]
null
null
null
source/common.hpp
ThatGuyMike7/masonc
43a3a69cd64f52fda8a629360c52a222549d6368
[ "BSL-1.0" ]
null
null
null
#ifndef MASONC_COMMON_HPP #define MASONC_COMMON_HPP #include <iostream> #include <cstdint> #include <cstdlib> namespace masonc { using s8 = int8_t; using s16 = int16_t; using s32 = int32_t; using s64 = int64_t; using u8 = uint8_t; using u16 = uint16_t; using u32 = uint32_t; using u64 = uint64_t; using f32 = float; using f64 = double; void assume(bool statement, const char* msg = "", int code = -1); /* template <typename T> class result { public: result() : is_ok(false) { } result(T value) : _value(value), is_ok(true) { } ~result() { if (is_ok) _value.~T(); } explicit operator bool() const { return is_ok; } T value() { assume(is_ok, "\"is_ok\" in std::optional<T> is false"); return _value; } private: union { T _value; }; bool is_ok; }; template <typename T> class _result { public: _result() : is_ok(false) { } _result(T _value) : is_ok(true), _value(_value) { } //operator bool&() { return is_ok; } explicit operator bool() const { return is_ok; } T value() { assume(is_ok, "\"is_ok\" in std::optional<T> is false"); return _value; } private: T _value; bool is_ok; }; */ } #endif
18.055556
68
0.572308
ThatGuyMike7
a5f01c982bcd6aee3293a2863608db335b73fb03
8,146
cpp
C++
src/ioManager.cpp
maxwillf/Huffman
8de0e08050b5ada24c0114b8832fca192f8abce7
[ "MIT" ]
null
null
null
src/ioManager.cpp
maxwillf/Huffman
8de0e08050b5ada24c0114b8832fca192f8abce7
[ "MIT" ]
null
null
null
src/ioManager.cpp
maxwillf/Huffman
8de0e08050b5ada24c0114b8832fca192f8abce7
[ "MIT" ]
null
null
null
#include "../include/ioManager.h" int *IOManager::countFrequencies(std::ifstream &input) { int *ascii = new int[128]; char c = '\0'; while (input.get(c)) { if ((int) c == 10) continue; ascii[(int) c] +=1; } for (int i = 0; i < 128; ++i) { if (ascii[i] != 0) { c = i; std::cout << c << " " << ascii[i] << std::endl; } } return ascii; } void IOManager::readFile(std::ifstream &input) { int *ascii = countFrequencies(input); std::vector<Node*> orderedNodes; for (int i = 0; i < 128; ++i) { if (ascii[i] != 0) { char character = i; Node *node = new Node(ascii[i], character); insertOrd(orderedNodes, node, pred); } } insertOrd(orderedNodes, new Node(1, '$'), pred); tree = new HuffmanTree(orderedNodes); tree->printTree(); tree->fillMap(); delete [] ascii; } std::string IOManager::charBitsToString(unsigned char c) { unsigned char mask = 1; std::string bits = ""; while(byteIndex != 8){ if( (c & mask) == mask){ bits += '1'; } else { bits += '0'; } byteIndex++; c = c >> 1; } byteIndex = 0; std::reverse(bits.begin(),bits.end()); return bits; } /* TODO: get the string generated by the preOrder() method from the tree, compact it like it was done with the text in the compact() method and insert it in the beginning of the file, using '$' or some other char as the delimiter between where the tree starts and where the text starts */ void IOManager::encodeTree(std::ofstream &output) { std::string treeString = tree->preOrder(); std::string encodedString = ""; std::istringstream input(treeString); std::cout << tree->preOrder() << std::endl; char c = '\0'; while (input.get(c)) { if (c != '0' and c != '1') encodedString += charBitsToString(c); else encodedString += c; } std::cout << encodedString << std::endl; for (size_t i = 0; i < encodedString.size(); ++i) { if (encodedString[i] == '1') { c = c << 1; c += 1; } else { c = c << 1; } if(i + 1 == encodedString.size()) { while (++i % 8 != 0) c = c << 1; output << c; } else if ((i != 0 and (i + 1) % 8 == 0) or (i + 1) == encodedString.size()) { output << c; c = '\0'; } } output << (char) 255; } void IOManager::compact(std::ifstream &input, std::ofstream &output) { encodeTree(output); std::cout << tree->preOrder() << std::endl; // reset file stream input.clear(); input.seekg(0, std::ios::beg); char c = '\0'; std::string encodedString = ""; while (input.get(c)) encodedString += tree->findLetterPath(c); std::cout << encodedString << std::endl; c = '\0'; for (size_t i = 0; i < encodedString.size(); ++i) { if (encodedString[i] == '1') { c = c << 1; c += 1; } else { c = c << 1; } if(i+1 == encodedString.size()) { int it = encodedString.size() % 8; while(it++ != 8){ c = c << 1; } output << c; } else if ((i != 0 and (i + 1) % 8 == 0) or (i + 1) == encodedString.size()) { output << c; c = '\0'; } } } void IOManager::binaryToString(std::ifstream &input) { unsigned char mask = 0b10000000; unsigned char delim = (char) 255; while(input.get(byte)){ if((byte & delim) == delim){ std::cout << "broke free" << std::endl; break; } for (int i = 0; i < 8; ++i) { if( (byte & mask) == 0){ byte = byte << 1; decodingString += '0'; } else { byte = byte << 1; decodingString += '1'; } } } std::cout << decodingString << std::endl; std::vector<std::string> StringNodes; stringToVec(decodingString.begin(),StringNodes); for (auto i : StringNodes) { std::cout << i << std::endl; } std::cout << StringNodes.size() << std::endl; byteIndex = 0; delete tree; this->tree = new HuffmanTree(constructTree(StringNodes)); std::cout << tree->preOrder() << std::endl; } Node * IOManager::constructTree(std::vector<std::string> & vec) { if(byteIndex < vec.size()){ if(vec[byteIndex] == "0"){ byteIndex++; Node * left = constructTree(vec); byteIndex++; Node * right = constructTree(vec); return new Node(0,left,right); } else return new Node(0,stringToChar(vec[byteIndex])); } return nullptr; } char IOManager::stringToChar(std::string str) { unsigned char byte = 0; for (auto i = str.begin(); i < str.end(); ++i) { if(*i == '0'){ byte = byte << 1; } else { byte = byte << 1; byte += 1; } } //std::cout << byte << std::endl; return byte; } void IOManager::stringToVec(std::string::iterator curr_symbol, std::vector<std::string> & vec) { if(curr_symbol != decodingString.end()){ if(*curr_symbol == '0'){ vec.push_back("0"); stringToVec(++curr_symbol,vec); } else { curr_symbol++; int beginIndex = std::distance(decodingString.begin(),curr_symbol); std::string letter = decodingString.substr(beginIndex,8); vec.push_back(letter); stringToVec(curr_symbol+8,vec); } } } void IOManager::decodeTree(std::ifstream &input, std::ofstream &output){ binaryToString(input); readCompressed(input, output); /* delete tree; tree = new HuffmanTree(decodeTreeR(input)); std::cout << tree->preOrder();*/ } void IOManager::readCompressed(std::ifstream & input, std::ofstream &output) { unsigned char mask = 0x80; std::string file; char temp = '\0'; while(input.get(byte)){ // std::cout << byte << std::endl; for (int i = 0; i < 8; ++i) { if( (byte & mask) == mask){ //std::cout << "1"; temp = tree->searchByBit(mask); } else { //std::cout << "0" ; temp = tree->searchByBit(0); } if(temp == '$'){ break; } if (temp != (char) 255) { file += temp; } byte = byte << 1; } } output << file; } Node* IOManager::decodeTreeR(std::ifstream &input){ if(byteIndex % 8 == 0){ input.get(byte); //std::cout << "urgh" << byte << std::endl; if(byte == '\0'){ //std::cout << "null " << byte << std::endl; return nullptr; } byteIndex = 0; } unsigned char mask = 0b10000000; if( (byte & mask) == 0){ byte = byte << 1; byteIndex++; // std::cout << "ue" << std::endl; return new Node(0,decodeTreeR(input),decodeTreeR(input)); } else { nodeChar = 0; while(currentNodeIndex < 8){ if( (byte & mask) == mask){ nodeChar += 1; nodeChar = nodeChar << 1; byte = byte << 1; byteIndex++; currentNodeIndex++; } else { nodeChar = nodeChar << 1; byte = byte << 1; byteIndex++; currentNodeIndex++; } if(byteIndex % 8 == 0){ input.get(byte); if(byte == '\0'){ return nullptr; } byteIndex = 0; } } currentNodeIndex = 0; return new Node(0,nodeChar); } }
23.274286
94
0.465873
maxwillf
a5f0640634f5d138d8050e6a60263d9f048cb94f
304
cpp
C++
TimerThread.cpp
xuleilx/TimerThread
74e0759f879597ac2e9a48509af72ab12bb493d8
[ "MIT" ]
null
null
null
TimerThread.cpp
xuleilx/TimerThread
74e0759f879597ac2e9a48509af72ab12bb493d8
[ "MIT" ]
null
null
null
TimerThread.cpp
xuleilx/TimerThread
74e0759f879597ac2e9a48509af72ab12bb493d8
[ "MIT" ]
null
null
null
#include "TimerThread.h" TimerThread::TimerThread(int val, int interval, Callback cb) :_timer(val, interval, std::move(cb)), _thread(std::bind(&Timer::start, &_timer)) { } void TimerThread::start() { _thread.start(); } void TimerThread::stop() { _timer.stop(); _thread.join(); }
15.2
60
0.644737
xuleilx
a5f5c2c204ac6234895f3d98507208f20884c11c
459
cc
C++
chrome/browser/policy/cloud_policy_provider.cc
gavinp/chromium
681563ea0f892a051f4ef3d5e53438e0bb7d2261
[ "BSD-3-Clause" ]
1
2016-03-10T09:13:57.000Z
2016-03-10T09:13:57.000Z
chrome/browser/policy/cloud_policy_provider.cc
gavinp/chromium
681563ea0f892a051f4ef3d5e53438e0bb7d2261
[ "BSD-3-Clause" ]
1
2022-03-13T08:39:05.000Z
2022-03-13T08:39:05.000Z
chrome/browser/policy/cloud_policy_provider.cc
gavinp/chromium
681563ea0f892a051f4ef3d5e53438e0bb7d2261
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2011 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 "chrome/browser/policy/cloud_policy_provider.h" namespace policy { CloudPolicyProvider::CloudPolicyProvider( const PolicyDefinitionList* policy_list) : ConfigurationPolicyProvider(policy_list) { } CloudPolicyProvider::~CloudPolicyProvider() { } } // namespace policy
25.5
73
0.771242
gavinp
a5f9f8ff5e5826ab9ff5edb39e4173a69d49f7d6
3,638
hxx
C++
private/inet/mshtml/dead/site/dfrm/propchg.hxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/inet/mshtml/dead/site/dfrm/propchg.hxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/inet/mshtml/dead/site/dfrm/propchg.hxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
//+--------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1994 // // File: propchg.hxx // // Contents: defines the propnotification holder class // // Classes: CPropertyChange // // Maintained by Frankman // //---------------------------------------------------------------------------- #ifndef _PROPCHG_HXX_ # define _PROPCHG_HXX_ 1 class CPropertyChange { public: // destruction and initialisation CPropertyChange(); ~CPropertyChange(); virtual void Passivate(void); public: // operations for manipulating members HRESULT AddDispID(DISPID dispid); BOOL IsDirty(void) { return ((BOOL) (_DispidArray.Size() || _fDataSourceModified || _fRegenerate || _fCreateToFit )); } BOOL IsTemplateModified(void) {return (BOOL) _fTemplateModified; } void SetDataSourceModified(BOOL f) { _fDataSourceModified = f;}; BOOL IsDataSourceModified(void) {return (BOOL) _fDataSourceModified;}; void SetRegenerate(BOOL f) { _fRegenerate = f; }; BOOL NeedRegenerate(void) { return (BOOL) _fRegenerate;}; void SetCreateToFit(BOOL f) { _fCreateToFit = f; }; BOOL NeedCreateToFit(void) { return (BOOL) _fCreateToFit;}; void SetLinkInfoChanged(BOOL f) { _fLinkInfoChanged = f; }; BOOL IsLinkInfoChanged(void) { return (BOOL) _fLinkInfoChanged; }; void SetNeedToScroll (BOOL f) { _fScroll = f; }; BOOL NeedToScroll (void) { return (BOOL) _fScroll;}; void SetNeedToInvalidate (BOOL f) { _fInvalidate = f; }; BOOL NeedToInvalidate (void) { return (BOOL) _fInvalidate;}; void SetNeedGridResize(BOOL f) { _fNeedGridResize = f; } BOOL NeedGridResize (void) { return (BOOL) _fNeedGridResize ;}; public: // enum operations virtual void EnumReset(void); BOOL EnumNextDispID(DISPID *pDispid); protected: // property change notification members unsigned _fTemplateModified :1; // indicates that someone added/deleted controls unsigned _fDataSourceModified :1;// indicates that someone modified the datasource unsigned _fRegenerate:1; // indicates regeneration is needed unsigned _fCreateToFit:1; // indicates create to fit is needed unsigned _fLinkInfoChanged:1; // indicates that either linkmaster or linkchild changed unsigned _fScroll:1; // indicates that OnScroll is needed. unsigned _fInvalidate:1; // indicates that Invalidate is needed. unsigned _fNeedGridResize:1; // indication for the root for pass gridresize flags CDataAry<DISPID> _DispidArray; // array of DISPIDs of the props that changed int _iCurrentDispid; }; class CControlPropertyChange : public CPropertyChange { public: // destruction and initialisation CControlPropertyChange(); virtual void Passivate(void); public: // operations for manipulating members HRESULT AddDispIDAndVariant(DISPID dispid, VARIANT *pvar); public: virtual void EnumReset(void); BOOL EnumNextVariant(VARIANT **ppvar); protected: CPtrAry<VARIANT *> _VariantArray; // array of variants, if the control does not provide IControlInstance int _iCurrentVariant; }; #endif
31.912281
115
0.600605
King0987654
a5fbf18ca957270531a4f7c6926d659ace12a737
530
cpp
C++
components/common/tests/strlib/regexp3.cpp
untgames/funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
7
2016-03-30T17:00:39.000Z
2017-03-27T16:04:04.000Z
components/common/tests/strlib/regexp3.cpp
untgames/Funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
4
2017-11-21T11:25:49.000Z
2018-09-20T17:59:27.000Z
components/common/tests/strlib/regexp3.cpp
untgames/Funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
4
2016-11-29T15:18:40.000Z
2017-03-27T16:04:08.000Z
#include <stdio.h> #include <common/strlib.h> using namespace stl; using namespace common; int main () { printf ("Results of regexp3_test:\n"); const char* pattern = "dynamic *\\( *([[:digit:]]*) *, *([[:digit:]]*) *, *'(.*)' *\\).*"; const char* str = "dynamic (256 , 512,'test_query')???"; StringArray tokens = parse (str,pattern); printf ("parse '%s' (pattern='%s') on %lu tokens:\n", str,pattern,tokens.Size ()); for (size_t i=0;i<tokens.Size ();i++) printf (" '%s'\n",tokens [i]); return 0; }
23.043478
92
0.567925
untgames
a5ff2dc7d7d2edf3377a16a2dd0dea6bb814a1bd
1,223
cpp
C++
src/Solver2.cpp
SanteriHetekivi/JudgmentSolver
ede2c336cbed8e595d6cf296175181725cbfab61
[ "Apache-2.0" ]
null
null
null
src/Solver2.cpp
SanteriHetekivi/JudgmentSolver
ede2c336cbed8e595d6cf296175181725cbfab61
[ "Apache-2.0" ]
null
null
null
src/Solver2.cpp
SanteriHetekivi/JudgmentSolver
ede2c336cbed8e595d6cf296175181725cbfab61
[ "Apache-2.0" ]
null
null
null
#include "Solver2.hpp" // public: /** * @brief Initialize solver with integer values for A, B, C and D. * */ Solver2::Solver2() { } /** * @brief Running solver and returning pointer to correct result. * */ int *Solver2::run() { // Running all the tests. if (!this->test(111, 2, 3)) throw TEST_111_2_3_FAILED; if (!this->test(222, 0, 1)) throw TEST_222_0_1_FAILED; if (!this->test(11, 99, 4)) throw TEST_11_99_4_FAILED; if (!this->test(3, 4, 2)) throw TEST_3_4_2_FAILED; // Solving safe numbers. int *result = new int[4]; result[0] = this->solve(111, 3); result[1] = this->solve(12, 99); result[2] = this->solve(333, 0); result[3] = this->solve(5, 6); return result; } // private: /** * @brief Testing if given integer inputs give the given result. * */ bool Solver2::test(int int1, int int2, int result) { int solve_result = this->solve(int1, int2); return solve_result == result; } /** * @brief Solve number with given input numbers. * */ int Solver2::solve(int int1, int int2) { int result = 0; int n = (int1 * int2); do { ++result; n /= 10; } while (n); return result; }
19.412698
66
0.582175
SanteriHetekivi
570019bfd7a1ae4cb73439d908ab22dae9ef0b6f
2,864
cpp
C++
LeetCode/C++/1536. Minimum Swaps to Arrange a Binary Grid.cpp
shreejitverma/GeeksforGeeks
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-18T05:14:28.000Z
2022-03-08T07:00:08.000Z
LeetCode/C++/1536. Minimum Swaps to Arrange a Binary Grid.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
6
2022-01-13T04:31:04.000Z
2022-03-12T01:06:16.000Z
LeetCode/C++/1536. Minimum Swaps to Arrange a Binary Grid.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-14T19:53:53.000Z
2022-02-18T05:14:30.000Z
//WA //104 / 129 test cases passed. //[[1,0,0,0,0,0],[0,1,0,1,0,0],[1,0,0,0,0,0],[1,1,1,0,0,0],[1,1,0,1,0,0],[1,0,0,0,0,0]] class Solution { public: int minSwaps(vector<vector<int>>& grid) { int n = grid.size(); vector<pair<int, int>> maxRight(n); for(int i = 0; i < n; ++i){ int j; for(j = n-1; j >= 0 && grid[i][j] == 0; --j){} maxRight[i] = {n-1-j, i}; } /* sort descending by count and then ascending by index [[1,0,0,0],[1,1,1,1],[1,0,0,0],[1,0,0,0]] */ sort(maxRight.begin(), maxRight.end(), [](pair<int,int>& a, pair<int,int>& b){ return (a.first == b.first) ? a.second < b.second : a.first > b.first; }); for(int i = 0; i < n; ++i){ if(maxRight[i].first < n-1-i) return -1; } //now we are sure that the answer exist int swaps = 0; for(int i = 0; i < n; ++i){ swaps += maxRight[i].second - i; for(int j = i+1; j < n; ++j){ if(maxRight[j].second < maxRight[i].second){ ++maxRight[j].second; } } } return swaps; } }; //Greedy //https://leetcode.com/problems/minimum-swaps-to-arrange-a-binary-grid/discuss/768076/Min-Adjacent-Swaps-to-Sort-the-array-of-INTEGERS-with-Proof //Runtime: 156 ms, faster than 100.00% of C++ online submissions for Minimum Swaps to Arrange a Binary Grid. //Memory Usage: 25.9 MB, less than 100.00% of C++ online submissions for Minimum Swaps to Arrange a Binary Grid. class Solution { public: int minSwaps(vector<vector<int>>& grid) { int n = grid.size(); vector<int> maxRight(n); for(int i = 0; i < n; ++i){ int j; for(j = n-1; j >= 0 && grid[i][j] == 0; --j){} maxRight[i] = n-1-j; } //sort descending vector<int> tmp = maxRight; sort(tmp.rbegin(), tmp.rend()); for(int i = 0; i < n; ++i){ if(tmp[i] < n-1-i) return -1; } //now we are sure that the answer exist int swaps = 0; for(int i = 0; i < n; ++i){ if(maxRight[i] < n-1-i){ //move some row up int j; for(j = i+1; j < n && maxRight[j] < n-1-i; ++j){} //jth row is what we want //move jth row to ith row //i,i+1,...,j-1,j -> j,i+1,i+2,...,j-1 int jcount = maxRight[j]; maxRight.erase(maxRight.begin()+j); maxRight.insert(maxRight.begin()+i, jcount); swaps += j-i; } } return swaps; } };
31.472527
145
0.440642
shreejitverma
570226223317993e885a3bb8083bfba067ae4628
17,223
cc
C++
src/modular/tests/module_context_test.cc
zhangpf/fuchsia-rs
903568f28ddf45f09157ead36d61b50322c9cf49
[ "BSD-3-Clause" ]
null
null
null
src/modular/tests/module_context_test.cc
zhangpf/fuchsia-rs
903568f28ddf45f09157ead36d61b50322c9cf49
[ "BSD-3-Clause" ]
5
2020-09-06T09:02:06.000Z
2022-03-02T04:44:22.000Z
src/modular/tests/module_context_test.cc
ZVNexus/fuchsia
c5610ad15208208c98693618a79c705af935270c
[ "BSD-3-Clause" ]
null
null
null
// 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 <fuchsia/modular/testing/cpp/fidl.h> #include <lib/fsl/vmo/strings.h> #include <lib/modular_test_harness/cpp/fake_module.h> #include <lib/modular_test_harness/cpp/fake_session_shell.h> #include <lib/modular_test_harness/cpp/test_harness_fixture.h> #include <src/lib/fxl/logging.h> #include "gmock/gmock.h" using testing::ElementsAre; namespace { class ModuleContextTest : public modular::testing::TestHarnessFixture { protected: void StartSession(modular::testing::TestHarnessBuilder builder) { builder.InterceptSessionShell(session_shell_.GetOnCreateHandler(), {.sandbox_services = {"fuchsia.modular.SessionShellContext"}}); builder.BuildAndRun(test_harness()); // Wait for our session shell to start. RunLoopUntil([this] { return session_shell_.is_running(); }); } void RestartStory(std::string story_name) { fuchsia::modular::StoryControllerPtr story_controller; session_shell_.story_provider()->GetController(story_name, story_controller.NewRequest()); bool restarted = false; story_controller->Stop([&] { story_controller->RequestStart(); restarted = true; }); RunLoopUntil([&] { return restarted; }); } modular::testing::FakeSessionShell* session_shell() { return &session_shell_; } private: modular::testing::FakeSessionShell session_shell_; }; // A version of FakeModule which captures handled intents in a std::vector<> // and exposes callbacks triggered on certain lifecycle events. class FakeModule : public modular::testing::FakeModule { public: std::vector<fuchsia::modular::Intent> handled_intents; fit::function<void()> on_destroy; fit::function<void()> on_create; private: // |modular::testing::FakeModule| void OnCreate(fuchsia::sys::StartupInfo startup_info) override { modular::testing::FakeModule::OnCreate(std::move(startup_info)); if (on_create) on_create(); } // |modular::testing::FakeModule| void OnDestroy() override { handled_intents.clear(); if (on_destroy) on_destroy(); } // |fuchsia::modular::IntentHandler| void HandleIntent(fuchsia::modular::Intent intent) { handled_intents.push_back(std::move(intent)); } }; // Test that ModuleContext.AddModuleToStory() starts child modules and that // calling it multiple times for the same child has different behavior if the // Intent specifies the same handler, versus if it specifies a different // handler. TEST_F(ModuleContextTest, AddModuleToStory) { modular::testing::TestHarnessBuilder builder; struct FakeModuleInfo { std::string url; FakeModule component; fuchsia::modular::ModuleControllerPtr controller; }; FakeModuleInfo parent_module{.url = modular::testing::GenerateFakeUrl("parent_module")}; FakeModuleInfo child_module1{.url = modular::testing::GenerateFakeUrl("child_module1")}; FakeModuleInfo child_module2{.url = modular::testing::GenerateFakeUrl("child_module2")}; builder.InterceptComponent( parent_module.component.GetOnCreateHandler(), {.url = parent_module.url, .sandbox_services = parent_module.component.GetSandboxServices()}); builder.InterceptComponent( child_module1.component.GetOnCreateHandler(), {.url = child_module1.url, .sandbox_services = child_module1.component.GetSandboxServices()}); builder.InterceptComponent( child_module2.component.GetOnCreateHandler(), {.url = child_module2.url, .sandbox_services = child_module2.component.GetSandboxServices()}); StartSession(std::move(builder)); modular::testing::AddModToStory(test_harness(), "storyname", "modname", {.action = "action", .handler = parent_module.url}); RunLoopUntil([&] { return parent_module.component.is_running(); }); // Add a single child module. fuchsia::modular::ModuleControllerPtr child_module1_controller; parent_module.component.module_context()->AddModuleToStory( "childmodname", {.action = "action", .handler = child_module1.url}, child_module1.controller.NewRequest(), /*surface_relation=*/nullptr, [&](fuchsia::modular::StartModuleStatus status) { ASSERT_EQ(status, fuchsia::modular::StartModuleStatus::SUCCESS); }); RunLoopUntil([&] { return child_module1.component.is_running() && child_module1.component.handled_intents.size() == 1; }); EXPECT_EQ(child_module1.component.handled_intents.at(0).action, "action"); // Add the same module again but with a different Intent action. bool child_module1_destroyed{false}; child_module1.component.on_destroy = [&] { child_module1_destroyed = true; }; parent_module.component.module_context()->AddModuleToStory( "childmodname", {.action = "action2", .handler = child_module1.url}, child_module1.controller.NewRequest(), /*surface_relation=*/nullptr, [&](fuchsia::modular::StartModuleStatus status) { ASSERT_EQ(status, fuchsia::modular::StartModuleStatus::SUCCESS); }); RunLoopUntil([&] { return child_module1.component.handled_intents.size() == 2; }); EXPECT_EQ(child_module1.component.handled_intents.at(1).action, "action2"); // At no time should the child module have been destroyed. EXPECT_EQ(child_module1_destroyed, false); // This time change the handler. Expect the first module to be shut down, // and the second to run in its place. parent_module.component.module_context()->AddModuleToStory( "childmodname", {.action = "action", .handler = child_module2.url}, child_module2.controller.NewRequest(), /*surface_relation=*/nullptr, [&](fuchsia::modular::StartModuleStatus status) { ASSERT_EQ(status, fuchsia::modular::StartModuleStatus::SUCCESS); }); RunLoopUntil([&] { return child_module2.component.is_running() && child_module2.component.handled_intents.size() == 1; }); EXPECT_FALSE(child_module1.component.is_running()); EXPECT_EQ(child_module2.component.handled_intents.at(0).action, "action"); } // Test that ModuleContext.RemoveSelfFromStory() has the affect of shutting // down the module and removing it permanently from the story (if the story is // restarted, it is not relaunched). TEST_F(ModuleContextTest, RemoveSelfFromStory) { modular::testing::TestHarnessBuilder builder; struct FakeModuleInfo { std::string url; FakeModule component; }; FakeModuleInfo module1{.url = modular::testing::GenerateFakeUrl("module1")}; FakeModuleInfo module2{.url = modular::testing::GenerateFakeUrl("module2")}; builder.InterceptComponent( module1.component.GetOnCreateHandler(), {.url = module1.url, .sandbox_services = module1.component.GetSandboxServices()}); builder.InterceptComponent( module2.component.GetOnCreateHandler(), {.url = module2.url, .sandbox_services = module2.component.GetSandboxServices()}); StartSession(std::move(builder)); modular::testing::AddModToStory(test_harness(), "storyname", "modname1", {.action = "action", .handler = module1.url}); modular::testing::AddModToStory(test_harness(), "storyname", "modname2", {.action = "action", .handler = module2.url}); RunLoopUntil([&] { return module1.component.is_running() && module2.component.is_running(); }); // Instruct module1 to remove itself from the story. Expect to see that // module1 is terminated and module2 is not. module1.component.module_context()->RemoveSelfFromStory(); RunLoopUntil([&] { return !module1.component.is_running(); }); ASSERT_TRUE(module2.component.is_running()); // Additionally, restarting the story should not result in module1 being // restarted whereas it should for module2. bool module2_destroyed = false; bool module2_restarted = false; module2.component.on_destroy = [&] { module2_destroyed = true; }; module2.component.on_create = [&] { module2_restarted = true; }; RestartStory("storyname"); RunLoopUntil([&] { return module2_restarted; }); EXPECT_FALSE(module1.component.is_running()); EXPECT_TRUE(module2_destroyed); } // Create a story-hosted Entity using ModuleContext, verify that it can be // updated and that it has a valid Entity reference. TEST_F(ModuleContextTest, CreateEntity) { modular::testing::TestHarnessBuilder builder; auto module_url = modular::testing::GenerateFakeUrl("module"); FakeModule module; builder.InterceptComponent(module.GetOnCreateHandler(), {.url = module_url, .sandbox_services = module.GetSandboxServices()}); StartSession(std::move(builder)); modular::testing::AddModToStory(test_harness(), "storyname", "modname", {.action = "action", .handler = module_url}); RunLoopUntil([&] { return module.is_running(); }); // Create an entity, acquire an Entity handle as well as a reference // to it. fidl::StringPtr reference; fuchsia::modular::EntityPtr entity; { fuchsia::mem::Buffer buffer; ASSERT_TRUE(fsl::VmoFromString("42", &buffer)); module.module_context()->CreateEntity("entity_type", std::move(buffer), entity.NewRequest(), [&](fidl::StringPtr new_reference) { ASSERT_FALSE(new_reference.is_null()); reference = new_reference; }); RunLoopUntil([&] { return !reference.is_null(); }); } // Get the types and value from the handle returned by CreateEntity() and // observe they are accurate. { std::vector<std::string> types; bool gettypes_done = false; entity->GetTypes([&](auto entity_types) { types = entity_types; gettypes_done = true; }); fuchsia::mem::Buffer buffer; bool getdata_done = false; entity->GetData("entity_type", [&](auto data) { ASSERT_TRUE(data); buffer = std::move(*data); getdata_done = true; }); RunLoopUntil([&] { return gettypes_done && getdata_done; }); EXPECT_THAT(types, ElementsAre("entity_type")); std::string value; ASSERT_TRUE(fsl::StringFromVmo(buffer, &value)); EXPECT_EQ(value, "42"); } // Get an Entity handle using the reference returned by CreateEntity(). { fuchsia::modular::EntityResolverPtr resolver; module.modular_component_context()->GetEntityResolver(resolver.NewRequest()); fuchsia::modular::EntityPtr entity_from_reference; resolver->ResolveEntity(reference, entity_from_reference.NewRequest()); std::vector<std::string> types; bool gettypes_done = false; entity_from_reference->GetTypes([&](auto entity_types) { types = entity_types; gettypes_done = true; }); fuchsia::mem::Buffer buffer; bool getdata_done = false; entity_from_reference->GetData("entity_type", [&](auto data) { ASSERT_TRUE(data); buffer = std::move(*data); getdata_done = true; }); RunLoopUntil([&] { return gettypes_done && getdata_done; }); EXPECT_THAT(types, ElementsAre("entity_type")); std::string value; ASSERT_TRUE(fsl::StringFromVmo(buffer, &value)); EXPECT_EQ(value, "42"); } // Update the entity and observe its value changed. { fuchsia::mem::Buffer new_value; ASSERT_TRUE(fsl::VmoFromString("43", &new_value)); bool writedata_done = false; entity->WriteData("entity_type", std::move(new_value), [&](auto status) { ASSERT_EQ(status, fuchsia::modular::EntityWriteStatus::OK); writedata_done = true; }); bool getdata_done = false; fuchsia::mem::Buffer current_value; entity->GetData("entity_type", [&](auto data) { ASSERT_TRUE(data); current_value = std::move(*data); getdata_done = true; }); RunLoopUntil([&] { return getdata_done; }); EXPECT_TRUE(writedata_done); std::string current_value_str; ASSERT_TRUE(fsl::StringFromVmo(current_value, &current_value_str)); EXPECT_EQ(current_value_str, "43"); } } // A simple story activity watcher implementation. class TestStoryActivityWatcher : fuchsia::modular::StoryActivityWatcher { public: using ActivityChangeFn = fit::function<void(std::string, std::vector<fuchsia::modular::OngoingActivityType>)>; TestStoryActivityWatcher(ActivityChangeFn on_change) : on_change_(std::move(on_change)), binding_(this) {} ~TestStoryActivityWatcher() override = default; void Watch(fuchsia::modular::StoryProvider* const story_provider) { story_provider->WatchActivity(binding_.NewBinding()); } private: // |fuchsia::modular::StoryActivityWatcher| void OnStoryActivityChange( std::string story_id, std::vector<fuchsia::modular::OngoingActivityType> activities) override { on_change_(std::move(story_id), std::move(activities)); } ActivityChangeFn on_change_; fidl::Binding<fuchsia::modular::StoryActivityWatcher> binding_; }; // When a shell registers a watcher for ongoing activities and modules create // and destroy them, the shell should ge appropriately notified. TEST_F(ModuleContextTest, OngoingActivity_NotifyOnWatch) { modular::testing::TestHarnessBuilder builder; struct FakeModuleInfo { std::string url; FakeModule component; }; FakeModuleInfo module1{.url = modular::testing::GenerateFakeUrl("module1")}; FakeModuleInfo module2{.url = modular::testing::GenerateFakeUrl("module2")}; builder.InterceptComponent( module1.component.GetOnCreateHandler(), {.url = module1.url, .sandbox_services = module1.component.GetSandboxServices()}); builder.InterceptComponent( module2.component.GetOnCreateHandler(), {.url = module2.url, .sandbox_services = module2.component.GetSandboxServices()}); StartSession(std::move(builder)); modular::testing::AddModToStory(test_harness(), "storyname", "modname1", {.action = "action", .handler = module1.url}); modular::testing::AddModToStory(test_harness(), "storyname", "modname2", {.action = "action", .handler = module2.url}); RunLoopUntil([&] { return module1.component.is_running() && module2.component.is_running(); }); std::vector<std::vector<fuchsia::modular::OngoingActivityType>> on_change_updates; TestStoryActivityWatcher activity_watcher( [&](std::string story_id, std::vector<fuchsia::modular::OngoingActivityType> activities) { ASSERT_EQ(story_id, "storyname"); on_change_updates.push_back(std::move(activities)); }); auto RunLoopUntilActivityUpdate = [&] { auto current_size = on_change_updates.size(); RunLoopUntil([&] { return on_change_updates.size() > current_size; }); }; // Watch for activity updates. activity_watcher.Watch(session_shell()->story_provider()); // And expect to see a notification immediately for "storyname". RunLoopUntilActivityUpdate(); EXPECT_THAT(on_change_updates, ElementsAre(ElementsAre())); // Now instruct module1 to create an ongoing activity. fuchsia::modular::OngoingActivityPtr ongoing_activity1; module1.component.module_context()->StartOngoingActivity( fuchsia::modular::OngoingActivityType::VIDEO, ongoing_activity1.NewRequest()); RunLoopUntilActivityUpdate(); EXPECT_THAT( on_change_updates, ElementsAre(ElementsAre(), ElementsAre(fuchsia::modular::OngoingActivityType::VIDEO))); // When module2 creates one also, expect to see both represented. fuchsia::modular::OngoingActivityPtr ongoing_activity2; module2.component.module_context()->StartOngoingActivity( fuchsia::modular::OngoingActivityType::AUDIO, ongoing_activity2.NewRequest()); RunLoopUntilActivityUpdate(); EXPECT_THAT(on_change_updates, ElementsAre(ElementsAre(), ElementsAre(fuchsia::modular::OngoingActivityType::VIDEO), ElementsAre(fuchsia::modular::OngoingActivityType::VIDEO, fuchsia::modular::OngoingActivityType::AUDIO))); // module1 terminating its activity should result in a new notification. ongoing_activity1.Unbind(); RunLoopUntilActivityUpdate(); EXPECT_THAT(on_change_updates, ElementsAre(ElementsAre(), ElementsAre(fuchsia::modular::OngoingActivityType::VIDEO), ElementsAre(fuchsia::modular::OngoingActivityType::VIDEO, fuchsia::modular::OngoingActivityType::AUDIO), ElementsAre(fuchsia::modular::OngoingActivityType::AUDIO))); // And lastly terminating module2's activity results in no more activities. ongoing_activity2.Unbind(); RunLoopUntilActivityUpdate(); EXPECT_THAT( on_change_updates, ElementsAre(ElementsAre(), ElementsAre(fuchsia::modular::OngoingActivityType::VIDEO), ElementsAre(fuchsia::modular::OngoingActivityType::VIDEO, fuchsia::modular::OngoingActivityType::AUDIO), ElementsAre(fuchsia::modular::OngoingActivityType::AUDIO), ElementsAre())); } } // namespace
41.401442
100
0.702317
zhangpf
57038c2c1e697f411729105cb1dab6214c993c82
2,758
cpp
C++
include/asioext/impl/file_handle.cpp
zweistein-frm2/asio-extensions
bafea77c48d674930405cb7f93bdfe65539abc39
[ "BSL-1.0" ]
17
2018-04-13T00:38:55.000Z
2022-01-21T08:38:36.000Z
include/asioext/impl/file_handle.cpp
zweistein-frm2/asio-extensions
bafea77c48d674930405cb7f93bdfe65539abc39
[ "BSL-1.0" ]
4
2017-03-16T03:34:38.000Z
2020-05-08T00:05:51.000Z
include/asioext/impl/file_handle.cpp
zweistein-frm2/asio-extensions
bafea77c48d674930405cb7f93bdfe65539abc39
[ "BSL-1.0" ]
5
2017-09-06T15:56:04.000Z
2021-09-14T07:38:02.000Z
/// @copyright Copyright (c) 2015 Tim Niederhausen (tim@rnc-ag.de) /// 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 "asioext/file_handle.hpp" #include "asioext/detail/throw_error.hpp" ASIOEXT_NS_BEGIN file_handle::file_handle(const native_handle_type& handle) ASIOEXT_NOEXCEPT : handle_(handle) { // ctor } file_handle::~file_handle() { } void file_handle::close() { error_code ec; close(ec); detail::throw_error(ec, "close"); } uint64_t file_handle::position() { error_code ec; uint64_t s = position(ec); detail::throw_error(ec, "position"); return s; } uint64_t file_handle::seek(seek_origin origin, int64_t offset) { error_code ec; uint64_t s = seek(origin, offset, ec); detail::throw_error(ec, "seek"); return s; } uint64_t file_handle::size() { error_code ec; uint64_t s = size(ec); detail::throw_error(ec, "size"); return s; } void file_handle::truncate(uint64_t new_size) { error_code ec; truncate(new_size, ec); detail::throw_error(ec, "truncate"); } #if defined(ASIOEXT_MSVC) && (ASIOEXT_MSVC >= 1400) \ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0600) #pragma warning(push) #pragma warning(disable:4996) #endif file_perms file_handle::permissions() { error_code ec; file_perms p = permissions(ec); detail::throw_error(ec, "get_permissions"); return p; } void file_handle::permissions(file_perms perms, file_perm_options opts) { error_code ec; permissions(perms, opts, ec); detail::throw_error(ec, "set_permissions"); } void file_handle::permissions(file_perms perms, error_code& ec) ASIOEXT_NOEXCEPT { permissions(perms, file_perm_options::replace, ec); } file_attrs file_handle::attributes() { error_code ec; file_attrs a = attributes(ec); detail::throw_error(ec, "get_attributes"); return a; } void file_handle::attributes(file_attrs attrs, file_attr_options opts) { error_code ec; attributes(attrs, opts, ec); detail::throw_error(ec, "set_attributes"); } void file_handle::attributes(file_attrs attrs, error_code& ec) ASIOEXT_NOEXCEPT { attributes(attrs, file_attr_options::replace, ec); } #if defined(ASIOEXT_MSVC) && (ASIOEXT_MSVC >= 1400) \ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0600) #pragma warning(pop) #endif file_times file_handle::times() { error_code ec; file_times t = times(ec); detail::throw_error(ec, "get_times"); return t; } void file_handle::times(const file_times& new_times) { error_code ec; times(new_times, ec); detail::throw_error(ec, "set_times"); } ASIOEXT_NS_END
21.215385
91
0.694344
zweistein-frm2
5712df6e00d1ab2b785c47a085d18056c5f285e7
1,490
cc
C++
src/phy/AutoGain.cc
drexelwireless/dragonradio
885abd68d56af709e7a53737352641908005c45b
[ "MIT" ]
8
2020-12-05T20:30:54.000Z
2022-01-22T13:32:14.000Z
src/phy/AutoGain.cc
drexelwireless/dragonradio
885abd68d56af709e7a53737352641908005c45b
[ "MIT" ]
3
2020-10-28T22:15:27.000Z
2021-01-27T14:43:41.000Z
src/phy/AutoGain.cc
drexelwireless/dragonradio
885abd68d56af709e7a53737352641908005c45b
[ "MIT" ]
null
null
null
// Copyright 2018-2020 Drexel University // Author: Geoffrey Mainland <mainland@drexel.edu> #include "logging.hh" #include "phy/AutoGain.hh" void AutoGain::autoSoftGain0dBFS(float g, std::shared_ptr<IQBuf> buf) { { std::unique_lock<std::shared_mutex> lock(mutex_); if (nestimates_0dBFS_ > 0) --nestimates_0dBFS_; else return; } size_t n = buf->size(); // This should never happen, but just in case... if (n == 0) return; std::complex<float>* f = buf->data(); auto power = std::unique_ptr<float[]>(new float[n]); for (size_t i = 0; i < n; ++i) { std::complex<float> temp = f[i]; power[i] = temp.real()*temp.real() + temp.imag()*temp.imag(); } std::sort(power.get(), power.get() + n); size_t max_n = getAutoSoftTXGainClipFrac()*n; if (max_n < 0) max_n = 0; else if (max_n >= n) max_n = n - 1; float max_amp2 = power[max_n]; // Avoid division by 0! if (max_amp2 == 0.0) return; // XXX Should I^2 + Q^2 = 1.0 or 2.0? float g_estimate = sqrtf(1.0/max_amp2); // g is the gain multiplier used to produce the IQ samples { std::unique_lock<std::shared_mutex> lock(mutex_); g_0dBFS_estimate_.update(g*g_estimate); g_0dBFS_.store(*g_0dBFS_estimate_, std::memory_order_relaxed); } logAMC(LOGDEBUG-1, "updated auto-gain %0.1f", (double) getSoftTXGain0dBFS()); }
24.42623
81
0.58255
drexelwireless
5713256abe23bcd57036b18d9639c7a22c42922e
3,309
hpp
C++
src/common/global/global.hpp
mshiryaev/oneccl
fb4bd69b0bfa72f0ed16ac2328205e51cf12d4aa
[ "Apache-2.0" ]
null
null
null
src/common/global/global.hpp
mshiryaev/oneccl
fb4bd69b0bfa72f0ed16ac2328205e51cf12d4aa
[ "Apache-2.0" ]
null
null
null
src/common/global/global.hpp
mshiryaev/oneccl
fb4bd69b0bfa72f0ed16ac2328205e51cf12d4aa
[ "Apache-2.0" ]
null
null
null
/* Copyright 2016-2019 Intel 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. */ #pragma once #include "ccl.h" #include "common/utils/utils.hpp" #include "coll/algorithms/algorithms_enum.hpp" #include <memory> #include <thread> #define COMMON_CATCH_BLOCK() \ catch (ccl::ccl_error& ccl_e) \ { \ LOG_ERROR("ccl internal error: ", ccl_e.what()); \ return ccl_status_invalid_arguments; \ } \ catch (std::exception& e) \ { \ LOG_ERROR("error: ", e.what()); \ return ccl_status_runtime_error; \ } \ catch (...) \ { \ LOG_ERROR("general error"); \ return ccl_status_runtime_error; \ } \ class ccl_comm; class ccl_stream; class ccl_atl_tag; class ccl_comm_id_storage; class ccl_executor; class ccl_sched_cache; class ccl_parallelizer; class ccl_fusion_manager; class ccl_unordered_coll_manager; template<ccl_coll_type... registered_types_id> struct ccl_algorithm_selector_wrapper; struct alignas(CACHELINE_SIZE) ccl_global_data { std::unique_ptr<ccl_comm_id_storage> comm_ids; std::shared_ptr<ccl_comm> comm; std::unique_ptr<ccl_atl_tag> atl_tag; std::unique_ptr<ccl_executor> executor; std::unique_ptr<ccl_coll_attr_t> default_coll_attr; std::unique_ptr<ccl_sched_cache> sched_cache; std::unique_ptr<ccl_parallelizer> parallelizer; std::unique_ptr<ccl_fusion_manager> fusion_manager; std::unique_ptr<ccl_unordered_coll_manager> unordered_coll_manager; std::unique_ptr<ccl_algorithm_selector_wrapper<CCL_COLL_LIST>> algorithm_selector; static thread_local bool is_worker_thread; bool is_ft_enabled; }; extern ccl_global_data global_data; #define CCL_CHECK_IS_BLOCKED() \ { \ do \ { \ if (unlikely(global_data.executor->is_locked)) \ { \ return ccl_status_blocked_due_to_resize; \ } \ } while (0); \ } void reset_for_size_update(ccl_global_data* gl_data); void ccl_init_global_objects(ccl_global_data& gl_data);
37.602273
86
0.550922
mshiryaev
5718d406a63067946b8977563d455cf8cc504621
1,180
cpp
C++
PA1/src/Scene.cpp
dowoncha/COMP575
6e48bdd80cb1a3e677c07655640efa941325e59c
[ "MIT" ]
null
null
null
PA1/src/Scene.cpp
dowoncha/COMP575
6e48bdd80cb1a3e677c07655640efa941325e59c
[ "MIT" ]
null
null
null
PA1/src/Scene.cpp
dowoncha/COMP575
6e48bdd80cb1a3e677c07655640efa941325e59c
[ "MIT" ]
null
null
null
#include "Scene.h" Scene::Scene() { } Scene::~Scene() { for (Surface* s : Surfaces) { delete s; } for (Light* l : Lights) { delete l; } } void Scene::AddSurface(Surface* s) { Surfaces.push_back(s); } void Scene::AddLight(Light* l) { Lights.push_back(l); } bool Scene::IntersectSurfaces(const Ray& ray, float tMax, HitData& data) const { bool surfacehit = false; // Intersect all surfaces using view ray // float tMin = tMax; for (Surface* s : Surfaces) { if (s->Intersect(ray, data.t, data.tMax, data.tPoint)) { data.Point = data.tPoint; data.t = data.tMax; data.HitSurface = s; data.Normal = data.HitSurface->GetNormal(data.Point); surfacehit = true; } } return surfacehit; } bool Scene::IntersectSurfaces(const Ray& ray, float tMax, const Surface *ignore) const { // Intersect all surfaces using view ray for (Surface* s : Surfaces) { if (s == ignore) continue; if (s->Intersect(ray, tMax)) { return true; } } return false; }
18.153846
86
0.545763
dowoncha
571946ce5f50cbfcefca6e36e3c4a56f6d2b1851
1,056
cpp
C++
codeforces/441div2/A/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
null
null
null
codeforces/441div2/A/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
19
2016-05-04T02:46:31.000Z
2021-11-27T06:18:33.000Z
codeforces/441div2/A/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
null
null
null
#include <bits/stdc++.h> #define each(i, c) for (auto& i : c) #define unless(cond) if (!(cond)) using namespace std; typedef long long int lli; typedef unsigned long long ull; typedef complex<double> point; template<typename P, typename Q> ostream& operator << (ostream& os, pair<P, Q> p) { os << "(" << p.first << "," << p.second << ")"; return os; } int main(int argc, char *argv[]) { ios_base::sync_with_stdio(0); cin.tie(0); int n, a, b, c; while (cin >> n >> a >> b >> c) { // Rabbit's and Owl's houses is a meters // Rabbit's and Eeyore's house is b meters // Owl's and Eeyore's house is c meters. const int N = 3; int g[N][N]; g[0][1] = g[1][0] = a; g[0][2] = g[2][0] = b; g[1][2] = g[2][1] = c; lli sum = 0; int i = 0; --n; while (n--) { int j = (i + 1) % N; int k = (i - 1 + N) % N; if (g[i][j] < g[i][k]) { sum += g[i][j]; i = j; } else { sum += g[i][k]; i = k; } } cout << sum << endl; } return 0; }
19.2
49
0.47822
Johniel
5719f56df9b589bdc681f0e94d09c6925c683e0d
2,709
cpp
C++
RemClientCPP/client_libsocket/client_libsocket.cpp
nemo9955/RespirMesh
afef38c85e5686a565d1d6b577578e1fdc426cbc
[ "Apache-2.0" ]
null
null
null
RemClientCPP/client_libsocket/client_libsocket.cpp
nemo9955/RespirMesh
afef38c85e5686a565d1d6b577578e1fdc426cbc
[ "Apache-2.0" ]
null
null
null
RemClientCPP/client_libsocket/client_libsocket.cpp
nemo9955/RespirMesh
afef38c85e5686a565d1d6b577578e1fdc426cbc
[ "Apache-2.0" ]
null
null
null
#include <pb_encode.h> #include <pb_decode.h> #include <pb.h> #include <signal.h> #include "mesh-packet.pb.h" #include "RemHeaderTypes.hpp" #include "RemChannel.hpp" #include "RemOrchestrator.hpp" #include "RemRouter.hpp" #include "RemConnectionController.hpp" #include "RemLogger.hpp" #include "TaskLooper.hpp" #include "RemHardware.hpp" #include "X86_64/X86LinuxClientChannel.hpp" #include "X86_64/X86LinuxServerChannel.hpp" #include "X86_64/SimpleListChnCtrl.hpp" #include "X86_64/X86LinuxHardware.hpp" uint32_t chipID = 0; void sig_exit(int s); SimpleListChnCtrl parentScanner; X86LinuxHardware hardware_; RemRouter remRouter; RemOrchestrator remOrch; RemLogger logs; TaskLooper update_looper; void sig_exit(int s) { remOrch.stop(); exit(0); } int main(int argc, char *argv[]) { remOrch.set_router(&remRouter); remOrch.set_scanner(&parentScanner); remOrch.set_hardware(&hardware_); remOrch.set_logger(&logs); update_looper.begin(remOrch.basicHardware); update_looper.set(1 * 1000); // for (size_t i = 0; i < argc; i++) // { // printf(" %d %s \n", i, argv[i]); // } // return 0; logs.info("_ STARTING !!!!!!!!!!!!!!!!!!!!! _"); if (argc < 6) { printf("First 2 arguments specify host and port of the server \n"); printf("3th arg, the ID of the device, random if 0 \n"); printf("Next sets of 2 arguments specify host and port of client \n"); exit(1); } srand(time(NULL)); if (atoi(argv[3]) != 0) chipID = atoi(argv[3]); else chipID = rand() % 640000; hardware_.chip_id = chipID; char *server_host = const_cast<char *>(argv[1]); char *server_port = const_cast<char *>(argv[2]); parentScanner.add_server_host(server_host, server_port); for (size_t i = 4; i < argc; i += 2) { char *client_host = const_cast<char *>(argv[i]); char *client_port = const_cast<char *>(argv[i + 1]); parentScanner.add_client_host(client_host, client_port); } // parentScanner.set_inst_server(X86LinuxServerChannel::instantiate); // parentScanner.set_inst_client(X86LinuxClientChannel::instantiate); signal(SIGINT, sig_exit); logf("chipID %d %x \n", chipID, chipID); logf("Time : %u \n", remOrch.basicHardware->time_milis()); logf("devID: %d == 0x%x \n", remOrch.basicHardware->device_id(), remOrch.basicHardware->device_id()); remOrch.begin(); while (1) { if (update_looper.check()) { remOrch.update(); } sleep(0.5); // logs.trace("main loop update"); } // sleep(1); // remOrch.update(); remOrch.stop(); return 0; }
24.1875
105
0.635659
nemo9955
571eed7509330fe9237cc46a01edb5c9cc7a93a3
3,698
cpp
C++
firmware/modules/core/cRgbw.cpp
klaus-liebler/sensact
b8fc05eff67f23cf58c4fdf53e0026aab0966f6b
[ "Apache-2.0" ]
2
2021-02-09T16:17:43.000Z
2021-08-09T04:02:44.000Z
firmware/modules/core/cRgbw.cpp
klaus-liebler/sensact
b8fc05eff67f23cf58c4fdf53e0026aab0966f6b
[ "Apache-2.0" ]
2
2016-05-17T20:45:10.000Z
2020-03-10T07:03:39.000Z
firmware/modules/core/cRgbw.cpp
klaus-liebler/sensact
b8fc05eff67f23cf58c4fdf53e0026aab0966f6b
[ "Apache-2.0" ]
1
2020-05-24T13:37:55.000Z
2020-05-24T13:37:55.000Z
#include "cMaster.h" #include "cRgbw.h" #define LOGLEVEL LEVEL_INFO #define LOGNAME "RGBW " #include "cLog.h" namespace sensact { //targetValue absolut setzen oder aktuellen targetValue ver�ndern mit einem sint16_t //oder ausschalten, sonst geht der targetLevel nicht auf 0 cRgbw::cRgbw(const eApplicationID id, uint16_t const outputR, uint16_t const outputG, uint16_t const outputB, uint16_t const outputW, const bool lowMeansLampOn, const uint8_t *const WellKnownColors, const uint8_t WellKnownColorsLength, const eApplicationID standbyController, const Time_t autoOffIntervalMsecs) : cApplication(id), outputR(outputR), outputG(outputG), outputB(outputB), outputW(outputW), lowMeansLampOn(lowMeansLampOn), WellKnownColors(WellKnownColors), WellKnownColorsLength(WellKnownColorsLength), standbyController(standbyController), autoOffIntervalMsecs(autoOffIntervalMsecs), lastHeartbeatToStandbycontroller(0), lastColor(0), state(ePowerState::INACTIVE), changeRecorded(false), autoOffTime(TIME_MAX) { } eAppType cRgbw::GetAppType() { return eAppType::RGBW; } void cRgbw::showColorOfIndex(Time_t now, uint8_t index) { index%=WellKnownColorsLength; uint8_t* ptr = (uint8_t*)(this->WellKnownColors+4*index); lastColor=index; LOGD("Showing Color ID %d", lastColor); showColorOfRGBW(now, ptr[0], ptr[1], ptr[2], ptr[3]); } void cRgbw::showColorOfRGBW(Time_t now, uint8_t R, uint8_t G, uint8_t B, uint8_t W) { if(R==0 && G==0 && B==0 && W==0 ) { this->state = ePowerState::INACTIVE; } else { this->state = ePowerState::ACTIVE; } if(!lowMeansLampOn) { R=UINT8_MAX-R; B=UINT8_MAX-B; G=UINT8_MAX-G; W=UINT8_MAX-W; } BSP::SetDigitalOutput(this->outputR, R==255?UINT16_MAX:R<<8); BSP::SetDigitalOutput(this->outputG, G==255?UINT16_MAX:G<<8); BSP::SetDigitalOutput(this->outputB, B==255?UINT16_MAX:B<<8); if(this->outputW!=UINT16_MAX) { BSP::SetDigitalOutput(this->outputW, W==255?UINT16_MAX:W<<8); } changeRecorded=true; if(autoOffIntervalMsecs!=0) { autoOffTime=now+autoOffIntervalMsecs; } } void cRgbw::switchOff(Time_t now) { showColorOfRGBW(now, 0,0,0,0); } void cRgbw::OnSTEP_VERTICALCommand(int16_t step, Time_t now) { UNUSED(now); if(step==0) step=1; uint8_t index = ((int)(100 + lastColor + step)) % WellKnownColorsLength;//+100 um ausreichend im Positiven zu sein auch bei negativen steps showColorOfIndex(now, index); } void cRgbw::OnTOGGLECommand(Time_t now) { UNUSED(now); if(this->state == ePowerState::INACTIVE) { showColorOfIndex(now, lastColor); } else { switchOff(now); } } void cRgbw::OnSET_RGBWCommand(uint8_t R, uint8_t G, uint8_t B, uint8_t W, Time_t now) { showColorOfRGBW(now, R, G, B, W); } //Payload enth�lt 16bit wellKnownColorIndex void cRgbw::OnSET_SIGNALCommand(uint16_t signal, Time_t now) { UNUSED(now); uint8_t index = signal%WellKnownColorsLength; showColorOfIndex(now, index); } eAppCallResult cRgbw::DoEachCycle(volatile Time_t now, uint8_t *statusBuffer, size_t *statusBufferLength) { if(standbyController!=eApplicationID::NO_APPLICATION && state==ePowerState::ACTIVE && now-lastHeartbeatToStandbycontroller>10000) { cMaster::SendCommandToMessageBus(now, standbyController, eCommandType::HEARTBEAT, 0, 0); lastHeartbeatToStandbycontroller=now; } Common::WriteInt16(outputR, statusBuffer, 0); Common::WriteInt16(outputG, statusBuffer, 2); Common::WriteInt16(outputB, statusBuffer, 4); Common::WriteInt16(outputW, statusBuffer, 6); *statusBufferLength=8; eAppCallResult ret = changeRecorded?eAppCallResult::OK_CHANGED:eAppCallResult::OK; changeRecorded=false; return ret; } eAppCallResult cRgbw::Setup() { switchOff(0); return eAppCallResult::OK; } }
26.042254
312
0.751217
klaus-liebler
57204e8a0af2a07ece27f8de81c6dacb89509453
3,714
cpp
C++
gui/dialogs/pixelize-dialog.cpp
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
10
2016-12-28T22:06:31.000Z
2021-05-24T13:42:30.000Z
gui/dialogs/pixelize-dialog.cpp
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
4
2015-10-09T23:55:10.000Z
2020-04-04T08:09:22.000Z
gui/dialogs/pixelize-dialog.cpp
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
null
null
null
// -*- coding: us-ascii-unix -*- // Copyright 2013 Lukas Kemmer // // 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 "wx/dialog.h" #include "wx/sizer.h" #include "bitmap/bitmap-templates.hh" #include "gui/dialog-context.hh" #include "gui/slider.hh" #include "util/accessor.hh" #include "util-wx/fwd-wx.hh" #include "util-wx/gui-util.hh" #include "util-wx/key-codes.hh" #include "util-wx/layout-wx.hh" #include "util/command-util.hh" #include "util/optional.hh" namespace faint{ static bool enable_preview_default(const Bitmap& bmp){ return area(bmp.GetSize()) < area({2000, 2000}); } class PixelizeDialog : public wxDialog { public: PixelizeDialog(wxWindow& parent, const SliderCursors& sliderCursors, DialogFeedback& feedback) : wxDialog(&parent, wxID_ANY, "Pixelize", wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxWANTS_CHARS | wxRESIZE_BORDER), m_bitmap(feedback.GetBitmap()), m_pixelSizeSlider(nullptr), m_enablePreview(nullptr), m_feedback(feedback), m_sliderCursors(sliderCursors) { using namespace layout; // Create the member-controls in intended tab-order (placement follows) m_enablePreview = create_checkbox(this, "&Preview", enable_preview_default(m_bitmap), [&](){ if (PreviewEnabled()){ UpdatePreview(); } else{ ResetPreview(); } }); m_pixelSizeSlider = create_slider(this, BoundedInt::Mid(min_t(1), max_t(100)), SliderDir::HORIZONTAL, slider_marker_BorderedLine(), slider_bg_Rectangle(), m_sliderCursors, IntSize(200, 20)); set_sizer(this, create_column({ create_row({raw(m_enablePreview)}), grow(create_row({grow(m_pixelSizeSlider)})), center(create_row_no_pad({ make_default(this, create_ok_button(this)), create_cancel_button(this)})) })); center_over_parent(this); set_accelerators(this, { {key::F5, [=](){UpdatePreview();}}, {key::P, [=](){ toggle(m_enablePreview); }}}); events::on_slider_change(this, [&](int){ if (PreviewEnabled()){ UpdatePreview(); } }); m_pixelSizeSlider->SetFocus(); if (PreviewEnabled()){ UpdatePreview(); } } BitmapCommandPtr GetCommand(){ return get_pixelize_command(m_pixelSizeSlider->GetValue()); } bool ValuesModified() const{ return m_pixelSizeSlider->GetValue() != 1; } private: bool PreviewEnabled() const{ return get(m_enablePreview); } void ResetPreview(){ m_feedback.SetBitmap(m_bitmap); } void UpdatePreview(){ m_feedback.SetBitmap(onto_new(pixelize, m_bitmap, m_pixelSizeSlider->GetValue())); } Bitmap m_bitmap; Slider* m_pixelSizeSlider; wxCheckBox* m_enablePreview; DialogFeedback& m_feedback; const SliderCursors& m_sliderCursors; }; BitmapCommandPtr show_pixelize_dialog(wxWindow& parent, DialogContext& c, DialogFeedback& feedback) { PixelizeDialog dlg(parent, c.GetSliderCursors(), feedback); bool ok = c.ShowModal(dlg) == DialogChoice::OK && dlg.ValuesModified(); return ok ? dlg.GetCommand() : nullptr; } } // namespace
26.719424
79
0.679052
lukas-ke
5727218bb4d7c664723283b21759cb4abc996ae9
1,219
cc
C++
vendor/chromium/base/android/child_process_unittest.cc
thorium-cfx/fivem
587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c
[ "MIT" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
vendor/chromium/base/android/child_process_unittest.cc
thorium-cfx/fivem
587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c
[ "MIT" ]
802
2017-04-21T14:18:36.000Z
2022-03-31T21:20:48.000Z
vendor/chromium/base/android/child_process_unittest.cc
thorium-cfx/fivem
587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c
[ "MIT" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2018 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 "base/android/jni_android.h" #include "base/run_loop.h" #include "base/test/multiprocess_test.h" #include "base/test/test_timeouts.h" #include "testing/multiprocess_func_list.h" namespace base { namespace android { MULTIPROCESS_TEST_MAIN(BasicMain) { return 0; } MULTIPROCESS_TEST_MAIN(WaitingMain) { base::RunLoop().Run(); return 0; } class ChildProcessTest : public MultiProcessTest {}; // Test disabled due to flakiness: https://crbug.com/950772. TEST_F(ChildProcessTest, DISABLED_ChildHasCleanExit) { Process process = SpawnChild("BasicMain"); int exit_code = 0; EXPECT_TRUE(WaitForMultiprocessTestChildExit( process, TestTimeouts::action_timeout(), &exit_code)); EXPECT_EQ(exit_code, 0); EXPECT_TRUE(MultiProcessTestChildHasCleanExit(process)); } TEST_F(ChildProcessTest, ChildTerminated) { Process process = SpawnChild("WaitingMain"); EXPECT_TRUE(TerminateMultiProcessTestChild(process, 0, true)); EXPECT_FALSE(MultiProcessTestChildHasCleanExit(process)); } } // namespace android } // namespace base
28.348837
73
0.769483
thorium-cfx
5729cb383bf59af6b6ff843255dfd1cf3acd3b8e
5,258
cpp
C++
src/MultiMonteCarloTreeSearch.cpp
renewang/HexGame
21d271091c0b09dd701e1d7b61673ab944e7d45b
[ "MIT" ]
1
2015-05-05T08:35:11.000Z
2015-05-05T08:35:11.000Z
src/MultiMonteCarloTreeSearch.cpp
renewang/HexGame
21d271091c0b09dd701e1d7b61673ab944e7d45b
[ "MIT" ]
null
null
null
src/MultiMonteCarloTreeSearch.cpp
renewang/HexGame
21d271091c0b09dd701e1d7b61673ab944e7d45b
[ "MIT" ]
null
null
null
/* * MultiMonteCarloTreeSearch.cpp * This file declares a Mont Carlo Tree Search implementation for AI player * Created on: Feb 11, 2014 * Author: renewang */ #include "Global.h" #include "LockableGameTree.h" #include "MultiMonteCarloTreeSearch.h" #include <algorithm> #include <boost/thread/detail/memory.hpp> using namespace std; using namespace boost; #if __cplusplus > 199711L MultiMonteCarloTreeSearch::MultiMonteCarloTreeSearch(const HexBoard* board, const Player* aiplayer) : MultiMonteCarloTreeSearch(board, aiplayer, 8, 2048) { } MultiMonteCarloTreeSearch::MultiMonteCarloTreeSearch(const HexBoard* board, const Player* aiplayer, size_t numberofthreads) : MultiMonteCarloTreeSearch(board, aiplayer, numberofthreads, 2048) { } #else MultiMonteCarloTreeSearch::MultiMonteCarloTreeSearch(const HexBoard* board, const Player* aiplayer) : AbstractStrategyImpl(board, aiplayer), mcstimpl(MonteCarloTreeSearch(board, aiplayer)), ptrtoboard(board), ptrtoplayer(aiplayer), numberofthreads(4), numberoftrials(2048) { babywatsoncolor = mcstimpl.babywatsoncolor; oppoenetcolor = mcstimpl.oppoenetcolor; } MultiMonteCarloTreeSearch::MultiMonteCarloTreeSearch(const HexBoard* board, const Player* aiplayer, size_t numberofthreads):AbstractStrategyImpl(board, aiplayer), mcstimpl(MonteCarloTreeSearch(board, aiplayer)), ptrtoboard(board), ptrtoplayer(aiplayer), numberofthreads(numberofthreads), numberoftrials(2048) { babywatsoncolor = mcstimpl.babywatsoncolor; oppoenetcolor = mcstimpl.oppoenetcolor; } #endif MultiMonteCarloTreeSearch::MultiMonteCarloTreeSearch(const HexBoard* board, const Player* aiplayer, size_t numberofthreads, size_t numberoftrials) : AbstractStrategyImpl(board, aiplayer), mcstimpl(MonteCarloTreeSearch(board, aiplayer)), ptrtoboard(board), ptrtoplayer(aiplayer), numberofthreads(numberofthreads), numberoftrials(numberoftrials) { babywatsoncolor = mcstimpl.babywatsoncolor; oppoenetcolor = mcstimpl.oppoenetcolor; } ///Overwritten simulation method. See AbstractStrategy. int MultiMonteCarloTreeSearch::simulation(int currentempty) { hexgame::shared_ptr<bool> emptyglobal; vector<int> bwglobal, oppglobal; initGameState(emptyglobal, bwglobal, oppglobal); LockableGameTree gametree(ptrtoplayer->getViewLabel()); //shared and lockable for (size_t i = 0; i < (numberoftrials / numberofthreads); ++i) { thread_group threads; for (size_t j = 0; j < numberofthreads; ++j) threads.create_thread( boost::bind(boost::mem_fn(&MultiMonteCarloTreeSearch::task), boost::ref(*this), boost::cref(bwglobal), boost::cref(oppglobal), boost::cref(emptyglobal), currentempty, boost::ref(gametree))); assert(threads.size() == numberofthreads); threads.join_all(); } int resultmove = mcstimpl.getBestMove(gametree); //find the move with the maximal successful simulated outcome assert(resultmove != -1); return resultmove; } ///the actual task passed to each thread for execution which contains selection, expansion and backpropagation phases ///@param bwglobal is the moves made by AI player in the current actual game state ///@param oppglobal is the moves made by human player in the current actual game state ///@param emptyglobal stores indicator of a position on the hex board is empty or not which will be modified when a simulated game progresses ///@param currentempty is the current empty hexgons or positions left in the actual game state which will be the number of children nodes of root of game tree ///@param gametree is a game tree object which stores the simulation progress and result ///@return NONE void MultiMonteCarloTreeSearch::task( const std::vector<int>& bwglobal, const std::vector<int>& oppglobal, const hexgame::shared_ptr<bool>& emptyglobal, int currentempty, AbstractGameTree& gametree) { //initialize the following containers to the current progress of playing board vector<int> babywatsons(bwglobal), opponents(oppglobal); hexgame::shared_ptr<bool> emptyindicators = hexgame::shared_ptr<bool>( new bool[ptrtoboard->getSizeOfVertices()], hexgame::default_delete<bool[]>()); copy(emptyglobal.get(), emptyglobal.get() + ptrtoboard->getSizeOfVertices(), emptyindicators.get()); int proportionofempty = currentempty; //in-tree phase pair<int, int> selectresult = mcstimpl.selection(currentempty, gametree); int expandednode = mcstimpl.expansion(selectresult, emptyindicators, proportionofempty, babywatsons, opponents, gametree); //simulation phase int winner = mcstimpl.playout(emptyindicators, proportionofempty, babywatsons, opponents); assert(winner != 0); //back-propagate mcstimpl.backpropagation(expandednode, winner, gametree); }
42.747967
158
0.699696
renewang
572ca03d6bead26129956de432ea288566889b62
317
cpp
C++
src/lib/bios_opencv/filter/grab_frame.cpp
BioBoost/opencv_potty_detector
45700507dc491f899c8d8a2bfa5212fe4310e3e2
[ "MIT" ]
1
2018-02-21T19:00:29.000Z
2018-02-21T19:00:29.000Z
src/lib/bios_opencv/filter/grab_frame.cpp
BioBoost/opencv_potty_detector
45700507dc491f899c8d8a2bfa5212fe4310e3e2
[ "MIT" ]
null
null
null
src/lib/bios_opencv/filter/grab_frame.cpp
BioBoost/opencv_potty_detector
45700507dc491f899c8d8a2bfa5212fe4310e3e2
[ "MIT" ]
null
null
null
#include "grab_frame.h" namespace BiosOpenCV { GrabFrame::GrabFrame(cv::Mat& result, FrameGrabber * frame_grabber) : OutputFilter(result) { this->frame_grabber = frame_grabber; } void GrabFrame::execute(void) { cv::Mat frame = frame_grabber->grab_frame(); frame.copyTo(get_result()); } };
19.8125
69
0.684543
BioBoost
572dd1921403d80652dab4116fffdd442bdb8d6c
507
cpp
C++
1301-1400/1317-Convert Integer to the Sum of Two No-Zero Integers/1317-Convert Integer to the Sum of Two No-Zero Integers.cpp
jiadaizhao/LeetCode
4ddea0a532fe7c5d053ffbd6870174ec99fc2d60
[ "MIT" ]
49
2018-05-05T02:53:10.000Z
2022-03-30T12:08:09.000Z
1301-1400/1317-Convert Integer to the Sum of Two No-Zero Integers/1317-Convert Integer to the Sum of Two No-Zero Integers.cpp
jolly-fellow/LeetCode
ab20b3ec137ed05fad1edda1c30db04ab355486f
[ "MIT" ]
11
2017-12-15T22:31:44.000Z
2020-10-02T12:42:49.000Z
1301-1400/1317-Convert Integer to the Sum of Two No-Zero Integers/1317-Convert Integer to the Sum of Two No-Zero Integers.cpp
jolly-fellow/LeetCode
ab20b3ec137ed05fad1edda1c30db04ab355486f
[ "MIT" ]
28
2017-12-05T10:56:51.000Z
2022-01-26T18:18:27.000Z
class Solution { public: vector<int> getNoZeroIntegers(int n) { int A = 0; bool hasZero = false; do { ++A; hasZero = false; if (to_string(A).find('0') != string::npos) { hasZero = true; } else { if (to_string(n - A).find('0') != string::npos) { hasZero = true; } } } while(hasZero); return {A, n - A}; } };
24.142857
65
0.368836
jiadaizhao
572f0a71176a2bbdded6ad9534af864370daa235
5,922
hpp
C++
common/logging/include/claragenomics/logging/logging.hpp
billchenxi/ClaraGenomicsAnalysis
544effc5881560de6d316f39c47c87014da14d70
[ "Apache-2.0" ]
1
2020-01-21T09:07:02.000Z
2020-01-21T09:07:02.000Z
common/logging/include/claragenomics/logging/logging.hpp
billchenxi/ClaraGenomicsAnalysis
544effc5881560de6d316f39c47c87014da14d70
[ "Apache-2.0" ]
1
2020-12-04T06:24:05.000Z
2020-12-04T06:24:05.000Z
common/logging/include/claragenomics/logging/logging.hpp
billchenxi/ClaraGenomicsAnalysis
544effc5881560de6d316f39c47c87014da14d70
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. * * NVIDIA CORPORATION and its licensors retain all intellectual property * and proprietary rights in and to this software, related documentation * and any modifications thereto. Any use, reproduction, disclosure or * distribution of this software and related documentation without an express * license agreement from NVIDIA CORPORATION is strictly prohibited. */ #pragma once /// \file /// \defgroup logging Internal logging package /// Base docs for the logging package /// This package makes use of SpdLog under the following license: /// /// The MIT License (MIT) /// /// Copyright (c) 2016 Gabi Melman. /// /// 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 <claragenomics/utils/cudaversions.hpp> /// \ingroup logging /// \{ /// \brief DEBUG log level #define cga_log_level_debug 0 /// \brief INFO log level #define cga_log_level_info 1 /// \brief WARN log level #define cga_log_level_warn 2 /// \brief ERROR log level #define cga_log_level_error 3 /// \brief CRITICAL log level #define cga_log_level_critical 4 /// \brief No logging #define cga_log_level_off 5 #ifndef CGA_LOG_LEVEL #ifndef NDEBUG /// \brief Defines the logging level used in the current module #define CGA_LOG_LEVEL cga_log_level_debug #else // NDEBUG /// \brief Defines the logging level used in the current module #define CGA_LOG_LEVEL cga_log_level_error #endif // NDEBUG #endif // CGA_LOG_LEVEL #if CGA_LOG_LEVEL == cga_log_level_info /// \brief Set log level to INFO #define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_INFO #elif CGA_LOG_LEVEL == cga_log_level_debug /// \brief Set log level to DEBUG #define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_DEBUG #elif CGA_LOG_LEVEL == cga_log_level_warn /// \brief Set log level to WARN #define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_WARN #elif CGA_LOG_LEVEL == cga_log_level_error /// \brief Set log level to ERROR #define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_ERROR #elif CGA_LOG_LEVEL == cga_log_level_critical /// \brief Set log level to CRITICAL #define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_CRITICAL #else /// \brief Set log level to OFF #define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_OFF #endif // MUST come after the defines of the logging level! #ifdef CGA_CUDA_BEFORE_9_2 // Due to a header file incompatibility with nvcc in CUDA 9.0 // logging through the logger class in CGA is disabled for any .cu files. #pragma message("Logging disabled for CUDA Toolkit < 9.2") #else #include <spdlog/spdlog.h> #endif namespace claragenomics { namespace logging { /// \ingroup logging /// Logging status type enum class LoggingStatus { success = 0, ///< Success cannot_open_file, ///< Initialization could not open the output file requested cannot_open_stdout ///< Stdout could not be opened for logging }; /// \ingroup logging /// Init Initialize the logging /// \param filename if specified, the path/name of the file into which logging should be placed. /// The default is stdout /// \return success or error status LoggingStatus Init(const char* filename = nullptr); /// \ingroup logging /// SetHeader Adjust the header/preface for each log message /// \param logTime if true, the detailed time will be prepended to each message. /// \param logLocation if true, the file and line location logging will be prepended to each message. /// \return success or error status LoggingStatus SetHeader(bool logTime, bool logLocation); /// \ingroup logging /// \def CGA_LOG_DEBUG /// \brief Log at debug level /// /// parameters as per https://github.com/gabime/spdlog/blob/v1.x/README.md #ifdef CGA_CUDA_BEFORE_9_2 #define CGA_LOG_DEBUG(...) #else #define CGA_LOG_DEBUG(...) SPDLOG_DEBUG(__VA_ARGS__) #endif /// \ingroup logging /// \def CGA_LOG_INFO /// \brief Log at info level /// /// parameters as per https://github.com/gabime/spdlog/blob/v1.x/README.md #ifdef CGA_CUDA_BEFORE_9_2 #define CGA_LOG_INFO(...) #else #define CGA_LOG_INFO(...) SPDLOG_INFO(__VA_ARGS__) #endif /// \ingroup logging /// \def CGA_LOG_WARN /// \brief Log at warning level /// /// parameters as per https://github.com/gabime/spdlog/blob/v1.x/README.md #ifdef CGA_CUDA_BEFORE_9_2 #define CGA_LOG_WARN(...) #else #define CGA_LOG_WARN(...) SPDLOG_WARN(__VA_ARGS__) #endif /// \ingroup logging /// \def CGA_LOG_ERROR /// \brief Log at error level /// /// parameters as per https://github.com/gabime/spdlog/blob/v1.x/README.md #ifdef CGA_CUDA_BEFORE_9_2 #define CGA_LOG_ERROR(...) #else #define CGA_LOG_ERROR(...) SPDLOG_ERROR(__VA_ARGS__) #endif /// \ingroup logging /// \def CGA_LOG_CRITICAL /// \brief Log at fatal/critical error level (does NOT exit) /// /// parameters as per https://github.com/gabime/spdlog/blob/v1.x/README.md #ifdef CGA_CUDA_BEFORE_9_2 #define CGA_LOG_CRITICAL(...) #else #define CGA_LOG_CRITICAL(...) SPDLOG_CRITICAL(__VA_ARGS__) #endif } // namespace logging } // namespace claragenomics /// \}
32.538462
101
0.756839
billchenxi
572fad19e76a2beb0fa39b24f596ad8638156222
566
cpp
C++
myLinuxMonitor/tableview.cpp
Xiang-Pan/HUST_OS_CourseProject
c04a51dd71a30d6f3f1f760c3674ca5fabc29e5f
[ "MIT" ]
4
2020-07-22T15:25:00.000Z
2022-03-27T09:22:31.000Z
myLinuxMonitor/tableview.cpp
HoverWings/HUST_OS_CourseProject
c04a51dd71a30d6f3f1f760c3674ca5fabc29e5f
[ "MIT" ]
null
null
null
myLinuxMonitor/tableview.cpp
HoverWings/HUST_OS_CourseProject
c04a51dd71a30d6f3f1f760c3674ca5fabc29e5f
[ "MIT" ]
null
null
null
/* FileName: tableview.cpp * Author: Hover * E-Mail: hover@hust.edu.cn * GitHub: HoverWings * Description: tableview overload */ #include "tableview.h" #include "tablemodel.h" #include "progressbardelegate.h" TableView::TableView(QWidget *parent) : QTableView(parent) { iniData(); } TableView::~TableView() { delete m_model; } void TableView::iniData() { m_model = new TableModel(); this->setModel(m_model); m_progressBarDelegate = new ProgressBarDelegate(this); this->setItemDelegate(m_progressBarDelegate); }
18.866667
58
0.683746
Xiang-Pan
5732522781098380fce8a3e94688427fd91c611f
2,847
cpp
C++
net/tapi/skywalker/apps/avdialer/avdialer/dialtoolbr.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
net/tapi/skywalker/apps/avdialer/avdialer/dialtoolbr.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
net/tapi/skywalker/apps/avdialer/avdialer/dialtoolbr.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
///////////////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 1997 Active Voice Corporation. All Rights Reserved. // // Active Agent(r) and Unified Communications(tm) are trademarks of Active Voice Corporation. // // Other brand and product names used herein are trademarks of their respective owners. // // The entire program and user interface including the structure, sequence, selection, // and arrangement of the dialog, the exclusively "yes" and "no" choices represented // by "1" and "2," and each dialog message are protected by copyrights registered in // the United States and by international treaties. // // Protected by one or more of the following United States patents: 5,070,526, 5,488,650, // 5,434,906, 5,581,604, 5,533,102, 5,568,540, 5,625,676, 5,651,054. // // Active Voice Corporation // Seattle, Washington // USA // ///////////////////////////////////////////////////////////////////////////////////////// // DialToolBar.cpp : implementation file // #include "stdafx.h" #include "avDialer.h" #include "DialToolBar.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// //Defines #define COMBO_STATUS_WIDTH 250 #define COMBO_STATUS_HEIGHT 100 ///////////////////////////////////////////////////////////////////////////// // CDialToolBar CDialToolBar::CDialToolBar() { } CDialToolBar::~CDialToolBar() { } BEGIN_MESSAGE_MAP(CDialToolBar, CCoolToolBar) //{{AFX_MSG_MAP(CDialToolBar) ON_WM_CREATE() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CDialToolBar message handlers int CDialToolBar::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CCoolToolBar::OnCreate(lpCreateStruct) == -1) return -1; return 0; } void CDialToolBar::Init() { /* CString sButtonText; sButtonText.LoadString(IDS_TOOLBAR_BUTTON_PLACECALL); CToolBar::SetButtonText(0,sButtonText); sButtonText.LoadString(IDS_TOOLBAR_BUTTON_REDIAL); CToolBar::SetButtonText(1,sButtonText); SetButtonStyle(0,TBSTYLE_AUTOSIZE); SetButtonStyle(1,TBSTYLE_DROPDOWN|TBSTYLE_AUTOSIZE); */ /* SetButtonInfo(1, 1001 , TBBS_SEPARATOR, COMBO_STATUS_WIDTH); CRect rect; GetItemRect(1, &rect); rect.top = 3; rect.bottom = rect.top + COMBO_STATUS_HEIGHT; rect.DeflateRect(2,0); //add some border around it if (!m_comboDial.Create(WS_VISIBLE|WS_VSCROLL|CBS_DROPDOWNLIST,//|CBS_SORT, rect, this, 1)) { return; } //Default font for GUI m_comboDial.SendMessage(WM_SETFONT, (WPARAM)GetStockObject(DEFAULT_GUI_FONT)); */ return; }
27.375
94
0.597471
npocmaka
5733eb52abb19370a610a08e87ee52b8a416eaf2
7,885
cpp
C++
Examen3/filosofos_camarero_ex.cpp
Cadiducho/UGR-Sistemas-Concurrentes-Distribuidos
f9d91308a2df93c4b84f630b9a146231027e35dd
[ "MIT" ]
1
2017-12-25T20:15:08.000Z
2017-12-25T20:15:08.000Z
Examen3/filosofos_camarero_ex.cpp
Cadiducho/UGR-Sistemas-Concurrentes-Distribuidos
f9d91308a2df93c4b84f630b9a146231027e35dd
[ "MIT" ]
null
null
null
Examen3/filosofos_camarero_ex.cpp
Cadiducho/UGR-Sistemas-Concurrentes-Distribuidos
f9d91308a2df93c4b84f630b9a146231027e35dd
[ "MIT" ]
null
null
null
#include <mpi.h> #include <thread> #include <random> #include <chrono> #include <iostream> using namespace std; using namespace std::this_thread ; using namespace std::chrono ; const int num_filosofos = 5 , num_procesos = 2*num_filosofos ; const int accion_soltar = 0, accion_coger = 1, accion_sentarse = 2, accion_levantarse = 3; const int accion_coger_cucharilla = 4, accion_soltar_cucharilla = 5, accion_cucharilla_otorgada = 6, accion_cucharilla_devuelta = 7; const int id_camarero = 10; const int id_camarero_postre = 11; template< int min, int max > int aleatorio() { static default_random_engine generador( (random_device())() ); static uniform_int_distribution<int> distribucion_uniforme( min, max ) ; return distribucion_uniforme( generador ); } // --------------------------------------------------------------------- void funcion_filosofos( int id ) { int id_ten_izq = (id+1) % num_procesos, //id. tenedor izq. id_ten_der = (id+num_procesos-1) % num_procesos; //id. tenedor der. MPI_Status estado; while ( true ) { //Solicita sentarse cout << "Filósofo " << id << " solicita sentarse" <<endl; MPI_Send(NULL, 0, MPI_INT, id_camarero, accion_sentarse, MPI_COMM_WORLD); //Espera a tener permiso MPI_Recv(NULL, 0, MPI_INT, id_camarero, accion_sentarse, MPI_COMM_WORLD, &estado); cout << "Filósofo " << id << " se sienta" <<endl; cout << "Filósofo " << id << " solicita ten. izq." <<id_ten_izq <<endl; MPI_Ssend(NULL, 0, MPI_INT, id_ten_izq, accion_coger, MPI_COMM_WORLD); cout << "Filósofo " << id <<" solicita ten. der." <<id_ten_der <<endl; MPI_Ssend(NULL, 0, MPI_INT, id_ten_der, accion_coger, MPI_COMM_WORLD); cout << "Filósofo " << id <<" comienza a comer" <<endl ; sleep_for( milliseconds( aleatorio<10,100>() ) ); cout << "Filósofo " << id <<" suelta ten. izq. " <<id_ten_izq <<endl; MPI_Ssend(NULL, 0, MPI_INT, id_ten_izq, accion_soltar, MPI_COMM_WORLD); cout<< "Filósofo " << id <<" suelta ten. der. " <<id_ten_der <<endl; MPI_Ssend(NULL, 0, MPI_INT, id_ten_der, accion_soltar, MPI_COMM_WORLD); //EXAMEN: Se come un postre cout << "Filósofo " << id << " solicita una cucharilla." <<endl; MPI_Ssend(NULL, 0, MPI_INT, id_camarero_postre, accion_coger_cucharilla, MPI_COMM_WORLD); //espera a tener la cucharilla MPI_Recv(NULL, 0, MPI_INT, id_camarero_postre, accion_cucharilla_otorgada, MPI_COMM_WORLD, &estado); cout << "Filósofo " << id <<" comienza a comerse un postre. " << endl ; sleep_for( milliseconds( aleatorio<10,100>() ) ); cout<< "Filósofo " << id <<" suelta la cucharilla " <<endl; MPI_Ssend(NULL, 0, MPI_INT, id_camarero_postre, accion_soltar_cucharilla, MPI_COMM_WORLD); MPI_Recv(NULL, 0, MPI_INT, id_camarero_postre, accion_cucharilla_devuelta, MPI_COMM_WORLD, &estado); //Se levanta de la mesa y avisa al camarero cout << "Filósofo " << id << " se levanta" <<endl; MPI_Ssend(NULL, 0, MPI_INT, id_camarero, accion_levantarse, MPI_COMM_WORLD); cout << "Filosofo " << id << " comienza a pensar" << endl; sleep_for( milliseconds( aleatorio<10,100>() ) ); } } // --------------------------------------------------------------------- void funcion_tenedores( int id ) { int valor, id_filosofo ; // valor recibido, identificador del filósofo MPI_Status estado ; // metadatos de las dos recepciones while ( true ) { MPI_Recv(&valor, 1, MPI_INT, MPI_ANY_SOURCE, accion_coger, MPI_COMM_WORLD, &estado); id_filosofo = estado.MPI_SOURCE; cout << "Ten. " <<id <<" ha sido cogido por filo. " << id_filosofo << endl; MPI_Recv(&id_filosofo, 1, MPI_INT, id_filosofo, accion_soltar, MPI_COMM_WORLD, &estado); cout << "Ten. "<< id << " ha sido liberado por filo. " << id_filosofo << endl ; } } // --------------------------------------------------------------------- void funcion_camarero( int id ) { int valor; int filosofos_sentados = 0; MPI_Status estado; while (true) { //Si hay 4 filosofos comiendo solo podrá levantarse uno. Si hay menos, también sentarse if (filosofos_sentados < 4) { MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &estado); } else { MPI_Probe(MPI_ANY_SOURCE, accion_levantarse, MPI_COMM_WORLD, &estado); } valor = estado.MPI_SOURCE; if (estado.MPI_TAG == accion_sentarse) { MPI_Recv(NULL, 0, MPI_INT, valor, accion_sentarse, MPI_COMM_WORLD, &estado); filosofos_sentados++; MPI_Send(NULL, 0, MPI_INT, valor, accion_sentarse, MPI_COMM_WORLD); cout << "El filosofo " << valor << " se sienta (" << filosofos_sentados << ")" << endl; } if (estado.MPI_TAG == accion_levantarse) { MPI_Recv(NULL, 0, MPI_INT, valor, accion_levantarse, MPI_COMM_WORLD, &estado); filosofos_sentados--; MPI_Send(NULL, 0, MPI_INT, valor, accion_levantarse, MPI_COMM_WORLD); cout << "El filosofo " << valor << " se levanta (" << filosofos_sentados << ")" << endl; } } } void funcion_camarero_postre(int id) { int valor; int cucharillas_ocupadas = 0; MPI_Status estado; while (true) { //Si hay 3 cucharillas ocupadas sólo podrá soltar. Si no también podrá solicitarlas if (cucharillas_ocupadas < 3) { MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &estado); } else { MPI_Probe(MPI_ANY_SOURCE, accion_soltar_cucharilla, MPI_COMM_WORLD, &estado); } valor = estado.MPI_SOURCE; if (estado.MPI_TAG == accion_coger_cucharilla) { MPI_Recv(NULL, 0, MPI_INT, valor, accion_coger_cucharilla, MPI_COMM_WORLD, &estado); cucharillas_ocupadas++; MPI_Send(NULL, 0, MPI_INT, valor, accion_cucharilla_otorgada, MPI_COMM_WORLD); cout << "El filosofo " << valor << " coge una cucharilla (" << cucharillas_ocupadas << " ocupadas de 3)" << endl; } if (estado.MPI_TAG == accion_soltar_cucharilla) { MPI_Recv(NULL, 0, MPI_INT, valor, accion_soltar_cucharilla, MPI_COMM_WORLD, &estado); cucharillas_ocupadas--; MPI_Send(NULL, 0, MPI_INT, valor, accion_cucharilla_devuelta, MPI_COMM_WORLD); cout << "El filosofo " << valor << " devuelve la cucharilla (" << cucharillas_ocupadas << " ocupadas de 3)" << endl; } } } // --------------------------------------------------------------------- int main( int argc, char** argv ) { int id_propio, num_procesos_actual ; MPI_Init( &argc, &argv ); MPI_Comm_rank( MPI_COMM_WORLD, &id_propio ); MPI_Comm_size( MPI_COMM_WORLD, &num_procesos_actual ); if (num_procesos_actual == 12) { // ejecutar la función correspondiente a 'id_propio' if (id_propio == id_camarero) { funcion_camarero(id_propio); } else if (id_propio == id_camarero_postre) { funcion_camarero_postre(id_propio); } else if (id_propio % 2 == 0) { funcion_filosofos( id_propio ); // es un filósofo } else { // si es impar funcion_tenedores( id_propio ); // es un tenedor } } else { if ( id_propio == 0 ) { // solo el primero escribe error, indep. del rol cout << "el número de procesos esperados es: " << num_procesos + 2 << endl << "el número de procesos en ejecución es: " << num_procesos_actual << endl << "(programa abortado)" << endl ; } } MPI_Finalize( ); return 0; } // ---------------------------------------------------------------------
40.64433
132
0.599493
Cadiducho
5736f5d36bbfafce59a69072822e7e335c6c639a
5,251
hpp
C++
packages/monte_carlo/collision/native/src/MonteCarlo_StandardPhotoatomicReaction.hpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
packages/monte_carlo/collision/native/src/MonteCarlo_StandardPhotoatomicReaction.hpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
packages/monte_carlo/collision/native/src/MonteCarlo_StandardPhotoatomicReaction.hpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
//---------------------------------------------------------------------------// //! //! \file MonteCarlo_StandardPhotoatomicReaction.hpp //! \author Alex Robinson //! \brief The standard photoatomic reaction base class declaration //! //---------------------------------------------------------------------------// #ifndef MONTE_CARLO_STANDARD_PHOTOATOMIC_REACTION_HPP #define MONTE_CARLO_STANDARD_PHOTOATOMIC_REACTION_HPP // Trilinos Includes #include <Teuchos_ArrayRCP.hpp> // FRENSIE Includes #include "MonteCarlo_PhotoatomicReaction.hpp" #include "MonteCarlo_PhotonState.hpp" #include "MonteCarlo_ParticleBank.hpp" #include "Utility_HashBasedGridSearcher.hpp" namespace MonteCarlo{ /*! The standard photoatomic reaction base class * \details Use the InterpPolicy template parameter and the * processed_cross_section template parameter to customize the behavior of * this class. Raw cross section data from the EPDL library would use * a LogLog policy with processed_cross_section = false. Processed cross * section data from an ACE library would use a LogLog policy with * processed_cross_section = true. When data is processed, the policy is used * to indicate how the data was processed. */ template<typename InterpPolicy, bool processed_cross_section> class StandardPhotoatomicReaction : public PhotoatomicReaction { public: //! Basic constructor StandardPhotoatomicReaction( const Teuchos::ArrayRCP<const double>& incoming_energy_grid, const Teuchos::ArrayRCP<const double>& cross_section, const unsigned threshold_energy_index ); //! Constructor StandardPhotoatomicReaction( const Teuchos::ArrayRCP<const double>& incoming_energy_grid, const Teuchos::ArrayRCP<const double>& cross_section, const unsigned threshold_energy_index, const Teuchos::RCP<const Utility::HashBasedGridSearcher>& grid_searcher ); //! Destructor virtual ~StandardPhotoatomicReaction() { /* ... */ } //! Test if the energy falls within the energy grid bool isEnergyWithinEnergyGrid( const double energy ) const; //! Return the cross section at the given energy double getCrossSection( const double energy ) const; //! Return the cross section at the given energy (efficient) double getCrossSection( const double energy, const unsigned bin_index ) const; //! Return the threshold energy double getThresholdEnergy() const; protected: //! Return the head of the energy grid const double* getEnergyGridHead() const; private: // The processed incoming energy grid Teuchos::ArrayRCP<const double> d_incoming_energy_grid; // The processed cross section values evaluated on the incoming e. grid Teuchos::ArrayRCP<const double> d_cross_section; // The threshold energy unsigned d_threshold_energy_index; // The hash-based grid searcher Teuchos::RCP<const Utility::HashBasedGridSearcher> d_grid_searcher; }; //! Partial template specialization for raw data template<typename InterpPolicy> class StandardPhotoatomicReaction<InterpPolicy,false> : public PhotoatomicReaction { public: //! Basic constructor StandardPhotoatomicReaction( const Teuchos::ArrayRCP<const double>& incoming_energy_grid, const Teuchos::ArrayRCP<const double>& cross_section, const unsigned threshold_energy_index ); //! Constructor StandardPhotoatomicReaction( const Teuchos::ArrayRCP<const double>& incoming_energy_grid, const Teuchos::ArrayRCP<const double>& cross_section, const unsigned threshold_energy_index, const Teuchos::RCP<const Utility::HashBasedGridSearcher>& grid_searcher ); //! Destructor virtual ~StandardPhotoatomicReaction() { /* ... */ } //! Test if the energy falls within the energy grid bool isEnergyWithinEnergyGrid( const double energy ) const; //! Return the cross section at the given energy double getCrossSection( const double energy ) const; //! Return the cross section at the given energy (efficient) double getCrossSection( const double energy, const unsigned bin_index ) const; //! Return the threshold energy double getThresholdEnergy() const; protected: //! Return the head of the energy grid const double* getEnergyGridHead() const; private: // The incoming energy grid Teuchos::ArrayRCP<const double> d_incoming_energy_grid; // The cross section values evaluated on the incoming energy grid Teuchos::ArrayRCP<const double> d_cross_section; // The threshold energy const unsigned d_threshold_energy_index; // The hash-based grid searcher Teuchos::RCP<const Utility::HashBasedGridSearcher> d_grid_searcher; }; } // end MonteCarlo namespace //---------------------------------------------------------------------------// // Template Includes. //---------------------------------------------------------------------------// #include "MonteCarlo_StandardPhotoatomicReaction_def.hpp" //---------------------------------------------------------------------------// #endif // end MONTE_CARLO_STANDARD_PHOTOATOMIC_REACTION_HPP //---------------------------------------------------------------------------// // end MonteCarlo_StandardPhotoatomicReaction.hpp //---------------------------------------------------------------------------//
32.81875
82
0.689583
lkersting
573945dbbc052f7a77ec3b1a7ae29ce1374d1f64
1,841
cpp
C++
src/nodes/utility.cpp
csvance/jetson_tensorrt
a406fd4f89352742a03765c5eabc2655442b01cb
[ "MIT" ]
9
2018-10-14T12:06:29.000Z
2019-11-07T02:17:25.000Z
src/nodes/utility.cpp
csvance/jetson_tensorrt
a406fd4f89352742a03765c5eabc2655442b01cb
[ "MIT" ]
10
2018-10-11T00:18:09.000Z
2018-10-25T12:43:40.000Z
src/nodes/utility.cpp
csvance/ros_jetson_tensorrt
a406fd4f89352742a03765c5eabc2655442b01cb
[ "MIT" ]
2
2019-12-28T11:55:57.000Z
2021-02-03T11:01:35.000Z
/** * @file utility.cpp * @author Carroll Vance * @brief Node Utility Functions * * Copyright (c) 2018 Carroll Vance. * * 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 <fstream> #include <streambuf> #include "utility.h" std::vector<std::string> load_class_descriptions(std::string filename) { std::vector<std::string> classes; std::ifstream words_file(filename.c_str()); std::string text((std::istreambuf_iterator<char>(words_file)), std::istreambuf_iterator<char>()); std::string delim = "\n"; auto start = 0U; auto end = text.find(delim); int index = 0; while (end != std::string::npos) { classes.push_back(text.substr(start, end - start)); start = end + delim.length(); end = text.find(delim, start); index++; } return classes; }
33.472727
77
0.716458
csvance
5739c1d6759bbd572e67e59cb1f4569bcd017480
7,905
cpp
C++
libClearCore/src/ShiftRegister.cpp
SSteve/ClearCore-library
5d13647aa1e8045451695bc1b26b5fd745dc16c8
[ "MIT" ]
8
2020-06-25T20:50:59.000Z
2022-02-24T18:52:32.000Z
libClearCore/src/ShiftRegister.cpp
SSteve/ClearCore-library
5d13647aa1e8045451695bc1b26b5fd745dc16c8
[ "MIT" ]
null
null
null
libClearCore/src/ShiftRegister.cpp
SSteve/ClearCore-library
5d13647aa1e8045451695bc1b26b5fd745dc16c8
[ "MIT" ]
8
2020-08-11T00:54:24.000Z
2022-03-05T22:23:24.000Z
/* * Copyright (c) 2020 Teknic, Inc. * * 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. */ /** LED shift register chain implementation Implementation of ClearCore shift register chain for LED displays and connector setups. **/ #include "ShiftRegister.h" #include <sam.h> #include "atomic_utils.h" #include "HardwareMapping.h" #include "SysTiming.h" #include "SysUtils.h" namespace ClearCore { /** Constructs and adjusts inversions for hardware constraints **/ ShiftRegister::ShiftRegister() : m_fastCounter(FAST_COUNTER_PERIOD, FAST_COUNTER_CC), m_breathingCounter(), m_fadeCounter(), m_patternMasks{UINT32_MAX}, m_patternOutputs{SR_UNDERGLOW_MASK}, m_altOutput(0), m_initialized(false), m_blinkCodeActive(false), m_blinkCodeState(false), m_useAltOutput(false), m_pendingOutput(0), m_lastOutput(0) { m_shiftInversions.reg = 0xffffffff; m_shiftInversions.bit.LED_USB = 0; m_shiftInversions.bit.LED_IO_4 = 0; m_shiftInversions.bit.LED_IO_5 = 0; m_shiftInversions.bit.LED_COM_0 = 0; m_shiftInversions.bit.LED_COM_1 = 0; m_shiftInversions.bit.UNDERGLOW = 0; m_shiftInversions.bit.EN_OUT_0 = 0; m_shiftInversions.bit.EN_OUT_1 = 0; m_shiftInversions.bit.EN_OUT_2 = 0; m_shiftInversions.bit.EN_OUT_3 = 0; m_shiftInversions.bit.UART_TTL_0 = 0; m_shiftInversions.bit.UART_TTL_1 = 0; } /** Turn on the shifter and setup the mode for SPI **/ void ShiftRegister::Initialize() { SET_CLOCK_SOURCE(SERCOM6_GCLK_ID_CORE, 5); CLOCK_ENABLE(APBDMASK, SERCOM6_); // Set up pins for SERCOM6 in SPI master mode and enable it to control them PMUX_SELECTION(SR_CLK.gpioPort, SR_CLK.gpioPin, PER_SERCOM); PMUX_ENABLE(SR_CLK.gpioPort, SR_CLK.gpioPin); PMUX_SELECTION(SR_DATA.gpioPort, SR_DATA.gpioPin, PER_SERCOM); PMUX_ENABLE(SR_DATA.gpioPort, SR_DATA.gpioPin); PMUX_SELECTION(SR_DATA_RET.gpioPort, SR_DATA_RET.gpioPin, PER_SERCOM); PMUX_ENABLE(SR_DATA_RET.gpioPort, SR_DATA_RET.gpioPin); // Set up Load/Enable pins as outputs DATA_OUTPUT_STATE(SR_ENn.gpioPort, 1UL << SR_ENn.gpioPin, true); DATA_OUTPUT_STATE(SR_LOAD.gpioPort, 1UL << SR_LOAD.gpioPin, false); DATA_DIRECTION_OUTPUT(SR_ENn.gpioPort, (1UL << SR_ENn.gpioPin)); DATA_DIRECTION_OUTPUT(SR_LOAD.gpioPort, (1UL << SR_LOAD.gpioPin)); // A pointer to the SPI register to make things easier. SercomSpi *sercomSpi = &SERCOM6->SPI; // Disable SERCOM6 to switch its role sercomSpi->CTRLA.bit.ENABLE = 0; SYNCBUSY_WAIT(sercomSpi, SERCOM_SPI_SYNCBUSY_ENABLE); // Sets SERCOM6 to SPI Master mode sercomSpi->CTRLA.reg |= SERCOM_SPI_CTRLA_MODE(0x3); // Sets PAD[3] to DO, PAD[2] to DI, and sets LSB-first transmission sercomSpi->CTRLA.reg |= SERCOM_SPI_CTRLA_DOPO(0x2) | SERCOM_SPI_CTRLA_DIPO(0x2) | SERCOM_SPI_CTRLA_DORD; // Enables the data receiver sercomSpi->CTRLB.bit.RXEN = 1; // Enables 32-bit DATA register transactions sercomSpi->CTRLC.reg |= SERCOM_SPI_CTRLC_DATA32B; // Sets the baud rate to GCLK1 frequency sercomSpi->BAUD.reg = 0; // Enables SERCOM6 and wait for core sync sercomSpi->CTRLA.bit.ENABLE = 1; SYNCBUSY_WAIT(sercomSpi, SERCOM_SPI_SYNCBUSY_ENABLE); // Send the initial values to the chain sercomSpi->DATA.reg = atomic_load_n(&m_patternOutputs[LED_BLINK_IO_SET]) ^ m_shiftInversions.reg; // Generate strobe and update Send(); // Enable the chain, clear and set SR_EN_N DATA_OUTPUT_STATE(SR_ENn.gpioPort, 1UL << SR_ENn.gpioPin, false); // Allow timer tick to update m_initialized = true; } void ShiftRegister::Update() { if (!m_initialized) { return; } // Update Counter Outputs m_patternOutputs[LED_BLINK_FAST_STROBE] = m_fastCounter.Update(); m_patternOutputs[LED_BLINK_BREATHING] = m_breathingCounter.Update(); m_patternOutputs[LED_BLINK_FADE] = m_fadeCounter.Update(); Send(); } void ShiftRegister::Send() { // Wait for TX-complete interrupt flag in case we get here too quickly while (!(SERCOM6->SPI.INTFLAG.bit.TXC)) { continue; } uint32_t output; // Strobe the output with minimum pulse width to display last transfer DATA_OUTPUT_STATE(SR_LOAD.gpioPort, 1UL << SR_LOAD.gpioPin, true); DATA_OUTPUT_STATE(SR_LOAD.gpioPort, 1UL << SR_LOAD.gpioPin, false); while (!(SERCOM6->SPI.INTFLAG.bit.RXC)) { continue; } m_latchedOutput = SERCOM6->SPI.DATA.reg ^ m_shiftInversions.reg; m_lastOutput = m_pendingOutput; if (m_useAltOutput) { output = m_altOutput; } else { // Start the output with the low priority mask output = m_patternOutputs[LED_BLINK_IO_SET]; // Start at 1 to skip the user LEDs for (uint32_t i = LED_BLINK_IO_SET + 1; i < LED_BLINK_CODE_MAX; i++) { // AND in the inverse of the mask to clear out the lower priority // patterns. output &= ~m_patternMasks[i]; // Set the output bits to the output of the pattern output. output |= m_patternOutputs[i] & m_patternMasks[i]; } if (m_blinkCodeActive) { output &= ~SR_UNDERGLOW_MASK; if (m_blinkCodeState) { output |= SR_UNDERGLOW_MASK; } } } m_pendingOutput = output; // Apply inversion output ^= m_shiftInversions.reg; SERCOM6->SPI.DATA.reg = output; } /** Turn all of the LEDs on briefly so the user can see that they all work. **/ void ShiftRegister::DiagnosticLedSweep() { m_altOutput = 0; m_useAltOutput = true; // Illuminate bank 2 for (uint8_t i = 0; i < LED_BANK_2_LEN; i++) { m_altOutput |= LED_BANK_2[i]; Delay_ms(DELAY_TIME); } // Illuminate bank 0 and 1 simultaneously uint8_t largerBankLen = (LED_BANK_1_LEN > LED_BANK_0_LEN) ? LED_BANK_1_LEN : LED_BANK_0_LEN; for (uint8_t i = 0; i < largerBankLen; i++) { if (i < LED_BANK_0_LEN) { m_altOutput |= LED_BANK_0[i]; } if (i < LED_BANK_1_LEN) { m_altOutput |= LED_BANK_1[i]; } Delay_ms(DELAY_TIME); } Delay_ms(50); // Turn them off the same way they were turned on for (uint8_t i = 0; i < LED_BANK_2_LEN; i++) { m_altOutput &= ~LED_BANK_2[i]; Delay_ms(DELAY_TIME); } ShifterStateSet(SR_UNDERGLOW_MASK); for (uint8_t i = 0; i < largerBankLen; i++) { if (i < LED_BANK_0_LEN) { m_altOutput &= ~LED_BANK_0[i]; } if (i < LED_BANK_1_LEN) { m_altOutput &= ~LED_BANK_1[i]; } Delay_ms(DELAY_TIME); } m_useAltOutput = false; } } // ClearCore namespace
32.665289
80
0.672486
SSteve
573f5c01356eb80f9361483fd66c7b9372074c2b
5,011
cpp
C++
src/analysis.cpp
git-steb/structural-deformable-models
4706a65e0dc031d16e259e526fd6a55e805855d1
[ "MIT" ]
2
2017-03-01T20:07:09.000Z
2020-07-12T11:02:21.000Z
src/analysis.cpp
git-steb/structural-deformable-models
4706a65e0dc031d16e259e526fd6a55e805855d1
[ "MIT" ]
null
null
null
src/analysis.cpp
git-steb/structural-deformable-models
4706a65e0dc031d16e259e526fd6a55e805855d1
[ "MIT" ]
null
null
null
//this is a dump of different analysis sources //springconst tuning evaluation { ofstream os("refinestat.txt",ios::app); os << "statistics for shape refinement" << endl; os << "model\tpoint dist\tchamfer\thausdorff" << endl; do{ loadSpecies(m_DBSelector.getCurSpecies()); CHECK_THREAD(DO_ANALYSIS); cout << "hello" << endl; //do analysis here (anahere) Model refmod(*m_Geom); Model omod(*m_Geom); m_GeomMutex.lock(); if(st.getRefModel(m_CSpecies.id, refmod)) { attachBrowseData(); refmod.attachDataset(&m_Data); omod.attachDataset(&m_Data); m_GeomMutex.unlock(); os << "species id: " << m_CSpecies.id << " ppmm = " << m_Data.getPPMM() << endl; cout << "original model" << endl; *m_Geom = omod; m_Geom->adaptProperties(refmod.getProperties()); unsigned long nowticks = getMilliSeconds(); while(getMilliSeconds()-nowticks < 5*1000) CHECK_THREAD(DO_ANALYSIS); // sleep DUMP(refmod.distance(*m_Geom, Model::DIST_POINTS)); DUMP(refmod.distance(*m_Geom, Model::DIST_CPOINTS)); DUMP(refmod.distance(*m_Geom, Model::DIST_HPOINTS)); os << "orig\t" << refmod.distance(*m_Geom, Model::DIST_POINTS) /m_Data.getPPMM()<<"\t" << refmod.distance(*m_Geom, Model::DIST_CPOINTS) /m_Data.getPPMM()<<"\t" << refmod.distance(*m_Geom, Model::DIST_HPOINTS) /m_Data.getPPMM() << endl; cout << "reference model" << endl; *m_Geom = refmod; m_Geom->adaptProperties(refmod.getProperties()); nowticks = getMilliSeconds(); while(getMilliSeconds()-nowticks < 5*1000) CHECK_THREAD(DO_ANALYSIS); // sleep DUMP(refmod.distance(*m_Geom, Model::DIST_POINTS)); DUMP(refmod.distance(*m_Geom, Model::DIST_CPOINTS)); DUMP(refmod.distance(*m_Geom, Model::DIST_HPOINTS)); os << "ref\t" << refmod.distance(*m_Geom, Model::DIST_POINTS) /m_Data.getPPMM()<<"\t" << refmod.distance(*m_Geom, Model::DIST_CPOINTS) /m_Data.getPPMM()<<"\t" << refmod.distance(*m_Geom, Model::DIST_HPOINTS) /m_Data.getPPMM() << endl; static float sscs[] = {0.05, 0.1, 0.2, 0.4, 0.8, 1, 1.3, 1.5, 1.8, 2, 2.5, 3, 4, 5, 7, 10,-1}; for(int ssi = 0; sscs[ssi]>0; ssi++) { float scscale = sscs[ssi]; cout << "master model scscale = "<<scscale<< endl; st.buildMasterModel(scscale); *m_Geom = st.getModel(); m_Geom->adaptProperties(refmod.getProperties()); nowticks = getMilliSeconds(); while(getMilliSeconds()-nowticks < 5*1000) CHECK_THREAD(DO_ANALYSIS); // sleep DUMP(refmod.distance(*m_Geom,Model::DIST_POINTS)); DUMP(refmod.distance(*m_Geom,Model::DIST_CPOINTS)); DUMP(refmod.distance(*m_Geom,Model::DIST_HPOINTS)); os << scscale<<"\t" << refmod.distance(*m_Geom, Model::DIST_POINTS) /m_Data.getPPMM()<<"\t" << refmod.distance(*m_Geom, Model::DIST_CPOINTS) /m_Data.getPPMM()<<"\t" << refmod.distance(*m_Geom, Model::DIST_HPOINTS) /m_Data.getPPMM() << endl; } m_GeomMutex.lock(); } m_GeomMutex.unlock(); if(anastate == -1) { EXIT_THREAD(DO_ANALYSIS); break; } } EXIT_THREAD(DO_ANALYSIS); cout << "analysis terminated" << endl; break; }
52.197917
79
0.4089
git-steb
57451206f19d3a9216145823244259ca05bad775
849
cpp
C++
Source/Testing/tests/LTextureTest.cpp
SirRamEsq/LEngine
24f748a4f9e29cd5d35d012b46e1bc7a2c285f9c
[ "Apache-2.0" ]
1
2020-05-24T14:04:12.000Z
2020-05-24T14:04:12.000Z
Source/Testing/tests/LTextureTest.cpp
SirRamEsq/LEngine
24f748a4f9e29cd5d35d012b46e1bc7a2c285f9c
[ "Apache-2.0" ]
21
2017-09-20T13:39:12.000Z
2018-01-27T22:21:13.000Z
Source/Testing/tests/LTextureTest.cpp
SirRamEsq/LEngine
24f748a4f9e29cd5d35d012b46e1bc7a2c285f9c
[ "Apache-2.0" ]
null
null
null
#include "../../Engine/Kernel.h" #include "../catch.hpp" TEST_CASE("Can Load and Bind Texture", "[resources][texture]") { Kernel::Inst(); auto initialCount = Kernel::rscTexMan.GetSize(); std::string texName = "System/testImage.png"; int expectedW = 72; int expectedH = 72; auto resource = Kernel::rscTexMan.GetLoadItem(texName, texName); REQUIRE(resource != NULL); auto name = resource->GetName(); REQUIRE(name == texName); auto width = resource->GetWidth(); REQUIRE(width == expectedW); auto height = resource->GetHeight(); REQUIRE(height == expectedH); resource->Bind(); auto id = resource->GetOpenGLID(); REQUIRE(id != 0); auto itemCount = Kernel::rscTexMan.GetSize(); REQUIRE(itemCount == initialCount + 1); Kernel::Close(); itemCount = Kernel::rscTexMan.GetSize(); REQUIRE(itemCount == 0); }
23.583333
66
0.669022
SirRamEsq
5749fc279454bcb0b1367f1c9592be679d428efa
558
cpp
C++
Online-Judge-Solution/UVA Solutions/10282(Babelfish).cpp
arifparvez14/Basic-and-competetive-programming
4cb9ee7fbed3c70307d0f63499fcede86ed3c732
[ "MIT" ]
null
null
null
Online-Judge-Solution/UVA Solutions/10282(Babelfish).cpp
arifparvez14/Basic-and-competetive-programming
4cb9ee7fbed3c70307d0f63499fcede86ed3c732
[ "MIT" ]
null
null
null
Online-Judge-Solution/UVA Solutions/10282(Babelfish).cpp
arifparvez14/Basic-and-competetive-programming
4cb9ee7fbed3c70307d0f63499fcede86ed3c732
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { map<string, string> conversion; string temp, second; getline(cin, temp); while (temp.size() !=0) { stringstream ss(temp); ss >> temp >> second; conversion[second] = temp; getline(cin, temp); } while (cin >> temp) { map<string, string>::const_iterator iter = conversion.find(temp); if (iter == conversion.end()) cout << "eh\n"; else cout << iter->second << '\n'; } return 0; }
19.928571
73
0.516129
arifparvez14
574c6c9afe987c406eee9a2359d1f5ce1488a479
4,740
cpp
C++
src/devices/bus/pet/user.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/devices/bus/pet/user.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/devices/bus/pet/user.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:smf /********************************************************************** Commodore PET User Port emulation **********************************************************************/ #include "emu.h" #include "user.h" // class pet_user_port_device DEFINE_DEVICE_TYPE(PET_USER_PORT, pet_user_port_device, "pet_user_port", "PET user port") pet_user_port_device::pet_user_port_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : device_t(mconfig, PET_USER_PORT, tag, owner, clock), device_slot_interface(mconfig, *this), m_2_handler(*this), m_3_handler(*this), m_4_handler(*this), m_5_handler(*this), m_6_handler(*this), m_7_handler(*this), m_8_handler(*this), m_9_handler(*this), m_10_handler(*this), m_b_handler(*this), m_c_handler(*this), m_d_handler(*this), m_e_handler(*this), m_f_handler(*this), m_h_handler(*this), m_j_handler(*this), m_k_handler(*this), m_l_handler(*this), m_m_handler(*this), m_card(nullptr) { } void pet_user_port_device::device_config_complete() { m_card = dynamic_cast<device_pet_user_port_interface *>(get_card_device()); } void pet_user_port_device::device_start() { m_2_handler.resolve_safe(); m_3_handler.resolve_safe(); m_4_handler.resolve_safe(); m_5_handler.resolve_safe(); m_6_handler.resolve_safe(); m_7_handler.resolve_safe(); m_8_handler.resolve_safe(); m_9_handler.resolve_safe(); m_10_handler.resolve_safe(); m_b_handler.resolve_safe(); m_c_handler.resolve_safe(); m_d_handler.resolve_safe(); m_e_handler.resolve_safe(); m_f_handler.resolve_safe(); m_h_handler.resolve_safe(); m_j_handler.resolve_safe(); m_k_handler.resolve_safe(); m_l_handler.resolve_safe(); m_m_handler.resolve_safe(); // pull up m_3_handler(1); m_4_handler(1); m_5_handler(1); m_6_handler(1); m_7_handler(1); m_8_handler(1); m_9_handler(1); m_b_handler(1); m_c_handler(1); m_d_handler(1); m_e_handler(1); m_f_handler(1); m_h_handler(1); m_j_handler(1); m_k_handler(1); m_l_handler(1); m_m_handler(1); } WRITE_LINE_MEMBER( pet_user_port_device::write_2 ) { if (m_card != nullptr) m_card->input_2(state); } WRITE_LINE_MEMBER( pet_user_port_device::write_3 ) { if (m_card != nullptr) m_card->input_3(state); } WRITE_LINE_MEMBER( pet_user_port_device::write_4 ) { if (m_card != nullptr) m_card->input_4(state); } WRITE_LINE_MEMBER( pet_user_port_device::write_5 ) { if (m_card != nullptr) m_card->input_5(state); } WRITE_LINE_MEMBER( pet_user_port_device::write_6 ) { if (m_card != nullptr) m_card->input_6(state); } WRITE_LINE_MEMBER( pet_user_port_device::write_7 ) { if (m_card != nullptr) m_card->input_7(state); } WRITE_LINE_MEMBER( pet_user_port_device::write_8 ) { if (m_card != nullptr) m_card->input_8(state); } WRITE_LINE_MEMBER( pet_user_port_device::write_9 ) { if (m_card != nullptr) m_card->input_9(state); } WRITE_LINE_MEMBER( pet_user_port_device::write_10 ) { if (m_card != nullptr) m_card->input_10(state); } WRITE_LINE_MEMBER( pet_user_port_device::write_b ) { if (m_card != nullptr) m_card->input_b(state); } WRITE_LINE_MEMBER( pet_user_port_device::write_c ) { if (m_card != nullptr) m_card->input_c(state); } WRITE_LINE_MEMBER( pet_user_port_device::write_d ) { if (m_card != nullptr) m_card->input_d(state); } WRITE_LINE_MEMBER( pet_user_port_device::write_e ) { if (m_card != nullptr) m_card->input_e(state); } WRITE_LINE_MEMBER( pet_user_port_device::write_f ) { if (m_card != nullptr) m_card->input_f(state); } WRITE_LINE_MEMBER( pet_user_port_device::write_h ) { if (m_card != nullptr) m_card->input_h(state); } WRITE_LINE_MEMBER( pet_user_port_device::write_j ) { if (m_card != nullptr) m_card->input_j(state); } WRITE_LINE_MEMBER( pet_user_port_device::write_k ) { if (m_card != nullptr) m_card->input_k(state); } WRITE_LINE_MEMBER( pet_user_port_device::write_l ) { if (m_card != nullptr) m_card->input_l(state); } WRITE_LINE_MEMBER( pet_user_port_device::write_m ) { if (m_card != nullptr) m_card->input_m(state); } // class device_pet_user_port_interface device_pet_user_port_interface::device_pet_user_port_interface(const machine_config &mconfig, device_t &device) : device_interface(device, "petuser") { m_slot = dynamic_cast<pet_user_port_device *>(device.owner()); } device_pet_user_port_interface::~device_pet_user_port_interface() { } #include "diag.h" #include "petuja.h" #include "cb2snd.h" #include "2joysnd.h" void pet_user_port_cards(device_slot_interface &device) { device.option_add("diag", PET_USERPORT_DIAGNOSTIC_CONNECTOR); device.option_add("petuja", PET_USERPORT_JOYSTICK_ADAPTER); device.option_add("cb2snd", PET_USERPORT_CB2_SOUND_DEVICE); device.option_add("2joysnd", PET_USERPORT_JOYSTICK_AND_SOUND_DEVICE); }
35.111111
125
0.741772
Robbbert
574d4b9576b1f94fa65372186f91603b835ca3a7
26,098
cpp
C++
source/script/compiler.cpp
evanbowman/skyland
a62827a0dbcab705ba8ddf75cb74e975ceadec39
[ "MIT" ]
24
2021-07-03T02:27:25.000Z
2022-03-29T05:21:32.000Z
source/script/compiler.cpp
evanbowman/skyland
a62827a0dbcab705ba8ddf75cb74e975ceadec39
[ "MIT" ]
3
2021-09-24T18:52:49.000Z
2021-11-13T00:16:47.000Z
source/script/compiler.cpp
evanbowman/skyland
a62827a0dbcab705ba8ddf75cb74e975ceadec39
[ "MIT" ]
1
2021-07-11T08:05:59.000Z
2021-07-11T08:05:59.000Z
#include "bytecode.hpp" #include "lisp.hpp" #include "number/endian.hpp" namespace lisp { Value* make_bytecode_function(Value* bytecode); u16 symbol_offset(const char* symbol); int compile_impl(ScratchBuffer& buffer, int write_pos, Value* code, int jump_offset, bool tail_expr); template <typename Instruction> static Instruction* append(ScratchBuffer& buffer, int& write_pos) { if (write_pos + sizeof(Instruction) >= SCRATCH_BUFFER_SIZE) { // FIXME: propagate error! We should return nullptr, but the caller does // not check the return value yet. Now, a lambda that takes up 2kb of // bytecode seems highly unlikely in the first place, but you never know // I guess... while (true) ; } auto result = (Instruction*)(buffer.data_ + write_pos); result->header_.op_ = Instruction::op(); write_pos += sizeof(Instruction); return result; } int compile_lambda(ScratchBuffer& buffer, int write_pos, Value* code, int jump_offset) { bool first = true; auto lat = code; while (lat not_eq get_nil()) { if (lat->type() not_eq Value::Type::cons) { // error... break; } if (not first) { append<instruction::Pop>(buffer, write_pos); } else { first = false; } bool tail_expr = lat->cons().cdr() == get_nil(); write_pos = compile_impl( buffer, write_pos, lat->cons().car(), jump_offset, tail_expr); lat = lat->cons().cdr(); } append<instruction::Ret>(buffer, write_pos); return write_pos; } int compile_quoted(ScratchBuffer& buffer, int write_pos, Value* code, bool tail_expr) { if (code->type() == Value::Type::integer) { write_pos = compile_impl(buffer, write_pos, code, 0, tail_expr); } else if (code->type() == Value::Type::symbol) { auto inst = append<instruction::PushSymbol>(buffer, write_pos); inst->name_offset_.set(symbol_offset(code->symbol().name_)); } else if (code->type() == Value::Type::cons) { int list_len = 0; while (code not_eq get_nil()) { if (code->type() not_eq Value::Type::cons) { // ... break; } write_pos = compile_quoted( buffer, write_pos, code->cons().car(), tail_expr); code = code->cons().cdr(); list_len++; if (list_len == 255) { // FIXME: raise error! while (true) ; } } auto inst = append<instruction::PushList>(buffer, write_pos); inst->element_count_ = list_len; } return write_pos; } int compile_let(ScratchBuffer& buffer, int write_pos, Value* code, int jump_offset, bool tail_expr) { if (code->type() not_eq Value::Type::cons) { while (true) ; // TODO: raise error } const auto binding_count = length(code->cons().car()); if (binding_count not_eq 0) { append<instruction::LexicalFramePush>(buffer, write_pos); } foreach (code->cons().car(), [&](Value* val) { if (val->type() == Value::Type::cons) { auto sym = val->cons().car(); auto bind = val->cons().cdr(); if (sym->type() == Value::Type::symbol and bind->type() == Value::Type::cons) { write_pos = compile_impl( buffer, write_pos, bind->cons().car(), jump_offset, false); auto inst = append<instruction::LexicalDef>(buffer, write_pos); inst->name_offset_.set(symbol_offset(sym->symbol().name_)); } } }) ; code = code->cons().cdr(); while (code not_eq get_nil()) { bool tail = tail_expr and code->cons().cdr() == get_nil(); write_pos = compile_impl( buffer, write_pos, code->cons().car(), jump_offset, tail); code = code->cons().cdr(); } if (binding_count not_eq 0) { append<instruction::LexicalFramePop>(buffer, write_pos); } return write_pos; } int compile_impl(ScratchBuffer& buffer, int write_pos, Value* code, int jump_offset, bool tail_expr) { if (code->type() == Value::Type::nil) { append<instruction::PushNil>(buffer, write_pos); } else if (code->type() == Value::Type::integer) { if (code->integer().value_ == 0) { append<instruction::Push0>(buffer, write_pos); } else if (code->integer().value_ == 1) { append<instruction::Push1>(buffer, write_pos); } else if (code->integer().value_ == 2) { append<instruction::Push2>(buffer, write_pos); } else if (code->integer().value_ < 127 and code->integer().value_ > -127) { append<instruction::PushSmallInteger>(buffer, write_pos)->value_ = code->integer().value_; } else { append<instruction::PushInteger>(buffer, write_pos) ->value_.set(code->integer().value_); } } else if (code->type() == Value::Type::string) { const auto str = code->string().value(); const auto len = str_len(str); append<instruction::PushString>(buffer, write_pos)->length_ = len + 1; if (write_pos + len + 1 >= SCRATCH_BUFFER_SIZE) { while (true) ; } for (u32 i = 0; i < len; ++i) { *(buffer.data_ + write_pos++) = str[i]; } *(buffer.data_ + write_pos++) = '\0'; } else if (code->type() == Value::Type::symbol) { if (code->symbol().name_[0] == '$' and code->symbol().name_[1] not_eq 'V') { s32 argn = 0; for (u32 i = 1; code->symbol().name_[i] not_eq '\0'; ++i) { argn = argn * 10 + (code->symbol().name_[i] - '0'); } switch (argn) { case 0: append<instruction::Arg0>(buffer, write_pos); break; case 1: append<instruction::Arg1>(buffer, write_pos); break; case 2: append<instruction::Arg2>(buffer, write_pos); break; default: append<instruction::PushSmallInteger>(buffer, write_pos) ->value_ = argn; append<instruction::Arg>(buffer, write_pos); break; } } else { append<instruction::LoadVar>(buffer, write_pos) ->name_offset_.set(symbol_offset(code->symbol().name_)); } } else if (code->type() == Value::Type::cons) { auto lat = code; auto fn = lat->cons().car(); if (fn->type() == Value::Type::symbol and str_cmp(fn->symbol().name_, "let") == 0) { write_pos = compile_let( buffer, write_pos, lat->cons().cdr(), jump_offset, tail_expr); } else if (fn->type() == Value::Type::symbol and str_cmp(fn->symbol().name_, "if") == 0) { lat = lat->cons().cdr(); if (lat->type() not_eq Value::Type::cons) { while (true) ; // TODO: raise error! } write_pos = compile_impl( buffer, write_pos, lat->cons().car(), jump_offset, false); auto jne = append<instruction::JumpIfFalse>(buffer, write_pos); auto true_branch = get_nil(); auto false_branch = get_nil(); if (lat->cons().cdr()->type() == Value::Type::cons) { true_branch = lat->cons().cdr()->cons().car(); if (lat->cons().cdr()->cons().cdr()->type() == Value::Type::cons) { false_branch = lat->cons().cdr()->cons().cdr()->cons().car(); } } write_pos = compile_impl( buffer, write_pos, true_branch, jump_offset, tail_expr); auto jmp = append<instruction::Jump>(buffer, write_pos); jne->offset_.set(write_pos - jump_offset); write_pos = compile_impl( buffer, write_pos, false_branch, jump_offset, tail_expr); jmp->offset_.set(write_pos - jump_offset); } else if (fn->type() == Value::Type::symbol and str_cmp(fn->symbol().name_, "lambda") == 0) { lat = lat->cons().cdr(); if (lat->type() not_eq Value::Type::cons) { while (true) ; // TODO: raise error! } auto lambda = append<instruction::PushLambda>(buffer, write_pos); // TODO: compile multiple nested expressions! FIXME... pretty broken. write_pos = compile_impl(buffer, write_pos, lat->cons().car(), jump_offset + write_pos, false); append<instruction::Ret>(buffer, write_pos); lambda->lambda_end_.set(write_pos - jump_offset); } else if (fn->type() == Value::Type::symbol and str_cmp(fn->symbol().name_, "'") == 0) { write_pos = compile_quoted(buffer, write_pos, lat->cons().cdr(), tail_expr); } else if (fn->type() == Value::Type::symbol and str_cmp(fn->symbol().name_, "`") == 0) { while (true) ; // TODO: Implement quasiquote for compiled code. } else { u8 argc = 0; lat = lat->cons().cdr(); // Compile each function arument while (lat not_eq get_nil()) { if (lat->type() not_eq Value::Type::cons) { // ... break; } write_pos = compile_impl( buffer, write_pos, lat->cons().car(), jump_offset, false); lat = lat->cons().cdr(); argc++; if (argc == 255) { // FIXME: raise error! while (true) ; } } if (fn->type() == Value::Type::symbol and str_cmp(fn->symbol().name_, "cons") == 0 and argc == 2) { append<instruction::MakePair>(buffer, write_pos); } else if (fn->type() == Value::Type::symbol and str_cmp(fn->symbol().name_, "car") == 0 and argc == 1) { append<instruction::First>(buffer, write_pos); } else if (fn->type() == Value::Type::symbol and str_cmp(fn->symbol().name_, "cdr") == 0 and argc == 1) { append<instruction::Rest>(buffer, write_pos); } else if (fn->type() == Value::Type::symbol and str_cmp(fn->symbol().name_, "arg") == 0 and argc == 1) { append<instruction::Arg>(buffer, write_pos); } else if (fn->type() == Value::Type::symbol and str_cmp(fn->symbol().name_, "this") == 0 and argc == 0) { append<instruction::PushThis>(buffer, write_pos); } else if (fn->type() == Value::Type::symbol and str_cmp(fn->symbol().name_, "not") == 0 and argc == 1) { append<instruction::Not>(buffer, write_pos); } else { write_pos = compile_impl(buffer, write_pos, fn, jump_offset, false); if (tail_expr) { switch (argc) { case 1: append<instruction::TailCall1>(buffer, write_pos); break; case 2: append<instruction::TailCall2>(buffer, write_pos); break; case 3: append<instruction::TailCall3>(buffer, write_pos); break; default: append<instruction::TailCall>(buffer, write_pos) ->argc_ = argc; break; } } else { switch (argc) { case 1: append<instruction::Funcall1>(buffer, write_pos); break; case 2: append<instruction::Funcall2>(buffer, write_pos); break; case 3: append<instruction::Funcall3>(buffer, write_pos); break; default: append<instruction::Funcall>(buffer, write_pos)->argc_ = argc; break; } } } } } else { append<instruction::PushNil>(buffer, write_pos); } return write_pos; } void live_values(::Function<24, void(Value&)> callback); class PeepholeOptimizer { public: template <typename U, typename T> void replace(ScratchBuffer& code_buffer, U& dest, T& source, u32& code_size) { static_assert(sizeof dest > sizeof source); memcpy(&dest, &source, sizeof source); auto diff = (sizeof dest) - (sizeof source); const int start = ((u8*)&dest - (u8*)code_buffer.data_) + sizeof source; for (u32 i = start; i < code_size - diff; ++i) { code_buffer.data_[i] = code_buffer.data_[i + diff]; } code_size -= diff; fixup_jumps(code_buffer, start, -diff); } u32 run(ScratchBuffer& code_buffer, u32 code_size) { int index = 0; while (true) { using namespace instruction; auto inst = load_instruction(code_buffer, index); switch (inst->op_) { case PushLambda::op(): // FIXME! We do not support optimization yet when there are // nested lambda definitions, we need to carefully adjust the // jump instruction coordinates in these cases, as jumps are // relative to the beginning of the lambda. return code_size; case Ret::op(): goto TOP; default: ++index; break; } } TOP: index = 0; while (true) { using namespace instruction; auto inst = load_instruction(code_buffer, index); switch (inst->op_) { case Ret::op(): return code_size; case PushLambda::op(): return code_size; case PushSmallInteger::op(): { if (index > 0) { auto prev = load_instruction(code_buffer, index - 1); if (prev->op_ == PushSmallInteger::op()) { if (((PushSmallInteger*)prev)->value_ == ((PushSmallInteger*)inst)->value_) { Dup d; d.header_.op_ = Dup::op(); replace(code_buffer, *(PushSmallInteger*)inst, d, code_size); goto TOP; } } else if (prev->op_ == Dup::op()) { int backtrack = index - 2; while (backtrack > 0) { auto it = load_instruction(code_buffer, backtrack); if (it->op_ == Dup::op()) { --backtrack; } else if (it->op_ == PushSmallInteger::op()) { if (((PushSmallInteger*)it)->value_ == ((PushSmallInteger*)inst)->value_) { Dup d; d.header_.op_ = Dup::op(); replace(code_buffer, *(PushSmallInteger*)inst, d, code_size); // code_size -= sizeof(PushSmallInteger) - sizeof(Dup); goto TOP; } } else { break; } } } } ++index; break; } case SmallJump::op(): { SmallJump* sj = (SmallJump*)inst; if (code_buffer.data_[sj->offset_] == Ret::op() or code_buffer.data_[sj->offset_] == EarlyRet::op()) { // A jump to a return instruction can be replaced with a return // instruction. EarlyRet r; r.header_.op_ = EarlyRet::op(); replace(code_buffer, *sj, r, code_size); goto TOP; } else { ++index; } break; } case PushInteger::op(): { if (index > 0) { auto prev = load_instruction(code_buffer, index - 1); if (prev->op_ == PushInteger::op()) { if (((PushInteger*)prev)->value_.get() == ((PushInteger*)inst)->value_.get()) { Dup d; d.header_.op_ = Dup::op(); replace( code_buffer, *(PushInteger*)inst, d, code_size); goto TOP; } } else if (prev->op_ == Dup::op()) { int backtrack = index - 2; while (backtrack > 0) { auto it = load_instruction(code_buffer, backtrack); if (it->op_ == Dup::op()) { --backtrack; } else if (it->op_ == PushInteger::op()) { if (((PushInteger*)it)->value_.get() == ((PushInteger*)inst)->value_.get()) { Dup d; d.header_.op_ = Dup::op(); replace(code_buffer, *(PushInteger*)inst, d, code_size); goto TOP; } } else { break; } } } } ++index; break; } case Jump::op(): if (((Jump*)inst)->offset_.get() < 255) { SmallJump j; j.header_.op_ = SmallJump::op(); j.offset_ = ((Jump*)inst)->offset_.get(); replace(code_buffer, *(Jump*)inst, j, code_size); goto TOP; } ++index; break; case JumpIfFalse::op(): if (((JumpIfFalse*)inst)->offset_.get() < 255) { SmallJumpIfFalse j; j.header_.op_ = SmallJumpIfFalse::op(); j.offset_ = ((JumpIfFalse*)inst)->offset_.get(); replace(code_buffer, *(JumpIfFalse*)inst, j, code_size); goto TOP; } ++index; break; default: index++; break; } } } // We have just inserted/removed an instruction, and now need to scan // through the bytecode, and adjust the offsets of local jumps within the // lambda definition. void fixup_jumps(ScratchBuffer& code_buffer, int inflection_point, int size_diff) { int index = 0; int depth = 0; struct LambdaInfo { int start_ = 0; }; Buffer<LambdaInfo, 15> function_stack; function_stack.push_back({0}); while (true) { using namespace instruction; auto inst = load_instruction(code_buffer, index); switch (inst->op_) { case PushLambda::op(): ++depth; if (((PushLambda*)inst)->lambda_end_.get() > inflection_point) { auto end = ((PushLambda*)inst)->lambda_end_.get(); ((PushLambda*)inst)->lambda_end_.set(end + size_diff); } ++index; break; case Ret::op(): if (depth == 0) { return; } --depth; ++index; break; case Jump::op(): if (((Jump*)inst)->offset_.get() > inflection_point) { auto offset = ((Jump*)inst)->offset_.get(); ((Jump*)inst)->offset_.set(offset + size_diff); } ++index; break; case JumpIfFalse::op(): if (((JumpIfFalse*)inst)->offset_.get() > inflection_point) { auto offset = ((JumpIfFalse*)inst)->offset_.get(); ((JumpIfFalse*)inst)->offset_.set(offset + size_diff); } ++index; break; case SmallJump::op(): if (((SmallJump*)inst)->offset_ > inflection_point) { auto offset = ((SmallJump*)inst)->offset_; ((SmallJump*)inst)->offset_ = offset + size_diff; } ++index; break; case SmallJumpIfFalse::op(): if (((SmallJumpIfFalse*)inst)->offset_ > inflection_point) { auto offset = ((SmallJumpIfFalse*)inst)->offset_; ((SmallJumpIfFalse*)inst)->offset_ = offset + size_diff; } ++index; break; default: ++index; break; } } } }; void compile(Platform& pfrm, Value* code) { // We will be rendering all of our compiled code into this buffer. push_op(make_databuffer(pfrm)); if (get_op(0)->type() not_eq Value::Type::data_buffer) { return; } push_op(make_cons(make_integer(0), get_op(0))); if (get_op(0)->type() not_eq Value::Type::cons) { return; } auto fn = make_bytecode_function(get_op(0)); if (fn->type() not_eq Value::Type::function) { pop_op(); pop_op(); auto err = fn; push_op(err); return; } pop_op(); auto buffer = get_op(0)->data_buffer().value(); pop_op(); push_op(fn); __builtin_memset(buffer->data_, 0, sizeof buffer->data_); int write_pos = 0; write_pos = compile_lambda(*buffer, write_pos, code, 0); write_pos = PeepholeOptimizer().run( *fn->function().bytecode_impl_.databuffer()->data_buffer().value(), write_pos); // std::cout << "compilation finished, bytes used: " << write_pos << // std::endl; // OK, so now, we've successfully compiled our function into the scratch // buffer. But, what about all the extra space in the buffer!? So we're // going to scan over all of the interpreter's allocated memory, and // collapse our own bytecode into a previously allocated slab of bytecode, // if possible. const int bytes_used = write_pos; bool done = false; live_values([fn, &done, bytes_used](Value& val) { if (done) { return; } if (fn not_eq &val and val.type() == Value::Type::function and val.hdr_.mode_bits_ == Function::ModeBits::lisp_bytecode_function) { auto buf = val.function().bytecode_impl_.databuffer(); int used = SCRATCH_BUFFER_SIZE - 1; for (; used > 0; --used) { if ((Opcode)buf->data_buffer().value()->data_[used] not_eq instruction::Fatal::op()) { ++used; break; } } const int remaining = SCRATCH_BUFFER_SIZE - used; if (remaining >= bytes_used) { done = true; // std::cout << "found another buffer with remaining space: " // << remaining // << ", copying " << bytes_used // << " bytes to dest buffer offset " // << used; auto src_buffer = fn->function().bytecode_impl_.databuffer(); for (int i = 0; i < bytes_used; ++i) { buf->data_buffer().value()->data_[used + i] = src_buffer->data_buffer().value()->data_[i]; } Protected used_bytes(make_integer(used)); fn->function().bytecode_impl_.bytecode_ = compr(make_cons(used_bytes, buf)); } } }); } } // namespace lisp
32.339529
91
0.447659
evanbowman
574e9007b67248a726cb0aa08f00be1de23401e3
993
cpp
C++
UVa Online Judge/11536.cpp
xiezeju/ACM-Code-Archives
db135ed0953adcf5c7ab37a00b3f9458291ce0d7
[ "MIT" ]
1
2022-02-24T12:44:30.000Z
2022-02-24T12:44:30.000Z
UVa Online Judge/11536.cpp
xiezeju/ACM-Code-Archives
db135ed0953adcf5c7ab37a00b3f9458291ce0d7
[ "MIT" ]
null
null
null
UVa Online Judge/11536.cpp
xiezeju/ACM-Code-Archives
db135ed0953adcf5c7ab37a00b3f9458291ce0d7
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> ii; typedef vector<int> vi; typedef vector<ii> vii; const int INF = 1e9; const long long LLINF = 4e18; const double EPS = 1e-9; const int maxn = 1e6 + 10; int a[maxn]={},f[maxn]={}; int main() { ios::sync_with_stdio(false); int t;cin>>t; int x=1; while(t--){ memset(f,0,sizeof f); int n,m,k;cin>>n>>m>>k; int ans = INF; a[1] = 1,a[2] = 2,a[3] = 3; for(int i=4;i<=n;i++) a[i]=(a[i-1]+a[i-2]+a[i-3])%m+1; int l=1,r=1,cnt=0; while(l<=r&&r<=n){ if(cnt!=k) { if(!f[a[r]]&&a[r]<=k) cnt++; f[a[r++]]++; } else { ans=min(ans,r-l); f[a[l]]--; if(!f[a[l]]&&a[l]<=k) cnt--; l++; } //cout<<l<<" "<<r<<endl; } if(ans==INF) printf("Case %d: sequence nai\n",x++); else printf("Case %d: %d\n",x++,ans); } return 0; }
19.470588
57
0.449144
xiezeju
575270c2f184dbb4b32f47c6accdf3526f8a4cd4
1,411
hpp
C++
src/nnfusion/core/operators/op_define/variable.hpp
lynex/nnfusion
6332697c71b6614ca6f04c0dac8614636882630d
[ "MIT" ]
639
2020-09-05T10:00:59.000Z
2022-03-30T08:42:39.000Z
src/nnfusion/core/operators/op_define/variable.hpp
QPC-database/nnfusion
99ada47c50f355ca278001f11bc752d1c7abcee2
[ "MIT" ]
252
2020-09-09T05:35:36.000Z
2022-03-29T04:58:41.000Z
src/nnfusion/core/operators/op_define/variable.hpp
QPC-database/nnfusion
99ada47c50f355ca278001f11bc752d1c7abcee2
[ "MIT" ]
104
2020-09-05T10:01:08.000Z
2022-03-23T10:59:13.000Z
//***************************************************************************** // Copyright 2017-2020 Intel 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. //***************************************************************************** // Microsoft (c) 2019, NNFusion Team #pragma once #include "../util/tensor_op.hpp" namespace nnfusion { namespace op { /// \brief Class for variables. /// class Variable : public TensorOp { public: /// \brief Constructions a tensor view-typed variable node. /// /// \param element_type The element type of the variable. /// \param pshape The partial shape of the variable. Variable(const nnfusion::element::Type& element_type, const nnfusion::Shape& shape); bool is_variable() const override { return true; } }; } }
34.414634
96
0.584692
lynex
5754e94d5e3d00b985e1da1dfba001c4f78881c6
2,201
cpp
C++
leetcode/intersection.cpp
Mantissa-23/miniprojects
552b1329cc44b5036d1bc8c12dc83b802b18da29
[ "MIT" ]
null
null
null
leetcode/intersection.cpp
Mantissa-23/miniprojects
552b1329cc44b5036d1bc8c12dc83b802b18da29
[ "MIT" ]
null
null
null
leetcode/intersection.cpp
Mantissa-23/miniprojects
552b1329cc44b5036d1bc8c12dc83b802b18da29
[ "MIT" ]
null
null
null
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include <unordered_map> #include "doctest.h" using namespace std; // Using hashmaps /* class Solution { */ /* public: */ /* vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { */ /* unordered_map<int, int> set1, set2; */ /* for(const int& i : nums1) { */ /* if(set1.find(i) == set1.end()) { */ /* set1[i] = 1; */ /* } */ /* else */ /* set1[i]++; */ /* } */ /* for(const int& i : nums2) { */ /* if(set1.find(i) != set1.end()) { */ /* if(set2.find(i) == set2.end()) */ /* set2[i] = 1; */ /* else if(set2[i] < set1[i]) */ /* set2[i]++; */ /* } */ /* } */ /* vector<int> ret; */ /* for(auto it = set2.begin(); it != set2.end(); it++) { */ /* for(int i = 0; i < it->second; i++) { */ /* ret.push_back(it->first); */ /* } */ /* } */ /* return ret; */ /* } */ /* }; */ class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); vector<int> ret; for(auto i = nums1.begin(), j = nums2.begin(); i != nums1.end() && j != nums2.end();) { if(*i == *j) { ret.push_back(*i); i++; j++; } else if (*i < *j) i++; else j++; } return ret; } }; TEST_CASE("tests") { Solution s; vector<int> arr1; vector<int> arr2; vector<int> soln; SUBCASE("1") { arr1 = {1, 2, 2, 1}; arr2 = {2, 2}; soln = {2, 2}; } SUBCASE("2") { arr1 = {4,9,5}; arr2 = {9,4,9,8,4}; soln = {4,9}; } SUBCASE("empties") { arr1 = {}; arr2 = {1,2,3}; soln = {}; } SUBCASE("empties2") { arr1 = {1,2,3}; arr2 = {}; soln = {}; } SUBCASE("single_item_nonintersecting") { arr1 = {1}; arr2 = {2}; soln = {}; } SUBCASE("single_item_intersecting") { arr1 = {1}; arr2 = {1}; soln = {1}; } CHECK(s.intersect(arr1, arr2) == soln); }
21.792079
93
0.419809
Mantissa-23
57575ee784fca90ef995e8c1c221255cbf37b42c
3,064
cpp
C++
reconstruction/gadgetron/CS_LAB_Gadget/src/RETRO/CS_Retro_ImageCombinerGadget.cpp
alwaysbefun123/CS_MoCo_LAB
a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b
[ "BSD-2-Clause" ]
83
2017-08-11T09:18:17.000Z
2022-01-23T03:08:00.000Z
reconstruction/gadgetron/CS_LAB_Gadget/src/RETRO/CS_Retro_ImageCombinerGadget.cpp
MrYuwan/CS_MoCo_LAB
a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b
[ "BSD-2-Clause" ]
4
2017-09-19T23:02:12.000Z
2020-11-23T11:25:18.000Z
reconstruction/gadgetron/CS_LAB_Gadget/src/RETRO/CS_Retro_ImageCombinerGadget.cpp
MrYuwan/CS_MoCo_LAB
a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b
[ "BSD-2-Clause" ]
49
2017-03-19T18:41:55.000Z
2021-11-25T08:25:44.000Z
#include "CS_Retro_ImageCombinerGadget.h" #include <mri_core_data.h> using namespace Gadgetron; // class constructor CS_Retro_ImageCombinerGadget::CS_Retro_ImageCombinerGadget() { } // class destructor CS_Retro_ImageCombinerGadget::~CS_Retro_ImageCombinerGadget() { delete data_; } int CS_Retro_ImageCombinerGadget::process_config(ACE_Message_Block *mb) { return GADGET_OK; } int CS_Retro_ImageCombinerGadget::process(GadgetContainerMessage<ISMRMRD::ImageHeader> *m1, GadgetContainerMessage<hoNDArray<std::complex<float> > > *m2) { // receive [x y z resp_phases card_phases] hoNDArray<std::complex<float> > &received_data = *m2->getObjectPtr(); // handle first initialization if (data_ == NULL) { // create header for return message return_message_ = new GadgetContainerMessage<ISMRMRD::ImageHeader>(); fCopyImageHeader(return_message_, m1->getObjectPtr()); number_of_respiratory_phases_ = get_number_of_gates(m1->getObjectPtr()->user_int[0], 0); number_of_cardiac_phases_ = get_number_of_gates(m1->getObjectPtr()->user_int[0], 1); // just pass if whole data is processed at once if (received_data.get_size(3) == number_of_respiratory_phases_ && received_data.get_size(4) == number_of_cardiac_phases_) { GINFO("Whole data was processed at once, so nothing has to be combined. Gadget is bypassed.\n"); // put data on pipeline if (this->next()->putq(m1) < 0) { return GADGET_FAIL; } return GADGET_OK; } // order of array: [x y z resp_phases card_phases] data_ = new hoNDArray<std::complex<float> >(received_data.get_size(0), received_data.get_size(1), received_data.get_size(2), number_of_respiratory_phases_, number_of_cardiac_phases_); } // get current image position (which phase?) const unsigned int current_resp_phase = m1->getObjectPtr()->image_index; const unsigned int current_card_phase = m1->getObjectPtr()->image_series_index; // copy data to position const vector_td<size_t, 5> fill_offset = { static_cast<size_t>(0), static_cast<size_t>(0), static_cast<size_t>(0), current_resp_phase, current_card_phase }; fill(received_data, fill_offset, *data_); // increase receive counter receive_counter_ += received_data.get_size(3)*received_data.get_size(4); // free memory m1->release(); m1 = NULL; return GADGET_OK; } int CS_Retro_ImageCombinerGadget::close(unsigned long flags) { if (flags == 1) { GDEBUG("Finalizing array, with %d, %d, %d\n", receive_counter_, number_of_respiratory_phases_, number_of_cardiac_phases_); // create data element GadgetContainerMessage<hoNDArray<std::complex<float> > > *cm2 = new GadgetContainerMessage<hoNDArray<std::complex<float> > >(); cm2->getObjectPtr()->create(data_->get_dimensions()); memcpy(cm2->getObjectPtr()->get_data_ptr(), data_->get_data_ptr(), cm2->getObjectPtr()->get_number_of_bytes()); // concatenate data to header information return_message_->cont(cm2); // put data on pipeline this->next()->putq(return_message_); } return Gadget::close(flags); } GADGET_FACTORY_DECLARE(CS_Retro_ImageCombinerGadget)
33.67033
185
0.756854
alwaysbefun123
5759a3e5ae1c9bdff9aa1dd6605ce1a6dea911af
3,921
hh
C++
services/arena/include/fightingPit/contender/pit_contenders.hh
FreeYourSoul/FyS
123ca6e76387125909d343c23e788aa033221db5
[ "MIT" ]
9
2019-04-13T17:11:06.000Z
2020-04-23T12:06:59.000Z
services/arena/include/fightingPit/contender/pit_contenders.hh
FreeYourSoul/FyS
123ca6e76387125909d343c23e788aa033221db5
[ "MIT" ]
null
null
null
services/arena/include/fightingPit/contender/pit_contenders.hh
FreeYourSoul/FyS
123ca6e76387125909d343c23e788aa033221db5
[ "MIT" ]
2
2020-04-07T06:05:11.000Z
2020-11-07T23:26:56.000Z
// MIT License // // Copyright (c) 2021 Quentin Balland // Repository : https://github.com/FreeYourSoul/FyS // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #ifndef FYS_PITCONTENDERS_HH #define FYS_PITCONTENDERS_HH #include <functional> #include <memory> #include <vector> #include <fightingPit/data/common_types.hh> #include <fightingPit/hexagon_side.hh> namespace fys::arena { template<typename T> using comparator_selection = std::function<bool(std::shared_ptr<T>, std::shared_ptr<T>)>; //forward declarations class fighting_contender; class ally_party_teams; class pit_contenders { public: pit_contenders() = default; pit_contenders(const pit_contenders& other) = delete; void execute_contender_action(const data::priority_elem& contender); [[nodiscard]] std::vector<std::shared_ptr<fighting_contender>> contenders_on_side(hexagon_side::orientation side) const; [[nodiscard]] std::vector<std::shared_ptr<fighting_contender>> changing_side_contenders() const; // scripting utility [[nodiscard]] std::shared_ptr<fighting_contender> select_suitable_contender(comparator_selection<fighting_contender> comp) const; [[nodiscard]] std::shared_ptr<fighting_contender> select_suitable_contender_on_side(hexagon_side::orientation side, comparator_selection<fighting_contender> comp) const; [[nodiscard]] std::shared_ptr<fighting_contender> select_random_contender_on_side_alive(hexagon_side::orientation side) const; [[nodiscard]] std::shared_ptr<fighting_contender> select_suitable_contender_alive(comparator_selection<fighting_contender> comp) const; [[nodiscard]] std::shared_ptr<fighting_contender> select_suitable_contender_on_side_alive(hexagon_side::orientation side, comparator_selection<fighting_contender> comp) const; [[nodiscard]] std::shared_ptr<fighting_contender> fighting_contender_at(uint pos) const { return _contenders.at(pos); } [[nodiscard]] std::size_t number_contender() const { return _contenders.size(); } [[nodiscard]] std::vector<std::shared_ptr<fighting_contender>> get_dead_contender_on_side(hexagon_side::orientation contender_ptr) const; [[nodiscard]] const std::vector<std::shared_ptr<fighting_contender>>& get_contenders() const { return _contenders; } [[nodiscard]] unsigned number_contender_on_side(hexagon_side::orientation side) const; [[nodiscard]] bool add_contender(const std::shared_ptr<fighting_contender>& contender); [[nodiscard]] bool all_dead() const; private: std::vector<std::shared_ptr<fighting_contender>> _contenders; /** * Flags determining which contenders are going to move from one side to another<br> * (only _contenders having this flag (index equivalent) set to true have their position refreshed */ std::vector<bool> _change_side_flags; }; }// namespace fys::arena #endif// !FYS_PITCONTENDERS_HH
36.64486
127
0.770212
FreeYourSoul
575a1f9ea6c7ccd59fbbe26f7815cc81fc7567f8
2,948
cpp
C++
test/unit-tests/array/service/io_locker/stripe_locker_test.cpp
so931/poseidonos
2aa82f26bfbd0d0aee21cd0574779a655634f08c
[ "BSD-3-Clause" ]
38
2021-04-06T03:20:55.000Z
2022-03-02T09:33:28.000Z
test/unit-tests/array/service/io_locker/stripe_locker_test.cpp
so931/poseidonos
2aa82f26bfbd0d0aee21cd0574779a655634f08c
[ "BSD-3-Clause" ]
19
2021-04-08T02:27:44.000Z
2022-03-23T00:59:04.000Z
test/unit-tests/array/service/io_locker/stripe_locker_test.cpp
so931/poseidonos
2aa82f26bfbd0d0aee21cd0574779a655634f08c
[ "BSD-3-Clause" ]
28
2021-04-08T04:39:18.000Z
2022-03-24T05:56:00.000Z
#include "src/array/service/io_locker/stripe_locker.h" #include <gmock/gmock.h> #include <gtest/gtest.h> using ::testing::Return; namespace pos { TEST(StripeLocker, StripeLocker_testIfTryLockInNormal) { // Given StripeLocker sl; StripeId sid = 10; // When bool ret = sl.TryLock(sid); // Then ASSERT_TRUE(ret); } TEST(StripeLocker, StripeLocker_testIfTryLockInBusyButOutOfBusyRange) { // Given StripeLocker sl; StripeId busyRangeLower = 100; StripeId busyRangeUpper = 200; sl.TryBusyLock(busyRangeLower, busyRangeUpper); // When StripeId sid = 10; bool ret = sl.TryLock(sid); // Then ASSERT_TRUE(ret); } TEST(StripeLocker, StripeLocker_testIfTryLockInBusyRange) { // Given StripeLocker sl; StripeId busyRangeLower = 100; StripeId busyRangeUpper = 200; sl.TryBusyLock(busyRangeLower, busyRangeUpper); // When StripeId sid = 150; bool ret = sl.TryLock(sid); // Then ASSERT_FALSE(ret); } TEST(StripeLocker, StripeLocker_testIfTryLockAfterResetBusyRange) { // Given StripeLocker sl; StripeId busyRangeLower = 100; StripeId busyRangeUpper = 200; sl.TryBusyLock(busyRangeLower, busyRangeUpper); for (StripeId i = busyRangeLower; i <= busyRangeUpper; i++) { sl.Unlock(i); } sl.ResetBusyLock(); // When StripeId sid = 150; bool ret = sl.TryLock(sid); // Then ASSERT_TRUE(ret); } TEST(StripeLocker, StripeLocker_testIfRefuseResetBusyRangeDueToRemainings) { // Given StripeLocker sl; StripeId busyRangeLower = 100; StripeId busyRangeUpper = 200; sl.TryBusyLock(busyRangeLower, busyRangeUpper); // When bool ret = sl.ResetBusyLock(); // Then ASSERT_FALSE(ret); } TEST(StripeLocker, StripeLocker_testIfRefuseToTryBusyLockDueToRemainings) { // Given StripeLocker sl; StripeId busyRangeLower = 100; StripeId busyRangeUpper = 200; StripeId sidInBusyRange = 150; sl.TryLock(sidInBusyRange); // When bool ret = sl.TryBusyLock(busyRangeLower, busyRangeUpper); // Then ASSERT_FALSE(ret); } TEST(StripeLocker, StripeLocker_testIfUnlockInNormal) { // Given StripeLocker sl; StripeId sid = 10; // When sl.TryLock(sid); // Then sl.Unlock(sid); } TEST(StripeLocker, StripeLocker_testIfUnlockInBusyButOutOfBusyRange) { // Given StripeLocker sl; StripeId busyRangeLower = 100; StripeId busyRangeUpper = 200; sl.TryBusyLock(busyRangeLower, busyRangeUpper); // When StripeId sid = 10; sl.TryLock(sid); // Then sl.Unlock(sid); } TEST(StripeLocker, StripeLocker_testIfUnlockInBusyRange) { // Given StripeLocker sl; StripeId busyRangeLower = 100; StripeId busyRangeUpper = 200; sl.TryBusyLock(busyRangeLower, busyRangeUpper); // When StripeId sid = 150; // Then sl.Unlock(sid); } } // namespace pos
19.523179
74
0.676052
so931
575d6ed1d8dd01059469bbce716f5d5ffa7918b5
2,011
cpp
C++
framework/source/wrap/descriptor_pool.cpp
wobakj/VulkanFramework
960628dbc9743f0d74bc13b7d990d0795e32a542
[ "MIT" ]
null
null
null
framework/source/wrap/descriptor_pool.cpp
wobakj/VulkanFramework
960628dbc9743f0d74bc13b7d990d0795e32a542
[ "MIT" ]
null
null
null
framework/source/wrap/descriptor_pool.cpp
wobakj/VulkanFramework
960628dbc9743f0d74bc13b7d990d0795e32a542
[ "MIT" ]
null
null
null
#include "wrap/descriptor_pool.hpp" #include "wrap/descriptor_set_layout.hpp" #include "wrap/device.hpp" #include "wrap/shader.hpp" DescriptorPool::DescriptorPool() :WrapperDescriptorPool{} ,m_device{nullptr} {} DescriptorPool::DescriptorPool(DescriptorPool && DescriptorPool) :WrapperDescriptorPool{} ,m_device{nullptr} { swap(DescriptorPool); } DescriptorPool::DescriptorPool(Device const& device, DescriptorPoolInfo const& info) :DescriptorPool{} { m_device = device; m_info = info; m_object = m_device.createDescriptorPool(info); } DescriptorPool::~DescriptorPool() { cleanup(); } void DescriptorPool::destroy() { m_device.destroyDescriptorPool(get()); } DescriptorPool& DescriptorPool::operator=(DescriptorPool&& DescriptorPool) { swap(DescriptorPool); return *this; } void DescriptorPool::swap(DescriptorPool& DescriptorPool) { WrapperDescriptorPool::swap(DescriptorPool); std::swap(m_device, DescriptorPool.m_device); } std::vector<DescriptorSet> DescriptorPool::allocate(std::vector<DescriptorSetLayout> const& layouts) const { vk::DescriptorSetAllocateInfo info_alloc{}; info_alloc.descriptorPool = get(); info_alloc.descriptorSetCount = std::uint32_t(layouts.size()); std::vector<vk::DescriptorSetLayout> vklayouts{}; for (auto const& layout : layouts) { vklayouts.emplace_back(layout.get()); } info_alloc.pSetLayouts = vklayouts.data(); auto vk_sets = m_device.allocateDescriptorSets(info_alloc); std::vector<DescriptorSet> sets{}; for (size_t i = 0; i < layouts.size(); ++i) { sets.emplace_back(m_device, std::move(vk_sets[i]), layouts[i].info(), get()); } return sets; } DescriptorSet DescriptorPool::allocate(DescriptorSetLayout const& layout) const { vk::DescriptorSetAllocateInfo info_alloc{}; info_alloc.descriptorPool = get(); info_alloc.descriptorSetCount = 1; info_alloc.pSetLayouts = &layout.get(); return DescriptorSet{m_device, std::move(m_device.allocateDescriptorSets(info_alloc)[0]), layout.info(), get()}; }
29.573529
114
0.753357
wobakj
5762b3a443c7ff4ea8613ffe47c45b51a4fb3222
5,138
cpp
C++
src/JsonRecord.cpp
ojdkbuild/contrib_update-notifier
f462fe8378a6ec21223cb01c517d95ea19dca25e
[ "Apache-2.0" ]
2
2017-05-30T01:42:32.000Z
2020-07-25T19:17:49.000Z
src/JsonRecord.cpp
ojdkbuild/contrib_update-notifier
f462fe8378a6ec21223cb01c517d95ea19dca25e
[ "Apache-2.0" ]
null
null
null
src/JsonRecord.cpp
ojdkbuild/contrib_update-notifier
f462fe8378a6ec21223cb01c517d95ea19dca25e
[ "Apache-2.0" ]
1
2020-07-25T19:17:56.000Z
2020-07-25T19:17:56.000Z
/* * Copyright 2016 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * File: JsonRecord.cpp * Author: alex * * Created on October 21, 2016, 1:49 PM */ #include "JsonRecord.hpp" #include "transform.hpp" #include "utils.hpp" namespace checker { JsonRecord::JsonRecord() : json(json_object()) { if (!json) { throw CheckerException("Cannot create empty JSON object"); } } JsonRecord::JsonRecord(json_t* json) : json(download_manager_transform(json)) { if (!this->json) { throw CheckerException("Invalid 'null' JSON specified"); } if (!json_is_object(this->json)) { throw CheckerException("Invalid 'non-object' JSON specified"); } } JsonRecord::~JsonRecord() { if (json) { json_decref(json); } } /** * Pre-C++11 move logic * * @param other */ JsonRecord::JsonRecord(const JsonRecord& other) : json(other.json) { other.json = NULL; } const json_t* JsonRecord::get() const { return json; } const char* JsonRecord::get_string(const std::string& fieldname, const std::string& defaultval) const { json_t* field = json_object_get(json, fieldname.c_str()); if (!(field && json_is_string(field))) { return defaultval.c_str(); } return json_string_value(field); } void JsonRecord::put_string(const std::string& fieldname, const std::string& value) { json_t* field = json_string(value.c_str()); if (!field) { throw CheckerException("Cannot create JSON string, field: [" + fieldname + "]," + " value: [" + value +"]"); } int err = json_object_set_new(json, fieldname.c_str(), field); if (err) { throw CheckerException("Cannot set JSON string, field: [" + fieldname + "]," + " value: [" + value + "]"); } } uint32_t JsonRecord::get_uint32(const std::string& fieldname, uint32_t defaultval) const { json_t* field = json_object_get(json, fieldname.c_str()); if (!(field && json_is_integer(field))) { return defaultval; } json_int_t res = json_integer_value(field); if (res < 0) { return defaultval; } uint64_t res_u64 = static_cast<uint64_t> (res); if (res >= std::numeric_limits<uint32_t>::max()) { return defaultval; } return static_cast<uint32_t> (res_u64); } void JsonRecord::put_uint32(const std::string& fieldname, uint32_t value) { json_t* field = json_integer(static_cast<json_int_t> (value)); if (!field) { throw CheckerException("Cannot create JSON integer, field: [" + fieldname + "]," + " value: [" + utils::to_string(value) + "]"); } int err = json_object_set_new(json, fieldname.c_str(), field); if (err) { throw CheckerException("Cannot set JSON integer, field: [" + fieldname + "]," + " value: [" + utils::to_string(value) + "]"); } } uint64_t JsonRecord::get_uint64(const std::string& fieldname, uint64_t defaultval) const { json_t* field = json_object_get(json, fieldname.c_str()); if (!(field && json_is_integer(field))) { return defaultval; } json_int_t res = json_integer_value(field); if (res < 0) { return defaultval; } return static_cast<uint64_t> (res); } void JsonRecord::put_uint64(const std::string& fieldname, uint64_t value) { json_t* field = json_integer(static_cast<json_int_t> (value)); if (!field) { throw CheckerException("Cannot create JSON integer, field: [" + fieldname + "]," + " value: [" + utils::to_string(value) + "]"); } int err = json_object_set_new(json, fieldname.c_str(), field); if (err) { throw CheckerException("Cannot set JSON integer, field: [" + fieldname + "]," + " value: [" + utils::to_string(value) + "]"); } } bool JsonRecord::get_bool(const std::string& fieldname, bool defaultval) const { json_t* field = json_object_get(json, fieldname.c_str()); if (!(field && json_is_boolean(field))) { return defaultval; } return json_is_true(field) ? true : false; } void JsonRecord::put_bool(const std::string& fieldname, bool value) { json_t* field = json_boolean(value); if (!field) { throw CheckerException("Cannot create JSON bool, field: [" + fieldname + "]," + " value: [" + utils::to_string(value) + "]"); } int err = json_object_set_new(json, fieldname.c_str(), field); if (err) { throw CheckerException("Cannot set JSON bool, field: [" + fieldname + "]," + " value: [" + utils::to_string(value) + "]"); } } } // namespace
30.951807
103
0.630012
ojdkbuild
57641e0ecfae90946fbcdd763683ac2e1dfa5517
2,079
cpp
C++
Level5/Level5/Section 3.5/Exercise 3.5.4/TestProgram.cpp
chunyuyuan/My-Solution-for-C-Programming-for-Financial-Engineering
478b414714edbea1ebdc2f565baad6f04f54bc70
[ "MIT" ]
1
2021-09-12T08:15:57.000Z
2021-09-12T08:15:57.000Z
Level5/Level5/Section 3.5/Exercise 3.5.4/TestProgram.cpp
chunyuyuan/My-Solution-for-C-Programming-for-Financial-Engineering
478b414714edbea1ebdc2f565baad6f04f54bc70
[ "MIT" ]
null
null
null
Level5/Level5/Section 3.5/Exercise 3.5.4/TestProgram.cpp
chunyuyuan/My-Solution-for-C-Programming-for-Financial-Engineering
478b414714edbea1ebdc2f565baad6f04f54bc70
[ "MIT" ]
null
null
null
/* * Level_5 Exercise 3.5.4: * Test program for Abstract Functions Draw() function * * * @file TestProgram.cpp * @author Chunyu Yuan * @version 1.0 02/14/2021 * */ #include "Point.hpp" // Header file for point class #include "Line.hpp" // Header file for line class #include "Circle.hpp" //header file for circle class #include "Shape.hpp" //header file for Shape class using namespace std; //namespace declaration for using std using namespace Chunyu::CAD; //namespace declaration for using Chunyu::CAD /* * Controls operation of the program * Return type of main() expects an int * * @function main() * @param none * @return 0 */ int main() { Shape* shapes[10]; //declare a shape array with 10 elements shapes[0] = new Line; //create a Line object and assign it to first element of this shape array shapes[1] = new Point; //create a Point object and assign it to second element of this shape array shapes[2] = new Circle; //create a circle object and assign it to third element of this shape array shapes[3] = new Line(Point(0,0),Point(0,0)); //create a Line object and assign it to third element of this shape array shapes[4] = new Point(1,1); //create a Point object and assign it to 4th element of this shape array shapes[5] = new Circle(Point(0,0),10); //create a circle object and assign it to 5th element of this shape array shapes[6] = new Circle(Point(10, 0), 100); //create a circle object and assign it to 6th element of this shape array shapes[7] = new Line(Point(1, 1), Point(0, 0)); //create a Line object and assign it to 7th element of this shape array shapes[8] = new Circle(Point(10, 0), 10); //create a circle object and assign it to 8th element of this shape array shapes[9] = new Line(Point(1.0, 2.5), Point(3.4, 5.2)); //create a Line object and assign it to 9th element of this shape array //for loop, iterate to tes the Draw() function for (int i = 0; i != 10; i++) shapes[i]->Draw(); //for loop, iterate to delete elements for (int i = 0; i != 10; i++) delete shapes[i]; return 0; //return 0 to end program }
41.58
128
0.699375
chunyuyuan
576652c02a64047b6ec2175daa5912b4ae081b0b
4,853
cc
C++
common/nice_type_name.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
2
2021-02-25T02:01:02.000Z
2021-03-17T04:52:04.000Z
common/nice_type_name.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
null
null
null
common/nice_type_name.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
1
2021-06-13T12:05:39.000Z
2021-06-13T12:05:39.000Z
/* Portions copyright (c) 2014 Stanford University and the Authors. Authors: Chris Dembia, Michael Sherman 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. */ #include "drake/common/nice_type_name.h" #include <algorithm> #include <array> #include <initializer_list> #include <regex> #include <string> #include "drake/common/never_destroyed.h" #include "drake/common/nice_type_name_override.h" using std::string; // __GNUG__ is defined both for gcc and clang. See: // https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.3/a01696.html #if defined(__GNUG__) /* clang-format off */ #include <cxxabi.h> #include <cstdlib> /* clang-format on */ #endif namespace drake { // On gcc and clang typeid(T).name() returns an indecipherable mangled string // that requires processing to become human readable. Microsoft returns a // reasonable name directly. string NiceTypeName::Demangle(const char* typeid_name) { #if defined(__GNUG__) int status = -100; // just in case it doesn't get set char* ret = abi::__cxa_demangle(typeid_name, NULL, NULL, &status); const char* const demangled_name = (status == 0) ? ret : typeid_name; string demangled_string(demangled_name); if (ret) std::free(ret); return demangled_string; #else // On other platforms, we hope the typeid name is not mangled. return typeid_name; #endif } // Given a demangled string, attempt to canonicalize it for platform // indpendence. We'll remove Microsoft's "class ", "struct ", etc. // designations, and get rid of all unnecessary spaces. string NiceTypeName::Canonicalize(const string& demangled) { using SPair = std::pair<std::regex, string>; using SPairList = std::initializer_list<SPair>; // These are applied in this order. static const never_destroyed<std::vector<SPair>> subs{SPairList{ // Remove unwanted keywords and following space. (\b is word boundary.) SPair(std::regex("\\b(class|struct|enum|union) "), ""), // Tidy up anonymous namespace. SPair(std::regex("[`(]anonymous namespace[')]"), "(anonymous)"), // Replace Microsoft __int64 with long long. SPair(std::regex("\\b__int64\\b"), "long long"), // Temporarily replace spaces we want to keep with "!". (\w is // alphanumeric or underscore.) SPair(std::regex("(\\w) (\\w)"), "$1!$2"), SPair(std::regex(" "), ""), // Delete unwanted spaces. // Some compilers throw in extra namespaces like "__1" or "__cxx11". // Delete them. SPair(std::regex("\\b__[[:alnum:]_]+::"), ""), SPair(std::regex("!"), " "), // Restore wanted spaces. // Recognize std::string's full name and abbreviate. SPair(std::regex("\\bstd::basic_string<char,std::char_traits<char>," "std::allocator<char>>"), "std::string"), // Recognize Eigen types ... // ... square matrices ... SPair(std::regex("\\bEigen::Matrix<([^,<>]*),(-?\\d+),\\2,0,\\2,\\2>"), "drake::Matrix$2<$1>"), // ... vectors ... SPair(std::regex("\\bEigen::Matrix<([^,<>]*),(-?\\d+),1,0,\\2,1>"), "drake::Vector$2<$1>"), // ... dynamic-size is "X" not "-1" ... SPair(std::regex("drake::(Matrix|Vector)-1<"), "drake::$1X<"), // ... for double, float, and int, prefer native Eigen spellings ... SPair(std::regex("drake::(Vector|Matrix)(X|\\d+)" "<((d)ouble|(f)loat|(i)nt)>"), "Eigen::$1$2$4$5$6"), // ... AutoDiff. SPair(std::regex("Eigen::AutoDiffScalar<Eigen::VectorXd>"), "drake::AutoDiffXd"), }}; string canonical(demangled); for (const auto& sp : subs.access()) { canonical = std::regex_replace(canonical, sp.first, sp.second); } return canonical; } string NiceTypeName::RemoveNamespaces(const string& canonical) { // Removes everything up to and including the last "::" that isn't part of a // template argument. If the string ends with "::", returns the original // string unprocessed. We are depending on the fact that namespaces can't be // templatized to avoid bad behavior for template types where the template // argument might include namespaces (those should not be touched). static const never_destroyed<std::regex> regex{"^[^<>]*::"}; const std::string no_namespace = std::regex_replace(canonical, regex.access(), ""); return no_namespace.empty() ? canonical : no_namespace; } std::string NiceTypeName::GetWithPossibleOverride( const void* ptr, const std::type_info& info) { internal::NiceTypeNamePtrOverride ptr_override = internal::GetNiceTypeNamePtrOverride(); if (ptr_override) { return ptr_override(internal::type_erased_ptr{ptr, info}); } else { return Get(info); } } } // namespace drake
37.914063
80
0.663301
RobotLocomotion
5766eeb52049e919ed012727d98466222aa78aac
3,550
cpp
C++
forked/macrokeyboard_by_nicaqueous.cpp
saltyfishie98/MacroPad
d90601b7795676449c7d3ddb88360516e806d4ac
[ "MIT" ]
null
null
null
forked/macrokeyboard_by_nicaqueous.cpp
saltyfishie98/MacroPad
d90601b7795676449c7d3ddb88360516e806d4ac
[ "MIT" ]
null
null
null
forked/macrokeyboard_by_nicaqueous.cpp
saltyfishie98/MacroPad
d90601b7795676449c7d3ddb88360516e806d4ac
[ "MIT" ]
null
null
null
#include <Keyboard.h> // Code by youtube.com/nicaqueous // assign each key to a digital pin const int key[16] = {6, 5, 4, 3, 2, 7, 8, 9, 10, 16, 14, 15, 18, 19, 20, 21}; uint32_t previousmillis; // used for debouncing int keypressed = 0; void setup() { for (int i = 0; i < 16; i++) { pinMode(key[i], INPUT); } Serial.begin(9600); Keyboard.begin(); } void loop() { for (int i = 0; i < 16; i++) { if (digitalRead(key[i]) == 1) { if (millis() - previousmillis > 200) // debouncing { previousmillis = millis(); keypressed = i + 1; Serial.println(keypressed); switch (keypressed) { case 0: break; // assign macros here! case 1: Keyboard.press(KEY_F13); Keyboard.releaseAll(); break; case 2: Keyboard.press(KEY_F14); Keyboard.releaseAll(); break; case 3: Keyboard.press(KEY_F15); Keyboard.releaseAll(); break; case 4: Keyboard.press(KEY_F16); Keyboard.releaseAll(); break; case 5: Keyboard.press(KEY_F17); Keyboard.releaseAll(); break; case 6: Keyboard.press(KEY_F18); Keyboard.releaseAll(); break; case 7: Keyboard.press(KEY_F19); Keyboard.releaseAll(); break; case 8: Keyboard.press(KEY_F20); Keyboard.releaseAll(); break; case 9: Keyboard.press(KEY_F21); Keyboard.releaseAll(); break; case 10: Keyboard.press(KEY_F22); Keyboard.releaseAll(); break; case 11: Keyboard.press(KEY_F23); Keyboard.releaseAll(); break; case 12: // open command prompt Keyboard.press(KEY_LEFT_GUI); Keyboard.press('r'); Keyboard.releaseAll(); break; case 13: // mute/unmute Keyboard.press(KEY_LEFT_CTRL); Keyboard.press(KEY_LEFT_SHIFT); Keyboard.press('m'); Keyboard.releaseAll(); break; case 14: // deafen/undeafen Keyboard.press(KEY_LEFT_CTRL); Keyboard.press(KEY_LEFT_SHIFT); Keyboard.press('d'); Keyboard.releaseAll(); break; case 15: // switch tabs Keyboard.press(KEY_LEFT_ALT); Keyboard.press(KEY_TAB); Keyboard.releaseAll(); break; case 16: // tba break; default: keypressed = 0; break; } } } } }
33.809524
78
0.378873
saltyfishie98
576775beddf22f405f4e36cee2ec47e0a163842e
16,297
cc
C++
libgearman/add.cc
alionurdemetoglu/gearmand
dd9ac59a730f816e0dc5f27f98fdc06a08cc4c22
[ "BSD-3-Clause" ]
712
2016-07-02T03:32:22.000Z
2022-03-23T14:23:02.000Z
libgearman/add.cc
alionurdemetoglu/gearmand
dd9ac59a730f816e0dc5f27f98fdc06a08cc4c22
[ "BSD-3-Clause" ]
294
2016-07-03T16:17:41.000Z
2022-03-30T04:37:49.000Z
libgearman/add.cc
alionurdemetoglu/gearmand
dd9ac59a730f816e0dc5f27f98fdc06a08cc4c22
[ "BSD-3-Clause" ]
163
2016-07-08T10:03:38.000Z
2022-01-21T05:03:48.000Z
/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Gearmand client and server library. * * Copyright (C) 2011 Data Differential, http://datadifferential.com/ * Copyright (C) 2008 Brian Aker, Eric Day * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * The names of its contributors may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "gear_config.h" #include <libgearman/common.h> #include <libgearman/universal.hpp> #include <libgearman/add.hpp> #include <libgearman/packet.hpp> #include "libgearman/assert.hpp" #include "libgearman/log.hpp" #include "libgearman/vector.h" #include "libgearman/uuid.hpp" #include "libhashkit-1.0/hashkit.h" #include <cerrno> #include <cstdio> #include <cstdlib> #include <cstring> #include <memory> namespace { bool is_background(gearman_command_t command) { switch (command) { case GEARMAN_COMMAND_SUBMIT_JOB_EPOCH: case GEARMAN_COMMAND_SUBMIT_JOB_SCHED: case GEARMAN_COMMAND_SUBMIT_JOB_BG: case GEARMAN_COMMAND_SUBMIT_JOB_LOW_BG: case GEARMAN_COMMAND_SUBMIT_JOB_HIGH_BG: case GEARMAN_COMMAND_SUBMIT_REDUCE_JOB_BACKGROUND: return true; case GEARMAN_COMMAND_SUBMIT_REDUCE_JOB: case GEARMAN_COMMAND_SUBMIT_JOB: case GEARMAN_COMMAND_SUBMIT_JOB_LOW: case GEARMAN_COMMAND_SUBMIT_JOB_HIGH: return true; case GEARMAN_COMMAND_ALL_YOURS: case GEARMAN_COMMAND_CANT_DO: case GEARMAN_COMMAND_CAN_DO: case GEARMAN_COMMAND_CAN_DO_TIMEOUT: case GEARMAN_COMMAND_ECHO_REQ: case GEARMAN_COMMAND_ECHO_RES: case GEARMAN_COMMAND_ERROR: case GEARMAN_COMMAND_GET_STATUS: case GEARMAN_COMMAND_GRAB_JOB: case GEARMAN_COMMAND_GRAB_JOB_ALL: case GEARMAN_COMMAND_GRAB_JOB_UNIQ: case GEARMAN_COMMAND_JOB_ASSIGN: case GEARMAN_COMMAND_JOB_ASSIGN_ALL: case GEARMAN_COMMAND_JOB_ASSIGN_UNIQ: case GEARMAN_COMMAND_JOB_CREATED: case GEARMAN_COMMAND_MAX: case GEARMAN_COMMAND_NOOP: case GEARMAN_COMMAND_NO_JOB: case GEARMAN_COMMAND_OPTION_REQ: case GEARMAN_COMMAND_OPTION_RES: case GEARMAN_COMMAND_PRE_SLEEP: case GEARMAN_COMMAND_RESET_ABILITIES: case GEARMAN_COMMAND_SET_CLIENT_ID: case GEARMAN_COMMAND_STATUS_RES: case GEARMAN_COMMAND_TEXT: case GEARMAN_COMMAND_UNUSED: case GEARMAN_COMMAND_WORK_COMPLETE: case GEARMAN_COMMAND_WORK_DATA: case GEARMAN_COMMAND_WORK_EXCEPTION: case GEARMAN_COMMAND_WORK_FAIL: case GEARMAN_COMMAND_WORK_STATUS: case GEARMAN_COMMAND_WORK_WARNING: case GEARMAN_COMMAND_GET_STATUS_UNIQUE: case GEARMAN_COMMAND_STATUS_RES_UNIQUE: assert(0); break; } return false; } } // namespace gearman_task_st *add_task(Client& client, void *context, gearman_command_t command, const gearman_string_t &function, gearman_unique_t &unique, const gearman_string_t &workload, time_t when, const gearman_actions_t &actions) { return add_task(client, NULL, context, command, function, unique, workload, when, actions); } gearman_task_st *add_task_ptr(Client& client, gearman_task_st *task, void *context, gearman_command_t command, const char *function_name, const char *unique, const void *workload_str, size_t workload_size, time_t when, gearman_return_t& ret_ptr, const gearman_actions_t &actions) { gearman_string_t function= { gearman_string_param_cstr(function_name) }; gearman_unique_t local_unique= gearman_unique_make(unique, unique ? strlen(unique) : 0); gearman_string_t workload= { static_cast<const char *>(workload_str), workload_size }; task= add_task(client, task, context, command, function, local_unique, workload, when, actions); if (task == NULL) { ret_ptr= client.universal.error_code(); return NULL; } ret_ptr= GEARMAN_SUCCESS; return task; } gearman_task_st *add_task(Client& client, gearman_task_st *task_shell, void *context, gearman_command_t command, const gearman_string_t &function, gearman_unique_t &unique, const gearman_string_t &workload, time_t when, const gearman_actions_t &actions) { if (gearman_size(function) == 0 or gearman_c_str(function) == NULL or gearman_size(function) > GEARMAN_FUNCTION_MAX_SIZE) { if (gearman_size(function) > GEARMAN_FUNCTION_MAX_SIZE) { gearman_error(client.universal, GEARMAN_INVALID_ARGUMENT, "function name longer then GEARMAN_MAX_FUNCTION_SIZE"); } else { gearman_error(client.universal, GEARMAN_INVALID_ARGUMENT, "invalid function"); } return NULL; } if (gearman_size(unique) > GEARMAN_MAX_UNIQUE_SIZE) { gearman_error(client.universal, GEARMAN_INVALID_ARGUMENT, "unique name longer then GEARMAN_MAX_UNIQUE_SIZE"); return NULL; } if ((gearman_size(workload) && gearman_c_str(workload) == NULL) or (gearman_size(workload) == 0 && gearman_c_str(workload))) { gearman_error(client.universal, GEARMAN_INVALID_ARGUMENT, "invalid workload"); return NULL; } task_shell= gearman_task_internal_create(&client, task_shell); if (task_shell == NULL or task_shell->impl() == NULL) { assert(client.universal.error()); return NULL; } assert(task_shell->impl()->client); Task* task= task_shell->impl(); task->context= context; task->func= actions; if (gearman_unique_is_hash(unique)) { task->unique_length= snprintf(task->unique, GEARMAN_MAX_UNIQUE_SIZE, "%u", libhashkit_murmur3(gearman_string_param(workload))); } else if ((task->unique_length= gearman_size(unique))) { if (task->unique_length >= GEARMAN_MAX_UNIQUE_SIZE) { task->unique_length= GEARMAN_MAX_UNIQUE_SIZE -1; // Leave space for NULL byte } strncpy(task->unique, gearman_c_str(unique), GEARMAN_MAX_UNIQUE_SIZE); task->unique[task->unique_length]= 0; } else { if (client.options.generate_unique or is_background(command)) { if (safe_uuid_generate(task->unique, task->unique_length) == -1) { gearman_log_debug(task->client->universal, "uuid_generate_time_safe() failed or does not exist on this platform"); } } else { task->unique_length= 0; task->unique[0]= 0; } } gearman_unique_t final_unique= gearman_unique_make(task->unique, task->unique_length); assert(task->client); gearman_return_t rc= GEARMAN_INVALID_ARGUMENT; switch (command) { case GEARMAN_COMMAND_SUBMIT_JOB: case GEARMAN_COMMAND_SUBMIT_JOB_LOW: case GEARMAN_COMMAND_SUBMIT_JOB_HIGH: rc= libgearman::protocol::submit(task->client->universal, task->send, final_unique, command, function, workload); break; case GEARMAN_COMMAND_SUBMIT_JOB_EPOCH: rc= libgearman::protocol::submit_epoch(task->client->universal, task->send, final_unique, function, workload, when); break; case GEARMAN_COMMAND_SUBMIT_JOB_BG: case GEARMAN_COMMAND_SUBMIT_JOB_LOW_BG: case GEARMAN_COMMAND_SUBMIT_JOB_HIGH_BG: rc= libgearman::protocol::submit_background(task->client->universal, task->send, final_unique, command, function, workload); break; case GEARMAN_COMMAND_SUBMIT_REDUCE_JOB: case GEARMAN_COMMAND_SUBMIT_REDUCE_JOB_BACKGROUND: rc= GEARMAN_INVALID_ARGUMENT; assert(rc != GEARMAN_INVALID_ARGUMENT); break; case GEARMAN_COMMAND_SUBMIT_JOB_SCHED: case GEARMAN_COMMAND_ALL_YOURS: case GEARMAN_COMMAND_CANT_DO: case GEARMAN_COMMAND_CAN_DO: case GEARMAN_COMMAND_CAN_DO_TIMEOUT: case GEARMAN_COMMAND_ECHO_REQ: case GEARMAN_COMMAND_ECHO_RES: case GEARMAN_COMMAND_ERROR: case GEARMAN_COMMAND_GET_STATUS: case GEARMAN_COMMAND_GRAB_JOB: case GEARMAN_COMMAND_GRAB_JOB_ALL: case GEARMAN_COMMAND_GRAB_JOB_UNIQ: case GEARMAN_COMMAND_JOB_ASSIGN: case GEARMAN_COMMAND_JOB_ASSIGN_ALL: case GEARMAN_COMMAND_JOB_ASSIGN_UNIQ: case GEARMAN_COMMAND_JOB_CREATED: case GEARMAN_COMMAND_MAX: case GEARMAN_COMMAND_NOOP: case GEARMAN_COMMAND_NO_JOB: case GEARMAN_COMMAND_OPTION_REQ: case GEARMAN_COMMAND_OPTION_RES: case GEARMAN_COMMAND_PRE_SLEEP: case GEARMAN_COMMAND_RESET_ABILITIES: case GEARMAN_COMMAND_SET_CLIENT_ID: case GEARMAN_COMMAND_STATUS_RES: case GEARMAN_COMMAND_TEXT: case GEARMAN_COMMAND_UNUSED: case GEARMAN_COMMAND_WORK_COMPLETE: case GEARMAN_COMMAND_WORK_DATA: case GEARMAN_COMMAND_WORK_EXCEPTION: case GEARMAN_COMMAND_WORK_FAIL: case GEARMAN_COMMAND_WORK_STATUS: case GEARMAN_COMMAND_WORK_WARNING: case GEARMAN_COMMAND_GET_STATUS_UNIQUE: case GEARMAN_COMMAND_STATUS_RES_UNIQUE: rc= GEARMAN_INVALID_ARGUMENT; assert(rc != GEARMAN_INVALID_ARGUMENT); break; } if (gearman_success(rc)) { client.new_tasks++; client.running_tasks++; task->options.send_in_use= true; return task->shell(); } gearman_task_free(task->shell()); return NULL; } gearman_task_st *add_reducer_task(Client* client, gearman_command_t command, const gearman_job_priority_t, const gearman_string_t &function, const gearman_string_t &reducer, const gearman_unique_t &unique, const gearman_string_t &workload, const gearman_actions_t &actions, const time_t, void *context) { const void *args[5]; size_t args_size[5]; if (gearman_size(function) == 0 or gearman_c_str(function) == NULL or gearman_size(function) > GEARMAN_FUNCTION_MAX_SIZE) { if (gearman_size(function) > GEARMAN_FUNCTION_MAX_SIZE) { gearman_error(client->universal, GEARMAN_INVALID_ARGUMENT, "function name longer then GEARMAN_MAX_FUNCTION_SIZE"); } else { gearman_error(client->universal, GEARMAN_INVALID_ARGUMENT, "invalid function"); } return NULL; } if (gearman_size(unique) > GEARMAN_MAX_UNIQUE_SIZE) { gearman_error(client->universal, GEARMAN_INVALID_ARGUMENT, "unique name longer then GEARMAN_MAX_UNIQUE_SIZE"); return NULL; } if ((gearman_size(workload) and not gearman_c_str(workload)) or (gearman_size(workload) == 0 && gearman_c_str(workload))) { gearman_error(client->universal, GEARMAN_INVALID_ARGUMENT, "invalid workload"); return NULL; } gearman_task_st *task_shell= gearman_task_internal_create(client, NULL); if (task_shell == NULL) { assert(client->universal.error_code()); return NULL; } Task* task= task_shell->impl(); task->context= context; task->func= actions; /** @todo fix it so that NULL is done by default by the API not by happenstance. */ char function_buffer[1024]; if (client->universal._namespace) { char *ptr= function_buffer; memcpy(ptr, gearman_string_value(client->universal._namespace), gearman_string_length(client->universal._namespace)); ptr+= gearman_string_length(client->universal._namespace); memcpy(ptr, gearman_c_str(function), gearman_size(function) +1); ptr+= gearman_size(function); args[0]= function_buffer; args_size[0]= ptr- function_buffer +1; } else { args[0]= gearman_c_str(function); args_size[0]= gearman_size(function) + 1; } if (gearman_unique_is_hash(unique)) { task->unique_length= snprintf(task->unique, GEARMAN_MAX_UNIQUE_SIZE, "%u", libhashkit_murmur3(gearman_string_param(workload))); } else if ((task->unique_length= gearman_size(unique))) { if (task->unique_length >= GEARMAN_MAX_UNIQUE_SIZE) { task->unique_length= GEARMAN_MAX_UNIQUE_SIZE -1; // Leave space for NULL byte } strncpy(task->unique, gearman_c_str(unique), GEARMAN_MAX_UNIQUE_SIZE); task->unique[task->unique_length]= 0; } else { if (client->options.generate_unique or is_background(command)) { safe_uuid_generate(task->unique, task->unique_length); } else { task->unique_length= 0; task->unique[0]= 0; } } args[1]= task->unique; args_size[1]= task->unique_length +1; // +1 is for the needed null assert_msg(command == GEARMAN_COMMAND_SUBMIT_REDUCE_JOB or command == GEARMAN_COMMAND_SUBMIT_REDUCE_JOB_BACKGROUND, "Command was not appropriate for request"); char reducer_buffer[1024]; if (client->universal._namespace) { char *ptr= reducer_buffer; memcpy(ptr, gearman_string_value(client->universal._namespace), gearman_string_length(client->universal._namespace)); ptr+= gearman_string_length(client->universal._namespace); memcpy(ptr, gearman_c_str(reducer), gearman_size(reducer) +1); ptr+= gearman_size(reducer); args[2]= reducer_buffer; args_size[2]= ptr- reducer_buffer +1; } else { args[2]= gearman_c_str(reducer); args_size[2]= gearman_size(reducer) +1; } char aggregate[1]; aggregate[0]= 0; args[3]= aggregate; args_size[3]= 1; assert_msg(gearman_c_str(workload), "Invalid workload (NULL)"); assert_msg(gearman_size(workload), "Invalid workload of zero"); args[4]= gearman_c_str(workload); args_size[4]= gearman_size(workload); gearman_return_t rc; if (gearman_success(rc= gearman_packet_create_args(client->universal, task->send, GEARMAN_MAGIC_REQUEST, command, args, args_size, 5))) { client->new_tasks++; client->running_tasks++; task->options.send_in_use= true; } else { gearman_gerror(client->universal, rc); gearman_task_free(task); task= NULL; } task->type= GEARMAN_TASK_KIND_EXECUTE; return task->shell(); }
32.923232
131
0.667608
alionurdemetoglu
5768de1bae61b5928fdd1486b79ab38194e7fb7a
969
hpp
C++
crc32.hpp
salleaffaire/MP2TS
78d0b3fbfcc331157565ac5bb9cc52437c4bc3fa
[ "MIT" ]
11
2016-06-29T06:10:43.000Z
2019-05-14T14:32:31.000Z
crc32.hpp
salleaffaire/MP2TS
78d0b3fbfcc331157565ac5bb9cc52437c4bc3fa
[ "MIT" ]
2
2017-09-15T02:04:01.000Z
2019-04-27T13:11:48.000Z
crc32.hpp
salleaffaire/MP2TS
78d0b3fbfcc331157565ac5bb9cc52437c4bc3fa
[ "MIT" ]
8
2015-08-22T01:36:43.000Z
2018-11-15T07:39:59.000Z
/* * crc32.hpp * * Created on: Jul 3, 2015 * Author: luc.martel */ #ifndef CRC32_HPP_ #define CRC32_HPP_ #include <cstdint> template <int IN, int OUT> class CRC32 { public: CRC32(uint32_t poly) { mTable = new uint32_t [256]; CreateTable(poly); }; ~CRC32() { delete [] mTable; } uint32_t operator()(unsigned char *buffer, unsigned int length) { uint32_t i_crc = IN; for(unsigned int i = 0; i < length;i++) { i_crc = (i_crc << 8) ^ mTable[((i_crc >> 24) ^ buffer[i]) & 0xff]; } return i_crc ^ OUT; } private: uint32_t *mTable; void CreateTable(uint32_t poly) { uint32_t i, j, k; for(i = 0; i < 256; i++) { k = 0; for(j = (i << 24) | 0x800000; j != 0x80000000; j <<= 1) { k = (k << 1) ^ (((k ^ j) & 0x80000000) ? poly : 0); } mTable[i] = k; } } CRC32() {} // Disallowed }; #endif /* CRC32_HPP_ */
17.944444
76
0.501548
salleaffaire
576a3e141b7e0513474a91390f186b503e28452c
1,680
cpp
C++
test/engine/scene/nxn_scene_graph.t.cpp
invaderjon/gdev
3f5c5da22160c4980afd6099b0b4e06fdf106204
[ "Apache-2.0" ]
1
2018-10-20T22:08:59.000Z
2018-10-20T22:08:59.000Z
test/engine/scene/nxn_scene_graph.t.cpp
invaderjon/gdev
3f5c5da22160c4980afd6099b0b4e06fdf106204
[ "Apache-2.0" ]
null
null
null
test/engine/scene/nxn_scene_graph.t.cpp
invaderjon/gdev
3f5c5da22160c4980afd6099b0b4e06fdf106204
[ "Apache-2.0" ]
null
null
null
// nxn_scene_graph.t.cpp #include <engine/scene/nxn_scene_graph.h> #include <engine/scene/test_collider.h> #include <gtest/gtest.h> TEST( NxNSceneGraphTest, Construction ) { using namespace StevensDev::sgds; NxNSceneGraph graph; NxNSceneGraph sized( 1, 10 ); NxNSceneGraph copy( graph ); graph = copy; } TEST( NxNSceneGraphTest, ColliderManagement ) { using namespace StevensDev::sgds; using namespace StevensDev::sgdt; NxNSceneGraph graph; TestCollider collider; graph.addCollider( &collider ); graph.removeCollider( &collider ); } TEST( NxNSceneGraphTest, CollisionDetection ) { using namespace StevensDev::sgds; using namespace StevensDev::sgdt; using namespace StevensDev::sgdc; NxNSceneGraph graph( 10.0f, 100 ); RectangleBounds ra( 0.0f, 0.0f, 1.0f, 1.0f ); RectangleBounds rb( 0.5f, 0.5f, 2.0f, 2.0f ); RectangleBounds rc( 1.0f, 0.0f, 1.0f, 1.0f ); RectangleBounds rd( 2.0f, 2.0f, 1.0f, 1.0f ); TestCollider a( ra ); TestCollider b( rb ); TestCollider c( rc ); TestCollider d( rd ); DynamicArray<ICollider*> results; graph.addCollider( &a ); graph.addCollider( &b ); graph.addCollider( &c ); graph.addCollider( &d ); results = graph.find( 0.0f, 0.0f, 1.0f, 1.0f ); EXPECT_EQ( 3, results.size() ); results = graph.find( ra ); EXPECT_EQ( 3, results.size() ); results = graph.find( &a ); EXPECT_EQ( 3, results.size() ); results = graph.find( 0.0f, 0.0f, 1.0f, 1.0f, 1 ); EXPECT_EQ( 0, results.size() ); results = graph.find( ra, 1 ); EXPECT_EQ( 0, results.size() ); graph.removeCollider( &a ); }
23.013699
54
0.639286
invaderjon
576b5f4522e4061f8ef99a79f1ae993c781df238
1,757
cpp
C++
Assignment 4/Computer Graphics_assignment4/assignment4/src/base/Shader.cpp
Yanko96/CS-C3100-Computer-Graphics
83b369a6fd5723f53b6ba1c84e8e8babd750f562
[ "MIT" ]
null
null
null
Assignment 4/Computer Graphics_assignment4/assignment4/src/base/Shader.cpp
Yanko96/CS-C3100-Computer-Graphics
83b369a6fd5723f53b6ba1c84e8e8babd750f562
[ "MIT" ]
null
null
null
Assignment 4/Computer Graphics_assignment4/assignment4/src/base/Shader.cpp
Yanko96/CS-C3100-Computer-Graphics
83b369a6fd5723f53b6ba1c84e8e8babd750f562
[ "MIT" ]
null
null
null
#define _CRT_SECURE_NO_WARNINGS #include "Shader.hpp" #include <fstream> #include <sstream> #include <iostream> #include <vector> using namespace FW; using namespace std; void ReadFile(string filename, string &source) { ifstream in(filename); if (in.good()) source = string((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>()); else { std::cout << "Could not open file " << filename << "!\n"; __debugbreak(); } } FW::Shader::Shader(const std::string & name, const bool compute, GLContext *ctx) { std::cout << "Compiling shader " << name << "..."; if (compute) { // Read shader source to string string source; ReadFile("shaders/" + name + ".glsl", source); // Add preprocess definitions to make line numbers match text editor and allow multiple shaders per file (though not necessary with compute shaders) source = (string)"#version 430\n" + (string)"#define ComputeShader\n" + (string)"#line 1\n" + source; // Create program from string program = new GLContext::Program(source.c_str()); } else { // Read shader source to string string source; ReadFile("shaders/" + name + ".glsl", source); // Add preprocess definitions to make line numbers match text editor and allow multiple shaders per file string vertSource = (string)"#version 430\n" + (string)"#define VertexShader\n" + (string)"#line 1\n" + source; string fragSource = (string)"#version 430\n" + (string)"#define FragmentShader\n" + (string)"#line 1\n" + source; // Create program from strings program = new GLContext::Program(vertSource.c_str(), fragSource.c_str()); } ctx->setProgram(name.c_str(), program); handle = program->getHandle(); initialized = true; std::cout << " Done!\n"; } FW::Shader::~Shader() { }
27.453125
150
0.684121
Yanko96
576d91c6c573555234b324441177eaf73b68d3d9
4,488
cpp
C++
inference-engine/thirdparty/clDNN/src/primitive_inst.cpp
mypopydev/dldt
8cd639116b261adbbc8db860c09807c3be2cc2ca
[ "Apache-2.0" ]
3
2019-07-08T09:03:03.000Z
2020-09-09T10:34:17.000Z
inference-engine/thirdparty/clDNN/src/primitive_inst.cpp
openvino-pushbot/dldt
e607ee70212797cf9ca51dac5b7ac79f66a1c73f
[ "Apache-2.0" ]
3
2020-11-13T18:59:18.000Z
2022-02-10T02:14:53.000Z
inference-engine/thirdparty/clDNN/src/primitive_inst.cpp
openvino-pushbot/dldt
e607ee70212797cf9ca51dac5b7ac79f66a1c73f
[ "Apache-2.0" ]
1
2018-12-14T07:56:02.000Z
2018-12-14T07:56:02.000Z
/* // Copyright (c) 2016 Intel 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. */ /////////////////////////////////////////////////////////////////////////////////////////////////// #include "primitive_inst.h" #include "data_inst.h" #include "mutable_data_inst.h" #include "generic_layer_inst.h" #include "input_layout_inst.h" #include "max_unpooling_inst.h" #include "apply_adam_inst.h" #include "network_impl.h" #include "engine_impl.h" #include "memory_impl.h" #include "error_handler.h" #include "json_object.h" namespace cldnn { event_impl::ptr primitive_inst::execute(const std::vector<event_impl::ptr>& events) { CLDNN_ERROR_BOOL(id(), "Invalid/unset input", !_has_valid_input, "Cannot execute primitive " + id() + " with invalid/unset input"); on_execute(); if (_exec_deps.size() == 0) return _impl->execute(events, *this); std::vector<event_impl::ptr> dependencies; dependencies.reserve(_exec_deps.size()); for (auto& input : _exec_deps) { dependencies.emplace_back(get_network().execute_primitive(input, events)); } return _impl->execute(dependencies, *this); } primitive_inst::primitive_inst(network_impl& network, program_node const& node, bool allocate_memory) : _network(network) , _node(node) , _impl(node.get_selected_impl()) , _output() , _output_changed(false) { if (allocate_memory) { if (node.get_users().size() == 1 && node.get_users().front()->is_type<mutable_data>()) _output = node.get_users().front()->as<mutable_data>().get_attached_memory_ptr(); else _output = allocate_output(); } } memory_impl::ptr primitive_inst::allocate_output() { auto layout = _node.get_output_layout(); if (!_network.is_internal() && (_node.can_be_optimized() || _node.is_type<generic_layer>())) { return get_network().get_engine().allocate_memory(layout, _node.id(), get_network_id(), _node.get_memory_dependencies(), false); } else if (_network.is_internal() || _node.is_type<data>() || _node.is_type<mutable_data>() || _node.is_type<input_layout>() || //for max_unpooling initial zero values are significant _node.is_type<max_unpooling>() || //apply adam's output initial val should be either 0 or use same buffer as mutable_data after it (no allocation needed) _node.is_type<apply_adam>() || _node.can_be_optimized() || _node.is_output()) { return get_network().get_engine().allocate_memory(layout); } return get_network().get_engine().allocate_memory(layout, _node.id(), get_network_id(), _node.get_memory_dependencies(), true); } std::vector<std::shared_ptr<primitive_inst>> primitive_inst::build_exec_deps(std::vector<std::shared_ptr<primitive_inst>> const& mem_deps) { std::vector<std::shared_ptr<primitive_inst>> exec_deps; exec_deps.reserve(mem_deps.size()); for (auto& mem_dep : mem_deps) if (mem_dep->get_impl() != nullptr) exec_deps.push_back(mem_dep); return exec_deps; } std::string primitive_inst::generic_to_string(program_node const& node, const char* type_name) { auto node_info = node.desc_to_json(); std::stringstream primitive_description; std::stringstream ss_inputs; for (size_t i = 0; i < node.get_dependencies().size(); ++i) { auto& in = node.get_dependency(i); ss_inputs << in.id(); ss_inputs << ", count: " << in.get_output_layout().count(); i != (node.get_dependencies().size() - 1) ? ss_inputs << ", " : ss_inputs << ""; } json_composite generic_info; generic_info.add("type_name", type_name); generic_info.add("deps count", node.get_dependencies().size()); generic_info.add("deps", ss_inputs.str()); node_info.add("generic info", generic_info); node_info.dump(primitive_description); return primitive_description.str(); } }
33.244444
138
0.666889
mypopydev
577117501ac5044eb3128d584f6ee08d7efbb524
3,429
cpp
C++
test/poiner_variant_impl.cpp
foonathan/tiny
1fb39508d0320c61be5a0ecb670d55b889d7dc87
[ "BSL-1.0" ]
96
2018-11-09T13:29:02.000Z
2022-02-13T21:20:36.000Z
test/poiner_variant_impl.cpp
foonathan/tiny
1fb39508d0320c61be5a0ecb670d55b889d7dc87
[ "BSL-1.0" ]
1
2018-11-09T17:03:14.000Z
2018-11-09T18:12:10.000Z
test/poiner_variant_impl.cpp
foonathan/tiny
1fb39508d0320c61be5a0ecb670d55b889d7dc87
[ "BSL-1.0" ]
6
2019-01-04T13:02:27.000Z
2021-06-01T03:56:52.000Z
// Copyright (C) 2018 Jonathan Müller <jonathanmueller.dev@gmail.com> // This file is subject to the license terms in the LICENSE file // found in the top-level directory of this distribution. #include <foonathan/tiny/pointer_variant_impl.hpp> #include <catch.hpp> using namespace foonathan::tiny; namespace { template <typename T> struct get_pointer { using type = T; static T* get() { return reinterpret_cast<T*>(std::uintptr_t(1024)); } }; template <typename T, std::size_t Alignment> struct get_pointer<aligned_obj<T, Alignment>> { using type = T; static T* get() { return reinterpret_cast<T*>(std::uintptr_t(1024)); } }; template <typename A, typename B, typename C> void verify_variant_impl(bool is_compressed) { using variant = pointer_variant_impl<A, B, C>; REQUIRE(typename variant::is_compressed{} == is_compressed); auto a_ptr = get_pointer<A>::get(); using a_type = typename get_pointer<A>::type; using a_tag_t = typename variant::template tag_of<A>; REQUIRE(typename a_tag_t::is_valid{}); auto a_tag = a_tag_t::value; auto b_ptr = get_pointer<B>::get(); using b_type = typename get_pointer<B>::type; using b_tag_t = typename variant::template tag_of<B>; REQUIRE(typename b_tag_t::is_valid{}); auto b_tag = b_tag_t::value; auto c_ptr = get_pointer<C>::get(); using c_type = typename get_pointer<C>::type; using c_tag_t = typename variant::template tag_of<C>; REQUIRE(typename c_tag_t::is_valid{}); auto c_tag = c_tag_t::value; REQUIRE(a_tag != b_tag); REQUIRE(a_tag != c_tag); REQUIRE(b_tag != c_tag); auto verify_null = [&](const variant& v) { REQUIRE(!v.has_value()); REQUIRE(v.tag() != a_tag); REQUIRE(v.tag() != b_tag); REQUIRE(v.tag() != c_tag); REQUIRE(v.get() == nullptr); }; variant v(nullptr); verify_null(v); v.reset(a_ptr); REQUIRE(v.has_value()); REQUIRE(v.tag() == a_tag); REQUIRE(v.get() == a_ptr); REQUIRE(v.template pointer_to<a_type>() == a_ptr); v.reset(b_ptr); REQUIRE(v.has_value()); REQUIRE(v.tag() == b_tag); REQUIRE(v.get() == b_ptr); REQUIRE(v.template pointer_to<b_type>() == b_ptr); v.reset(nullptr); verify_null(v); v.reset(c_ptr); REQUIRE(v.has_value()); REQUIRE(v.tag() == c_tag); REQUIRE(v.get() == c_ptr); REQUIRE(v.template pointer_to<c_type>() == c_ptr); v.reset(static_cast<a_type*>(nullptr)); verify_null(v); } } // namespace TEST_CASE("pointer_variant_impl") { SECTION("not compressed: normal") { verify_variant_impl<std::int32_t, std::int64_t, const char>(false); } SECTION("not compressed: aligned_obj") { verify_variant_impl<std::int32_t, aligned_obj<char, 2>, const char>(false); } SECTION("compressed: normal") { verify_variant_impl<std::int32_t, std::int64_t, const std::uint32_t>(true); } SECTION("compressed: aligned_obj") { verify_variant_impl<std::int32_t, aligned_obj<char, 4>, aligned_obj<signed char, 8>>(true); } }
28.815126
99
0.588218
foonathan
5775045ade6c2ee5adad77152f22e911d987da8d
14,156
cpp
C++
SU2-Quantum/SU2_CFD/src/output/filewriter/CParaviewXMLFileWriter.cpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
null
null
null
SU2-Quantum/SU2_CFD/src/output/filewriter/CParaviewXMLFileWriter.cpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
null
null
null
SU2-Quantum/SU2_CFD/src/output/filewriter/CParaviewXMLFileWriter.cpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
1
2021-12-03T06:40:08.000Z
2021-12-03T06:40:08.000Z
/*! * \file CParaviewXMLFileWriter.cpp * \brief Filewriter class for Paraview binary format. * \author T. Albring * \version 7.0.6 "Blackbird" * * SU2 Project Website: https://su2code.github.io * * The SU2 Project is maintained by the SU2 Foundation * (http://su2foundation.org) * * Copyright 2012-2020, SU2 Contributors (cf. AUTHORS.md) * * SU2 is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * SU2 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with SU2. If not, see <http://www.gnu.org/licenses/>. */ #include "../../../include/output/filewriter/CParaviewXMLFileWriter.hpp" #include "../../../../Common/include/toolboxes/printing_toolbox.hpp" const string CParaviewXMLFileWriter::fileExt = ".vtu"; CParaviewXMLFileWriter::CParaviewXMLFileWriter(string valFileName, CParallelDataSorter *valDataSorter) : CFileWriter(std::move(valFileName), valDataSorter, fileExt){ /* Check for big endian. We have to swap bytes otherwise. * Since size of character is 1 byte when the character pointer * is de-referenced it will contain only first byte of integer. ---*/ bigEndian = false; unsigned int i = 1; char *c = (char*)&i; if (*c) bigEndian = false; else bigEndian = true; } CParaviewXMLFileWriter::~CParaviewXMLFileWriter(){ } void CParaviewXMLFileWriter::Write_Data(){ if (!dataSorter->GetConnectivitySorted()){ SU2_MPI::Error("Connectivity must be sorted.", CURRENT_FUNCTION); } /*--- We always have 3 coords, independent of the actual value of nDim ---*/ const int NCOORDS = 3; const unsigned short nDim = dataSorter->GetnDim(); unsigned short iDim = 0; /*--- Array containing the field names we want to output ---*/ const vector<string>& fieldNames = dataSorter->GetFieldNames(); unsigned long iPoint, iElem; char str_buf[255]; OpenMPIFile(); dataOffset = 0; /*--- Communicate the number of total points that will be written by each rank. After this communication, each proc knows how many poinnts will be written before its location in the file and the offsets can be correctly set. ---*/ unsigned long myPoint, GlobalPoint; GlobalPoint = dataSorter->GetnPointsGlobal(); myPoint = dataSorter->GetnPoints(); /*--- Compute our local number of elements, the required storage, and reduce the total number of elements and storage globally. ---*/ unsigned long myElem, myElemStorage, GlobalElem, GlobalElemStorage; unsigned long nParallel_Line = dataSorter->GetnElem(LINE), nParallel_Tria = dataSorter->GetnElem(TRIANGLE), nParallel_Quad = dataSorter->GetnElem(QUADRILATERAL), nParallel_Tetr = dataSorter->GetnElem(TETRAHEDRON), nParallel_Hexa = dataSorter->GetnElem(HEXAHEDRON), nParallel_Pris = dataSorter->GetnElem(PRISM), nParallel_Pyra = dataSorter->GetnElem(PYRAMID); myElem = dataSorter->GetnElem(); myElemStorage = dataSorter->GetnConn(); GlobalElem = dataSorter->GetnElemGlobal(); GlobalElemStorage = dataSorter->GetnConnGlobal(); /* Write the ASCII XML header. Note that we use the appended format for the data, * which means that all data is appended at the end of the file in one binary blob. */ if (!bigEndian){ WriteMPIString("<VTKFile type=\"UnstructuredGrid\" version=\"1.0\" byte_order=\"LittleEndian\" header_type=\"UInt64\">\n", MASTER_NODE); } else { WriteMPIString("<VTKFile type=\"UnstructuredGrid\" version=\"1.0\" byte_order=\"BigEndian\" header_type=\"UInt64\">\n", MASTER_NODE); } WriteMPIString("<UnstructuredGrid>\n", MASTER_NODE); SPRINTF(str_buf, "<Piece NumberOfPoints=\"%i\" NumberOfCells=\"%i\">\n", SU2_TYPE::Int(GlobalPoint), SU2_TYPE::Int(GlobalElem)); WriteMPIString(std::string(str_buf), MASTER_NODE); WriteMPIString("<Points>\n", MASTER_NODE); AddDataArray(VTKDatatype::FLOAT32, "", NCOORDS, myPoint*NCOORDS, GlobalPoint*NCOORDS); WriteMPIString("</Points>\n", MASTER_NODE); WriteMPIString("<Cells>\n", MASTER_NODE); AddDataArray(VTKDatatype::INT32, "connectivity", 1, myElemStorage, GlobalElemStorage); AddDataArray(VTKDatatype::INT32, "offsets", 1, myElem, GlobalElem); AddDataArray(VTKDatatype::UINT8, "types", 1, myElem, GlobalElem); WriteMPIString("</Cells>\n", MASTER_NODE); WriteMPIString("<PointData>\n", MASTER_NODE); /*--- Adjust container start location to avoid point coords. ---*/ unsigned short varStart = 2; if (nDim == 3) varStart++; /*--- Loop over all variables that have been registered in the output. ---*/ unsigned short iField, VarCounter = varStart; for (iField = varStart; iField < fieldNames.size(); iField++) { string fieldname = fieldNames[iField]; fieldname.erase(remove(fieldname.begin(), fieldname.end(), '"'), fieldname.end()); /*--- Check whether this field is a vector or scalar. ---*/ bool output_variable = true, isVector = false; size_t found = fieldNames[iField].find("_x"); if (found!=string::npos) { output_variable = true; isVector = true; } found = fieldNames[iField].find("_y"); if (found!=string::npos) { /*--- We have found a vector, so skip the Y component. ---*/ output_variable = false; VarCounter++; } found = fieldNames[iField].find("_z"); if (found!=string::npos) { /*--- We have found a vector, so skip the Z component. ---*/ output_variable = false; VarCounter++; } /*--- Write the point data as an <X,Y,Z> vector or a scalar. ---*/ if (output_variable && isVector) { /*--- Adjust the string name to remove the leading "X-" ---*/ fieldname.erase(fieldname.end()-2,fieldname.end()); AddDataArray(VTKDatatype::FLOAT32, fieldname, NCOORDS, myPoint*NCOORDS, GlobalPoint*NCOORDS); } else if (output_variable) { AddDataArray(VTKDatatype::FLOAT32, fieldname, 1, myPoint, GlobalPoint); } } WriteMPIString("</PointData>\n", MASTER_NODE); WriteMPIString("</Piece>\n", MASTER_NODE); WriteMPIString("</UnstructuredGrid>\n", MASTER_NODE); /*--- Now write all the data we have previously defined into the binary section of the file ---*/ WriteMPIString("<AppendedData encoding=\"raw\">\n_", MASTER_NODE); /*--- Load/write the 1D buffer of point coordinates. Note that we always have 3 coordinate dimensions, even for 2D problems. ---*/ vector<float> dataBufferFloat(myPoint*NCOORDS); for (iPoint = 0; iPoint < myPoint; iPoint++) { for (iDim = 0; iDim < NCOORDS; iDim++) { if (nDim == 2 && iDim == 2) { dataBufferFloat[iPoint*NCOORDS + iDim] = 0.0; } else { float val = (float)dataSorter->GetData(iDim, iPoint); dataBufferFloat[iPoint*NCOORDS + iDim] = val; } } } WriteDataArray(dataBufferFloat.data(), VTKDatatype::FLOAT32, NCOORDS*myPoint, GlobalPoint*NCOORDS, dataSorter->GetnPointCumulative(rank)*NCOORDS); /*--- Load/write 1D buffers for the connectivity of each element type. ---*/ vector<int> connBuf(myElemStorage); vector<int> offsetBuf(myElem); unsigned long iStorage = 0, iElemID = 0; unsigned short iNode = 0; auto copyToBuffer = [&](GEO_TYPE type, unsigned long nElem, unsigned short nPoints){ for (iElem = 0; iElem < nElem; iElem++) { for (iNode = 0; iNode < nPoints; iNode++){ connBuf[iStorage+iNode] = int(dataSorter->GetElem_Connectivity(type, iElem, iNode)-1); } iStorage += nPoints; offsetBuf[iElemID++] = int(iStorage + dataSorter->GetnElemConnCumulative(rank)); } }; copyToBuffer(LINE, nParallel_Line, N_POINTS_LINE); copyToBuffer(TRIANGLE, nParallel_Tria, N_POINTS_TRIANGLE); copyToBuffer(QUADRILATERAL, nParallel_Quad, N_POINTS_QUADRILATERAL); copyToBuffer(TETRAHEDRON, nParallel_Tetr, N_POINTS_TETRAHEDRON); copyToBuffer(HEXAHEDRON, nParallel_Hexa, N_POINTS_HEXAHEDRON); copyToBuffer(PRISM, nParallel_Pris, N_POINTS_PRISM); copyToBuffer(PYRAMID, nParallel_Pyra, N_POINTS_PYRAMID); WriteDataArray(connBuf.data(), VTKDatatype::INT32, myElemStorage, GlobalElemStorage, dataSorter->GetnElemConnCumulative(rank)); WriteDataArray(offsetBuf.data(), VTKDatatype::INT32, myElem, GlobalElem, dataSorter->GetnElemCumulative(rank)); /*--- Load/write the cell type for all elements in the file. ---*/ vector<uint8_t> typeBuf(myElem); vector<uint8_t>::iterator typeIter = typeBuf.begin(); std::fill(typeIter, typeIter+nParallel_Line, LINE); typeIter += nParallel_Line; std::fill(typeIter, typeIter+nParallel_Tria, TRIANGLE); typeIter += nParallel_Tria; std::fill(typeIter, typeIter+nParallel_Quad, QUADRILATERAL); typeIter += nParallel_Quad; std::fill(typeIter, typeIter+nParallel_Tetr, TETRAHEDRON); typeIter += nParallel_Tetr; std::fill(typeIter, typeIter+nParallel_Hexa, HEXAHEDRON); typeIter += nParallel_Hexa; std::fill(typeIter, typeIter+nParallel_Pris, PRISM); typeIter += nParallel_Pris; std::fill(typeIter, typeIter+nParallel_Pyra, PYRAMID); typeIter += nParallel_Pyra; WriteDataArray(typeBuf.data(), VTKDatatype::UINT8, myElem, GlobalElem, dataSorter->GetnElemCumulative(rank)); /*--- Loop over all variables that have been registered in the output. ---*/ VarCounter = varStart; for (iField = varStart; iField < fieldNames.size(); iField++) { /*--- Check whether this field is a vector or scalar. ---*/ bool output_variable = true, isVector = false; size_t found = fieldNames[iField].find("_x"); if (found!=string::npos) { output_variable = true; isVector = true; } found = fieldNames[iField].find("_y"); if (found!=string::npos) { /*--- We have found a vector, so skip the Y component. ---*/ output_variable = false; VarCounter++; } found = fieldNames[iField].find("_z"); if (found!=string::npos) { /*--- We have found a vector, so skip the Z component. ---*/ output_variable = false; VarCounter++; } /*--- Write the point data as an <X,Y,Z> vector or a scalar. ---*/ if (output_variable && isVector) { /*--- Load up the buffer for writing this rank's vector data. ---*/ float val = 0.0; for (iPoint = 0; iPoint < myPoint; iPoint++) { for (iDim = 0; iDim < NCOORDS; iDim++) { if (nDim == 2 && iDim == 2) { dataBufferFloat[iPoint*NCOORDS + iDim] = 0.0; } else { val = (float)dataSorter->GetData(VarCounter+iDim,iPoint); dataBufferFloat[iPoint*NCOORDS + iDim] = val; } } } WriteDataArray(dataBufferFloat.data(), VTKDatatype::FLOAT32, myPoint*NCOORDS, GlobalPoint*NCOORDS, dataSorter->GetnPointCumulative(rank)*NCOORDS); VarCounter++; } else if (output_variable) { /*--- For now, create a temp 1D buffer to load up the data for writing. This will be replaced with a derived data type most likely. ---*/ for (iPoint = 0; iPoint < myPoint; iPoint++) { float val = (float)dataSorter->GetData(VarCounter,iPoint); dataBufferFloat[iPoint] = val; } WriteDataArray(dataBufferFloat.data(), VTKDatatype::FLOAT32, myPoint, GlobalPoint, dataSorter->GetnPointCumulative(rank)); VarCounter++; } } WriteMPIString("</AppendedData>\n", MASTER_NODE); WriteMPIString("</VTKFile>\n", MASTER_NODE); CloseMPIFile(); } void CParaviewXMLFileWriter::WriteDataArray(void* data, VTKDatatype type, unsigned long arraySize, unsigned long globalSize, unsigned long offset){ std::string typeStr; unsigned long typeSize = 0; GetTypeInfo(type, typeStr, typeSize); /*--- Compute the size of the data to write in bytes ---*/ int byteSize; byteSize = arraySize*typeSize; /*--- The total data size ---*/ unsigned long totalByteSize; totalByteSize = globalSize*typeSize; /*--- Only the master node writes the total size in bytes as unsigned long in front of the array data ---*/ if (!WriteMPIBinaryData(&totalByteSize, sizeof(unsigned long), MASTER_NODE)){ SU2_MPI::Error("Writing array size failed", CURRENT_FUNCTION); } /*--- Collectively write all the data ---*/ if (!WriteMPIBinaryDataAll(data, byteSize, totalByteSize, offset*typeSize)){ SU2_MPI::Error("Writing data array failed", CURRENT_FUNCTION); } } void CParaviewXMLFileWriter::AddDataArray(VTKDatatype type, string name, unsigned short nComponents, unsigned long arraySize, unsigned long globalSize){ /*--- Add quotation marks around the arguments ---*/ name = "\"" + name + "\""; string nComp ="\"" + PrintingToolbox::to_string(nComponents) + "\""; /*--- Full precision ASCII output of offset for 32 bit integer ---*/ stringstream ss; ss.precision(10); ss.setf(std::ios::fixed, std::ios::floatfield); ss << "\"" << dataOffset << "\""; string offsetStr = ss.str(); std::string typeStr; unsigned long typeSize = 0, totalByteSize; GetTypeInfo(type, typeStr, typeSize); /*--- Total data size ---*/ totalByteSize = globalSize*typeSize; /*--- Write the ASCII XML header information for this array ---*/ WriteMPIString(string("<DataArray type=") + typeStr + string(" Name=") + name + string(" NumberOfComponents= ") + nComp + string(" offset=") + offsetStr + string(" format=\"appended\"/>\n"), MASTER_NODE); dataOffset += totalByteSize + sizeof(unsigned long); }
35.837975
140
0.666502
Agony5757
5775afc3bd539cd97b23a3a15f3950aa3b600cfc
1,833
cpp
C++
src/Widget.cpp
Ingener74/Nodewitter
759e7a6c782c831c6aed3d55cfcdb71846a06708
[ "MIT" ]
null
null
null
src/Widget.cpp
Ingener74/Nodewitter
759e7a6c782c831c6aed3d55cfcdb71846a06708
[ "MIT" ]
null
null
null
src/Widget.cpp
Ingener74/Nodewitter
759e7a6c782c831c6aed3d55cfcdb71846a06708
[ "MIT" ]
null
null
null
// // Created by Pavel on 26.08.2017. // #include "Widget.h" Widget::Widget() {} Widget::Widget(std::string const &id) : id(id) { } Widget::~Widget() { } void Widget::SetId(std::string const &id) { Widget::id = id; } const std::string &Widget::GetId() const { return id; } void Widget::SetPos(float x, float y) { Widget::x = x; Widget::y = y; } void Widget::SetSize(float w, float h) { Widget::w = w; Widget::h = h; } void Widget::Show() { bVisible = true; } void Widget::Hide() { bVisible = false; } void Widget::Enter() { hgeGUIObject::Enter(); // CallEvent(MouseEnter); } void Widget::Leave() { hgeGUIObject::Leave(); // CallEvent(MouseLeave); } bool Widget::IsDone() { return hgeGUIObject::IsDone(); } void Widget::Focus(bool bFocused) { hgeGUIObject::Focus(bFocused); } void Widget::MouseOver(bool bOver) { bOver ? CallEvent(MouseEnter) : CallEvent(MouseLeave); hgeGUIObject::MouseOver(bOver); } bool Widget::MouseMove(float x, float y) { return hgeGUIObject::MouseMove(x, y); } bool Widget::MouseLButton(bool bDown) { bDown ? CallEvent(MouseLDown) : CallEvent(MouseLUp); return hgeGUIObject::MouseLButton(bDown); } bool Widget::MouseRButton(bool bDown) { bDown ? CallEvent(MouseRDown) : CallEvent(MouseRUp); return hgeGUIObject::MouseRButton(bDown); } bool Widget::MouseWheel(int nNotches) { return hgeGUIObject::MouseWheel(nNotches); } bool Widget::KeyClick(int key, int chr) { return hgeGUIObject::KeyClick(key, chr); } void Widget::SetEventHandler(Event event, EventHandler eventHandler) { eventHandlers[event] = eventHandler; } void Widget::CallEvent(Event event) { EventHandlers::iterator ehIt = eventHandlers.find(event); if (ehIt != eventHandlers.end() && (*ehIt).second) (*ehIt).second(this); }
19.709677
70
0.665576
Ingener74
577cd9c85a3128c6ce5d217b084a1b959d75173a
2,736
hpp
C++
src/thread/ProcessingThread.hpp
tlmrgvf/drtd
bf31747b963673797239cb11cd45c1c1ee4aeaa6
[ "BSD-2-Clause" ]
6
2020-07-11T11:16:18.000Z
2021-12-17T23:30:36.000Z
src/thread/ProcessingThread.hpp
tlmrgvf/drtd
bf31747b963673797239cb11cd45c1c1ee4aeaa6
[ "BSD-2-Clause" ]
9
2020-07-03T21:23:50.000Z
2022-02-15T12:56:16.000Z
src/thread/ProcessingThread.hpp
tlmrgvf/drtd
bf31747b963673797239cb11cd45c1c1ee4aeaa6
[ "BSD-2-Clause" ]
null
null
null
/* BSD 2-Clause License Copyright (c) 2020, Till Mayer All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED 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. */ #pragma once #include <atomic> #include <decoder/Decoder.hpp> #include <thread> #include <util/Buffer.hpp> #include <util/Resampler.hpp> #include <util/Logger.hpp> namespace Dsp { class ProcessingLock final { public: ProcessingLock(bool from_main_thread = true); ~ProcessingLock(); private: ProcessingLock(const ProcessingLock&) = delete; ProcessingLock(const ProcessingLock&&) = delete; ProcessingLock& operator=(const ProcessingLock&) = delete; ProcessingLock& operator=(const ProcessingLock&&) = delete; static inline std::mutex s_pipeline_mutex; }; class ProcessingThread { public: static constexpr size_t s_sample_buffer_size { 1024 }; ProcessingThread(std::shared_ptr<Dsp::DecoderBase> decoder, SampleRate input_sample_rate, SampleRate target_sample_rate); virtual ~ProcessingThread() {} void start(); void request_stop_and_wait(); void join(); bool is_running(); protected: std::thread& thread() { return m_thread; } void request_stop() { m_run.store(false); }; private: void run(); virtual void on_stop_requested() {}; virtual size_t fill_buffer(Util::Buffer<float>&) = 0; Logger m_log {"Processing thread"}; std::unique_ptr<Util::Resampler> m_resampler; std::shared_ptr<Dsp::DecoderBase> m_decoder; std::atomic<bool> m_run { true }; std::thread m_thread {}; bool m_running { false }; }; }
32.963855
125
0.754751
tlmrgvf
577d41ab5891c3050a5b3bf52ce276a4fbdeb97c
510
cpp
C++
src/robot/graphical/components/lineClass.cpp
1069B/Tower_Takeover
331a323216cd006a8cc3bc7a326ebe3a463e429f
[ "MIT" ]
null
null
null
src/robot/graphical/components/lineClass.cpp
1069B/Tower_Takeover
331a323216cd006a8cc3bc7a326ebe3a463e429f
[ "MIT" ]
3
2019-07-26T15:56:19.000Z
2019-07-29T02:55:32.000Z
src/robot/graphical/components/lineClass.cpp
1069B/Tower_Takeover
331a323216cd006a8cc3bc7a326ebe3a463e429f
[ "MIT" ]
null
null
null
#include "robot/graphical/components/lineClass.hpp" #include "robot/graphical/components/passInfo.hpp" #include "robot/graphical/screenClass.hpp" Line::Line(const PassInfo& p_info, Screen& p_screen): m_screen(p_screen){ m_points = p_info.points; m_style = p_info.style1; } void Line::draw(){ m_line = lv_line_create(m_screen.getObject(), NULL); lv_line_set_points(m_line, m_points, 2); lv_obj_align(m_line, m_screen.getObject(), LV_ALIGN_IN_TOP_LEFT, 0, 0); lv_line_set_style(m_line, m_style); }
31.875
73
0.762745
1069B
578186ba2dfdc05317aed07cb344ba63bb8c927b
654
cpp
C++
firmware/ToneClass.cpp
pooyapooya/rizpardazande
818721a3daac1385daf71ac508ad00bf153cbf0b
[ "MIT" ]
1
2018-08-02T12:08:24.000Z
2018-08-02T12:08:24.000Z
firmware/ToneClass.cpp
pooyapooya/rizpardazande
818721a3daac1385daf71ac508ad00bf153cbf0b
[ "MIT" ]
null
null
null
firmware/ToneClass.cpp
pooyapooya/rizpardazande
818721a3daac1385daf71ac508ad00bf153cbf0b
[ "MIT" ]
1
2018-08-02T12:13:08.000Z
2018-08-02T12:13:08.000Z
#include <Arduino.h> #include "ToneClass.h" #include <stdlib.h> void nanpy::ToneClass::elaborate( nanpy::MethodDescriptor* m ) { if (strcmp(m->getClass(), "Tone") == 0) { ObjectsManager::elaborate(m); if (strcmp(m->getName(),"new") == 0) { v.insert(new Tone (m->getInt(0))); m->returns(v.getLastIndex()); } if (strcmp(m->getName(), "play") == 0) { v[m->getObjectId()]->play(m->getInt(0), m->getInt(0)); m->returns(0); } if (strcmp(m->getName(), "stop") == 0) { v[m->getObjectId()]->stop(); m->returns(0); } } };
24.222222
66
0.480122
pooyapooya
578374281864cdbbcf9947891ed79edf12d14c85
10,000
cpp
C++
WinSTDyn/OSEnvironment/OSEnvironment.cpp
chen0040/ogre-war-game-simulator
58eee268eae0612d206e7eb0b8e495708db1ef27
[ "MIT" ]
null
null
null
WinSTDyn/OSEnvironment/OSEnvironment.cpp
chen0040/ogre-war-game-simulator
58eee268eae0612d206e7eb0b8e495708db1ef27
[ "MIT" ]
null
null
null
WinSTDyn/OSEnvironment/OSEnvironment.cpp
chen0040/ogre-war-game-simulator
58eee268eae0612d206e7eb0b8e495708db1ef27
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "OSEnvironment.h" #include <sstream> #include <fstream> #include <iostream> #include <io.h> #include <vector> #include <iomanip> #include <shlobj.h> #include <boost/filesystem.hpp> #include <atlstr.h> std::string OSEnvironment::getApplicationDir() { TCHAR appPath1[_MAX_PATH]; ::GetModuleFileName(NULL, appPath1, _MAX_PATH); std::string path=CT2CA(appPath1); size_t end_index=path.rfind("\\"); return path.substr(0, end_index); } bool OSEnvironment::copyFile2Folder(const std::string& filename, const std::string& sourceFolderPath, const std::string& destinationFolderPath) { std::ostringstream oss1; oss1 << sourceFolderPath << "\\" << filename; std::string sourceFile=oss1.str(); if(!OSEnvironment::exists(sourceFile)) { return false; } std::ostringstream oss2; oss2 << destinationFolderPath << "\\" << filename; OSEnvironment::copyFile(sourceFile, oss2.str()); return true; } std::string OSEnvironment::getFullPath(std::string relPath) { TCHAR appPath1[_MAX_PATH]; ::GetModuleFileName(NULL, appPath1, _MAX_PATH); std::string path=CT2CA(appPath1); size_t end_index=path.rfind("\\"); path.replace(end_index+1, path.length()-end_index, relPath); return path; } void OSEnvironment::showWinMsgBox(const char* msg, const char* title, UINT uType) { ::ShowCursor(TRUE); MessageBox(NULL, CA2CT(msg), CA2CT(title), uType); ::ShowCursor(FALSE); } std::string OSEnvironment::append(const std::string& str1, const std::string& str2) { std::ostringstream oss; oss << str1 << str2; return oss.str(); } bool OSEnvironment::replaceFileContent(const std::string& destinationFile, const std::map<std::string, std::string>& dic, bool onceOnly) { std::vector<std::string> outlines; std::ifstream infile; infile.open(destinationFile.c_str()); std::string line; bool found=false; while(std::getline(infile, line)) { if((!found) || (!onceOnly)) { std::map<std::string, std::string>::const_iterator miter; for(miter=dic.begin(); miter != dic.end(); ++miter) { const std::string& paramName=miter->first; const std::string& paramValue=miter->second; size_t fnd=line.find(paramName); if(onceOnly) { if(fnd != std::string::npos) { line.replace(fnd, paramName.length(), paramValue); found=true; break; } } else { while(fnd != std::string::npos) { found=true; line.replace(fnd, paramName.length(), paramValue); fnd=line.find(paramName); } } } } outlines.push_back(line); } infile.close(); std::ofstream outfile; outfile.open(destinationFile.c_str()); for(size_t i=0; i<outlines.size(); ++i) { outfile << outlines[i] << "\n"; } outfile.close(); return found; } std::string OSEnvironment::readFile(std::string fileName) { std::ostringstream oss; std::ifstream ifs; ifs.open(fileName.c_str()); std::string line; while(!ifs.eof()) { std::getline(ifs, line); oss << line; } ifs.close(); return oss.str(); } bool OSEnvironment::copyFile(const std::string& sourceFile, const std::string& destinationFile, bool FailedIfExists) { if(!exists(sourceFile)) { return false; } std::string destinationFileDir=getParentDirectory(destinationFile); if(!exists(destinationFileDir)) { createDirectory(destinationFileDir); } BOOL bFailedIfExists=FailedIfExists ? TRUE : FALSE; if(::CopyFile(CA2CT(sourceFile.c_str()), CA2CT(destinationFile.c_str()), bFailedIfExists) == TRUE) { return true; } else { return false; } } bool OSEnvironment::copyFolder(const std::string& sourceFolder, const std::string& destinationFolder) { if(!exists(sourceFolder)) { return false; } if(!exists(destinationFolder)) { createDirectory(destinationFolder); } using namespace boost::filesystem; directory_iterator end_iterator; path dir_path(sourceFolder); for(boost::filesystem::directory_iterator iter(dir_path); iter != end_iterator; ++iter) { std::ostringstream oss1; oss1 << sourceFolder << "\\" << iter->leaf(); std::ostringstream oss2; oss2 << destinationFolder << "\\" << iter->leaf(); if(boost::filesystem::is_directory(iter->status())) { copyFolder(oss1.str(), oss2.str()); } else { copyFile(oss1.str(), oss2.str()); } } return true; } bool OSEnvironment::exists(const std::string& fileName) { if(_access(fileName.c_str(), 0)==-1) { return false; } else { return true; } } std::string OSEnvironment::getWinFolderSelector() { ::ShowCursor(TRUE); TCHAR path[MAX_PATH]; BROWSEINFO bi = { 0 }; bi.ulFlags |= BIF_NEWDIALOGSTYLE; bi.lpszTitle = _T("Browse Folder"); LPITEMIDLIST pidl = ::SHBrowseForFolder(&bi); std::string folderName=""; if(pidl != 0) { // get the name of the folder and put it in path ::SHGetPathFromIDList (pidl, path); folderName=CT2CA(path); IMalloc * imalloc = 0; if ( SUCCEEDED( SHGetMalloc ( &imalloc )) ) { imalloc->Free (pidl); imalloc->Release( ); } } ::ShowCursor(FALSE); return folderName; } std::string OSEnvironment::getWinSaveFileDialog(const char* filtertype, const char* filterextension) { OPENFILENAME sfn; TCHAR szFile[MAX_PATH]; TCHAR currentDir[MAX_PATH]; TCHAR* szTitle=_T("Save File Dialog"); szFile[0]='\0'; ::GetCurrentDirectory(MAX_PATH, currentDir); ::ShowCursor(TRUE); size_t ftLen=strlen(filtertype); size_t feLen=strlen(filterextension); CA2CT szFilterType(filtertype); CA2CT szFilterExtension(filterextension); size_t index=0; TCHAR szFilter[MAX_PATH]; for(size_t i=0; i< ftLen; ++i) { szFilter[index++]=szFilterType[i]; } szFilter[index++]='\0'; szFilter[index++]='*'; szFilter[index++]='.'; for(size_t i=0; i<feLen; ++i) { szFilter[index++]=szFilterExtension[i]; } szFilter[index++]='\0'; szFilter[index++]='\0'; ::ZeroMemory(&sfn, sizeof(OPENFILENAME)); sfn.lStructSize = sizeof(OPENFILENAME); sfn.lpstrFilter = szFilter; sfn.nFilterIndex = 0; sfn.lpstrFile = szFile; sfn.nMaxFile = sizeof(szFile) / sizeof(*szFile); sfn.lpstrInitialDir = currentDir; sfn.lpstrTitle = szTitle; sfn.nMaxFileTitle=sizeof(szTitle); sfn.Flags = OFN_CREATEPROMPT | OFN_OVERWRITEPROMPT; //OFN_NOREADONLYRETURN if(GetSaveFileName(&sfn) == TRUE) { ::SetCurrentDirectory(currentDir); ::ShowCursor(FALSE); return std::string(CT2CA(szFile)); } else { ::SetCurrentDirectory(currentDir); ::ShowCursor(FALSE); return ""; } } std::string OSEnvironment::getWinOpenFileDialog(const char* filtertype, const char* filterextension) { OPENFILENAME ofn; TCHAR szFile[MAX_PATH]; TCHAR currentDir[MAX_PATH]; TCHAR* szTitle=_T("Open File Dialog"); szFile[0] = '\0'; ::GetCurrentDirectory(MAX_PATH, currentDir); ::ShowCursor(TRUE); size_t ftLen=strlen(filtertype); size_t feLen=strlen(filterextension); CA2CT szFilterType(filtertype); CA2CT szFilterExtension(filterextension); size_t index=0; TCHAR szFilter[MAX_PATH]; for(size_t i=0; i<ftLen; ++i) { szFilter[index++]=szFilterType[i]; } szFilter[index++]='\0'; szFilter[index++]='*'; szFilter[index++]='.'; for(size_t i=0; i<feLen; ++i) { szFilter[index++]=szFilterExtension[i]; } szFilter[index++]='\0'; szFilter[index++]='\0'; ::ZeroMemory(&ofn, sizeof(OPENFILENAME)); ofn.lStructSize = sizeof(OPENFILENAME); ofn.lpstrFilter =szFilter; ofn.lpstrFile = szFile; ofn.nMaxFile = sizeof(szFile) / sizeof(*szFile); ofn.nFilterIndex = 0; ofn.lpstrInitialDir = currentDir; ofn.lpstrTitle =szTitle; ofn.nMaxFileTitle=sizeof(szTitle); ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST; if(::GetOpenFileName(&ofn) == TRUE) { ::SetCurrentDirectory(currentDir); ::ShowCursor(FALSE); return std::string(CT2CA(szFile)); } else { ::SetCurrentDirectory(currentDir); ::ShowCursor(FALSE); return ""; } } bool OSEnvironment::createDirectory(const std::string& dir) { if(exists(dir)) { return true; } std::string parentDirectory=getParentDirectory(dir); if(!exists(parentDirectory)) { createDirectory(parentDirectory); } ::CreateDirectory(CA2CT(dir.c_str()), NULL); return true; } std::string OSEnvironment::getParentDirectory(const std::string& path) { size_t fnd=path.rfind("\\"); if(fnd != std::string::npos) { return path.substr(0, fnd); } return ""; } int OSEnvironment::parseInt(const std::string& strVal) { std::istringstream iss(strVal); int val; iss >> val; return val; } double OSEnvironment::parseDouble(const std::string& strVal) { std::istringstream iss(strVal); double val; iss >> val; return val; } float OSEnvironment::parseFloat(const std::string& strVal) { std::istringstream iss(strVal); float val; iss >> val; return val; } void OSEnvironment::writeLines(const std::string& destinationFile, const std::string& fileType, const std::vector<std::string>& lines) { std::ofstream outfile; outfile.open(destinationFile.c_str()); for(size_t i=0; i<lines.size(); ++i) { outfile << lines[i] << "\n"; } outfile.close(); } std::string OSEnvironment::toString(float val) { std::ostringstream oss; oss << val; return oss.str(); } std::string OSEnvironment::toString(int val) { std::ostringstream oss; oss << val; return oss.str(); } std::string OSEnvironment::toString(size_t val) { std::ostringstream oss; oss << val; return oss.str(); } void OSEnvironment::setCurrentDir2ExecutableDir() { std::string appDir=OSEnvironment::getApplicationDir(); ::SetCurrentDirectory(CA2CT(appDir.c_str())); } std::string OSEnvironment::createSQLDateTimeString(std::string& ms) { std::ostringstream oss; SYSTEMTIME st; ::GetSystemTime(&st); oss << st.wYear << "-"; oss << st.wMonth << "-"; oss << st.wDay << " "; oss << std::setfill('0') << std::setw(2) << st.wHour << ":"; oss << std::setfill('0') << std::setw(2) << st.wMinute << ":"; oss << std::setfill('0') << std::setw(2) << st.wSecond; std::ostringstream oss2; oss2 << st.wMilliseconds; ms=oss2.str(); //1776-7-4 04:13:54 return oss.str(); }
21.367521
144
0.6831
chen0040
5789ac8b0d197f3c47ff42e1fea7e1f3b3000c4c
2,531
cpp
C++
STM32F407/Src-rtt/user_main.cpp
SuWeipeng/car_407ve_rtt
c04745c4801998e6d82db516138d6adf846e64f8
[ "Apache-2.0" ]
8
2020-01-19T00:04:35.000Z
2022-01-05T19:08:05.000Z
STM32F407/Src-rtt/user_main.cpp
SuWeipeng/car_407ve_rtt
c04745c4801998e6d82db516138d6adf846e64f8
[ "Apache-2.0" ]
null
null
null
STM32F407/Src-rtt/user_main.cpp
SuWeipeng/car_407ve_rtt
c04745c4801998e6d82db516138d6adf846e64f8
[ "Apache-2.0" ]
3
2020-02-26T01:26:22.000Z
2021-01-26T06:02:56.000Z
#include <rtthread.h> #include <rtdevice.h> #include <board.h> #include <stdlib.h> #include "rtt_interface.h" #include "AC_Base.h" #include "Logger.h" #include "AP_Buffer.h" #include "SRV_Channel.h" #include "mode.h" #if defined(__ICCARM__) || defined(__GNUC__) #include "AP_RangeFinder.h" #include "AP_KF.h" #endif using namespace rtthread; #if defined(__ICCARM__) || defined(__GNUC__) static rt_timer_t vl53lxx_timer; #endif extern TIM_HandleTypeDef htim2; extern TIM_HandleTypeDef htim11; extern rt_device_t vcom; AC_Base *base; AP_Buffer *buffer; Mode *car_mode; ModeManual *mode_manual; ModeAuto *mode_auto; ModeROS *mode_ros; SRV_Channel *servo_bottom; SRV_Channel *servo_top; Mode::Number current_mode = Mode::Number::MAN; Mode::Number prev_mode = Mode::Number::MAN; Mode::ModeReason mode_reason = Mode::ModeReason::UNKNOWN; #if defined(__ICCARM__) || defined(__GNUC__) RangeFinder *range_finder; AP_KF *kalman_filter; #endif extern "C" { #if defined(__ICCARM__) || defined(__GNUC__) static int sensor_timer_create(); static void vl53lxx_timeout(void *parameter); #endif void setup(void) { base = new AC_Base(AC_Base::Type::MECANUM_4WD); buffer = new AP_Buffer(); servo_bottom = new SRV_Channel(&htim2 , TIM_CHANNEL_1, SERVO_MAX_PWM, SERVO_MIN_PWM); servo_top = new SRV_Channel(&htim11, TIM_CHANNEL_1, SERVO_MAX_PWM, SERVO_MIN_PWM); mode_manual = new ModeManual(); mode_auto = new ModeAuto(); mode_ros = new ModeROS(); car_mode = mode_manual; base->init(); buffer->init(AP_Buffer::RING); #if defined(__ICCARM__) || defined(__GNUC__) range_finder = new RangeFinder(); range_finder->init(RangeFinder::Type::VL53L0X); sensor_timer_create(); kalman_filter = new AP_KF(); kalman_filter->set_var(1e-2, 6.75); #endif //Log_Init(); } void loop(void* parameter) { while(1) { update_mode(); rt_thread_delay(50); } } #if defined(__ICCARM__) || defined(__GNUC__) static int sensor_timer_create() { RTT_TIMER_CREATE(vl53lxx,vl53lxx_timeout,RT_NULL,33,RT_TIMER_FLAG_SOFT_TIMER | RT_TIMER_CTRL_SET_PERIODIC); return 0; } static void vl53lxx_timeout(void *parameter) { // read vl53lxx range_finder->timer(parameter); // updae data range_finder->update(); //char buf[100]; //sprintf(buf, "dist_cm: %d\r\n", range_finder->distance_cm()); //rt_kputs(buf); //Write_RangeFinder(range_finder->distance_cm()); } #endif //#if defined(__ICCARM__) || defined(__GNUC__) } // extern "C"
23.877358
109
0.713157
SuWeipeng
578b34c0678726d348f2d7925ce7b8279b6750dc
6,888
cpp
C++
Libraries/RobsJuceModules/jura_framework/gui/panels/jura_DualWaveformDisplay.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
34
2017-04-19T18:26:02.000Z
2022-02-15T17:47:26.000Z
Libraries/RobsJuceModules/jura_framework/gui/panels/jura_DualWaveformDisplay.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
307
2017-05-04T21:45:01.000Z
2022-02-03T00:59:01.000Z
Libraries/RobsJuceModules/jura_framework/gui/panels/jura_DualWaveformDisplay.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
4
2017-09-05T17:04:31.000Z
2021-12-15T21:24:28.000Z
//------------------------------------------------------------------------------------------------- // construction/destruction: DualWaveformDisplay::DualWaveformDisplay(AudioFileBuffer* newBuffer) : Component("DualWaveformDisplay"), AudioFileBufferUser(newBuffer) { //ScopedLock pointerLock(audioFileBufferPointerLock); //lockUsedBufferPointer(); addAndMakeVisible( waveDisplayL = new WaveformDisplay(newBuffer) ); //waveDisplayL->setAxisPositionX(CoordinateSystem::INVISIBLE); //waveDisplayL->setAxisPositionY(CoordinateSystem::INVISIBLE); waveDisplayL->plotOnlyOneChannel(0); addAndMakeVisible( waveDisplayR = new WaveformDisplay(newBuffer) ); //waveDisplayR->setAxisPositionX(CoordinateSystem::INVISIBLE); //waveDisplayR->setAxisPositionY(CoordinateSystem::INVISIBLE); waveDisplayR->plotOnlyOneChannel(1); //unlockUsedBufferPointer(); } DualWaveformDisplay::~DualWaveformDisplay() { //ScopedLock pointerLock(audioFileBufferPointerLock); //lockUsedBufferPointer(); deleteAllChildren(); //unlockUsedBufferPointer(); } //------------------------------------------------------------------------------------------------- // setup: void DualWaveformDisplay::assignAudioFileBuffer(AudioFileBuffer* newBuffer) { lockUsedBufferPointer(); AudioFileBufferUser::assignAudioFileBuffer(newBuffer); waveDisplayL->assignAudioFileBuffer(newBuffer); waveDisplayR->assignAudioFileBuffer(newBuffer); unlockUsedBufferPointer(); resized(); // to update the arrangement of one or two displays } //------------------------------------------------------------------------------------------------- // appearance stuff: void DualWaveformDisplay::resized() { //ScopedLock pointerLock(audioFileBufferPointerLock); lockUsedBufferPointer(); //int x = 0; int w = getWidth(); int h = getHeight(); /* // handle the situation when no audio buffer is assigned: if( bufferToUse == NULL ) { waveDisplayL->setBounds(0, 0, w, h ); waveDisplayR->setBounds(0, h/2, w, h/2); return; } */ int numChannels = waveDisplayL->getNumChannels(); // show either one waveform display over the full height (for mono clips) or two displays of // half height (for stereo clips) if( numChannels < 2 ) { waveDisplayL->setBounds(0, 0, w, h); waveDisplayR->setBounds(0, 0, 0, 0); } else { waveDisplayL->setBounds(0, 0, w, h/2); waveDisplayR->setBounds(0, h/2, w, h/2); } unlockUsedBufferPointer(); } //------------------------------------------------------------------------------------------------- // the CoordinateSystem mimics: double DualWaveformDisplay::getMaximumRangeMinX() const { //ScopedLock pointerLock(audioFileBufferPointerLock); return waveDisplayL->getMaximumRangeMinX(); } double DualWaveformDisplay::getMaximumRangeMaxX() const { //ScopedLock pointerLock(audioFileBufferPointerLock); return waveDisplayL->getMaximumRangeMaxX(); } double DualWaveformDisplay::getCurrentRangeMinX() const { //ScopedLock pointerLock(audioFileBufferPointerLock); return waveDisplayL->getCurrentRangeMinX(); } double DualWaveformDisplay::getCurrentRangeMaxX() const { //ScopedLock pointerLock(audioFileBufferPointerLock); return waveDisplayL->getCurrentRangeMaxX(); } void DualWaveformDisplay::setMaximumRange(double newMinX, double newMaxX, double newMinY, double newMaxY) { //ScopedLock pointerLock(audioFileBufferPointerLock); waveDisplayL->setMaximumRange(newMinX, newMaxX, newMinY, newMaxY); waveDisplayR->setMaximumRange(newMinX, newMaxX, newMinY, newMaxY); } void DualWaveformDisplay::setMaximumRangeX(double newMinX, double newMaxX) { //ScopedLock pointerLock(audioFileBufferPointerLock); waveDisplayL->setMaximumRangeX(newMinX, newMaxX); waveDisplayR->setMaximumRangeX(newMinX, newMaxX); } void DualWaveformDisplay::setMaximumRangeY(double newMinY, double newMaxY) { //ScopedLock pointerLock(audioFileBufferPointerLock); waveDisplayL->setMaximumRangeY(newMinY, newMaxY); waveDisplayR->setMaximumRangeY(newMinY, newMaxY); } void DualWaveformDisplay::setCurrentRange(double newMinX, double newMaxX, double newMinY, double newMaxY) { //ScopedLock pointerLock(audioFileBufferPointerLock); waveDisplayL->setCurrentRange(newMinX, newMaxX, newMinY, newMaxY); waveDisplayR->setCurrentRange(newMinX, newMaxX, newMinY, newMaxY); } void DualWaveformDisplay::setCurrentRangeX(double newMinX, double newMaxX) { //ScopedLock pointerLock(audioFileBufferPointerLock); waveDisplayL->setCurrentRangeX(newMinX, newMaxX); waveDisplayR->setCurrentRangeX(newMinX, newMaxX); } void DualWaveformDisplay::setCurrentRangeMinX(double newMinX) { //ScopedLock pointerLock(audioFileBufferPointerLock); waveDisplayL->setCurrentRangeMinX(newMinX); waveDisplayR->setCurrentRangeMinX(newMinX); } void DualWaveformDisplay::setCurrentRangeMaxX(double newMaxX) { //ScopedLock pointerLock(audioFileBufferPointerLock); waveDisplayL->setCurrentRangeMaxX(newMaxX); waveDisplayR->setCurrentRangeMaxX(newMaxX); } void DualWaveformDisplay::setCurrentRangeY(double newMinY, double newMaxY) { //ScopedLock pointerLock(audioFileBufferPointerLock); waveDisplayL->setCurrentRangeY(newMinY, newMaxY); waveDisplayR->setCurrentRangeY(newMinY, newMaxY); } void DualWaveformDisplay::setDrawingThread(TimeSliceThread* newDrawingThread) { waveDisplayL->setDrawingThread(newDrawingThread); waveDisplayR->setDrawingThread(newDrawingThread); } void DualWaveformDisplay::setVisibleTimeRange(double newMinTimeInSeconds, double newMaxTimeInSeconds) { //ScopedLock pointerLock(audioFileBufferPointerLock); waveDisplayL->setVisibleTimeRange(newMinTimeInSeconds, newMaxTimeInSeconds); waveDisplayR->setVisibleTimeRange(newMinTimeInSeconds, newMaxTimeInSeconds); } void DualWaveformDisplay::updatePlotImage() { //ScopedLock pointerLock(audioFileBufferPointerLock); waveDisplayL->setDirty(); waveDisplayR->setDirty(); } void DualWaveformDisplay::lockUsedBufferPointer() { AudioFileBufferUser::lockUsedBufferPointer(); waveDisplayL->lockUsedBufferPointer(); waveDisplayR->lockUsedBufferPointer(); } void DualWaveformDisplay::unlockUsedBufferPointer() { waveDisplayR->unlockUsedBufferPointer(); waveDisplayL->unlockUsedBufferPointer(); AudioFileBufferUser::unlockUsedBufferPointer(); } void DualWaveformDisplay::acquireAudioFileBufferWriteLock() { AudioFileBufferUser::acquireAudioFileBufferWriteLock(); waveDisplayL->acquireAudioFileBufferWriteLock(); waveDisplayR->acquireAudioFileBufferWriteLock(); } void DualWaveformDisplay::releaseAudioFileBufferWriteLock() { waveDisplayR->releaseAudioFileBufferWriteLock(); waveDisplayL->releaseAudioFileBufferWriteLock(); AudioFileBufferUser::releaseAudioFileBufferWriteLock(); }
31.59633
99
0.732143
RobinSchmidt
578c3fdf19ce32d93dd251eb0e9ed059b316a3f5
8,826
cpp
C++
src/common/AxisUtils.cpp
vlsinitsyn/axis1
65a622201e526dedf7c3aeadce7cac5bd79895bf
[ "Apache-2.0" ]
1
2021-11-10T19:36:30.000Z
2021-11-10T19:36:30.000Z
src/common/AxisUtils.cpp
vlsinitsyn/axis1
65a622201e526dedf7c3aeadce7cac5bd79895bf
[ "Apache-2.0" ]
null
null
null
src/common/AxisUtils.cpp
vlsinitsyn/axis1
65a622201e526dedf7c3aeadce7cac5bd79895bf
[ "Apache-2.0" ]
2
2021-11-02T13:09:57.000Z
2021-11-10T19:36:22.000Z
/* -*- C++ -*- */ /* * Copyright 2003-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * @author Susantha Kumara (skumara@virtusa.com) * @author Roshan Weerasuriya (roshanw@jkcsworld.com, roshan@opensource.lk, roshan_444@yahoo.com) * */ // !!! This include file must be first thing in file !!! #include "../platforms/PlatformAutoSense.hpp" #include <axis/AxisUserAPI.hpp> #include "AxisUtils.h" #include "../soap/apr_base64.h" #include "AxisTrace.h" AXIS_CPP_NAMESPACE_START AxisXMLCh AxisUtils::m_Buffer[CONVERT_BUFFER_SIZE]; AxisUtils::AxisUtils () { } AxisUtils::~AxisUtils () { } const AxisXMLCh* AxisUtils::ToAxisXMLCh (const AxisChar* pch) { /* return XMLString::transcode(pch); * this is ok as long as we use xerces library. */ return pch; } void AxisUtils::initialize () { } /* following functions is not thread safe and should only be used * for initialization purposes. */ const AxisXMLCh * AxisUtils::Convert (const AxisChar * pch) { /* if (XMLString::transcode(pch, m_Buffer, CONVERT_BUFFER_SIZE)) * return m_Buffer; * return NULL; */ return pch; } int AxisUtils::clearArray (char* arrCh, int iSize) { for (int iTmp = 0; iTmp < iSize; iTmp++) { arrCh[iTmp] = '\0'; } return AXIS_SUCCESS; } bool AxisUtils::isCharacterAvailable (const string &sString, const char cCharacter) { bool bFoundStatus = false; if ((sString.find (cCharacter, 0)) != string::npos) { bFoundStatus = true; } return bFoundStatus; } bool AxisUtils::isCharacterAvailable (const char* pchStringToSearch, const char cCharacter) { bool bFoundStatus = false; if (strchr (pchStringToSearch, cCharacter)) { bFoundStatus = true; } return bFoundStatus; } string AxisUtils::toUpperCase (const string sWord) { /* Fill the code */ return NULL; } char* AxisUtils::toUpperCase (const char* pchWord) { /* Fill the code */ return NULL; } string AxisUtils::toLowerCase (const string sWord) { /* Fill the code */ return NULL; } char* AxisUtils::toLowerCase (const char* pchWord) { /* Fill the code */ return NULL; } xsd__base64Binary * AxisUtils::decodeFromBase64Binary(const AxisChar *pValue) { xsd__base64Binary* value = new xsd__base64Binary(); int size = apr_base64_decode_len (pValue); xsd__unsignedByte * pTemp = new unsigned char[size + 1]; size = apr_base64_decode_binary (pTemp, pValue); pTemp[size] = 0; // Null terminate so it could be used as a string value->set(pTemp, size); delete [] pTemp; return value; } bool AxisUtils::isStringOnlyWithSpaces(const char* pchWord) { bool blnStatus = true; int iLen = strlen(pchWord); for (int i=0; i<iLen; i++) { if (pchWord[i] != ' ') { blnStatus = false; break; } } return blnStatus; } IAnySimpleType* AxisUtils::createSimpleTypeObject(XSDTYPE type) { return createSimpleTypeObject(NULL, type); } IAnySimpleType* AxisUtils::createSimpleTypeObject(void * pValue, XSDTYPE type) { logEntryEngine("AxisUtils::createSimpleTypeObject") IAnySimpleType* xsdValue = NULL; // Put commonly used type at top of switch statement! switch (type) { case XSD_STRING: xsdValue = new String((xsd__string) pValue); break; case XSD_NORMALIZEDSTRING: xsdValue = new NormalizedString((xsd__normalizedString) pValue); break; case XSD_DECIMAL: xsdValue = new Decimal((xsd__decimal*) pValue); break; case XSD_INTEGER: xsdValue = new Integer((xsd__integer*) pValue); break; case XSD_LONG: xsdValue = new Long((xsd__long*) pValue); break; case XSD_INT: xsdValue = new Int((xsd__int*) pValue); break; case XSD_SHORT: xsdValue = new Short((xsd__short*) pValue); break; case XSD_BYTE: xsdValue = new Byte((xsd__byte*) pValue); break; case XSD_NONNEGATIVEINTEGER: xsdValue = new NonNegativeInteger((xsd__nonNegativeInteger*) pValue); break; case XSD_UNSIGNEDLONG: xsdValue = new UnsignedLong((xsd__unsignedLong*) pValue); break; case XSD_UNSIGNEDINT: xsdValue = new UnsignedInt((xsd__unsignedInt*) pValue); break; case XSD_UNSIGNEDSHORT: xsdValue = new UnsignedShort((xsd__unsignedShort*) pValue); break; case XSD_UNSIGNEDBYTE: xsdValue = new UnsignedByte((xsd__unsignedByte*) pValue); break; case XSD_POSITIVEINTEGER: xsdValue = new PositiveInteger((xsd__positiveInteger*) pValue); break; case XSD_NONPOSITIVEINTEGER: xsdValue = new NonPositiveInteger((xsd__nonPositiveInteger*) pValue); break; case XSD_NEGATIVEINTEGER: xsdValue = new NegativeInteger((xsd__negativeInteger*) pValue); break; case XSD_FLOAT: xsdValue = new Float((xsd__float*) pValue); break; case XSD_BOOLEAN: xsdValue = new Boolean((xsd__boolean*) pValue); break; case XSD_DOUBLE: xsdValue = new Double((xsd__double*) pValue); break; case XSD_DURATION: xsdValue = new Duration((xsd__duration*) pValue); break; case XSD_DATETIME: xsdValue = new DateTime((xsd__dateTime*) pValue); break; case XSD_TIME: xsdValue = new Time((xsd__time*) pValue); break; case XSD_DATE: xsdValue = new Date((xsd__date*) pValue); break; case XSD_GYEARMONTH: xsdValue = new GYearMonth((xsd__gYearMonth*) pValue); break; case XSD_GYEAR: xsdValue = new GYear((xsd__gYear*) pValue); break; case XSD_GMONTHDAY: xsdValue = new GMonthDay((xsd__gMonthDay*) pValue); break; case XSD_GDAY: xsdValue = new GDay((xsd__gDay*) pValue); break; case XSD_GMONTH: xsdValue = new GMonth((xsd__gMonth*) pValue); break; case XSD_HEXBINARY: xsdValue = new HexBinary((xsd__hexBinary*) pValue); break; case XSD_BASE64BINARY: xsdValue = new Base64Binary((xsd__base64Binary*) pValue); break; case XSD_ANYURI: xsdValue = new AnyURI((xsd__anyURI) pValue); break; case XSD_QNAME: xsdValue = new XSD_QName((xsd__QName) pValue); break; case XSD_NOTATION: xsdValue = new NOTATION((xsd__NOTATION) pValue); break; case XSD_TOKEN: xsdValue = new Token((xsd__token) pValue); break; case XSD_LANGUAGE: xsdValue = new Language((xsd__language) pValue); break; case XSD_NAME: xsdValue = new Name((xsd__Name) pValue); break; case XSD_NCNAME: xsdValue = new NCName((xsd__NCName) pValue); break; case XSD_ID: xsdValue = new ID((xsd__ID) pValue); break; case XSD_IDREF: xsdValue = new IDREF((xsd__IDREF) pValue); break; case XSD_IDREFS: xsdValue = new IDREFS((xsd__IDREFS) pValue); break; case XSD_ENTITY: xsdValue = new ENTITY((xsd__ENTITY) pValue); break; case XSD_ENTITIES: xsdValue = new ENTITIES((xsd__ENTITIES) pValue); break; case XSD_NMTOKEN: xsdValue = new NMTOKEN((xsd__NMTOKEN) pValue); break; case XSD_NMTOKENS: xsdValue = new NMTOKENS((xsd__NMTOKENS) pValue); break; case XSD_ANYTYPE: xsdValue = new AnyType2((xsd__anyType) pValue); break; default: break; } logExitWithPointer(xsdValue) return xsdValue; } AXIS_CPP_NAMESPACE_END
26.908537
97
0.600725
vlsinitsyn
c237f9fc1ca14be7d63ad58b08100b1c3bc23395
1,563
cpp
C++
src/modules/packet/generator/traffic/length_template.cpp
gchagnotSpt/openperf
0ae14cb7a685b1b059f707379773fb3bcb421d40
[ "Apache-2.0" ]
20
2019-12-04T01:28:52.000Z
2022-03-17T14:09:34.000Z
src/modules/packet/generator/traffic/length_template.cpp
gchagnotSpt/openperf
0ae14cb7a685b1b059f707379773fb3bcb421d40
[ "Apache-2.0" ]
115
2020-02-04T21:29:54.000Z
2022-02-17T13:33:51.000Z
src/modules/packet/generator/traffic/length_template.cpp
gchagnotSpt/openperf
0ae14cb7a685b1b059f707379773fb3bcb421d40
[ "Apache-2.0" ]
16
2019-12-03T16:41:18.000Z
2021-11-06T04:44:11.000Z
#include "packet/generator/traffic/length_template.hpp" #include "utils/overloaded_visitor.hpp" namespace openperf::packet::generator::traffic { length_container get_lengths(const length_config& config) { return (std::visit( utils::overloaded_visitor( [](const length_fixed_config& fixed) { return (length_container{fixed.length}); }, [](const length_list_config& list) { return (list.items); }, [](const length_sequence_config& seq) { return (ranges::to<length_container>(modifier::to_range(seq))); }), config)); } length_container get_lengths(length_config&& config) { return (get_lengths(config)); } length_template::length_template(length_container&& lengths) : m_lengths(std::move(lengths)) {} uint16_t length_template::max_packet_length() const { return (*(std::max_element(std::begin(m_lengths), std::end(m_lengths)))); } size_t length_template::size() const { return (m_lengths.size()); } length_template::view_type length_template::operator[](size_t idx) const { return (m_lengths[idx]); } length_template::iterator length_template::begin() { return (iterator(*this)); } length_template::const_iterator length_template::begin() const { return (iterator(*this)); } length_template::iterator length_template::end() { return (iterator(*this, size())); } length_template::const_iterator length_template::end() const { return (iterator(*this, size())); } } // namespace openperf::packet::generator::traffic
26.491525
80
0.68778
gchagnotSpt
c240626234213bf83b24e123c9ac27339c4fbc35
2,087
hpp
C++
src/algorithms/data_structures/array/array_permutations.hpp
iamantony/CppNotes
2707db6560ad80b0e5e286a04b2d46e5c0280b3f
[ "MIT" ]
2
2020-07-31T14:13:56.000Z
2021-02-03T09:51:43.000Z
src/algorithms/data_structures/array/array_permutations.hpp
iamantony/CppNotes
2707db6560ad80b0e5e286a04b2d46e5c0280b3f
[ "MIT" ]
28
2015-09-22T07:38:21.000Z
2018-10-02T11:00:58.000Z
src/algorithms/data_structures/array/array_permutations.hpp
iamantony/CppNotes
2707db6560ad80b0e5e286a04b2d46e5c0280b3f
[ "MIT" ]
2
2018-10-11T14:10:50.000Z
2021-02-27T08:53:50.000Z
#ifndef ARRAY_PERMUTATIONS_HPP #define ARRAY_PERMUTATIONS_HPP /* https://leetcode.com/problems/permutations/description/ Given a collection of distinct integers, return all possible permutations. Example: Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] https://leetcode.com/problems/permutations-ii/description/ Given a collection of numbers that might contain duplicates, return all possible unique permutations. Example: Input: [1,1,2] Output: [ [1,1,2], [1,2,1], [2,1,1] ] */ #include <vector> #include <algorithm> namespace Algo::DS::Array { class ArrayPermutations { public: static std::vector<std::vector<int>> GetAll(std::vector<int> v) { std::vector<std::vector<int>> result; if (v.empty()) { return result; } CreatePermutation(v, 0, v.size() - 1, result); std::sort(result.begin(), result.end()); return result; } static std::vector<std::vector<int>> GetUnique(std::vector<int> v) { std::vector<std::vector<int>> allPermut = GetAll(v); if (allPermut.size() < 2) { return allPermut; } std::sort(allPermut.begin(), allPermut.end()); std::vector<std::vector<int>> result; result.push_back(allPermut[0]); for (size_t i = 1; i < allPermut.size(); ++i) { if (allPermut[i] != allPermut[i - 1]) { result.push_back(allPermut[i]); } } return result; } private: static void CreatePermutation(std::vector<int>& v, const size_t& left, const size_t& right, std::vector<std::vector<int>>& result) { if (left >= right) { result.push_back(v); } else { for (size_t i = left; i <= right; ++i) { std::swap(v[i], v[left]); CreatePermutation(v, left + 1, right, result); std::swap(v[i], v[left]); } } } }; } #endif // ARRAY_PERMUTATIONS_HPP
22.44086
74
0.548155
iamantony
c240b6d834c87e5fd237d91a213e2771f97ed6fe
3,575
cpp
C++
Teaching/NodeEditor/ParamWidget.cpp
ryhanai/teachingplugin
a495885899eaa36ea00ba8ab89057cd4d3f36350
[ "MIT" ]
2
2020-07-21T06:08:42.000Z
2020-07-21T06:08:44.000Z
Teaching/NodeEditor/ParamWidget.cpp
ryhanai/teachingplugin
a495885899eaa36ea00ba8ab89057cd4d3f36350
[ "MIT" ]
null
null
null
Teaching/NodeEditor/ParamWidget.cpp
ryhanai/teachingplugin
a495885899eaa36ea00ba8ab89057cd4d3f36350
[ "MIT" ]
null
null
null
#include "ParamWidget.hpp" #include "../TeachingEventHandler.h" #include "../TeachingUtil.h" #include "../LoggerUtil.h" ParamWidget::ParamWidget(QWidget* parent) : QWidget(parent) { //setStyleSheet( "QWidget{ background-color : rgba( 160, 160, 160, 255); border-radius : 7px; }" ); nameEdit = new QLineEdit(this); valueEdit = new QLineEdit(this); nameEdit->setText("screw pos"); valueEdit->setText("0.0"); QVBoxLayout* layout = new QVBoxLayout(); layout->addWidget(nameEdit); layout->addWidget(valueEdit); setLayout(layout); } FrameParamWidget::FrameParamWidget(QWidget* parent) : QWidget(parent) { //setStyleSheet( "QWidget{ background-color : rgba( 160, 160, 160, 255); border-radius : 7px; }" ); nameEdit = new QLineEdit(this); xEdit = new QLineEdit(this); yEdit = new QLineEdit(this); zEdit = new QLineEdit(this); rxEdit = new QLineEdit(this); ryEdit = new QLineEdit(this); rzEdit = new QLineEdit(this); nameEdit->setText("screw pos"); xEdit->setText("0.0"); yEdit->setText("0.0"); zEdit->setText("0.0"); rxEdit->setText("0.0"); ryEdit->setText("0.0"); rzEdit->setText("0.0"); QGridLayout* layout = new QGridLayout(); layout->addWidget(nameEdit, 0, 0, 1, 3); layout->addWidget(xEdit, 1, 0, 1, 1); layout->addWidget(yEdit, 1, 1, 1, 1); layout->addWidget(zEdit, 1, 2, 1, 1); layout->addWidget(rxEdit, 2, 0, 1, 1); layout->addWidget(ryEdit, 2, 1, 1, 1); layout->addWidget(rzEdit, 2, 2, 1, 1); setLayout(layout); } ////////// ModelWidget::ModelWidget(QWidget* parent) : QWidget(parent), flowModelParamId_(NULL_ID){ imageView = new QGraphicsView(); scene = new QGraphicsScene(); imageView->setScene(scene); nameEdit = new QLineEdit; nameEdit->setText("New Model Param"); cmbModelName = new QComboBox; cmbModelName->addItem("XXXXXXXXXXXXXXX"); // QGridLayout* layout = new QGridLayout(); layout->addWidget(imageView, 0, 0, 2, 1); layout->addWidget(nameEdit, 0, 1, 1, 1); layout->addWidget(cmbModelName, 1, 1, 1, 1); setLayout(layout); connect(cmbModelName, SIGNAL(currentIndexChanged(int)), this, SLOT(modelSelectionChanged(int))); } void ModelWidget::showModelInfo() { cmbModelName->clear(); modelMasterList_ = TeachingDataHolder::instance()->getModelMasterList(); for (int index = 0; index < modelMasterList_.size(); index++) { ModelMasterParamPtr param = modelMasterList_[index]; cmbModelName->addItem(param->getName(), param->getId()); } } void ModelWidget::modelSelectionChanged(int index) { scene->clear(); int modelId = cmbModelName->itemData(index).toInt(); vector<ModelMasterParamPtr>::iterator masterParamItr = find_if(modelMasterList_.begin(), modelMasterList_.end(), ModelMasterComparator(modelId)); if (masterParamItr == modelMasterList_.end()) return; QPixmap pixmap = QPixmap::fromImage((*masterParamItr)->getImage()); if (!pixmap.isNull()) { pixmap = pixmap.scaled(imageView->width() - 5, imageView->height() - 5, Qt::KeepAspectRatio, Qt::FastTransformation); } scene->addPixmap(pixmap); // if (0 < flowModelParamId_) { TeachingEventHandler::instance()->flv_ModelParamChanged(flowModelParamId_, *masterParamItr); } } void ModelWidget::setMasterInfo(int masterId) { int masterIndex = 0; for (int index = 0; index < cmbModelName->count(); index++) { if (cmbModelName->itemData(index) == masterId) { masterIndex = index; break; } } cmbModelName->setCurrentIndex(masterIndex); }
34.047619
148
0.67049
ryhanai
c242a8c291fe9e7a1719cd5b61b3cb9d4932244a
6,297
cpp
C++
TESTS/network/wifi/main.cpp
pradeep-gr/mbed-os5-onsemi
576d096f2d9933c39b8a220f486e9756d89173f2
[ "Apache-2.0" ]
7
2017-01-15T16:37:41.000Z
2021-08-10T02:14:04.000Z
TESTS/network/wifi/main.cpp
pradeep-gr/mbed-os5-onsemi
576d096f2d9933c39b8a220f486e9756d89173f2
[ "Apache-2.0" ]
1
2018-05-18T10:50:02.000Z
2018-05-18T10:50:02.000Z
TESTS/network/wifi/main.cpp
pradeep-gr/mbed-os5-onsemi
576d096f2d9933c39b8a220f486e9756d89173f2
[ "Apache-2.0" ]
9
2017-04-27T07:54:26.000Z
2021-08-10T02:14:05.000Z
/* mbed Microcontroller Library * Copyright (c) 2016 ARM Limited * * 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 "utest/utest.h" #include "unity/unity.h" #include "greentea-client/test_env.h" #include "mbed.h" #if TARGET_UBLOX_EVK_ODIN_W2 #include "OdinWiFiInterface.h" #else #error [NOT_SUPPORTED] Only built in WiFi modules are supported at this time. #endif using namespace utest::v1; /** * WiFi tests require following macros to be defined: * - MBED_CONF_APP_WIFI_SSID - SSID of a network the test will try connecting to * - MBED_CONF_APP_WIFI_PASSWORD - Passphrase that will be used to connecting to the network * - WIFI_TEST_NETWORKS - List of network that presence will be asserted e.g. "net1", "net2", "net3" */ #if !defined(MBED_CONF_APP_WIFI_SSID) || !defined(MBED_CONF_APP_WIFI_PASSWORD) || !defined(MBED_CONF_APP_WIFI_NETWORKS) #error [NOT_SUPPORTED] MBED_CONF_APP_WIFI_SSID, MBED_CONF_APP_WIFI_PASSWORD and MBED_CONF_APP_WIFI_NETWORKS have to be defined for this test. #endif const char *networks[] = {MBED_CONF_APP_WIFI_NETWORKS, NULL}; WiFiInterface *wifi; /* In normal circumstances the WiFi object could be global, but the delay introduced by WiFi initialization is an issue for the tests. It causes Greentea to timeout on syncing with the board. To solve it we defer the actual object creation till we actually need it. */ WiFiInterface *get_wifi() { if (wifi == NULL) { /* We don't really care about freeing this, as its lifetime is through the full test suit run. */ #if TARGET_UBLOX_EVK_ODIN_W2 wifi = new OdinWiFiInterface; #endif } return wifi; } void check_wifi(const char *ssid, bool *net_stat) { int i = 0; while(networks[i]) { if (strcmp(networks[i], ssid) == 0) { net_stat[i] = true; break; } i++; } } void wifi_scan() { int count; WiFiAccessPoint *aps; const int net_len = sizeof(networks)/sizeof(networks[0]); bool net_stat[net_len - 1]; memset(net_stat, 0, sizeof(net_stat)); count = get_wifi()->scan(NULL, 0); TEST_ASSERT_MESSAGE(count >= 0, "WiFi interface returned error"); TEST_ASSERT_MESSAGE(count > 0, "Scan result empty"); aps = new WiFiAccessPoint[count]; count = get_wifi()->scan(aps, count); for(int i = 0; i < count; i++) { check_wifi(aps[i].get_ssid(), net_stat); } delete[] aps; for (unsigned i = 0; i < sizeof(net_stat); i++) { TEST_ASSERT_MESSAGE(net_stat[i] == true, "Not all required WiFi network detected"); } } void wifi_connect() { int ret; ret = get_wifi()->connect(MBED_CONF_APP_WIFI_SSID, MBED_CONF_APP_WIFI_PASSWORD, NSAPI_SECURITY_WPA_WPA2); TEST_ASSERT_MESSAGE(ret == 0, "Connect failed"); ret = get_wifi()->disconnect(); TEST_ASSERT_MESSAGE(ret == 0, "Disconnect failed"); } void wifi_connect_scan() { int ret; int count; WiFiAccessPoint *aps; const int net_len = sizeof(networks)/sizeof(networks[0]); bool net_stat[net_len - 1]; memset(net_stat, 0, sizeof(net_stat)); ret = get_wifi()->connect(MBED_CONF_APP_WIFI_SSID, MBED_CONF_APP_WIFI_PASSWORD, NSAPI_SECURITY_WPA_WPA2); TEST_ASSERT_MESSAGE(ret == 0, "Connect failed"); count = get_wifi()->scan(NULL, 0); TEST_ASSERT_MESSAGE(count >= 0, "WiFi interface returned error"); TEST_ASSERT_MESSAGE(count > 0, "Scan result empty"); aps = new WiFiAccessPoint[count]; count = get_wifi()->scan(aps, count); for(int i = 0; i < count; i++) { check_wifi(aps[i].get_ssid(), net_stat); } delete[] aps; ret = get_wifi()->disconnect(); TEST_ASSERT_MESSAGE(ret == 0, "Disconnect failed"); for (unsigned i = 0; i < sizeof(net_stat); i++) { TEST_ASSERT_MESSAGE(net_stat[i] == true, "Not all required WiFi network detected"); } } void wifi_http() { TCPSocket socket; int ret; ret = get_wifi()->connect(MBED_CONF_APP_WIFI_SSID, MBED_CONF_APP_WIFI_PASSWORD, NSAPI_SECURITY_WPA_WPA2); TEST_ASSERT_MESSAGE(ret == 0, "Connect failed"); // Open a socket on the network interface, and create a TCP connection to www.arm.com ret = socket.open(get_wifi()); TEST_ASSERT_MESSAGE(ret == 0, "Socket open failed"); ret = socket.connect("www.arm.com", 80); TEST_ASSERT_MESSAGE(ret == 0, "Socket connect failed"); // Send a simple http request char sbuffer[] = "GET / HTTP/1.1\r\nHost: www.arm.com\r\n\r\n"; int scount = socket.send(sbuffer, sizeof sbuffer); TEST_ASSERT_MESSAGE(scount >= 0, "Socket send failed"); // Recieve a simple http response and check if it's not empty char rbuffer[64]; int rcount = socket.recv(rbuffer, sizeof rbuffer); TEST_ASSERT_MESSAGE(rcount >= 0, "Socket recv error"); TEST_ASSERT_MESSAGE(rcount > 0, "No data received"); ret = socket.close(); TEST_ASSERT_MESSAGE(ret == 0, "Socket close failed"); ret = get_wifi()->disconnect(); TEST_ASSERT_MESSAGE(ret == 0, "Disconnect failed"); } status_t greentea_failure_handler(const Case *const source, const failure_t reason) { greentea_case_failure_abort_handler(source, reason); return STATUS_CONTINUE; } Case cases[] = { Case("Scan test", wifi_scan, greentea_failure_handler), Case("Connect test", wifi_connect, greentea_failure_handler), Case("Scan while connected test", wifi_connect_scan, greentea_failure_handler), Case("HTTP test", wifi_http, greentea_failure_handler), }; status_t greentea_test_setup(const size_t number_of_cases) { GREENTEA_SETUP(90, "default_auto"); return greentea_test_setup_handler(number_of_cases); } int main() { Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler); Harness::run(specification); }
31.964467
141
0.698428
pradeep-gr
c245a47f8969f5028610449d9b98ed96fb979682
861
cpp
C++
COJ/COJ Progressive Contest #8/TobyAndGraph.cpp
MartinAparicioPons/Competitive-Programming
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
[ "Apache-2.0" ]
1
2019-09-29T03:58:35.000Z
2019-09-29T03:58:35.000Z
COJ/COJ Progressive Contest #8/TobyAndGraph.cpp
MartinAparicioPons/Competitive-Programming
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
[ "Apache-2.0" ]
null
null
null
COJ/COJ Progressive Contest #8/TobyAndGraph.cpp
MartinAparicioPons/Competitive-Programming
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> #define DEB(x) cerr << "#" << (#x) << ": " << (x) << endl using namespace std; typedef long long ll; typedef pair<int, int> ii; typedef pair<int, ii> iii; typedef vector<int> vi; typedef vector<ii> vii; typedef vector<vi> vvi; const int MAXN = 10010; vi G[MAXN]; bool vis[MAXN]; void dfs(int v){ for(int i = 0; i < G[v].size(); i++){ if(!vis[G[v][i]]){ vis[G[v][i]] = true; dfs(G[v][i]); } } } int main () { ios_base::sync_with_stdio(0); cin.tie(0); int n, m, i, a, b, T, r; cin >> T; while(T--){ cin >> n >> m; memset(vis, 0, sizeof vis); for(i = 1; i <= n; i++) G[i].clear(); for(i = 0; i < m; i++){ cin >> a >> b; G[a].push_back(b); G[b].push_back(a); } for(i = 1, r = 0; i <= n; i++){ if(vis[i]) continue; vis[i] = true; r++; dfs(i); } cout << (r*(r-1))/2 << "\n"; } }
19.568182
57
0.497096
MartinAparicioPons
c246f747c0c221357307596931c7804f458554c0
18,730
cpp
C++
src/modules/SD2/scripts/northrend/icecrown_citadel/icecrown_citadel/instance_icecrown_citadel.cpp
Zilvereyes/ServerThree
b61c215b000f199eb884ebc39844ebbbd0703a1b
[ "PostgreSQL", "Zlib", "OpenSSL" ]
null
null
null
src/modules/SD2/scripts/northrend/icecrown_citadel/icecrown_citadel/instance_icecrown_citadel.cpp
Zilvereyes/ServerThree
b61c215b000f199eb884ebc39844ebbbd0703a1b
[ "PostgreSQL", "Zlib", "OpenSSL" ]
null
null
null
src/modules/SD2/scripts/northrend/icecrown_citadel/icecrown_citadel/instance_icecrown_citadel.cpp
Zilvereyes/ServerThree
b61c215b000f199eb884ebc39844ebbbd0703a1b
[ "PostgreSQL", "Zlib", "OpenSSL" ]
null
null
null
/* Copyright (C) 2006 - 2013 ScriptDev2 <http://www.scriptdev2.com/> * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: instance_icecrown_citadel SD%Complete: 20% SDComment: Just basic stuff SDCategory: Icecrown Citadel EndScriptData */ #include "precompiled.h" #include "icecrown_citadel.h" enum { // Marrowgar SAY_MARROWGAR_INTRO = -1631001, // Deathwhisper SAY_DEATHWHISPER_SPEECH_1 = -1631011, SAY_DEATHWHISPER_SPEECH_2 = -1631012, SAY_DEATHWHISPER_SPEECH_3 = -1631013, SAY_DEATHWHISPER_SPEECH_4 = -1631014, SAY_DEATHWHISPER_SPEECH_5 = -1631015, SAY_DEATHWHISPER_SPEECH_6 = -1631016, SAY_DEATHWHISPER_SPEECH_7 = -1631017, // Festergut SAY_STINKY_DIES = -1631081, // Rotface SAY_PRECIOUS_DIES = -1631070, }; static const DialogueEntry aCitadelDialogue[] = { {SAY_DEATHWHISPER_SPEECH_1, NPC_LADY_DEATHWHISPER, 12000}, {SAY_DEATHWHISPER_SPEECH_2, NPC_LADY_DEATHWHISPER, 11000}, {SAY_DEATHWHISPER_SPEECH_3, NPC_LADY_DEATHWHISPER, 10000}, {SAY_DEATHWHISPER_SPEECH_4, NPC_LADY_DEATHWHISPER, 9000}, {SAY_DEATHWHISPER_SPEECH_5, NPC_LADY_DEATHWHISPER, 10000}, {SAY_DEATHWHISPER_SPEECH_6, NPC_LADY_DEATHWHISPER, 10000}, {SAY_DEATHWHISPER_SPEECH_7, NPC_LADY_DEATHWHISPER, 0}, {0, 0, 0}, }; instance_icecrown_citadel::instance_icecrown_citadel(Map* pMap) : ScriptedInstance(pMap), DialogueHelper(aCitadelDialogue), m_uiTeam(0), m_uiPutricideValveTimer(0), m_bHasMarrowgarIntroYelled(false), m_bHasDeathwhisperIntroYelled(false), m_bHasRimefangLanded(false), m_bHasSpinestalkerLanded(false) { Initialize(); } void instance_icecrown_citadel::Initialize() { InitializeDialogueHelper(this); memset(&m_auiEncounter, 0, sizeof(m_auiEncounter)); } bool instance_icecrown_citadel::IsEncounterInProgress() const { for (uint8 i = 0; i < MAX_ENCOUNTER; ++i) { if (m_auiEncounter[i] == IN_PROGRESS) return true; } return false; } void instance_icecrown_citadel::DoHandleCitadelAreaTrigger(uint32 uiTriggerId, Player* pPlayer) { if (uiTriggerId == AREATRIGGER_MARROWGAR_INTRO && !m_bHasMarrowgarIntroYelled) { if (Creature* pMarrowgar = GetSingleCreatureFromStorage(NPC_LORD_MARROWGAR)) { DoScriptText(SAY_MARROWGAR_INTRO, pMarrowgar); m_bHasMarrowgarIntroYelled = true; } } else if (uiTriggerId == AREATRIGGER_DEATHWHISPER_INTRO && !m_bHasDeathwhisperIntroYelled) { StartNextDialogueText(SAY_DEATHWHISPER_SPEECH_1); m_bHasDeathwhisperIntroYelled = true; } else if (uiTriggerId == AREATRIGGER_SINDRAGOSA_PLATFORM) { if (Creature* pSindragosa = GetSingleCreatureFromStorage(NPC_SINDRAGOSA)) { if (pSindragosa->IsAlive() && !pSindragosa->IsInCombat()) pSindragosa->SetInCombatWithZone(); } else { if (!m_bHasRimefangLanded) { if (Creature* pRimefang = GetSingleCreatureFromStorage(NPC_RIMEFANG)) { pRimefang->AI()->AttackStart(pPlayer); m_bHasRimefangLanded = true; } } if (!m_bHasSpinestalkerLanded) { if (Creature* pSpinestalker = GetSingleCreatureFromStorage(NPC_SPINESTALKER)) { pSpinestalker->AI()->AttackStart(pPlayer); m_bHasSpinestalkerLanded = true; } } } } } void instance_icecrown_citadel::OnPlayerEnter(Player* pPlayer) { if (!m_uiTeam) // very first player to enter m_uiTeam = pPlayer->GetTeam(); } void instance_icecrown_citadel::OnCreatureCreate(Creature* pCreature) { switch (pCreature->GetEntry()) { case NPC_LORD_MARROWGAR: case NPC_LADY_DEATHWHISPER: case NPC_DEATHBRINGER_SAURFANG: case NPC_FESTERGUT: case NPC_ROTFACE: case NPC_PROFESSOR_PUTRICIDE: case NPC_TALDARAM: case NPC_VALANAR: case NPC_KELESETH: case NPC_LANATHEL_INTRO: case NPC_VALITHRIA: case NPC_SINDRAGOSA: case NPC_LICH_KING: case NPC_TIRION: case NPC_RIMEFANG: case NPC_SPINESTALKER: case NPC_VALITHRIA_COMBAT_TRIGGER: case NPC_BLOOD_ORB_CONTROL: m_mNpcEntryGuidStore[pCreature->GetEntry()] = pCreature->GetObjectGuid(); break; case NPC_DEATHWHISPER_SPAWN_STALKER: m_lDeathwhisperStalkersGuids.push_back(pCreature->GetObjectGuid()); return; } } void instance_icecrown_citadel::OnObjectCreate(GameObject* pGo) { switch (pGo->GetEntry()) { case GO_ICEWALL_1: case GO_ICEWALL_2: case GO_ORATORY_DOOR: if (m_auiEncounter[TYPE_MARROWGAR] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; case GO_DEATHWHISPER_ELEVATOR: // ToDo: set in motion when TYPE_LADY_DEATHWHISPER == DONE break; case GO_SAURFANG_DOOR: case GO_SCIENTIST_DOOR: case GO_CRIMSON_HALL_DOOR: case GO_GREEN_DRAGON_ENTRANCE: if (m_auiEncounter[TYPE_DEATHBRINGER_SAURFANG] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; case GO_ORANGE_TUBE: if (m_auiEncounter[TYPE_FESTERGUT] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; case GO_GREEN_TUBE: if (m_auiEncounter[TYPE_ROTFACE] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; case GO_SCIENTIST_DOOR_GREEN: // If both Festergut and Rotface are DONE, set as ACTIVE_ALTERNATIVE if (m_auiEncounter[TYPE_FESTERGUT] == DONE && m_auiEncounter[TYPE_ROTFACE] == DONE) pGo->SetGoState(GO_STATE_ACTIVE_ALTERNATIVE); else if (m_auiEncounter[TYPE_ROTFACE] == DONE) pGo->SetGoState(GO_STATE_READY); break; case GO_SCIENTIST_DOOR_ORANGE: // If both Festergut and Rotface are DONE, set as ACTIVE_ALTERNATIVE if (m_auiEncounter[TYPE_FESTERGUT] == DONE && m_auiEncounter[TYPE_ROTFACE] == DONE) pGo->SetGoState(GO_STATE_ACTIVE_ALTERNATIVE); else if (m_auiEncounter[TYPE_FESTERGUT] == DONE) pGo->SetGoState(GO_STATE_READY); break; case GO_SCIENTIST_DOOR_COLLISION: if (m_auiEncounter[TYPE_FESTERGUT] == DONE && m_auiEncounter[TYPE_ROTFACE] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; case GO_COUNCIL_DOOR_1: case GO_COUNCIL_DOOR_2: if (m_auiEncounter[TYPE_BLOOD_PRINCE_COUNCIL] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; case GO_GREEN_DRAGON_EXIT: if (m_auiEncounter[TYPE_VALITHRIA] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; case GO_SAURFANG_CACHE: case GO_SAURFANG_CACHE_25: case GO_SAURFANG_CACHE_10_H: case GO_SAURFANG_CACHE_25_H: m_mGoEntryGuidStore[GO_SAURFANG_CACHE] = pGo->GetObjectGuid(); return; case GO_GUNSHIP_ARMORY_A: case GO_GUNSHIP_ARMORY_A_25: case GO_GUNSHIP_ARMORY_A_10H: case GO_GUNSHIP_ARMORY_A_25H: m_mGoEntryGuidStore[GO_GUNSHIP_ARMORY_A] = pGo->GetObjectGuid(); return; case GO_GUNSHIP_ARMORY_H: case GO_GUNSHIP_ARMORY_H_25: case GO_GUNSHIP_ARMORY_H_10H: case GO_GUNSHIP_ARMORY_H_25H: m_mGoEntryGuidStore[GO_GUNSHIP_ARMORY_H] = pGo->GetObjectGuid(); return; case GO_DREAMWALKER_CACHE: case GO_DREAMWALKER_CACHE_25: case GO_DREAMWALKER_CACHE_10_H: case GO_DREAMWALKER_CACHE_25_H: m_mGoEntryGuidStore[GO_DREAMWALKER_CACHE] = pGo->GetObjectGuid(); return; case GO_ICESHARD_1: case GO_ICESHARD_2: case GO_ICESHARD_3: case GO_ICESHARD_4: case GO_FROSTY_WIND: case GO_FROSTY_EDGE: case GO_SNOW_EDGE: case GO_ARTHAS_PLATFORM: case GO_ARTHAS_PRECIPICE: case GO_MARROWGAR_DOOR: case GO_BLOODPRINCE_DOOR: case GO_SINDRAGOSA_ENTRANCE: case GO_VALITHRIA_DOOR_1: case GO_VALITHRIA_DOOR_2: case GO_VALITHRIA_DOOR_3: case GO_VALITHRIA_DOOR_4: case GO_ICECROWN_GRATE: case GO_SINDRAGOSA_SHORTCUT_ENTRANCE: case GO_SINDRAGOSA_SHORTCUT_EXIT: case GO_ORANGE_PLAGUE: case GO_GREEN_PLAGUE: case GO_ORANGE_VALVE: case GO_GREEN_VALVE: break; } m_mGoEntryGuidStore[pGo->GetEntry()] = pGo->GetObjectGuid(); } void instance_icecrown_citadel::OnCreatureDeath(Creature* pCreature) { switch (pCreature->GetEntry()) { case NPC_STINKY: if (Creature* pFestergut = GetSingleCreatureFromStorage(NPC_FESTERGUT)) { if (pFestergut->IsAlive()) DoScriptText(SAY_STINKY_DIES, pFestergut); } break; case NPC_PRECIOUS: if (Creature* pRotface = GetSingleCreatureFromStorage(NPC_ROTFACE)) { if (pRotface->IsAlive()) DoScriptText(SAY_PRECIOUS_DIES, pRotface); } break; } } void instance_icecrown_citadel::SetData(uint32 uiType, uint32 uiData) { switch (uiType) { case TYPE_MARROWGAR: m_auiEncounter[uiType] = uiData; DoUseDoorOrButton(GO_MARROWGAR_DOOR); if (uiData == DONE) { DoUseDoorOrButton(GO_ICEWALL_1); DoUseDoorOrButton(GO_ICEWALL_2); // Note: this door use may not be correct. In theory the door should be already opened DoUseDoorOrButton(GO_ORATORY_DOOR); } break; case TYPE_LADY_DEATHWHISPER: m_auiEncounter[uiType] = uiData; DoUseDoorOrButton(GO_ORATORY_DOOR); // ToDo: set the elevateor in motion when TYPE_LADY_DEATHWHISPER == DONE break; case TYPE_GUNSHIP_BATTLE: m_auiEncounter[uiType] = uiData; if (uiData == DONE) DoRespawnGameObject(m_uiTeam == ALLIANCE ? GO_GUNSHIP_ARMORY_A : GO_GUNSHIP_ARMORY_H, 60 * MINUTE); break; case TYPE_DEATHBRINGER_SAURFANG: m_auiEncounter[uiType] = uiData; if (uiData == DONE) { DoUseDoorOrButton(GO_SAURFANG_DOOR); DoRespawnGameObject(GO_SAURFANG_CACHE, 60 * MINUTE); // Note: these doors may not be correct. In theory the doors should be already opened DoUseDoorOrButton(GO_SCIENTIST_DOOR); DoUseDoorOrButton(GO_CRIMSON_HALL_DOOR); DoUseDoorOrButton(GO_GREEN_DRAGON_ENTRANCE); } break; case TYPE_FESTERGUT: m_auiEncounter[uiType] = uiData; DoUseDoorOrButton(GO_ORANGE_PLAGUE); if (uiData == DONE) DoToggleGameObjectFlags(GO_ORANGE_VALVE, GO_FLAG_NO_INTERACT, false); break; case TYPE_ROTFACE: m_auiEncounter[uiType] = uiData; DoUseDoorOrButton(GO_GREEN_PLAGUE); if (uiData == DONE) DoToggleGameObjectFlags(GO_GREEN_VALVE, GO_FLAG_NO_INTERACT, false); break; case TYPE_PROFESSOR_PUTRICIDE: m_auiEncounter[uiType] = uiData; DoUseDoorOrButton(GO_SCIENTIST_DOOR); break; case TYPE_BLOOD_PRINCE_COUNCIL: m_auiEncounter[uiType] = uiData; DoUseDoorOrButton(GO_CRIMSON_HALL_DOOR); if (uiData == DONE) { DoUseDoorOrButton(GO_COUNCIL_DOOR_1); DoUseDoorOrButton(GO_COUNCIL_DOOR_2); } break; case TYPE_QUEEN_LANATHEL: m_auiEncounter[uiType] = uiData; DoUseDoorOrButton(GO_BLOODPRINCE_DOOR); if (uiData == DONE) DoUseDoorOrButton(GO_ICECROWN_GRATE); break; case TYPE_VALITHRIA: m_auiEncounter[uiType] = uiData; DoUseDoorOrButton(GO_GREEN_DRAGON_ENTRANCE); // Side doors DoUseDoorOrButton(GO_VALITHRIA_DOOR_1); DoUseDoorOrButton(GO_VALITHRIA_DOOR_2); // Some doors are used only in 25 man mode if (instance->GetDifficulty() == RAID_DIFFICULTY_25MAN_NORMAL || instance->GetDifficulty() == RAID_DIFFICULTY_25MAN_HEROIC) { DoUseDoorOrButton(GO_VALITHRIA_DOOR_3); DoUseDoorOrButton(GO_VALITHRIA_DOOR_4); } if (uiData == DONE) { DoUseDoorOrButton(GO_GREEN_DRAGON_EXIT); DoUseDoorOrButton(GO_SINDRAGOSA_ENTRANCE); DoRespawnGameObject(GO_DREAMWALKER_CACHE, 60 * MINUTE); } break; case TYPE_SINDRAGOSA: m_auiEncounter[uiType] = uiData; DoUseDoorOrButton(GO_SINDRAGOSA_ENTRANCE); break; case TYPE_LICH_KING: m_auiEncounter[uiType] = uiData; break; default: script_error_log("Instance Icecrown Citadel: ERROR SetData = %u for type %u does not exist/not implemented.", uiType, uiData); return; } if (uiData == DONE) { OUT_SAVE_INST_DATA; std::ostringstream saveStream; saveStream << m_auiEncounter[0] << " " << m_auiEncounter[1] << " " << m_auiEncounter[2] << " " << m_auiEncounter[3] << " " << m_auiEncounter[4] << " " << m_auiEncounter[5] << " " << m_auiEncounter[6] << " " << m_auiEncounter[7] << " " << m_auiEncounter[8] << " " << m_auiEncounter[9] << " " << m_auiEncounter[10] << " " << m_auiEncounter[11]; m_strInstData = saveStream.str(); SaveToDB(); OUT_SAVE_INST_DATA_COMPLETE; } } uint32 instance_icecrown_citadel::GetData(uint32 uiType) const { if (uiType < MAX_ENCOUNTER) return m_auiEncounter[uiType]; return 0; } bool instance_icecrown_citadel::CheckAchievementCriteriaMeet(uint32 /*uiCriteriaId*/, Player const* /*pSource*/, Unit const* /*pTarget*/, uint32 /*uiMiscvalue1*/) const { // ToDo: return false; } void instance_icecrown_citadel::Load(const char* strIn) { if (!strIn) { OUT_LOAD_INST_DATA_FAIL; return; } OUT_LOAD_INST_DATA(strIn); std::istringstream loadStream(strIn); loadStream >> m_auiEncounter[0] >> m_auiEncounter[1] >> m_auiEncounter[2] >> m_auiEncounter[3] >> m_auiEncounter[4] >> m_auiEncounter[5] >> m_auiEncounter[6] >> m_auiEncounter[7] >> m_auiEncounter[8] >> m_auiEncounter[9] >> m_auiEncounter[10] >> m_auiEncounter[11]; for (uint8 i = 0; i < MAX_ENCOUNTER; ++i) { if (m_auiEncounter[i] == IN_PROGRESS) m_auiEncounter[i] = NOT_STARTED; } OUT_LOAD_INST_DATA_COMPLETE; } void instance_icecrown_citadel::Update(uint32 uiDiff) { DialogueUpdate(uiDiff); if (m_uiPutricideValveTimer) { if (m_uiPutricideValveTimer <= uiDiff) { // Open the pathway to Putricide when the timer expires DoUseDoorOrButton(GO_SCIENTIST_DOOR_COLLISION); if (GameObject* pDoor = GetSingleGameObjectFromStorage(GO_SCIENTIST_DOOR_GREEN)) pDoor->SetGoState(GO_STATE_ACTIVE_ALTERNATIVE); if (GameObject* pDoor = GetSingleGameObjectFromStorage(GO_SCIENTIST_DOOR_ORANGE)) pDoor->SetGoState(GO_STATE_ACTIVE_ALTERNATIVE); m_uiPutricideValveTimer = 0; } else m_uiPutricideValveTimer -= uiDiff; } } InstanceData* GetInstanceData_instance_icecrown_citadel(Map* pMap) { return new instance_icecrown_citadel(pMap); } bool AreaTrigger_at_icecrown_citadel(Player* pPlayer, AreaTriggerEntry const* pAt) { if (pAt->id == AREATRIGGER_MARROWGAR_INTRO || pAt->id == AREATRIGGER_DEATHWHISPER_INTRO || pAt->id == AREATRIGGER_SINDRAGOSA_PLATFORM) { if (pPlayer->isGameMaster() || pPlayer->IsDead()) return false; if (instance_icecrown_citadel* pInstance = (instance_icecrown_citadel*)pPlayer->GetInstanceData()) pInstance->DoHandleCitadelAreaTrigger(pAt->id, pPlayer); } return false; } bool ProcessEventId_event_gameobject_citadel_valve(uint32 /*uiEventId*/, Object* pSource, Object* /*pTarget*/, bool bIsStart) { if (bIsStart && pSource->GetTypeId() == TYPEID_PLAYER) { if (instance_icecrown_citadel* pInstance = (instance_icecrown_citadel*)((Player*)pSource)->GetInstanceData()) { // Note: the Tubes and doors are activated by DB script if (pInstance->GetData(TYPE_FESTERGUT) == DONE && pInstance->GetData(TYPE_ROTFACE) == DONE) pInstance->DoPreparePutricideDoor(); return false; } } return false; } void AddSC_instance_icecrown_citadel() { Script* pNewScript; pNewScript = new Script; pNewScript->Name = "instance_icecrown_citadel"; pNewScript->GetInstanceData = &GetInstanceData_instance_icecrown_citadel; pNewScript->RegisterSelf(); pNewScript = new Script; pNewScript->Name = "at_icecrown_citadel"; pNewScript->pAreaTrigger = &AreaTrigger_at_icecrown_citadel; pNewScript->RegisterSelf(); pNewScript = new Script; pNewScript->Name = "event_gameobject_citadel_valve"; pNewScript->pProcessEventId = &ProcessEventId_event_gameobject_citadel_valve; pNewScript->RegisterSelf(); }
35.339623
168
0.633316
Zilvereyes
c25162a62b9cef97e02505a748b1ff416a91629b
7,266
cpp
C++
test/connect_server_tests.cpp
brusdev/libWakaamaEmb
cfc1d4b4900fcd53d6b18bd40cca973bca2294df
[ "MIT" ]
2
2019-11-08T00:31:42.000Z
2020-03-12T14:00:57.000Z
test/connect_server_tests.cpp
brusdev/libWakaamaEmb
cfc1d4b4900fcd53d6b18bd40cca973bca2294df
[ "MIT" ]
null
null
null
test/connect_server_tests.cpp
brusdev/libWakaamaEmb
cfc1d4b4900fcd53d6b18bd40cca973bca2294df
[ "MIT" ]
null
null
null
/******************************************************************************* * Copyright (c) 2016 MSc. David Graeff <david.graeff@web.de> * * 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. */ #include <gtest/gtest.h> #include "wakaama_simple_client.h" #include "wakaama_object_utils.h" #include "wakaama_client_debug.h" #include "wakaama_server_debug.h" #include "wakaama_network.h" #include "wakaama_client_internal.h" #include "network_helper.h" #ifdef TAP_SERVER_ADDR #define LWM2M_SERVER_ADDR "coap://" TAP_SERVER_ADDR #else #define LWM2M_SERVER_ADDR "coap://127.0.0.1" #endif #include <stdint.h> #include <stdio.h> #include <thread> #include <memory> extern "C" { #include "internals.h" } class ConnectServerTests : public testing::Test { public: lwm2m_context_t * client_context = nullptr; lwm2m_object_t * securityObj = nullptr; lwm2m_object_t * serverObj = nullptr; std::unique_ptr<std::thread> serverThread; volatile bool server_running = false; lwm2m_context_t * server_context; int client_bound_sockets; // Client name and connected client name char* connected_client_name = nullptr; const char* client_name = "testClient"; int client_updated; protected: virtual void TearDown() { if (!client_context) return; lwm2m_network_close(client_context); lwm2m_client_close(); server_running = false; if (serverThread) serverThread->join(); if (server_context) { lwm2m_network_close(server_context); lwm2m_close(server_context); server_context = nullptr; } network_close(); } virtual void SetUp() { ASSERT_TRUE(network_init()); client_context = lwm2m_client_init(client_name); ASSERT_TRUE(client_context) << "Failed to initialize wakaama\r\n"; securityObj = client_context->objectList; ASSERT_EQ(securityObj->objID, 0); ASSERT_TRUE(securityObj); serverObj = securityObj->next; ASSERT_TRUE(serverObj); ASSERT_EQ(serverObj->objID, 1); // The meta data pointer is not an official member of the lwm2m_object_t struct. lwm2m_object_meta_information_t* metaP = ((lwm2m_object_with_meta_t*)serverObj)->meta; for(unsigned i=0;i<metaP->ressources_len;++i) { lwm2m_object_res_item_t* resP = &(metaP->ressources[i]); if ((resP->type_and_access & O_RES_E)) continue; ASSERT_TRUE(resP->struct_member_offset); } client_bound_sockets = lwm2m_network_init(client_context, NULL); ASSERT_GE(client_bound_sockets, 1); server_context = nullptr; } }; static void prv_monitor_callback(uint16_t clientID, lwm2m_uri_t * uriP, int status, lwm2m_media_type_t format, uint8_t * data, int dataLength, void * userData) { ConnectServerTests* t = (ConnectServerTests*) userData; lwm2m_context_t * lwm2mH = t->server_context; lwm2m_client_t * targetP; switch (status) { case COAP_201_CREATED: targetP = (lwm2m_client_t *)lwm2m_list_find((lwm2m_list_t *)lwm2mH->clientList, clientID); t->connected_client_name = targetP->name; //prv_dump_client(targetP); break; case COAP_202_DELETED: t->connected_client_name = nullptr; break; case COAP_204_CHANGED: ++t->client_updated; //prv_dump_client(targetP); break; default: break; } } TEST_F(ConnectServerTests, ConnectServer) { int server_bound_sockets; //// init server thread //// server_context = lwm2m_init(NULL); server_context->state = STATE_READY; ASSERT_TRUE(server_context); lwm2m_set_monitoring_callback(server_context, prv_monitor_callback, this); server_bound_sockets = lwm2m_network_init(server_context, LWM2M_DEFAULT_SERVER_PORT); ASSERT_LE(1, server_bound_sockets); client_updated = 0; connected_client_name = nullptr; server_running = true; #ifdef TAP_SERVER_ADDR //lwip // listen on the second lwip network interface for the server server_bound_sockets = 1; lwm2m_network_force_interface(server_context, network_get_interface(server_bound_sockets)); #endif serverThread = std::unique_ptr<std::thread>(new std::thread([this,server_bound_sockets]() { while (server_running) { network_step_blocking(server_context,server_bound_sockets); } })); //// client: add server and register //// ASSERT_TRUE(lwm2m_add_server(123, LWM2M_SERVER_ADDR, 100, false, NULL, NULL, 0)); uint8_t steps = 0; uint8_t result; #ifdef TAP_SERVER_ADDR //lwip client_bound_sockets = 0; // use the first lwip network interface for the server lwm2m_network_force_interface(client_context, network_get_interface(client_bound_sockets)); #endif while (steps++ < 10) { result = network_step_blocking(client_context,client_bound_sockets); if (result == COAP_NO_ERROR) { if (client_context->state == STATE_READY) break; } else { prv_print_error(result); // print_status(result); print_state(client_context); } usleep(1000*20); } ASSERT_EQ(COAP_NO_ERROR, result); ASSERT_EQ(STATE_READY, client_context->state); ASSERT_STREQ(connected_client_name, client_name); //// client: deregister from server //// security_instance_t* instances = (security_instance_t*)securityObj->instanceList; ASSERT_TRUE(lwm2m_unregister_server(instances->instanceId)); // One network_step_blocking is necessary to send/receive the unregister request // All further steps make sure, the result does not change. steps = 0; while (steps++ < 10) { result = network_step_blocking(client_context,client_bound_sockets); if (result == COAP_503_SERVICE_UNAVAILABLE) { if (client_context->state == STATE_BOOTSTRAP_REQUIRED) break; } else { prv_print_error(result); print_state(client_context); ASSERT_EQ(COAP_503_SERVICE_UNAVAILABLE, result); } usleep(1000*20); } lwm2m_remove_unregistered_servers(); result = network_step_blocking(client_context,client_bound_sockets); ASSERT_EQ(COAP_503_SERVICE_UNAVAILABLE, result); ASSERT_EQ(STATE_BOOTSTRAP_REQUIRED, client_context->state); ASSERT_EQ(nullptr, connected_client_name); }
32.58296
98
0.661987
brusdev
c254a33094ffc58d602b462c4a936d65a0d24f73
24,501
cpp
C++
plugins/fnUsdMeshImport/GeoData.cpp
TheFoundryVisionmongers/mariusdplugins
b3ff07dade27f20426599a5a6905d3eb1182474f
[ "Apache-2.0" ]
11
2020-07-13T15:06:05.000Z
2022-03-21T09:45:50.000Z
plugins/fnUsdMeshImport/GeoData.cpp
TheFoundryVisionmongers/mariusdplugins
b3ff07dade27f20426599a5a6905d3eb1182474f
[ "Apache-2.0" ]
2
2020-09-17T01:07:14.000Z
2021-01-20T08:56:39.000Z
plugins/fnUsdMeshImport/GeoData.cpp
TheFoundryVisionmongers/mariusdplugins
b3ff07dade27f20426599a5a6905d3eb1182474f
[ "Apache-2.0" ]
1
2021-05-24T02:22:45.000Z
2021-05-24T02:22:45.000Z
// These files were initially authored by Pixar. // In 2019, Foundry and Pixar agreed Foundry should maintain and curate // these plug-ins, and they moved to // https://github.com/TheFoundryVisionmongers/mariusdplugins // under the same Modified Apache 2.0 license as the main USD library, // as shown below. // // Copyright 2019 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "GeoData.h" #include "pxr/base/gf/vec3d.h" #include "pxr/base/gf/vec2f.h" #include "pxr/base/vt/value.h" #include "pxr/base/vt/array.h" #include "pxr/base/tf/envSetting.h" #include "pxr/usd/usdGeom/mesh.h" #include "pxr/usd/usdGeom/xformCache.h" #include <float.h> using namespace std; PXR_NAMESPACE_USING_DIRECTIVE TF_DEFINE_ENV_SETTING(MARI_READ_FLOAT2_AS_UV, true, "Set to false to disable ability to read Float2 type as a UV set"); std::vector<std::string> GeoData::_requireGeomPathSubstring; std::vector<std::string> GeoData::_ignoreGeomPathSubstring; std::string GeoData::_requireGeomPathSubstringEnvVar = "PX_USDREADER_REQUIRE_GEOM_PATH_SUBSTR"; std::string GeoData::_ignoreGeomPathSubstringEnvVar = "PX_USDREADER_IGNORE_GEOM_PATH_SUBSTR"; //#define PRINT_DEBUG //#define PRINT_ARRAYS //------------------------------------------------------------------------------ // GeoData implementation //------------------------------------------------------------------------------ bool GeoData::ReadFloat2AsUV() { static const bool readFloat2AsUV = TfGetEnvSetting(MARI_READ_FLOAT2_AS_UV); return readFloat2AsUV; } GeoData::GeoData(UsdPrim const &prim, std::string uvSet, std::string mappingScheme, std::vector<int> frames, bool conformToMariY, bool readerIsUpY, bool keepCentered, UsdPrim const &model, const MriGeoReaderHost& host, std::vector<std::string>& log) { // Init m_isSubdivMesh = false; m_subdivisionScheme = ""; m_interpolateBoundary = 0; m_faceVaryingLinearInterpolation = 0; m_propagateCorner = 0; UsdGeomMesh mesh(prim); if (not mesh) { host.trace("[GeoData:%d] Invalid non-mesh prim %s (type %s)", __LINE__, prim.GetPath().GetText(), prim.GetTypeName().GetText()); log.push_back("** Invalid non-mesh prim " + std::string(prim.GetPath().GetText()) + " of type " + std::string(prim.GetTypeName().GetText())); return; } bool isTopologyVarying = mesh.GetFaceVertexIndicesAttr().GetNumTimeSamples() >= 1; #if defined(PRINT_DEBUG) host.trace("[ !! ] ---------------------------------------"); host.trace("[ GeoData:%d] Reading MESH %s (type %s) (topology Varying %d)", __LINE__, prim.GetPath().GetText(), prim.GetTypeName().GetText(), isTopologyVarying); #endif // Read vertex/face indices { VtIntArray vertsIndicesArray; bool ok = isTopologyVarying ? mesh.GetFaceVertexIndicesAttr().Get(&vertsIndicesArray, UsdTimeCode::EarliestTime()) : mesh.GetFaceVertexIndicesAttr().Get(&vertsIndicesArray); if (!ok) { host.trace("[GeoData:%d]\tfailed getting face vertex indices on %s.", __LINE__, prim.GetPath().GetText()); log.push_back("** Failed getting faces on " + std::string(prim.GetPath().GetText())); return;// this is not optional! } m_vertexIndices = vector<int>(vertsIndicesArray.begin(), vertsIndicesArray.end()); } // Read face counts { VtIntArray nvertsPerFaceArray; bool ok = isTopologyVarying ? mesh.GetFaceVertexCountsAttr().Get(&nvertsPerFaceArray, UsdTimeCode::EarliestTime()) : mesh.GetFaceVertexCountsAttr().Get(&nvertsPerFaceArray); if (!ok) { host.trace("[GeoData:%d]\tfailed getting face counts on %s", __LINE__, prim.GetPath().GetText()); log.push_back("** Failed getting faces on " + std::string(prim.GetPath().GetText())); return;// this is not optional! } m_faceCounts = vector<int>(nvertsPerFaceArray.begin(), nvertsPerFaceArray.end()); } // Create face selection indices { m_faceSelectionIndices.reserve(m_faceCounts.size()); for(int x = 0; x < m_faceCounts.size(); ++x) { m_faceSelectionIndices.push_back(x); } } if (mappingScheme != "Force Ptex" and uvSet.length() > 0) { // Get UV set primvar if (UsdGeomPrimvar uvPrimvar = mesh.GetPrimvar(TfToken(uvSet))) { SdfValueTypeName typeName = uvPrimvar.GetTypeName(); TfToken interpolation = uvPrimvar.GetInterpolation(); if ((interpolation == UsdGeomTokens->faceVarying or interpolation == UsdGeomTokens->vertex) and (typeName == SdfValueTypeNames->TexCoord2fArray or (GeoData::ReadFloat2AsUV() and typeName == SdfValueTypeNames->Float2Array))) { VtVec2fArray values; VtIntArray indices; if (uvPrimvar.Get(&values, UsdTimeCode::EarliestTime())) { // Read uvs m_uvs.resize(values.size()*2); for (int i = 0; i < values.size(); ++i) { m_uvs[i * 2 ] = values[i][0]; m_uvs[i * 2 + 1] = values[i][1]; } // Get indices bool ok = isTopologyVarying ? uvPrimvar.GetIndices(&indices, UsdTimeCode::EarliestTime()) : uvPrimvar.GetIndices(&indices); if (ok) { if (interpolation == UsdGeomTokens->faceVarying) { // All good -> primvar is indexed: validate/process values and indices together m_uvIndices = vector<int>(indices.begin(), indices.end()); } else { // vertex interpolated -> do extra extrapolation m_uvIndices.reserve(m_vertexIndices.size()); // To build an actual face varying uv indices array, we need to // 1. for each vertex V on a face F, get its vertex index V from the vertexIndices array // 2. use VI as an index into the original vertex-interpolcated uv index table, to get uv index UVI // 3. add UVI to final face varying uv index array // VITAL NOTE: the final uv indices array count MUST MATCH the vertex indices array count std::vector<int> UvIndices = vector<int>(indices.begin(), indices.end()); int globalIndex = 0; for(int x = 0; x < m_faceCounts.size(); ++x) { int vertCount = m_faceCounts[x]; for (int vertIndex = 0; vertIndex < vertCount; ++vertIndex) { int vertId = m_vertexIndices[globalIndex++]; int uvId = UvIndices[vertId]; m_uvIndices.push_back(uvId); } } } } else { // Our uvs are not indexed -> we need to fill in an ordered list of indices m_uvIndices.reserve(m_vertexIndices.size()); for (unsigned int x = 0; x < m_vertexIndices.size(); ++x) { m_uvIndices.push_back(x); } } } else { // Could not read uvs host.trace("[GeoData:%d]\tDiscarding mesh %s - specified uv set %s cannot be read", __LINE__, prim.GetPath().GetText(), uvSet.c_str()); log.push_back("** Discarding mesh " + std::string(prim.GetPath().GetText()) + " - specified uv set " + uvSet + " cannot be read"); return; } } else { // Incorrect interpolation host.trace("[GeoData:%d]\tDiscarding mesh %s - specified uv set %s is not of type 'faceVarying or vertex'", __LINE__, prim.GetPath().GetText(), uvSet.c_str()); log.push_back("** Discarding mesh " + std::string(prim.GetPath().GetText()) + " - specified uv set " + uvSet + " is not of type 'faceVarying or vertex'"); return; } } else { // UV set not found on mesh host.trace("[GeoData:%d]\tSpecified uv set %s not found on mesh %s - will use ptex", __LINE__, uvSet.c_str(), prim.GetPath().GetText()); log.push_back("** Discarding mesh " + std::string(prim.GetPath().GetText()) + " - specified uv set " + uvSet + " not found"); } } else { // Mari will use Ptex for uv-ing later on } // Read normals { VtVec3fArray normalsVt; bool ok = isTopologyVarying ? mesh.GetNormalsAttr().Get(&normalsVt, UsdTimeCode::EarliestTime()) : mesh.GetNormalsAttr().Get(&normalsVt); if (ok) { m_normals.resize(normalsVt.size() * 3); for(int i = 0; i < normalsVt.size(); ++i) { m_normals[i * 3 ] = normalsVt[i][0]; m_normals[i * 3 + 1] = normalsVt[i][1]; m_normals[i * 3 + 2] = normalsVt[i][2]; } m_normalIndices.reserve(m_vertexIndices.size()); for (unsigned int x = 0; x < m_vertexIndices.size(); ++x) { m_normalIndices.push_back(x); } } } // Load vertices and animation frames GfMatrix4d const IDENTITY(1); vector<float> points; for (unsigned int iFrame = 0; iFrame < frames.size(); ++iFrame) { // Get frame sample corresponding to frame index unsigned int frameSample = frames[iFrame]; double currentTime = double(frameSample); // Read points for this frame sample VtVec3fArray pointsVt; if (!mesh.GetPointsAttr().Get(&pointsVt, frameSample)) { host.trace("[GeoData:%d]\tfailed getting vertices on %s.", __LINE__, prim.GetPath().GetName().c_str()); log.push_back("** Failed getting faces on " + prim.GetPath().GetName()); return;// this is not optional! } points.resize(pointsVt.size() * 3); for(int i = 0; i < pointsVt.size(); ++i) { points[i * 3 ] = pointsVt[i][0]; points[i * 3 + 1] = pointsVt[i][1]; points[i * 3 + 2] = pointsVt[i][2]; } // Calculate transforms - if not identity, pre-transform all points in place UsdGeomXformCache xformCache(currentTime); GfMatrix4d fullXform = xformCache.GetLocalToWorldTransform(prim); if (keepCentered) { // ignore transforms up to the model level GfMatrix4d m = xformCache.GetLocalToWorldTransform(model); fullXform = fullXform * m.GetInverse(); } if (fullXform != IDENTITY) { unsigned int psize = points.size(); for (unsigned int iPoint = 0; iPoint < psize; iPoint += 3) { GfVec4d p(points[iPoint], points[iPoint + 1], points[iPoint + 2], 1.0); p = p * fullXform; points[iPoint ] = p[0]; points[iPoint + 1] = p[1]; points[iPoint + 2] = p[2]; } } if (conformToMariY && !readerIsUpY) { // Our source is Z and we need to conform to Y -> let's flip unsigned int psize = points.size(); for (unsigned int iPoint = 0; iPoint < psize; iPoint += 3) { int y = points[iPoint + 1]; points[iPoint + 1] = points[iPoint + 2]; points[iPoint + 2] = -y; } } // Insert transformed vertices in our map m_vertices[frameSample].resize(points.size()); m_vertices[frameSample] = points; } // DEBUG #if defined(PRINT_DEBUG) { host.trace("[GeoData:%d]\t\t Face counts %i", __LINE__, m_faceCounts.size()); #if defined(PRINT_ARRAYS) for (unsigned int x = 0; x < m_faceCounts.size(); ++x) { host.trace("\t\t face count[%d] : %d", x, m_faceCounts[x]); } #endif host.trace("[GeoData:%d]\t\t vertex indices %i", __LINE__, m_vertexIndices.size()); #if defined(PRINT_ARRAYS) for (unsigned x = 0; x < m_vertexIndices.size(); ++x) { host.trace("\t\t vertex Index[%d] : %d", x, m_vertexIndices[x]); } #endif host.trace("[GeoData:%d]\t\t vertex frame count %i", __LINE__, m_vertices.size()); vector<float> vertices0 = m_vertices.begin()->second; host.trace("[GeoData:%d]\t\t vertex @ frame0 count %i", __LINE__, vertices0.size()/3); #if defined(PRINT_ARRAYS) for (unsigned x = 0; x < vertices0.size()/3; ++x) { host.trace("\t\t vertex[%d] : (%f, %f, %f)", x, vertices0[(x*3)+0], vertices0[(x*3)+1], vertices0[(x*3)+2]); } #endif host.trace("[GeoData:%d]\t\t uvs count %i", __LINE__, m_uvs.size()/2); #if defined(PRINT_ARRAYS) for(int x = 0; x < m_uvs.size()/2; ++x) { host.trace("\t\t uv[%d] : (%f, %f)", x, m_uvs[(x*2)+0], m_uvs[(x*2)+1]); } #endif host.trace("[GeoData:%d]\t\t uv indices %i", __LINE__, m_uvIndices.size()); #if defined(PRINT_ARRAYS) for(int x = 0; x < m_uvIndices.size(); ++x) { host.trace("\t\t UV Index[%d] : %d", x, m_uvIndices[x]); } #endif host.trace("[GeoData:%d]\t\t normals count %i", __LINE__, m_normals.size()/3); #if defined(PRINT_ARRAYS) for(int x = 0; x < m_normals.size()/3; ++x) { host.trace("\t\t normal[%d] : (%f, %f, %f)", x, m_normals[(x*3)+0], m_normals[(x*3)+1], m_normals[(x*3)+2]); } #endif host.trace("[GeoData:%d]\t\t normals indices %i", __LINE__, m_normalIndices.size()); #if defined(PRINT_ARRAYS) for(int x = 0; x < m_normalIndices.size(); ++x) { host.trace("\t\t Normal Index[%d] : %d", x, m_normalIndices[x]); } #endif } #endif // Read OpenSubdiv structures { VtIntArray creaseIndicesArray; if (mesh.GetCreaseIndicesAttr().Get(&creaseIndicesArray)) { m_creaseIndices = vector<int>(creaseIndicesArray.begin(), creaseIndicesArray.end()); } VtIntArray creaseLengthsArray; if (mesh.GetCreaseLengthsAttr().Get(&creaseLengthsArray)) { m_creaseLengths = vector<int>(creaseLengthsArray.begin(), creaseLengthsArray.end()); } VtFloatArray creaseSharpnessArray; if (mesh.GetCreaseSharpnessesAttr().Get(&creaseSharpnessArray)) { m_creaseSharpness = vector<float>(creaseSharpnessArray.begin(), creaseSharpnessArray.end()); } VtIntArray cornerIndicesArray; if (mesh.GetCornerIndicesAttr().Get(&cornerIndicesArray)) { m_cornerIndices = vector<int>(cornerIndicesArray.begin(), cornerIndicesArray.end()); } VtFloatArray cornerSharpnessArray; if (mesh.GetCornerSharpnessesAttr().Get(&cornerSharpnessArray)) { m_cornerSharpness = vector<float>(cornerSharpnessArray.begin(), cornerSharpnessArray.end()); } VtIntArray holeIndicesArray; if (mesh.GetHoleIndicesAttr().Get(&holeIndicesArray)) { m_holeIndices = vector<int>(holeIndicesArray.begin(), holeIndicesArray.end()); } m_isSubdivMesh = false; TfToken subdivisionScheme; if (mesh.GetSubdivisionSchemeAttr().Get(&subdivisionScheme)) { if (subdivisionScheme == UsdGeomTokens->none) { // This mesh is not subdivideable m_isSubdivMesh = false; } else { m_isSubdivMesh = true; if (subdivisionScheme == UsdGeomTokens->catmullClark) { m_subdivisionScheme = "catmullClark"; } else if (subdivisionScheme == UsdGeomTokens->loop) { m_subdivisionScheme = "loop"; } else if (subdivisionScheme == UsdGeomTokens->bilinear) { m_subdivisionScheme = "bilinear"; } TfToken interpolateBoundary; if (mesh.GetInterpolateBoundaryAttr().Get(&interpolateBoundary, UsdTimeCode::EarliestTime())) { if (interpolateBoundary == UsdGeomTokens->none) { m_interpolateBoundary = 0; } else if (interpolateBoundary == UsdGeomTokens->edgeAndCorner) { m_interpolateBoundary = 1; } else if (interpolateBoundary == UsdGeomTokens->edgeOnly) { m_interpolateBoundary = 2; } } TfToken faceVaryingLinearInterpolation; if (mesh.GetFaceVaryingLinearInterpolationAttr().Get(&faceVaryingLinearInterpolation, UsdTimeCode::EarliestTime())) { // See MriOpenSubdivDialog::faceVaryingBoundaryInterpolationFromInt for reference if (faceVaryingLinearInterpolation == UsdGeomTokens->all) { m_faceVaryingLinearInterpolation = 0; } else if (faceVaryingLinearInterpolation == UsdGeomTokens->cornersPlus1) { m_faceVaryingLinearInterpolation = 1; m_propagateCorner = 0; } else if (faceVaryingLinearInterpolation == UsdGeomTokens->none) { m_faceVaryingLinearInterpolation = 2; } else if (faceVaryingLinearInterpolation == UsdGeomTokens->boundaries) { m_faceVaryingLinearInterpolation = 3; } else if (faceVaryingLinearInterpolation == UsdGeomTokens->cornersPlus2) { m_faceVaryingLinearInterpolation = 1; m_propagateCorner = 1; } } } } } } GeoData::~GeoData() { Reset(); } // Print the internal status of the Geometric Data. void GeoData::Log(const MriGeoReaderHost& host) { } // Cast to bool. False if no good data is found. GeoData::operator bool() { return (m_vertices.size() > 0 && m_vertices.begin()->second.size()>0 && m_vertexIndices.size()>0); } // Static - Sanity test to see if the usd prim is something we can use. bool GeoData::IsValidNode(UsdPrim const &prim) { if (not prim.IsA<UsdGeomMesh>()) return false; else return TestPath( prim.GetPath().GetText()); } // Pre-scan the UsdStage to see what uv sets are included. void GeoData::GetUvSets(UsdPrim const &prim, UVSet &retval) { UsdGeomGprim gprim(prim); if (not gprim) return; vector<UsdGeomPrimvar> primvars = gprim.GetPrimvars(); TF_FOR_ALL(primvar, primvars) { TfToken name, interpolation; SdfValueTypeName typeName; int elementSize; primvar->GetDeclarationInfo(&name, &typeName, &interpolation, &elementSize); if (interpolation == UsdGeomTokens->vertex or interpolation == UsdGeomTokens->faceVarying) { string prefix = name.GetString().substr(0,2); string mapName(""); if ((prefix == "v_" || prefix == "u_") and (typeName == SdfValueTypeNames->FloatArray)) { mapName = name.GetString().substr(2); } else if (typeName == SdfValueTypeNames->TexCoord2fArray || (GeoData::ReadFloat2AsUV() && typeName == SdfValueTypeNames->Float2Array)) { mapName = name.GetString(); } if (mapName.length()) { UVSet::iterator it = retval.find(mapName); if (it == retval.end()) retval[mapName] = 1; else retval[mapName] += 1; } } } } float* GeoData::GetVertices(int frameSample) { if (m_vertices.size() > 0) { if (m_vertices.find(frameSample) != m_vertices.end()) { return &(m_vertices[frameSample][0]); } else { // Could not find frame -> let's return frame 0 return &(m_vertices.begin()->second[0]); } } // frame not found. return NULL; } void GeoData::Reset() { m_vertexIndices.clear(); m_faceCounts.clear(); m_faceSelectionIndices.clear(); m_vertices.clear(); m_normalIndices.clear(); m_normals.clear(); m_uvIndices.clear(); m_uvs.clear(); m_creaseIndices.clear(); m_creaseLengths.clear(); m_creaseSharpness.clear(); m_cornerIndices.clear(); m_cornerSharpness.clear(); m_holeIndices.clear(); } bool GeoData::TestPath(string path) { bool requiredSubstringFound = true; std::vector<std::string>::iterator i; for (i=_requireGeomPathSubstring.begin(); i!=_requireGeomPathSubstring.end(); ++i) { if (path.find(*i) != string::npos) { requiredSubstringFound = true; break; } else { requiredSubstringFound = false; } } if (requiredSubstringFound == false) { return false; } for (i=_ignoreGeomPathSubstring.begin(); i!=_ignoreGeomPathSubstring.end(); ++i) { if (path.find(*i) != string::npos) { return false; } } return true; } void GeoData::InitializePathSubstringLists() { char * ignoreEnv = getenv(_ignoreGeomPathSubstringEnvVar.c_str()); char * requireEnv = getenv(_requireGeomPathSubstringEnvVar.c_str()); if (ignoreEnv) { _ignoreGeomPathSubstring.clear(); _ignoreGeomPathSubstring = TfStringTokenize(ignoreEnv, ","); } if (requireEnv) { _requireGeomPathSubstring.clear(); _requireGeomPathSubstring = TfStringTokenize(requireEnv, ","); } } template <typename SOURCE, typename TYPE> bool GeoData::CastVtValueAs(SOURCE &obj, TYPE &result) { if ( obj.template CanCast<TYPE>() ) { obj = obj.template Cast<TYPE>(); result = obj.template Get<TYPE>(); return true; } return false; }
36.678144
235
0.547651
TheFoundryVisionmongers
c2557edf945cc5ce276a758dd2d0feb408b1f279
3,617
cpp
C++
software/threads/CentralMain.cpp
dettus/dettusSDR
066a96ab7becdd612bab04e33ea0840234a8a6a8
[ "BSD-2-Clause" ]
null
null
null
software/threads/CentralMain.cpp
dettus/dettusSDR
066a96ab7becdd612bab04e33ea0840234a8a6a8
[ "BSD-2-Clause" ]
null
null
null
software/threads/CentralMain.cpp
dettus/dettusSDR
066a96ab7becdd612bab04e33ea0840234a8a6a8
[ "BSD-2-Clause" ]
null
null
null
#include <QApplication> #include "CentralMain.h" #include "Tuners.h" CentralMain::CentralMain(TunerMain* tunerMain,DemodMain* demodMain,AudioMain* audioMain) { int i; int fftsize; char tmp[32]; mTunerMain=tunerMain; mDemodMain=demodMain; mAudioMain=audioMain; mV1Layout=new QVBoxLayout; mV2Layout=new QVBoxLayout; mV3Layout=new QVBoxLayout; mH1Layout=new QHBoxLayout; mH2Layout=new QHBoxLayout; mH3Layout=new QHBoxLayout; mainWin=new QWidget(nullptr); mWVolume=new WVolume(nullptr); mWSpectrum=new WSpectrum(nullptr); mRecordButton=new QPushButton("Record"); mDemodWidget=nullptr; connect(mRecordButton,SIGNAL(released()),this,SLOT(handleRecord())); mainWin->hide(); mDemodWidget=demodMain->getDemodWidget(); mH3Layout->setAlignment(Qt::AlignLeft); mH3Layout->addWidget(new QLabel("FFT size:")); fftsize=256; for (i=0;i<8;i++) { snprintf(tmp,32,"%d",fftsize); bFFT[i]=new QPushButton(tmp); bFFT[i]->setFlat(false); connect(bFFT[i] ,SIGNAL(clicked()),this,SLOT(handleFFTclicked())); mH3Layout->addWidget(bFFT[i]); fftsize*=2; } mV3Layout->setStretch(0,1000); mV3Layout->setStretch(1,100); } void CentralMain::stop() { mStopped=true; } void CentralMain::run() { Tuners* tuner=nullptr; tIQSamplesBlock iqSamples; while (!mStopped && tuner==nullptr) { QThread::msleep(100); tuner=mTunerMain->getTuner(); } tuner->initialize(); // mWSpectrum->setFFTsize(32768); mWSpectrum->setFFTsize(8192); bFFT[5]->setFlat(true); // mWSpectrum->setFFTsize(4096); mH2Layout->addWidget(mWVolume); mH2Layout->addWidget(mDemodWidget); mH1Layout->setStretch(0,5); mH1Layout->setStretch(1,30); mV1Layout->addLayout(mH2Layout); mV2Layout->addWidget(tuner); mV2Layout->addWidget(mRecordButton); mH1Layout->addLayout(mV2Layout); mV3Layout->addWidget(mWSpectrum); mV3Layout->addLayout(mH3Layout); mH1Layout->addLayout(mV3Layout); mH1Layout->setStretch(0,10); mH1Layout->setStretch(1,30); mV1Layout->addLayout(mH1Layout); mV1Layout->setStretch(0,5); mV1Layout->setStretch(1,50); mainWin->setLayout(mV1Layout); mainWin->showMaximized(); while (!mStopped) { QThread::msleep(100); tuner->getSamples(&iqSamples); if (iqSamples.sampleNum) { int demodFreq; int demodBw; int raster; bool demodOn; mDemodMain->setDemodFreq(mWSpectrum->getLastFreq()); mDemodMain->getDemodParams(&demodFreq,&demodBw,&raster,&demodOn); mDemodMain->onNewSamples(&iqSamples); mWSpectrum->onNewSamples(&iqSamples); mWSpectrum->setDemodParams(demodFreq,demodBw,raster,demodOn); } mAudioMain->setVolume((double)mWVolume->getVolume()/255.0f); mLock.lock(); if (mRecord && mFptr!=nullptr) { fwrite(iqSamples.pData,sizeof(tSComplex),iqSamples.sampleNum,mFptr); } mLock.unlock(); } QApplication::quit(); } void CentralMain::handleRecord() { if (mRecord==false) { QString filename=QFileDialog::getSaveFileName(nullptr,"Record as...","signal.iq2048"); mLock.lock(); if (mFptr!=nullptr) { fclose(mFptr); } mFptr=fopen(filename.toLocal8Bit().data(),"wb"); mRecord=true; if (mFptr!=nullptr) { mRecordButton->setText("Stop Recording"); } mLock.unlock(); }else { mLock.lock(); if (mFptr!=nullptr) { fclose(mFptr); } mRecord=false; mRecordButton->setText("Record"); mLock.unlock(); } } void CentralMain::handleFFTclicked() { int i; int fftsize; QPushButton *sender = (QPushButton*)QObject::sender(); fftsize=256; for (i=0;i<8;i++) { if (sender==bFFT[i]) { mWSpectrum->setFFTsize(fftsize); bFFT[i]->setFlat(true); } else bFFT[i]->setFlat(false); fftsize*=2; } }
22.054878
88
0.709151
dettus
c2592d0ebcdc8615edda83bba0c966ef0f02a3a7
12,460
cpp
C++
src/Needleman_Wunsch/NW_C_SSE.cpp
kugelblitz1235/TPOrga_Final
320e30f165be9c4ee0b57535c9db8d09d42ad389
[ "MIT" ]
null
null
null
src/Needleman_Wunsch/NW_C_SSE.cpp
kugelblitz1235/TPOrga_Final
320e30f165be9c4ee0b57535c9db8d09d42ad389
[ "MIT" ]
null
null
null
src/Needleman_Wunsch/NW_C_SSE.cpp
kugelblitz1235/TPOrga_Final
320e30f165be9c4ee0b57535c9db8d09d42ad389
[ "MIT" ]
2
2021-04-29T15:02:41.000Z
2021-06-15T17:31:36.000Z
#include "NW_C_SSE.hpp" namespace NW{ namespace C{ namespace SSE{ // Equivalentes a registros nombrados: __m128i constant_gap_xmm, constant_missmatch_xmm, constant_match_xmm, zeroes_xmm; __m128i str_row_xmm, str_col_xmm, left_score_xmm, up_score_xmm, diag_score_xmm; __m128i reverse_mask_xmm; __m128i diag1_xmm, diag2_xmm; char* seq1; char* seq2; unsigned int seq1_len; unsigned int seq2_len; // Máscara utilizada para invertir el string almacenado en un registro char reverse_mask[16] = {0xE,0xF,0xC,0xD,0xA,0xB,0x8,0x9,0x6,0x7,0x4,0x5,0x2,0x3,0x0,0x1}; int vector_len = 8; int height; // Cantidad de "franjas" de diagonales int width; // Cantidad de diagonales por franja int score_matrix_sz; // Cantidad de celdas de la matriz // Reservar memoria para la matriz de puntajes y el vector auxiliar, luego inicializamos sus valores short* score_matrix; short* v_aux; // Inicializar los valores del vector auxiliar y la matriz de puntajes void inicializar_casos_base(Alignment& alignment){ // Llenar vector auxiliar con un valor inicial negativo grande para no afectar los calculos for(int i = 0;i < width-1;i++){ v_aux[i] = SHRT_MIN; } // Inicializar por cada franja las primeras 2 diagonales. // Se pone en cada posicion un valor negativo grande para no afectar los calculos posteriores __m128i diag; for(int i = 0 ; i < height ; i++){ unsigned int offset_y = i * width * vector_len; // Broadcastear el valor SHRT_MIN/2 a nivel word en el registro diag diag = _mm_insert_epi16(diag,SHRT_MIN,0); diag = _mm_shufflelo_epi16(diag,0b0); diag = _mm_shuffle_epi32 (diag,0b0); _mm_storeu_si128((__m128i*)(score_matrix + offset_y), diag); // Insertar la penalidad adecuada para la franja en la posicion mas alta de la diagonal diag = _mm_insert_epi16(diag,i * vector_len * alignment.parameters->gap, 7); // 7 = vector_len - 1 _mm_storeu_si128((__m128i*)(score_matrix + offset_y + vector_len), diag); } } // Lee de memoria y almacena correctamente en los registros los caracteres de la secuencia columna a utilizar en la comparación void leer_secuencia_columna(int i){ if((i+1)*vector_len >= (int)seq2_len){// Caso de desborde por abajo int offset_col = (i+1)*vector_len - seq2_len; // Indica cuanto hay que shiftear el string columna luego de levantarlo str_col_xmm = _mm_loadl_epi64((__m128i*)(seq2 + seq2_len - vector_len) ); __m128i shift_count_xmm = zeroes_xmm; // Se utiliza junto con offset_col para shiftear str_col_xmm __m128i shift_mask_xmm = zeroes_xmm; // Acomodar los caracteres en str_col_xmm para que queden en las posiciones correctas para la comparación mas adelante shift_count_xmm = _mm_insert_epi8(shift_count_xmm, offset_col * 8, 0); str_col_xmm = _mm_srl_epi64(str_col_xmm, shift_count_xmm); // str_col_xmm = |0...0|str_col| // shift_mask_xmm va a tener 1's donde haya caracteres inválidos shift_mask_xmm = _mm_cmpeq_epi8(shift_mask_xmm, shift_mask_xmm); shift_count_xmm = _mm_insert_epi8(shift_count_xmm, (char)(8 - offset_col) * 8, 0); shift_mask_xmm = _mm_sll_epi64(shift_mask_xmm, shift_count_xmm); // shift_mask_xmm = |1...1|0...0| // Combinar la mascara de caracteres invalidos con los caracteres validos str_col_xmm = _mm_or_si128(str_col_xmm, shift_mask_xmm); // str_col_xmm = |1...1|str_col| }else{ // Caso sin desborde // Levantar directamente de memoria, no hay desborde str_col_xmm = _mm_loadl_epi64((__m128i*)(seq2 + i * vector_len) ); } // Desempaquetar los caracteres en str_col_xmm para trabajar con words str_col_xmm = _mm_unpacklo_epi8(str_col_xmm, zeroes_xmm); // Invertir la secuencia de caracteres para compararlos correctamente mas adelante str_col_xmm = _mm_shuffle_epi8(str_col_xmm, reverse_mask_xmm); } // Lee de memoria y almacena correctamente en los registros los caracteres de la secuencia fila a utilizar en la comparación void leer_secuencia_fila(int j) { __m128i shift_count = zeroes_xmm; // Se utiliza junto con offset_row para shiftear str_row_xmm en los casos de desborde if(j-vector_len < 0){ // Caso de desborde por izquierda int offset_str_row = vector_len - j; // Indica cuanto hay que shiftear a la izquierda el string fila luego de levantarlo str_row_xmm = _mm_loadl_epi64((__m128i*)(seq1)); // Acomodar los caracteres en str_row_xmm para que queden en las posiciones correctas para la comparación mas adelante shift_count = _mm_insert_epi8(shift_count, offset_str_row * 8, 0); str_row_xmm = _mm_sll_epi64(str_row_xmm, shift_count); // str_row_xmm = |str_row|0...0| } else if(j > width-vector_len){ // Caso de desborde por derecha // Desplazamiento de puntero a derecha y levantar datos de memoria int offset_str_row = j - (width-vector_len); // Indica cuanto hay que shiftear a la derecha el string fila luego de levantarlo str_row_xmm = _mm_loadl_epi64((__m128i*)(seq1 + j - vector_len - offset_str_row) ); // Acomodar los caracteres en str_row_xmm para que queden en las posiciones correctas para la comparación mas adelante shift_count = _mm_insert_epi8(shift_count, offset_str_row * 8, 0); str_row_xmm = _mm_srl_epi64(str_row_xmm, shift_count); // str_row_xmm = |0...0|str_row| }else{ // Caso sin desborde str_row_xmm = _mm_loadl_epi64((__m128i*)(seq1 + j - vector_len) ); } // Desempaquetar los caracteres en str_row_xmm para trabajar con words str_row_xmm = _mm_unpacklo_epi8(str_row_xmm,zeroes_xmm); } // Calcula los puntajes resultantes de las comparaciones entre caracteres void calcular_scores(int j){ // Calcular los scores viniendo por izquierda, sumandole a cada posicion la penalidad del gap left_score_xmm = diag2_xmm; left_score_xmm = _mm_adds_epi16(left_score_xmm, constant_gap_xmm); // Calcular los scores viniendo por arriba, sumandole a cada posicion la penalidad del gap up_score_xmm = diag2_xmm; up_score_xmm = _mm_srli_si128(up_score_xmm, 2); up_score_xmm = _mm_insert_epi16(up_score_xmm,v_aux[j-1],0b111); up_score_xmm = _mm_adds_epi16(up_score_xmm, constant_gap_xmm); // Calcular los scores viniendo diagonalmente, sumando en cada caso el puntaje de match o missmatch // si coinciden o no los caracteres de la fila y columna correspondientes diag_score_xmm = diag1_xmm; diag_score_xmm = _mm_srli_si128(diag_score_xmm, 2); diag_score_xmm = _mm_insert_epi16(diag_score_xmm,v_aux[j-2],0b111); // Comparar los dos strings y colocar según corresponda el puntaje correcto (match o missmatch) en cada posición __m128i cmp_match_xmm; cmp_match_xmm = _mm_cmpeq_epi16(str_col_xmm,str_row_xmm); // Mascara con unos en las posiciones donde coinciden los caracteres cmp_match_xmm = _mm_blendv_epi8(constant_missmatch_xmm,constant_match_xmm,cmp_match_xmm); // Seleccionar para cada posicion el puntaje correcto basado en la mascara previa diag_score_xmm = _mm_adds_epi16(diag_score_xmm, cmp_match_xmm); } void NW (Alignment& alignment, bool debug){ // Tamaños y punteros a las secuencias seq1 = alignment.sequence_1->sequence; seq2 = alignment.sequence_2->sequence; seq1_len = alignment.sequence_1->length; seq2_len = alignment.sequence_2->length; // Broadcastear el valor de gap, a nivel word, en el registro constant_gap_xmm = _mm_insert_epi16(constant_gap_xmm,alignment.parameters->gap,0); constant_gap_xmm = _mm_shufflelo_epi16(constant_gap_xmm,0b0); constant_gap_xmm = _mm_shuffle_epi32 (constant_gap_xmm,0b0); // Broadcastear el valor de missmatch, a nivel word, en el registro constant_missmatch_xmm = _mm_insert_epi16(constant_missmatch_xmm,alignment.parameters->missmatch,0); constant_missmatch_xmm = _mm_shufflelo_epi16(constant_missmatch_xmm,0b0); constant_missmatch_xmm = _mm_shuffle_epi32 (constant_missmatch_xmm,0b0); // Broadcastear el valor de match, a nivel word, en el registro constant_match_xmm = _mm_insert_epi16(constant_match_xmm,alignment.parameters->match,0); constant_match_xmm = _mm_shufflelo_epi16(constant_match_xmm,0b0); constant_match_xmm = _mm_shuffle_epi32 (constant_match_xmm,0b0); // Máscara de ceros zeroes_xmm = _mm_setzero_si128(); reverse_mask_xmm = _mm_loadu_si128((__m128i*)reverse_mask); // El tamaño del vector auxiliar se corresponde con la cantidad de caracteres que vamos a procesar simultáneamente vector_len = 8; height = ((seq2_len + vector_len - 1)/ vector_len); // Cantidad de "franjas" de diagonales width = (1 + seq1_len + vector_len - 1); // Cantidad de diagonales por franja score_matrix_sz = height * width * vector_len; // Cantidad de celdas de la matriz // Reservar memoria para la matriz de puntajes y el vector auxiliar, luego inicializamos sus valores score_matrix = (short*)malloc(score_matrix_sz*sizeof(short)); v_aux = (short*)malloc((width-1)*sizeof(short)); inicializar_casos_base(alignment); /******************************************************************************************************/ for( int i = 0 ; i < height ; i++){ int offset_y = i * width * vector_len; leer_secuencia_columna(i); // Cargar las primeras 2 diagonales de la franja actual necesarios para el primer calculo dentro de la franja diag1_xmm = _mm_loadu_si128((__m128i const*) (score_matrix + offset_y)); diag2_xmm = _mm_loadu_si128((__m128i const*) (score_matrix + offset_y + vector_len)); for( int j = 2; j < width ; j++){ int offset_x = j * vector_len; // String horizontal ------------------------------------------------------------------ leer_secuencia_fila(j); // Calculo scores de izquierda, arriba y diagonal -------------------------------------------------------------------- calcular_scores(j); // Guardar en cada posicion de la diagonal el maximo entre los puntajes de venir por izquierda, arriba y diagonalmente diag_score_xmm = _mm_max_epi16(diag_score_xmm,up_score_xmm); diag_score_xmm = _mm_max_epi16(diag_score_xmm,left_score_xmm); // Almacenamos el puntaje máximo en la posición correcta de la matriz _mm_storeu_si128((__m128i*)(score_matrix + offset_y + offset_x), diag_score_xmm); if(j>=vector_len){ v_aux[j - vector_len] = _mm_extract_epi16 (diag_score_xmm, 0b0000); } // Actualizar las 2 diagonales anteriores para la siguiente iteracion, actualizando diag2 con el valor de la actual diag1_xmm = diag2_xmm; diag2_xmm = diag_score_xmm; } } if(debug){// Utilizar para debuggear los valores en la matriz de puntajes alignment.matrix = score_matrix; } // Recuperar los 2 strings del mejor alineamiento utilizando backtracking, empezando desde la posicion mas inferior derecha backtracking_C( score_matrix, alignment, vector_len, alignment.sequence_1->length-1,alignment.sequence_2->length-1, false, (score_fun_t)get_score_SSE, false ); if(!debug) free(score_matrix); } } } }
53.939394
180
0.646549
kugelblitz1235
c25abd0112b9255784826dce5d2720c8743d40f6
4,808
hpp
C++
src/web_server/session/handle_request/handle_request.hpp
X-rays5/web_server
c14e2c8e6e53797d2179cb5985a135e34173b3b9
[ "MIT" ]
2
2021-09-16T03:22:45.000Z
2021-11-09T11:45:07.000Z
src/web_server/session/handle_request/handle_request.hpp
X-rays5/web_server
c14e2c8e6e53797d2179cb5985a135e34173b3b9
[ "MIT" ]
null
null
null
src/web_server/session/handle_request/handle_request.hpp
X-rays5/web_server
c14e2c8e6e53797d2179cb5985a135e34173b3b9
[ "MIT" ]
null
null
null
// // Created by X-ray on 5/30/2021. // #pragma once #include <utility> #include <iostream> #include <memory> #include <boost/beast.hpp> #include "../../utility/mime.hpp" #include "../../utility/path_cat.hpp" #include "response_builder.hpp" namespace web_server { namespace session { namespace handle_request { namespace beast = boost::beast; namespace http = beast::http; struct request { http::verb method; std::string url; std::map<std::string, std::string> parameters; http::header<true, http::basic_fields<std::allocator<char>>> headers; }; std::string ErrorResponse(std::string title, std::string what, int error_code); std::map<std::string, std::string> ParseUrlParameters(std::string url); class handle_tools { public: boost::beast::http::message<false, boost::beast::http::basic_string_body<char>> HandleError(http_status status, std::string error); using error_handler_t = std::function<boost::beast::http::response<boost::beast::http::string_body>(std::string)>; void AddErrorHandler(http_status status, error_handler_t handler); private: std::map<http_status, error_handler_t> error_handlers; }; class handle { public: handle() { RegisterErrorHandlers(); } template<bool isRequest, class Body, class Allocator = std::allocator<char>, class Send> void run(beast::string_view doc_root, http::message<isRequest, Body, Allocator>&& req, Send&& send) { try { request Req{ static_cast<http::verb>(req.method()), std::string(req.target()), ParseUrlParameters(std::string(req.target())), req.base(), }; // Make sure we can handle the method if(Req.method != http::verb::get && Req.method != http::verb::head) return send(tools_.HandleError(http_status::bad_request, "Unknown HTTP-method")); // Request path must be absolute and not contain "..". if(Req.url.empty() || req.target()[0] != '/' || Req.url.find("..") != std::string::npos) return send(tools_.HandleError(http_status::bad_request, "Illegal request-target")); // Build the path to the requested file std::string path = utility::path_cat(doc_root, Req.url); if(Req.url.ends_with('/')) path.append("index.html"); // Attempt to open the file beast::error_code ec; if (path.find('?') != std::string::npos) { path.erase(path.find('?')); } http::file_body::value_type body; body.open(path.c_str(), beast::file_mode::scan, ec); // Handle the case where the file doesn't exist if(ec == beast::errc::no_such_file_or_directory) return send(tools_.HandleError(http_status::not_found, "The requested url was not found: " + std::string(Req.headers["Host"]) +Req.url)); // Handle an unknown error if(ec) return send(tools_.HandleError(http_status::internal_server_error, ec.message())); if (Req.method == http::verb::head) { responsebuilder res(http_status::ok, std::string(utility::mime_type(path))); return send(res.GetStringResponse()); } else if (Req.method == http::verb::get) { responsebuilder res(http_status::ok, std::string(utility::mime_type(path)), body); return send(res.GetFileResponse()); } return send(tools_.HandleError(http_status::internal_server_error, "Request was not handled")); } catch(std::exception &e) { return send(tools_.HandleError(http_status::internal_server_error, e.what())); } } private: handle_tools tools_; private: void RegisterErrorHandlers(); }; } // handle_request } // session } // web_server
45.358491
165
0.501872
X-rays5
c25afe9c6187dcf5f92becc2e151af012fecfc44
2,657
cpp
C++
samples/_opengl/TessellationBezier/src/TessellationBezierApp.cpp
migeran/Cinder
5efc6d4d33b9f1caf826058728e334108b8e905f
[ "BSD-2-Clause" ]
1
2018-03-09T18:31:25.000Z
2018-03-09T18:31:25.000Z
samples/_opengl/TessellationBezier/src/TessellationBezierApp.cpp
migeran/Cinder
5efc6d4d33b9f1caf826058728e334108b8e905f
[ "BSD-2-Clause" ]
null
null
null
samples/_opengl/TessellationBezier/src/TessellationBezierApp.cpp
migeran/Cinder
5efc6d4d33b9f1caf826058728e334108b8e905f
[ "BSD-2-Clause" ]
null
null
null
#include "cinder/app/App.h" #include "cinder/app/RendererGl.h" #include "cinder/gl/gl.h" using namespace ci; using namespace ci::app; using namespace std; const int NUM_POINTS = 4; // can't be changed const int SUBDIVISIONS = 30; // can be class TessellationBezierApp : public App { public: void setup() override; void mouseDown( MouseEvent event ) override; void mouseDrag( MouseEvent event ) override; void mouseUp( MouseEvent event ) override; void draw() override; int mSelectedIndex; vec2 mVertices[NUM_POINTS]; gl::GlslProgRef mGlslProg; gl::VboMeshRef mBezierControlMesh; gl::BatchRef mBezierBatch; }; void TessellationBezierApp::setup() { mSelectedIndex = -1; mVertices[0] = vec2( 50, 250 ); mVertices[1] = vec2( 20, 50 ); mVertices[2] = vec2( 450, 100 ); mVertices[3] = vec2( 350, 350 ); mGlslProg = gl::GlslProg::create( gl::GlslProg::Format().vertex( loadAsset( "bezier.vert" ) ) .tessellationCtrl( loadAsset( "bezier.tesc" ) ) .tessellationEval( loadAsset( "bezier.tese" ) ) .fragment( loadAsset( "bezier.frag" ) ) ); mGlslProg->uniform( "uSubdivisions", SUBDIVISIONS ); // a VertBatch would be fine for a simple mesh like ours but for more vertices we'd want to use a technique like this. mBezierControlMesh = gl::VboMesh::create( NUM_POINTS, GL_PATCHES, { gl::VboMesh::Layout().attrib( geom::POSITION, 2 ) } ); mBezierControlMesh->bufferAttrib( geom::POSITION, sizeof(vec2) * NUM_POINTS, &mVertices[0] ); mBezierBatch = gl::Batch::create( mBezierControlMesh, mGlslProg ); } void TessellationBezierApp::mouseDown( MouseEvent event ) { mSelectedIndex = -1; for( size_t i = 0; i < NUM_POINTS; ++i ) if( glm::distance( vec2( event.getPos() ), mVertices[i] ) < 7.0f ) mSelectedIndex = i; } void TessellationBezierApp::mouseDrag( MouseEvent event ) { if( mSelectedIndex > -1 ) { mVertices[mSelectedIndex] = event.getPos(); // update the points of our mesh mBezierControlMesh->bufferAttrib( geom::POSITION, sizeof(vec2) * NUM_POINTS, &mVertices[0] ); } } void TessellationBezierApp::mouseUp( MouseEvent event ) { mSelectedIndex = -1; } void TessellationBezierApp::draw() { gl::clear( Color( 0, 0, 0 ) ); gl::color( 1, 0.5f, 0.25f ); gl::patchParameteri( GL_PATCH_VERTICES, 4 ); mBezierBatch->draw(); for( size_t i = 0; i < NUM_POINTS; ++i ) { if( mSelectedIndex == i ) gl::color( 1, 1, 0 ); else gl::color( 0, 0, 1 ); gl::drawSolidRect( Rectf( mVertices[i] - vec2( 3 ), mVertices[i] + vec2( 3 ) ) ); } } CINDER_APP( TessellationBezierApp, RendererGl( RendererGl::Options().msaa( 16 ).version( 4, 0 ) ) )
29.522222
123
0.67595
migeran
c25b59c40d8d20cb19b29cade51afc9201bfb141
1,300
cpp
C++
src/prod/test/LinuxRunAsTest/FabricUnknownBase.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/test/LinuxRunAsTest/FabricUnknownBase.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/test/LinuxRunAsTest/FabricUnknownBase.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" #include "FabricUnknownBase.h" EXTERN_GUID(IID_IUnknown, 0x00000000, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); FabricUnknownBase::FabricUnknownBase() : _refCount() { this->AddRef(); } FabricUnknownBase::~FabricUnknownBase() { } HRESULT STDMETHODCALLTYPE FabricUnknownBase::GetAndAddRef( /* [iid_is][out] */ _COM_Outptr_ void __RPC_FAR *__RPC_FAR *ppvObject) { *ppvObject = this; this->AddRef(); return S_OK; } HRESULT STDMETHODCALLTYPE FabricUnknownBase::QueryInterface( /* [in] */ REFIID riid, /* [iid_is][out] */ _COM_Outptr_ void __RPC_FAR *__RPC_FAR *ppvObject) { if (riid == IID_IUnknown) { return this->GetAndAddRef(ppvObject); } return E_NOINTERFACE; } ULONG STDMETHODCALLTYPE FabricUnknownBase::AddRef(void) { return ++_refCount; } ULONG STDMETHODCALLTYPE FabricUnknownBase::Release(void) { auto count = --_refCount; if (count == 0) { delete this; } return count; }
23.636364
102
0.624615
AnthonyM
c25c2a9aaba86ea6c81a5c08f7d9815c52f9a36d
3,917
cpp
C++
tc 160+/Orchard.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
3
2015-05-25T06:24:37.000Z
2016-09-10T07:58:00.000Z
tc 160+/Orchard.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
null
null
null
tc 160+/Orchard.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
5
2015-05-25T06:24:40.000Z
2021-08-19T19:22:29.000Z
#include <algorithm> #include <cassert> #include <cstdio> #include <iostream> #include <sstream> #include <string> #include <vector> #include <queue> #include <functional> using namespace std; typedef pair<int, int> PII; struct Entry { PII pos; int len; Entry(PII p, int l): pos(p), len(l) {} }; const int di[] = { -1, 0, 1, 0 }; const int dj[] = { 0, 1, 0, -1 }; bool valid(int i, int j, int m, int n) { return i>=0 && i<m && j>=0 && j<n; } class Orchard { public: vector <int> nextTree(vector <string> orchard) { int best = 0; PII loc = make_pair(-1, -1); const int m(orchard.size()); const int n(orchard[0].size()); for (int i=0; i<m; ++i) for (int j=0; j<n; ++j) if (orchard[i][j]=='-') { vector<vector<bool> > used(m, vector<bool>(n, false)); queue<Entry> q; used[i][j] = true; q.push(Entry(make_pair(i, j), 0)); while (!q.empty()) { const Entry t = q.front(); q.pop(); for (int dir=0; dir<4; ++dir) { const int ii = t.pos.first+di[dir]; const int jj = t.pos.second+dj[dir]; if (valid(ii, jj, m, n) && used[ii][jj]) continue; if (!valid(ii, jj, m, n) || orchard[ii][jj]=='T') { if (t.len+1 > best) { best = t.len+1; loc = make_pair(i, j); } goto kraj; } else { q.push(Entry(make_pair(ii, jj), t.len+1)); used[ii][jj] = true; } } } kraj: ; } vector<int> sol; sol.push_back(loc.first+1); sol.push_back(loc.second+1); return sol; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const vector <int> &Expected, const vector <int> &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: " << print_array(Expected) << endl; cerr << "\tReceived: " << print_array(Received) << endl; } } void test_case_0() { string Arr0[] = { "----" , "T---" , "----" , "----" }; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = { 2, 3 }; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(0, Arg1, nextTree(Arg0)); } void test_case_1() { string Arr0[] = {"---T--","------","------","----T-","------","------"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = { 3, 3 }; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(1, Arg1, nextTree(Arg0)); } void test_case_2() { string Arr0[] = {"------------","------------","------------","------------", "------------","------------","------------","------------", "------------","------------","------------","------------"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = { 6, 6 }; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(2, Arg1, nextTree(Arg0)); } void test_case_3() { string Arr0[] = {"-T----T", "T---T--", "-----TT", "---TT--", "T-----T", "-------", "T-T--T-"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = { 2, 3 }; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(3, Arg1, nextTree(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { Orchard ___test; ___test.run_test(-1); } // END CUT HERE
38.029126
333
0.503447
ibudiselic
c261f63c268381814286dd26a32cc5ebc4cc60eb
15,353
cpp
C++
palimp-shader/src/ofApp.cpp
headrotor/ofx
ac16ebb3b5d7160faf924bb7b7181d41baae0b1a
[ "MIT" ]
null
null
null
palimp-shader/src/ofApp.cpp
headrotor/ofx
ac16ebb3b5d7160faf924bb7b7181d41baae0b1a
[ "MIT" ]
null
null
null
palimp-shader/src/ofApp.cpp
headrotor/ofx
ac16ebb3b5d7160faf924bb7b7181d41baae0b1a
[ "MIT" ]
null
null
null
#include "ofApp.h" // for time stamps #include <ctime> using namespace ofxCv; using namespace cv; void ofApp::setup() { // init shaders //shader.load("shadersES2/mix-shader"); #ifdef TARGET_OPENGLES shader.load("shadersES2/mix-shader"); #else if (ofIsGLProgrammableRenderer()) { shader.load("shadersGL3/mix-shader"); } else { shader.load("shadersGL2/mix-shader"); } #endif // signal handler for clean exit image.loadImage("img.jpg"); // load config file config.loadFile("config.xml"); int frameRate; if (config.tagExists("config:frameRate", 0)) { frameRate = config.getValue("config:frameRate", 30); cout << "\nframe rate from config file" << frameRate << "\n"; } else { cout << "\nerror reading frameRate from xml config file\n"; cout << "\nframe rate from config file" << frameRate << "\n"; } double smoothingRate; if (config.tagExists("config:smoothingRate", 0)) { smoothingRate = config.getValue("config:smoothingRate", 0.2); cout << "smoothing rate from config file: " << smoothingRate << "\n"; } else { cout << "error reading smoothingRate from xml config file\n"; smoothingRate = 0.2; } int cannyPruning; if (config.tagExists("config:cannyPruning", 0)) { cannyPruning = config.getValue("config:cannyPruning", 0); } else { cout << "error reading cannyPruning from xml config file\n"; cannyPruning = 1; } if (config.tagExists("config:face_dropped_threshold")) { face_dropped_threshold = config.getValue("config:face_dropped_threshold", FACE_DROPPED_THRESHOLD); } else { cout << "error reading face_dropped_threshold from xml config file\n"; face_dropped_threshold = FACE_DROPPED_THRESHOLD; } if (config.tagExists("config:nod_threshold")) { nod_threshold = config.getValue("config:nod_threshold", NOD_THRESHOLD); } else { cout << "error reading nod_threshold from xml config file\n"; nod_threshold = NOD_THRESHOLD; } if (config.tagExists("config:num_images")) { num_images = config.getValue("config:num_images", NUM_IMAGES); cout << "num_images from config file: " << num_images << "\n"; } else { cout << "error reading num_images from xml config file\n"; num_images = NUM_IMAGES; } #ifdef RPI if (signal(SIGUSR1, clean_exit) == SIG_ERR) { cout << "can't catch signal\n"; } #endif ofSetVerticalSync(true); ofSetFrameRate(frameRate); // smaller = smoother //finder.getTracker().setSmoothingRate(smoothingRate); // ignore low-contrast regions finder.setCannyPruning((cannyPruning > 0)); finder.setup("haarcascade_frontalface_default.xml"); finder.setPreset(ObjectFinder::Fast); finder.setFindBiggestObject(true); finder.getTracker().setSmoothingRate(smoothingRate); //cam.listDevices(); cam.setDeviceID(0); cam.setup(CAM_WIDTH, CAM_HEIGHT); ofEnableAlphaBlending(); id = 0; grabimg.allocate(CAM_WIDTH, CAM_HEIGHT, OF_IMAGE_COLOR); colorimg.allocate(CAM_WIDTH, CAM_HEIGHT); grayimg.allocate(CAM_WIDTH, CAM_HEIGHT); // something to display if facefinder doesn't grayimg.set(127.0); // state machine handling state.set(S_IDLE, 0); // allocate array of images for (int i = 0; i < num_images; i++) { gray_images.push_back(ofImage()); gray_rects.push_back(ofRectangle()); } msg.loadFont("impact.ttf", 36, true, false, true, 0.1); facerect = ofRectangle(0, 0, 0, 0); // load stored images init_idle(); // setup shader FBOs //fbo.allocate(SCREEN_WIDTH, SCREEN_HEIGHT); fbo.allocate(image.getWidth(),image.getHeight()); maskFbo.allocate(SCREEN_WIDTH, SCREEN_HEIGHT); } void ofApp::update() { ofVec2f vel; cam.update(); if (cam.isFrameNew()) { grabimg.setFromPixels(cam.getPixels()); colorimg.setFromPixels(grabimg.getPixels()); // convert to grayscale grayimg = colorimg; // do face detection in grayscale finder.update(grayimg); //cropimg = grayimg(cropr); vel.set(0, 0); if (finder.size() > 0) { cv::Vec2f v = finder.getVelocity(0); vel = toOf(v); facerect = finder.getObjectSmoothed(0); // scale by size of camera and face rect to normalize motion vel.x *= 500. / facerect.x; vel.y *= 500. / facerect.y; //cout << "velx:" << setw(6) << setprecision(2) << vel.x; //cout << " vely: " << setw(6) << setprecision(2) << vel.y << "\n"; float mix = 0.3; avg_xvel = mix*abs(vel.x) + 0.9*(1 - mix)*avg_xvel; avg_yvel = mix*abs(vel.y) + 0.9*(1 - mix)*avg_yvel; /* cout << " avg_x:" << fixed << setw(6) << setprecision(1) << avg_xvel; cout << " avg_y: " << fixed << setw(6) << setprecision(1) << avg_yvel << "\n"; if (avg_xvel > 35) cout << "X NO----"; else cout << " "; if (avg_yvel > 25) cout << "Y+YES+++\n"; else cout << " \n"; */ } } // state machine handling switch (state.state) { case S_IDLE: if (false) { //disable for testing //if (finder.size() > 0) { // found face, so go to capture mode // check for face size here if (state.timeout() && (facerect.width*xscale > ofGetWidth() / 5.0)) { state.set(S_HELLO, 2.); // grab image when first detected } } break; case S_HELLO: /* if (finder.size() == 0) { state.set(S_NO_IMG, 2.); } */ //update_idle(); yes_flag = false; avg_xvel = 0; avg_yvel = 0; if (state.timeout()) { state.set(S_QUESTION, 5); } case S_QUESTION: if (state.timeout()) { // no obvious yes, so default to no state.set(S_NO_IMG, 2.); } if (finder.size() > 0) { if (avg_yvel > nod_threshold) { state.set(S_THREE, 1.); } //if (avg_xvel > 45.0) { // state.set(S_NO_IMG, 2.); // yes_flag = false; //} } break; case S_THREE: if (state.timeout()) { state.set(S_TWO, 1.); } case S_TWO: if (state.timeout()) { state.set(S_ONE, 1.); } case S_ONE: if (state.timeout()) { state.set(S_CAPTURE, 2); } case S_CAPTURE: //if (finder.size() == 0) { // state.set(S_NO_IMG, 2.); //} if (state.timeout()) { state.set(S_YES_IMG, 2); saveimg.setFromPixels(cam.getPixels()); saverect = finder.getObjectSmoothed(0); store_image(); yes_flag = true; } case S_YES_IMG: if (state.timeout()) { state.set(S_IDLE, 10); } break; case S_NO_IMG: if (state.timeout()) { state.set(S_IDLE, 10); } break; } } void ofApp::draw() { fbo.begin(); ofClear(0, 0, 127, 255); shader.begin(); shader.setUniformTexture("tex0", image, 1); //shader.setUniformTexture("tex1", grayimg, 2); //shader.setUniformTexture("tex2", grayimg, 3); //shader.setUniformTexture("tex1", image, 2); //shader.setUniformTexture("tex2", movie.getTextureReference(), 3); //shader.setUniformTexture("imageMask", maskFbo.getTextureReference(), 4); // we are drawing this fbo so it is used just as a frame. maskFbo.draw(0, 0); shader.end(); fbo.end(); fbo.draw(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT); fbo.draw(0, 0, 320, 240); image.draw(320, 240, 320, 240); return; ofSetHexColor(0xFFFFFFFF); // disable for testing idle grayimg.draw(0, 0, ofGetWidth(), ofGetHeight()); ofNoFill(); ofSetHexColor(0xFFFF00FF); ofDrawRectRounded(facerect.x * xscale, facerect.y*yscale, facerect.width*xscale, facerect.height*yscale, 30.0); float underface_x = facerect.x * xscale; //float underface_y = min(float(facerect.y + facerect.height + 10.), ofGetHeight() - 30.); float underface_y = std::min(float(facerect.getBottom()*yscale + 20.0), float(ofGetHeight() - 30)); switch (state.state) { case S_IDLE: //draw_idle(); draw_idle1(); break; case S_HELLO: msg.drawString("Hello!", 50, 100); break; case S_QUESTION: msg.drawString("Hello!", 50, 100); msg.drawString("May we take your picture?", 50, ofGetHeight() - 150); msg.drawString("(nod yes or no)", 50, ofGetHeight() - 75); break; case S_THREE: msg.drawString("Ready! 3...", underface_x, underface_y); break; case S_TWO: msg.drawString("Ready! 3... 2...", underface_x, underface_y); break; case S_ONE: msg.drawString("Ready! 3... 2... 1...", underface_x, underface_y); break; case S_CAPTURE: msg.drawString("Ready! 3... 2... 1... Pose!", underface_x, underface_y); break; case S_YES_IMG: msg.drawString("Thank you!", underface_x, underface_y); ofSetColor(255, 255, 255, 127); idle_image.draw(0, 0, ofGetWidth(), ofGetHeight()); break; case S_NO_IMG: msg.drawString("OK, thanks anyway!", 50, ofGetHeight() - 100); break; } } void ofApp::init_idle() { //some path, may be absolute or relative to bin/data cout << "init idle\n"; string path = ""; ofDirectory imgs(path); //only show png files imgs.allowExt("png"); //populate the directory object //imgs.listDir(); imgs.getSorted(); imgs.listDir(); // if (imgs.size() > 0) { // cout << "loading color file " << imgs.getPath(imgs.size() - 1) << "\n"; // idle_image.load(imgs.getFile(imgs.size()-1)); // } int img_count = 0; int num_dir_images = imgs.size(); for (int i = 0; i < std::min(num_images, num_dir_images); i++) { // load most recent images int j = imgs.size() - i - 1; cout << "loading gray file " << imgs.getPath(j) << "\n"; gray_images[i].load(imgs.getFile(j)); gray_images[i].setImageType(OF_IMAGE_GRAYSCALE); img_count++; // parse rectangle out of file name ofRectangle r = gray_rects[i]; unsigned int x, y, w, h; char timestamp[20]; sscanf(imgs.getPath(j).c_str(), "%14sx%3uy%3uw%3uh%3u.png", timestamp, &x, &y, &w, &h); gray_rects[i].set(x, y, w, h); cout << "timestamp: " << timestamp << "\n"; cout << "x: " << x << " y:" << y << "\n"; cout << "w: " << w << " h:" << h << "\n"; } num_images = img_count; } void ofApp::store_image() { time_t rawtime; time(&rawtime); struct tm *timeinfo; timeinfo = localtime(&rawtime); char timestamp[80]; strftime(timestamp, 80, "%m-%d-%H-%M-%S", timeinfo); cout << timestamp << std::endl; ofRectangle r = facerect; char name[256]; sprintf(name, "%sx%03dy%03dw%03dh%03d.png", timestamp, int(r.x), int(r.y), int(r.width), int(r.height)); cout << "saving image: " << name; saveimg.save(name); idle_image.clone(saveimg); id++; } //-------------------------------------------------------------- void ofApp::draw_idle1() { // list of images in ofDirectory imgs, load and display // idle1: align faces & crossfade ofSetColor(255, 255, 255, 255); if (yes_flag) { ofSetColor(255, 255, 255, int(127 * (cos(0.5*state.time_elapsed()) + 1))); idle_image.draw(0, 0, ofGetWidth(), ofGetHeight()); } ofSetColor(255, 255, 255, 127); //grayimg.draw(0, 0, ofGetWidth(), ofGetHeight()); for (int i = 0; i < num_images; i++) { ofRectangle r = gray_rects[i]; ofPoint fc = gray_rects[i].getCenter(); ofPoint cp = ofPoint(ofGetWidth() / 2, ofGetHeight() / 2, 0.); //gray_images[i].drawSubsection(x, y, ss, ss, r.width, r.height, r.x, r.y); // draw image so faces are centered. Face center is at fc ofPushMatrix(); ofSetColor(0, 255, 0, 255); // scale faces to take up 1/3 of screen float scale = ofGetWidth() / (3*r.width); //scale = 1.0; ofScale(scale, scale, 1.0); ofTranslate((cp.x/scale) - fc.x, (cp.y/scale) - fc.y); ofRect(r); ofSetColor(255, 255, 255, 127); gray_images[i].draw(0, 0); //x += ss; ofPopMatrix(); } return; // brady bunch int x = 0; int y = 0; int maxy = -1; for (int i = 0; i < num_images; i++) { //ofSetColor(255, 255, 255, int(127 * (sin(float(i)*0.2*ofGetElapsedTimef()) + 1.))); ofSetColor(255, 255, 255, 255); ofRectangle r = gray_rects[i]; //gray_images[i].drawSubsection(x, y, ss, ss, r.width, r.height, r.x, r.y); gray_images[i].drawSubsection(x, y, r.width, r.height, r.x, r.y); //x += ss; if (r.height > maxy) { maxy = r.height; } x += r.width; if (x > ofGetWidth() - 150) { y += maxy; x = 0; maxy = -1; } } } //-------------------------------------------------------------- void ofApp::draw_idle() { // boring plain image crossfade // list of images in ofDirectory imgs, load and display ofSetColor(255, 255, 255, 255); for (int i = 0; i < num_images; i++) { //ofSetColor(255, 255, 255, int((100 / (i + 1)) * (sin(float(i)*0.2*ofGetElapsedTimef()) + 1.))); ofSetColor(255, 255, 255, int(100 * (sin(float(i)*0.2*ofGetElapsedTimef()) + 1. / (i + 1)))); //ofSetColor(255, 255, 255, 100); gray_images[i].draw(0, 0, ofGetWidth(), ofGetHeight()); //ofSetColor(0,255,0,255); //ofRect(gray_rects[i]); } if (yes_flag) { ofSetColor(255, 255, 255, int(127 * (cos(0.5*state.time_elapsed()) + 1))); idle_image.draw(0, 0, ofGetWidth(), ofGetHeight()); } ofSetColor(255, 255, 255, 127); grayimg.draw(0, 0, ofGetWidth(), ofGetHeight()); return; // brady bunch int x = 0; int y = 0; int maxy = -1; for (int i = 0; i < num_images; i++) { //ofSetColor(255, 255, 255, int(127 * (sin(float(i)*0.2*ofGetElapsedTimef()) + 1.))); ofSetColor(255, 255, 255, 255); ofRectangle r = gray_rects[i]; //gray_images[i].drawSubsection(x, y, ss, ss, r.width, r.height, r.x, r.y); gray_images[i].drawSubsection(x, y, r.width, r.height, r.x, r.y); //x += ss; if (r.height > maxy) { maxy = r.height; } x += r.width; if (x > ofGetWidth() - 150) { y += maxy; x = 0; maxy = -1; } } } void ofApp::clean_exit(int signal) { // clean exit, signal handler cout << "Exit signal caught, bye!\n"; ofExit(); } void ofApp::keyPressed(int key) { if (key == 'x') { ofExit(); } if (key == 's') { // test back-to-idle handling saveimg.setFromPixels(cam.getPixels()); if (finder.size()) { saverect = finder.getObjectSmoothed(0); store_image(); } init_idle(); } if (key == 'p') { time_t rawtime; time(&rawtime); struct tm *timeinfo; timeinfo = localtime(&rawtime); //char buffer[80]; //strftime(buffer, 80, "Now it's %I:%M%p.", timeinfo); char timestamp[80]; strftime(timestamp, 80, "%m-%d-%H-%M-%S", timeinfo); //cout << "Current time is :: " << ctime(&rawtime) << std::endl; cout << timestamp << std::endl; } } // State machine handling ------------------------------------------------------------ void StateMach::set(int next_state, float timeout) { state = next_state; timeout_time = timeout; // default no timeout if (timeout >= 0) { ofResetElapsedTimeCounter(); reset_timer(); } print(); } void StateMach::reset_timer(void) { start_time = ofGetElapsedTimef(); } float StateMach::time_elapsed(void) { return(ofGetElapsedTimef() - start_time); } // return the fraction of elapsed time that has passed float StateMach::frac_time_elapsed(void) { if (time_elapsed() > timeout_time) { return 1.0; } return(time_elapsed() / timeout_time); } bool StateMach::timeout(void) { if (timeout_time < 0) return(true); if (time_elapsed() > timeout_time) return(true); return(false); } void StateMach::print(void) { cout << "State ID:" << state << " "; switch (state) { case S_IDLE: cout << "State: IDLE\n"; break; case S_HELLO: cout << "State: HELLO\n"; break; case S_QUESTION: cout << "State: QUESTION\n"; break; case S_THREE: cout << "State: THREE\n"; break; case S_TWO: cout << "State: TWO\n"; break; case S_ONE: cout << "State: ONE\n"; break; case S_YES_COUNT: cout << "State: YES_COUNT\n"; break; case S_CAPTURE: cout << "State: CAPTURE\n"; break; case S_NO_IMG: cout << "State: NO_IMG\n"; break; case S_YES_IMG: cout << "State: YES_IMG\n"; break; default: cout << "unknown state\n"; break; } }
24.292722
112
0.628672
headrotor
c262bca714dad9e0b60929913636e2e68ebe3e48
93
cpp
C++
GameEngine/AudioEngine.cpp
BenMarshall98/Game-Engine-Uni
cb2e0a75953db0960e3d58a054eb9a6e213ae12a
[ "MIT" ]
null
null
null
GameEngine/AudioEngine.cpp
BenMarshall98/Game-Engine-Uni
cb2e0a75953db0960e3d58a054eb9a6e213ae12a
[ "MIT" ]
null
null
null
GameEngine/AudioEngine.cpp
BenMarshall98/Game-Engine-Uni
cb2e0a75953db0960e3d58a054eb9a6e213ae12a
[ "MIT" ]
null
null
null
#include "AudioEngine.h" AudioEngine::AudioEngine() { } AudioEngine::~AudioEngine() { }
7.153846
27
0.677419
BenMarshall98
c263bfb04b139469452d16ffed84546b5da382e9
931
cpp
C++
lsteamclient/cb_converters_141.cpp
neuroradiology/Proton
5aed286761234b1b362471ca5cf80d25f64cb719
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-07-05T06:40:08.000Z
2021-07-05T06:40:08.000Z
lsteamclient/cb_converters_141.cpp
neuroradiology/Proton
5aed286761234b1b362471ca5cf80d25f64cb719
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
lsteamclient/cb_converters_141.cpp
neuroradiology/Proton
5aed286761234b1b362471ca5cf80d25f64cb719
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
#include "steamclient_private.h" #include "steam_defs.h" #include "steamworks_sdk_141/steam_api.h" #include "steamworks_sdk_141/isteamgameserver.h" #include "steamworks_sdk_141/isteamgameserverstats.h" #include "steamworks_sdk_141/isteamgamecoordinator.h" extern "C" { struct winSteamUnifiedMessagesSendMethodResult_t_24 { ClientUnifiedMessageHandle m_hHandle; uint64 m_unContext; EResult m_eResult; uint32 m_unResponseSize; } __attribute__ ((ms_struct)); void cb_SteamUnifiedMessagesSendMethodResult_t_24(void *l, void *w) { SteamUnifiedMessagesSendMethodResult_t *lin = (SteamUnifiedMessagesSendMethodResult_t *)l; struct winSteamUnifiedMessagesSendMethodResult_t_24 *win = (struct winSteamUnifiedMessagesSendMethodResult_t_24 *)w; win->m_hHandle = lin->m_hHandle; win->m_unContext = lin->m_unContext; win->m_eResult = lin->m_eResult; win->m_unResponseSize = lin->m_unResponseSize; } }
35.807692
120
0.795918
neuroradiology
c266616a3d542e0e5896238f95e56522f30e576d
5,077
hpp
C++
modules/core/include/perf_manager.hpp
CambriconKnight/CNStream
555c4a54f4766cc7b6b230bd822c6689869fbce0
[ "Apache-2.0" ]
1
2020-04-22T08:36:51.000Z
2020-04-22T08:36:51.000Z
modules/core/include/perf_manager.hpp
CambriconKnight/CNStream
555c4a54f4766cc7b6b230bd822c6689869fbce0
[ "Apache-2.0" ]
null
null
null
modules/core/include/perf_manager.hpp
CambriconKnight/CNStream
555c4a54f4766cc7b6b230bd822c6689869fbce0
[ "Apache-2.0" ]
null
null
null
/************************************************************************* * Copyright (C) [2019] by Cambricon, Inc. All rights reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. *************************************************************************/ #ifndef MODULES_CORE_INCLUDE_PERF_MANAGER_HPP_ #define MODULES_CORE_INCLUDE_PERF_MANAGER_HPP_ #include <stdlib.h> #include <atomic> #include <memory> #include <string> #include <thread> #include <vector> #include <unordered_map> #include <unordered_set> #include <utility> #include "threadsafe_queue.hpp" namespace cnstream { class Sqlite; class PerfCalculator; class PerfStats; /** * @brief The basic data structure of measuring performance. * * Record PerfInfo at start time point and end time point. */ struct PerfInfo { bool is_finished; /// If it is true means start time, otherwise end time. std::string perf_type; /// perf type std::string module_name; /// module name int64_t pts; /// pts of each data frame size_t timestamp; /// timestamp }; // struct PerfInfo /** * @brief PerfManager class * * It could record PerfInfo and calculate modules and pipeline performance statistics. */ class PerfManager { public: /** * @brief Constructor of PerfManager. */ PerfManager() { } /** * @brief Destructor of PerfManager. */ ~PerfManager(); /** * @brief Stops to record PerfInfo. * * @return Void. */ void Stop(); /** * @brief Inits PerfManager. * * Create database and tables, create PerfCalculator, and start thread function, which is used to insert PerfInfo to database. * * @param db_name The name of the database. * @param module_names All module names of the pipeline. * @param start_node Start node module name of the pipeline. * @param end_nodes All end node module names of the pipeline. * * @return Returns true if PerfManager inits successfully, otherwise returns false. */ bool Init(std::string db_name, std::vector<std::string> module_names, std::string start_node, std::vector<std::string> end_nodes); /** * @brief Records PerfInfo. * * Create timestamp and set it to PerfInfo. And then insert it to database. * * @param info PerfInfo. * * @return Returns true if the info is recorded successfully, otherwise returns false. */ bool RecordPerfInfo(PerfInfo info); /** * @brief Registers perf type. * * @param type perf type. * * @return Returns true if type is registered successfully, otherwise returns false. */ bool RegisterPerfType(std::string type); /** * @brief Begins sqlite3 event. * * @return Void. */ void SqlBeginTrans(); /** * @brief Commits sqlite3 event. * * @return Void. */ void SqlCommitTrans(); /** * @brief Calculates Performance statistics of modules. * * @param perf_type perf type. * @param module_name module name. * * @return Returns performance statistics. */ PerfStats CalculatePerfStats(std::string perf_type, std::string module_name); /** * @brief Calculates Performance statistics of pipeline. * * @param perf_type perf type. * * @return Returns performance statistics of all end nodes of pipeline. */ std::vector<std::pair<std::string, PerfStats>> CalculatePipelinePerfStats(std::string perf_type); private: #ifdef UNIT_TEST public: // NOLINT #endif std::vector<std::string> GetKeys(const std::vector<std::string>& module_names); void PopInfoFromQueue(); void InsertInfoToDb(const PerfInfo& info); void CreatePerfCalculator(std::string perf_type); bool PrepareDbFileDir(std::string file_dir); bool CreateDir(std::string dir); std::shared_ptr<PerfCalculator> GetCalculator(std::string perf_type, std::string module_name); bool is_initialized_ = false; std::string start_node_; std::vector<std::string> end_nodes_; std::vector<std::string> module_names_; std::unordered_set<std::string> perf_type_; std::shared_ptr<Sqlite> sql_ = nullptr; std::unordered_map<std::string, std::shared_ptr<PerfCalculator>> calculator_map_; ThreadSafeQueue<PerfInfo> queue_; std::thread thread_; std::atomic<bool> running_{false}; }; // PerfManager } // namespace cnstream #endif // MODULES_CORE_INCLUDE_PERF_MANAGER_HPP_
30.401198
127
0.693717
CambriconKnight
c268b22af2d91e43d4394597ba70a505385f5236
5,305
cpp
C++
spoki/libspoki/src/trace/reader.cpp
inetrg/spoki
599a19366e4cea70e2391471de6f6b745935cddf
[ "MIT" ]
1
2022-02-03T15:35:16.000Z
2022-02-03T15:35:16.000Z
spoki/libspoki/src/trace/reader.cpp
inetrg/spoki
599a19366e4cea70e2391471de6f6b745935cddf
[ "MIT" ]
null
null
null
spoki/libspoki/src/trace/reader.cpp
inetrg/spoki
599a19366e4cea70e2391471de6f6b745935cddf
[ "MIT" ]
null
null
null
/* * This file is part of the CAF spoki driver. * * Copyright (C) 2018-2021 * Authors: Raphael Hiesgen * * All rights reserved. * * Report any bugs, questions or comments to raphael.hiesgen@haw-hamburg.de * */ #include "spoki/trace/reader.hpp" #include "spoki/atoms.hpp" #include "spoki/collector.hpp" #include "spoki/logger.hpp" #include "spoki/trace/processing.hpp" #include "spoki/trace/reporting.hpp" #include "spoki/trace/state.hpp" namespace spoki::trace { namespace { constexpr auto trace_header = "timestamp,accepted,filtered,captured,errors," "dropped,missing"; } // namespace caf::behavior reader(caf::stateful_actor<reader_state>* self, std::vector<caf::actor> probers) { return reader_with_filter(self, std::move(probers), {}); } caf::behavior reader_with_filter(caf::stateful_actor<reader_state>* self, std::vector<caf::actor> probers, std::unordered_set<caf::ipv4_address> filter) { self->state.ids = 0; self->state.statistics = false; self->state.filter = std::move(filter); self->state.probers = std::move(probers); return { [=](trace_atom, std::string uri, uint32_t threads, size_t batch_size) -> caf::result<success_atom> { auto& s = self->state; auto next_id = s.ids++; auto state = std::make_shared<trace::global>(self->system(), self->state.probers, self, next_id, batch_size, self->state.filter); s.states[next_id] = state; auto p = instance::make_processing_callbacks(trace::start_processing, trace::stop_processing, trace::per_packet); auto r = instance::make_reporting_callbacks(trace::start_reporting, trace::stop_reporting, trace::per_result); auto einst = instance::create(std::move(uri), std::move(p), std::move(r), state, next_id); if (!einst) return caf::make_error(caf::sec::invalid_argument); if (threads == 1) einst->set_static_hasher(); auto started = einst->start(threads); if (!started) return caf::make_error(caf::sec::bad_function_call); s.traces[next_id] = std::move(*einst); return success_atom_v; }, [=](report_atom, uint64_t id, trace::tally t) { auto& s = self->state; // Should halve already stopped by now, just making sure. s.traces[id].join(); s.traces.erase(id); s.states.erase(id); CS_LOG_DEBUG("Processed " << t.total_packets << " packets (" << t.ipv4_packets << " IPv4, " << t.ipv6_packets << " IPv6, " << t.others << " other)"); // Prevent waring without logging. static_cast<void>(t); self->send(self, done_atom_v); }, // Some statistics for testing the whole thing. [=](stats_atom, start_atom, std::string path) { self->send(self->state.stats_handler, done_atom_v); auto id = "stats-" + std::string(self->state.name) + "-" + std::to_string(self->id()) + "-" + caf::to_string(self->node()); self->state.stats_handler = self->system().spawn(collector, std::move(path), std::string{"trace"}, std::string{"stats"}, std::string{trace_header}, static_cast<uint32_t>(self->id())); if (!self->state.statistics) { self->send(self, stats_atom_v); self->state.statistics = true; } }, [=](stats_atom, start_atom) { if (!self->state.statistics) { self->send(self, stats_atom_v); self->state.statistics = true; } }, [=](stats_atom, stop_atom) { self->state.statistics = false; self->send(self->state.stats_handler, done_atom_v); }, [=](stats_atom) { auto& s = self->state; if (s.traces.empty()) { aout(self) << "no traces to collect statistics from\n"; return; } if (self->state.statistics) { self->delayed_send(self, std::chrono::seconds(1), stats_atom_v); } auto& tr = s.traces.begin()->second; tr.update_statistics(); auto acc = tr.get_accepted(); auto err = tr.get_errors(); auto dro = tr.get_dropped(); std::string str = std::to_string(self->id()); // str += "|"; // str += std::to_string(make_timestamp().time_since_epoch().count()); str += " | a: "; str += std::to_string(acc - s.accepted); str += ", e: "; str += std::to_string(err - s.errors); str += ", d: "; str += std::to_string(dro - s.dropped); str += "\n"; aout(self) << str; s.accepted = acc; s.errors = err; s.dropped = dro; }, [=](done_atom) { for (auto& r : self->state.traces) r.second.pause(); self->quit(); }, }; } const char* reader_state::name = "reader"; } // namespace spoki::trace
35.604027
80
0.540245
inetrg
c26e526cb28c62e9e57a96405ae6c167c3e28949
1,768
cpp
C++
Code/BBearEditor/Engine/Render/RayTracing/BBRayTracker.cpp
xiaoxianrouzhiyou/BBearEditor
0f1b779d87c297661f9a1e66d0613df43f5fe46b
[ "MIT" ]
26
2021-06-30T02:19:30.000Z
2021-07-23T08:38:46.000Z
Code/BBearEditor/Engine/RayTracing/BBRayTracker.cpp
lishangdian/BBearEditor-2.0
1f4b463ef756ed36cc15d10abae822efc400c4d7
[ "MIT" ]
null
null
null
Code/BBearEditor/Engine/RayTracing/BBRayTracker.cpp
lishangdian/BBearEditor-2.0
1f4b463ef756ed36cc15d10abae822efc400c4d7
[ "MIT" ]
3
2021-09-01T08:19:30.000Z
2021-12-28T19:06:40.000Z
#include "BBRayTracker.h" #include "Utils/BBUtils.h" #include "Scene/BBScene.h" #include "Scene/BBSceneManager.h" #include "BBScreenSpaceRayTracker.h" #include "Base/BBGameObject.h" void BBRayTracker::enable(int nAlgorithmIndex, bool bEnable) { BBScene *pScene = BBSceneManager::getScene(); if (bEnable) { switch (nAlgorithmIndex) { case 0: BBScreenSpaceRayTracker::open(pScene); break; default: break; } } else { pScene->setRenderingFunc(&BBScene::defaultRendering); // objects go back original materials QList<BBGameObject*> objects = pScene->getModels(); for (QList<BBGameObject*>::Iterator itr = objects.begin(); itr != objects.end(); itr++) { BBGameObject *pObject = *itr; pObject->restoreMaterial(); } } } //void BBRayTracker::open() //{ // // Stop refresh per frame // BBSceneManager::getEditViewOpenGLWidget()->stopRenderThread(); // m_pScene->setRenderingFunc(&BBScene::rayTracingRendering); // // open thread // m_pRenderThread = new QThread(this); // QObject::connect(m_pRenderThread, SIGNAL(started()), this, SLOT(render())); // m_pRenderThread->start(); //} //void BBRayTracker::close() //{ // BBSceneManager::getEditViewOpenGLWidget()->startRenderThread(); // m_pScene->setRenderingFunc(&BBScene::defaultRendering); // m_pRenderThread->quit(); // m_pRenderThread->wait(); // BB_SAFE_DELETE(m_pRenderThread); //} //QColor BBRayTracker::getPixelColor(int x, int y) //{ // QColor color; // BBRay inputRay = m_pScene->getCamera()->createRayFromScreen(x, y); // m_pScene->pickObjectInModels(inputRay, false); // return color; //}
25.257143
95
0.639706
xiaoxianrouzhiyou
c2707f3719d52bc7279cb7503fdbc4fc00891f33
3,639
cpp
C++
dmserializers/importsfmv4.cpp
DannyParker0001/Kisak-Strike
99ed85927336fe3aff2efd9b9382b2b32eb1d05d
[ "Unlicense" ]
252
2020-12-16T15:34:43.000Z
2022-03-31T23:21:37.000Z
dmserializers/importsfmv4.cpp
DannyParker0001/Kisak-Strike
99ed85927336fe3aff2efd9b9382b2b32eb1d05d
[ "Unlicense" ]
23
2020-12-20T18:02:54.000Z
2022-03-28T16:58:32.000Z
dmserializers/importsfmv4.cpp
DannyParker0001/Kisak-Strike
99ed85927336fe3aff2efd9b9382b2b32eb1d05d
[ "Unlicense" ]
42
2020-12-19T04:32:33.000Z
2022-03-30T06:00:28.000Z
//====== Copyright � 1996-2006, Valve Corporation, All rights reserved. ======= // // Purpose: // //============================================================================= #include "dmserializers.h" #include "dmebaseimporter.h" #include "datamodel/idatamodel.h" #include "datamodel/dmelement.h" #include "datamodel/dmattributevar.h" #include "tier1/keyvalues.h" #include "tier1/utlbuffer.h" #include "tier1/utlmap.h" #include <limits.h> //----------------------------------------------------------------------------- // Format converter //----------------------------------------------------------------------------- class CImportSFMV4 : public CSFMBaseImporter { typedef CSFMBaseImporter BaseClass; public: CImportSFMV4( char const *formatName, char const *nextFormatName ); private: virtual bool DoFixup( CDmElement *pSourceRoot ); void FixupElement( CDmElement *pElement ); // Fixes up all elements void BuildList( CDmElement *pElement, CUtlRBTree< CDmElement *, int >& list ); }; //----------------------------------------------------------------------------- // Singleton instance //----------------------------------------------------------------------------- static CImportSFMV4 s_ImportSFMV4( "sfm_v4", "sfm_v5" ); void InstallSFMV4Importer( IDataModel *pFactory ) { pFactory->AddLegacyUpdater( &s_ImportSFMV4 ); } //----------------------------------------------------------------------------- // Constructor //----------------------------------------------------------------------------- CImportSFMV4::CImportSFMV4( char const *formatName, char const *nextFormatName ) : BaseClass( formatName, nextFormatName ) { } // Fixes up all elements //----------------------------------------------------------------------------- void CImportSFMV4::FixupElement( CDmElement *pElement ) { if ( !pElement ) return; const char *pType = pElement->GetTypeString(); if ( !V_stricmp( pType, "DmeCamera" ) ) { CDmAttribute *pOldToneMapScaleAttr = pElement->GetAttribute( "toneMapScale" ); float fNewBloomScale = pOldToneMapScaleAttr->GetValue<float>( ); Assert( !pElement->HasAttribute("bloomScale") ); CDmAttribute *pNewBloomScaleAttr = pElement->AddAttribute( "bloomScale", AT_FLOAT ); pNewBloomScaleAttr->SetValue( fNewBloomScale ); pOldToneMapScaleAttr->SetValue( 1.0f ); } } // Fixes up all elements //----------------------------------------------------------------------------- void CImportSFMV4::BuildList( CDmElement *pElement, CUtlRBTree< CDmElement *, int >& list ) { if ( !pElement ) return; if ( list.Find( pElement ) != list.InvalidIndex() ) return; list.Insert( pElement ); // Descend to bottom of tree, then do fixup coming back up the tree for ( CDmAttribute *pAttribute = pElement->FirstAttribute(); pAttribute; pAttribute = pAttribute->NextAttribute() ) { if ( pAttribute->GetType() == AT_ELEMENT ) { CDmElement *pElement = pAttribute->GetValueElement<CDmElement>( ); BuildList( pElement, list ); continue; } if ( pAttribute->GetType() == AT_ELEMENT_ARRAY ) { CDmrElementArray<> array( pAttribute ); int nCount = array.Count(); for ( int i = 0; i < nCount; ++i ) { CDmElement *pChild = array[ i ]; BuildList( pChild, list ); } continue; } } } bool CImportSFMV4::DoFixup( CDmElement *pSourceRoot ) { CUtlRBTree< CDmElement *, int > fixlist( 0, 0, DefLessFunc( CDmElement * ) ); BuildList( pSourceRoot, fixlist ); for ( int i = fixlist.FirstInorder(); i != fixlist.InvalidIndex() ; i = fixlist.NextInorder( i ) ) { // Search and replace in the entire tree! FixupElement( fixlist[ i ] ); } return true; }
29.112
116
0.565815
DannyParker0001
c27c6056ae64f5d37e7c8774e0c7948dddf668e2
3,490
cpp
C++
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/events/SoButtonEvent.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/events/SoButtonEvent.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/events/SoButtonEvent.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
/**************************************************************************\ * * This file is part of the Coin 3D visualization library. * Copyright (C) by Kongsberg Oil & Gas Technologies. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * ("GPL") version 2 as published by the Free Software Foundation. * See the file LICENSE.GPL at the root directory of this source * distribution for additional information about the GNU GPL. * * For using Coin with software that can not be combined with the GNU * GPL, and for taking advantage of the additional benefits of our * support services, please contact Kongsberg Oil & Gas Technologies * about acquiring a Coin Professional Edition License. * * See http://www.coin3d.org/ for more information. * * Kongsberg Oil & Gas Technologies, Bygdoy Alle 5, 0257 Oslo, NORWAY. * http://www.sim.no/ sales@sim.no coin-support@coin3d.org * \**************************************************************************/ /*! \class SoButtonEvent SoButtonEvent.h Inventor/events/SoButtonEvent.h \brief The SoButtonEvent class is the base class for all button events. \ingroup events The event classes which results from the user pushing buttons on some device (keyboard, mouse or spaceball) all inherit this class. The SoButtonEvent class contains methods for setting and getting the state of the button(s). \sa SoEvent, SoKeyboardEvent, SoMouseButtonEvent, SoSpaceballButtonEvent \sa SoEventCallback, SoHandleEventAction */ #include <Inventor/events/SoButtonEvent.h> #include <Inventor/SbName.h> #include <cassert> /*! \enum SoButtonEvent::State This gives the actual state of the button. */ /*! \var SoButtonEvent::State SoButtonEvent::UP Button has been released. */ /*! \var SoButtonEvent::State SoButtonEvent::DOWN Button has been pressed down. */ /*! \var SoButtonEvent::State SoButtonEvent::UNKNOWN The state of the button is unknown. */ SO_EVENT_SOURCE(SoButtonEvent); /*! Initialize the type information data. */ void SoButtonEvent::initClass(void) { SO_EVENT_INIT_CLASS(SoButtonEvent, SoEvent); } /*! Constructor. */ SoButtonEvent::SoButtonEvent(void) { this->buttonstate = SoButtonEvent::UNKNOWN; } /*! Destructor. */ SoButtonEvent::~SoButtonEvent() { } /*! Set the state of the button which the user interacted with. This method is used from the window specific device classes when translating events to the generic Coin library. \sa getState() */ void SoButtonEvent::setState(SoButtonEvent::State state) { this->buttonstate = state; } /*! Returns the state of the button which is the cause of the event, i.e. whether it was pushed down or released. \sa wasShiftDown(), wasCtrlDown(), wasAltDown(), getPosition(), getTime() */ SoButtonEvent::State SoButtonEvent::getState(void) const { return this->buttonstate; } /*! Converts from an enum value of type SoButtonEvent::State to a string containing the enum symbol. \COIN_FUNCTION_EXTENSION \since Coin 3.0 */ // Should we add stringToEnum as well perhaps? SbBool SoButtonEvent::enumToString(State enumval, SbString & stringrep) { switch (enumval) { case SoButtonEvent::UP: stringrep = "UP"; break; case SoButtonEvent::DOWN: stringrep = "DOWN"; break; case SoButtonEvent::UNKNOWN: stringrep = "UNKNOWN"; break; default: return FALSE; } return TRUE; }
25.474453
76
0.697708
KraftOreo
c27e211f722049acc93ae5e293433f2fb5ceb56d
667
hpp
C++
tests/helper/compare.hpp
rsjtaylor/libear
40a4000296190c3f91eba79e5b92141e368bd72a
[ "Apache-2.0" ]
14
2019-07-30T17:58:00.000Z
2022-02-15T15:33:36.000Z
tests/helper/compare.hpp
rsjtaylor/libear
40a4000296190c3f91eba79e5b92141e368bd72a
[ "Apache-2.0" ]
27
2019-07-30T18:01:58.000Z
2021-12-14T10:24:52.000Z
tests/helper/compare.hpp
rsjtaylor/libear
40a4000296190c3f91eba79e5b92141e368bd72a
[ "Apache-2.0" ]
5
2019-07-30T15:12:02.000Z
2020-09-14T16:22:43.000Z
#pragma once #include "ear/common_types.hpp" namespace ear { inline bool operator==(const CartesianPosition& a, const CartesianPosition& b) { return a.X == b.X && a.Y == b.Y && a.Z == b.Z; } inline bool operator!=(const CartesianPosition& a, const CartesianPosition& b) { return !(a == b); } inline bool operator==(const PolarPosition& a, const PolarPosition& b) { return a.azimuth == b.azimuth && a.elevation == b.elevation && a.distance == b.distance; } inline bool operator!=(const PolarPosition& a, const PolarPosition& b) { return !(a == b); } }; // namespace ear
27.791667
74
0.589205
rsjtaylor
c281ba89e3604dbff2de3cb053699968c26adb83
42,921
inl
C++
volume/Unified2/src/Task/ElasticSystem/ElasticSystemCommon.inl
llmontoryxd/mipt_diploma
7d7d65cd619fe983736773f95ebb50b470adbed2
[ "MIT" ]
null
null
null
volume/Unified2/src/Task/ElasticSystem/ElasticSystemCommon.inl
llmontoryxd/mipt_diploma
7d7d65cd619fe983736773f95ebb50b470adbed2
[ "MIT" ]
null
null
null
volume/Unified2/src/Task/ElasticSystem/ElasticSystemCommon.inl
llmontoryxd/mipt_diploma
7d7d65cd619fe983736773f95ebb50b470adbed2
[ "MIT" ]
null
null
null
#include "../VolumeMethod/FunctionGetters/BoundaryFunctionGetter.h" template <typename Space> void ElasticSystemCommon<Space>::ValueTypeCommon::SetZeroValues() { std::fill_n(values, dimsCount, Scalar(0.0)); } template <> Space2::Vector ElasticSystemCommon<Space2>::ValueTypeCommon::GetVelocity() const { return Space2::Vector(values[3], values[4]); } template <> Space3::Vector ElasticSystemCommon<Space3>::ValueTypeCommon::GetVelocity() const { return Space3::Vector(values[6], values[7], values[8]); } template <> void ElasticSystemCommon<Space2>::ValueTypeCommon::SetVelocity(const Vector& velocity) { values[3] = velocity.x; values[4] = velocity.y; } template <> void ElasticSystemCommon<Space3>::ValueTypeCommon::SetVelocity(const Vector& velocity) { values[6] = velocity.x; values[7] = velocity.y; values[8] = velocity.z; } template <> void ElasticSystemCommon<Space2>::ValueTypeCommon::SetTension(const Tensor& tension) { values[0] = tension.xx; values[1] = tension.yy; values[2] = tension.xy; } template <> void ElasticSystemCommon<Space3>::ValueTypeCommon::SetTension(const Tensor& tension) { values[0] = tension.xx; values[1] = tension.yy; values[2] = tension.zz; values[3] = tension.xy; values[4] = tension.yz; values[5] = tension.xz; } template <typename Space> typename Space::Scalar ElasticSystemCommon<Space>::ValueTypeCommon::GetXX() const { return values[0]; } template <typename Space> typename Space::Scalar ElasticSystemCommon<Space>::ValueTypeCommon::GetYY() const { return values[1]; } template <> Space2::Scalar ElasticSystemCommon<Space2>::ValueTypeCommon::GetXY() const { return values[2]; } template <> Space3::Scalar ElasticSystemCommon<Space3>::ValueTypeCommon::GetXY() const { return values[3]; } template <> void ElasticSystemCommon<Space2>::ValueTypeCommon::MakeDimension( Scalar tensionDimensionlessMult, Scalar velocityDimensionlessMult) { for (IndexType valueIndex = 0; valueIndex < dimsCount; ++valueIndex) { switch (valueIndex) { case 0: case 1: case 2: values[valueIndex] *= tensionDimensionlessMult; break; case 3: case 4: values[valueIndex] *= velocityDimensionlessMult; break; default: assert(0); break; } } } template <> void ElasticSystemCommon<Space3>::ValueTypeCommon::MakeDimension( Scalar tensionDimensionlessMult, Scalar velocityDimensionlessMult) { for (IndexType valueIndex = 0; valueIndex < dimsCount; ++valueIndex) { switch (valueIndex) { case 0: case 1: case 2: case 3: case 4: case 5: values[valueIndex] *= tensionDimensionlessMult; break; case 6: case 7: case 8: values[valueIndex] *= velocityDimensionlessMult; break; default: assert(0); break; } } } template <> void ElasticSystemCommon<Space2>::BuildXMatrix(const MediumParameters& mediumParameters, MatrixXDim& xMatrix) { xMatrix << mediumParameters.flowVelocity.x, 0, 0, -(mediumParameters.lambda + Scalar(2.0) * mediumParameters.mju), 0, 0, mediumParameters.flowVelocity.x, 0, -mediumParameters.lambda, 0, 0, 0, mediumParameters.flowVelocity.x, 0, -mediumParameters.mju, -mediumParameters.invRho, 0, 0, mediumParameters.flowVelocity.x, 0, 0, 0, -mediumParameters.invRho, 0, mediumParameters.flowVelocity.x; } template <> void ElasticSystemCommon<Space3>::BuildXMatrix(const MediumParameters& mediumParameters, MatrixXDim& xMatrix) { xMatrix << mediumParameters.flowVelocity.x, 0, 0, 0, 0, 0, -(mediumParameters.lambda + Scalar(2.0) * mediumParameters.mju), 0, 0, 0, mediumParameters.flowVelocity.x, 0, 0, 0, 0, -mediumParameters.lambda , 0, 0, 0, 0, mediumParameters.flowVelocity.x, 0, 0, 0, -mediumParameters.lambda , 0, 0, 0, 0, 0, mediumParameters.flowVelocity.x, 0, 0, 0, -mediumParameters.mju, 0, 0, 0, 0, 0, mediumParameters.flowVelocity.x, 0, 0, 0, 0, 0, 0, 0, 0, 0, mediumParameters.flowVelocity.x, 0, 0, -mediumParameters.mju, -mediumParameters.invRho, 0, 0, 0, 0, 0, mediumParameters.flowVelocity.x, 0, 0, 0, 0, 0, -mediumParameters.invRho, 0, 0, 0, mediumParameters.flowVelocity.x, 0, 0, 0, 0, 0, 0, -mediumParameters.invRho, 0, 0, mediumParameters.flowVelocity.x; } template <> void ElasticSystemCommon<Space2>::BuildYMatrix(const MediumParameters& mediumParameters, MatrixXDim& yMatrix) { yMatrix << mediumParameters.flowVelocity.y, 0, 0, 0, -mediumParameters.lambda, 0, mediumParameters.flowVelocity.y, 0, 0, -(mediumParameters.lambda + Scalar(2.0) * mediumParameters.mju), 0, 0, mediumParameters.flowVelocity.y, -mediumParameters.mju, 0, 0, 0, -mediumParameters.invRho, mediumParameters.flowVelocity.y, 0, 0, -mediumParameters.invRho, 0, 0, mediumParameters.flowVelocity.y; } template <> void ElasticSystemCommon<Space3>::BuildYMatrix(const MediumParameters& mediumParameters, MatrixXDim& yMatrix) { yMatrix << mediumParameters.flowVelocity.y, 0, 0, 0, 0, 0, 0, -mediumParameters.lambda , 0, 0, mediumParameters.flowVelocity.y, 0, 0, 0, 0, 0, -(mediumParameters.lambda + Scalar(2.0) * mediumParameters.mju), 0, 0, 0, mediumParameters.flowVelocity.y, 0, 0, 0, 0, -mediumParameters.lambda , 0, 0, 0, 0, mediumParameters.flowVelocity.y, 0, 0, -mediumParameters.mju, 0, 0, 0, 0, 0, 0, mediumParameters.flowVelocity.y, 0, 0, 0, -mediumParameters.mju, 0, 0, 0, 0, 0, mediumParameters.flowVelocity.y, 0, 0, 0, 0, 0, 0, -mediumParameters.invRho, 0, 0, mediumParameters.flowVelocity.y, 0, 0, 0, -mediumParameters.invRho, 0, 0, 0, 0, 0, mediumParameters.flowVelocity.y, 0, 0, 0, 0, 0, -mediumParameters.invRho, 0, 0, 0, mediumParameters.flowVelocity.y; } template <> void ElasticSystemCommon<Space2>::BuildRMatrix( const MediumParameters& interiorMediumParameters, const MediumParameters& exteriorMediumParameters, MatrixXDim& rMatrix) { rMatrix << interiorMediumParameters.lambda + 2 * interiorMediumParameters.mju, 0, 0, 0, exteriorMediumParameters.lambda + 2 * exteriorMediumParameters.mju, interiorMediumParameters.lambda , 0, 1, 0, exteriorMediumParameters.lambda , 0, interiorMediumParameters.mju, 0, exteriorMediumParameters.mju, 0, interiorMediumParameters.GetPSpeed(), 0, 0, 0, -exteriorMediumParameters.GetPSpeed(), 0, interiorMediumParameters.GetSSpeed(), 0, -exteriorMediumParameters.GetSSpeed(), 0; } template <> void ElasticSystemCommon<Space3>::BuildRMatrix( const MediumParameters& interiorMediumParameters, const MediumParameters& exteriorMediumParameters, MatrixXDim& rMatrix) { rMatrix << interiorMediumParameters.lambda + 2 * interiorMediumParameters.mju, 0, 0, 0, 0, 0, 0, 0, exteriorMediumParameters.lambda + 2 * exteriorMediumParameters.mju, interiorMediumParameters.lambda , 0, 0, 0, 1, 0, 0, 0, exteriorMediumParameters.lambda , interiorMediumParameters.lambda , 0, 0, 0, 0, 1, 0, 0, exteriorMediumParameters.lambda , 0, interiorMediumParameters.mju, 0, 0, 0, 0, 0, exteriorMediumParameters.mju, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, interiorMediumParameters.mju, 0, 0, 0, exteriorMediumParameters.mju, 0, 0, interiorMediumParameters.GetPSpeed(), 0, 0, 0, 0, 0, 0, 0, -exteriorMediumParameters.GetPSpeed(), 0, interiorMediumParameters.GetSSpeed(), 0, 0, 0, 0, 0, -exteriorMediumParameters.GetSSpeed(), 0, 0, 0, interiorMediumParameters.GetSSpeed(), 0, 0, 0, -exteriorMediumParameters.GetSSpeed(), 0, 0; } template <> void ElasticSystemCommon<Space2>::BuildXnAuxMatrix( const MediumParameters& interiorMediumParameters, const MediumParameters& exteriorMediumParameters, MatrixXDim& xnAuxMatrix) { /* Eigen::Matrix<Scalar, dimsCount, dimsCount> rMatrix; BuildRMatrix(interiorMediumParameters, exteriorMediumParameters, rMatrix); Eigen::Matrix<Scalar, 1, dimsCount> lambdaMatrix; lambdaMatrix << interiorMediumParameters.GetPSpeed(), interiorMediumParameters.GetSSpeed(), 0, 0, 0; xnAuxMatrix.noalias() = rMatrix * lambdaMatrix.asDiagonal() * rMatrix.inverse(); */ Scalar cpInt = interiorMediumParameters.GetPSpeed(); Scalar cpExt = exteriorMediumParameters.GetPSpeed(); Scalar csInt = interiorMediumParameters.GetSSpeed(); Scalar csExt = exteriorMediumParameters.GetSSpeed(); Scalar rhoInt = 1 / interiorMediumParameters.invRho; Scalar rhoExt = 1 / exteriorMediumParameters.invRho; Scalar zpInt = cpInt * rhoInt; Scalar zsInt = csInt * rhoInt; Scalar zpExt = cpExt * rhoExt; Scalar zsExt = csExt * rhoExt; Scalar coeffP = 1 / (zpInt + zpExt); Scalar coeffS = Scalar(1.0) / (rhoInt + rhoExt); if (zsInt + zsExt > std::numeric_limits<Scalar>::epsilon()) { coeffS = csInt / (zsInt + zsExt); } xnAuxMatrix << coeffP * zpInt * cpInt, 0, 0, coeffP * zpInt * zpExt * cpInt, 0, coeffP * interiorMediumParameters.lambda, 0, 0, coeffP * interiorMediumParameters.lambda * zpExt, 0, 0, 0, coeffS * zsInt, 0, coeffS * zsInt * zsExt, coeffP * cpInt, 0, 0, coeffP * cpInt * zpExt, 0, 0, 0, coeffS, 0, coeffS * zsExt; } template <> void ElasticSystemCommon<Space3>::BuildXnAuxMatrix( const MediumParameters& interiorMediumParameters, const MediumParameters& exteriorMediumParameters, MatrixXDim& xnAuxMatrix) { /* Eigen::Matrix<Scalar, dimsCount, dimsCount> rMatrix; BuildRMatrix(interiorMediumParameters, exteriorMediumParameters, rMatrix); Eigen::Matrix<Scalar, 1, dimsCount> lambdaMatrix; lambdaMatrix << interiorMediumParameters.GetPSpeed(), interiorMediumParameters.GetSSpeed(), interiorMediumParameters.GetSSpeed(), 0, 0, 0, 0, 0, 0; xnAuxMatrix.noalias() = rMatrix * lambdaMatrix.asDiagonal() * rMatrix.inverse(); */ Scalar cpInt = interiorMediumParameters.GetPSpeed(); Scalar cpExt = exteriorMediumParameters.GetPSpeed(); Scalar csInt = interiorMediumParameters.GetSSpeed(); Scalar csExt = exteriorMediumParameters.GetSSpeed(); Scalar rhoInt = 1 / interiorMediumParameters.invRho; Scalar rhoExt = 1 / exteriorMediumParameters.invRho; Scalar zpInt = cpInt * rhoInt; Scalar zsInt = csInt * rhoInt; Scalar zpExt = cpExt * rhoExt; Scalar zsExt = csExt * rhoExt; Scalar coeffP = 1 / (zpInt + zpExt); Scalar coeffS = Scalar(1.0) / (rhoInt + rhoExt); if (zsInt + zsExt > std::numeric_limits<Scalar>::epsilon()) { coeffS = csInt / (zsInt + zsExt); } xnAuxMatrix << coeffP * zpInt * cpInt, 0, 0, 0, 0, 0, coeffP * zpInt * zpExt * cpInt, 0, 0, coeffP * interiorMediumParameters.lambda, 0, 0, 0, 0, 0, coeffP * zpExt * interiorMediumParameters.lambda, 0, 0, coeffP * interiorMediumParameters.lambda, 0, 0, 0, 0, 0, coeffP * zpExt * interiorMediumParameters.lambda, 0, 0, 0, 0, 0, coeffS * zsInt, 0, 0, 0, coeffS * zsInt * zsExt, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, coeffS * zsInt, 0, 0, coeffS * zsInt * zsExt, coeffP * cpInt, 0, 0, 0, 0, 0, coeffP * zpExt * cpInt, 0, 0, 0, 0, 0, coeffS, 0, 0, 0, coeffS * zsExt, 0, 0, 0, 0, 0, 0, coeffS, 0, 0, coeffS * zsExt; } template <> void ElasticSystemCommon<Space2>::BuildXnInteriorMatrix( const MediumParameters& interiorMediumParameters, const MediumParameters& exteriorMediumParameters, const Vector& edgeNormal, const MatrixXDim& xnAuxMatrix, MatrixXDim& xnInteriorMatrix) { // BuildXnAuxMatrix(interiorMediumParameters, exteriorMediumParameters, xnInteriorMatrix); xnInteriorMatrix = xnAuxMatrix; // XMatrix xnInteriorMatrix(0, 3) -= interiorMediumParameters.lambda + Scalar(2.0) * interiorMediumParameters.mju; xnInteriorMatrix(1, 3) -= interiorMediumParameters.lambda; xnInteriorMatrix(2, 4) -= interiorMediumParameters.mju; xnInteriorMatrix(3, 0) -= interiorMediumParameters.invRho; xnInteriorMatrix(4, 2) -= interiorMediumParameters.invRho; Scalar un = interiorMediumParameters.flowVelocity * edgeNormal; for (int row = 0; row < dimsCount; ++row) { // diagonal elements xnInteriorMatrix(row, row) += (un + fabs(un)) * Scalar(0.5); } } template <> void ElasticSystemCommon<Space3>::BuildXnInteriorMatrix( const MediumParameters& interiorMediumParameters, const MediumParameters& exteriorMediumParameters, const Vector& faceNormal, const MatrixXDim& xnAuxMatrix, MatrixXDim& xnInteriorMatrix) { //BuildXnAuxMatrix(interiorMediumParameters, exteriorMediumParameters, xnInteriorMatrix); xnInteriorMatrix = xnAuxMatrix; // XMatrix xnInteriorMatrix(0, 6) -= interiorMediumParameters.lambda + Scalar(2.0) * interiorMediumParameters.mju; xnInteriorMatrix(1, 6) -= interiorMediumParameters.lambda; xnInteriorMatrix(2, 6) -= interiorMediumParameters.lambda; xnInteriorMatrix(3, 7) -= interiorMediumParameters.mju; xnInteriorMatrix(5, 8) -= interiorMediumParameters.mju; xnInteriorMatrix(6, 0) -= interiorMediumParameters.invRho; xnInteriorMatrix(7, 3) -= interiorMediumParameters.invRho; xnInteriorMatrix(8, 5) -= interiorMediumParameters.invRho; Scalar un = interiorMediumParameters.flowVelocity * faceNormal; for (int row = 0; row < dimsCount; ++row) { // diagonal elements xnInteriorMatrix(row, row) += (un + fabs(un)) * Scalar(0.5); } } template <typename Space> void ElasticSystemCommon<Space>::BuildXnExteriorMatrix( const MediumParameters& interiorMediumParameters, const MediumParameters& exteriorMediumParameters, const Vector& normal, const MatrixXDim& xnAuxMatrix, MatrixXDim& xnExteriorMatrix) { //BuildXnAuxMatrix(interiorMediumParameters, exteriorMediumParameters, xnExteriorMatrix); //xnExteriorMatrix *= Scalar(-1.0); xnExteriorMatrix = -xnAuxMatrix; Scalar un = interiorMediumParameters.flowVelocity * normal; for (int row = 0; row < dimsCount; ++row) { // diagonal elements xnExteriorMatrix(row, row) += (un - fabs(un)) * Scalar(0.5); } } template <> void ElasticSystemCommon<Space2>::BuildBoundaryMatrix(IndexType interactionType, Eigen::Matrix<Scalar, 1, dimsCount>& boundaryMatrix) { IndexType boundaryType = boundaryDescriptions[interactionType].type; Scalar reflectionCoeff = boundaryDescriptions[interactionType].reflectionCoeff; switch(boundaryType) { case BoundaryConditions::Absorb: { boundaryMatrix << 0, 0, 0, 0, 0; } break; case BoundaryConditions::Free: { boundaryMatrix << -reflectionCoeff, reflectionCoeff, -reflectionCoeff, reflectionCoeff, reflectionCoeff; } break; case BoundaryConditions::Fixed: { boundaryMatrix << reflectionCoeff, reflectionCoeff, reflectionCoeff, -reflectionCoeff, -reflectionCoeff; } break; case BoundaryConditions::Symmetry: { boundaryMatrix << Scalar(1.0), Scalar(1.0), -Scalar(1.0), // sigma.xy -Scalar(1.0), // v.x Scalar(1.0); } break; case BoundaryConditions::AntiSymmetry: { boundaryMatrix << -Scalar(1.0), // sigma.xx Scalar(1.0), Scalar(1.0), Scalar(1.0), -Scalar(1.0); // v.y } break; default: assert(0); break; } } template <> void ElasticSystemCommon<Space3>::BuildBoundaryMatrix(IndexType interactionType, Eigen::Matrix<Scalar, 1, dimsCount>& boundaryMatrix) { IndexType boundaryType = boundaryDescriptions[interactionType].type; Scalar reflectionCoeff = boundaryDescriptions[interactionType].reflectionCoeff; switch (boundaryType) { case BoundaryConditions::Absorb: { boundaryMatrix << 0, 0, 0, 0, 0, 0, 0, 0, 0; } break; case BoundaryConditions::Free: { boundaryMatrix << -reflectionCoeff, // sigma.xx reflectionCoeff, reflectionCoeff, -reflectionCoeff, // sigma.xy reflectionCoeff, -reflectionCoeff, // sigma.xz reflectionCoeff, reflectionCoeff, reflectionCoeff; } break; case BoundaryConditions::Fixed: { boundaryMatrix << reflectionCoeff, reflectionCoeff, reflectionCoeff, reflectionCoeff, reflectionCoeff, reflectionCoeff, -reflectionCoeff, // v.x -reflectionCoeff, // v.y -reflectionCoeff; // v.z } break; case BoundaryConditions::Symmetry: { boundaryMatrix << reflectionCoeff, reflectionCoeff, reflectionCoeff, -reflectionCoeff, // sigma xy -reflectionCoeff, // sigma yz -reflectionCoeff, // sigma xz -reflectionCoeff, // v.x reflectionCoeff, reflectionCoeff; } break; case BoundaryConditions::AntiSymmetry: { boundaryMatrix << -reflectionCoeff, // sigma.xx reflectionCoeff, reflectionCoeff, reflectionCoeff, reflectionCoeff, reflectionCoeff, reflectionCoeff, -reflectionCoeff, // v.y -reflectionCoeff; // v.z } break; default: assert(0); break; } } template <> void ElasticSystemCommon<Space2>::BuildContactMatrices(IndexType interactionType, Eigen::Matrix<Scalar, 1, dimsCount>& leftContactMatrix, Eigen::Matrix<Scalar, 1, dimsCount>& rightContactMatrix) { IndexType contactType = contactDescriptions[interactionType].type; switch(contactType) { case ContactConditions::Glue: { leftContactMatrix << 0, 0, 0, 0, 0; rightContactMatrix << 1, 1, 1, 1, 1; } break; case ContactConditions::Glide: { // it`s correct when materials on the both sides of contact are the same leftContactMatrix << 0, 1, -1, 0, 1; rightContactMatrix << 1, 0, 0, 1, 0; } break; case ContactConditions::Friction: { // friction should be computed as a dynamic contact assert(0); } break; } } template <> void ElasticSystemCommon<Space3>::BuildContactMatrices(IndexType interactionType, Eigen::Matrix<Scalar, 1, dimsCount>& leftContactMatrix, Eigen::Matrix<Scalar, 1, dimsCount>& rightContactMatrix) { IndexType contactType = contactDescriptions[interactionType].type; switch (contactType) { case ContactConditions::Glue: { leftContactMatrix << 0, 0, 0, 0, 0, 0, 0, 0, 0; rightContactMatrix << 1, 1, 1, 1, 1, 1, 1, 1, 1; } break; case ContactConditions::Glide: { // TODO leftContactMatrix << 0, 1, 1, -1, -1, -1, 0, 1, 1; rightContactMatrix << 1, 0, 0, 0, 0, 0, 1, 0, 0; } break; case ContactConditions::Friction: { // friction should be computed as a dynamic contact assert(0); } break; default: assert(0); break; } } template<typename Space> void ElasticSystemCommon<Space>::SetAbsorbBoundary(IndexType interactionType) { BoundaryDescription newBoundary; newBoundary.type = BoundaryConditions::Absorb; newBoundary.infoIndex = -1; SetBoundaryDescription(interactionType, newBoundary); } template<typename Space> void ElasticSystemCommon<Space>::SetSymmetryBoundary(IndexType interactionType) { BoundaryDescription newBoundary; newBoundary.type = BoundaryConditions::Symmetry; newBoundary.infoIndex = -1; SetBoundaryDescription(interactionType, newBoundary); } template<typename Space> void ElasticSystemCommon<Space>::SetAntiSymmetryBoundary(IndexType interactionType) { BoundaryDescription newBoundary; newBoundary.type = BoundaryConditions::AntiSymmetry; newBoundary.infoIndex = -1; SetBoundaryDescription(interactionType, newBoundary); } template<typename Space> void ElasticSystemCommon<Space>::SetGlueContact(IndexType interactionType) { ContactDescription newContact; newContact.type = ContactConditions::Glue; newContact.infoIndex = -1; SetContactDescription(interactionType, newContact); } template<typename Space> void ElasticSystemCommon<Space>::SetGlueContact(IndexType interactionType, Scalar maxShearStress, Scalar maxLongitudinalStress, IndexType dynamicBoundaryInteractionType) { ContactDescription newContact; newContact.type = ContactConditions::Glue; newContact.infoIndex = glueContactInfos.size(); SetContactDescription(interactionType, newContact); glueContactInfos.push_back( GlueContactInfo<Space>(maxShearStress, maxLongitudinalStress, dynamicBoundaryInteractionType)); } template<typename Space> void ElasticSystemCommon<Space>::SetFrictionContact(IndexType interactionType, Scalar frictionCoeff, IndexType dynamicBoundaryInteractionType) { ContactDescription newContact; newContact.type = ContactConditions::Friction; newContact.infoIndex = frictionContactInfos.size(); SetContactDescription(interactionType, newContact); frictionContactInfos.push_back(FrictionContactInfo<Space>(frictionCoeff, dynamicBoundaryInteractionType)); } template<typename Space> void ElasticSystemCommon<Space>::SetFrictionContact(IndexType interactionType) { ContactDescription newContact; newContact.type = ContactConditions::Friction; newContact.infoIndex = frictionContactInfos.size(); SetContactDescription(interactionType, newContact); } template<typename Space> void ElasticSystemCommon<Space>::SetGlideContact(IndexType interactionType) { ContactDescription newContact; newContact.type = ContactConditions::Glide; newContact.infoIndex = -1; SetContactDescription(interactionType, newContact); } template<typename Space> typename Space::IndexType ElasticSystemCommon<Space>::GetContactDynamicBoundaryType(IndexType contactInteractionType) const { if(contactInteractionType < contactDescriptions.size() && contactDescriptions[contactInteractionType].type == ContactConditions::Glue && contactDescriptions[contactInteractionType].infoIndex != IndexType(-1)) { IndexType glueInfoIndex = contactDescriptions[contactInteractionType].infoIndex; return glueInfoIndex != IndexType(-1) ? glueContactInfos.at(glueInfoIndex).dynamicBoundaryInteractionType : IndexType(-1); } return IndexType(-1); } template<typename Space> typename Space::IndexType ElasticSystemCommon<Space>::GetBoundaryDynamicContactType(IndexType boundaryInteractionType) const { if(boundaryInteractionType < boundaryDescriptions.size() && boundaryDescriptions[boundaryInteractionType].type == BoundaryConditions::Free && boundaryDescriptions[boundaryInteractionType].infoIndex != IndexType(-1)) { IndexType freeInfoIndex = boundaryDescriptions[boundaryInteractionType].infoIndex; return freeInfoIndex != IndexType(-1) ? freeBoundaryInfos[freeInfoIndex].dynamicContactInteractionType : IndexType(-1); } return IndexType(-1); } template<typename Space> void ElasticSystemCommon<Space>::GetFrictionContactInfo(IndexType interactionType, Scalar &frictionCoeff) { if(contactDescriptions[interactionType].type == ContactConditions::Friction && contactDescriptions[interactionType].infoIndex != IndexType(-1)) { frictionCoeff = frictionContactInfos[contactDescriptions[interactionType].infoIndex].frictionCoeff; return; } assert(0); frictionCoeff = 0; //should never happen. hopefully. } template<typename Space> void ElasticSystemCommon<Space>::GetContactCriticalInfo(IndexType interactionType, Scalar &maxShearStress, Scalar &maxLongitudinalStress) { assert(GetContactDynamicBoundaryType(interactionType) != IndexType(-1)); if(contactDescriptions[interactionType].type == ContactConditions::Glue && contactDescriptions[interactionType].infoIndex != IndexType(-1)) { maxShearStress = glueContactInfos[contactDescriptions[interactionType].infoIndex].maxShearStress; maxLongitudinalStress = glueContactInfos[contactDescriptions[interactionType].infoIndex].maxLongitudinalStress; return; } assert(0); maxShearStress = 0; //should never happen. hopefully. maxLongitudinalStress = 0; } template<typename Space> BoundaryConditions::Types ElasticSystemCommon<Space>::GetBoundaryType(IndexType interactionType) const { return boundaryDescriptions[interactionType].type; } template<typename Space> ContactConditions::Types ElasticSystemCommon<Space>::GetContactType(IndexType interactionType) const { return contactDescriptions[interactionType].type; } template<typename Space> typename ElasticSystemCommon<Space>::SourceFunctorT* ElasticSystemCommon<Space>::GetSourceFunctor() const { return sourceFunctor; } template<typename Space> void ElasticSystemCommon<Space>::SetSourceFunctor(SourceFunctorT* sourceFunctor) { this->sourceFunctor = sourceFunctor; } template<typename Space> void ElasticSystemCommon<Space>::SetPointSources(const std::vector<PointSource<Space>* >& pointSources) { this->pointSources = pointSources; } template<typename Space> typename Space::Scalar ElasticSystemCommon<Space>::GetMaxWaveSpeed(const MediumParameters& mediumParameters) const { return mediumParameters.GetPSpeed(); } template<typename Space> void ElasticSystemCommon<Space>::SetBoundaryDescription(IndexType interactionType, BoundaryDescription boundaryDescription) { if(boundaryDescriptions.size() < interactionType + 1) { boundaryDescriptions.resize(interactionType + 1); } boundaryDescriptions[interactionType] = boundaryDescription; } template<typename Space> void ElasticSystemCommon<Space>::SetContactDescription(IndexType interactionType, ContactDescription contactDescription) { if(contactDescriptions.size() < interactionType + 1) { contactDescriptions.resize(interactionType + 1); } contactDescriptions[interactionType] = contactDescription; } template <typename Space> ElasticSystemCommon<Space>::MediumParameters::MediumParameters(): lambda(Scalar(2.0)), mju(Scalar(1.0)), invRho(Scalar(1.0)), destroyed(false), dimensionless(false), fixed(false) { } template <typename Space> ElasticSystemCommon<Space>::MediumParameters::MediumParameters( Scalar lambda, Scalar mju, Scalar invRho): lambda(lambda), mju(mju), invRho(invRho), destroyed(false), dimensionless(false), fixed(false) { } template <typename Space> void ElasticSystemCommon<Space>::MediumParameters::SetFromVelocities(Scalar pSpeed, Scalar sSpeed, Scalar rho) { mju = Sqr(sSpeed) * rho; lambda = (Sqr(pSpeed) - 2.0 * Sqr(sSpeed)) * rho; invRho = 1 / rho; } template <typename Space> void ElasticSystemCommon<Space>::MediumParameters::SetFromLameParameters(Scalar lambda, Scalar mju, Scalar rho) { this->lambda = lambda; this->mju = mju; invRho = 1 / rho; } template <typename Space> void ElasticSystemCommon<Space>::MediumParameters::SetFromYoungModuleAndNju(Scalar youngModule, Scalar nju, Scalar rho) { this->lambda = nju * youngModule / (1 + nju) / (1 - 2 * nju); this->mju = youngModule / Scalar(2.0) / (1 + nju); invRho = 1 / rho; } template <typename Space> typename Space::Scalar ElasticSystemCommon<Space>::MediumParameters::GetPSpeed() const { return sqrt((lambda + Scalar(2.0) * mju) * invRho); } template <typename Space> typename Space::Scalar ElasticSystemCommon<Space>::MediumParameters::GetSSpeed() const { return sqrt(mju * invRho); } template <typename Space> typename Space::Scalar ElasticSystemCommon<Space>::MediumParameters::GetZp() const { return GetPSpeed() / invRho; } template <typename Space> typename Space::Scalar ElasticSystemCommon<Space>::MediumParameters::GetZs() const { return GetSSpeed() / invRho; } template <typename Space> void ElasticSystemCommon<Space>::MediumParameters::MakeDimensionless( Scalar tensionDimensionlessMult, Scalar velocityDimensionlessMult) { if (!dimensionless) { dimensionless = true; lambda /= tensionDimensionlessMult; mju /= tensionDimensionlessMult; invRho *= tensionDimensionlessMult / Sqr(velocityDimensionlessMult); plasticity.k0 /= tensionDimensionlessMult; flowVelocity /= velocityDimensionlessMult; } } template <typename Space> bool ElasticSystemCommon<Space>::MediumParameters::IsZero() const { bool isZero = true; for (IndexType paramIndex = 0; paramIndex < ParamsCount; ++paramIndex) { if (params[paramIndex] > std::numeric_limits<Scalar>::epsilon()) isZero = false; } return isZero; } template<typename Space> bool ElasticSystemCommon<Space>::IsProperContact(const ValueTypeCommon& value0, const ValueTypeCommon& value1, const Vector& contactNormal) { // return true; Scalar eps = std::numeric_limits<Scalar>::epsilon(); if (value1.GetForce(-contactNormal) * contactNormal - value0.GetForce(contactNormal) * contactNormal > -eps && (value0.GetVelocity() - value1.GetVelocity()) * contactNormal > eps) return true; return false; } template<typename Space> BoundaryInfoFunctor<Space>* ElasticSystemCommon<Space>::GetBoundaryInfoFunctor(IndexType interactionType) { int infoIndex = boundaryDescriptions[interactionType].infoIndex; BoundaryFunctionGetter<Space>* getter = nullptr; switch(boundaryDescriptions[interactionType].type) { case BoundaryConditions::Absorb: { return nullptr; }break; case BoundaryConditions::Free: { assert(infoIndex != -1); return freeBoundaryInfos[infoIndex].boundaryFunctor; }break; case BoundaryConditions::Fixed: { assert(infoIndex != -1); return fixedBoundaryInfos[infoIndex].boundaryFunctor; }break; case BoundaryConditions::Symmetry: { return nullptr; }break; case BoundaryConditions::AntiSymmetry: { return nullptr; }break; default: assert(0); break; } assert(0); //unknown interation type return nullptr; } template<typename Space> void ElasticSystemCommon<Space>::SetFreeBoundary(IndexType interactionType, Scalar tensionDimensionlessMult, Scalar reflectionCoeff, VectorFunctor<Space>* externalForceFunctor, IndexType dynamicContactInteractionType) { BoundaryDescription newBoundary; newBoundary.type = BoundaryConditions::Free; newBoundary.infoIndex = freeBoundaryInfos.size(); newBoundary.reflectionCoeff = reflectionCoeff; SetBoundaryDescription(interactionType, newBoundary); FreeBoundaryInfo<Space> freeInfo; if (externalForceFunctor) freeInfo.boundaryFunctor = externalForceFunctor ? new FreeBoundaryInfoFunctor(externalForceFunctor, tensionDimensionlessMult) : nullptr; freeInfo.dynamicContactInteractionType = dynamicContactInteractionType; freeBoundaryInfos.push_back(freeInfo); } template<typename Space> void ElasticSystemCommon<Space>::SetFixedBoundary(IndexType interactionType, Scalar velocityDimensionlessMult, Scalar reflectionCoeff, VectorFunctor<Space>* externalVelocityFunctor) { BoundaryDescription newBoundary; newBoundary.type = BoundaryConditions::Fixed; newBoundary.infoIndex = fixedBoundaryInfos.size(); newBoundary.reflectionCoeff = reflectionCoeff; SetBoundaryDescription(interactionType, newBoundary); FixedBoundaryInfo<Space> fixedInfo; fixedInfo.boundaryFunctor = externalVelocityFunctor ? new FixedBoundaryInfoFunctor(externalVelocityFunctor, velocityDimensionlessMult) : nullptr; fixedBoundaryInfos.push_back(fixedInfo); } template <> void ElasticSystemCommon<Space2>::FreeBoundaryInfoFunctor::operator()( const Vector& globalPoint, const Vector& externalNormal, const Scalar time, Scalar* values) { Vector externalForce = (*forceFunctor)(globalPoint, externalNormal, time) / tensionDimensionlessMult; Vector force(externalForce * externalNormal, externalNormal ^ externalForce); /*const Scalar frictionCoeff = Scalar(0.002); force.y *= -frictionCoeff * externalForce.GetNorm() * externalNormal;*/ Tensor tension(force.x, force.y, 0); Tensor rotatedTension = tension.RotateAxes(-externalNormal); values[0] = rotatedTension.xx; values[1] = rotatedTension.yy; values[2] = rotatedTension.xy; values[3] = values[4] = 0; } template <> void ElasticSystemCommon<Space3>::FreeBoundaryInfoFunctor::operator()( const Vector& globalPoint, const Vector& externalNormal, const Scalar time, Scalar* values) { Vector externalForce = (*forceFunctor)(globalPoint, externalNormal, time) / tensionDimensionlessMult; Vector tangent0 = (externalNormal ^ externalForce).GetNorm(); Vector tangent1 = (externalNormal ^ tangent0).GetNorm(); Vector force(externalForce * externalNormal, externalForce * tangent0, externalForce * tangent1); Tensor tension(force.x, force.y, force.z, 0, 0, 0); Tensor rotatedTension = tension.RotateAxes(externalNormal, tangent0, tangent1); values[0] = rotatedTension.xx; values[1] = rotatedTension.yy; values[2] = rotatedTension.zz; values[3] = rotatedTension.xy; values[4] = rotatedTension.yz; values[5] = rotatedTension.xz; values[6] = values[7] = values[8] = 0; } template <> void ElasticSystemCommon<Space2>::FixedBoundaryInfoFunctor::SetVelocity( const Vector& externalVelocity, Scalar* values) { values[3] = externalVelocity.x; values[4] = externalVelocity.y; } template <> void ElasticSystemCommon<Space3>::FixedBoundaryInfoFunctor::SetVelocity( const Vector& externalVelocity, Scalar* values) { values[6] = externalVelocity.x; values[7] = externalVelocity.y; values[8] = externalVelocity.z; }
43.223565
332
0.562941
llmontoryxd
c281d6c35e23c92207db648e10807fda97c31be8
847
hpp
C++
c++/en/dropbox/remove_sentences_effectively/remove_sentences_effectively/Args.hpp
aimldl/coding
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
[ "MIT" ]
null
null
null
c++/en/dropbox/remove_sentences_effectively/remove_sentences_effectively/Args.hpp
aimldl/coding
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
[ "MIT" ]
null
null
null
c++/en/dropbox/remove_sentences_effectively/remove_sentences_effectively/Args.hpp
aimldl/coding
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
[ "MIT" ]
null
null
null
#pragma once #include <iostream> #include <cassert> #include <string> #include "GetOpt.hpp" using namespace std; //================================================================== // Class Declaration // //================================================================== class Args // (Command Line) Arguments { public: Args(int argc, char **argv); ~Args(); bool is_word_level(); bool is_sentence_level(); bool match_filenames(); private: void process(int argc, char **argv); void show_usage(); void show_version(); void show_default_message(); string program_name; string release_date; string version_number; bool process_words; bool process_sentences; bool process_filenames; };
23.527778
69
0.493506
aimldl
c286523148f437f27158a97f03a733470c12de16
1,286
cpp
C++
binary-tree-level-order-traversal-II/main.cpp
rickytan/LeetCode
7df9a47928552babaf5d2abf1d153bd92d44be09
[ "MIT" ]
1
2015-04-04T18:32:31.000Z
2015-04-04T18:32:31.000Z
binary-tree-level-order-traversal-II/main.cpp
rickytan/LeetCode
7df9a47928552babaf5d2abf1d153bd92d44be09
[ "MIT" ]
null
null
null
binary-tree-level-order-traversal-II/main.cpp
rickytan/LeetCode
7df9a47928552babaf5d2abf1d153bd92d44be09
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <queue> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: vector<vector<int> > levelOrderBottom(TreeNode *root) { vector<vector<int>> result; if (!root) return result; queue<pair<TreeNode *, int>> treeStack; treeStack.push(make_pair(root, 0)); int count = 0; while (!treeStack.empty()) { pair<TreeNode *, int> p = treeStack.front(); treeStack.pop(); TreeNode *top = p.first; int level = p.second; if (level >= result.size()) result.push_back(vector<int>()); result[level].push_back(top->val); if (top->left) { treeStack.push(make_pair(top->left, level+1)); //result[level].push_back(top->left->val); } if (top->right) { treeStack.push(make_pair(top->right, level+1)); //result[level].push_back(top->right->val); } } std::reverse(result.begin(), result.end()); return result; } }; int main() { return 0; }
23.381818
63
0.51944
rickytan
c287b86aab29f4aa747149d64d45827da01a9cf3
470
cpp
C++
drazy/sparse_table.cpp
gbuenoandrade/Manual-da-Sarrada
dc44666b8f926428164447997b5ea8363ebd6fda
[ "MIT" ]
null
null
null
drazy/sparse_table.cpp
gbuenoandrade/Manual-da-Sarrada
dc44666b8f926428164447997b5ea8363ebd6fda
[ "MIT" ]
null
null
null
drazy/sparse_table.cpp
gbuenoandrade/Manual-da-Sarrada
dc44666b8f926428164447997b5ea8363ebd6fda
[ "MIT" ]
null
null
null
const int MAXN = 100010; const int MAX_LOG = 18; int v[MAXN]; int st[MAXN][MAX_LOG]; int logt[MAXN]; int n; void build() { logt[1] = 0; for (int i=2, val=1; i<=n; i*=2, ++val) { int lim = min(2*i, n+1); FOR(j,i,lim) { logt[j] = val; } } FOR0(j,MAX_LOG) FOR0(i,n) if(i + (1 << j) - 1 < n) { st[i][j] = (j ? min(st[i][j-1], st[i + (1 << (j-1))][j-1]): v[i]); } } int query(int l, int r) { int x = logt[r-l+1]; return min(st[l][x],st[r-(1<<x)+1][x]); }
19.583333
68
0.493617
gbuenoandrade
c29056431c86089520a9e21ee2cc507ccc5340c7
3,763
hpp
C++
src/RemotePhotoTool/TimelapseVideoOptionsDlg.hpp
vividos/RemotePhotoTool
d17ae2abbda531acbd0ec8e90ddc4856c4fdfa00
[ "BSD-2-Clause" ]
16
2015-03-26T02:32:43.000Z
2021-10-18T16:34:31.000Z
src/RemotePhotoTool/TimelapseVideoOptionsDlg.hpp
vividos/RemotePhotoTool
d17ae2abbda531acbd0ec8e90ddc4856c4fdfa00
[ "BSD-2-Clause" ]
7
2019-02-21T06:07:09.000Z
2022-01-01T10:00:50.000Z
src/RemotePhotoTool/TimelapseVideoOptionsDlg.hpp
vividos/RemotePhotoTool
d17ae2abbda531acbd0ec8e90ddc4856c4fdfa00
[ "BSD-2-Clause" ]
6
2019-05-07T09:21:15.000Z
2021-09-01T06:36:24.000Z
// // RemotePhotoTool - remote camera control software // Copyright (C) 2008-2018 Michael Fink // /// \file TimelapseVideoOptionsDlg.hpp Settings dialog // #pragma once /// \brief timelapse video options dialog /// \details shows some common ffmpeg options for selection and returns the /// resulting command line string class TimelapseVideoOptionsDlg : public CDialogImpl<TimelapseVideoOptionsDlg>, public CWinDataExchange<TimelapseVideoOptionsDlg> { public: /// ctor TimelapseVideoOptionsDlg(const CString& commandLine); /// dialog id enum { IDD = IDD_TIMELAPSE_VIDEO_OPTIONS }; /// returns complete command line text that was configured using this dialog CString GetCommandLine() const; private: BEGIN_DDX_MAP(TimelapseVideoOptionsDlg) DDX_INT(IDC_EDIT_TIMELAPSE_VIDEO_OPTIONS_FRAMERATE, m_framerate) DDX_CONTROL_HANDLE(IDC_EDIT_TIMELAPSE_VIDEO_OPTIONS_FRAMERATE, m_editFramerate) DDX_CONTROL_HANDLE(IDC_COMBO_TIMELAPSE_VIDEO_OPTIONS_FORMAT, m_comboVideoEncoding) DDX_CONTROL_HANDLE(IDC_COMBO_TIMELAPSE_VIDEO_OPTIONS_PRESET, m_comboVideoPreset) DDX_COMBO_INDEX(IDC_COMBO_TIMELAPSE_VIDEO_OPTIONS_FORMAT, m_indexVideoEncoding) DDX_COMBO_INDEX(IDC_COMBO_TIMELAPSE_VIDEO_OPTIONS_PRESET, m_indexVideoPreset) DDX_CONTROL_HANDLE(IDC_EDIT_TIMELAPSE_VIDEO_OPTIONS_EXTRA_FFMPEG_CMDLINE, m_editExtraOptions) DDX_TEXT(IDC_EDIT_TIMELAPSE_VIDEO_OPTIONS_EXTRA_FFMPEG_CMDLINE, m_extraFfmpegCmdline) DDX_TEXT(IDC_EDIT_TIMELAPSE_VIDEO_OPTIONS_COMPLETE_FFMPEG_CMDLINE, m_commandLine) END_DDX_MAP() BEGIN_MSG_MAP(TimelapseVideoOptionsDlg) MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) COMMAND_ID_HANDLER(IDOK, OnCloseCmd) COMMAND_ID_HANDLER(IDCANCEL, OnCloseCmd) COMMAND_HANDLER(IDC_EDIT_TIMELAPSE_VIDEO_OPTIONS_FRAMERATE, EN_CHANGE, OnInputControlChanged) COMMAND_HANDLER(IDC_EDIT_TIMELAPSE_VIDEO_OPTIONS_EXTRA_FFMPEG_CMDLINE, EN_CHANGE, OnInputControlChanged) COMMAND_HANDLER(IDC_COMBO_TIMELAPSE_VIDEO_OPTIONS_FORMAT, CBN_SELCHANGE, OnInputControlChanged) COMMAND_HANDLER(IDC_COMBO_TIMELAPSE_VIDEO_OPTIONS_PRESET, CBN_SELCHANGE, OnInputControlChanged) END_MSG_MAP() /// called when dialog is being shown LRESULT OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); /// called when OK or Cancel button is pressed LRESULT OnCloseCmd(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled); /// called when an input control has changed its contents LRESULT OnInputControlChanged(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled); /// returns a complete command line, from reading the current UI control contents CString GetCommandLineFromControls(); /// updates command line from UI controls void UpdateCommandLineFromControls(); /// sets UI controls from given command line void SetControlsFromCommandLine(const CString& commandLine); private: // model /// current command line string CString m_commandLine; /// contains selected framerate int m_framerate; /// contains index of currently selected video encoding option int m_indexVideoEncoding; /// contains index of currently selected video preset option int m_indexVideoPreset; /// contains extra options for the ffmpeg command line CString m_extraFfmpegCmdline; // UI /// indicates if the "change update" handler is currently running bool m_inChangeHandler; /// edit control containing the framerate CEdit m_editFramerate; /// combobox for selecting video encoding CComboBox m_comboVideoEncoding; /// combobox for selecting video preset CComboBox m_comboVideoPreset; /// edit control containing the extra options CEdit m_editExtraOptions; };
36.892157
110
0.790858
vividos
c29342e635ddbd340f8dc0c7cfdd7f46193c695e
342
hpp
C++
phase_1/eval/york/challenge/src/http/empty_response.hpp
cromulencellc/chess-aces
7780e29de1991758078816ca501ff79a2586b8c2
[ "MIT" ]
null
null
null
phase_1/eval/york/challenge/src/http/empty_response.hpp
cromulencellc/chess-aces
7780e29de1991758078816ca501ff79a2586b8c2
[ "MIT" ]
null
null
null
phase_1/eval/york/challenge/src/http/empty_response.hpp
cromulencellc/chess-aces
7780e29de1991758078816ca501ff79a2586b8c2
[ "MIT" ]
null
null
null
#pragma once #include "response.hpp" namespace http { class EmptyResponse : public Response { public: EmptyResponse() {}; virtual ~EmptyResponse() {}; bool has_countable_body_size() const override { return true; } int body_size() override { return 0; } void stream_body_to(int _out_fd) override { return; } }; }
20.117647
66
0.675439
cromulencellc
c296ab4e3067513df354a6fc03342dea09095dcc
5,705
cc
C++
RecoTauTag/RecoTau/src/PFRecoTauTagInfoAlgorithm.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
RecoTauTag/RecoTau/src/PFRecoTauTagInfoAlgorithm.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
RecoTauTag/RecoTau/src/PFRecoTauTagInfoAlgorithm.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include "RecoTauTag/RecoTau/interface/PFRecoTauTagInfoAlgorithm.h" #include "DataFormats/Math/interface/deltaR.h" #include "RecoTauTag/RecoTau/interface/TauTagTools.h" using namespace reco; PFRecoTauTagInfoAlgorithm::PFRecoTauTagInfoAlgorithm(const edm::ParameterSet& parameters) { // parameters of the considered charged hadr. PFCandidates, based on their rec. tk properties : ChargedHadronsAssociationCone_ = parameters.getParameter<double>("ChargedHadrCand_AssociationCone"); ChargedHadrCand_tkminPt_ = parameters.getParameter<double>("ChargedHadrCand_tkminPt"); ChargedHadrCand_tkminPixelHitsn_ = parameters.getParameter<int>("ChargedHadrCand_tkminPixelHitsn"); ChargedHadrCand_tkminTrackerHitsn_ = parameters.getParameter<int>("ChargedHadrCand_tkminTrackerHitsn"); ChargedHadrCand_tkmaxipt_ = parameters.getParameter<double>("ChargedHadrCand_tkmaxipt"); ChargedHadrCand_tkmaxChi2_ = parameters.getParameter<double>("ChargedHadrCand_tkmaxChi2"); // parameters of the considered neutral hadr. PFCandidates, based on their rec. HCAL clus. properties : NeutrHadrCand_HcalclusMinEt_ = parameters.getParameter<double>("NeutrHadrCand_HcalclusMinEt"); // parameters of the considered gamma PFCandidates, based on their rec. ECAL clus. properties : GammaCand_EcalclusMinEt_ = parameters.getParameter<double>("GammaCand_EcalclusMinEt"); // parameters of the considered rec. Tracks (these ones catched through a JetTracksAssociation object, not through the charged hadr. PFCandidates inside the PFJet ; the motivation for considering them is the need for checking that a selection by the charged hadr. PFCandidates is equivalent to a selection by the rec. Tracks.) : tkminPt_ = parameters.getParameter<double>("tkminPt"); tkminPixelHitsn_ = parameters.getParameter<int>("tkminPixelHitsn"); tkminTrackerHitsn_ = parameters.getParameter<int>("tkminTrackerHitsn"); tkmaxipt_ = parameters.getParameter<double>("tkmaxipt"); tkmaxChi2_ = parameters.getParameter<double>("tkmaxChi2"); // UsePVconstraint_ = parameters.getParameter<bool>("UsePVconstraint"); ChargedHadrCand_tkPVmaxDZ_ = parameters.getParameter<double>("ChargedHadrCand_tkPVmaxDZ"); tkPVmaxDZ_ = parameters.getParameter<double>("tkPVmaxDZ"); } PFTauTagInfo PFRecoTauTagInfoAlgorithm::buildPFTauTagInfo(const JetBaseRef& thePFJet, const std::vector<reco::CandidatePtr>& thePFCandsInEvent, const TrackRefVector& theTracks, const Vertex& thePV) const { PFTauTagInfo resultExtended; resultExtended.setpfjetRef(thePFJet); std::vector<reco::CandidatePtr> thePFCands; const float jetPhi = (*thePFJet).phi(); const float jetEta = (*thePFJet).eta(); auto dr2 = [jetPhi, jetEta](float phi, float eta) { return reco::deltaR2(jetEta, jetPhi, eta, phi); }; for (const auto& iPFCand : thePFCandsInEvent) { float delta = dr2((*iPFCand).phi(), (*iPFCand).eta()); if (delta < ChargedHadronsAssociationCone_ * ChargedHadronsAssociationCone_) thePFCands.push_back(iPFCand); } bool pvIsFake = (thePV.z() < -500.); std::vector<reco::CandidatePtr> theFilteredPFChargedHadrCands; if (UsePVconstraint_ && !pvIsFake) { theFilteredPFChargedHadrCands = tautagtools::filteredPFChargedHadrCands(thePFCands, ChargedHadrCand_tkminPt_, ChargedHadrCand_tkminPixelHitsn_, ChargedHadrCand_tkminTrackerHitsn_, ChargedHadrCand_tkmaxipt_, ChargedHadrCand_tkmaxChi2_, ChargedHadrCand_tkPVmaxDZ_, thePV, thePV.z()); } else { theFilteredPFChargedHadrCands = tautagtools::filteredPFChargedHadrCands(thePFCands, ChargedHadrCand_tkminPt_, ChargedHadrCand_tkminPixelHitsn_, ChargedHadrCand_tkminTrackerHitsn_, ChargedHadrCand_tkmaxipt_, ChargedHadrCand_tkmaxChi2_, thePV); } resultExtended.setPFChargedHadrCands(theFilteredPFChargedHadrCands); resultExtended.setPFNeutrHadrCands(tautagtools::filteredPFNeutrHadrCands(thePFCands, NeutrHadrCand_HcalclusMinEt_)); resultExtended.setPFGammaCands(tautagtools::filteredPFGammaCands(thePFCands, GammaCand_EcalclusMinEt_)); TrackRefVector theFilteredTracks; if (UsePVconstraint_ && !pvIsFake) { theFilteredTracks = tautagtools::filteredTracks( theTracks, tkminPt_, tkminPixelHitsn_, tkminTrackerHitsn_, tkmaxipt_, tkmaxChi2_, tkPVmaxDZ_, thePV, thePV.z()); } else { theFilteredTracks = tautagtools::filteredTracks( theTracks, tkminPt_, tkminPixelHitsn_, tkminTrackerHitsn_, tkmaxipt_, tkmaxChi2_, thePV); } resultExtended.setTracks(theFilteredTracks); return resultExtended; }
66.337209
330
0.6305
ckamtsikis
c298ba2ea7469e032a9c6e9566796468f41872bb
2,151
cpp
C++
src/app/clusters/power-source-server/power-source-server.cpp
hnnajh/connectedhomeip
249a6c65a820c711d23135d38eec0ab288d3f38f
[ "Apache-2.0" ]
null
null
null
src/app/clusters/power-source-server/power-source-server.cpp
hnnajh/connectedhomeip
249a6c65a820c711d23135d38eec0ab288d3f38f
[ "Apache-2.0" ]
null
null
null
src/app/clusters/power-source-server/power-source-server.cpp
hnnajh/connectedhomeip
249a6c65a820c711d23135d38eec0ab288d3f38f
[ "Apache-2.0" ]
null
null
null
/** * * Copyright (c) 2020 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * * Copyright (c) 2020 Silicon Labs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance 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 "power-source-server.h" #include <app/CommandHandler.h> #include <app/reporting/reporting.h> #include <app/util/af-event.h> #include <app/util/af-types.h> #include <app/util/af.h> #include <app/util/attribute-storage.h> #include <lib/support/TypeTraits.h> #include <string.h> using namespace chip; #ifndef emberAfPowerSourceClusterPrintln #define emberAfPowerSourceClusterPrintln(...) ChipLogProgress(Zcl, __VA_ARGS__); #endif //------------------------------------------------------------------------------ // Callbacks //------------------------------------------------------------------------------ /** @brief Power Source Cluster Init * * Cluster Init * * @param endpoint Endpoint that is being initialized */ void emberAfPowerSourceClusterInitCallback(chip::EndpointId endpoint) { emberAfPowerSourceClusterPrintln("Power Source Cluster init"); }
32.590909
80
0.666202
hnnajh
c29906300bed592b7d0f6125beabc3e161352bfc
1,345
cxx
C++
Packages/java/nio/file/LinkOption.cxx
Brandon-T/Aries
4e8c4f5454e8c7c5cd0611b1b38b5be8186f86ca
[ "MIT" ]
null
null
null
Packages/java/nio/file/LinkOption.cxx
Brandon-T/Aries
4e8c4f5454e8c7c5cd0611b1b38b5be8186f86ca
[ "MIT" ]
null
null
null
Packages/java/nio/file/LinkOption.cxx
Brandon-T/Aries
4e8c4f5454e8c7c5cd0611b1b38b5be8186f86ca
[ "MIT" ]
null
null
null
// // LinkOption.cxx // Aries // // Created by Brandon on 2018-02-25. // Copyright © 2018 Brandon. All rights reserved. // #include "LinkOption.hxx" #include "Enum.hxx" #include "String.hxx" using java::nio::file::LinkOption; using java::lang::Enum; using java::lang::String; LinkOption::LinkOption(JVM* vm, jobject instance) : Enum() { if (vm && instance) { this->vm = vm; this->cls = JVMRef<jclass>(this->vm, this->vm->FindClass("Ljava/nio/file/LinkOption;")); this->inst = JVMRef<jobject>(this->vm, instance); } } LinkOption LinkOption::valueOf(JVM* vm, String value) { static JVMRef<jclass> cls = JVMRef<jclass>(vm, vm->FindClass("Ljava/nio/file/LinkOption;")); static jmethodID valueOfMethod = vm->GetStaticMethodID(cls.get(), "valueOf", "(Ljava/lang/String;)Ljava/nio/file/LinkOption;"); return LinkOption(vm, vm->CallStaticObjectMethod(cls.get(), valueOfMethod, value.ref().get())); } Array<LinkOption> LinkOption::values(JVM* vm) { static JVMRef<jclass> cls = JVMRef<jclass>(vm, vm->FindClass("Ljava/nio/file/LinkOption;")); static jmethodID valuesMethod = vm->GetStaticMethodID(cls.get(), "values", "()[Ljava/nio/file/LinkOption;"); jarray arr = reinterpret_cast<jarray>(vm->CallStaticObjectMethod(cls.get(), valuesMethod)); return Array<LinkOption>(vm, arr); }
32.02381
131
0.681784
Brandon-T
c2994debdd0e9f785619897ea07406601e14677b
6,276
hh
C++
nox/src/include/expr.hh
ayjazz/OESS
deadc504d287febc7cbd7251ddb102bb5c8b1f04
[ "Apache-2.0" ]
28
2015-02-04T13:59:25.000Z
2021-12-29T03:44:47.000Z
nox/src/include/expr.hh
ayjazz/OESS
deadc504d287febc7cbd7251ddb102bb5c8b1f04
[ "Apache-2.0" ]
552
2015-01-05T18:25:54.000Z
2022-03-16T18:51:13.000Z
nox/src/include/expr.hh
ayjazz/OESS
deadc504d287febc7cbd7251ddb102bb5c8b1f04
[ "Apache-2.0" ]
25
2015-02-04T18:48:20.000Z
2020-06-18T15:51:05.000Z
/* Copyright 2008 (C) Nicira, Inc. * * This file is part of NOX. * * NOX is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NOX is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NOX. If not, see <http://www.gnu.org/licenses/>. */ #ifndef PACKET_EXPR_HH #define PACKET_EXPR_HH #include <string> #include <stdint.h> #include "cnode.hh" #include "cnode-result.hh" /* * Example implementation of the Expr model used by Classifier, Cnode, * Cnode_result, and Rule. * * An Expr describes the set of packets a given rule should be applied to. How * an expression class chooses to describe these sets is completely up to the * implementation. However, to utilize the general classification mechanism * encoded in the Cnode structure, an Expr should expose the following * interface. * * Overview: * * An Expr should define a constant 'NUM_FIELDS' equal to the number of * different fields it would like the Cnode tree to attempt to split rules of * its type on. Note that an Expr can be defined over additional fields that * it would not like Cnode to split on, it should just not include these fields * in the 'NUM_FIELDS' constant. Cnode represents each of the 'NUM_FIELDS' * fields by an integer value less than 'NUM_FIELDS' and greater than or equal * to zero. An Expr can be wildcarded on any number of these fields (i.e. the * Expr allows 'any' value on the field). A path in Cnode is then denoted by a * bit mask in which the ith bit is on if and only if field i has been split * on. * * The required constants and methods needed to be implemented by an Expr in * order to be used in a Cnode tree are described below. */ namespace vigil { class Flow; class Packet_expr { public: /*************************** BEGIN REQUIRED INTERFACE *************************/ /* Constants */ static const uint32_t NUM_FIELDS = 13; // num fields that can be split // on by Cnode static const uint32_t LEAF_THRESHOLD = 1; // min num rules that should be // saved by a split for it to be // worth the hash cost. /* * Returns 'true' if the expr is wildcarded on 'field', else 'false'. */ bool is_wildcard(uint32_t field) const; /* * Returns 'true' if the expr, having already been split on all fields * denoted by 'path', could potentially be split on any other fields. * Needed in order to avoid copying rules to a node's children when it is * known in advance that the rule will apply to all possible descendents. * Returns 'false' if no further splits can be made (i.e. expr is * wildcarded on all fields that have yet to be split on). */ bool splittable(uint32_t path) const; /* * Sets the memory pointed to by 'value' equal to the expression's value * for 'field'. Returns 'false' if 'value' has not been set (i.e. when * expr is wildcarded on 'field'), else returns 'true'. Should set any of * the MAX_FIELD_LEN * 4 bytes in 'value' not used by 'field' to 0. */ bool get_field(uint32_t field, uint32_t& value) const; /**************************** END REQUIRED INTERFACE **************************/ Packet_expr() : wildcards(~0) { } ~Packet_expr() { } enum Expr_field { AP_SRC, AP_DST, DL_VLAN, DL_VLAN_PCP, DL_TYPE, DL_SRC, DL_DST, NW_SRC, NW_DST, NW_PROTO, TP_SRC, TP_DST, GROUP_SRC, GROUP_DST, }; static const int MAX_FIELD_LEN = 2; void set_field(Expr_field, const uint32_t [MAX_FIELD_LEN]); void print() const; void print(uint32_t) const; const std::string to_string() const; const std::string to_string(uint32_t field) const; uint16_t ap_src; uint16_t ap_dst; //how have data during classification uint16_t dl_vlan; uint16_t dl_vlan_pcp; uint16_t dl_proto; uint8_t dl_src[6]; uint8_t dl_dst[6]; uint32_t nw_src; uint32_t nw_dst; uint16_t tp_src; uint16_t tp_dst; uint32_t group_src; uint32_t group_dst; uint32_t wildcards; uint8_t nw_proto; }; /* * This function should be defined for every Data type that * Classifier::traverse might get called on. This example Expr assumes it * will get called on either a Flow or another Packet_expr. Sets the * memory pointed to by 'value' equal to the data's value for 'field' where * 'field' is one of the above-described single-bit masks. Returns 'true' * if 'value' was set, else 'false' (e.g. when the data does not have a * value for 'field'. Should set any of the MAX_FIELD_LEN * 4 bytes in * 'value' not used by 'field' equal to '0'. */ template <> bool get_field<Packet_expr, Flow>(uint32_t field, const Flow& flow, uint32_t idx, uint32_t& value); template <> bool get_field<Packet_expr, Packet_expr>(uint32_t field, const Packet_expr& expr, uint32_t idx, uint32_t& value); /* * This function should be defined for every Data type that * Classifier::traverse might get called on. It is used by Cnode_result to * iterate through only the valid rules. This example Expr assumes it will * get called on either a Flow or another Packet_expr. Returns * 'true' if the expr matches the packet argument. This is where the expr * can check for fields that the Cnode tree either has not or cannot * split on. Returns 'false' if the expr does not match the argument. */ template <> bool matches(uint32_t rule_id, const Packet_expr&, const Flow&); template <> bool matches(uint32_t rule_id, const Packet_expr&, const Packet_expr&); } // namespace vigil #endif
33.031579
80
0.663161
ayjazz
c2995fa5f6b0b17693dffa2e5d7303634e3b6922
1,285
cpp
C++
reading_raw_data_alsa_library.cpp
harasstheworld/network-programming
f99a8ca2e5f5aa88268ec6ac07290262e84d8b15
[ "MIT" ]
1
2022-03-25T05:41:46.000Z
2022-03-25T05:41:46.000Z
reading_raw_data_alsa_library.cpp
harasstheworld/network-programming
f99a8ca2e5f5aa88268ec6ac07290262e84d8b15
[ "MIT" ]
null
null
null
reading_raw_data_alsa_library.cpp
harasstheworld/network-programming
f99a8ca2e5f5aa88268ec6ac07290262e84d8b15
[ "MIT" ]
null
null
null
/*This program demonstrates how to read in a raw data file and write it to the sound device to be played. The program uses the ALSA library. Use option -lasound on compile line.*/ #include </usr/include/alsa/asoundlib.h> #include <math.h> #include <iostream> using namespace std; static char *device = "default"; /*default playback device */ int main(int argc, char* argv[]) { int err, numSamples; snd_pcm_t *handle; snd_pcm_sframes_t frames; numSamples = atoi(argv[1]); char* samples = (char*) malloc((size_t) numSamples); FILE *inFile = fopen(argv[2], "rb"); int numRead = fread(samples, 1, numSamples, inFile); fclose(inFile); if ((err=snd_pcm_open(&handle, device, SND_PCM_STREAM_PLAYBACK, 0)) < 0){ printf("Playback open error: %s\n", snd_strerror(err)); exit(EXIT_FAILURE); } if ((err = snd_pcm_set_params(handle,SND_PCM_FORMAT_U8, SND_PCM_ACCESS_RW_INTERLEAVED,1,44100, 1, 100000) ) < 0 ){ printf("Playback open error: %s\n", snd_strerror(err)); exit(EXIT_FAILURE); } frames = snd_pcm_writei(handle, samples, numSamples); if (frames < 0) frames = snd_pcm_recover(handle, frames, 0); if (frames < 0) { printf("snd_pcm_writei failed: %s\n", snd_strerror(err)); } snd_pcm_close(handle); return 0; }
31.341463
73
0.686381
harasstheworld
c29ba5e146d7cb6631d92e38d91bbb259dbb2a40
523
cc
C++
src/main.cc
milesdiprata/conga-minimax-alpha-beta
0080bc62a71efd77ed499c6bd605f4120ccee73a
[ "MIT" ]
null
null
null
src/main.cc
milesdiprata/conga-minimax-alpha-beta
0080bc62a71efd77ed499c6bd605f4120ccee73a
[ "MIT" ]
null
null
null
src/main.cc
milesdiprata/conga-minimax-alpha-beta
0080bc62a71efd77ed499c6bd605f4120ccee73a
[ "MIT" ]
null
null
null
#include <memory> #include "conga/board.h" #include "conga/game.h" #include "conga/minimax_agent.h" #include "conga/random_agent.h" #include "conga/stone.h" int main(const int argc, const char* const argv[]) { auto game = conga::Game( std::make_unique<conga::Board>(), std::make_unique<conga::MinimaxAgent>( conga::Stone::kBlack, conga::MinimaxAgent::Evaluation::kPlayerMinusOpponentMoves), std::make_unique<conga::RandomAgent>(conga::Stone::kWhite)); game.Play(); return 0; }
27.526316
70
0.678776
milesdiprata
c2a071902edecdb9f32d1b872e898c94677a62a6
4,417
cpp
C++
exampleTranslators/graphicalUserInterfaceExamples/query/query.cpp
ouankou/rose
76f2a004bd6d8036bc24be2c566a14e33ba4f825
[ "BSD-3-Clause" ]
488
2015-01-09T08:54:48.000Z
2022-03-30T07:15:46.000Z
exampleTranslators/graphicalUserInterfaceExamples/query/query.cpp
WildeGeist/rose
17db6454e8baba0014e30a8ec23df1a11ac55a0c
[ "BSD-3-Clause" ]
174
2015-01-28T18:41:32.000Z
2022-03-31T16:51:05.000Z
exampleTranslators/graphicalUserInterfaceExamples/query/query.cpp
WildeGeist/rose
17db6454e8baba0014e30a8ec23df1a11ac55a0c
[ "BSD-3-Clause" ]
146
2015-04-27T02:48:34.000Z
2022-03-04T07:32:53.000Z
#include <rose.h> #include <config.h> #include <qrose.h> class QueryCollection { public: bool findPublicVarMembers (SgNode *node, string &str) { SgVariableDeclaration *decl; if (decl = isSgVariableDeclaration(node)) { SgDeclarationModifier &dfm = decl->get_declarationModifier(); if (dfm.get_accessModifier().isPublic()) { // check if it belongs to a class SgStatement *block = ((SgVariableDeclaration *) node)->get_scope(); SgClassDefinition *classDef; if (classDef = isSgClassDefinition(block)) { if (classDef->get_declaration()->get_class_type() == SgClassDeclaration::e_class) { str = classDef->get_qualified_name().getString(); return true; } } } } return false; } bool findCallsWithFuncArgs(SgNode *node, string &str) { SgExprStatement *statement; if (statement = isSgExprStatement(node)) { SgFunctionCallExp *call_exp; if (call_exp = isSgFunctionCallExp(statement->get_the_expr())) { m_nodes.clear(); m_nodes.insert(call_exp); m_domain.expand(&m_nodes, QRQueryDomain::all_children); m_domain.getNodes()->erase(call_exp); NodeQuery::VariantVector vector(V_SgFunctionCallExp); QRQueryOpVariant op(vector); op.performQuery(&m_domain, &m_range); unsigned hits = m_range.countRange(); if (hits) { sprintf(m_buffer, "%d", hits); str = m_buffer; return true; } } } return false; } bool findCallsWithFuncArgs2(SgNode *node, string &str) { SgExprStatement *statement; if (statement = isSgExprStatement(node)) { SgFunctionCallExp *call_exp; if (call_exp = isSgFunctionCallExp(statement->get_the_expr())) { m_nodes.clear(); m_nodes.insert(call_exp); m_domain.expand(&m_nodes, QRQueryDomain::all_children); m_domain.getNodes()->erase(call_exp); NodeQuery::VariantVector vector (V_SgFunctionCallExp); QRQueryOpVariant op(vector); op.performQuery(&m_domain, &m_range); unsigned hits = m_range.countRange(); if (hits) { set<SgNode *> *rnodes = m_range.getNodes(); for (set<SgNode *>::iterator iter = rnodes->begin(); iter != rnodes->end(); ) { SgFunctionCallExp *exp = (SgFunctionCallExp *) *iter; iter++; SgExpression *funcexpr = exp->get_function(); str += funcexpr->unparseToString(); if (iter != rnodes->end()) { str += ", "; } } return true; } } } return false; } protected: QRQueryDomain m_domain; QRQueryRange m_range; set<SgNode *> m_nodes; char m_buffer[10]; }; int main(int argc, char **argv) { // DQ (4/6/2017): This will not fail if we skip calling ROSE_INITIALIZE (but // any warning message using the message looging feature in ROSE will fail). ROSE_INITIALIZE; SgProject *project = frontend(argc, argv); QRGUI::init(argc, argv, project); QRQueryBox *query = new QRQueryBox(); query->insertVariantQuery("Loops", NodeQuery::VariantVector(V_SgDoWhileStmt) + NodeQuery::VariantVector(V_SgForStatement) + NodeQuery::VariantVector(V_SgWhileStmt)); query->insertVariantQuery("Function Declarations", NodeQuery::VariantVector(V_SgFunctionDeclaration)); query->insertCustomQuery<QueryCollection>("find public variable members", &QueryCollection::findPublicVarMembers); query->insertCustomQuery<QueryCollection>("find calls with function arguments I", &QueryCollection::findCallsWithFuncArgs); query->insertCustomQuery<QueryCollection>("find calls with function arguments II", &QueryCollection::findCallsWithFuncArgs2); new QRCodeBox(); // new QRTreeBox(); QRGUI::dialog()->setGeometry(0,0,1000,1000); QRGUI::dialog()->sizes(50); QRGUI::exec(); }
36.504132
129
0.576862
ouankou
c2a0b4f4ae9da49cac70b9b5302a50ed78ad8584
5,361
cpp
C++
src/storage/wasmrun.cpp
metabasenet/metabasenet
e9bc89b22c11981bcf1d71b63b9b66df3a4e54e1
[ "MIT" ]
null
null
null
src/storage/wasmrun.cpp
metabasenet/metabasenet
e9bc89b22c11981bcf1d71b63b9b66df3a4e54e1
[ "MIT" ]
null
null
null
src/storage/wasmrun.cpp
metabasenet/metabasenet
e9bc89b22c11981bcf1d71b63b9b66df3a4e54e1
[ "MIT" ]
null
null
null
// Copyright (c) 2021-2022 The MetabaseNet developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "wasmrun.h" #include <evmc/evmc.hpp> #include <evmc/loader.h> #include "block.h" #include "wasmhost.h" using namespace std; using namespace hcode; namespace metabasenet { namespace storage { ////////////////////////////// // CWasmRun bool CWasmRun::RunWasm(const uint256& from, const uint256& to, const uint256& hashWasmDest, const CDestination& destCodeOwner, const uint64 nTxGasLimit, const uint256& nGasPrice, const uint256& nTxAmount, const uint256& hashBlockMintDest, const uint32 nBlockTimestamp, const int nBlockHeight, const uint64 nBlockGasLimit, const bytes& btWasmCode, const bytes& btRunParam, const CTxContractData& txcd) { evmc::address sender; memcpy(sender.bytes, from.begin(), min(sizeof(sender.bytes), (size_t)(from.size()))); evmc_tx_context c; memcpy(c.tx_gas_price.bytes, nGasPrice.begin(), min(sizeof(c.tx_gas_price.bytes), (size_t)(nGasPrice.size()))); c.tx_origin = sender; memcpy(c.block_coinbase.bytes, hashBlockMintDest.begin(), min(sizeof(c.block_coinbase.bytes), (size_t)(hashBlockMintDest.size()))); c.block_timestamp = nBlockTimestamp; c.block_number = nBlockHeight; c.block_gas_limit = nBlockGasLimit; memcpy(c.block_difficulty.bytes, hashFork.begin(), min(sizeof(c.block_difficulty.bytes), (size_t)(hashFork.size()))); memcpy(c.chain_id.bytes, hashFork.begin(), min(sizeof(c.chain_id.bytes), (size_t)(hashFork.size()))); shared_ptr<CWasmHost> host(new CWasmHost(c, dbHost)); evmc_host_context* context = host->to_context(); const evmc_host_interface* host_interface = &evmc::Host::get_interface(); evmc::address destination; memcpy(destination.bytes, hashWasmDest.begin(), min(sizeof(destination.bytes), (size_t)(hashWasmDest.size()))); evmc::uint256be amount; memcpy(amount.bytes, nTxAmount.begin(), min(sizeof(amount.bytes), (size_t)(nTxAmount.size()))); //StdLog("CWasmRun", "Run Wasm: nTxAmount: %s", nTxAmount.GetHex().c_str()); evmc_message msg{ EVMC_CALL, 0, // flags; 0, // The call depth; nTxGasLimit, destination, sender, btRunParam.data(), btRunParam.size(), amount, {} }; struct evmc_vm* vm = evmc_load_and_create(); StdLog("CWasmRun", "Run Wasm: execute prev: gas: %ld", msg.gas); evmc_result result = vm->execute(vm, host_interface, context, EVMC_MAX_REVISION, &msg, btWasmCode.data(), btWasmCode.size()); StdLog("CWasmRun", "Run Wasm: execute last: gas: %ld, gas_left: %ld, gas used: %ld, owner: %s", msg.gas, result.gas_left, msg.gas - result.gas_left, destCodeOwner.ToString().c_str()); dbHost.SaveGasUsed(destCodeOwner, msg.gas - result.gas_left); if (result.status_code == EVMC_SUCCESS) { StdLog("CWasmRun", "Run Wasm: Run wasm success, gas left: %ld, gas used: %ld, to: %s", result.gas_left, nTxGasLimit - result.gas_left, to.ToString().c_str()); nStatusCode = result.status_code; vResult.assign(result.output_data, result.output_data + result.output_size); for (auto it = host->cacheKv.begin(); it != host->cacheKv.end(); ++it) { mapCacheKv.insert(make_pair(it->first, bytes(&(it->second.bytes[0]), &(it->second.bytes[0]) + sizeof(it->second.bytes)))); } nGasLeft = result.gas_left; for (size_t i = 0; i < sizeof(host->logAddr.bytes); i++) { if (host->logAddr.bytes[i] != 0) { logs.address.assign(&(host->logAddr.bytes[0]), &(host->logAddr.bytes[0]) + sizeof(host->logAddr.bytes)); break; } } logs.data = host->vLogData; for (auto& vd : host->vLogTopics) { bytes btTopics; btTopics.assign(&(vd.bytes[0]), &(vd.bytes[0]) + sizeof(vd.bytes)); logs.topics.push_back(btTopics); } if (result.release) { result.release(&result); } if (to == 0) { if (!dbHost.SaveWasmRunCode(hashWasmDest, vResult, txcd)) { StdLog("CWasmRun", "Run Wasm: Save wasm run code fail, hashWasmDest: %s, hashWasmCreateCode: %s, to: %s", hashWasmDest.ToString().c_str(), txcd.GetWasmCreateCodeHash().ToString().c_str(), to.ToString().c_str()); nStatusCode = EVMC_INTERNAL_ERROR; vResult.clear(); return false; } } dbHost.SaveRunResult(hashWasmDest, logs, mapCacheKv); return true; } StdLog("CWasmRun", "Run Wasm: Run wasm fail, status code: %ld, gas left: %ld, gas used: %ld, to: %s", result.status_code, result.gas_left, nTxGasLimit - result.gas_left, to.ToString().c_str()); nStatusCode = result.status_code; nGasLeft = result.gas_left; if (result.release) { result.release(&result); } return false; } } // namespace storage } // namespace metabasenet
39.711111
154
0.613878
metabasenet
c2a1a601d04b8827eb1f6fb63754da2fe734d2f9
5,196
hpp
C++
include/hipipe/core/stream/rebatch.hpp
iterait/hipipe
c2a6cc13857dce93e5ae3f76a86e8f029ca3f921
[ "BSL-1.0", "MIT" ]
16
2018-10-08T09:00:14.000Z
2021-07-11T12:35:09.000Z
include/hipipe/core/stream/rebatch.hpp
iterait/hipipe
c2a6cc13857dce93e5ae3f76a86e8f029ca3f921
[ "BSL-1.0", "MIT" ]
19
2018-09-26T13:55:40.000Z
2019-08-28T13:47:04.000Z
include/hipipe/core/stream/rebatch.hpp
iterait/hipipe
c2a6cc13857dce93e5ae3f76a86e8f029ca3f921
[ "BSL-1.0", "MIT" ]
null
null
null
/**************************************************************************** * hipipe library * Copyright (c) 2017, Cognexa Solutions s.r.o. * Copyright (c) 2018, Iterait a.s. * Author(s) Filip Matzner * * This file is distributed under the MIT License. * See the accompanying file LICENSE.txt for the complete license agreement. ****************************************************************************/ #pragma once #include <hipipe/core/stream/stream_t.hpp> #include <range/v3/core.hpp> #include <range/v3/functional/bind_back.hpp> #include <range/v3/view/all.hpp> #include <range/v3/view/view.hpp> #include <algorithm> namespace hipipe::stream { namespace rg = ranges; namespace rgv = ranges::views; template <typename Rng> struct rebatch_view : rg::view_facade<rebatch_view<Rng>> { private: /// \cond friend rg::range_access; /// \endcond Rng rng_; std::size_t n_; struct cursor { private: rebatch_view<Rng>* rng_ = nullptr; rg::iterator_t<Rng> it_ = {}; // the batch into which we accumulate the data // the batch will be a pointer to allow moving from it in const functions std::shared_ptr<batch_t> batch_; // the subbatch of the original range std::shared_ptr<batch_t> subbatch_; // whether the underlying range is at the end of iteration bool done_ = false; // find the first non-empty subbatch and return if successful bool find_next() { while (subbatch_->batch_size() == 0) { if (it_ == rg::end(rng_->rng_) || ++it_ == rg::end(rng_->rng_)) { return false; } subbatch_ = std::make_shared<batch_t>(*it_); } return true; } // fill the batch_ with the elements from the current subbatch_ void fill_batch() { do { assert(batch_->batch_size() < rng_->n_); std::size_t to_take = std::min(rng_->n_ - batch_->batch_size(), subbatch_->batch_size()); batch_->push_back(subbatch_->take(to_take)); } while (batch_->batch_size() < rng_->n_ && find_next()); } public: using single_pass = std::true_type; cursor() = default; explicit cursor(rebatch_view<Rng>& rng) : rng_{&rng} , it_{rg::begin(rng_->rng_)} { // do nothing if the subrange is empty if (it_ == rg::end(rng_->rng_)) { done_ = true; } else { subbatch_ = std::make_shared<batch_t>(*it_); next(); } } batch_t&& read() const { return std::move(*batch_); } bool equal(rg::default_sentinel_t) const { return done_; } bool equal(const cursor& that) const { assert(rng_ == that.rng_); return it_ == that.it_ && subbatch_->batch_size() == that.subbatch_->batch_size(); } void next() { batch_ = std::make_shared<batch_t>(); if (find_next()) fill_batch(); else done_ = true; } }; // struct cursor cursor begin_cursor() { return cursor{*this}; } public: rebatch_view() = default; rebatch_view(Rng rng, std::size_t n) : rng_{rng} , n_{n} { if (n_ <= 0) { throw std::invalid_argument{"hipipe::stream::rebatch:" " The new batch size " + std::to_string(n_) + " is not strictly positive."}; } } }; // class rebatch_view class rebatch_fn { public: CPP_template(class Rng)(requires rg::input_range<Rng>) rebatch_view<rgv::all_t<Rng>> operator()(Rng&& rng, std::size_t n) const { return {rgv::all(std::forward<Rng>(rng)), n}; } auto operator()(std::size_t n) const { return rg::make_view_closure(rg::bind_back(rebatch_fn{}, n)); } }; // class rebatch_fn /// \ingroup Stream /// \brief Accumulate the stream and yield batches of a different size. /// /// The batch size of the accumulated columns is allowed to differ between batches. /// To make one large batch of all the data, use std::numeric_limits<std::size_t>::max(). /// /// Note that this stream transformer is not lazy and instead _eagerly evaluates_ /// the batches computed by the previous stream pipeline and reorganizes the /// evaluated data to batches of a different size. To avoid recalculation of the /// entire stream whenever e.g., std::distance is called, this transformer /// intentionally changes the stream type to input_range. The downside is that no /// further transformations or buffering can be appended and everything has to be /// prepared before the application of this transformer. /// /// \code /// HIPIPE_DEFINE_COLUMN(value, int) /// auto rng = views::iota(0, 10) /// | create<value>(2) // batches the data by two examples /// | rebatch(3); // changes the batch size to three examples /// \endcode inline rgv::view_closure<rebatch_fn> rebatch{}; } // namespace hipipe::stream
30.745562
94
0.572171
iterait
c2a31b8ed1ae65367c9af6077c84ca9fe8f1d39c
1,455
cpp
C++
cpp/src/Exceptions/Except.cpp
enea-scaccabarozzi/Image_to_ascii
7cb4aeb168321f23a22cc1340900f40807fb74cc
[ "MIT" ]
null
null
null
cpp/src/Exceptions/Except.cpp
enea-scaccabarozzi/Image_to_ascii
7cb4aeb168321f23a22cc1340900f40807fb74cc
[ "MIT" ]
null
null
null
cpp/src/Exceptions/Except.cpp
enea-scaccabarozzi/Image_to_ascii
7cb4aeb168321f23a22cc1340900f40807fb74cc
[ "MIT" ]
null
null
null
/** </src/Exceptions/Except.cpp> * * Written by Enea Scaccabarozzi * In date 2022-03-09 * * @description: This file rapresent the definition * of the custom Exception class for this project * * @declaration: See declarations for this file at * </src/Exceptions/Except.h> * */ #include "Except.h" using IMAGE_ASCII::EXCEPTIONS::Except; /** Constructor (C++ STL string, C++ STL string, C++ STL string, int). * * @param msg The error message * @param file File that throw exception * @param func Function that throw exception * @param line Line's number that throw exception * */ Except::Except(const string &msg, const string &file, const string &func, int line) { _info = (msg); _file = (file); _func = (func); _line = line; _what = ""; } /** Destructor. * * @description: Virtual to allow for subclassing. * */ Except::~Except() noexcept { } /** Member function what(). * * @description: Returns a pointer to the (constant) error description, * comprensive of all error's data available * * @return: A pointer to a const char*. * The underlying memory is in possession of the Except * object. Callers must not attempt to free the memory. * */ const char* Except::what() noexcept { _what = "\t[INFO]: " + _info + "\n" + _what += "\t[IN FILE]: " + _file + "\n"; _what += "\t[IN FUNCTION]: " + _func + "\n"; _what += "\t[AT LINE]: " + std::to_string(_line) + "\n"; return _what.c_str(); }
23.467742
83
0.645361
enea-scaccabarozzi