blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
sequencelengths
1
1
author
stringlengths
0
119
3b9b1332878914cd0f4e98fdd0e045c1fcae691c
00e69a7bc07b52878fbc43679f83dac715b5c7a9
/leetcode_solved/[editing]leetcode_1154_Day_of_the_Year.cpp
21f4d16891d4e37d4cfc4090cf7916dee3db55c8
[]
no_license
Ghost-2019/Algorithm
0589e3017c76d312d26e3433498379e75ad975fd
e4421bf5e900ff5fbe3035456b66bd18f0c30bbe
refs/heads/master
2022-04-17T00:31:04.963031
2020-04-12T06:16:21
2020-04-12T06:16:21
258,400,595
1
0
null
2020-04-24T03:59:37
2020-04-24T03:59:36
null
UTF-8
C++
false
false
75
cpp
class Solution { public: int dayOfYear(string date) { } };
ee72e5310eb0b5d0790d7b26cfeb640d207fe90f
fc94c4115d2382c75bc7f9c3255fe055864bb8be
/src/test/testutil.cpp
e4c7204a2d56421525cd5bbc005e98f50c362869
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
cenut/ilcoin-master
21b4bad92a094df5a24226686a3408e0c5680cba
8bfc6f7e5e23bcf35840e1988bf19ec6096be9c2
refs/heads/master
2020-07-09T16:58:22.347829
2019-08-23T16:13:03
2019-08-23T16:13:03
204,027,887
0
1
null
2019-08-23T15:46:33
2019-08-23T15:46:32
null
UTF-8
C++
false
false
300
cpp
// Copyright (c) 2009-2016 The Ilcoin Core developers // All Rights Reserved. Ilgamos International 2017© #include "testutil.h" #ifdef WIN32 #include <shlobj.h> #endif #include <boost/filesystem.hpp> boost::filesystem::path GetTempPath() { return boost::filesystem::temp_directory_path(); }
d7b5c48e0c1cccd4eeb7c0ee236e4b7c19e6e473
6d972aef47d164282d6c5579d2f09cd086ddb5c7
/tests/test_eigen_solve_system.cpp
96bd9c9b848373f3b7a6f50fd431915ddbf63eb0
[]
no_license
nparent/PS2
ed37dbe98ba861f673b5cb146d4f919eedbc9811
018f68dfc26f8fef9c428b0b59fbaf9982dec6eb
refs/heads/master
2020-08-08T00:43:17.363348
2019-11-03T16:11:26
2019-11-03T16:11:26
213,641,977
0
0
null
null
null
null
UTF-8
C++
false
false
426
cpp
#define BOOST_TEST_MODULE test_eigen_solve_system #include <iostream> #include <Eigen/Dense> #include <boost/timer/timer.hpp> #include <boost/test/unit_test.hpp> using namespace std; using namespace Eigen; BOOST_AUTO_TEST_CASE(solve_system) { MatrixXd a = MatrixXd::Random(10,10); MatrixXd b = MatrixXd::Zero(10,1); MatrixXd c(10,1); // c = a*b; c = a.colPivHouseholderQr().solve(b); BOOST_CHECK_EQUAL(b,c); }
4122292a718915e68dacd9668e725e5aed4d07a9
31ac07ecd9225639bee0d08d00f037bd511e9552
/externals/OCCTLib/inc/TopTools_MapIteratorOfMapOfOrientedShape.hxx
9856c7d935d960ee12349b7c70bca58f5bd31225
[]
no_license
litao1009/SimpleRoom
4520e0034e4f90b81b922657b27f201842e68e8e
287de738c10b86ff8f61b15e3b8afdfedbcb2211
refs/heads/master
2021-01-20T19:56:39.507899
2016-07-29T08:01:57
2016-07-29T08:01:57
64,462,604
1
0
null
null
null
null
UTF-8
C++
false
false
1,580
hxx
// This file is generated by WOK (CPPExt). // Please do not edit this file; modify original file instead. // The copyright and license terms as defined for the original file apply to // this header file considered to be the "object code" form of the original source. #ifndef _TopTools_MapIteratorOfMapOfOrientedShape_HeaderFile #define _TopTools_MapIteratorOfMapOfOrientedShape_HeaderFile #ifndef _Standard_HeaderFile #include <Standard.hxx> #endif #ifndef _Standard_DefineAlloc_HeaderFile #include <Standard_DefineAlloc.hxx> #endif #ifndef _Standard_Macro_HeaderFile #include <Standard_Macro.hxx> #endif #ifndef _TCollection_BasicMapIterator_HeaderFile #include <TCollection_BasicMapIterator.hxx> #endif #ifndef _Handle_TopTools_StdMapNodeOfMapOfOrientedShape_HeaderFile #include <Handle_TopTools_StdMapNodeOfMapOfOrientedShape.hxx> #endif class Standard_NoSuchObject; class TopoDS_Shape; class TopTools_OrientedShapeMapHasher; class TopTools_MapOfOrientedShape; class TopTools_StdMapNodeOfMapOfOrientedShape; class TopTools_MapIteratorOfMapOfOrientedShape : public TCollection_BasicMapIterator { public: DEFINE_STANDARD_ALLOC Standard_EXPORT TopTools_MapIteratorOfMapOfOrientedShape(); Standard_EXPORT TopTools_MapIteratorOfMapOfOrientedShape(const TopTools_MapOfOrientedShape& aMap); Standard_EXPORT void Initialize(const TopTools_MapOfOrientedShape& aMap) ; Standard_EXPORT const TopoDS_Shape& Key() const; protected: private: }; // other Inline functions and methods (like "C++: function call" methods) #endif
d16b6bdc5de7df932f7066dfd19a6ba549dbc5b7
39e4103c8e217cae8a95f1067de08cc864d9c007
/project/shape/cone.cpp
927be1ed7822108ea100c90ef5d289cd56ca5db1
[]
no_license
jfreilich/CS123-Final
8924eb5e7befd4abed3037ddce1dfbb04260d50b
04adb1ce2912d8533c64175f068ba509ce1c3883
refs/heads/master
2020-06-13T23:05:18.873322
2012-12-17T04:19:46
2012-12-17T04:19:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,523
cpp
#include "cone.h" #include "Shape.h" Cone::Cone() :Shape(){ } void Cone::normal_vector(double points[9], double normal[9]){ double rt5=pow(5.0,0.5); for(int i =0;i<3;i++){ double x=points[3*i]; double y=points[3*i+1]; double z=points[3*i+2]; double r=pow(x*x+z*z,0.5); if(y==-0.5&&r==0.5){ //cross product double x1=points[0]; double x2=points[3]; double x3=points[6]; double z1=points[2]; double z2=points[5]; double z3=points[8]; double b1=x2-x1; double c1=x3-x1; double b3=z2-z1; double c3=z3-z1; double y4=b3*c1-b1*c3; if (y4>0){ x=2.0*x/(r*rt5); z=2.0*z/(r*rt5); y=1.0/rt5; } else{ y=-1; x=0; z=0; } } else if(y==-0.5){ y=-1; z=0; x=0; } else{ if(y==0.5){ x=(points[0]+points[3])/2.0; z=(points[2]+points[5])/2.0; r=pow(x*x+z*z,0.5); } x=2.0*x/(r*rt5); z=2.0*z/(r*rt5); y=1.0/rt5; } normal[3*i]=x; normal[3*i+1]=y; normal[3*i+2]=z; } fflush(stdout); } void Cone::tesselate(int p1, int p2){ if (m_triangles){ delete[] m_triangles; } if(p2<3){ p2=3; } m_size=2*p2*(2*p1-1); m_triangles=new triangle[m_size]; double x=0; double y=0; double z=0; int index=0; for (int a=0;a<p2;a++){ for (int b =0;b<p1;b++){ triangle tri; float ang=a*M_PI*2.0/p2; for (int m=0;m<=2;m++){ if (m==1){ ang=ang+M_PI*2.0/p2; } x=0.5*sin(ang)*(p1-b-m/2)/(float) p1; y=(-0.5+(b+(m/2))/(float) p1); z=0.5*cos(ang)*(p1-b-m/2)/(float) p1; tri.coordinates[3*m]=x; tri.coordinates[3*m+1]=y; tri.coordinates[3*m+2]=z; } this->normal_vector(tri.coordinates,tri.normals); m_triangles[index]=tri; index++; if(b<p1-1){ triangle tri2; ang=ang-M_PI*2.0/p2; for (int m=1;m<=3;m++){ if (m>1){ x=0.5*sin(ang)*(p1-b-1+m/3)/(float) p1; y=(-0.5+(b+1-(m/3))/(float) p1); z=0.5*cos(ang)*(p1-b-1+m/3)/(float) p1; } tri2.coordinates[3*(m-1)]=x; tri2.coordinates[3*m-2]=y; tri2.coordinates[3*m-1]=z; } this->normal_vector(tri2.coordinates,tri2.normals); m_triangles[index]=tri2; index++; } } } for (int a=0;a<index;a++){ triangle tri=m_triangles[a]; for (int b=1;b<=3;b++){ tri.coordinates[3*b-2]=-0.5; } float tempx=tri.coordinates[3]; tri.coordinates[3]=tri.coordinates[6]; tri.coordinates[6]=tempx; float tempz=tri.coordinates[5]; tri.coordinates[5]=tri.coordinates[8]; tri.coordinates[8]=tempz; this->normal_vector(tri.coordinates,tri.normals); m_triangles[a+index]=tri; } }
cdf9ae9c90e6e6b4e88d12bc6046b50ee3a28244
99d91bdfa1b50c9a78493def1f081a0608127821
/MinesweeperBoard.cpp
892a789b97645d287d693b84ddc021cadcd75e82
[]
no_license
xdawxd/SFML-Saper
015c994967e1ef9b0625e2d92d57616bc666f374
b729e04c7e1a9174c1c1a8d215605c4cc42e79b4
refs/heads/master
2023-04-21T21:57:22.204920
2021-05-02T21:33:28
2021-05-02T21:33:28
363,751,127
0
0
null
null
null
null
UTF-8
C++
false
false
6,734
cpp
#include <iostream> #include "MinesweeperBoard.h" void MinesweeperBoard::createDebugBoard() { int counter = 0; for (int row = 0; row < height; ++row) { for (int col = 0; col < width; ++col) { if (row == col || row == 0 || (col == 0 && row % 2 == 0)) { board[row][col].hasMine = true; counter++; } } } numOfMines = counter; } void MinesweeperBoard::placeRandomMine() { int randRow = rand() % height; int randCol = rand() % width; if (board[randRow][randCol].hasMine) placeRandomMine(); else board[randRow][randCol].hasMine = true; } void MinesweeperBoard::createRandomBoard() { for (int mines = 0; mines < numOfMines; ++mines) placeRandomMine(); } void MinesweeperBoard::chooseDifficulty() { switch (mode) { case EASY: numOfMines = width * height * 0.1; break; case NORMAL: numOfMines = width * height * 0.2; break; case HARD: numOfMines = width * height * 0.3; break; case DEBUG: createDebugBoard(); break; } if (mode != DEBUG) { this->numOfMines = numOfMines; createRandomBoard(); } } MinesweeperBoard::MinesweeperBoard(int width, int height, GameMode mode) { this->width = width; this->height = height; this->mode = mode; moves = 0; int numOfMines = 0; state = RUNNING; firstAction = true; for (int row = 0; row < height; ++row) { for (int col = 0; col < width; ++col) { board[row][col] = { 0, 0, 0 }; } } chooseDifficulty(); } int MinesweeperBoard::getBoardWidth() const { return width; } int MinesweeperBoard::getBoardHeight() const { return height; } int MinesweeperBoard::getMineCount() const { return numOfMines; } bool MinesweeperBoard::isOutside(int row, int col) const { if (row < 0 || row > height || col < 0 || col > width) return true; return false; } int MinesweeperBoard::countMines(int boardRow, int boardCol) const { int count = 0; if (isOutside(boardRow, boardCol)) return -1; if(!board[boardRow][boardCol].isRevealed) return -1; for (int row = -1; row <= 1; ++row) { for (int col = -1; col <= 1; ++col) { if (((boardRow + row) >= 0 && (boardRow + row) < height) && ((boardCol + col) >= 0 && (boardCol + col) < width) && board[boardRow + row][boardCol + col].hasMine) count++; } } return count; } bool MinesweeperBoard::hasMine(int row, int col) const { if (isOutside(row, col)) return false; if (board[row][col].hasMine) return true; return false; } bool MinesweeperBoard::hasFlag(int row, int col) const { if (isOutside(row, col)) return false; if (board[row][col].hasFlag) return true; if (board[row][col].isRevealed || board[row][col].hasFlag) return false; return 0; } void MinesweeperBoard::toggleFlag(int row, int col) { if (state != RUNNING) return; if (isOutside(row, col)) return; if (board[row][col].isRevealed) return; if (!board[row][col].isRevealed && !board[row][col].hasFlag) board[row][col].hasFlag = true; else if(!board[row][col].isRevealed && board[row][col].hasFlag) board[row][col].hasFlag = false; } void MinesweeperBoard::revealField(int row, int col) { if (state != RUNNING) return; if (isOutside(row, col)) return; if (board[row][col].isRevealed || board[row][col].hasFlag) return; if (!board[row][col].isRevealed && !board[row][col].hasMine) board[row][col].isRevealed = true; if (!board[row][col].isRevealed && board[row][col].hasMine) { if (firstAction && mode != DEBUG) { placeRandomMine(); board[row][col].hasMine = false; firstAction = false; } else state = FINISHED_LOSS; board[row][col].isRevealed = true; } firstAction = false; } bool MinesweeperBoard::isRevealed(int row, int col) const { if (board[row][col].isRevealed) return true; return false; } GameState MinesweeperBoard::getGameState() const { if (state == FINISHED_LOSS) return FINISHED_LOSS; int fieldsLeft = 0; for (int row = 0; row < height; ++row) { for (int col = 0; col < width; ++col) { if (!board[row][col].hasMine && !board[row][col].isRevealed) fieldsLeft++; } } if (fieldsLeft == 0) return FINISHED_WIN; return RUNNING; } char MinesweeperBoard::getFieldInfo(int row, int col) const { if (isOutside(row, col)) return '#'; if (board[row][col].isRevealed && board[row][col].hasMine) return 'x'; if (!board[row][col].isRevealed && board[row][col].hasFlag) return 'F'; if (!board[row][col].isRevealed && !board[row][col].hasFlag) return '_'; if (board[row][col].isRevealed) return '0' + countMines(row, col); return ' '; } void MinesweeperBoard::debugDisplay() const { for (int row = 0; row < height; ++row) { for (int col = 0; col < width; ++col) { std::string fld = "[]"; board[row][col].hasMine == 1 ? fld.insert(1, "M") : fld.insert(1, "."); board[row][col].isRevealed == 1 ? fld.insert(2, "o") : fld.insert(2, "."); board[row][col].hasFlag == 1 ? fld.insert(3, "f") : fld.insert(3, "."); std::cout << fld; } std::cout << std::endl; } } void MinesweeperBoard::setBoard() { for (int row = 0; row < height; ++row) { for (int col = 0; col < width; ++col) { board[row][col] = { 0, 0, 0 }; } } std::cout << "Board cleared" << std::endl; createRandomBoard(); firstAction = true; state = RUNNING; } void MinesweeperBoard::setDifficulty(GameMode mode) { state = RUNNING; this->mode = mode; chooseDifficulty(); setBoard(); std::cout << "Game mode changed to: " << mode << std::endl; } void MinesweeperBoard::floodFill(int row, int col) { if (isOutside(row, col)) return; if (isRevealed(row, col)) return; revealField(row, col); if (countMines(row, col) == 0) { floodFill(row + 1, col + 1); floodFill(row - 1, col - 1); floodFill(row, col - 1); floodFill(row - 1, col); floodFill(row + 1, col); floodFill(row, col + 1); floodFill(row - 1, col + 1); floodFill(row + 1, col - 1); } }
b1a01aaedf42c563566092ec5efec6e6c46af600
1c67abbfd0ef08cc880cc1746b8d36b4444dfcf1
/round-3/math/728-self-dividing.cpp
4a93071b84eadbe57542fa8cfb66203a4a058790
[]
no_license
pwyq/LeetCode
916371991a550d2abd4e2349695fe1a2b242ef78
a88800aacda8456429c8449c180fc18b4c16bcc2
refs/heads/master
2022-04-27T05:23:02.133765
2020-04-12T00:13:07
2020-04-12T00:13:07
119,621,665
0
0
null
null
null
null
UTF-8
C++
false
false
859
cpp
class Solution { public: vector<int> selfDividingNumbers(int left, int right) { vector<int> res; for (int i = left; i <= right; i++) { bool isTrue = true; int temp = i; while (temp > 0) { int digit = temp % 10; if (digit == 0) { isTrue = false; break; } if (i % digit != 0) { isTrue = false; break; } temp = temp / 10; } if (isTrue) { res.push_back(i); } } return res; } }; Runtime: 0 ms, faster than 100.00% of C++ online submissions for Self Dividing Numbers. Memory Usage: 8.4 MB, less than 88.00% of C++ online submissions for Self Dividing Numbers.
61a3f6199eedf3dc5272b6b033f6ecdfdade0d21
3c48f61c8893c072847a9f8cf618fcb50efc2a21
/hhkb2020/hhkb2020_b/main.cpp
537ba31128ff3a1276d1048afd449c35a0f39470
[]
no_license
sotetsuk/procon
550ae9b9c39ea8616789f5b4566d6715bb9d0828
e6f2c5fb558d372efd7833825e885db7a4fee4a8
refs/heads/master
2021-06-28T01:30:50.794701
2020-10-17T19:47:30
2020-10-17T19:47:30
20,493,581
0
0
null
null
null
null
UTF-8
C++
false
false
477
cpp
#include <bits/stdc++.h> using namespace std; using ll = long long; int main() { int H, W; cin >> H >> W; vector<string> S(H); for (int i = 0; i < H; ++i) cin >> S[i]; int cnt = 0; for (int i = 0; i < H; ++i) { for (int j = 0; j < W; ++j) { if (S[i][j] != '.') continue; if (i + 1 < H && S[i + 1][j] == '.') ++cnt; if (j + 1 < W && S[i][j + 1] == '.') ++cnt; } } cout << cnt << endl; return 0; }
47f6b4bd165d2d86ee6e179e50d40e9c08461768
1af43c4ba32d78c60f007a4d068136ce575d917f
/system/apps_featured/118_basic/source/terminal-basic/basic_parser_value.hpp
32972ea28444df06de82f158ae3d52cc55dd736f
[ "MIT" ]
permissive
gabonator/LA104
a4f1cdf2b3e513300d61c50fff091c5717abda9e
27d0eece7302c479da2cf86e881b6a51a535f93d
refs/heads/master
2023-08-31T22:09:36.272616
2023-08-27T20:08:08
2023-08-27T20:08:08
155,659,451
500
69
MIT
2023-08-17T08:44:32
2018-11-01T03:54:21
C
UTF-8
C++
false
false
3,501
hpp
/* * Terminal-BASIC is a lightweight BASIC-like language interpreter * * Copyright (C) 2016-2018 Andrey V. Skvortsov <[email protected]> * Copyright (C) 2019,2020 Terminal-BASIC team * <https://bitbucket.org/%7Bf50d6fee-8627-4ce4-848d-829168eedae5%7D/> * * 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 3 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, see <http://www.gnu.org/licenses/>. */ #ifndef BASIC_PARSER_VALUE_HPP #define BASIC_PARSER_VALUE_HPP #include "basic_parser.hpp" #include "basic_value.h" #include <Printable.h> namespace BASIC { class PACKED Parser::Value { public: /** * @brief types of the value */ enum Type : uint8_t { INTEGER = BASIC_VALUE_TYPE_INTEGER, #if USE_LONGINT LONG_INTEGER = BASIC_VALUE_TYPE_LONG_INTEGER, #endif #if USE_REALS REAL = BASIC_VALUE_TYPE_REAL, #if USE_LONG_REALS LONG_REAL = BASIC_VALUE_TYPE_LONG_REAL, #endif #endif // USE_REALS LOGICAL = BASIC_VALUE_TYPE_LOGICAL, STRING = BASIC_VALUE_TYPE_STRING }; /** * @brief Default constructor * * Initializes a value with 0 INTEGER, which s always available */ Value() { basic_value_setFromInteger(&m_value, 0); } #if USE_LONGINT /** * @brief Constructor ftrom LongInteger number * @param v */ Value(LongInteger v) { basic_value_setFromLongInteger(&m_value, v); } #endif Value(Integer); #if USE_REALS Value(Real); #if USE_LONG_REALS Value(LongReal); #endif #endif // USE_REALS Value(bool); #if USE_REALS explicit operator Real() const; #if USE_LONG_REALS explicit operator LongReal() const; #endif #endif // USE_REALS explicit operator bool() const; explicit operator Integer() const; #if USE_LONGINT explicit operator LongInteger() const; #endif bool operator<(const Value&) const; bool operator==(const Value&) const; bool operator>(const Value&) const; friend bool operator >=(const Value&, const Value&); friend bool operator <=(const Value&, const Value&); Value &operator+=(const Value&); Value &operator-=(const Value&); Value &operator*=(const Value&); Value &operator/=(const Value&); Value &divEquals(const Value&); Value &modEquals(const Value&); Value &operator^=(const Value&); Value &operator|=(const Value&); Value &operator&=(const Value&); void switchSign(); static size_t size(Type); // Return Variable/Array/Function type based on it's name static Type typeFromName(const char*); Type type() const { return Type(m_value.type); } void setType(Type newVal) { m_value.type = basic_value_type_t(newVal); } basic_value_t m_value; // Printable interface size_t printTo(Print& p) const; }; template <> inline void writeValue<Parser::Value>(Parser::Value v, uint8_t* str) { memcpy(str, &v, sizeof(Parser::Value)); } template <> inline typename Parser::Value readValue<Parser::Value>(const uint8_t* str) { Parser::Value result; memcpy(&result, str, sizeof(Parser::Value)); return result; } } // namespace BASIC #endif // BASIC_PARSER_VALUE_HPP
58d4ca2b200d722061d39d8125b790cf35de3da6
bdd9f3cdabe0c768641cf61855a6f24174735410
/src/engine/shared/library/sharedCollision/src/shared/core/CollisionMesh.cpp
80a0e930c37dc4ad56092aea3f787a42318291ce
[]
no_license
SWG-Source/client-tools
4452209136b376ab369b979e5c4a3464be28257b
30ec3031184243154c3ba99cedffb2603d005343
refs/heads/master
2023-08-31T07:44:22.692402
2023-08-28T04:34:07
2023-08-28T04:34:07
159,086,319
15
47
null
2022-04-15T16:20:34
2018-11-25T23:57:31
C++
UTF-8
C++
false
false
26,469
cpp
// ====================================================================== // // CollisionMesh.cpp // copyright (c) 2001 Sony Online Entertainment // // ====================================================================== #include "sharedCollision/FirstSharedCollision.h" #include "sharedCollision/CollisionMesh.h" #include "sharedCollision/SimpleExtent.h" #include "sharedCollision/FloorTri.h" #include "sharedCollision/Intersect3d.h" #include "sharedCollision/Overlap3d.h" #include "sharedCollision/Distance3d.h" #include "sharedCollision/CollisionUtils.h" #include "sharedCollision/ConfigSharedCollision.h" #include "sharedCollision/BoxTree.h" #include "sharedCollision/FloorLocator.h" #include "sharedMath/Triangle3d.h" #include "sharedMath/AxialBox.h" #include "sharedMath/Transform.h" #include "sharedMath/IndexedTriangleList.h" #include "sharedMath/Sphere.h" #include "sharedMath/Ray3d.h" #include "sharedMath/Range.h" #include "sharedMath/Line3d.h" #include "sharedMath/Segment3d.h" #include "sharedMath/ShapeUtils.h" #include <vector> #include <algorithm> #include <stack> namespace CollisionMeshNamespace { static std::vector<int> gs_tempResultVec; } using namespace CollisionMeshNamespace; // ---------------------------------------------------------------------- // Accessories int CollisionMesh::FindEdgeDirected ( IndexedTri const & T, int index1, int index2 ) { for(int i = 0; i < 3; i++) { if( (T.getCornerIndex(i) == index1) && (T.getCornerIndex(i+1) == index2) ) { return i; } } return -1; } // ---------- int CollisionMesh::FindEdgeUndirected ( IndexedTri const & T, int index1, int index2 ) { for(int i = 0; i < 3; i++) { if( (T.getCornerIndex(i) == index1) && (T.getCornerIndex(i+1) == index2) ) { return i; } if( (T.getCornerIndex(i+1) == index1) && (T.getCornerIndex(i) == index2) ) { return i; } } return -1; } // ---------- void CollisionMesh::LinkTris( ConnectedTri & A, ConnectedTri & B) { for(int edgeA = 0; edgeA < 3; edgeA++) { int index1 = A.getCornerIndex(edgeA); int index2 = A.getCornerIndex(edgeA+1); int edgeB = FindEdgeDirected(B,index2,index1); if(edgeB != -1) { A.setNeighborIndex(edgeA,B.getIndex()); B.setNeighborIndex(edgeB,A.getIndex()); } } } // ---------------------------------------------------------------------- CollisionMesh::CollisionMesh() : CollisionSurface(), m_id(0), m_version(1), m_boxTree(NULL), m_extent(NULL), m_boundsDirty(true) { m_extent = new SimpleExtent( MultiShape(AxialBox()) ); } CollisionMesh::~CollisionMesh() { delete m_boxTree; m_boxTree = NULL; delete m_extent; m_extent = NULL; } // ---------------------------------------------------------------------- Transform const & CollisionMesh::getTransform_o2p ( void ) const { return Transform::identity; } Transform const & CollisionMesh::getTransform_o2w ( void ) const { return Transform::identity; } float CollisionMesh::getScale ( void ) const { return 1.0f; } BaseExtent const * CollisionMesh::getExtent_l ( void ) const { return m_extent; } BaseExtent const * CollisionMesh::getExtent_p ( void ) const { return m_extent; } // ---------------------------------------------------------------------- void CollisionMesh::clear ( void ) { delete m_boxTree; m_boxTree = NULL; } // ---------------------------------------------------------------------- // Brute-force vertex merge void CollisionMesh::merge ( void ) { int nVerts = getVertexCount(); int nTris = getTriCount(); real epsilon = 0.0000000000001f; // ---------- // A temporary table that we'll use to remap vertex indices when // we're done with the merge. IntVector vertRemap(nVerts); for(int iRemap = 0; iRemap < nVerts; iRemap++) { vertRemap[iRemap] = static_cast<int>(iRemap); } // ---------- for(int iVert = 0; iVert < nVerts; iVert++) { // If this vertex has already been remapped, skip it. if(vertRemap[iVert] != static_cast<int>(iVert)) continue; // ---------- // Otherwise, remap all vertices in the rest of the array that are // mergeable with this vertex so that they reference this vertex for (int jVert = iVert+1; jVert < nVerts; jVert++) { Vector const & A = getVertex(iVert); Vector const & B = getVertex(jVert); if(A == B) { vertRemap[jVert] = static_cast<int>(iVert); } else if(A.magnitudeBetween(B) <= epsilon) { vertRemap[jVert] = static_cast<int>(iVert); } } } // ---------- // Done building the remapping table, remap all our floor tris for(int iTri = 0; iTri < nTris; iTri++) { IndexedTri I = getIndexedTri(iTri); int iA = vertRemap[ I.getCornerIndex(0) ]; int iB = vertRemap[ I.getCornerIndex(1) ]; int iC = vertRemap[ I.getCornerIndex(2) ]; I.setCornerIndex( 0, iA ); I.setCornerIndex( 1, iB ); I.setCornerIndex( 2, iC ); setIndexedTri(iTri,I); } setBoundsDirty(true); } // ---------------------------------------------------------------------- // Remove all degenerate triangles from the mesh int CollisionMesh::scrub ( void ) { IntVector badTris; for(int iTri = 0; iTri < getTriCount(); iTri++) { if(getTriangle(iTri).isDegenerate()) { badTris.push_back(iTri); } } int nBadTris = static_cast<int>(badTris.size()); deleteTris(badTris); setBoundsDirty(true); return nBadTris; } // ---------------------------------------------------------------------- void CollisionMesh::calcBounds() const { AxialBox bounds; for(int i = 0; i < getVertexCount(); i++) { bounds.add( getVertex(i) ); } m_extent->setShape( MultiShape(bounds) ); setBoundsDirty(false); } // ---------------------------------------------------------------------- void CollisionMesh::setBoundsDirty(bool const dirty) const { bool const finalizeTheData = m_boundsDirty && !dirty; m_boundsDirty = dirty; if (finalizeTheData) const_cast<CollisionMesh *>(this)->finalizeData(); } // ---------------------------------------------------------------------- AxialBox CollisionMesh::getBoundingABox ( void ) const { if(m_boundsDirty) { calcBounds(); } return m_extent->getShape().getAxialBox(); } // ---------- Sphere CollisionMesh::getBoundingSphere ( void ) const { if(m_boundsDirty) { calcBounds(); } return m_extent->getShape().getBoundingSphere(); } // ---------------------------------------------------------------------- // This has the potential to be a little slow depending on the size of the // polygon soup. If that becomes the case we can look at storing the soup // more efficiently (octree, etc) bool CollisionMesh::intersect(Vector const & begin, Vector const & end, Vector * surfaceNormal, float * time) const { Vector direction(end - begin); bool hit = false; if (direction.normalize()) { Ray3d const ray(begin, direction); real bestTime = REAL_MAX; int bestTriangle = -1; int const nTris = getTriCount(); for(int i = 0; i < nTris; ++i) { // be nice if getTriangle returned a pointer or a const ref // I'm hesitant to change it at this moment -- tmf Triangle3d const triangle(getTriangle(i)); Vector hitPoint; real t; if (Intersect3d::IntersectRayTriSided(ray, triangle, hitPoint, t)) { if (t < bestTime) { bestTime = t; bestTriangle = i; } hit = true; } } if (hit) { if (surfaceNormal) { *surfaceNormal = getTriangle(bestTriangle).getNormal(); } if (time) { float const magnitude = (end - begin).magnitude(); *time = bestTime / magnitude; } } } return(hit); } bool CollisionMesh::testIntersect ( Line3d const & L, int triId ) const { return Overlap3d::TestSided(L,getTriangle(triId)); } bool CollisionMesh::testIntersect ( Ray3d const & R, int triId ) const { return Overlap3d::TestSided(R,getTriangle(triId)); } bool CollisionMesh::testIntersect ( Segment3d const & S, int triId ) const { return Overlap3d::TestSided(S,getTriangle(triId)); } bool CollisionMesh::testIntersectUnsided ( Line3d const & L, int triId ) const { return Overlap3d::TestUnsided(L,getTriangle(triId)); } bool CollisionMesh::testIntersectUnsided ( Ray3d const & R, int triId ) const { return Overlap3d::TestUnsided(R,getTriangle(triId)); } bool CollisionMesh::testIntersectUnsided ( Segment3d const & S, int triId ) const { return Overlap3d::TestUnsided(S,getTriangle(triId)); } // ---------------------------------------------------------------------- template<class TestShape> static inline bool templateTestIntersectSided ( TestShape const & shape, CollisionMesh const & mesh, int triId ) { return Overlap3d::TestSided(shape,mesh.getTriangle(triId)); } template<class TestShape> static inline bool templateTestIntersectUnsided ( TestShape const & shape, CollisionMesh const & mesh, int triId ) { return Overlap3d::TestUnsided(shape,mesh.getTriangle(triId)); } // ---------- template<class TestShape> static inline bool templateTestIntersectSided_slow ( TestShape const & shape, CollisionMesh const & mesh ) { int nTris = mesh.getTriCount(); for(int triId = 0; triId < nTris; triId++) { if(templateTestIntersectSided(shape,mesh,triId)) { return true; } } return false; } // ---------- template<class TestShape> static inline bool templateTestIntersectSided_fast ( TestShape const & shape, CollisionMesh const & mesh ) { BoxTree const * tree = mesh.getBoxTree(); if(!tree) { return templateTestIntersectSided_slow(shape,mesh); } // ---------- IntVector & tempResults = mesh.getTempResultVector(); tempResults.clear(); tree->testOverlap(shape,tempResults); int resultCount = tempResults.size(); for(int i = 0; i < resultCount; i++) { int triId = tempResults[i]; if(templateTestIntersectSided(shape,mesh,triId)) { return true; } } return false; } // ---------- template<class TestShape> static inline bool templateTestIntersectSided ( TestShape const & shape, CollisionMesh const & mesh ) { #if DEBUG_LEVEL == DEBUG_LEVEL_DEBUG if(ConfigSharedCollision::getEnableCollisionValidate()) { bool hitFast = templateTestIntersectSided_fast(shape,mesh); bool hitSlow = templateTestIntersectSided_slow(shape,mesh); DEBUG_FATAL(hitFast != hitSlow,("CollisionMesh::test - Fast and slow versions disagree\n")); return hitFast; } else { return templateTestIntersectSided_fast(shape,mesh); } #else return templateTestIntersectSided_fast(shape,mesh); #endif } // ---------- bool CollisionMesh::testIntersect ( Line3d const & line ) const { return templateTestIntersectSided(line,*this); } bool CollisionMesh::testIntersect ( Ray3d const & ray ) const { return templateTestIntersectSided(ray,*this); } bool CollisionMesh::testIntersect ( Segment3d const & segment ) const { return templateTestIntersectSided(segment,*this); } // ---------------------------------------------------------------------- void CollisionMesh::makeResult ( bool hit, int id, Vector const & pos, float param, ContactPoint & result ) const { UNREF(hit); result = ContactPoint(this,pos,id,param); } void CollisionMesh::makeResult ( bool hit, int id, Vector const & pos, float param, LineIntersectResult & result ) const { UNREF(hit); result = LineIntersectResult( true, param, ContactPoint(this,pos,id,param) ); } void CollisionMesh::makeResult ( bool hit, int id, Vector const & pos, float param, bool & result ) const { result = hit; UNREF(id); UNREF(pos); UNREF(param); } // ---------- template< class TestShape, class ResultType > static inline bool templateTestIntersectSided ( TestShape const & shape, CollisionMesh const & mesh, int triId, ResultType & result ) { Vector newPos; real param; bool hit = Intersect3d::IntersectSided(shape,mesh.getTriangle(triId),newPos,param); if(hit) { mesh.makeResult(hit,triId,newPos,param,result); } return hit; } template< class TestShape, class ResultType > static inline bool templateTestIntersectUnsided ( TestShape const & shape, CollisionMesh const & mesh, int triId, ResultType & result ) { Vector newPos; real param; bool hit = Intersect3d::IntersectUnsided(shape,mesh.getTriangle(triId),newPos,param); if(hit) { mesh.makeResult(hit,triId,newPos,param,result); } return hit; } // ---------- bool CollisionMesh::testIntersect ( Line3d const & L, int triId, ContactPoint & result ) const { return templateTestIntersectSided(L,*this,triId,result); } bool CollisionMesh::testIntersect ( Ray3d const & R, int triId, ContactPoint & result ) const { return templateTestIntersectSided(R,*this,triId,result); } bool CollisionMesh::testIntersect ( Segment3d const & S, int triId, ContactPoint & result ) const { return templateTestIntersectSided(S,*this,triId,result); } bool CollisionMesh::testIntersectUnsided ( Line3d const & L, int triId, ContactPoint & result ) const { return templateTestIntersectUnsided(L,*this,triId,result); } bool CollisionMesh::testIntersectUnsided ( Ray3d const & R, int triId, ContactPoint & result ) const { return templateTestIntersectUnsided(R,*this,triId,result); } bool CollisionMesh::testIntersectUnsided ( Segment3d const & S, int triId, ContactPoint & result ) const { return templateTestIntersectUnsided(S,*this,triId,result); } bool CollisionMesh::testIntersect ( Line3d const & L, int triId, LineIntersectResult & result ) const { return templateTestIntersectSided(L,*this,triId,result); } bool CollisionMesh::testIntersect ( Ray3d const & R, int triId, LineIntersectResult & result ) const { return templateTestIntersectSided(R,*this,triId,result); } bool CollisionMesh::testIntersect ( Segment3d const & S, int triId, LineIntersectResult & result ) const { return templateTestIntersectSided(S,*this,triId,result); } // ---------------------------------------------------------------------- template< class TestShape, class ResultType > static inline bool templateIntersectAny_slow ( TestShape const & shape, CollisionMesh const & mesh, ResultType & result ) { int nTris = mesh.getTriCount(); for(int i = 0; i < nTris; i++) { if(templateTestIntersectSided(shape,mesh,i,result)) { return true; } } return false; } // ---------- template< class TestShape, class ResultType > static inline bool templateIntersectAny_fast ( TestShape const & shape, CollisionMesh const & mesh, ResultType & result ) { BoxTree const * tree = mesh.getBoxTree(); if(!tree) { return templateIntersectAny_slow(shape,mesh,result); } // ---------- IntVector & tempResults = mesh.getTempResultVector(); tempResults.clear(); tree->testOverlap(shape,tempResults); int resultCount = tempResults.size(); for(int i = 0; i < resultCount; i++) { int triId = tempResults[i]; if(templateTestIntersectSided(shape,mesh,triId,result)) { return true; } } return false; } // ---------- template< class TestShape, class ResultType > static inline bool templateIntersectAny ( TestShape const & shape, CollisionMesh const & mesh, ResultType & result ) { #if DEBUG_LEVEL == DEBUG_LEVEL_DEBUG if(ConfigSharedCollision::getEnableCollisionValidate()) { bool hitFast = templateIntersectAny_fast(shape,mesh,result); bool hitSlow = templateIntersectAny_slow(shape,mesh,result); DEBUG_FATAL(hitFast != hitSlow,("CollisionMesh::test - Fast and slow versions disagree\n")); return hitFast; } else { return templateIntersectAny_fast(shape,mesh,result); } #else return templateIntersectAny_fast(shape,mesh,result); #endif } // ---------- bool CollisionMesh::intersectAny ( Line3d const & L, ContactPoint & result ) const { return templateIntersectAny(L,*this,result); } bool CollisionMesh::intersectAny ( Ray3d const & R, ContactPoint & result ) const { return templateIntersectAny(R,*this,result); } bool CollisionMesh::intersectAny ( Segment3d const & S, ContactPoint & result ) const { return templateIntersectAny(S,*this,result); } // ---------------------------------------------------------------------- bool CollisionMesh::intersectClosest ( Line3d const & line, ContactPoint & closest ) const { if(!testBounds(line)) { return false; } // ---------- FloorLocator closestFront; FloorLocator closestBack; IGNORE_RETURN( findClosestPair(line,-1,closestFront,closestBack) ); if(closestFront.isAttached()) { closest = closestFront; return true; } else if(closestBack.isAttached()) { closest = closestBack; return true; } else { closest = FloorLocator::invalid; return false; } } // ---------- bool CollisionMesh::intersectClosest ( Ray3d const & ray, ContactPoint & closest ) const { Line3d line(ray.getPoint(),ray.getNormal()); FloorLocator closestFront; FloorLocator closestBack; IGNORE_RETURN( findClosestPair(line,-1,closestFront,closestBack) ); if(closestFront.isAttached()) { closest = closestFront; return true; } else { closest = FloorLocator::invalid; return false; } } // ---------- bool CollisionMesh::intersectClosest ( Segment3d const & seg, ContactPoint & closest ) const { Line3d line(seg.getBegin(),seg.getDelta()); FloorLocator closestFront; FloorLocator closestBack; IGNORE_RETURN( findClosestPair(line,-1,closestFront,closestBack) ); if(closestFront.isAttached() && (closestFront.getOffset() <= 1.0f)) { closest = closestFront; return true; } else { closest = FloorLocator::invalid; return false; } } // ---------------------------------------------------------------------- template< class TestShape, class ResultType > static inline int templateIntersectAll_slow ( TestShape const & shape, CollisionMesh const & mesh, std::vector<ResultType> & results ) { ResultType result; int counter = 0; for(int i = 0; i < mesh.getTriCount(); i++) { if(templateTestIntersectSided(shape,mesh,i,result)) { results.push_back( result ); counter++; } } return counter; } // ---------- template< class TestShape, class ResultType > static inline int templateIntersectAll_fast ( TestShape const & shape, CollisionMesh const & mesh, std::vector<ResultType> & results ) { BoxTree const * tree = mesh.getBoxTree(); if(!tree) { return templateIntersectAll_slow(shape,mesh,results); } // ---------- IntVector & tempResults = mesh.getTempResultVector(); tempResults.clear(); tree->testOverlap(shape,tempResults); ResultType result; int counter = 0; int resultCount = tempResults.size(); for(int i = 0; i < resultCount; i++) { int triId = tempResults[i]; if(templateTestIntersectSided(shape,mesh,triId,result)) { results.push_back( result ); counter++; } } return counter; } // ---------- template< class TestShape, class ResultVector > static inline int templateIntersectAll ( TestShape const & shape, CollisionMesh const & mesh, ResultVector & results ) { #if DEBUG_LEVEL == DEBUG_LEVEL_DEBUG if(ConfigSharedCollision::getEnableCollisionValidate()) { ResultVector tempResults; int hitFast = templateIntersectAll_fast(shape,mesh,results); int hitSlow = templateIntersectAll_slow(shape,mesh,tempResults); DEBUG_FATAL(hitFast != hitSlow,("CollisionMesh::intersectRange - Fast and slow versions disagree\n")); return hitFast; } else { return templateIntersectAll_fast(shape,mesh,results); } #else return templateIntersectAll_fast(shape,mesh,results); #endif } // ---------- int CollisionMesh::intersectAll ( Line3d const & L, LineIntersectResultVec & results ) const { return templateIntersectAll(L,*this,results); } int CollisionMesh::intersectAll ( Ray3d const & R, LineIntersectResultVec & results ) const { return templateIntersectAll(R,*this,results); } int CollisionMesh::intersectAll ( Segment3d const & S, LineIntersectResultVec & results ) const { return templateIntersectAll(S,*this,results); } // ---------------------------------------------------------------------- template< class TestShape > static inline Range templateIntersectRange_slow( CollisionMesh const & mesh, TestShape const & shape ) { ContactPoint contact; Range range( Range::empty ); int triCount = mesh.getTriCount(); for(int i = 0; i < triCount; i++) { if(templateTestIntersectUnsided(shape,mesh,i,contact)) { range = Range::enclose( range, contact.getOffset() ); } } return range; } // ---------- template< class TestShape > static inline Range templateIntersectRange_fast( CollisionMesh const & mesh, TestShape const & shape ) { BoxTree const * tree = mesh.getBoxTree(); if(!tree) { return templateIntersectRange_slow(mesh,shape); } // ---------- IntVector & tempResults = mesh.getTempResultVector(); tempResults.clear(); tree->testOverlap(shape,tempResults); ContactPoint contact; Range range( Range::empty ); int resultCount = tempResults.size(); for(int i = 0; i < resultCount; i++) { int triId = tempResults[i]; if(templateTestIntersectUnsided(shape,mesh,triId,contact)) { range = Range::enclose( range, contact.getOffset() ); } } return range; } // ---------- template< class TestShape > static inline Range templateIntersectRange( CollisionMesh const & mesh, TestShape const & shape ) { #if DEBUG_LEVEL == DEBUG_LEVEL_DEBUG if(ConfigSharedCollision::getEnableCollisionValidate()) { Range hitFast = templateIntersectRange_fast(mesh,shape); Range hitSlow = templateIntersectRange_slow(mesh,shape); DEBUG_FATAL(hitFast != hitSlow,("CollisionMesh::intersectRange - Fast and slow versions disagree\n")); return hitFast; } else { return templateIntersectRange_fast(mesh,shape); } #else return templateIntersectRange_fast(mesh,shape); #endif } Range CollisionMesh::intersectRange ( Line3d const & L ) const { return templateIntersectRange(*this,L); } Range CollisionMesh::intersectRange ( Ray3d const & R ) const { return templateIntersectRange(*this,R); } Range CollisionMesh::intersectRange ( Segment3d const & S ) const { return templateIntersectRange(*this,S); } // ---------------------------------------------------------------------- bool CollisionMesh::findClosestPair ( FloorLocator const & testLoc, Vector const & down, FloorLocator & outClosestAbove, FloorLocator & outClosestBelow ) const { Line3d line(testLoc.getPosition_l(),-down); int ignoreId = testLoc.getId(); return findClosestPair( line, ignoreId, outClosestAbove, outClosestBelow ); } // ---------------------------------------------------------------------- // Find the pair of triangles that intersect the line and are closest // to the line's origin. bool CollisionMesh::findClosestPair ( Line3d const & line, int ignoreId, FloorLocator & outClosestFront, FloorLocator & outClosestBack ) const { outClosestFront = FloorLocator( this, Vector::zero, -1, REAL_MAX, 0.0f ); outClosestBack = FloorLocator( this, Vector::zero, -1, -REAL_MAX, 0.0f ); if(!testBounds(line)) { return false; } static LineIntersectResultVec results; results.clear(); if(intersectAll(line,results)) { // ---------- // Search the triangles for one that is below the test point int resultCount = results.size(); for(int i = 0; i < resultCount; i++) { LineIntersectResult & result = results[i]; ContactPoint & contact = result.m_hitLoc; if(contact.getId() == ignoreId) continue; // ---------- // Found a triangle under/above the point. if(contact.getOffset() > 0) { if(contact.getOffset() < outClosestFront.getOffset()) { outClosestFront = contact; } } else { if(contact.getOffset() > outClosestBack.getOffset()) { outClosestBack = contact; } } } return outClosestBack.isAttached() || outClosestFront.isAttached(); } else { return false; } } // ---------------------------------------------------------------------- bool CollisionMesh::testBounds ( Line3d const & line ) const { return Overlap3d::Test( line, getBoundingABox() ); } bool CollisionMesh::testBounds ( Segment3d const & seg ) const { return Overlap3d::Test( seg, getBoundingABox() ); } bool CollisionMesh::testBounds ( Ray3d const & ray ) const { return Overlap3d::Test( ray, getBoundingABox() ); } // ---------------------------------------------------------------------- void CollisionMesh::transform( CollisionMesh const * sourceMesh, Transform const & tform, float scale ) { DEBUG_FATAL( sourceMesh->getVertexCount() != getVertexCount(), ("MeshExtent::transform - Source extent has a different number of vertices")); DEBUG_FATAL( sourceMesh->getTriCount() != getTriCount(), ("MeshExtent::transform - Source extent has a different number of indices")); // ---------- for(int i = 0; i < sourceMesh->getVertexCount(); i++) { Vector newVert = tform.rotateTranslate_l2p( sourceMesh->getVertex(i) * scale); setVertex(i,newVert); } setBoundsDirty(true); } // ---------------------------------------------------------------------- bool CollisionMesh::hasBoxTree ( void ) const { return m_boxTree != NULL; } // ---------- void CollisionMesh::buildBoxTree ( void ) { typedef std::vector<AxialBox> BoxVec; BoxVec tempBoxes; for(int i = 0; i < getTriCount(); i++) { Triangle3d tri = getTriangle(i); AxialBox box(tri.getCornerA(), tri.getCornerB()); box.add(tri.getCornerC()); // Inflate the box by a centimeter to avoid possible numerical inaccuracy box = ShapeUtils::inflate(box,0.01f); tempBoxes.push_back(box); } delete m_boxTree; m_boxTree = new BoxTree(); m_boxTree->build(tempBoxes); } // ---------------------------------------------------------------------- IntVector & CollisionMesh::getTempResultVector ( void ) const { return gs_tempResultVec; } // ---------------------------------------------------------------------- void CollisionMesh::getVertices ( VectorVector & outVerts ) const { int nVerts = getVertexCount(); outVerts.clear(); outVerts.reserve(nVerts); for(int i = 0; i < nVerts; i++) { outVerts.push_back( getVertex(i) ); } } void CollisionMesh::getIndices ( IntVector & outIndices ) const { int nTris = getTriCount(); outIndices.clear(); outIndices.reserve(nTris * 3); for(int i = 0; i < nTris; i++) { IndexedTri const & tri = getIndexedTri(i); outIndices.push_back(tri.getCornerIndex(0)); outIndices.push_back(tri.getCornerIndex(1)); outIndices.push_back(tri.getCornerIndex(2)); } } void CollisionMesh::finalizeData() { }
1ca5bc0c1d5aea44940cc5cba8ca114e7e84ba26
26fc2b20f1e732b7902a261e359476e1a9995cc9
/FirstGame/Score.h
6d5217da0f930bb72f477b2ce9859438a0dac11f
[]
no_license
Astromonomical/Qt-Projects
738274f1332fcc60efd84c913eedb63284d31a4f
df87bc250d8fdd13c2c46857dcd425d44dc55ee9
refs/heads/master
2023-07-15T09:40:39.832476
2021-08-24T21:09:59
2021-08-24T21:09:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
212
h
#pragma once #include <QGraphicsTextItem> #include <QFont> class Score : public QGraphicsTextItem { public: Score(QGraphicsItem *parent=Q_NULLPTR); void increase(); int getScore(); private: int score; };
d0ab55ffac5766c41bd410c81256d02593f556be
a5f35d0dfaddb561d3595c534b6b47f304dbb63d
/Source/BansheeCore/RenderAPI/BsTextureView.cpp
29a91b9b1c7fab699d9cae981e6e1205e96a1e41
[]
no_license
danielkrupinski/BansheeEngine
3ff835e59c909853684d4985bd21bcfa2ac86f75
ae820eb3c37b75f2998ddeaf7b35837ceb1bbc5e
refs/heads/master
2021-05-12T08:30:30.564763
2018-01-27T12:55:25
2018-01-27T12:55:25
117,285,819
1
0
null
2018-01-12T20:38:41
2018-01-12T20:38:41
null
UTF-8
C++
false
false
1,078
cpp
//********************************** Banshee Engine (www.banshee3d.com) **************************************************// //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************// #include "RenderAPI/BsTextureView.h" #include "Image/BsTexture.h" namespace bs { namespace ct { size_t TextureView::HashFunction::operator()(const TEXTURE_VIEW_DESC &key) const { size_t seed = 0; hash_combine(seed, key.mostDetailMip); hash_combine(seed, key.numMips); hash_combine(seed, key.firstArraySlice); hash_combine(seed, key.numArraySlices); hash_combine(seed, key.usage); return seed; } bool TextureView::EqualFunction::operator() (const TEXTURE_VIEW_DESC &a, const TEXTURE_VIEW_DESC &b) const { return a.mostDetailMip == b.mostDetailMip && a.numMips == b.numMips && a.firstArraySlice == b.firstArraySlice && a.numArraySlices == b.numArraySlices && a.usage == b.usage; } TextureView::~TextureView() { } TextureView::TextureView(const TEXTURE_VIEW_DESC& desc) :mDesc(desc) { } }}
d4174b6c735ed506031b47563997ac5c280709f0
0298a3d2c1a8e262b7e28dfa520b873a5225549d
/labs14/n3/n3.cpp
cab683d4bbba18d0f9a91900dcfb9fd3f63b848c
[]
no_license
flerince/labsvvp
693550a211f4f75267a6fd6975a6e35b3bd89f36
086f48aef0f71615590f4dc0ec47c23a19ab590e
refs/heads/main
2023-02-10T04:01:14.893541
2021-01-08T00:19:38
2021-01-08T00:19:38
301,724,474
0
0
null
null
null
null
UTF-8
C++
false
false
321
cpp
#include <stdio.h> #include <locale.h> int main() { setlocale(LC_ALL, "Russian"); int i=0,N,K=0; printf("Введите число (N>1) \n"); scanf_s("%d", &N); while (i < N) { K++; i +=3; } printf("Наименьшее из целых чисел: %d \n", K); printf("Сумма: %d.\n", i); return 0; }
b10cc0fe73794e7cda336646e6284666099eb164
89ebb0e2d24c8ecdb760d6ced31480e9a1c0d72e
/Motor/Motor.h
0809828507cdc4d94db6a37395690c74f41fcbaa
[]
no_license
anothermist/LIBRARIES
81354e0900555727d7cdbf773b7ad32c47715deb
6fa83f34d9e1e79028e4f0233782e440e9374fe0
refs/heads/master
2021-01-12T03:47:11.165195
2019-09-10T00:08:07
2019-09-10T00:08:07
78,262,870
16
12
null
2019-11-02T18:11:25
2017-01-07T06:27:33
C
UTF-8
C++
false
false
207
h
#ifndef __MOTOR_H__ #define __MOTOR_H__ class Motor { public: Motor(int pin, bool isDigital); void on(); void off(); void setSpeed(float percent); protected: int outputPin; bool isDigital; }; #endif
0929c7754fd79005d1e5cf87ceb2415903de5967
c591b56220405b715c1aaa08692023fca61f22d4
/Disha/Milestone-11/Codewin/EvenoddSort.cpp
022ff7e50c118c64324953c02935e8988e205a98
[]
no_license
Girl-Code-It/Beginner-CPP-Submissions
ea99a2bcf8377beecba811d813dafc2593ea0ad9
f6c80a2e08e2fe46b2af1164189272019759935b
refs/heads/master
2022-07-24T22:37:18.878256
2021-11-16T04:43:08
2021-11-16T04:43:08
263,825,293
37
105
null
2023-06-05T09:16:10
2020-05-14T05:39:40
C++
UTF-8
C++
false
false
1,056
cpp
using namespace std; #include<iostream> int _sort(int a[50],int stop,int start) { int i,temp; for(i=start;i<stop;i++) { for(int j=i+1;j<stop;j++) { if(a[i]>a[j]) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } } } int main() { int a[50],siz,i,temp,even=0; cout<<"\n Enter the size of array :"; cin>>siz; for(i=0;i<siz;i++) { cout<<"Enter number "<<i+1<<" :"; cin>>a[i]; if(a[i]%2==0) even++; } for(i=0;i<siz;i++) { if(a[i]%2!=0) { for(int j=i+1;j<siz;j++) { if(a[j]%2==0) { temp=a[i]; a[i]=a[j]; a[j]=temp; break; } } } } _sort(a,even,0); _sort(a,siz,even); cout<<"\n Sorted array ="; for(i=0;i<siz;i++) { cout<<a[i]<<" "; } return 0; }
d61f6b1c56690a6d12c93788271e02f30798ae4e
31fee731dda88255aef19e4091a839a2c1a51a60
/Simulations_C++/GHAME3/class_functions.cpp
be1369778d13bbd5c172c1c87f588d0ffb19c456
[]
no_license
octoberskyTW/CADAC4_Enhance
3a4ebf99caabd8925fdbd6d54be3f26a0984ed01
8c7df72e54ea008fd68136e6d3f2726a12f666f1
refs/heads/master
2021-09-24T20:18:46.936445
2018-10-14T05:55:35
2018-10-14T06:21:35
152,942,886
4
3
null
null
null
null
UTF-8
C++
false
false
8,844
cpp
/////////////////////////////////////////////////////////////////////////////// //FILE: 'class_functions.cpp' // Member functions of 'Cadac' class hierarchy // Member functions of class 'Variable' // //010628 Created by Peter H Zipfel //011129 Adapted to SRAAM6 simulation, PZi //060510 Updated from F16C for CRUISE, PZi //100505 Modified for GHAME3, PZi /////////////////////////////////////////////////////////////////////////////// #include "class_hierarchy.hpp" #include "global_header.hpp" using namespace std; /////////////////////////////////////////////////////////////////////////////// //////////////// Member functions of 'Cadac' class hierarchy ////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// //Constructor initializing // //001220 Created by Peter H Zipfel //011129 Adapted to SRAAM6 simulation, PZi /////////////////////////////////////////////////////////////////////////////// Round3::Round3() { //creating module-variable array try{round3=new Variable[NROUND3];} catch(bad_alloc xa){cerr<<"*** Error: round3[] allocation failed ***\n";system("pause");exit(1);} //zeroing module-variable array for(int i=0;i<NROUND3;i++)round3[i].init("empty",0," "," "," "," "); } /////////////////////////////////////////////////////////////////////////////// //Constructor initializing the modules and the module-variable arrays //Reading input data from 'input.asc' and putting into 'round3' and 'cruise' arrays //Writing banners to screen, 'tabout.asc' and to 'traj.asc' files // //Module-variable arrays: // cruise[NCRUISE] contains variables of modules under class 'Cruise' // cruise3[ncruise3] contains variables of all modules with empty slots removed // scrn_cruise3[nscrn_cruise3] contains variables to be displayed at screen and 'tabout.asc' // plot_cruise3[nplot_cruise3] contains variables to be plotted, i.e., written to 'traj.asc' // com_cruise3[ncom_cruise3] contains variables for communication among vehicles // event_ptr_list[NEVENT] event pointer list // //Index pointer arrays: // round3_scrn_ind[round3_scrn_count]; // cruise_scrn_ind[cruise_scrn_count]; // round3_plot_ind[round3_plot_count]; // cruise_plot_ind[cruise_plot_count]; // round3_com_ind[round3_com_count]; // cruise_com_ind[cruise_com_count]; // //001220 Created by Peter H Zipfel //011129 Adapted to SRAAM6 simulation, PZi /////////////////////////////////////////////////////////////////////////////// Cruise::Cruise(Module *module_list,int num_modules) { //initializing coutners int i(0); int j(0); //creating module-variable array try{cruise=new Variable[NCRUISE];} catch(bad_alloc xa){cerr<<"*** Error: cruise[] allocation failed ***\n";system("pause");exit(1);} //zeroing module-variable array for(i=0;i<NCRUISE;i++)cruise[i].init("empty",0," "," "," "," "); //calling initializer modules to build 'round3' and 'cruise' arrays // and make other initial calculations in the following sequence //call the module definitions -MOD for (j=0;j<num_modules;j++) { if((module_list[j].name=="environment")&&(module_list[j].definition=="def")) def_environment(); else if((module_list[j].name=="newton")&&(module_list[j].definition=="def")) def_newton(); else if((module_list[j].name=="aerodynamics")&&(module_list[j].definition=="def")) def_aerodynamics(); else if((module_list[j].name=="propulsion")&&(module_list[j].definition=="def")) def_propulsion(); else if((module_list[j].name=="forces")&&(module_list[j].definition=="def")) def_forces(); } //sizing module-variable arrays 'cruise3','scrn_cruise3','plot_cruise3' arrays //their dimensions are the protected data:'ncruise3','nscrn_cruise3','nplot_cruise3' sizing_arrays(); //allocating dynamic memory to the module-variable arrays try{cruise3=new Variable[ncruise3];} catch(bad_alloc xa){cerr<<"*** Error: cruise3[] allocation failed *** \n";system("pause");exit(1);} try{scrn_cruise3=new Variable[nscrn_cruise3];} catch(bad_alloc xa){cerr<<"*** Error: scrn_cruise3[] allocation failed *** \n";system("pause");exit(1);} try{plot_cruise3=new Variable[nplot_cruise3];} catch(bad_alloc xa){cerr<<"*** Error: plot_cruise3[] allocation failed *** \n";system("pause");exit(1);} try{com_cruise3=new Variable[ncom_cruise3];} catch(bad_alloc xa){cerr<<"*** Error: com_cruise3[] allocation failed *** \n";system("pause");exit(1);} // allocating memory for the screen index arrays round3_scrn_ind=new int[round3_scrn_count]; cruise_scrn_ind=new int[cruise_scrn_count]; // allocating memory for the plot index arrays round3_plot_ind=new int[round3_plot_count]; cruise_plot_ind=new int[cruise_plot_count]; // allocating memory for the com index arrays round3_com_ind=new int[round3_com_count]; cruise_com_ind=new int[cruise_com_count]; //allocating memory to each event object in event object list for (i=0;i<NEVENT;i++) try{event_ptr_list[i]=new Event;} catch(bad_alloc xa){cerr<<"*** Error: 'event' object allocation failed *** \n";system("pause");exit(1);} //initializing the event array index nevent=0; event_total=0; event_time=0; //building 'cruise3' array (compacting and merging 'round3' and 'cruise' arrays) vehicle_array(); //building 'scrn_cruise3' array from 'cruise3' array scrn_array(); //building 'plot_cruise3' array from 'cruise3' array plot_array(); //building the index arrays of the data to be written to the screen scrn_index_arrays(); //building the index arrays of the data to be written to the 'ploti.asc' files plot_index_arrays(); //building the index arrays of the data to be loaded into the packets of 'combus' com_index_arrays(); } /////////////////////////////////////////////////////////////////////////////// //Destructor deallocating dynamic memory // //010115 Created by Peter H Zipfel //011129 Adapted to SRAAM6 simulation, PZi /////////////////////////////////////////////////////////////////////////////// Cruise::~Cruise() { delete [] cruise; delete [] cruise3; delete [] round3; delete [] scrn_cruise3; delete [] plot_cruise3; delete [] com_cruise3; delete [] round3_scrn_ind; delete [] cruise_scrn_ind; delete [] cruise_plot_ind; delete [] round3_com_ind; delete [] cruise_com_ind; delete [] &event_ptr_list; } /////////////////////////////////////////////////////////////////////////////// //////////////////// Members of class 'Vehicle' /////////////////////////////// /////////////////////////////////////////////////////////////////////////////// //Constructor of class 'Vehicle' //allocating dynamic memory for the array of pointers of type 'Cadac' //and returning the pointer to array // //010626 Created by Peter H Zipfel /////////////////////////////////////////////////////////////////////////////// Vehicle::Vehicle(int number) { capacity=number; try{vehicle_ptr=new Cadac *[capacity];} catch(bad_alloc xa){cerr<<"*** Error:'vehicle_ptr' allocation failed *** \n";system("pause");exit(1);} howmany=0; // cerr<<">>> inside constructor of 'Vehicle' <<<\n"; } /////////////////////////////////////////////////////////////////////////////// //Destructor of class 'Vehicle' //de-allocating dynamic memory of the pointer-array of type 'Cadac' // //010626 Created by Peter H Zipfel /////////////////////////////////////////////////////////////////////////////// Vehicle::~Vehicle() { // cerr<<">>> inside destructor of 'Vehicle' <<<\n"; delete [] vehicle_ptr; } /////////////////////////////////////////////////////////////////////////////// //Adding a vehicle pointer to the vehicle list // //010626 Created by Peter H Zipfel /////////////////////////////////////////////////////////////////////////////// void Vehicle::add_vehicle(Cadac &pt) { if(howmany<capacity) vehicle_ptr[howmany++]=&pt; } /////////////////////////////////////////////////////////////////////////////// //Overloading operator [] so that it returns a 'Cadac' pointer // //010626 Created by Peter H Zipfel /////////////////////////////////////////////////////////////////////////////// Cadac * Vehicle::operator[](int position) { if(position>=0 && position<howmany) return vehicle_ptr[position]; else { cout<<"*** Bad value: "<<position<<'\n'; return 0; } } /////////////////////////////////////////////////////////////////////////////// //Obtaining size of vehicle list (total number of vehicles) // //010626 Created by Peter H Zipfel /////////////////////////////////////////////////////////////////////////////// int Vehicle::size() { return howmany; }
58b91c89489c1de1e40812243ab62311e5fa12ff
395d1860e82bc75ccc04b91c4b9a8fa46276d9bb
/Source/Vision/Runtime/Base/Graphics/Headless/Direct3DTexture9Dummy.h
39f753f5bfce7384b7476aeec6cc60f7906a2050
[]
no_license
Hakhyun-Kim/projectanarchy
28ba7370050000a12e4305faa11d5deb77c330a1
ccea719afcb03967a68a169730b59e8a8a6c45f8
refs/heads/master
2021-06-03T04:41:22.814866
2013-11-07T07:21:03
2013-11-07T07:21:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,140
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2013 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #pragma once #include <d3d9.h> #include <Vision/Runtime/Base/Graphics/Headless/UnknownDummy.h> #include <Vision/Runtime/Base/VBase.hpp> class Direct3DTexture9Dummy : public IDirect3DTexture9, public UnknownDummy { public: Direct3DTexture9Dummy(D3DSURFACE_DESC* pDesc); virtual ~Direct3DTexture9Dummy(); HKV_NR_IMPLEMENT_IUNKNOWN; /*** IDirect3DBaseTexture9 methods ***/ STDMETHOD(GetDevice)(THIS_ IDirect3DDevice9** ppDevice) HKV_NR_UNIMPLEMENTED STDMETHOD(SetPrivateData)(THIS_ REFGUID refguid,CONST void* pData,DWORD SizeOfData,DWORD Flags) HKV_NR_UNIMPLEMENTED STDMETHOD(GetPrivateData)(THIS_ REFGUID refguid,void* pData,DWORD* pSizeOfData) HKV_NR_UNIMPLEMENTED STDMETHOD(FreePrivateData)(THIS_ REFGUID refguid) HKV_NR_UNIMPLEMENTED STDMETHOD_(DWORD, SetPriority)(THIS_ DWORD PriorityNew) HKV_NR_UNIMPLEMENTED STDMETHOD_(DWORD, GetPriority)(THIS) HKV_NR_UNIMPLEMENTED STDMETHOD_(void, PreLoad)(THIS) {} STDMETHOD_(D3DRESOURCETYPE, GetType)(THIS) {return D3DRESOURCETYPE();} STDMETHOD_(DWORD, SetLOD)(THIS_ DWORD LODNew) HKV_NR_UNIMPLEMENTED STDMETHOD_(DWORD, GetLOD)(THIS) HKV_NR_UNIMPLEMENTED STDMETHOD_(DWORD, GetLevelCount)(THIS) HKV_NR_UNIMPLEMENTED STDMETHOD(SetAutoGenFilterType)(THIS_ D3DTEXTUREFILTERTYPE FilterType) HKV_NR_UNIMPLEMENTED STDMETHOD_(D3DTEXTUREFILTERTYPE, GetAutoGenFilterType)(THIS) {return D3DTEXTUREFILTERTYPE();} STDMETHOD_(void, GenerateMipSubLevels)(THIS) {} STDMETHOD(GetLevelDesc)(THIS_ UINT Level,D3DSURFACE_DESC *pDesc) HKV_NR_UNIMPLEMENTED STDMETHOD(AddDirtyRect)(THIS_ CONST RECT* pDirtyRect) HKV_NR_UNIMPLEMENTED // Implemented STDMETHOD(GetSurfaceLevel)(THIS_ UINT Level,IDirect3DSurface9** ppSurfaceLevel) HKV_OVERRIDE; STDMETHOD(LockRect)(THIS_ UINT Level,D3DLOCKED_RECT* pLockedRect,CONST RECT* pRect,DWORD Flags) HKV_OVERRIDE; STDMETHOD(UnlockRect)(THIS_ UINT Level) HKV_OVERRIDE; private: Direct3DTexture9Dummy(); VSmartPtr<IDirect3DSurface9> m_spSurface; UBYTE* m_pLockedPointer; }; /* * Havok SDK - Base file, BUILD(#20131019) * * Confidential Information of Havok. (C) Copyright 1999-2013 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available from [email protected]. * */
3272bb1ccf862453357169c93fdb043a8c924523
ac1c9fbc1f1019efb19d0a8f3a088e8889f1e83c
/out/release/gen/third_party/blink/renderer/bindings/modules/v8/v8_geolocation_position_error.h
d757e7522c1f8388263e6b21f42d3ab32608b293
[ "BSD-3-Clause" ]
permissive
xueqiya/chromium_src
5d20b4d3a2a0251c063a7fb9952195cda6d29e34
d4aa7a8f0e07cfaa448fcad8c12b29242a615103
refs/heads/main
2022-07-30T03:15:14.818330
2021-01-16T16:47:22
2021-01-16T16:47:22
330,115,551
1
0
null
null
null
null
UTF-8
C++
false
false
2,879
h
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file has been auto-generated from the Jinja2 template // third_party/blink/renderer/bindings/templates/interface.h.tmpl // by the script code_generator_v8.py. // DO NOT MODIFY! // clang-format off #ifndef THIRD_PARTY_BLINK_RENDERER_BINDINGS_MODULES_V8_V8_GEOLOCATION_POSITION_ERROR_H_ #define THIRD_PARTY_BLINK_RENDERER_BINDINGS_MODULES_V8_V8_GEOLOCATION_POSITION_ERROR_H_ #include "third_party/blink/renderer/bindings/core/v8/generated_code_helper.h" #include "third_party/blink/renderer/bindings/core/v8/native_value_traits.h" #include "third_party/blink/renderer/bindings/core/v8/to_v8_for_core.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h" #include "third_party/blink/renderer/modules/geolocation/geolocation_position_error.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" #include "third_party/blink/renderer/platform/bindings/v8_dom_wrapper.h" #include "third_party/blink/renderer/platform/bindings/wrapper_type_info.h" #include "third_party/blink/renderer/platform/heap/handle.h" namespace blink { MODULES_EXPORT extern const WrapperTypeInfo v8_geolocation_position_error_wrapper_type_info; class V8GeolocationPositionError { STATIC_ONLY(V8GeolocationPositionError); public: MODULES_EXPORT static bool HasInstance(v8::Local<v8::Value>, v8::Isolate*); static v8::Local<v8::Object> FindInstanceInPrototypeChain(v8::Local<v8::Value>, v8::Isolate*); MODULES_EXPORT static v8::Local<v8::FunctionTemplate> DomTemplate(v8::Isolate*, const DOMWrapperWorld&); static GeolocationPositionError* ToImpl(v8::Local<v8::Object> object) { return ToScriptWrappable(object)->ToImpl<GeolocationPositionError>(); } MODULES_EXPORT static GeolocationPositionError* ToImplWithTypeCheck(v8::Isolate*, v8::Local<v8::Value>); MODULES_EXPORT static constexpr const WrapperTypeInfo* GetWrapperTypeInfo() { return &v8_geolocation_position_error_wrapper_type_info; } static constexpr int kInternalFieldCount = kV8DefaultWrapperInternalFieldCount; // Callback functions MODULES_EXPORT static void CodeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>&); MODULES_EXPORT static void MessageAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>&); static void InstallRuntimeEnabledFeaturesOnTemplate( v8::Isolate*, const DOMWrapperWorld&, v8::Local<v8::FunctionTemplate> interface_template); }; template <> struct V8TypeOf<GeolocationPositionError> { typedef V8GeolocationPositionError Type; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_BINDINGS_MODULES_V8_V8_GEOLOCATION_POSITION_ERROR_H_
50dda313388f2c191bcdb39d797f811a64b4a113
8f01f1f8003cbc0ad91ae1c28aa3bac7eba8e477
/src/game/server/ai_speech.cpp
19b03218d64311f27ad8605cbd9f2f646e16db50
[]
no_license
Demez/demez_source_2013
078aa1e7a64fe773f061ced1e9718320f377c6ba
8bc82ca51ed8716dc742f96fff7283e116ed8d1c
refs/heads/master
2020-06-27T22:32:02.598265
2020-05-05T02:20:41
2020-05-05T02:20:41
200,069,527
0
1
null
null
null
null
UTF-8
C++
false
false
26,689
cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "ai_speech.h" #include "game.h" #include "engine/IEngineSound.h" #include "KeyValues.h" #include "ai_basenpc.h" #include "AI_Criteria.h" #include "isaverestore.h" #include "sceneentity.h" // memdbgon must be the last include file in a .cpp file!!! #include <tier0/memdbgon.h> #define DEBUG_AISPEECH 1 #ifdef DEBUG_AISPEECH ConVar ai_debug_speech( "ai_debug_speech", "0" ); #define DebuggingSpeech() ai_debug_speech.GetBool() #else inline void SpeechMsg( ... ) {} #define DebuggingSpeech() (false) #endif extern ConVar rr_debugresponses; //----------------------------------------------------------------------------- CAI_TimedSemaphore g_AIFriendliesTalkSemaphore; CAI_TimedSemaphore g_AIFoesTalkSemaphore; ConceptHistory_t::~ConceptHistory_t() { delete response; response = NULL; } ConceptHistory_t::ConceptHistory_t( const ConceptHistory_t& src ) { timeSpoken = src.timeSpoken; response = NULL; if ( src.response ) { response = new AI_Response( *src.response ); } } ConceptHistory_t& ConceptHistory_t::operator =( const ConceptHistory_t& src ) { if ( this != &src ) { timeSpoken = src.timeSpoken; delete response; response = NULL; if ( src.response ) { response = new AI_Response( *src.response ); } } return *this; } BEGIN_SIMPLE_DATADESC( ConceptHistory_t ) DEFINE_FIELD( timeSpoken, FIELD_TIME ), // Relative to server time // DEFINE_EMBEDDED( response, FIELD_??? ), // This is manually saved/restored by the ConceptHistory saverestore ops below END_DATADESC() class CConceptHistoriesDataOps : public CDefSaveRestoreOps { public: virtual void Save( const SaveRestoreFieldInfo_t &fieldInfo, ISave *pSave ) { CUtlDict< ConceptHistory_t, int > *ch = ((CUtlDict< ConceptHistory_t, int > *)fieldInfo.pField); int count = ch->Count(); pSave->WriteInt( &count ); for ( int i = 0 ; i < count; i++ ) { ConceptHistory_t *pHistory = &(*ch)[ i ]; pSave->StartBlock(); { // Write element name pSave->WriteString( ch->GetElementName( i ) ); // Write data pSave->WriteAll( pHistory ); // Write response blob bool hasresponse = !!pHistory->response; pSave->WriteBool( &hasresponse ); if ( hasresponse ) { pSave->WriteAll( pHistory->response ); } // TODO: Could blat out pHistory->criteria pointer here, if it's needed } pSave->EndBlock(); } } virtual void Restore( const SaveRestoreFieldInfo_t &fieldInfo, IRestore *pRestore ) { CUtlDict< ConceptHistory_t, int > *ch = ((CUtlDict< ConceptHistory_t, int > *)fieldInfo.pField); int count = pRestore->ReadInt(); Assert( count >= 0 ); for ( int i = 0 ; i < count; i++ ) { char conceptname[ 512 ]; conceptname[ 0 ] = 0; ConceptHistory_t history; pRestore->StartBlock(); { pRestore->ReadString( conceptname, sizeof( conceptname ), 0 ); pRestore->ReadAll( &history ); bool hasresponse = false; pRestore->ReadBool( &hasresponse ); if ( hasresponse ) { history.response = new AI_Response(); pRestore->ReadAll( history.response ); } } pRestore->EndBlock(); // TODO: Could restore pHistory->criteria pointer here, if it's needed // Add to utldict if ( conceptname[0] != 0 ) { ch->Insert( conceptname, history ); } else { Assert( !"Error restoring ConceptHistory_t, discarding!" ); } } } virtual void MakeEmpty( const SaveRestoreFieldInfo_t &fieldInfo ) { } virtual bool IsEmpty( const SaveRestoreFieldInfo_t &fieldInfo ) { CUtlDict< ConceptHistory_t, int > *ch = ((CUtlDict< ConceptHistory_t, int > *)fieldInfo.pField); return ch->Count() == 0 ? true : false; } }; CConceptHistoriesDataOps g_ConceptHistoriesSaveDataOps; //----------------------------------------------------------------------------- // // CLASS: CAI_Expresser // BEGIN_SIMPLE_DATADESC( CAI_Expresser ) // m_pSink (reconnected on load) // DEFINE_FIELD( m_pOuter, CHandle < CBaseFlex > ), DEFINE_CUSTOM_FIELD( m_ConceptHistories, &g_ConceptHistoriesSaveDataOps ), DEFINE_FIELD( m_flStopTalkTime, FIELD_TIME ), DEFINE_FIELD( m_flStopTalkTimeWithoutDelay, FIELD_TIME ), DEFINE_FIELD( m_flBlockedTalkTime, FIELD_TIME ), DEFINE_FIELD( m_voicePitch, FIELD_INTEGER ), DEFINE_FIELD( m_flLastTimeAcceptedSpeak, FIELD_TIME ), END_DATADESC() //------------------------------------- bool CAI_Expresser::SemaphoreIsAvailable( CBaseEntity *pTalker ) { if ( !GetSink()->UseSemaphore() ) return true; CAI_TimedSemaphore *pSemaphore = GetMySpeechSemaphore( pTalker->MyNPCPointer() ); return (pSemaphore ? pSemaphore->IsAvailable( pTalker ) : true); } //------------------------------------- float CAI_Expresser::GetSemaphoreAvailableTime( CBaseEntity *pTalker ) { CAI_TimedSemaphore *pSemaphore = GetMySpeechSemaphore( pTalker->MyNPCPointer() ); return (pSemaphore ? pSemaphore->GetReleaseTime() : 0); } //------------------------------------- int CAI_Expresser::GetVoicePitch() const { return m_voicePitch + random->RandomInt(0,3); } #ifdef DEBUG static int g_nExpressers; #endif CAI_Expresser::CAI_Expresser( CBaseFlex *pOuter ) : m_pOuter( pOuter ), m_pSink( NULL ), m_flStopTalkTime( 0 ), m_flLastTimeAcceptedSpeak( 0 ), m_flBlockedTalkTime( 0 ), m_flStopTalkTimeWithoutDelay( 0 ), m_voicePitch( 100 ) { #ifdef DEBUG g_nExpressers++; #endif } CAI_Expresser::~CAI_Expresser() { m_ConceptHistories.Purge(); CAI_TimedSemaphore *pSemaphore = GetMySpeechSemaphore( GetOuter() ); if ( pSemaphore ) { if ( pSemaphore->GetOwner() == GetOuter() ) pSemaphore->Release(); #ifdef DEBUG g_nExpressers--; if ( g_nExpressers == 0 && pSemaphore->GetOwner() ) DevMsg( 2, "Speech semaphore being held by non-talker entity\n" ); #endif } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CAI_Expresser::TestAllResponses() { IResponseSystem *pResponseSystem = GetOuter()->GetResponseSystem(); if ( pResponseSystem ) { CUtlVector<AI_Response *> responses; pResponseSystem->GetAllResponses( &responses ); for ( int i = 0; i < responses.Count(); i++ ) { const char *szResponse = responses[i]->GetResponsePtr(); Msg( "Response: %s\n", szResponse ); SpeakDispatchResponse( "", *responses[i] ); } } } //----------------------------------------------------------------------------- static const int LEN_SPECIFIC_SCENE_MODIFIER = strlen( AI_SPECIFIC_SCENE_MODIFIER ); //----------------------------------------------------------------------------- // Purpose: Searches for a possible response // Input : concept - // NULL - // Output : AI_Response //----------------------------------------------------------------------------- bool CAI_Expresser::SpeakFindResponse( AI_Response &outResponse, AIConcept_t concept, const char *modifiers /*= NULL*/ ) { IResponseSystem *rs = GetOuter()->GetResponseSystem(); if ( !rs ) { Assert( !"No response system installed for CAI_Expresser::GetOuter()!!!" ); return false; } AI_CriteriaSet set; // Always include the concept name set.AppendCriteria( "concept", concept, CONCEPT_WEIGHT ); // Always include any optional modifiers if ( modifiers ) { char copy_modifiers[ 255 ]; const char *pCopy; char key[ 128 ] = { 0 }; char value[ 128 ] = { 0 }; Q_strncpy( copy_modifiers, modifiers, sizeof( copy_modifiers ) ); pCopy = copy_modifiers; while( pCopy ) { pCopy = SplitContext( pCopy, key, sizeof( key ), value, sizeof( value ), NULL ); if( *key && *value ) { set.AppendCriteria( key, value, CONCEPT_WEIGHT ); } } } // Let our outer fill in most match criteria GetOuter()->ModifyOrAppendCriteria( set ); // Append local player criteria to set, but not if this is a player doing the talking if ( !GetOuter()->IsPlayer() ) { CBasePlayer *pPlayer = UTIL_GetNearestPlayer( GetOuter()->GetAbsOrigin() ); if( pPlayer ) pPlayer->ModifyOrAppendPlayerCriteria( set ); } // Now that we have a criteria set, ask for a suitable response bool found = rs->FindBestResponse( set, outResponse, this ); if ( rr_debugresponses.GetInt() == 3 ) { if ( ( GetOuter()->MyNPCPointer() && GetOuter()->m_debugOverlays & OVERLAY_NPC_SELECTED_BIT ) || GetOuter()->IsPlayer() ) { const char *pszName = GetOuter()->IsPlayer() ? ((CBasePlayer*)GetOuter())->GetPlayerName() : GetOuter()->GetDebugName(); if ( found ) { const char *szReponse = outResponse.GetResponsePtr(); Warning( "RESPONSERULES: %s spoke '%s'. Found response '%s'.\n", pszName, concept, szReponse ); } else { Warning( "RESPONSERULES: %s spoke '%s'. Found no matching response.\n", pszName, concept ); } } } if ( !found ) return false; const char *szReponse = outResponse.GetResponsePtr(); if ( !szReponse[0] ) return false; if ( ( outResponse.GetOdds() < 100 ) && ( random->RandomInt( 1, 100 ) <= outResponse.GetOdds() ) ) return false; return true; } //----------------------------------------------------------------------------- // Purpose: Dispatches the result // Input : *response - //----------------------------------------------------------------------------- bool CAI_Expresser::SpeakDispatchResponse( AIConcept_t concept, AI_Response& response, IRecipientFilter *filter /* = NULL */ ) { bool spoke = false; float delay = response.GetDelay(); const char *szResponse = response.GetResponsePtr(); soundlevel_t soundlevel = response.GetSoundLevel(); if ( IsSpeaking() && concept[0] != 0 ) { DevMsg( "SpeakDispatchResponse: Entity ( %i/%s ) already speaking, forcing '%s'\n", GetOuter()->entindex(), STRING( GetOuter()->GetEntityName() ), concept ); // Tracker 15911: Can break the game if we stop an imported map placed lcs here, so only // cancel actor out of instanced scripted scenes. ywb RemoveActorFromScriptedScenes( GetOuter(), true /*instanced scenes only*/ ); GetOuter()->SentenceStop(); if ( IsRunningScriptedScene( GetOuter() ) ) { DevMsg( "SpeakDispatchResponse: Entity ( %i/%s ) refusing to speak due to scene entity, tossing '%s'\n", GetOuter()->entindex(), STRING( GetOuter()->GetEntityName() ), concept ); return false; } } switch ( response.GetType() ) { default: case RESPONSE_NONE: break; case RESPONSE_SPEAK: if ( !response.ShouldntUseScene() ) { // This generates a fake CChoreoScene wrapping the sound.txt name spoke = SpeakAutoGeneratedScene( szResponse, delay ); } else { float speakTime = GetResponseDuration( response ); GetOuter()->EmitSound( szResponse ); DevMsg( "SpeakDispatchResponse: Entity ( %i/%s ) playing sound '%s'\n", GetOuter()->entindex(), STRING( GetOuter()->GetEntityName() ), szResponse ); NoteSpeaking( speakTime, delay ); spoke = true; } break; case RESPONSE_SENTENCE: spoke = ( -1 != SpeakRawSentence( szResponse, delay, VOL_NORM, soundlevel ) ) ? true : false; break; case RESPONSE_SCENE: spoke = SpeakRawScene( szResponse, delay, &response, filter ); break; case RESPONSE_RESPONSE: // This should have been recursively resolved already Assert( 0 ); break; case RESPONSE_PRINT: if ( g_pDeveloper->GetInt() > 0 ) { Vector vPrintPos; GetOuter()->CollisionProp()->NormalizedToWorldSpace( Vector(0.5,0.5,1.0f), &vPrintPos ); NDebugOverlay::Text( vPrintPos, szResponse, true, 1.5 ); spoke = true; } break; } if ( spoke ) { m_flLastTimeAcceptedSpeak = gpGlobals->curtime; if ( DebuggingSpeech() && g_pDeveloper->GetInt() > 0 && response.GetType() != RESPONSE_PRINT ) { Vector vPrintPos; GetOuter()->CollisionProp()->NormalizedToWorldSpace( Vector(0.5,0.5,1.0f), &vPrintPos ); NDebugOverlay::Text( vPrintPos, CFmtStr( "%s: %s", concept, szResponse ), true, 1.5 ); } if ( response.IsApplyContextToWorld() ) { CBaseEntity *pEntity = CBaseEntity::Instance( engine->PEntityOfEntIndex( 0 ) ); if ( pEntity ) { pEntity->AddContext( response.GetContext() ); } } else { GetOuter()->AddContext( response.GetContext() ); } SetSpokeConcept( concept, &response ); } return spoke; } //----------------------------------------------------------------------------- // Purpose: // Input : *response - // Output : float //----------------------------------------------------------------------------- float CAI_Expresser::GetResponseDuration( AI_Response& response ) { const char *szResponse = response.GetResponsePtr(); switch ( response.GetType() ) { default: case RESPONSE_NONE: break; case RESPONSE_SPEAK: return GetOuter()->GetSoundDuration( szResponse, STRING( GetOuter()->GetModelName() ) ); case RESPONSE_SENTENCE: Assert( 0 ); return 999.0f; case RESPONSE_SCENE: return GetSceneDuration( szResponse ); case RESPONSE_RESPONSE: // This should have been recursively resolved already Assert( 0 ); break; case RESPONSE_PRINT: return 1.0; } return 0.0f; } //----------------------------------------------------------------------------- // Purpose: Placeholder for rules based response system // Input : concept - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CAI_Expresser::Speak( AIConcept_t concept, const char *modifiers /*= NULL*/, char *pszOutResponseChosen /* = NULL*/, size_t bufsize /* = 0 */, IRecipientFilter *filter /* = NULL */ ) { AI_Response response; bool result = SpeakFindResponse( response, concept, modifiers ); if ( !result ) return false; SpeechMsg( GetOuter(), "%s (%p) spoke %s (%f)\n", STRING(GetOuter()->GetEntityName()), GetOuter(), concept, gpGlobals->curtime ); bool spoke = SpeakDispatchResponse( concept, response, filter ); if ( pszOutResponseChosen ) { const char *szResponse = response.GetResponsePtr(); Q_strncpy( pszOutResponseChosen, szResponse, bufsize ); } return spoke; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CAI_Expresser::SpeakRawScene( const char *pszScene, float delay, AI_Response *response, IRecipientFilter *filter /* = NULL */ ) { float sceneLength = GetOuter()->PlayScene( pszScene, delay, response, filter ); if ( sceneLength > 0 ) { SpeechMsg( GetOuter(), "SpeakRawScene( %s, %f) %f\n", pszScene, delay, sceneLength ); #if defined( HL2_EPISODIC ) || defined( TF_DLL ) char szInstanceFilename[256]; GetOuter()->GenderExpandString( pszScene, szInstanceFilename, sizeof( szInstanceFilename ) ); // Only mark ourselves as speaking if the scene has speech if ( GetSceneSpeechCount(szInstanceFilename) > 0 ) { NoteSpeaking( sceneLength, delay ); } #else NoteSpeaking( sceneLength, delay ); #endif return true; } return false; } // This will create a fake .vcd/CChoreoScene to wrap the sound to be played bool CAI_Expresser::SpeakAutoGeneratedScene( char const *soundname, float delay ) { float speakTime = GetOuter()->PlayAutoGeneratedSoundScene( soundname ); if ( speakTime > 0 ) { SpeechMsg( GetOuter(), "SpeakAutoGeneratedScene( %s, %f) %f\n", soundname, delay, speakTime ); NoteSpeaking( speakTime, delay ); return true; } return false; } //------------------------------------- int CAI_Expresser::SpeakRawSentence( const char *pszSentence, float delay, float volume, soundlevel_t soundlevel, CBaseEntity *pListener ) { int sentenceIndex = -1; if ( !pszSentence ) return sentenceIndex; if ( pszSentence[0] == AI_SP_SPECIFIC_SENTENCE ) { sentenceIndex = SENTENCEG_Lookup( pszSentence ); if( sentenceIndex == -1 ) { // sentence not found return -1; } CPASAttenuationFilter filter( GetOuter(), soundlevel ); CBaseEntity::EmitSentenceByIndex( filter, GetOuter()->entindex(), CHAN_VOICE, sentenceIndex, volume, soundlevel, 0, GetVoicePitch()); } else { sentenceIndex = SENTENCEG_PlayRndSz( GetOuter()->NetworkProp()->edict(), pszSentence, volume, soundlevel, 0, GetVoicePitch() ); } SpeechMsg( GetOuter(), "SpeakRawSentence( %s, %f) %f\n", pszSentence, delay, engine->SentenceLength( sentenceIndex ) ); NoteSpeaking( engine->SentenceLength( sentenceIndex ), delay ); return sentenceIndex; } //------------------------------------- void CAI_Expresser::BlockSpeechUntil( float time ) { SpeechMsg( GetOuter(), "BlockSpeechUntil(%f) %f\n", time, time - gpGlobals->curtime ); m_flBlockedTalkTime = time; } //------------------------------------- void CAI_Expresser::NoteSpeaking( float duration, float delay ) { duration += delay; GetSink()->OnStartSpeaking(); if ( duration <= 0 ) { // no duration :( m_flStopTalkTime = gpGlobals->curtime + 3; duration = 0; } else { m_flStopTalkTime = gpGlobals->curtime + duration; } m_flStopTalkTimeWithoutDelay = m_flStopTalkTime - delay; SpeechMsg( GetOuter(), "NoteSpeaking( %f, %f ) (stop at %f)\n", duration, delay, m_flStopTalkTime ); if ( GetSink()->UseSemaphore() ) { CAI_TimedSemaphore *pSemaphore = GetMySpeechSemaphore( GetOuter() ); if ( pSemaphore ) { pSemaphore->Acquire( duration, GetOuter() ); } } } //------------------------------------- void CAI_Expresser::ForceNotSpeaking( void ) { if ( IsSpeaking() ) { m_flStopTalkTime = gpGlobals->curtime; m_flStopTalkTimeWithoutDelay = gpGlobals->curtime; CAI_TimedSemaphore *pSemaphore = GetMySpeechSemaphore( GetOuter() ); if ( pSemaphore ) { if ( pSemaphore->GetOwner() == GetOuter() ) { pSemaphore->Release(); } } } } //------------------------------------- bool CAI_Expresser::IsSpeaking( void ) { if ( m_flStopTalkTime > gpGlobals->curtime ) SpeechMsg( GetOuter(), "IsSpeaking() %f\n", m_flStopTalkTime - gpGlobals->curtime ); if ( m_flLastTimeAcceptedSpeak == gpGlobals->curtime ) // only one speak accepted per think return true; return ( m_flStopTalkTime > gpGlobals->curtime ); } //------------------------------------- bool CAI_Expresser::CanSpeak() { if ( m_flLastTimeAcceptedSpeak == gpGlobals->curtime ) // only one speak accepted per think return false; float timeOk = MAX( m_flStopTalkTime, m_flBlockedTalkTime ); return ( timeOk <= gpGlobals->curtime ); } //----------------------------------------------------------------------------- // Purpose: Returns true if it's ok for this entity to speak after himself. // The base CanSpeak() includes the default speech delay, and won't // return true until that delay time has passed after finishing the // speech. This returns true as soon as the speech finishes. //----------------------------------------------------------------------------- bool CAI_Expresser::CanSpeakAfterMyself() { if ( m_flLastTimeAcceptedSpeak == gpGlobals->curtime ) // only one speak accepted per think return false; float timeOk = MAX( m_flStopTalkTimeWithoutDelay, m_flBlockedTalkTime ); return ( timeOk <= gpGlobals->curtime ); } //------------------------------------- bool CAI_Expresser::CanSpeakConcept( AIConcept_t concept ) { // Not in history? int iter = m_ConceptHistories.Find( concept ); if ( iter == m_ConceptHistories.InvalidIndex() ) { return true; } ConceptHistory_t *history = &m_ConceptHistories[iter]; Assert( history ); AI_Response *response = history->response; if ( !response ) return true; if ( response->GetSpeakOnce() ) return false; float respeakDelay = response->GetRespeakDelay(); if ( respeakDelay != 0.0f ) { if ( history->timeSpoken != -1 && ( gpGlobals->curtime < history->timeSpoken + respeakDelay ) ) return false; } return true; } //------------------------------------- bool CAI_Expresser::SpokeConcept( AIConcept_t concept ) { return GetTimeSpokeConcept( concept ) != -1.f; } //------------------------------------- float CAI_Expresser::GetTimeSpokeConcept( AIConcept_t concept ) { int iter = m_ConceptHistories.Find( concept ); if ( iter == m_ConceptHistories.InvalidIndex() ) return -1; ConceptHistory_t *h = &m_ConceptHistories[iter]; return h->timeSpoken; } //------------------------------------- void CAI_Expresser::SetSpokeConcept( AIConcept_t concept, AI_Response *response, bool bCallback ) { int idx = m_ConceptHistories.Find( concept ); if ( idx == m_ConceptHistories.InvalidIndex() ) { ConceptHistory_t h; h.timeSpoken = gpGlobals->curtime; idx = m_ConceptHistories.Insert( concept, h ); } ConceptHistory_t *slot = &m_ConceptHistories[ idx ]; slot->timeSpoken = gpGlobals->curtime; // Update response info if ( response ) { delete slot->response; slot->response = new AI_Response( *response ); } if ( bCallback ) GetSink()->OnSpokeConcept( concept, response ); } //------------------------------------- void CAI_Expresser::ClearSpokeConcept( AIConcept_t concept ) { m_ConceptHistories.Remove( concept ); } //------------------------------------- void CAI_Expresser::DumpHistories() { int c = 1; for ( int i = m_ConceptHistories.First(); i != m_ConceptHistories.InvalidIndex(); i = m_ConceptHistories.Next(i ) ) { ConceptHistory_t *h = &m_ConceptHistories[ i ]; DevMsg( "%i: %s at %f\n", c++, m_ConceptHistories.GetElementName( i ), h->timeSpoken ); } } //------------------------------------- bool CAI_Expresser::IsValidResponse( ResponseType_t type, const char *pszValue ) { if ( type == RESPONSE_SCENE ) { char szInstanceFilename[256]; GetOuter()->GenderExpandString( pszValue, szInstanceFilename, sizeof( szInstanceFilename ) ); return ( GetSceneDuration( szInstanceFilename ) > 0 ); } return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CAI_TimedSemaphore *CAI_Expresser::GetMySpeechSemaphore( CBaseEntity *pNpc ) { if ( !pNpc->MyNPCPointer() ) return NULL; return (pNpc->MyNPCPointer()->IsPlayerAlly() ? &g_AIFriendliesTalkSemaphore : &g_AIFoesTalkSemaphore ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CAI_Expresser::SpeechMsg( CBaseEntity *pFlex, const char *pszFormat, ... ) { if ( !DebuggingSpeech() ) return; char string[ 2048 ]; va_list argptr; va_start( argptr, pszFormat ); Q_vsnprintf( string, sizeof(string), pszFormat, argptr ); va_end( argptr ); if ( pFlex->MyNPCPointer() ) { DevMsg( pFlex->MyNPCPointer(), "%s", string ); } else { DevMsg( "%s", string ); } UTIL_LogPrintf( "%s", string ); } //----------------------------------------------------------------------------- void CAI_ExpresserHost_NPC_DoModifyOrAppendCriteria( CAI_BaseNPC *pSpeaker, AI_CriteriaSet& set ) { // Append current activity name const char *pActivityName = pSpeaker->GetActivityName( pSpeaker->GetActivity() ); if ( pActivityName ) { set.AppendCriteria( "activity", pActivityName ); } static const char *pStateNames[] = { "None", "Idle", "Alert", "Combat", "Scripted", "PlayDead", "Dead" }; if ( (int)pSpeaker->m_NPCState < ARRAYSIZE(pStateNames) ) { set.AppendCriteria( "npcstate", UTIL_VarArgs( "[NPCState::%s]", pStateNames[pSpeaker->m_NPCState] ) ); } if ( pSpeaker->GetEnemy() ) { set.AppendCriteria( "enemy", pSpeaker->GetEnemy()->GetClassname() ); set.AppendCriteria( "timesincecombat", "-1" ); } else { if ( pSpeaker->GetLastEnemyTime() == 0.0 ) set.AppendCriteria( "timesincecombat", "999999.0" ); else set.AppendCriteria( "timesincecombat", UTIL_VarArgs( "%f", gpGlobals->curtime - pSpeaker->GetLastEnemyTime() ) ); } set.AppendCriteria( "speed", UTIL_VarArgs( "%.3f", pSpeaker->GetSmoothedVelocity().Length() ) ); CBaseCombatWeapon *weapon = pSpeaker->GetActiveWeapon(); if ( weapon ) { set.AppendCriteria( "weapon", weapon->GetClassname() ); } else { set.AppendCriteria( "weapon", "none" ); } CBasePlayer *pPlayer = UTIL_GetNearestPlayer( pSpeaker->GetAbsOrigin() ); if ( pPlayer ) { Vector distance = pPlayer->GetAbsOrigin() - pSpeaker->GetAbsOrigin(); set.AppendCriteria( "distancetoplayer", UTIL_VarArgs( "%f", distance.Length() ) ); } else { set.AppendCriteria( "distancetoplayer", UTIL_VarArgs( "%i", MAX_COORD_RANGE ) ); } if ( pSpeaker->HasCondition( COND_SEE_PLAYER ) ) { set.AppendCriteria( "seeplayer", "1" ); } else { set.AppendCriteria( "seeplayer", "0" ); } if ( pPlayer && pPlayer->FInViewCone( pSpeaker ) && pPlayer->FVisible( pSpeaker ) ) { set.AppendCriteria( "seenbyplayer", "1" ); } else { set.AppendCriteria( "seenbyplayer", "0" ); } } //----------------------------------------------------------------------------- //============================================================================= // HPE_BEGIN: // [Forrest] Remove npc_speakall from Counter-Strike. //============================================================================= #ifndef CSTRIKE_DLL extern CBaseEntity *FindPickerEntity( CBasePlayer *pPlayer ); CON_COMMAND( npc_speakall, "Force the npc to try and speak all their responses" ) { if ( !UTIL_IsCommandIssuedByServerAdmin() ) return; CBaseEntity *pEntity; if ( args[1] && *args[1] ) { pEntity = gEntList.FindEntityByName( NULL, args[1], NULL ); if ( !pEntity ) { pEntity = gEntList.FindEntityByClassname( NULL, args[1] ); } } else { pEntity = FindPickerEntity( UTIL_GetCommandClient() ); } if ( pEntity ) { CAI_BaseNPC *pNPC = pEntity->MyNPCPointer(); if (pNPC) { if ( pNPC->GetExpresser() ) { bool save = engine->LockNetworkStringTables( false ); pNPC->GetExpresser()->TestAllResponses(); engine->LockNetworkStringTables( save ); } } } } #endif //============================================================================= // HPE_END //============================================================================= //----------------------------------------------------------------------------- CMultiplayer_Expresser::CMultiplayer_Expresser( CBaseFlex *pOuter ) : CAI_Expresser( pOuter ) { m_bAllowMultipleScenes = false; } bool CMultiplayer_Expresser::IsSpeaking( void ) { if ( m_bAllowMultipleScenes ) { return false; } return CAI_Expresser::IsSpeaking(); } void CMultiplayer_Expresser::AllowMultipleScenes() { m_bAllowMultipleScenes = true; } void CMultiplayer_Expresser::DisallowMultipleScenes() { m_bAllowMultipleScenes = false; }
ec7ec6af7359e56c1796cff255126b687edd1e7c
d84967ba1e6adc72e120f84524c51ad57912df5a
/devel/electron8/files/patch-components_sync__device__info_local__device__info__util.cc
04de0f1adb1dc3dde432ea8d98b245e29ae08a3a
[]
no_license
tagattie/FreeBSD-Electron
f191d03c067d03ad3007e7748de905da06ba67f9
af26f766e772bb04db5eb95148ee071101301e4e
refs/heads/master
2023-09-04T10:56:17.446818
2023-09-04T09:03:11
2023-09-04T09:03:11
176,520,396
73
9
null
2023-08-31T03:29:16
2019-03-19T13:41:20
C++
UTF-8
C++
false
false
582
cc
--- components/sync_device_info/local_device_info_util.cc.orig 2020-03-03 07:02:58 UTC +++ components/sync_device_info/local_device_info_util.cc @@ -19,7 +19,7 @@ std::string GetPersonalizableDeviceNameInternal(); sync_pb::SyncEnums::DeviceType GetLocalDeviceType() { #if defined(OS_CHROMEOS) return sync_pb::SyncEnums_DeviceType_TYPE_CROS; -#elif defined(OS_LINUX) +#elif defined(OS_LINUX) || defined(OS_BSD) return sync_pb::SyncEnums_DeviceType_TYPE_LINUX; #elif defined(OS_ANDROID) || defined(OS_IOS) return ui::GetDeviceFormFactor() == ui::DEVICE_FORM_FACTOR_TABLET
8af7031f440c67c4ac21c6d36e60085ed003cadf
2bf70fea41c01477d93fa4f6cb64809a74e643e0
/uva10070/main.cpp
f88a66a83378b437b6568f1dc878b7ad77046309
[]
no_license
Shafiahuma/UVA
3f6fc1517f1e0c09b4e8fcb8f383e8a3e6975a8e
94b179366fc33a6aac3f7465be3a3fa569816144
refs/heads/main
2023-04-26T00:32:54.148880
2021-05-24T07:03:00
2021-05-24T07:03:00
370,254,559
0
0
null
null
null
null
UTF-8
C++
false
false
549
cpp
#include <bits/stdc++.h> using namespace std; long long int sumo(string s) { } int main() { string s; long long int n,temp; n=s.length(); while(cin>>s) { if(s[n-1]==0 && s[n-2]==0) { temp=(2*(s[n-4]-48))+(s[n-3]-48); if(temp%4==0) cout<<"This is leap year."<<endl; } else { temp=(2*(s[n-2]-48))+(s[n-1]-48); if(temp%4==0) cout<<"This is leap year."<<endl; } if(s[n-1]==5 || s[n-1]==0) { } } return 0; }
2cf8466c3192a2e55776bd65f0658c5bcc516aad
7481cd579dbd72999141a2533cfab5414a9af059
/src/training/actions/activate_action.h
826ee2a4c8b9e2d9049f6e62fbd45e3e24ac4fe3
[]
no_license
Omegastick/bots
36d9c99ede06aed54fc66b6a8bc0b493924e3c34
25342bbeec18c228bd1ec5350573a1e4bee11337
refs/heads/master
2022-04-13T20:36:46.847747
2020-04-14T12:09:07
2020-04-14T12:09:07
150,558,810
1
1
null
null
null
null
UTF-8
C++
false
false
282
h
#pragma once #include "training/actions/iaction.h" namespace ai { class IActivatable; class ActivateAction : public IAction { public: ActivateAction(IActivatable *module); ~ActivateAction(); virtual void act(std::vector<int> flags); IActivatable *module; }; }
4eb4628ef7b4ee87694f4706a8e934df9c094bd4
ab4207e621d4603a3826db8deebea09e7ba987cf
/src/odom_estimator_main.cpp
2c7d65dec2279c7dd117dbe24d0867b6eb01e603
[]
no_license
bellz867/icl_stationary
b87e04ab32d0829b86e99c7c5897a78d22fade5e
514d9d07b3dfbfb0d76344f535ca6794547288ab
refs/heads/master
2023-06-14T00:48:42.127705
2021-07-07T15:21:40
2021-07-07T15:21:40
188,481,454
1
0
null
null
null
null
UTF-8
C++
false
false
360
cpp
#include <ros/ros.h> #include <odom_estimator.h> int main(int argc, char** argv) { ros::init(argc, argv, "odom_estimator_node"); OdomEstimator odomEstimator; //ros::AsyncSpinner spinner(4); //spinner.start(); //ros::waitForShutdown(); //ros::MultiThreadedSpinner spinner(4); //spinner.spin(); ros::spin(); return 0; }
a91132a980fed443d43fa44cce4cf475825ea7fc
624511f6ad0cf17a2ba1a1ea1f25c3b139ce4295
/baselib/lib/ullib/src/comlog/test/test2.cpp
4a254be82a5db997e49dec6d129be84793d9a5cc
[]
no_license
lightchainone/lightchain
7d90338d4a4e8d31d550c07bf380c06580941334
6fc7019c76a8b60d4fd63fba58fa79858856f66b
refs/heads/master
2021-05-11T05:47:17.672527
2019-12-16T09:51:39
2019-12-16T09:51:39
117,969,593
23
6
null
null
null
null
GB18030
C++
false
false
1,192
cpp
#include "com_log_if.h" int main() { //设置接受的日志等级 com_logstat_t logstat; logstat.sysevents = 16; snprintf(logstat.userevents, sizeof(logstat.userevents), "xiaowei,faint"); //创建设备 com_device_t dev[3]; //本地日志 snprintf(dev[0].host, sizeof(dev[0].host), "log"); snprintf(dev[0].file, sizeof(dev[0].file), "test2.log"); //dev[0].type = COM_ULLOGDEVICE; strcpy(dev[0].type, "ULLOG"); dev[0].log_size = 2048; COMLOG_SETSYSLOG(dev[0]); //设置自定义日志支持xiaow和faint日志 set_comdevice_selflog(dev, "xiaowei,faint"); //网络日志 snprintf(dev[1].host, sizeof(dev[1].host), "127.0.0.1:2121/log"); snprintf(dev[1].file, sizeof(dev[1].file), "test2.log"); //dev[1].type = COM_ULNETDEVICE; strcpy(dev[1].type, "ULNET"); COMLOG_SETSYSLOG(dev[1]); set_comdevice_selflog(dev+1, "xiaowei,faint"); //tty日志 //dev[2].type = COM_TTYDEVICE; strcpy(dev[2].type, "TTY"); #if 1 //打开设备 int ret = com_openlog("test2", dev, 2, &logstat); if (ret != 0) { fprintf(stderr, "open log err"); return -1; } #endif com_writelog(COMLOG_NOTICE, "hello comlog"); com_closelog(); return 0; } /* vim: set ts=4 sw=4 sts=4 tw=100 */
d7ae330d32d2f6f0d0ed259dd765d2f222b59427
43a2fbc77f5cea2487c05c7679a30e15db9a3a50
/Cpp/Internal/SDK/wld_sea_rock_cluster_h_classes.h
1e68d9afe1857dc7f39ea7a547181d8df43035b3
[]
no_license
zH4x/SoT-Insider-SDK
57e2e05ede34ca1fd90fc5904cf7a79f0259085c
6bff738a1b701c34656546e333b7e59c98c63ad7
refs/heads/main
2023-06-09T23:10:32.929216
2021-07-07T01:34:27
2021-07-07T01:34:27
383,638,719
0
0
null
null
null
null
UTF-8
C++
false
false
3,132
h
#pragma once // Name: SoT-Insider, Version: 1.102.2382.0 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass wld_sea_rock_cluster_h.wld_sea_rock_cluster_h_C // 0x0058 (FullSize[0x0428] - InheritedSize[0x03D0]) class Awld_sea_rock_cluster_h_C : public AActor { public: class UStaticMeshComponent* StaticMeshComponent07; // 0x03D0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor) class UStaticMeshComponent* StaticMeshComponent05; // 0x03D8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor) class UStaticMeshComponent* StaticMeshComponent09; // 0x03E0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor) class UStaticMeshComponent* StaticMeshComponent04; // 0x03E8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor) class UStaticMeshComponent* StaticMeshComponent01; // 0x03F0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor) class UStaticMeshComponent* StaticMeshComponent08; // 0x03F8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor) class UStaticMeshComponent* StaticMeshComponent06; // 0x0400(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor) class UStaticMeshComponent* StaticMeshComponent03; // 0x0408(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor) class UStaticMeshComponent* StaticMeshComponent02; // 0x0410(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor) class UStaticMeshComponent* StaticMeshComponent0; // 0x0418(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor) class USceneComponent* SharedRoot; // 0x0420(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor) static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass wld_sea_rock_cluster_h.wld_sea_rock_cluster_h_C"); return ptr; } void UserConstructionScript(); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
6272766e26662da8b883a23255253db78b3223b2
0f5e1ff7973c59bcd68958ee8f7d983d0dde5d3f
/09000~9999/9205_맥주 마시면서 걸어가기.cpp
0c0e62ed6c5656ddbb515be04a55f89b8b8ab9e6
[]
no_license
PowerNeverEnds/BaekjoonOnlineJudge_Cpp
f87909380f64489192e8161b7fdbf9b2d0e8263a
9e5eb8cebf921e41a266f1386e85ea0cf202f5e4
refs/heads/master
2023-02-09T19:39:42.727356
2021-01-02T14:37:27
2021-01-02T14:37:27
324,267,010
3
0
null
null
null
null
UHC
C++
false
false
1,662
cpp
#include <iostream> #include <vector> #include <climits> #include <cmath> #include <algorithm> #define INF 1e9 using namespace std; struct MyStruct { int y; int x; }; int getDist(MyStruct a, MyStruct b) { return abs(a.y - b.y) + abs(a.x - b.x); } int main() { cin.tie(NULL); ios_base::sync_with_stdio(false); int t; cin >> t; bool* out = new bool[(long long)t]; fill(out, out + t, false); for (int o = 0; o < t; o++) { vector<MyStruct> vec; int n; cin >> n; // i0: 상근이, i1,...,in:편의점, in+1: 펜타포트 for (int i = 0; i < n + 2; i++) { int x, y; cin >> x >> y; vec.push_back(MyStruct{ y,x }); } int** d = new int* [(long long)n + 2]; for (int i = 0; i < n + 2; i++) { d[i] = new int[(long long)n + 2]; fill(d[i], d[i] + n + 2, INF); } for (int i = 0; i < n + 2; i++) { for (int j = 0; j < n + 2; j++) { int dist = getDist(vec[i], vec[j]); if (dist <= 1000) { d[i][j] = dist; // 이거 dist대신에 1해도됨 d[j][i] = dist; // 여기 jj 되어있어서 틀렸습니다 나옴 } } } for (int i = 0; i < n + 2; i++) { d[i][i] = 0; } for (int k = 0; k < n + 2; k++) { for (int i = 0; i < n + 2; i++) { for (int j = 0; j < n + 2; j++) { d[i][j] = min(d[i][j], d[i][k] + d[k][j]); } } } if (d[0][n + 1] != INF) { out[o] = true; } //for (int i = 0; i < n + 2; i++) //{ // for (int j = 0; j < n + 2; j++) // { // cout << (d[i][j] != INF ? d[i][j] : -1) << " "; // } // cout << "\n"; //} } for (int i = 0; i < t; i++) { cout << (out[i] ? "happy" : "sad") << "\n"; } return 0; }
5eab1ffe6af0aadfea9df6596ff216d64128a51c
ad841e7cbd7e7cd2bfb59770a93b4a0a0c0cd0db
/include/mimedecode/object.h
e73f446cc43de7764854cba599b746d821c10c69
[ "MIT" ]
permissive
cybermaggedon/mimedecode
c2137e19de263ef39a4be6dda6d22586d277c307
71f532c9b7185999f7459a95510d1771ab11b628
refs/heads/master
2020-06-23T17:34:21.498022
2014-11-02T22:35:28
2014-11-02T22:35:28
198,699,814
0
0
null
null
null
null
UTF-8
C++
false
false
687
h
#ifndef OBJECT_H #define OBJECT_H #include <string> #include <list> #include <sys/types.h> #include <mimedecode/field.h> namespace mime { /** This object describes a MIME object. */ class object { public: /** The default constructor. */ object() { parent = 0; } /** The object's major type, derived from the MIME type e.g. "text" */ std::string type; /** The object's minor type, derived from the MIME type e.g. "plain" */ std::string subtype; /** All fields from the object's header */ std::map<std::string,field> fields; /** Pointer to the parent object, if one exists. */ object* parent; }; } #endif
d63f27a034cab25479fec3cf8f70e68ec6345478
9bc92c4616d4dc30918b54e99bd0ece08c77ce11
/project/Project11/ArifmeticheskieOperaziiSPrisvaivaniem.cpp
512e05d2e059a39b4f3b7d88876ba20a2cd77690
[]
no_license
StasBeep/programs-CPP-Lafore
90977d7de9291992c2454c1b93a0f38c445b2ccb
3771c5c86f0786d77e07c5c46e2909b7c366a03b
refs/heads/main
2023-03-19T06:52:36.182806
2021-03-06T00:14:09
2021-03-06T00:14:09
344,962,693
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
820
cpp
// assign.cpp // применение арифметических операций с присваиванием #include <iostream> using namespace std; int main() { int ans = 27; cout << "ans = " << ans << endl; ans += 10; // тоже самое,что и ans = ans + 10; cout << "ans + 10 = " << ans << endl; //37 ans -= 7; // тоже самое,что и ans = ans - 7; cout << "ans - 7 = " << ans << endl; //30 ans *= 2; // тоже самое,что и ans = ans * 2; cout << "ans * 2 = " << ans << endl; //60 ans /= 3; // тоже самое,что и ans = ans / 3; cout << "ans / 3 = " << ans << endl; //20 ans %= 3; // тоже самое,что и ans = ans % 3; cout << "ans % 3 = " << ans << endl; //2 // Инкремент ++ans; cout << "+1 = " << ans; return 0; }
2f370ef8fb58324f33b61fa64f796532077f3de4
814621dbf05f98a1d140c956c07ba5a6cd7e20bd
/src/mpvss/mpvss.cpp
fee4e010cd5f97b460418edb39a8dbbcae8c8363
[ "MIT" ]
permissive
sunny023/BigBang
64a308d340f1705a9161784c87c732a3a7a06dff
8a41582df5320b0c08fa4db2b143528bb219130c
refs/heads/master
2020-09-09T14:52:46.127960
2019-09-29T04:07:57
2019-09-29T04:07:57
221,476,302
1
0
MIT
2019-11-13T14:20:08
2019-11-13T14:20:07
null
UTF-8
C++
false
false
11,001
cpp
// Copyright (c) 2019 The Bigbang developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "mpvss.h" #include <iostream> #include <stdlib.h> #include "mpinterpolation.h" #include "util.h" using namespace std; using namespace xengine; ////////////////////////////// // CMPParticipant CMPParticipant::CMPParticipant() { } CMPParticipant::CMPParticipant(const CMPCandidate& candidate, size_t nIndexIn, const uint256& nSharedKeyIn) : nWeight(candidate.nWeight), nIndex(nIndexIn), sBox(candidate.sBox), nSharedKey(nSharedKeyIn) { } const uint256 CMPParticipant::Encrypt(const uint256& data) const { return (nSharedKey ^ data); } const uint256 CMPParticipant::Decrypt(const uint256& cipher) const { return (nSharedKey ^ cipher); } bool CMPParticipant::AcceptShare(size_t nThresh, size_t nIndexIn, const vector<uint256>& vEncrypedShare) { vShare.resize(vEncrypedShare.size()); for (size_t i = 0; i < vEncrypedShare.size(); i++) { vShare[i] = Decrypt(vEncrypedShare[i]); if (!sBox.VerifyPolynomial(nIndexIn + i, vShare[i])) { vShare.clear(); return false; } } return true; } bool CMPParticipant::VerifyShare(size_t nThresh, size_t nIndexIn, const vector<uint256>& vShare) { for (size_t i = 0; i < vShare.size(); i++) { if (!sBox.VerifyPolynomial(nIndexIn + i, vShare[i])) { return false; } } return true; } void CMPParticipant::PrepareVerification(std::size_t nThresh, std::size_t nLastIndex) { sBox.PrecalcPolynomial(nThresh, nLastIndex); } ////////////////////////////// // CMPSecretShare CMPSecretShare::CMPSecretShare() { nIndex = 0; nThresh = 0; nWeight = 0; } CMPSecretShare::CMPSecretShare(const uint256& nIdentIn) : nIdent(nIdentIn) { nIndex = 0; nThresh = 0; nWeight = 0; } void CMPSecretShare::RandGeneretor(uint256& r) { uint8_t* p = r.begin(); for (int i = 0; i < 32; i++) { *p++ = rand(); } } const uint256 CMPSecretShare::RandShare() { uint256 r; RandGeneretor(r); r[7] &= 0x0FFFFFFFULL; return r; } bool CMPSecretShare::GetParticipantRange(const uint256& nIdentIn, size_t& nIndexRet, size_t& nWeightRet) { if (nIdentIn == nIdent) { nIndexRet = nIndex; nWeightRet = nWeight; return true; } map<uint256, CMPParticipant>::iterator it = mapParticipant.find(nIdentIn); if (it == mapParticipant.end()) { return false; } nIndexRet = (*it).second.nIndex; nWeightRet = (*it).second.nWeight; return true; } void CMPSecretShare::Setup(size_t nMaxThresh, CMPSealedBox& sealed) { myBox.vCoeff.clear(); myBox.vCoeff.resize(nMaxThresh); do { myBox.nPrivKey = RandShare(); for (int i = 0; i < nMaxThresh; i++) { myBox.vCoeff[i] = RandShare(); } } while (!myBox.MakeSealedBox(sealed, nIdent, RandShare())); nIndex = 0; nThresh = 0; nWeight = 0; mapParticipant.clear(); mapOpenedShare.clear(); } void CMPSecretShare::SetupWitness() { myBox.vCoeff.clear(); nIdent = 0; nIndex = 0; nThresh = 0; nWeight = 0; mapParticipant.clear(); mapOpenedShare.clear(); } void CMPSecretShare::Enroll(const vector<CMPCandidate>& vCandidate) { size_t nLastIndex = 1; for (size_t i = 0; i < vCandidate.size(); i++) { const CMPCandidate& candidate = vCandidate[i]; if (candidate.nIdent == nIdent) { nIndex = nLastIndex; nWeight = candidate.nWeight; nLastIndex += candidate.nWeight; } else if (!mapParticipant.count(candidate.nIdent) && candidate.Verify()) { try { uint256 shared = myBox.SharedKey(candidate.PubKey()); mapParticipant[candidate.nIdent] = CMPParticipant(candidate, nLastIndex, shared); nLastIndex += candidate.nWeight; } catch (exception& e) { StdError(__PRETTY_FUNCTION__, e.what()); } } } nThresh = (nLastIndex - 1) / 2 + 1; // parallel compute vector<CMPParticipant*> vParticipant; vParticipant.reserve(mapParticipant.size()); for (auto& x : mapParticipant) { vParticipant.push_back(&x.second); } computer.Execute(vParticipant.begin(), vParticipant.end(), [&](CMPParticipant* p) { p->PrepareVerification(nThresh, nLastIndex); }); } void CMPSecretShare::Distribute(map<uint256, vector<uint256>>& mapShare) { vector<CMPParticipant*> vecParticipant; vecParticipant.reserve(mapParticipant.size()); vector<vector<uint256>*> vecShare; vecShare.reserve(mapParticipant.size()); for (auto it = mapParticipant.begin(); it != mapParticipant.end(); it++) { vecParticipant.push_back(&it->second); vector<uint256>& vShare = mapShare[it->first]; vecShare.push_back(&vShare); } computer.Transform( vecParticipant.size(), std::bind(&LoadVectorData<CMPParticipant*>, cref(vecParticipant), placeholders::_1), [&](size_t nIndex, const vector<uint256>& vShare) { *vecShare[nIndex] = vShare; }, [&](CMPParticipant* p) { vector<uint256> vShare; vShare.resize(p->nWeight); for (size_t i = 0; i < p->nWeight; i++) { vShare[i] = p->Encrypt(myBox.Polynomial(nThresh, p->nIndex + i)); } return vShare; }); } bool CMPSecretShare::Accept(const uint256& nIdentFrom, const vector<uint256>& vEncryptedShare) { if (vEncryptedShare.size() == nWeight) { map<uint256, CMPParticipant>::iterator it = mapParticipant.find(nIdentFrom); if (it != mapParticipant.end()) { return (*it).second.AcceptShare(nThresh, nIndex, vEncryptedShare); } } return false; } void CMPSecretShare::Publish(map<uint256, vector<uint256>>& mapShare) { mapShare.clear(); for (map<uint256, CMPParticipant>::iterator it = mapParticipant.begin(); it != mapParticipant.end(); ++it) { if (!(*it).second.vShare.empty()) { mapShare.insert(make_pair((*it).first, (*it).second.vShare)); } } vector<uint256>& myShare = mapShare[nIdent]; for (size_t i = 0; i < nWeight; i++) { myShare.push_back(myBox.Polynomial(nThresh, nIndex + i)); } } bool CMPSecretShare::Collect(const uint256& nIdentFrom, const map<uint256, vector<uint256>>& mapShare, bool& fCompleted) { size_t nIndexFrom, nWeightFrom; fCompleted = false; if (!GetParticipantRange(nIdentFrom, nIndexFrom, nWeightFrom)) { return false; } vector<tuple<CMPParticipant*, const vector<uint256>*>> vecPartShare; vecPartShare.reserve(mapShare.size()); for (map<uint256, vector<uint256>>::const_iterator mi = mapShare.begin(); mi != mapShare.end(); ++mi) { const vector<uint256>& vShare = (*mi).second; if (nWeightFrom != vShare.size()) { return false; } if ((*mi).first == nIdent) { for (size_t i = 0; i < vShare.size(); i++) { if (myBox.Polynomial(nThresh, nIndexFrom + i) != vShare[i]) { return false; } } continue; } map<uint256, CMPParticipant>::iterator it = mapParticipant.find((*mi).first); if (it == mapParticipant.end()) { return false; } vecPartShare.push_back(make_tuple(&it->second, &vShare)); } if (!computer.ExecuteUntil(vecPartShare.begin(), vecPartShare.end(), [&](CMPParticipant* p, const vector<uint256>* pVecShare) -> bool { return p->VerifyShare(nThresh, nIndexFrom, *pVecShare); })) { return false; } size_t nCompleteCollect = 0; for (map<uint256, vector<uint256>>::const_iterator mi = mapShare.begin(); mi != mapShare.end(); ++mi) { vector<pair<uint32_t, uint256>>& vOpenedShare = mapOpenedShare[(*mi).first]; for (size_t i = 0; i < nWeightFrom && vOpenedShare.size() < nThresh; i++) { vOpenedShare.push_back(make_pair(nIndexFrom + i, (*mi).second[i])); } if (vOpenedShare.size() == nThresh) { nCompleteCollect++; } } fCompleted = (nCompleteCollect >= mapShare.size()); return true; } void CMPSecretShare::Reconstruct(map<uint256, pair<uint256, size_t>>& mapSecret) { using ShareType = tuple<const uint256*, std::vector<std::pair<uint32_t, uint256>>*>; vector<ShareType> vOpenedShare; vOpenedShare.reserve(mapOpenedShare.size()); map<uint256, vector<pair<uint32_t, uint256>>>::iterator it; for (it = mapOpenedShare.begin(); it != mapOpenedShare.end(); ++it) { vOpenedShare.push_back(ShareType(&it->first, &it->second)); } // parallel compute using DataType = pair<uint256, size_t>; vector<DataType> vData(vOpenedShare.size()); computer.Transform(vOpenedShare.begin(), vOpenedShare.end(), vData.begin(), [&](const uint256* pIdent, std::vector<std::pair<uint32_t, uint256>>* pShare) { if (pShare->size() == nThresh) { const uint256& nIdentAvail = *pIdent; size_t nIndexRet, nWeightRet; if (GetParticipantRange(nIdentAvail, nIndexRet, nWeightRet)) { return make_pair(MPNewton(*pShare), nWeightRet); } } return make_pair(uint256(uint64(0)), (size_t)0); }); for (int i = 0; i < vData.size(); ++i) { const DataType& data = vData[i]; if (data.second > 0) { const uint256* pIndet = get<0>(vOpenedShare[i]); mapSecret[*pIndet] = data; } } } void CMPSecretShare::Signature(const uint256& hash, uint256& nR, uint256& nS) { uint256 r = RandShare(); myBox.Signature(hash, r, nR, nS); } bool CMPSecretShare::VerifySignature(const uint256& nIdentFrom, const uint256& hash, const uint256& nR, const uint256& nS) { if (nIdentFrom == nIdent) { return myBox.VerifySignature(hash, nR, nS); } map<uint256, CMPParticipant>::iterator it = mapParticipant.find(nIdentFrom); if (it == mapParticipant.end()) { return false; } CMPParticipant& participant = (*it).second; return participant.sBox.VerifySignature(hash, nR, nS); }
3939935f53aba5efebb4ba53f4e0f0e3b22d4b17
3aa9a68026ab10ced85dec559b6b4dfcb74ae251
/CodeChef/CHAOSEMP.cpp
e33c4d0d198e44c475356879372ee4aad4c6cead
[]
no_license
kushuu/competitive_programming_all
10eee29c3ca0656a2ffa37b142df680c3a022f1b
5edaec66d2179a012832698035bdfb0957dbd806
refs/heads/master
2023-08-17T15:09:48.492816
2021-10-04T20:09:37
2021-10-04T20:09:37
334,891,360
3
2
null
null
null
null
UTF-8
C++
false
false
1,150
cpp
/**************************************************************** Author: kushuu File: CHAOSEMP.cpp Date: Tue Apr 06 2021 ****************************************************************/ #include <bits/stdc++.h> //shorts #define ll long long int #define sll stack<long long int> #define vll vector<long long int> #define ld long double #define pb push_back #define mp make_pair #define vpll vector<pair<long long int, long long int>> #define fastIO ios_base::sync_with_stdio(false); cin.tie(NULL); #define fo(i,x,y) for(long long i = x; i < y; i++) #define MOD 1000000007 #define endl "\n" #define F first #define S second #define s(a) a.size() //program specific shorts (if any) // using namespace std; ll getlcm(ll a, ll b) { return (a*b)/__gcd(a, b); } int main() { fastIO; // perform binary search in a 2D matrix. ll T, Q, D; cin >> T >> Q >> D; while(T--) { if(!D) { ll maxH = LLONG_MAX, maxK = LLONG_MAX, minH = 0, minK = 0; cout << "1 0 0 " << endl; string res; cin >> res; while(res != "O") { } } } return 0; }
51b6ba4ceab4d9b67e38b833503c2b9ffae1c680
8cf32b4cbca07bd39341e1d0a29428e420b492a6
/contracts/libc++/upstream/test/std/containers/unord/unord.multimap/equal_range_const.pass.cpp
d40f58ffb8fb7983689225917226db5f7d4f8b44
[ "NCSA", "MIT" ]
permissive
cubetrain/CubeTrain
e1cd516d5dbca77082258948d3c7fc70ebd50fdc
b930a3e88e941225c2c54219267f743c790e388f
refs/heads/master
2020-04-11T23:00:50.245442
2018-12-17T16:07:16
2018-12-17T16:07:16
156,970,178
0
0
null
null
null
null
UTF-8
C++
false
false
3,201
cpp
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <unordered_map> // template <class Key, class T, class Hash = hash<Key>, class Pred = equal_to<Key>, // class Alloc = allocator<pair<const Key, T>>> // class unordered_multimap // pair<const_iterator, const_iterator> equal_range(const key_type& k) const; #include <unordered_map> #include <string> #include <cassert> #include "min_allocator.h" int main() { { typedef std::unordered_multimap<int, std::string> C; typedef C::const_iterator I; typedef std::pair<int, std::string> P; P a[] = { P(10, "ten"), P(20, "twenty"), P(30, "thirty"), P(40, "forty"), P(50, "fifty"), P(50, "fiftyA"), P(50, "fiftyB"), P(60, "sixty"), P(70, "seventy"), P(80, "eighty"), }; const C c(std::begin(a), std::end(a)); std::pair<I, I> r = c.equal_range(30); assert(std::distance(r.first, r.second) == 1); assert(r.first->first == 30); assert(r.first->second == "thirty"); r = c.equal_range(5); assert(std::distance(r.first, r.second) == 0); r = c.equal_range(50); assert(r.first->first == 50); assert(r.first->second == "fifty"); ++r.first; assert(r.first->first == 50); assert(r.first->second == "fiftyA"); ++r.first; assert(r.first->first == 50); assert(r.first->second == "fiftyB"); } #if TEST_STD_VER >= 11 { typedef std::unordered_multimap<int, std::string, std::hash<int>, std::equal_to<int>, min_allocator<std::pair<const int, std::string>>> C; typedef C::const_iterator I; typedef std::pair<int, std::string> P; P a[] = { P(10, "ten"), P(20, "twenty"), P(30, "thirty"), P(40, "forty"), P(50, "fifty"), P(50, "fiftyA"), P(50, "fiftyB"), P(60, "sixty"), P(70, "seventy"), P(80, "eighty"), }; const C c(std::begin(a), std::end(a)); std::pair<I, I> r = c.equal_range(30); assert(std::distance(r.first, r.second) == 1); assert(r.first->first == 30); assert(r.first->second == "thirty"); r = c.equal_range(5); assert(std::distance(r.first, r.second) == 0); r = c.equal_range(50); assert(r.first->first == 50); assert(r.first->second == "fifty"); ++r.first; assert(r.first->first == 50); assert(r.first->second == "fiftyA"); ++r.first; assert(r.first->first == 50); assert(r.first->second == "fiftyB"); } #endif }
4c4ae77f47aee92e25a3b9e3ed3086ac0fcc0287
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/chromium_org/net/http/http_auth_handler_basic.cc
e445c93100cbdf80f31a0f44b9ff620a3b1b7d12
[ "MIT", "BSD-3-Clause" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
4,076
cc
// 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 "net/http/http_auth_handler_basic.h" #include <string> #include "base/base64.h" #include "base/i18n/icu_string_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "net/base/net_errors.h" #include "net/http/http_auth.h" namespace net { namespace { // Parses a realm from an auth challenge, and converts to UTF8-encoding. // Returns whether the realm is invalid or the parameters are invalid. // // Note that if a realm was not specified, we will default it to ""; // so specifying 'Basic realm=""' is equivalent to 'Basic'. // // This is more generous than RFC 2617, which is pretty clear in the // production of challenge that realm is required. // // We allow it to be compatibility with certain embedded webservers that don't // include a realm (see http://crbug.com/20984.) // // The over-the-wire realm is encoded as ISO-8859-1 (aka Latin-1). // // TODO(cbentzel): Realm may need to be decoded using RFC 2047 rules as // well, see http://crbug.com/25790. bool ParseRealm(const HttpAuth::ChallengeTokenizer& tokenizer, std::string* realm) { CHECK(realm); realm->clear(); HttpUtil::NameValuePairsIterator parameters = tokenizer.param_pairs(); while (parameters.GetNext()) { if (!LowerCaseEqualsASCII(parameters.name(), "realm")) continue; if (!base::ConvertToUtf8AndNormalize( parameters.value(), base::kCodepageLatin1, realm)) return false; } return parameters.valid(); } } // namespace bool HttpAuthHandlerBasic::Init(HttpAuth::ChallengeTokenizer* challenge) { auth_scheme_ = HttpAuth::AUTH_SCHEME_BASIC; score_ = 1; properties_ = 0; return ParseChallenge(challenge); } bool HttpAuthHandlerBasic::ParseChallenge( HttpAuth::ChallengeTokenizer* challenge) { // Verify the challenge's auth-scheme. if (!LowerCaseEqualsASCII(challenge->scheme(), "basic")) return false; std::string realm; if (!ParseRealm(*challenge, &realm)) return false; realm_ = realm; return true; } HttpAuth::AuthorizationResult HttpAuthHandlerBasic::HandleAnotherChallenge( HttpAuth::ChallengeTokenizer* challenge) { // Basic authentication is always a single round, so any responses // should be treated as a rejection. However, if the new challenge // is for a different realm, then indicate the realm change. std::string realm; if (!ParseRealm(*challenge, &realm)) return HttpAuth::AUTHORIZATION_RESULT_INVALID; return (realm_ != realm)? HttpAuth::AUTHORIZATION_RESULT_DIFFERENT_REALM: HttpAuth::AUTHORIZATION_RESULT_REJECT; } int HttpAuthHandlerBasic::GenerateAuthTokenImpl( const AuthCredentials* credentials, const HttpRequestInfo*, const CompletionCallback&, std::string* auth_token) { DCHECK(credentials); // TODO(eroman): is this the right encoding of username/password? std::string base64_username_password; base::Base64Encode(UTF16ToUTF8(credentials->username()) + ":" + UTF16ToUTF8(credentials->password()), &base64_username_password); *auth_token = "Basic " + base64_username_password; return OK; } HttpAuthHandlerBasic::Factory::Factory() { } HttpAuthHandlerBasic::Factory::~Factory() { } int HttpAuthHandlerBasic::Factory::CreateAuthHandler( HttpAuth::ChallengeTokenizer* challenge, HttpAuth::Target target, const GURL& origin, CreateReason reason, int digest_nonce_count, const BoundNetLog& net_log, scoped_ptr<HttpAuthHandler>* handler) { // TODO(cbentzel): Move towards model of parsing in the factory // method and only constructing when valid. scoped_ptr<HttpAuthHandler> tmp_handler(new HttpAuthHandlerBasic()); if (!tmp_handler->InitFromChallenge(challenge, target, origin, net_log)) return ERR_INVALID_RESPONSE; handler->swap(tmp_handler); return OK; } } // namespace net
0f6a816d31dbd27002043e6d7ce4d79a230b1c42
3c3de5966143cc045104e88cc360c5a27a58e6d1
/src/vendors/OceanOptics/protocols/obp/exchanges/OBPQuery.cpp
c70931d2dff8b519e3ef72a91e1cb7f1d5f2eab2
[ "MIT" ]
permissive
ska/SeaBreeze
728c21436e5140ba19fdfe8544249fe883499e20
09aac3e764867825f51f75c519a025a863d03590
refs/heads/master
2020-12-24T21:46:00.693023
2016-04-18T11:23:08
2016-04-18T11:23:08
56,501,502
1
3
null
null
null
null
UTF-8
C++
false
false
1,777
cpp
/***************************************************//** * @file OBPQuery.cpp * @date May 2011 * @author Ocean Optics, Inc. * * LICENSE: * * SeaBreeze Copyright (C) 2014, Ocean Optics 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. *******************************************************/ #include "common/globals.h" #include "vendors/OceanOptics/protocols/obp/exchanges/OBPQuery.h" using namespace seabreeze; using namespace seabreeze::oceanBinaryProtocol; using namespace std; OBPQuery::OBPQuery() { } OBPQuery::~OBPQuery() { } vector<byte> *OBPQuery::queryDevice(TransferHelper *helper) throw (ProtocolException) { return OBPTransaction::queryDevice(helper, this->messageType, this->payload); }
9344fd2abc51be4eeeb3abf009ee0c8c639ff141
b256f60961c99aeb5853e40f6c2f61ceebbd147e
/miniSvLib/include/Common/Udp.cpp
a8a50c85c026e57f8fb0dbe2b794bab8352975ea
[]
no_license
Ziran-Li/Ground-station-English
e7dbecda7feb844baa7b571b9dd3797add426e5d
77212a68a5ed656865e67b92f993b39db86eda27
refs/heads/master
2022-11-22T08:58:55.847216
2020-04-09T02:05:47
2020-04-09T02:05:47
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
3,514
cpp
#include "Udp.h" #include <WinSock2.h> #pragma comment(lib, "wsock32.lib") _UDWORD Udp::s_Count = 0; //!< インスタンス生成カウント Udp::Udp(const char* HostName, _UWORD PortSend, _UWORD PortRecv) { if (Udp::s_Count++ == 0) { ::WSADATA wsaData; ::WSAStartup(MAKEWORD(2, 0), &wsaData); } m_pSock = NULL; m_pAddrOut = NULL; m_pAddrIn = NULL; m_RxLength = 0; m_RxReaded = 0; HOSTENT* pHostent = ::gethostbyname(HostName); if (pHostent == NULL) return; // 送信用 SOCKADDR_IN addr_out; ::memset(&addr_out, 0, sizeof(addr_out)); ::memcpy(&(addr_out.sin_addr), pHostent->h_addr_list[0], pHostent->h_length); addr_out.sin_family = AF_INET; addr_out.sin_port = ::htons(PortSend); // 受信用 SOCKADDR_IN addr_in; ::memset(&addr_in, 0, sizeof(addr_in)); addr_in.sin_addr.s_addr = ::htonl(INADDR_ANY); addr_in.sin_family = AF_INET; addr_in.sin_port = ::htons(PortRecv); m_pAddrOut = new SOCKADDR_IN(addr_out); m_pAddrIn = new SOCKADDR_IN(addr_in); } Udp::~Udp() { Close(); if (m_pSock) delete m_pSock; if (m_pAddrOut) delete m_pAddrOut; if (m_pAddrIn) delete m_pAddrIn; if (--Udp::s_Count == 0) { ::WSACleanup(); } } CRESULT Udp::Open() { CRESULT ret = C_FAIL; if (m_pSock == NULL && m_pAddrOut) { m_pSock = new SOCKET; *m_pSock = socket(AF_INET, SOCK_DGRAM, 0); ::bind(*m_pSock, (LPSOCKADDR)m_pAddrIn, sizeof(*m_pAddrIn)); // ノンブロッキング設定 u_long val = 1; ::ioctlsocket(*m_pSock, FIONBIO, &val); debug_printf("UDP Open Succeeded (Tx=%d.%d.%d.%d:%d Rx=%d)\n", m_pAddrOut->sin_addr.S_un.S_un_b.s_b1, m_pAddrOut->sin_addr.S_un.S_un_b.s_b2, m_pAddrOut->sin_addr.S_un.S_un_b.s_b3, m_pAddrOut->sin_addr.S_un.S_un_b.s_b4, ::htons(m_pAddrOut->sin_port), ::htons(m_pAddrIn->sin_port)); ret = C_OK; } else { debug_puts("UDP Open Failed"); } return ret; } void Udp::Close() { if (m_pSock) { ::closesocket(*m_pSock); delete m_pSock; m_pSock = NULL; } } bool Udp::IsEnable() const { return true; // 【暫定】 } // データ受信関数 bool Udp::IsReceiveData() { _Receive(); return (m_RxReaded < m_RxLength); } _UDWORD Udp::IsTransmittable() { return m_pSock ? (_UDWORD) - 1 : 0; } CRESULT Udp::WriteElement(_UBYTE chr) { CRESULT ret = C_FAIL; if (m_pSock) { int n = ::sendto(*m_pSock, reinterpret_cast<const char*>(&chr), 1, 0, (LPSOCKADDR)m_pAddrOut, sizeof(*m_pAddrOut)); ret = n == 1 ? C_OK : C_FAIL; } return ret; } CRESULT Udp::ReadString(void* ptr, _UWORD len) { CRESULT ret = C_FAIL; _Receive(); if (m_RxReaded + len <= m_RxLength) { memcpy_s(ptr, len, m_RxBuffer + m_RxReaded, len); m_RxReaded += len; ret = C_OK; } return ret; } CRESULT Udp::WriteString(const _UBYTE* ptr, _UWORD len) { CRESULT ret = C_FAIL; if (m_pSock && len) { int n = ::sendto(*m_pSock, reinterpret_cast<const char*>(ptr), len, 0, (LPSOCKADDR)m_pAddrOut, sizeof(*m_pAddrOut)); ret = n == len ? C_OK : C_FAIL; } return ret; } CRESULT Udp::ReadElement(_UBYTE* ptr) { CRESULT ret = C_FAIL; _Receive(); if (m_RxReaded < m_RxLength) { *ptr = m_RxBuffer[m_RxReaded++]; ret = C_OK; } return ret; } void Udp::_Receive() { if (m_pSock) { if (m_RxReaded == m_RxLength) { // 内部バッファエンプティ int n = ::recvfrom(*m_pSock, reinterpret_cast<char*>(m_RxBuffer), sizeof(m_RxBuffer), 0, NULL, NULL); if (n > 0) { // 受信OK m_RxLength = n; m_RxReaded = 0; } //debug_printf("%d ", n); } } }
466b7986b5b0cd288b2791e575c1c6113d8e1448
88e54d3ffdc9fbb20ca59d71849f614d7081cd23
/gamess/libcchem/src/ri-mp2/metric.cpp
3ec41c5045a80c1eb828a0a134447e367a2c9c1e
[]
no_license
nobuuuun/myGAMESS
0ab49da4aec4e2fe3341fda3da852d882f3af666
6f92861f0b8ccdbcaf9457219083e74bc47bd626
refs/heads/master
2021-04-09T11:07:06.125035
2018-03-16T08:09:26
2018-03-16T08:09:26
125,484,476
0
0
null
null
null
null
UTF-8
C++
false
false
15,972
cpp
/* * metric.cpp * * Created on: Nov 4, 2015 * Author: luke */ #include "metric.hpp" #include "ri-mp2/ri-integrals.hpp" #include <math.hpp> void cchem::rimp2_gradient::detail::Metric:: BuildTwoCenterEri(std::vector<MapMatrixXd> &sph_c){ MapMatrixXd twoc_eri(data_twoc_, nl_, nl_); pe_.task().reset(); if(pe_.rank() != 0) goto skip1; #pragma omp parallel if (pe_.node().rank() == 0) { BOOST_AUTO(const &auxbasis, auxbasis_.get()); BOOST_AUTO(const &auxshells, auxbasis.shells()); //for possible cartesian to spherical transformation (allocated for each thread) double *data_cart_to_sph = NULL; if(spherical_){ data_cart_to_sph= new double [auxbasis.max().size()*auxbasis.max().size()]; } //spherical_end detail::Thread::Task<Parallel::Task&> task(pe_.task()); #pragma omp barrier cchem::ri::AuxiliaryTwoCenterInt< ::rysq::TwoCenterEri > auxiliary_eri(boost::cref(auxbasis)); while (++task < auxshells.size()) { const Basis::Shell &S = auxbasis.shells().at(task); size_t s = task; for(size_t q= 0; q <= task; ++q){ const Basis::Shell &Q = auxbasis.shells().at(q); MapMatrixXd twoc_batch(auxiliary_eri(Q,S), S.size(), Q.size()); if(spherical_){ MapMatrixXd transformed_batch(data_cart_to_sph,S.sphsize(), Q.sphsize()); transformed_batch = sph_c[S.Lmin()].block(0,0,S.size(),S.sphsize()).transpose()*twoc_batch*sph_c[Q.Lmin()].block(0,0,Q.size(),Q.sphsize()); twoc_eri.block(S.sphstart(),Q.sphstart(),S.sphsize(),Q.sphsize()) = transformed_batch; twoc_eri.block(Q.sphstart(),S.sphstart(),Q.sphsize(),S.sphsize()) = transformed_batch.matrix().transpose(); }else{ twoc_eri.block(S.start(),Q.start(),S.size(),Q.size()) = twoc_batch; twoc_eri.block(Q.start(),S.start(),Q.size(),S.size()) = twoc_batch.matrix().transpose(); }//(spherical_) } //q } //task delete [] data_cart_to_sph; }//(pe_.node().rank() == 0) skip1:; pe_.broadcast(data_twoc_, nl_*nl_, 0); return; }; void ::cchem::rimp2_gradient::detail::Metric::DecomposeLDLT(){ MapMatrixXd twoc_eri(data_twoc_, nl_, nl_); MapMatrixXd twoc_pqm1(data_pqm1_, nl_, nl_); //--------LDLT from eigen-------- twoc_pqm1 = twoc_eri.ldlt().solve(Eigen::MatrixXd::Identity(nl_,nl_)); return; } void ::cchem::rimp2_gradient::detail::Metric::DecomposeLLT(){ MapMatrixXd twoc_eri(data_twoc_, nl_, nl_); MapMatrixXd twoc_pqm1(data_pqm1_, nl_, nl_); //--------LLT from eigen-------- Eigen::LLT<Eigen::MatrixXd> cho_twoc_eri(twoc_eri); //.solver(); twoc_pqm1 = cho_twoc_eri.matrixL(); return; }; void ::cchem::rimp2_gradient::detail::Metric::InvertL(){ MapMatrixXd twoc_pqm1(data_pqm1_, nl_, nl_); twoc_pqm1 = twoc_pqm1.inverse(); return; }; void ::cchem::rimp2_gradient::detail::Metric:: pseudoInvertedSqrt(const double &tol, double *pPqm12, double *pTwoC, bool doPrint){ if(doPrint)std::cout << "Performing Pseudo-Inversion" << std::endl; MapMatrixXd TwoC(pTwoC,nl_,nl_); MapMatrixXd Pqm12(pPqm12,nl_,nl_); Pqm12 = TwoC; //lm1 is temp here Eigen::VectorXd evalues(nl_); Eigen::MatrixXd evectors(nl_,nl_); Eigen::MatrixXd evectorsCopy(nl_,nl_); #if !HAVE_MKL //get eigenvalues and eigenvectors Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigensolver(Pqm12); if(eigensolver.info()) std::cout << "!!!something went wrong with eigensolver!!! " << __FILE__ << ":" << __LINE__ << std::endl; evalues = eigensolver.eigenvalues(); evectors = eigensolver.eigenvectors(); #endif #if HAVE_MKL evectors = TwoC; int info; LAPACKE_dsyev(LAPACK_COL_MAJOR, 'V', 'L' , nl_, evectors.data(), nl_, evalues.data() ); #endif // #if HAVE_OPENBLAS // evectors = twoc_eri; // int info; // LAPACKE_dsyev(LAPACK_COL_MAJOR, 'V', 'L' , nl_, evectors.data(), nl_, evalues.data() ); // #endif evectorsCopy = evectors; double maxJ = evalues(nl_-1); //eigenvectors with eigenvalues greater than the threshold 'tol' contribute int sig = 0; for (int ind=0; ind < nl_; ind++){ if( (evalues(ind) / maxJ) < tol || evalues(ind) <= 0.0 ){ sig++; evalues(ind) = 0; }else{ evalues(ind) = 1/ ( sqrt( evalues(ind) ) ); }//logic for(int jnd = 0; jnd < nl_; jnd++){ evectors(jnd,ind) = evectors(jnd,ind)*evalues(ind); }//tolerance }//ind if(doPrint)std::cout << " removed " << sig << " eigenvalues from pseudo-inversion" << std::endl; //construct (P|Q)^-0.5 Pqm12 = evectorsCopy*evectors.transpose(); } //pseudoInversion void ::cchem::rimp2_gradient::detail::Metric:: choleskyInversion(double *data_pqm1, double *data_twoc, bool doPrint){ MapMatrixXd twoc_eri(data_twoc,nl_,nl_); #ifdef HAVE_ATLAS clapack_dpotrf(CblasColMajor,CblasUpper, (int)nl_,data_twoc,(int)nl_); clapack_dtrtri(CblasColMajor,CblasUpper,CblasNonUnit, (int)nl_,data_twoc,(int)nl_); #endif #ifdef HAVE_MKL LAPACKE_dpotrf(LAPACK_COL_MAJOR,'U', (int)nl_,data_twoc,(int)nl_); LAPACKE_dtrtri(LAPACK_COL_MAJOR,'U','N', (int)nl_,data_twoc,(int)nl_); #endif #ifdef HAVE_OPENBLAS // LAPACKE_dpotrf(LAPACK_COL_MAJOR,'U', // (int)nl_,data_twoc,(int)nl_); // LAPACKE_dtrtri(LAPACK_COL_MAJOR,'U','N', // (int)nl_,data_twoc,(int)nl_); //have problems with openblas lapack --> use eigen Eigen::MatrixXd twoc_pqm1(nl_, nl_); twoc_pqm1.setZero(); //--------LLT from eigen-------- Eigen::LLT<Eigen::MatrixXd> cho_twoc_eri(twoc_eri); //.solver(); twoc_pqm1 = cho_twoc_eri.matrixL(); twoc_pqm1 = twoc_pqm1.inverse(); twoc_eri = twoc_pqm1.transpose(); #endif // this->pseudoInversion(1e-10,data_pqm1,data_twoc); // for(int i = 0; i < 10; i ++ ) // std::cout << nl_ << std::endl; // std::cout << twoc_eri.block(0,0,5,5) << std::endl << std::endl; //zap the lower off-diagonal twoc_eri = twoc_eri.triangularView<Eigen::Upper>(); // std::cout << twoc_eri.block(0,0,5,5) << std::endl << std::endl; // twoc_eri.setZero(); // twoc_eri.setIdentity(); //form (P|Q)-1 <--- Lm1 * Lm1^T //this is done locally (not on GPU), we use (P|Q)-1 with GPU #if HAVE_CUBLAS // MapMatrixXd pqm1(data_pqm1,nl_,nl_); // Eigen::MatrixXd temp(nl_,nl_); // temp.setZero(); // temp = pqm1*pqm1; // pqm1 = temp; // pqm1 = twoc_eri*twoc_eri.transpose(); // cblas_dgemm(CblasColMajor,CblasNoTrans,CblasTrans, // nl_,nl_,nl_, // 1.0, data_twoc, nl_, // data_twoc, nl_, // 0.0, data_pqm1, nl_); // temp = 0.5*pqm1 + 0.5*pqm1.transpose(); // pqm1 = temp; if(doPrint)std::cout << std::endl << "Building inverse Coulomb metric from Cholesky vectors:" << std::endl << " (P|Q)^-1 = U^-1 * [U^-1]^T" << std::endl << std::endl; cblas_dgemm(CblasColMajor,CblasNoTrans,CblasTrans, nl_,nl_,nl_, 1.0, data_twoc, nl_, data_twoc, nl_, 0.0, data_pqm1, nl_); #endif //put Lm1 --> data_pqm1 #if !HAVE_CUBLAS if(doPrint)std::cout << std::endl << "Using inverse Cholesky decomposed Coulomb metric L^-1" << std::endl << std::endl; memcpy(data_pqm1, data_twoc, nl_*nl_*sizeof(double) ); #endif }//choleskyInversion //--------Direct Eigen Inversion-------- // twoc_pqm1.setZero(); // twoc_pqm1 = twoc_eri.inverse(); //inverse for gradient // std::cout << "inverted " << std::endl << twoc_pqm1.block(0,0,5,5) << std::endl << std::endl; // Eigen::MatrixXd unit(nl,nl); // unit = Eigen::MatrixXd::Identity(nl,nl); // double error_value = ((twoc_eri*twoc_pqm1) - unit).norm(); // std::cout << "unit " << std::endl << (twoc_eri*twoc_pqm1).block(0,0,5,5) << std::endl << std::endl; // std::cout << "error_value: " << error_value << std::endl; //-------------------------------------- //----------------LU factorization with sequential inversion---------------- // twoc_pqm1 = twoc_eri; // int *IPIV = new int[nl+1]; // // int info2 = clapack_dgetrf(CblasColMajor, (int)nl, (int)nl, twoc_pqm1.data(), (int)nl, IPIV); // int info3 = clapack_dgetri(CblasColMajor, (int)nl, twoc_pqm1.data(), (int)nl, IPIV); // // // delete IPIV; // // std::cout << "inverted " << std::endl << twoc_pqm1.block(0,0,5,5) << std::endl << std::endl; // // Eigen::MatrixXd unit(nl,nl); // unit = Eigen::MatrixXd::Identity(nl,nl); // double error_value = ((twoc_eri*twoc_pqm1) - unit).norm(); // std::cout << "unit " << std::endl << (twoc_eri*twoc_pqm1).block(0,0,5,5) << std::endl << std::endl; // std::cout << "error_value: " << error_value << std::endl; //------------------------------------------------ // //--------Using atlas libaray exclisively to perform cholesky -> invert ( L -> L^-1 )-------- // twoc_pqm1 = twoc_eri; // // int info4 = clapack_dpotrf(CblasColMajor, CblasLower, (int)nl, data_real_pqm1, (int)nl); // // ////can invert with eigen // twoc_pqm1 = twoc_pqm1.triangularView<Eigen::Lower>(); // twoc_pqm1 = twoc_pqm1.inverse(); // twoc_pqm1 = twoc_pqm1.transpose()*twoc_pqm1; // //// //invert with atlas //// int info5 = clapack_dpotri(CblasColMajor, CblasLower, (int)nl, data_real_pqm1, (int)nl); //// std::cout << "info5 " << info5 << std::endl; //// //// std::cout << "inverted" << std::endl <<twoc_pqm1.block(0,0,5,5) << std::endl << std::endl; //// //need to symmeterize matrix //// for (int i =0; i < nl; i++){ //// for (int j=0; j < i; j++){ //// twoc_pqm1(j,i) = twoc_pqm1(i,j); //// }//j //// }//i // // Eigen::MatrixXd unit(nl,nl); // unit = Eigen::MatrixXd::Identity(nl,nl); // double error_value = ((twoc_eri*twoc_pqm1) - unit).norm(); // std::cout << "unit " << std::endl << (twoc_eri*twoc_pqm1).block(0,0,5,5) << std::endl << std::endl; // std::cout << "error_value: " << error_value << std::endl; // // //---------------------------------------------------------------- //--------here we're eigen SVD-------- // A = U * D * V^T // A^-1 = V * D^-1 * U^T // Eigen::MatrixXd tester(nl,nl); // twoc_pqm1 = twoc_eri; // Eigen::JacobiSVD<Eigen::MatrixXd> svd(twoc_pqm1, Eigen::ComputeThinU | Eigen::ComputeThinV); // tester = svd.matrixV()*svd.singularValues().asDiagonal().inverse()*svd.matrixU().transpose(); // std::cout << (tester*twoc_pqm1).block(0,0,5,5) << std::endl << std::endl; // std::cout << "the singular values are: " << std::endl << svd.singularValues() << std::endl; //// Eigen::MatrixXd unit(nl,nl); //// unit = Eigen::MatrixXd::Identity(nl,nl); //// double error_value = ((tester*twoc_pqm1) - unit).norm(); ////// std::cout << "unit " << std::endl << (tester*twoc_pqm1).block(0,0,5,5) << std::endl << std::endl; //// std::cout << "error_value: " << error_value << std::endl; //// twoc_pqm1 = tester; //// double cond = svd.singularValues()(0) / svd.singularValues()(svd.singularValues().size()-1); //// std::cout << "condition number is " << cond << std::endl; //---------------------------------------- // //--------This is using the LDLT Eigen routine instead of LLT-------- // // Eigen::MatrixXd temp(nl_temp,nl_temp); // twoc_pqm1 = twoc_eri; // temp = twoc_pqm1.ldlt().solve(Eigen::MatrixXd::Identity(nl_temp,nl_temp)); // twoc_pqm1 = temp; // // std::cout << "temp" << std::endl <<temp.block(0,0,5,5) << std::endl << std::endl; // // Eigen::MatrixXd unit(nl_temp,nl_temp); // unit = Eigen::MatrixXd::Identity(nl_temp,nl_temp); // double error_value = ((twoc_eri*twoc_pqm1) - unit).norm(); // std::cout << "unit " << std::endl << (twoc_eri*twoc_pqm1).block(0,0,5,5) << std::endl << std::endl; // std::cout << "error_value: " << error_value << std::endl; // // //---------------------------------------- // // // //---------------------------------------- // //find 1-norms // double ANorm = 0.0; // for(int j=0; j<nl_temp; j++){ // double col = 0.0; // for(int i=0; i<nl_temp; i++){ // col += std::abs(twoc_eri(i,j)); //1 //// col += twoc_eri(j,i); //infinity // // // }//i // if(col > ANorm) ANorm = col; // }//j // // // double Am1Norm = 0.0; // for(int j=0; j<nl_temp; j++){ // double col = 0.0; // for(int i=0; i<nl_temp; i++){ // col += std::abs(twoc_pqm1(i,j)); //1 //// col += twoc_pqm1(j,i); //inifinity // // // }//i // if(col > Am1Norm) Am1Norm = col; // }//j // // std::cout << "condition number " << ANorm*Am1Norm << std::endl; // std::cout << "condition number " << twoc_eri.norm()*twoc_pqm1.norm() << std::endl; // // //---------------------------------------- //--------cholesky decomposition from ublas/atlas-------- // #include "lapack.hpp" //must be declare at head // long info; // long psize = auxbasis.size(); // dpotrf_("L", &psize, twoc_eri.data(), &psize, &info); //this may take some more thought later // twoc_eri = twoc_eri.triangularView<Eigen::Lower>(); // int info; // int psize = auxbasis.size(); // char lower = 'L'; // info = _clapack_dpotrf_(CblasRowMajor,CblasLower, psize, twoc_eri.data(),psize); // twoc_eri = twoc_eri.triangularView<Eigen::Lower>(); //---------------------------------------- //--------default eigen inversion for L matrix-------- //slower for some reason // twoc_eri = twoc_eri.inverse(); //eigen-slower? //---------------------------------------- //--------ublas/atlas inversion for L matrix-------- //(this looks like ublas, should probaly fix this somehow???) // long info; //ublas // long psize = auxbasis.size(); //ublas // dtrtri_("L","N",&psize,twoc_eri.data(),&psize,&info); //ublas // int info = clapack_dtrtri( CblasColMajor,CblasLower,CblasNonUnit,(int)nl_temp, twoc_eri.data(), (int)nl_temp); //atlas //can't do this since it inverts original matrix (not the L matrix) dpotri_("L",&psize,twoc_eri.data(),&psize,&info); //----------------------------------------- // std::cout << "inverted" << std::endl << twoc_eri.block(0,0,5,5) << std::endl << std::endl; // //--------Here I am generating the (P|Q)^-1 matrix from (L^-1)^T * L -------- // //alternate: invert twoc_eri to twoc_pqm1 for gradient // twoc_pqm1 = twoc_eri.transpose()*twoc_eri; // std::cout << twoc_pqm1.block(0,0,5,5) << std::endl << std::endl; // // // Eigen::MatrixXd unit(nl,nl); // unit = Eigen::MatrixXd::Identity(nl,nl); // double error_value = ((tester*twoc_pqm1) - unit).norm(); // std::cout << "unit " << std::endl << (tester*twoc_pqm1).block(0,0,5,5) << std::endl << std::endl; // std::cout << "error_value: " << error_value << std::endl; //// twoc_pqm1 = tester; // // //--------------------------------------------------------------------------------
af580e1b7df7b43a4292a914f06acc81b95b8bb2
e9f60c823da0b4e6dad91834daf571dee4599fd8
/cpp_prac/190131.cpp
2261996be036651c2f5ee0be2e2e135b4e8b2c39
[]
no_license
2013011491/algorithm_practice
2595b0b32c7cb5ead040b76b9ca2415076770795
fd630ef028d95f7b0d6d81e491d3516cf34bc8b4
refs/heads/master
2022-09-20T15:37:41.734873
2020-06-06T13:44:41
2020-06-06T13:44:41
208,989,712
0
0
null
null
null
null
UHC
C++
false
false
3,404
cpp
#include <iostream> #include <cstring> using namespace std; class Employee { private: char name[100]; public: Employee(char * name) { strcpy(this->name, name); } void ShowYourName() const { cout<<"name: "<<name<<endl; } virtual int GetPay() const { return 0; } virtual void ShowSalaryInfo() const { } }; class PermanentWorker : public Employee { private: int salary; public: PermanentWorker(char * name, int money) : Employee(name), salary(money) { } int GetPay() const { return salary; } void ShowSalaryInfo() const { ShowYourName(); cout<<"salary: "<<GetPay()<<endl<<endl; } }; class TemporaryWorker : public Employee { private: int workTime; int payPerHour; public: TemporaryWorker(char * name, int pay) : Employee(name), workTime(0), payPerHour(pay) { } void AddWorkTime(int time) { workTime+=time; } int GetPay() const { return workTime*payPerHour; } void ShowSalaryInfo() const { ShowYourName(); cout<<"salary: "<<GetPay()<<endl<<endl; } }; class SalesWorker : public PermanentWorker { private: int salesResult; // 월 판매실적 double bonusRatio; // 상여금 비율 public: SalesWorker(char * name, int money, double ratio) : PermanentWorker(name, money), salesResult(0), bonusRatio(ratio) { } void AddSalesResult(int value) { salesResult+=value; } int GetPay() const { return PermanentWorker::GetPay() + (int)(salesResult*bonusRatio); } void ShowSalaryInfo() const { ShowYourName(); cout<<"salary: "<<GetPay()<<endl<<endl; } }; namespace RISK_LEVEL { enum { RISK_A=30, RISK_B=20, RISK_C=10 }; } class ForeignSalesWorker : public SalesWorker { private : int risk; public : ForeignSalesWorker(char * name, int money, double ratio, int riskness) : SalesWorker(name, money, ratio), risk(riskness) { } int RiskPay() const { return SalesWorker::GetPay()*(risk/100.0); } int GetPay() const { return SalesWorker::GetPay()+RiskPay(); } void ShowSalaryInfo() const { ShowYourName(); cout<<"salary: "<<SalesWorker::GetPay()<<endl; cout<<"risk pay: "<<RiskPay()<<endl; cout<<"sum: "<<GetPay()<<endl<<endl; } }; class EmployeeHandler { private: Employee* empList[50]; int empNum; public: EmployeeHandler() : empNum(0) { } void AddEmployee(Employee* emp) { empList[empNum++]=emp; } void ShowAllSalaryInfo() const { for(int i=0; i<empNum; i++) empList[i]->ShowSalaryInfo(); } void ShowTotalSalary() const { int sum=0; for(int i=0; i<empNum; i++) sum+=empList[i]->GetPay(); cout<<"salary sum: "<<sum<<endl; } ~EmployeeHandler() { for(int i=0; i<empNum; i++) delete empList[i]; } }; int main(void) { // 직원관리를 목적으로 설계된 컨트롤 클래스의 객체생성 EmployeeHandler handler; ForeignSalesWorker * fseller1=new ForeignSalesWorker("Hong", 1000, 0.1, RISK_LEVEL::RISK_A); fseller1->AddSalesResult(7000); handler.AddEmployee(fseller1); ForeignSalesWorker * fseller2=new ForeignSalesWorker("Yoon", 1000, 0.1, RISK_LEVEL::RISK_B); fseller2->AddSalesResult(7000); handler.AddEmployee(fseller2); ForeignSalesWorker * fseller3=new ForeignSalesWorker("Lee", 1000, 0.1, RISK_LEVEL::RISK_C); fseller3->AddSalesResult(7000); handler.AddEmployee(fseller3); // 이번 달에 지불해야 할 급여의 정보 handler.ShowAllSalaryInfo(); return 0; }
b785e5709f918cb4594f2e30704bb85ad214b04a
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_repos_function_2171.cpp
da2064e749502f572ef762d18e915466639af773
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
437
cpp
static int pre_config(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp) { apr_pool_t *global_pool; apr_status_t rv; rv = apr_pool_create(&global_pool, NULL); if (rv != APR_SUCCESS) { ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL, "Fatal error: unable to create global pool for shared slotmem"); return rv; } slotmem_shm_initgpool(global_pool); return OK; }
3fc0031b41e9ce85ab35887163c77671b61e69a4
1bd9e3cda029e15d43a2e537663495ff27e317e2
/buoyantPimpleFoam_timevaryingBC/heatfluxtimevary/14/uniform/cumulativeContErr
a0729940ba3622bc5f75b19a3d45c2fe082af582
[]
no_license
tsam1307/OpenFoam_heatTrf
810b81164d3b67001bfce5ab9311d9b3d45b5c9d
799753d24862607a3383aa582a6d9e23840c3b15
refs/heads/main
2023-08-10T23:27:40.420639
2021-09-18T12:46:01
2021-09-18T12:46:01
382,377,763
1
0
null
null
null
null
UTF-8
C++
false
false
954
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v2006 | | \\ / A nd | Website: www.openfoam.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class uniformDimensionedScalarField; location "14/uniform"; object cumulativeContErr; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 0 0 0 0 0 0]; value 1.7125e-12; // ************************************************************************* //
7c19460399e36e4e1e45aa948616545c98dc7788
dcd02773a441420673dbceafe08394868f00a565
/test/core/caching/mock/MockIBeaconCacheEvictor.h
2eb00f8408cfd2c1a85fcf0f8636d7a0556a0dda
[ "curl", "BSD-3-Clause", "Apache-2.0" ]
permissive
stefaneberl/openkit-native
7243419cb89dde17b8b816fc0c35bc6250bd7861
1dc042141f4990508742a89aacafda9b2a29aaaf
refs/heads/main
2021-06-27T00:31:30.082012
2020-10-02T11:49:42
2020-10-02T11:49:42
300,597,896
0
0
NOASSERTION
2020-10-02T11:47:47
2020-10-02T11:47:46
null
UTF-8
C++
false
false
1,504
h
/** * Copyright 2018-2020 Dynatrace LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _TEST_CORE_CACHING_MOCK_MOCKIBEACONCACHEEVICTOR_H #define _TEST_CORE_CACHING_MOCK_MOCKIBEACONCACHEEVICTOR_H #include "core/caching/IBeaconCacheEvictor.h" #include "gmock/gmock.h" #include <chrono> #include <memory> namespace test { class MockIBeaconCacheEvictor : public core::caching::IBeaconCacheEvictor { public: ~MockIBeaconCacheEvictor() override = default; static std::shared_ptr<testing::NiceMock<MockIBeaconCacheEvictor>> createNice() { return std::make_shared<testing::NiceMock<MockIBeaconCacheEvictor>>(); } static std::shared_ptr<testing::StrictMock<MockIBeaconCacheEvictor>> createStrict() { return std::make_shared<testing::StrictMock<MockIBeaconCacheEvictor>>(); } MOCK_METHOD0(isAlive, bool()); MOCK_METHOD0(start, bool()); MOCK_METHOD0(stop, bool()); MOCK_METHOD1(stop, bool( std::chrono::milliseconds ) ); }; } #endif
309a294c5e926fddac1095c5b9855cb49d7a129f
5ac237f7076f8ccd58022f12e65c88db28cf93c5
/src(add-to-xcode-proj)/OBJObject.cpp
381a15cdca4a4f291c754f05db95550cb50cf777
[]
no_license
ncarmont/-BIG-HERO-6-Interactive-3D-game
5148c96d8731b138d1f7cbef769a982207402bbe
ca5ecb6b605f39af3ca18b1db6b44b6957959cdb
refs/heads/master
2020-04-13T02:34:10.744277
2018-12-23T16:27:59
2018-12-23T16:27:59
162,905,857
0
0
null
null
null
null
UTF-8
C++
false
false
19,043
cpp
#include "OBJObject.h" #include "Window.h" #include <iostream> #include <fstream> #include <math.h> // include math functions, such as sin, cos, M_PI using namespace std; OBJObject::OBJObject(const char *filepath) { // this->angle = 0.0f; parse(filepath); printf("PARSING FINISHED\n"); center(); toWorld = glm::mat4(1.0f); glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); glGenBuffers(1, &VBON); //?? norm // glGenBuffers(1, &VBOT); glBindVertexArray(VAO); //Vertices glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0); //Normals glBindBuffer(GL_ARRAY_BUFFER, VBON); glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(glm::vec3), &normals[0], GL_STATIC_DRAW); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0); // //Texture // glBindBuffer(GL_ARRAY_BUFFER, VBOT); // glBufferData(GL_ARRAY_BUFFER, textures.size() * sizeof(glm::vec2), &textures[0], GL_STATIC_DRAW); // glEnableVertexAttribArray(2); // glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), (GLvoid*)0); // // OBJObject::loadTexture(); //Draws indices/Faces glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, faces.size()*sizeof(int), &faces[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } void OBJObject::draw(GLuint shaderProgram) { glm::mat4 modelview = Window::V * toWorld; uProjection = glGetUniformLocation(shaderProgram, "projection"); uModelview = glGetUniformLocation(shaderProgram, "modelview"); glUniformMatrix4fv(uProjection, 1, GL_FALSE, &Window::P[0][0]); glUniformMatrix4fv(uModelview, 1, GL_FALSE, &modelview[0][0]); GLuint uModel = glGetUniformLocation(shaderProgram, "model"); GLuint uView = glGetUniformLocation(shaderProgram, "view"); glUniformMatrix4fv(uModel, 1, GL_FALSE, &toWorld[0][0]); glUniformMatrix4fv(uView, 1, GL_FALSE, &Window::V[0][0]); glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, (GLsizei)faces.size(), GL_UNSIGNED_INT, 0); glBindVertexArray(0); } OBJObject::~OBJObject() { glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glDeleteBuffers(1, &EBO); glDeleteBuffers(1, &VBON); } void OBJObject::setModel(glm::mat4 model){ this->toWorld = model; } //for complex items with textures and more face items, ie robot stuff //void OBJObject::parse(const char *filepath) //{ // // Populate the face indices, vertices, and normals vectors with the OBJ Object data // // /* This next part taken from the write up, slightly edited */ // // FILE* file; // file pointer // float vx,vy,vz; // vertex coordinates // float vnx,vny,vnz; // vertex color // float vtx, vty; //texture coordinates // int tx,ty,tz; // texture indcies // int fx,fy,fz; // face indices // int nx,ny,nz; // normal indices // // int c1,c2; // characters read from file // // // std::vector<glm::vec2> input_textures; // std::vector<glm::vec3> input_vertices; // std::vector<glm::vec3> input_normals; // std::vector<int> input_indices; // // file = fopen(filepath,"rb"); // make the file name configurable so you can load other files // if (file == NULL) { // std::cerr << "error loading file" << std::endl; // exit(-1); // } // just in case the file can't be found or is corrupt // // // do{ // c1 = fgetc(file); // c2 = fgetc(file); // // //printf("\nProcess %c%c", c1, c2); // // //v // if ((c1=='v') && (c2==' ')){ // fscanf(file, "%f %f %f\n", &vx, &vy, &vz); // input_vertices.push_back({vx,vy,vz}); // //printf("v %f %f %f\n", vx, vy, vz); // } // //vn // else if ((c1=='v') && (c2=='n')){ // fscanf(file, "%f %f %f\n", &vnx, &vny, &vnz); // input_normals.push_back({vnx, vny, vnz}); // } // //vt // else if ((c1=='v') && (c2=='t')){ // fscanf(file, "%f %f\n", &vtx, &vty); // input_textures.push_back({vtx, vty}); // //printf("vt %f %f\n", vtx, vty); // } // else if ((c1 == 'f') && (c2 == ' ' )){ // //second throw away values?? check to see if theyre identical // fscanf(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n",&fx,&tx,&nx,&fy,&ty,&ny,&fz,&tz,&nz); // if (fx == -1 || fy == -1 || fz == -1){ //for error catching purposes // printf("\n\n\n PARSING ISSUE \n\n\n"); // break; // } // input_indices.push_back(fx-1); // input_indices.push_back(fy-1); // input_indices.push_back(fz-1); // t_indices.push_back(tx-1); // t_indices.push_back(ty-1); // t_indices.push_back(tz-1); // n_indices.push_back(nx-1); // n_indices.push_back(ny-1); // n_indices.push_back(nz-1); // // fx=-1; fy=-1; fz=-1; //for testing purposes // } // else if(c2=='v'){ // int c3=fgetc(file); // // printf("->%c",c3 ); // // //if ((c2=='v') && (fgetc(file)==' ')){ // if ((c2=='v') && (c3==' ')){ // fscanf(file, "%f %f %f\n", &vx, &vy, &vz); // input_vertices.push_back({vx,vy,vz}); // }else if((c2=='v') && (c3=='t')){ // fscanf(file, "%f %f\n", &vtx, &vty); // input_textures.push_back({vtx, vty}); // }else if((c2=='v') && (c3=='n')){ // fscanf(file, "%f %f %f\n", &vnx, &vny, &vnz); // input_normals.push_back({vnx, vny, vnz}); // } // }else if ((c2 == 'f') && (fgetc(file)==' ')){ //first f // fscanf(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n",&fx,&tx,&nx,&fy,&ty,&ny,&fz,&tz,&nz); // input_indices.push_back(fx-1); // input_indices.push_back(fy-1); // input_indices.push_back(fz-1); // t_indices.push_back(tx-1); // t_indices.push_back(ty-1); // t_indices.push_back(tz-1); // n_indices.push_back(nx-1); // n_indices.push_back(ny-1); // n_indices.push_back(nz-1); // } //// else if ((c1=='v') && (c2=='n') && (fgetc(file)==' ')){ //// fscanf(file, "%f %f %f\n", &x, &y, &z); //// normals.push_back({x,y,z}); //// } // // // }while(c1 != EOF && c2 != EOF); // // fclose(file); // make sure you don't forget to close the file when done // //// printf("\n\n\nvertices: %d\n", vertices.size()); //// printf("normals: %d\n", normals.size()); //// printf("textures: %d\n", textures.size()); //// printf("indices: %d\n", faces.size()); //// printf("t_indices: %d\n", t_indices.size()); //// printf("n_indices: %d\n\n\n\n", n_indices.size()); // // // for (unsigned i = 0; i < input_indices.size(); i++) { // vertices.push_back(input_vertices[input_indices[i]]); // normals.push_back(input_normals[n_indices[i]]); // textures.push_back(input_textures[t_indices[i]]); // faces.push_back(i); // } // // // //} //for eyeball sphere //void OBJObject::parse(const char *filepath) //{ // // Populate the face indices, vertices, and normals vectors with the OBJ Object data // // /* This next part taken from the write up, slightly edited */ // // FILE* file; // file pointer // float x,y,z; // vertex coordinates // float r,g,b; // vertex color // int fx,fy,fz; // face indices // int c1,c2; // characters read from file // // // // file = fopen(filepath,"rb"); // make the file name configurable so you can load other files // if (file == NULL) { // std::cerr << "error loading file" << std::endl; // exit(-1); // } // just in case the file can't be found or is corrupt // // // do{ // c1 = fgetc(file); // c2 = fgetc(file); // // if ((c1=='v') && (c2==' ')){ // fscanf(file, "%f %f %f %f %f %f\n", &x, &y, &z, &r, &g, &b); // vertices.push_back({x,y,z}); // } // else if ((c1 == 'f') && (c2 == ' ' )){ // //second throw away values?? check to see if theyre identical // fscanf(file, "%d//%d %d//%d %d//%d\n", &fx, &fx, &fy, &fy, &fz, &fz); // if (fx == -1 && fy == -1 && fz == -1){ // break; // } // faces.push_back(fx-1); // faces.push_back(fy-1); // faces.push_back(fz-1); // } // else if ((c2 == 'f') && (fgetc(file)==' ')){ //first f // //second throw away values?? check to see if theyre identical // fscanf(file, "%d//%d %d//%d %d//%d\n", &fx, &fx, &fy, &fy, &fz, &fz); // faces.push_back(fx-1); // faces.push_back(fy-1); // faces.push_back(fz-1); // } // else if ((c1=='v') && (c2=='n') && (fgetc(file)==' ')){ // fscanf(file, "%f %f %f\n", &x, &y, &z); // normals.push_back({x,y,z}); // } // // // }while(c1 != EOF && c2 != EOF); // // fclose(file); // make sure you don't forget to close the file when done // // std::cout << "Vertices: " << vertices.size() << std::endl; // std::cout << "Normals: " << normals.size() << std::endl; // std::cout << "Faces: " << faces.size() << std::endl; // // printf("First vertice: {%f,%f,%f}\n", vertices[0][0],vertices[0][1],vertices[0][2]); // printf("First normal: {%f,%f,%f}\n", normals[0][0],normals[0][1],normals[0][2]); // int s = faces.size(); // printf("First face: {%d,%d,%d}\n", faces[s-3],faces[s-2],faces[s-1]); //} //sphere, bunny, etc void OBJObject::parse(const char *filepath) { // Populate the face indices, vertices, and normals vectors with the OBJ Object data /* This next part taken from the write up, slightly edited */ FILE* file; // file pointer float vx,vy,vz; // vertex coordinates float vnx,vny,vnz; // vertex color int fx,fy,fz; // face indices int c1,c2; // characters read from file std::vector<glm::vec3> input_vertices; std::vector<glm::vec3> input_normals; std::vector<int> input_indices; file = fopen(filepath,"rb"); // make the file name configurable so you can load other files if (file == NULL) { std::cerr << "error loading file" << std::endl; exit(-1); } // just in case the file can't be found or is corrupt do{ c1 = fgetc(file); c2 = fgetc(file); //v if ((c1=='v') && (c2==' ')){ fscanf(file, "%f %f %f\n", &vx, &vy, &vz); input_vertices.push_back({vx,vy,vz}); } //vn else if ((c1=='v') && (c2=='n')){ fscanf(file, "%f %f %f\n", &vnx, &vny, &vnz); input_normals.push_back({vnx, vny, vnz}); } else if ((c1 == 'f') && (c2 == ' ' )){ //second throw away values?? check to see if theyre identical fscanf(file, "%d//%d %d//%d %d//%d\n", &fx, &fx, &fy, &fy, &fz, &fz); if (fx == -1 || fy == -1 || fz == -1){ //for error catching purposes printf("\n\n\n PARSING ISSUE \n\n\n"); break; } input_indices.push_back(fx-1); input_indices.push_back(fy-1); input_indices.push_back(fz-1); fx=-1; fy=-1; fz=-1; //for testing purposes } else if(c2=='v'){ int c3=fgetc(file); // printf("->%c",c3 ); //if ((c2=='v') && (fgetc(file)==' ')){ if ((c2=='v') && (c3==' ')){ fscanf(file, "%f %f %f\n", &vx, &vy, &vz); input_vertices.push_back({vx,vy,vz}); }else if((c2=='v') && (c3=='n')){ fscanf(file, "%f %f %f\n", &vnx, &vny, &vnz); input_normals.push_back({vnx, vny, vnz}); } }else if ((c2 == 'f') && (fgetc(file)==' ')){ //first f fscanf(file, "%d//%d %d//%d %d//%d\n", &fx, &fx, &fy, &fy, &fz, &fz); input_indices.push_back(fx-1); input_indices.push_back(fy-1); input_indices.push_back(fz-1); } }while(c1 != EOF && c2 != EOF); fclose(file); // make sure you don't forget to close the file when done unsigned i = 0; for ( ; i < input_vertices.size(); i++) { vertices.push_back(input_vertices[i]); normals.push_back(input_normals[i]); faces.push_back(input_indices[i]); } for (; i < input_indices.size(); i++) { faces.push_back(input_indices[i]); } } void OBJObject::center(){ float min_x = vertices[0].x, max_x = vertices[0].x; float min_y = vertices[0].y, max_y = vertices[0].y; float min_z = vertices[0].z, max_z = vertices[0].z; //find max and min of each dimension for (unsigned int i = 0; i < vertices.size(); i++) { if (vertices[i].x < min_x){ min_x = vertices[i].x; }else if (vertices[i].x > max_x){ max_x = vertices[i].x; } if (vertices[i].y < min_y){ min_y = vertices[i].y; }else if (vertices[i].y > max_y){ max_y = vertices[i].y; } if (vertices[i].z < min_z){ min_z = vertices[i].z; }else if (vertices[i].z > max_z){ max_z = vertices[i].z; } } //find midpoint float mid_x = (min_x + max_x) / 2; float mid_y = (min_y + max_y) / 2; float mid_z = (min_z + max_z) / 2; //center for (unsigned int i = 0; i < vertices.size(); ++i) { //center vertices[i].x -= mid_x; vertices[i].y -= mid_y; vertices[i].z -= mid_z; } } void OBJObject::update() { //move(); } void OBJObject::move(){ } glm::vec3 OBJObject::getCenter(){ float min_x = vertices[0].x, max_x = vertices[0].x; float min_y = vertices[0].y, max_y = vertices[0].y; float min_z = vertices[0].z, max_z = vertices[0].z; //find max and min of each dimension for (unsigned int i = 0; i < vertices.size(); i++) { if (vertices[i].x < min_x){ min_x = vertices[i].x; }else if (vertices[i].x > max_x){ max_x = vertices[i].x; } if (vertices[i].y < min_y){ min_y = vertices[i].y; }else if (vertices[i].y > max_y){ max_y = vertices[i].y; } if (vertices[i].z < min_z){ min_z = vertices[i].z; }else if (vertices[i].z > max_z){ max_z = vertices[i].z; } } //find midpoint float mid_x = (min_x + max_x) / 2; float mid_y = (min_y + max_y) / 2; float mid_z = (min_z + max_z) / 2; return glm::vec3(mid_x, mid_y, mid_z); } void OBJObject::spin(float deg) { this->angle += deg; if (this->angle > 360.0f || this->angle < -360.0f) this->angle = 0.0f; // This creates the matrix to rotate the cube this->toWorld = glm::rotate(glm::mat4(1.0f), this->angle / 180.0f * glm::pi<float>(), glm::vec3(0.0f, 1.0f, 0.0f)); } void OBJObject::scale(float s){ glm::vec3 scaled = glm::vec3(s,s,s); glm::mat4 scaling = glm::scale(glm::mat4(), scaled); this->toWorld = scaling * this->toWorld; } //void OBJObject::rotate(float angle, glm::vec3 axis){ // glm::mat4 matrix = glm::rotate(glm::mat4(1.0f), angle / 180.0f * glm::pi<float>(), axis); // this->toWorld = matrix * this->toWorld; //} void OBJObject::translate(float x, float y, float z) { glm::mat4 translationMat = glm::translate(glm::mat4(1.0f), glm::vec3(x, y, z)); this->toWorld = translationMat * this->toWorld; } void OBJObject::translate(glm::vec3 v) { glm::mat4 translationMat = glm::translate(glm::mat4(1.0f), glm::vec3(v.x, v.y, v.z)); this->toWorld = translationMat * this->toWorld; } ////////////// /** Load a ppm file from disk. @input filename The location of the PPM file. If the file is not found, an error message will be printed and this function will return 0 @input width This will be modified to contain the width of the loaded image, or 0 if file not found @input height This will be modified to contain the height of the loaded image, or 0 if file not found @return Returns the RGB pixel data as interleaved unsigned chars (R0 G0 B0 R1 G1 B1 R2 G2 B2 .... etc) or 0 if an error ocured **/ unsigned char* OBJObject::loadPPM(const char* filename, int& width, int& height) { const int BUFSIZE = 128; FILE* fp; unsigned int read; unsigned char* rawData; char buf[3][BUFSIZE]; char* retval_fgets; size_t retval_sscanf; if ( (fp=fopen(filename, "rb")) == NULL) { std::cerr << "error reading ppm file, could not locate " << filename << std::endl; width = 0; height = 0; return NULL; } // Read magic number: retval_fgets = fgets(buf[0], BUFSIZE, fp); // Read width and height: do { retval_fgets=fgets(buf[0], BUFSIZE, fp); } while (buf[0][0] == '#'); retval_sscanf=sscanf(buf[0], "%s %s", buf[1], buf[2]); width = atoi(buf[1]); height = atoi(buf[2]); // Read maxval: do { retval_fgets=fgets(buf[0], BUFSIZE, fp); } while (buf[0][0] == '#'); // Read image data: rawData = new unsigned char[width * height * 3]; read = fread(rawData, width * height * 3, 1, fp); fclose(fp); if (read != 1) { std::cerr << "error parsing ppm file, incomplete data" << std::endl; delete[] rawData; width = 0; height = 0; return NULL; } return rawData; } // load image file into texture object void OBJObject::loadTexture() { GLuint texture[1]; // storage for one texture int twidth, theight; // texture width/height [pixels] unsigned char* tdata; // texture pixel data // Load image file tdata = loadPPM("mochi.PPM", twidth, theight); if (tdata==NULL) return; // Create ID for texture glGenTextures(1, &texture[0]); // Set this texture to be the one we are working with glBindTexture(GL_TEXTURE_2D, texture[0]); glActiveTexture(GL_TEXTURE0+0); // Generate the texture glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, twidth, theight, 0, GL_RGB, GL_UNSIGNED_BYTE, tdata); // Set bi-linear filtering for both minification and magnification glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); }
0f4a9f4607006897276a338a60a1520a0bb4708d
c094d381422c2788d67a3402cff047b464bf207b
/c++_primer_plus/c++_primer_plus/p218函数实现模块化编程.cpp
e8744d86ebdea3571cff5fe03e49f8b9096cf8c1
[]
no_license
liuxuanhai/C-code
cba822c099fd4541f31001f73ccda0f75c6d9734
8bfeab60ee2f8133593e6aabfeefaf048357a897
refs/heads/master
2020-04-18T04:26:33.246444
2016-09-05T08:32:33
2016-09-05T08:32:33
67,192,848
1
0
null
null
null
null
UTF-8
C++
false
false
1,312
cpp
#include <iostream> const int Max = 5; int fill_array(double ar[], int limit); void show_array(const double ar[], int n); void revalue(double r, double ar[], int n); int main() { using namespace std; double properties[Max]; int size = fill_array(properties, Max); cout << size; show_array(properties, size); if (size > 0) { cout << "Enter revaluation factor: "; double factor; while (!(cin >> factor)) { cin.clear(); while (cin.get() != '\n') continue; cout << "Bad input; Please enter a number: "; } revalue(factor, properties, size); show_array(properties, size); } cout << "Done.\n"; cin.get(); cin.get(); return 0; } int fill_array(double ar[], int limit) { using namespace std; double temp; int i; for (i = 0; i < limit; i++) { cout << "Enter value #" << (i + 1) << ": "; cin >> temp; if (!cin) { cin.clear(); while (cin.get() != '\n') continue; cout << "Bad input; input process terminate.\n"; break; } else if (temp < 0) break; ar[i] = temp; } return i; } void show_array(const double ar[], int n) { using namespace std; for (int i = 0; i < n; i++) { cout << "Property #" << (i + 1) << ": $"; cout << ar[i] << endl; } } void revalue(double r, double ar[], int n) { for (int i = 0; i < n; i++) ar[i] *= r; }
9734f0d37968549a163ca05a59c421ae22fd9cec
52ca17dca8c628bbabb0f04504332c8fdac8e7ea
/boost/tti/gen/has_static_member_function_gen.hpp
c01f5899e742fdc51c5d280bb106f2422ecdec1a
[]
no_license
qinzuoyan/thirdparty
f610d43fe57133c832579e65ca46e71f1454f5c4
bba9e68347ad0dbffb6fa350948672babc0fcb50
refs/heads/master
2021-01-16T17:47:57.121882
2015-04-21T06:59:19
2015-04-21T06:59:19
33,612,579
0
0
null
2015-04-08T14:39:51
2015-04-08T14:39:51
null
UTF-8
C++
false
false
84
hpp
#include "thirdparty/boost_1_58_0/boost/tti/gen/has_static_member_function_gen.hpp"
187197842d27adfe4a2e4a2876218844c9f27584
1b720a8780b150eb623352597ae09f1a0180f799
/Resources/app/src/binary_build/squwbs/HP12.h
be64117dd53b3a3c5ba31d9715a6fb56d59f1de0
[ "MIT" ]
permissive
bgamut/squwbs_pro
51ec4e9416adcb881867628707de19676817ccbb
8c402d94a21bd2877f27dfc15734c4dfb003ec76
refs/heads/master
2022-12-21T13:17:19.027827
2020-02-25T11:49:38
2020-02-25T11:49:38
224,197,232
0
0
null
null
null
null
UTF-8
C++
false
false
1,535
h
/* ============================================================================== HP12.h Created: 4 Feb 2018 3:40:50pm Author: cumbe ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" #include "math.h" //============================================================================== /* */ class HP12 : public Component { public: HP12(): cutoff(750.0), resonance(0.0), buf0(0.0), buf1(0.0), sampleRate(44100.0) { calculateFeedbackAmount(); } ~HP12() { } float process(float inputValue){ buf0 += cutoff * (inputValue - buf0 + feedbackAmount * (buf0 - buf1)); //buf0 += cutoff * (inputValue - buf0); buf1 += cutoff * (buf0 - buf1); return inputValue - buf1; } void set(float newCutoff) { cutoff = 2*sin((float_Pi)*newCutoff/sampleRate); calculateFeedbackAmount(); } void setResonance(float newResonance){ resonance = newResonance; calculateFeedbackAmount(); } void setSampleRate(float sr){ sampleRate=sr; } private: float cutoff; float resonance; float feedbackAmount; void calculateFeedbackAmount() { feedbackAmount = resonance + resonance/(1.0 - cutoff); } float sampleRate; float buf0; float buf1; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HP12) };
66d8dc6de7661aa4963464ee27f735ce245fd952
5af86ef814f7b2655fce9bb1cc29eccaf2eb6576
/system-c/qt/20100818/6mytextedit-1/mainwindow.h
c8d05e18af4d48b3970b2c5a25386d20f7abbfd9
[]
no_license
Jacob-jiangbo/jacob-studio
537a5cb8105ea8bcd0f549b59de68f75fb10797f
c1b22e04fa98ede035b90af588444c1228750f5c
refs/heads/master
2022-04-18T01:02:25.006592
2020-04-03T08:48:48
2020-04-03T08:48:48
18,630,560
0
0
null
null
null
null
UTF-8
C++
false
false
582
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include "QtGui/QTextEdit" namespace Ui { class MainWindow; } class myTextEdit: public QTextEdit { Q_OBJECT public: QString outstr; myTextEdit(QWidget *parent); public slots: void slot_test(bool); }; class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = 0); ~MainWindow(); protected: void changeEvent(QEvent *e); private: Ui::MainWindow *ui; myTextEdit *mytextedit; }; #endif // MAINWINDOW_H
310a10cc93919b990a7560ba63db51bcc6feb630
6dad8696136ce04919c014011bcabd9a3edef3b1
/Terrace Source/codes/calibration/z_cameraModel.cpp
51da1b6c99560816bb585b3ee2d90f8fd1c76a26
[]
no_license
lochuynh211/Pedestrian-Tracking
0e0342a2ade24591846c4c7975d2fe75c8bd184c
0a02fb089ed8586dded8b481490d5e0d3dc72442
refs/heads/master
2021-01-10T23:20:43.861527
2016-10-11T14:07:33
2016-10-11T14:07:33
70,596,584
0
0
null
null
null
null
UTF-8
C++
false
false
8,548
cpp
/*************************************************************************** * cameraModel.cpp - description * * This program is part of the Etiseo project. * * See http://www.etiseo.net http://www.silogic.fr * * (C) Silogic - Etiseo Consortium ***************************************************************************/ #include <math.h> #include "z_cameraModel.h" CameraModel::CameraModel() { } CameraModel::~CameraModel() { } void CameraModel::internalInit() { double sa; double ca; double sb; double cb; double sg; double cg; // compute matrix ... sa = sin(mRx); ca = cos(mRx); sb = sin(mRy); cb = cos(mRy); sg = sin(mRz); cg = cos(mRz); mR11 = cb * cg; mR12 = cg * sa * sb - ca * sg; mR13 = sa * sg + ca * cg * sb; mR21 = cb * sg; mR22 = sa * sb * sg + ca * cg; mR23 = ca * sb * sg - cg * sa; mR31 = -sb; mR32 = cb * sa; mR33 = ca * cb; //compute camera position mCposx = -(mTx*mR11 + mTy*mR21 + mTz*mR31); mCposy = -(mTx*mR12 + mTy*mR22 + mTz*mR32); mCposz = -(mTx*mR13 + mTy*mR23 + mTz*mR33); } void CameraModel::setGeometry(int width, int height, double ncx, double nfx, double dx, double dy, double dpx, double dpy) { mImgWidth = width; mImgHeight = height; mNcx = ncx; mNfx = nfx; mDx = dx; mDy = dy; mDpx = dpx; mDpy = dpy; } void CameraModel::setIntrinsic(double focal, double kappa1, double cx, double cy, double sx) { mFocal = focal; mKappa1 = kappa1; mCx = cx; mCy = cy; mSx = sx; } void CameraModel::setExtrinsic(double tx, double ty, double tz, double rx, double ry, double rz) { mTx = tx; mTy = ty; mTz = tz; mRx = rx; mRy = ry; mRz = rz; } bool CameraModel::imageToWorld(double Xi, double Yi, double Zw, double& Xw, double& Yw) { bool done; double Xd; double Yd; double Xu; double Yu; double common_denominator; /* convert from image to distorted sensor coordinates */ Xd = mDpx * (Xi - mCx) / mSx; Yd = mDpy * (Yi - mCy); /* convert from distorted sensor to undistorted sensor plane coordinates */ distortedToUndistortedSensorCoord (Xd, Yd, Xu, Yu); /* calculate the corresponding xw and yw world coordinates */ /* (these equations were derived by simply inverting */ /* the perspective projection equations using Macsyma) */ common_denominator = ((mR11 * mR32 - mR12 * mR31) * Yu + (mR22 * mR31 - mR21 * mR32) * Xu - mFocal * mR11 * mR22 + mFocal * mR12 * mR21); Xw = (((mR12 * mR33 - mR13 * mR32) * Yu + (mR23 * mR32 - mR22 * mR33) * Xu - mFocal * mR12 * mR23 + mFocal * mR13 * mR22) * Zw + (mR12 * mTz - mR32 * mTx) * Yu + (mR32 * mTy - mR22 * mTz) * Xu - mFocal * mR12 * mTy + mFocal * mR22 * mTx) / common_denominator; Yw = -(((mR11 * mR33 - mR13 * mR31) * Yu + (mR23 * mR31 - mR21 * mR33) * Xu - mFocal * mR11 * mR23 + mFocal * mR13 * mR21) * Zw + (mR11 * mTz - mR31 * mTx) * Yu + (mR31 * mTy - mR21 * mTz) * Xu - mFocal * mR11 * mTy + mFocal * mR21 * mTx) / common_denominator; done = true; return done; } void CameraModel::distortedToUndistortedSensorCoord (double Xd, double Yd, double& Xu, double& Yu) { double distortion_factor; /* convert from distorted to undistorted sensor plane coordinates */ distortion_factor = 1 + mKappa1 * (Xd*Xd + Yd*Yd); Xu = Xd * distortion_factor; Yu = Yd * distortion_factor; } bool CameraModel::worldToImage(double Xw, double Yw, double Zw, double& Xi, double& Yi) { bool done = false; double xc; double yc; double zc; double Xu; double Yu; double Xd; double Yd; /* convert from world coordinates to camera coordinates */ xc = mR11 * Xw + mR12 * Yw + mR13 * Zw + mTx; yc = mR21 * Xw + mR22 * Yw + mR23 * Zw + mTy; zc = mR31 * Xw + mR32 * Yw + mR33 * Zw + mTz; /* convert from camera coordinates to undistorted sensor plane coordinates */ Xu = mFocal * xc / zc; Yu = mFocal * yc / zc; /* convert from undistorted to distorted sensor plane coordinates */ undistortedToDistortedSensorCoord (Xu, Yu, Xd, Yd); /* convert from distorted sensor plane coordinates to image coordinates */ Xi = Xd * mSx / mDpx + mCx; Yi = Yd / mDpy + mCy; //cout<<Xu<<" "<<Yu<<" "<<Xd<<" "<<Yd<<" "<<Xi<<" "<<Yi<<"\n"; done = true; return done; } void CameraModel::undistortedToDistortedSensorCoord (double Xu, double Yu, double& Xd, double& Yd) { double Ru; double Rd; double lambda; double c; double d; double Q; double R; double D; double S; double T; double sinT; double cosT; if (((Xu == 0) && (Yu == 0)) || (mKappa1 == 0)) { Xd = Xu; Yd = Yu; } else { Ru = sqrt(Xu*Xu + Yu*Yu); c = 1.0 / mKappa1; d = -c * Ru; Q = c / 3; R = -d / 2; D = Q*Q*Q + R*R; if (D >= 0) { /* one real root */ D = sqrt(D); if (R + D > 0) { S = pow(R + D, 1.0/3.0); } else { S = -pow(-R - D, 1.0/3.0); } if (R - D > 0) { T = pow(R - D, 1.0/3.0); } else { T = -pow(D - R, 1.0/3.0); } Rd = S + T; if (Rd < 0) { Rd = sqrt(-1.0 / (3 * mKappa1)); /*fprintf (stderr, "\nWarning: undistorted image point to distorted image point mapping limited by\n"); fprintf (stderr, " maximum barrel distortion radius of %lf\n", Rd); fprintf (stderr, " (Xu = %lf, Yu = %lf) -> (Xd = %lf, Yd = %lf)\n\n", Xu, Yu, Xu * Rd / Ru, Yu * Rd / Ru);*/ } } else { /* three real roots */ D = sqrt(-D); S = pow( sqrt(R*R + D*D) , 1.0/3.0 ); T = atan2(D, R) / 3; sinT = sin(T); cosT = cos(T); /* the larger positive root is 2*S*cos(T) */ /* the smaller positive root is -S*cos(T) + SQRT(3)*S*sin(T) */ /* the negative root is -S*cos(T) - SQRT(3)*S*sin(T) */ Rd = -S * cosT + sqrt(3.0) * S * sinT; /* use the smaller positive root */ } lambda = Rd / Ru; Xd = Xu * lambda; Yd = Yu * lambda; } } bool CameraModel::undistortedToDistortedImageCoord (double Xfu, double Yfu, double& Xfd, double& Yfd) { bool done = false; double Xu; double Yu; double Xd; double Yd; /* convert from image to sensor coordinates */ Xu = mDpx * (Xfu - mCx) / mSx; Yu = mDpy * (Yfu - mCy); /* convert from undistorted sensor to distorted sensor plane coordinates */ undistortedToDistortedSensorCoord (Xu, Yu, Xd, Yd); /* convert from sensor to image coordinates */ Xfd = Xd * mSx / mDpx + mCx; Yfd = Yd / mDpy + mCy; done = true; return done; } bool CameraModel::distortedToUndistortedImageCoord (double Xfd, double Yfd, double& Xfu, double& Yfu) { bool done = false; double Xd; double Yd; double Xu; double Yu; /* convert from image to sensor coordinates */ Xd = mDpx * (Xfd - mCx) / mSx; Yd = mDpy * (Yfd - mCy); /* convert from distorted sensor to undistorted sensor plane coordinates */ distortedToUndistortedSensorCoord (Xd, Yd, Xu, Yu); /* convert from sensor to image coordinates */ Xfu = Xu * mSx / mDpx + mCx; Yfu = Yu / mDpy + mCy; done = true; return done; } bool CameraModel::worldToCameraCoord (double xw, double yw, double zw, double& xc, double& yc, double& zc) { bool done = false; xc = mR11 * xw + mR12 * yw + mR13 * zw + mTx; yc = mR21 * xw + mR22 * yw + mR23 * zw + mTy; zc = mR31 * xw + mR32 * yw + mR33 * zw + mTz; done = true; return done; } bool CameraModel::cameraToWorldCoord (double xc, double yc, double zc, double& xw, double& yw, double& zw) { bool done = false; double common_denominator; /* these equations were found by simply inverting the previous routine using Macsyma */ common_denominator = ((mR11 * mR22 - mR12 * mR21) * mR33 + (mR13 * mR21 - mR11 * mR23) * mR32 + (mR12 * mR23 - mR13 * mR22) * mR31); xw = ((mR12 * mR23 -mR13 * mR22) * zc + (mR13 * mR32 - mR12 * mR33) * yc + (mR22 * mR33 - mR23 * mR32) * xc + (mR13 * mR22 - mR12 * mR23) * mTz + (mR12 * mR33 - mR13 * mR32) * mTy + (mR23 * mR32 - mR22 * mR33) * mTx) / common_denominator; yw = -((mR11 * mR23 - mR13 * mR21) * zc + (mR13 * mR31 - mR11 * mR33) * yc + (mR21 * mR33 - mR23 * mR31) * xc + (mR13 * mR21 - mR11 * mR23) * mTz + (mR11 * mR33 - mR13 * mR31) * mTy + (mR23 * mR31 - mR21 * mR33) * mTx) / common_denominator; zw = ((mR11 * mR22 - mR12 * mR21) * zc + (mR12 * mR31 - mR11 * mR32) * yc + (mR21 * mR32 - mR22 * mR31) * xc + (mR12 * mR21 - mR11 * mR22) * mTz + (mR11 * mR32 - mR12 * mR31) * mTy + (mR22 * mR31 - mR21 * mR32) * mTx) / common_denominator; return true; }
e8ab90dd431aac3f8079261d33083e3fd3c2d2ff
c6fa1b9f90044ad35097b01e6671b09d4252db13
/145 reversible numbers/main.cpp
e3299d0bea17ee9c3f8669846347bb772b5cbd34
[]
no_license
fangzhou070101/Project_Euler
5d84be3dd6f1b3165307bd945ce3911915e574c9
7476b3a3444044232b9037785e3cf63d2acfbf8c
refs/heads/master
2022-03-11T19:22:04.949271
2022-03-02T03:29:23
2022-03-02T03:29:23
41,497,563
0
0
null
null
null
null
UTF-8
C++
false
false
487
cpp
#include <iostream> using namespace std; int rev(int n); bool allOdd(int n); int main() { int n,tot; for(n=1;n<1000000000;n++) { if(n%10!=0 && allOdd(n+rev(n))) tot++; } cout<<tot; return 0; } int rev(int n) { int r=0; do { r*=10; r+=n%10; n/=10; }while(n!=0); return r; } bool allOdd(int n) { do { if(n%2==0) return false; n/=10; }while(n!=0); return true; }
c05fdcf39cc9fc6a8d4b41e42ce086b1ad6ff8cd
341e111a9ff68c1266c8609ad42c6d8a6e5f2a11
/app/src/main/cpp/core/trunk/main/framework/protocol_help_package/src/commonconnectioncallbackimpl.cpp
b70d8e06532f5562878717739e698b32ed314bf8
[]
no_license
chengchuishu/ysos_platform_as812
91131dc777f263d18c31efe1e6bb839c71b4afb2
acb12f01d1e307b459a418ed5865f2581de68a00
refs/heads/main
2023-05-13T13:56:59.951152
2021-06-03T02:47:50
2021-06-03T02:47:50
373,361,526
0
0
null
null
null
null
UTF-8
C++
false
false
8,341
cpp
/* # commonconnectioncallbackimpl.cpp # Definition of commonconnectioncallbackimpl # Created on: 2016-06-03 16:43:58 # Original author: jinchengzhe # Copyright (c) 2016 YunShen Technology. All rights reserved. # # version 0.1, 20160912, created by JinChengZhe */ /// Private Headers #include "../../../protect/include/protocol_help_package/commonconnectioncallbackimpl.h" /// ThirdParty Headers #include <boost/thread.hpp> #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_generators.hpp> #include <boost/uuid/uuid_io.hpp> /// Platform Headers #include "../../../protect/include/protocol_help_package/basetransportcallbackimpl.h" #include "../../../public/include/core_help_package/utility.h" #include "../../../public/include/os_hal_package/bufferutility.h" #include "../../../protect/include/protocol_help_package/platformprotocolimpl.h" namespace ysos { static const char* g_error_param_error_code = "error_code"; static const char* g_error_param_callback_type = "callback_type"; static const char* g_error_param_description = "description"; bool CommonConnectionCallbackImpl::ConnectionCallbackErrorParam::ToString(std::string& to_string) { bool result = false; do { JsonValue json_value_error_param; PlatformProtocolImpl::PlatformProtocolParamPair platform_protocol_param_pair; platform_protocol_param_pair.first = g_error_param_error_code; platform_protocol_param_pair.second = GetUtility()->ConvertToString(error_code); PlatformProtocolImpl::JsonObjectFromStringPair(platform_protocol_param_pair, json_value_error_param); platform_protocol_param_pair.first = g_error_param_callback_type; platform_protocol_param_pair.second = callback_type; PlatformProtocolImpl::JsonObjectFromStringPair(platform_protocol_param_pair, json_value_error_param); platform_protocol_param_pair.first = g_error_param_description; platform_protocol_param_pair.second = description; PlatformProtocolImpl::JsonObjectFromStringPair(platform_protocol_param_pair, json_value_error_param); if (YSOS_ERROR_SUCCESS != PlatformProtocolImpl::JsonValueToString(json_value_error_param, to_string)) { break; } result = true; } while (0); return result; } bool CommonConnectionCallbackImpl::ConnectionCallbackErrorParam::FromString(const std::string& from_string) { bool result = false; do { JsonValue json_value_result; if (YSOS_ERROR_SUCCESS != PlatformProtocolImpl::JsonObjectFromString(from_string, json_value_result)) { break; } /// error_code if ( true == json_value_result.isMember(g_error_param_error_code) && true == json_value_result[g_error_param_error_code].isString() ) { uint32_t i = 0; error_code = GetUtility()->ConvertFromString(json_value_result[g_error_param_error_code].asString(), i); } /// callback_type if ( true == json_value_result.isMember(g_error_param_callback_type) && true == json_value_result[g_error_param_callback_type].isString() ) { callback_type = json_value_result[g_error_param_callback_type].asString(); } /// description if ( true == json_value_result.isMember(g_error_param_description) && true == json_value_result[g_error_param_description].isString() ) { description = json_value_result[g_error_param_description].asString(); } result = true; } while (0); return result; } CommonConnectionCallbackImpl::CommonConnectionCallbackImpl(const std::string &strClassName /* =CommonConnectionCallbackImpl */) : BaseInterfaceImpl(strClassName), mode_(CLIENT), address_("127.0.0.1"), port_(0), buffer_length_(0), buffer_number_(0), enable_wrap_(true), enable_read_(true), enable_write_(true), transport_callback_ptr_(NULL) { logger_ = GetUtility()->GetLogger("ysos.sdk"); if (YSOS_ERROR_SUCCESS != Initialize()) { YSOS_LOG_DEBUG("CommonConnectionCallbackImpl::Initialize[Fail][The function[Initialize()] is failed]"); } } CommonConnectionCallbackImpl::~CommonConnectionCallbackImpl() { if (NULL != transport_callback_ptr_) { transport_callback_ptr_ = NULL; } } int CommonConnectionCallbackImpl::Initialize(void *param) { YSOS_LOG_DEBUG("CommonConnectionCallbackImpl::Initialize[Enter]"); if (NULL == transport_callback_ptr_) { YSOS_LOG_DEBUG("CommonConnectionCallbackImpl::Initialize[Check Point][0]"); transport_callback_ptr_ = TransportCallbackInterfacePtr(BaseTransportCallbackImpl::CreateInstance()); if (NULL == transport_callback_ptr_) { YSOS_LOG_DEBUG("CommonConnectionCallbackImpl::Initialize[Fail][0]"); return YSOS_ERROR_FAILED; } } YSOS_LOG_DEBUG("CommonConnectionCallbackImpl::Initialize[Exit]"); return YSOS_ERROR_SUCCESS; } UINT32 CommonConnectionCallbackImpl::GetMode(void) { return mode_; } void CommonConnectionCallbackImpl::SetMode(const UINT32 mode) { mode_ = mode; transport_callback_ptr_->SetMode(SERVER == mode_ ? PROP_SERVER : PROP_CLIENT); if (SERVERTERMINAL == mode_) { transport_callback_ptr_->SetMode(PROP_SERVER_TERMINAL); } return; } std::string CommonConnectionCallbackImpl::GetAddress(void) { return address_; } void CommonConnectionCallbackImpl::SetAddress(const std::string &address) { address_ = address; transport_callback_ptr_->SetAddress(address_); return; } short CommonConnectionCallbackImpl::GetPort(void) { return port_; } void CommonConnectionCallbackImpl::SetPort(const short port) { port_ = port; transport_callback_ptr_->SetPort(port_); return; } bool CommonConnectionCallbackImpl::GetEnableWrap(void) { return enable_wrap_; } void CommonConnectionCallbackImpl::SetEnableWrap(const bool enable_wrap) { enable_wrap_ = enable_wrap; } bool CommonConnectionCallbackImpl::GetEnableRead(void) { return enable_read_; } void CommonConnectionCallbackImpl::SetEnableRead(const bool enable_read) { enable_read_ = enable_read; transport_callback_ptr_->SetEnableRead(enable_read_); return; } bool CommonConnectionCallbackImpl::GetEnableWrite(void) { return enable_write_; } void CommonConnectionCallbackImpl::SetEnableWrite(const bool enable_write) { enable_write_ = enable_write; transport_callback_ptr_->SetEnableWrite(enable_write_); return; } TransportCallbackInterfacePtr CommonConnectionCallbackImpl::GetTransportCallbackPtr(void) { return transport_callback_ptr_; } void CommonConnectionCallbackImpl::SetTransportCallbackPtr(const TransportCallbackInterfacePtr& transport_callback_ptr) { transport_callback_ptr_ = transport_callback_ptr; return; } unsigned int CommonConnectionCallbackImpl::GetBufferLength(void) { return buffer_length_; } void CommonConnectionCallbackImpl::SetBufferLength(unsigned int buffer_length) { buffer_length_ = buffer_length; return; } unsigned int CommonConnectionCallbackImpl::GetBufferNumber(void) { return buffer_number_; } void CommonConnectionCallbackImpl::SetBufferNumber(unsigned int buffer_number) { buffer_number_ = buffer_number; return; } void CommonConnectionCallbackImpl::HandleAccept(const boost::system::error_code& error_code, const ConnectionInterfacePtr& connection_ptr) { YSOS_LOG_DEBUG("CommonConnectionCallbackImpl::HandleAccept()"); } void CommonConnectionCallbackImpl::HandleConnect(const boost::system::error_code& error_code, const ConnectionInterfacePtr& connection_ptr) { YSOS_LOG_DEBUG("CommonConnectionCallbackImpl::HandleConnect()"); } void CommonConnectionCallbackImpl::HandleDisconnect(const boost::system::error_code& error_code, const ConnectionInterfacePtr& connection_ptr) { YSOS_LOG_DEBUG("CommonConnectionCallbackImpl::HandleDisconnect()"); } void CommonConnectionCallbackImpl::HandleRead(const BufferInterfacePtr& buffer_ptr, const ConnectionInterfacePtr& connection_ptr) { YSOS_LOG_DEBUG("CommonConnectionCallbackImpl::HandleRead()"); } void CommonConnectionCallbackImpl::HandleWrite(const BufferInterfacePtr& buffer_ptr, const ConnectionInterfacePtr& connection_ptr) { YSOS_LOG_DEBUG("CommonConnectionCallbackImpl::HandleWrite()"); } void CommonConnectionCallbackImpl::HandleError(const boost::system::error_code& error_code, const UINT32 callback_type, const ConnectionInterfacePtr& connection_ptr) { YSOS_LOG_DEBUG("CommonConnectionCallbackImpl::HandleError()"); } }
078ce65d582e6209a8f6d2da15d39f8c7b8f00e6
78cd1d08162358e33a9ab64f7094ac22f5f62c80
/src/snippets/geometry.cpp
a760c6419db057b527b2cea5e764dde6fd6c9eae
[]
no_license
hav4ik/contest-snippets
6858a56082a5fbba593053410db5d034486310ac
b7d37d94d12ffd4ba080f78d64e703b0a4ab1be5
refs/heads/master
2020-03-13T02:09:47.012470
2019-06-29T11:59:16
2019-06-29T11:59:16
130,919,085
2
0
null
null
null
null
UTF-8
C++
false
false
2,203
cpp
#include "common.hpp" MACROSNIPPET("head", "skeleton.snippets", "Geometry 2D", "Basic geometry operations and structs") /// Vector 2D and operations template<typename T> struct vec2 { T x, y; vec2(T u, T v): x(u), y(v) {} vec2<T>& operator= (const vec2<T>& a) { x=a.x; y=a.y; return *this; } }; template<typename T> bool operator== (const vec2<T>& a, const vec2<T>& b) { return b.x==a.x && b.y==a.y; } template<typename T> vec2<T> operator+ (const vec2<T>& a, const vec2<T>& b) { return vec2<T>(a.x+b.x,a.y+b.y); } template<typename T> vec2<T> operator- (const vec2<T>& a, const vec2<T>& b) { return vec2<T>(a.x-b.x,a.y-b.y); } template<typename T> vec2<T> operator* (const vec2<T>& a, T b) { return vec2<T>(a.x*b,a.y*b); } template<typename T> vec2<T> operator* (T a, const vec2<T>& b) { return vec2<T>(a*b.x,a*b.y); } template<typename T> vec2<T> operator/ (const vec2<T>& a, T b) { return vec2<T>(a.x/b,a.y/b); } template<typename T> inline T scalar(const vec2<T>& a, const vec2<T>& b) { return a.x*b.x+a.y*b.y; } template<typename T> inline T dot(const vec2<T>& a, const vec2<T>& b) { return a.x*b.y-a.y*b.x; } template<typename T> inline vec2<T> rot(const vec2<T>& v, double theta, const vec2<T>& anchor=vec2<T>(T(0), T(0))) { vec2<T> t = v - anchor; return vec2<T>(t.x*cos(theta)-t.y*sin(theta),t.x*sin(theta)+t.y*cos(theta)); } typedef vec2<int> vec2i; typedef vec2<float> vec2f; typedef vec2<double> vec2d; TABSTOP(0) TESTSNIPPET TEST(Geometry2D, SimpleOperations) { vec2i a(1, 2), b(3, 4); ASSERT_EQ(a == vec2i(1, 2), true); // operator==(vec2<T>, vec2<T>) ASSERT_EQ(a + b, vec2i(4, 6)); // operator+ (vec2<T>, vec2<T>) ASSERT_EQ(a - b, vec2i(-2, -2)); // operator- (vec2<T>, vec2<T>) ASSERT_EQ(a * 2, vec2i(2, 4)); // operator* (vec2<T>, T) ASSERT_EQ(2 * a, vec2i(2, 4)); // operator* (T, vec2<T>) ASSERT_EQ(a / 2, vec2i(0, 1)); // operator/ (vec2<T>, T) ASSERT_EQ(scalar(a, b), 11); // scalar product ASSERT_EQ(dot(a, b), -2); // dot product ASSERT_EQ(rot(a,M_PI/2.),vec2i(-2,1)); // rotation (with default anchor {0,0}) } ENDMACROSNIPPET
1e891cb65800e78921643af03604ac8be9e91ec1
3c6c0914530ccdd3808622138134e53118053dcf
/openvpn3-linux/src/common/utils.hpp
2a710c6e9f0a31d810cc152cc1a26496c1f7ef6a
[]
no_license
WeilerWebServices/OpenVPN
c788bc6ef5079c2ec2b147de4ff1fb7e3a975ec1
a3d6e4bf7bf0ddb6d548f315091f96a4147f67b1
refs/heads/master
2022-12-25T10:17:01.531589
2020-10-01T19:19:01
2020-10-01T19:19:01
255,415,557
2
0
null
null
null
null
UTF-8
C++
false
false
1,244
hpp
// OpenVPN 3 Linux client -- Next generation OpenVPN client // // Copyright (C) 2018 OpenVPN Inc <[email protected]> // Copyright (C) 2018 David Sommerseth <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, version 3 of the // License. // // 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // /** * @file utils.hpp * * @brief Misc utility functions */ #pragma once const char * package_version(); void drop_root(); std::string get_version(std::string component); const std::string get_guiversion(); int stop_handler(void *loop); void set_console_echo(bool echo); static inline std::string simple_basename(const std::string filename) { return filename.substr(filename.rfind('/')+1); }
1448402d4d9f328ff57083f333087b429427819f
198ab1f04fe64af050b428235ccb44f6ef35250d
/Singleton.cpp
698928fb313d3acc2087c3f4991ae4abdd89180d
[]
no_license
SlimeVRS/Design-Patterns
93439193c9593eee3149d0f260af86fe43756a6a
fffd8eaf138adb069dcc9f052f8ff18d3c570f62
refs/heads/master
2022-12-18T16:47:43.560108
2020-09-24T03:01:28
2020-09-24T03:01:28
298,142,699
0
0
null
null
null
null
UTF-8
C++
false
false
545
cpp
#include <iostream> class Singleton { private: static Singleton* instance; Singleton(); public: static Singleton* getInstance(); }; Singleton* Singleton::instance = 0; Singleton* Singleton::getInstance(){ if(instance == 0){ instance = new Singleton(); } return instance; } Singleton::Singleton(){} int main(){ Singleton* s = Singleton::getInstance(); Singleton* r = Singleton::getInstance(); std::cout << s << std::endl; std::cout << r << std::endl; }
7efd4a2aa3f84e2d6b89c984578544c31ac9dcda
b38439cf6b261713b44200b15163153b7eceb3a9
/JumpingOnTheCloud/JumpingOnTheCloud/JumpingOnTheCloud.cpp
ee27fe1ed33009ec9acccf5fe10ec429ad3ae654
[]
no_license
Suresh3d/CPP-Practice
0f4e9265ec8563a4a300b6891a729e7c4236e2a7
c2a66644c82e7a0c942ee4ba23626d47807ad1bc
refs/heads/master
2022-10-09T22:49:28.254916
2020-06-07T17:09:31
2020-06-07T17:09:31
269,586,876
0
0
null
null
null
null
UTF-8
C++
false
false
926
cpp
#include <iostream> #include <vector> using namespace std; bool isAvailable(vector<int> arr, int n) { bool isAvailable = false; for (int i = 0; i < arr.size(); i++) { if (arr[i] == n) { isAvailable = true; break; } } return isAvailable; } int jumpingOnTheCloud(int arr[], int n) { vector<int> avoid; for (int i = 0; i < n; i++) { if (arr[i]) avoid.push_back(i); } int c_p = 0; int jump = 0; bool J_Completed = false; while (!J_Completed) { if ((c_p + 2) <= n-1 && !isAvailable(avoid,c_p+2)) { jump++; c_p = c_p + 2; } else if ((c_p + 1) <= n - 1 && !isAvailable(avoid, c_p + 1)) { jump++; c_p = c_p + 1; } else { J_Completed = true; } } return jump; } int main() { int arr[7] = { 0, 0, 1, 0, 0, 1, 0 }; int n_jump = jumpingOnTheCloud(arr, 7); cout << n_jump << " "; return 0; }
d7683ab5106ab6f2c8b4e7853f6e5c55ae7c06a9
d0f614fcd9ec4e9ed7bf4bbae43c4e57339cf0f7
/src/Demos.cpp
b64aef42c4388ca8a8335fce1d6bb160f21950ae
[]
no_license
henne90gen/RacingToHell
6f0cda167b6432016ae8629f37047762b5456df5
4b928478ecc7ef1f3d9714721ab02e0c22947733
refs/heads/master
2023-03-15T13:57:49.191425
2023-03-10T11:27:57
2023-03-10T11:28:02
51,105,446
3
0
null
null
null
null
UTF-8
C++
false
false
5,612
cpp
#include "Demos.h" #include "Helper.h" #include "Renderer.h" #include <array> #include <fmt/core.h> void textDemo(Platform &platform, AtomPlane plane) { static std::array<std::string, 3> fontFileNames = { "res/font/DejaVuSansMono.ttf", "res/font/ComicSans.ttf", "res/font/Arial.ttf", }; static int fontIndex = 0; if (platform.input.enterKeyClicked) { loadFont(platform, fontFileNames[fontIndex]); fontIndex++; if (fontIndex >= 3) { fontIndex = 0; } } GameState *gameState = getGameState(platform); Math::Rectangle rect = {}; rect.position = glm::vec2(-platform.memory.aspectRatio, 0.5); rect.size = glm::vec2(platform.memory.aspectRatio * 2.0f, 1.0); Render::pushRectangle(gameState, rect, glm::vec4(0, 1, 0, 1), plane - 1); std::string text = "The quick brown fox jumps over the lazy dog."; glm::vec2 position = glm::vec2(-1.7f, 0.3); const auto color = glm::vec4(1, 0, 1, 1); Render::pushText(gameState, text, position, Render::FontSize::Small, color, plane); position = glm::vec2(-1.7f, 0); Render::pushText(gameState, text, position, Render::FontSize::Medium, color, plane); position = glm::vec2(-1.7f, -0.35); Render::pushText(gameState, text, position, Render::FontSize::Large, color, plane); } void performanceDemo(Platform &platform, AtomType type) { GameState *gameState = getGameState(platform); AtomPlane plane = AtomPlane::AI; switch (type) { case AtomType::RECTANGLE: { Math::Rectangle dim = {}; dim.position = glm::vec2(0, 0); dim.size = glm::vec2(1, 1); Render::pushRectangle(gameState, dim, glm::vec4(1, 0, 0, 1), plane); } break; case AtomType::TEXTURE: { Render::Texture *texture = &gameState->resources.playerCarTextures[0]; glm::vec2 pos = glm::vec2(0, 0); glm::vec2 size = glm::vec2(1, 1); glm::vec2 dir = glm::vec2(1, 1); Render::pushTexture(gameState, texture, pos, size, dir, plane); } break; case AtomType::TRIANGLE: { glm::vec2 p1 = glm::vec2(1, 1); glm::vec2 p2 = glm::vec2(-1, 1); glm::vec2 p3 = glm::vec2(); Render::pushTriangle(gameState, p1, p2, p3, glm::vec4(1, 0, 0, 1), plane); } break; case AtomType::CIRCLE: { glm::vec2 position = glm::vec2(); Render::pushCircle(gameState, position, 1, glm::vec4(1, 0, 0, 1), plane); } break; case AtomType::TEXT: { glm::vec2 position = glm::vec2(-1.7f, 0.7); std::string msg = "The quick brown fox jumps over the lazy dog"; Render::pushText(gameState, msg, position, Render::FontSize::Medium, glm::vec4(1, 0, 0, 1), plane); } break; } } void performanceDemo(Platform &platform, AtomType type, int n) { for (int i = 0; i < n; i++) { performanceDemo(platform, type); } } void animationDemo(Platform &platform, AtomPlane plane) { GameState *gameState = getGameState(platform); Render::Texture *explosionTexture = &gameState->resources.explosion; static unsigned int explosionIndex3 = 0; glm::vec2 position = glm::vec2(1, 0); glm::vec2 size = glm::vec2(1, 1); Render::pushAnimation(gameState, explosionTexture, position, size, &explosionIndex3, plane, 3); static unsigned int explosionIndex2 = 0; if (explosionIndex2 >= explosionIndex3) { position = glm::vec2(); size = glm::vec2(1, 1); Render::pushAnimation(gameState, explosionTexture, position, size, &explosionIndex2, plane, 2); } static unsigned int explosionIndex1 = 0; if (explosionIndex1 >= explosionIndex3) { position = glm::vec2(-1, 0); size = glm::vec2(1, 1); Render::pushAnimation(gameState, explosionTexture, position, size, &explosionIndex1, plane); } } void followingCarDemo(Platform &platform) { GameState *gameState = getGameState(platform); if (platform.input.shootKeyPressed && gameState->agentCount < (int)sizeof(gameState->agents) / (int)sizeof(Player)) { platform.log(fmt::format("Spawning agent {}", gameState->agentCount)); gameState->agents[gameState->agentCount++] = Agent(); auto &agent = gameState->agents[gameState->agentCount - 1]; agent.position = platform.input.mousePosition; agent.size = glm::vec2(0.05f, 0.10f); agent.maxSpeed = PLAYER_SPEED; agent.carIndex = std::rand() % NUM_PLAYER_TEXTURES; } for (int i = 0; i < gameState->agentCount; i++) { auto &agent = gameState->agents[i]; Render::Texture *texture = &gameState->resources.playerCarTextures[agent.carIndex]; glm::vec2 desired = platform.input.mousePosition - agent.position; desired = glm::normalize(desired); desired = desired * static_cast<float>(agent.maxSpeed); glm::vec2 steering = desired - agent.velocity; steering = glm::normalize(steering); steering = steering * 0.00005f; agent.acceleration = agent.acceleration + steering; agent.velocity = agent.velocity + agent.acceleration; if (glm::length(agent.velocity) > agent.maxSpeed) { agent.velocity = glm::normalize(agent.velocity) * static_cast<float>(agent.maxSpeed); } agent.position = agent.position + agent.velocity; if (agent.velocity.x != 0.0f && agent.velocity.y != 0.0f) { agent.direction = agent.velocity; } Render::pushTexture(gameState, texture, agent.position, agent.size, agent.direction, 0, AtomPlane::PLAYER); } }
b4e352a413c3b44783d55bf168a48f6fa549d24b
9a2c1b2a59617f5367f14fd494a03c2c64c8a908
/WordText/renew.h
3511384b06318d8f3f779fc4413809b2c1ba2b69
[]
no_license
lizhenjie94/textword
dacf4d26ee4d6fa796fb9970208c5a42df76fa16
b58d5ff2b5aece050db2b3b60aee12800ddc35c9
refs/heads/master
2021-01-10T08:15:54.127601
2015-12-23T15:32:32
2015-12-23T15:32:32
48,487,254
0
1
null
null
null
null
UTF-8
C++
false
false
340
h
#ifndef RENEW_H #define RENEW_H #include <QDialog> namespace Ui { class Renew; } class Renew : public QDialog { Q_OBJECT public: explicit Renew(QWidget *parent = 0); ~Renew(); public slots: void openRenewproperty(); private: Ui::Renew *ui; private slots: void on_LineEdit_textChanged(); }; #endif // RENEW_H
f1d0ec72786c4334d87bfe5a7029031219272d59
884c41edb91b958c2250a05f3d03fe38002233c7
/src/AsioExecutionContext.hpp
422f6f4a6ed207c6907ee1c1c6871457540b7d72
[]
no_license
teams2ua/lib-core-cmd
1639071f90ba567be79be9a14dfbf0060e1d9c5b
8d4274bb44624469bc6cc3c50d3156800bdc08c4
refs/heads/master
2021-07-10T03:27:48.073834
2020-07-15T10:21:01
2020-07-15T10:21:01
171,478,879
1
1
null
null
null
null
UTF-8
C++
false
false
727
hpp
#pragma once #include "api/ExecutionContext.hpp" #include <boost/asio.hpp> #include <queue> #include <mutex> namespace ledger { namespace core { namespace api { class Runnable; }; } } class AsioExecutionContext : public ledger::core::api::ExecutionContext { public: void execute(const std::shared_ptr<ledger::core::api::Runnable> & runnable) override; void delay(const std::shared_ptr<ledger::core::api::Runnable> & runnable, int64_t millis) override; void start(); void stop(); public: boost::asio::io_service _io_service; private: std::queue<std::shared_ptr<ledger::core::api::Runnable>> q; std::mutex _lock; bool shouldStop{false}; std::thread executionThread; };
8ba88e502f4b94c67d18ba9219a4eb2ac7f5e9c4
70f8491a27470287090d3c2be061d5fce23f07a9
/algorithms/p520/520.hpp
914b98078ed7ae1b918e1fa964df75da6ca9ac3b
[ "Apache-2.0" ]
permissive
baishuai/leetcode
44094a91e95c0557394cf15324008f79fc2d6688
440ff08cf15e03ee64b3aa18370af1f75e958d18
refs/heads/master
2021-09-01T01:02:33.335046
2017-12-24T01:01:47
2017-12-24T01:01:47
84,698,557
10
1
null
null
null
null
UTF-8
C++
false
false
804
hpp
#ifndef LEETCODE_520_HPP #define LEETCODE_520_HPP #include <iostream> #include <queue> #include <algorithm> #include <vector> #include <unordered_map> #include <unordered_set> #include <set> #include <numeric> #include <stack> #include <string> using namespace std; class Solution { public: bool detectCapitalUse(string word) { if (word.size() <= 1) return true; if (word[0] > 'Z') return word[1] > 'Z' && allCapletters(word, false); else return allCapletters(word, word[1] <= 'Z'); } private: bool allCapletters(string &word, bool flag) { for (int i = 2; i < word.size(); ++i) { if ((word[i] <= 'Z') != flag) return false; } return true; } }; #endif //LEETCODE_520_HPP
ef4834ce77109db3b6e205cce2944bde1e2f5cbe
67e5ed145e918dd2ad3edf4de93987fa9af971f4
/archive_code/encoder_arduino/encoder_arduino.ino
d8604262941f1960c06d98db84f577bfad84b3bc
[ "MIT" ]
permissive
kavli-ntnu/wheel_tracker
34f4d7a2ca83ae99374648af1d5f6ce03d9fd56e
30f90691ffaeea564cdb174bb9e715dea8a0d10e
refs/heads/master
2023-04-02T05:20:33.672657
2023-03-20T13:44:30
2023-03-20T13:44:30
129,443,866
0
1
MIT
2023-03-20T13:44:32
2018-04-13T19:15:34
C++
UTF-8
C++
false
false
1,557
ino
/* Rotary encoder code Sends values "newPosition" over serial. */ #include <Encoder.h> elapsedMillis interval_timer; // for regular intervals elapsedMillis measure_timer; // measure frameclock unsigned int interval_ = 25; // time in ms between serial events int frameclock_pin = 3; int beambreak_pin = 17; int sync_pin = 4; // "wheel serial" int sync_beambreak_pin = 15; bool measurement = false; bool start_clock = true; int sync_state = LOW; int status_measure; int status_beambreak; Encoder myEnc(1,0); void setup() { Serial.begin(250000); pinMode(frameclock_pin, INPUT); pinMode(beambreak_pin, INPUT); pinMode(sync_pin, OUTPUT); pinMode(sync_beambreak_pin, OUTPUT); } void loop() { long newPosition = myEnc.read(); status_measure = digitalReadFast(frameclock_pin); status_beambreak = digitalReadFast(beambreak_pin); if (status_measure == HIGH){ measurement = true; if (start_clock == true){ interval_timer = interval_; start_clock = false; } measure_timer = 0; } if (measurement == true){ if (interval_timer >= interval_){ interval_timer = interval_timer-interval_; digitalWrite(sync_pin, HIGH); if (status_beambreak == LOW){ // beam break goes low when interrupted digitalWrite(sync_beambreak_pin, HIGH); } Serial.println(newPosition); delay(5); digitalWrite(sync_pin, LOW); digitalWrite(sync_beambreak_pin, LOW); } } if(measure_timer > 1000){ measurement = false; start_clock = true; } }
5e3f1450a7071f290432f7a4418c0d3241301d87
d6b4bdf418ae6ab89b721a79f198de812311c783
/redis/include/tencentcloud/redis/v20180412/model/DescribeTaskListResponse.h
897eaee9a3ee1a0400d9e2b78cbf984e14a21f79
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp-intl-en
d0781d461e84eb81775c2145bacae13084561c15
d403a6b1cf3456322bbdfb462b63e77b1e71f3dc
refs/heads/master
2023-08-21T12:29:54.125071
2023-08-21T01:12:39
2023-08-21T01:12:39
277,769,407
2
0
null
null
null
null
UTF-8
C++
false
false
3,010
h
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TENCENTCLOUD_REDIS_V20180412_MODEL_DESCRIBETASKLISTRESPONSE_H_ #define TENCENTCLOUD_REDIS_V20180412_MODEL_DESCRIBETASKLISTRESPONSE_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/AbstractModel.h> #include <tencentcloud/redis/v20180412/model/TaskInfoDetail.h> namespace TencentCloud { namespace Redis { namespace V20180412 { namespace Model { /** * DescribeTaskList response structure. */ class DescribeTaskListResponse : public AbstractModel { public: DescribeTaskListResponse(); ~DescribeTaskListResponse() = default; CoreInternalOutcome Deserialize(const std::string &payload); std::string ToJsonString() const; /** * 获取Total number of tasks * @return TotalCount Total number of tasks * */ int64_t GetTotalCount() const; /** * 判断参数 TotalCount 是否已赋值 * @return TotalCount 是否已赋值 * */ bool TotalCountHasBeenSet() const; /** * 获取Task details * @return Tasks Task details * */ std::vector<TaskInfoDetail> GetTasks() const; /** * 判断参数 Tasks 是否已赋值 * @return Tasks 是否已赋值 * */ bool TasksHasBeenSet() const; private: /** * Total number of tasks */ int64_t m_totalCount; bool m_totalCountHasBeenSet; /** * Task details */ std::vector<TaskInfoDetail> m_tasks; bool m_tasksHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_REDIS_V20180412_MODEL_DESCRIBETASKLISTRESPONSE_H_
5e2ee3da86072e587aabace96c0fb1c3ce20805e
6310aab78aee0a1b422e1b159f60c244d81e0821
/boj1764/boj1764/소스.cpp
b72f6288571e6a64ecd696ff1173d047e4d69ebd
[]
no_license
locking3456/Boj_practice
cd856d700b1430ebe37e351469534631b39c970d
6e183134301ad5e3cb581563bdef45e75095fa95
refs/heads/main
2023-06-11T00:19:30.138169
2023-06-05T14:58:28
2023-06-05T14:58:28
348,374,860
0
1
null
2023-03-27T05:31:32
2021-03-16T14:17:51
null
UTF-8
C++
false
false
881
cpp
#include <iostream> #include <string> #include <algorithm> using namespace std; string DeutBo[500000]; string Bodo[500000]; string Answer[500000]; int binarysearch(string* a, string answer, int low, int high) { int mid; if (low > high) return 0; else { mid = (low + high) / 2; if (answer == a[mid]) { return 1; } else if (answer < a[mid]) return binarysearch(a, answer, low, mid - 1); else return binarysearch(a, answer, mid + 1, high); } } int main() { int N, M; int cnt=0; cin >> N >> M; for (int i = 0; i < N; i++) { cin >> DeutBo[i]; } sort(DeutBo, DeutBo+N); for (int i = 0; i < M; i++) { cin >> Bodo[i]; } sort(Bodo, Bodo + M); for (int i = 0; i < M; i++) { if (binarysearch(DeutBo, Bodo[i], 0, M)) { Answer[cnt] = Bodo[i]; cnt++; } } cout << cnt<<'\n'; for (int i = 0; i < cnt; i++) { cout << Answer[i] << '\n'; } }
09a5452c18361318fb1983ca99776124e61140f2
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5708284669460480_0/C++/dongockhanh1997/B-small.cpp
8f687b18cbede5fbd3eaa9831acd7427667ce27e
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
2,543
cpp
#include <bits/stdc++.h> using namespace std; vector<int> getFail(const string &s) { vector<int> f (s.size()); f[0] = -1; for (int i = 1, j = -1; i < (int) s.size(); ++i) { while (j >= 0 && s[i] != s[j + 1]) j = f[j]; if (s[i] == s[j + 1]) ++j; f[i] = j; } return f; } double f[101][101][101]; bool possible[101][101][101]; double runTest() { int k; cin >> k; int l; cin >> l; int s; cin >> s; string keyboard; cin >> keyboard; string target; cin >> target; vector<int> fail = getFail(target); vector<vector<int> > next (fail.size(), vector<int>(26, 0)); for (int match = 0; match < (int) fail.size(); ++match) { for (int c = 0; c < 26; ++c) { int j = match - 1; while (j >= 0 && 'A' + c != target[j + 1]) j = fail[j]; if ('A' + c == target[j + 1]) ++j; next[match][c] = j + 1; } } memset(f, 0, sizeof f); memset(possible, 0, sizeof possible); f[0][0][0] = 1; possible[0][0][0] = true; for (int typed = 0; typed < s; ++typed) { for (int match = 0; match < l; ++match) { for (int cnt = 0; cnt <= typed; ++cnt) if (possible[typed][match][cnt]) { for (char foo : keyboard) { int c = foo - 'A'; if (next[match][c] == l) { f[typed + 1][fail[l - 1] + 1][cnt + 1] += f[typed][match][cnt] / keyboard.size(); possible[typed + 1][fail[l - 1] + 1][cnt + 1] = true; } else { f[typed + 1][next[match][c]][cnt] += f[typed][match][cnt] / keyboard.size(); possible[typed + 1][next[match][c]][cnt] = true; } } } } } double result = 0; int worst = 0; for (int match = 0; match < l; ++match) { for (int cnt = 0; cnt <= s; ++cnt) if (possible[s][match][cnt]) { result += f[s][match][cnt] * cnt; worst = max(worst, cnt); } } return worst - result; } int main() { assert(freopen("B-small-0.in", "r", stdin)); assert(freopen("B-small-0.out", "w", stdout)); ios::sync_with_stdio(false); int numTests; cin >> numTests; cout << fixed << setprecision(12); for (int test = 0; test < numTests; ++test) { cout << "Case #" << test + 1 << ": " << runTest() << '\n'; } return 0; }
7d3f1920b60587cde5ee33e4664de1592cfbdabc
485ff07efdbb3e56b9633e3134b1c81271c2d8a3
/cpp/SampleRdkMarmalade/MarmaladeNewAutoUITexture.cpp
808deaaddeeb180b5ee0ad1d1458e983f77c5c77
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
mcneel/rhino-developer-samples
8f8a332d4d6a9a5fa064be6c1532e665d37c8f13
4fb376adcf94f9d583878d1c1208038f86bde312
refs/heads/7
2023-08-18T22:04:34.036498
2023-06-08T16:28:43
2023-06-08T16:28:43
72,225,588
526
362
NOASSERTION
2023-09-06T20:29:31
2016-10-28T16:52:21
C++
UTF-8
C++
false
false
3,496
cpp
#include "stdafx.h" #include "MarmaladeNewAutoUITexture.h" #include "MarmaladeAutoUITexture.h" #include "MarmaladePlugIn.h" #include "MarmaladeActualShaders.h" // This is similar to CMarmaladeAutoUITexture but it uses content fields to store // the texture's colors. This makes it a bit easier to implement and is the // recommended way to create custom textures. CMarmaladeNewAutoUITextureFactory::CMarmaladeNewAutoUITextureFactory() { } CRhRdkTexture* CMarmaladeNewAutoUITextureFactory::NewTexture(void) const { return new CMarmaladeNewAutoUITexture; } CMarmaladeNewAutoUITexture::CMarmaladeNewAutoUITexture() : m_color1(*this, MARM_TEXTURE_COLOR_1, L"Color1", L"Color1"), m_color2(*this, MARM_TEXTURE_COLOR_2, L"Color2", L"Color2") { m_color1 = CRhRdkColor(255, 140, 0); m_color2 = CRhRdkColor(255, 255, 255); } CMarmaladeNewAutoUITexture::~CMarmaladeNewAutoUITexture() { } UUID CMarmaladeNewAutoUITexture::RenderEngineId(void) const { return CMarmaladePlugIn::ID(); } UUID CMarmaladeNewAutoUITexture::PlugInId(void) const { return CMarmaladePlugIn::ID(); } UUID CMarmaladeNewAutoUITexture::TypeId(void) const { // !!!! DO NOT REUSE THIS UUID !!!! // !!!! DO NOT REUSE THIS UUID !!!! // !!!! DO NOT REUSE THIS UUID !!!! // !!!! DO NOT REUSE THIS UUID !!!! static const UUID uuidTypeId = { 0x5313b92f, 0x9357, 0x443c, { 0x95, 0x5a, 0x43, 0xa1, 0x57, 0xcf, 0xe5, 0x13 } }; // !!!! DO NOT REUSE THIS UUID !!!! // !!!! DO NOT REUSE THIS UUID !!!! // !!!! DO NOT REUSE THIS UUID !!!! // !!!! DO NOT REUSE THIS UUID !!!! return uuidTypeId; } ON_wString CMarmaladeNewAutoUITexture::TypeName(void) const { return L"Marmalade New Automatic UI Texture"; } ON_wString CMarmaladeNewAutoUITexture::TypeDescription(void) const { return L"Marmalade New Automatic UI Texture"; } ON_wString CMarmaladeNewAutoUITexture::InternalName(void) const { return L"MarmaladeNewAutoUITexture"; } void CMarmaladeNewAutoUITexture::AddUISections(IRhRdkExpandableContentUI& ui) { const auto* wsz = L"Marmalade parameters"; AddAutomaticUISection(ui, wsz, wsz); CRhRdkTexture::AddUISections(ui); } unsigned int CMarmaladeNewAutoUITexture::BitFlags(void) const { auto flags = CRhRdkTexture::BitFlags(); // | bfSharedUI; // Shared UI is mandatory now. flags &= ~bfTextureSummary; // No texture summary required. flags |= bfFields; // Use content fields. return flags; } void CMarmaladeNewAutoUITexture::AddAutoParameters(IRhRdkParamBlock& paramBlock, int id) const { // Since we are using fields, we can just get the fields to do the necessary work. Fields().AddValuesToParamBlock(paramBlock, id); } void CMarmaladeNewAutoUITexture::GetAutoParameters(const IRhRdkParamBlock& paramBlock, int id) { // This method is called when something changes in the automatic UI as a result // of the user clicking on a control. Since we are using fields, we can just get // the fields to do the necessary work. Fields().GetValuesFromParamBlock(paramBlock, id); } bool CMarmaladeNewAutoUITexture::IsFactoryProductAcceptableAsChild(const CRhRdkContentFactory& f, const wchar_t* wszChildSlotName) const { if (f.Kind() == Kinds::Texture) return true; // Factory produces textures. return false; // Factory produces something "unpalatable". } IRhRdkTextureEvaluator* CMarmaladeNewAutoUITexture::NewTextureEvaluator(IRhRdkTextureEvaluator::CEvalFlags ef) const { return new CMarmaladeAutoUITexture::Evaluator(ef, m_color1, m_color2, LocalMappingTransform()); }
1fce2ea4206b83c4794dc25e069f63e0574497e3
3ced9eca538ad51595240950899611fd8d038fd0
/src/kernel/memory.cpp
e441c92a92873661ae125d4e2d010243d6329fe8
[]
no_license
m8939605/DSOS
746afaa540d442c4662de9151734b5367e4c36fb
90a72d74d8f43c68ed119c6fc5eda636528338d5
refs/heads/master
2022-12-24T13:47:05.008453
2019-11-02T04:08:48
2019-11-02T04:08:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
222
cpp
#include "common.h" extern "C" unsigned long allocPage(); extern "C" void freePage(unsigned long p); void memcpy(byte *dest, byte *source, dword len) { for (int i=0; i<len; i++) { dest[i] = source[i]; } }
a02fdcad9e4162465d3cfeeb05bd24e7676e9764
5b30dc8638b31b4921ac1611950d48065319ad42
/POJ/POJ2989.cpp
5a9cac29494bbff53ce63a82c17ae78f76911c4e
[ "Apache-2.0" ]
permissive
taisuishen/code
041916ac14973d24f669efd0f6c2606ad9cb554b
b959ffcd9f401fa7c6362d6d7cf745e48acfca89
refs/heads/main
2023-02-02T21:31:27.448785
2020-12-21T16:25:16
2020-12-21T16:25:16
303,955,660
1
0
null
null
null
null
GB18030
C++
false
false
1,662
cpp
#include <cstdio> #include <iostream> #include <algorithm> #include <vector> #include <stack> #include <cstring> #define For(i,j,k) for(int i = j;i <= (int)k;i ++) #define Set(i,j) memset(i, j, sizeof(i)) using namespace std; const int N = 130; int Ans, G[N][N], all[N][N], some[N][N], none[N][N]; void DFS(int n, int an, int sn, int nn){ if(!sn && !nn) Ans++; if(Ans > 1000) return; int key = some[n][1]; For(j,1,sn){ int v = some[n][j], tsn = 0, tnn = 0; // cout<<key<<" "<<v<<endl; if(G[key][v])continue; For(i,1,an) all[n+1][i] = all[n][i]; all[n+1][an+1] = v; For(i,1,sn) if(G[v][some[n][i]]) some[n+1][++tsn] = some[n][i]; For(i,1,nn) if(G[v][none[n][i]]) none[n+1][++tnn] = none[n][i]; DFS(n + 1, an + 1, tsn, tnn); some[n][j] = 0, none[n][++nn] = v; } } int main(){ int n, m; while(scanf("%d%d", &n, &m) == 2){ int x, y; Set(G, 0), Ans = 0; For(i,1,m){ scanf("%d%d", &x, &y); G[x][y] = G[y][x] = 1; } For(i,1,n) some[1][i] = i; DFS(1, 0, n, 0); if(Ans > 1000) puts("Too many maximal sets of friends."); else printf("%d\n", Ans); } return 0; } BronKerbosch(All, Some, None): if Some and None are both empty: report All as a maximal clique //所有点已选完,且没有不能选的点,累加答案 for each vertex v in Some: //枚举Some中的每一个元素 BronKerbosch1(All ? {v}, Some ? N(v), None ? N(v)) //将v加入All,显然只有与v为朋友的人才能作为备选,None中也只有与v为朋友的才会对接下来造成影响 Some := Some - {v} //已经搜过,在Some中删除,加入None None := None ? {v}
69cc368d8744e439d7668436dfab4b1ddc6137df
9b775ad06355064e5eeb01d807b53cd309f2a866
/String/Palindrome/palindrome.cpp
5e3b1113b75b3f441b29d0850c66a1b25bc992a5
[]
no_license
pratikjain04/ACM-ICPC-Algorithms
f29095b70a78e617f2f945ae2af10abc46e99df9
a85c1b4dd4cf0f460844a629013c7f571cc46f99
refs/heads/master
2020-06-12T06:42:49.814246
2019-10-17T19:39:44
2019-10-17T19:39:44
194,222,848
3
2
null
2019-10-17T19:39:45
2019-06-28T06:50:52
C++
UTF-8
C++
false
false
205
cpp
#include <bits/stdc++.h> using namespace std; int isPalindrome(string s) { return reverse(s.begin(), s.end())==s; } int main() { string s; cin>>s; isPalindrome(s); return 0; }
44aa19b2e6bf9534e71e16af3947fb99452d2454
301bdb50009961c35494df9fb43625c262047a17
/src/miner.cpp
02f99400feaac54eed8520f00507e1e292f644dc
[ "MIT" ]
permissive
franklee1/master4
e6a10bcf068259aab70f886cd1dac50261deda73
a82cf06267de12b685390c26075e3debfd937788
refs/heads/master
2021-05-11T13:21:19.785228
2018-01-16T11:57:01
2018-01-16T11:57:01
117,677,623
0
0
null
null
null
null
UTF-8
C++
false
false
21,664
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2014-2017 The master Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "miner.h" #include "amount.h" #include "chain.h" #include "chainparams.h" #include "coins.h" #include "consensus/consensus.h" #include "consensus/merkle.h" #include "consensus/validation.h" #include "hash.h" #include "validation.h" #include "net.h" #include "policy/policy.h" #include "pow.h" #include "primitives/transaction.h" #include "script/standard.h" #include "timedata.h" #include "txmempool.h" #include "util.h" #include "utilmoneystr.h" #include "masternode-payments.h" #include "masternode-sync.h" #include "validationinterface.h" #include <boost/thread.hpp> #include <boost/tuple/tuple.hpp> #include <queue> using namespace std; ////////////////////////////////////////////////////////////////////////////// // // masterMiner // // // Unconfirmed transactions in the memory pool often depend on other // transactions in the memory pool. When we select transactions from the // pool, we select by highest priority or fee rate, so we might consider // transactions that depend on transactions that aren't yet in the block. uint64_t nLastBlockTx = 0; uint64_t nLastBlockSize = 0; class ScoreCompare { public: ScoreCompare() {} bool operator()(const CTxMemPool::txiter a, const CTxMemPool::txiter b) { return CompareTxMemPoolEntryByScore()(*b,*a); // Convert to less than } }; int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev) { int64_t nOldTime = pblock->nTime; int64_t nNewTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime()); if (nOldTime < nNewTime) pblock->nTime = nNewTime; // Updating time can change work required on testnet: if (consensusParams.fPowAllowMinDifficultyBlocks) pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams); return nNewTime - nOldTime; } CBlockTemplate* CreateNewBlock(const CChainParams& chainparams, const CScript& scriptPubKeyIn) { // Create new block std::unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate()); if(!pblocktemplate.get()) return NULL; CBlock *pblock = &pblocktemplate->block; // pointer for convenience // Create coinbase tx CMutableTransaction txNew; txNew.vin.resize(1); txNew.vin[0].prevout.SetNull(); txNew.vout.resize(1); txNew.vout[0].scriptPubKey = scriptPubKeyIn; // Largest block you're willing to create: unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE); // Limit to between 1K and MAX_BLOCK_SIZE-1K for sanity: nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MaxBlockSize(fDIP0001ActiveAtTip)-1000), nBlockMaxSize)); // How much of the block should be dedicated to high-priority transactions, // included regardless of the fees they pay unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE); nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize); // Minimum block size you want to create; block will be filled with free transactions // until there are no more or the block reaches this size: unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE); nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize); // Collect memory pool transactions into the block CTxMemPool::setEntries inBlock; CTxMemPool::setEntries waitSet; // This vector will be sorted into a priority queue: vector<TxCoinAgePriority> vecPriority; TxCoinAgePriorityCompare pricomparer; std::map<CTxMemPool::txiter, double, CTxMemPool::CompareIteratorByHash> waitPriMap; typedef std::map<CTxMemPool::txiter, double, CTxMemPool::CompareIteratorByHash>::iterator waitPriIter; double actualPriority = -1; std::priority_queue<CTxMemPool::txiter, std::vector<CTxMemPool::txiter>, ScoreCompare> clearedTxs; bool fPrintPriority = GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY); uint64_t nBlockSize = 1000; uint64_t nBlockTx = 0; unsigned int nBlockSigOps = 100; int lastFewTxs = 0; CAmount nFees = 0; { LOCK(cs_main); CBlockIndex* pindexPrev = chainActive.Tip(); const int nHeight = pindexPrev->nHeight + 1; pblock->nTime = GetAdjustedTime(); const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast(); // Add our coinbase tx as first transaction pblock->vtx.push_back(txNew); pblocktemplate->vTxFees.push_back(-1); // updated at end pblocktemplate->vTxSigOps.push_back(-1); // updated at end pblock->nVersion = ComputeBlockVersion(pindexPrev, chainparams.GetConsensus()); // -regtest only: allow overriding block.nVersion with // -blockversion=N to test forking scenarios if (chainparams.MineBlocksOnDemand()) pblock->nVersion = GetArg("-blockversion", pblock->nVersion); int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST) ? nMedianTimePast : pblock->GetBlockTime(); { LOCK(mempool.cs); bool fPriorityBlock = nBlockPrioritySize > 0; if (fPriorityBlock) { vecPriority.reserve(mempool.mapTx.size()); for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi) { double dPriority = mi->GetPriority(nHeight); CAmount dummy; mempool.ApplyDeltas(mi->GetTx().GetHash(), dPriority, dummy); vecPriority.push_back(TxCoinAgePriority(dPriority, mi)); } std::make_heap(vecPriority.begin(), vecPriority.end(), pricomparer); } CTxMemPool::indexed_transaction_set::nth_index<3>::type::iterator mi = mempool.mapTx.get<3>().begin(); CTxMemPool::txiter iter; while (mi != mempool.mapTx.get<3>().end() || !clearedTxs.empty()) { bool priorityTx = false; if (fPriorityBlock && !vecPriority.empty()) { // add a tx from priority queue to fill the blockprioritysize priorityTx = true; iter = vecPriority.front().second; actualPriority = vecPriority.front().first; std::pop_heap(vecPriority.begin(), vecPriority.end(), pricomparer); vecPriority.pop_back(); } else if (clearedTxs.empty()) { // add tx with next highest score iter = mempool.mapTx.project<0>(mi); mi++; } else { // try to add a previously postponed child tx iter = clearedTxs.top(); clearedTxs.pop(); } if (inBlock.count(iter)) continue; // could have been added to the priorityBlock const CTransaction& tx = iter->GetTx(); bool fOrphan = false; BOOST_FOREACH(CTxMemPool::txiter parent, mempool.GetMemPoolParents(iter)) { if (!inBlock.count(parent)) { fOrphan = true; break; } } if (fOrphan) { if (priorityTx) waitPriMap.insert(std::make_pair(iter,actualPriority)); else waitSet.insert(iter); continue; } unsigned int nTxSize = iter->GetTxSize(); if (fPriorityBlock && (nBlockSize + nTxSize >= nBlockPrioritySize || !AllowFree(actualPriority))) { fPriorityBlock = false; waitPriMap.clear(); } if (!priorityTx && (iter->GetModifiedFee() < ::minRelayTxFee.GetFee(nTxSize) && nBlockSize >= nBlockMinSize)) { break; } if (nBlockSize + nTxSize >= nBlockMaxSize) { if (nBlockSize > nBlockMaxSize - 100 || lastFewTxs > 50) { break; } // Once we're within 1000 bytes of a full block, only look at 50 more txs // to try to fill the remaining space. if (nBlockSize > nBlockMaxSize - 1000) { lastFewTxs++; } continue; } if (!IsFinalTx(tx, nHeight, nLockTimeCutoff)) continue; unsigned int nTxSigOps = iter->GetSigOpCount(); unsigned int nMaxBlockSigOps = MaxBlockSigOps(fDIP0001ActiveAtTip); if (nBlockSigOps + nTxSigOps >= nMaxBlockSigOps) { if (nBlockSigOps > nMaxBlockSigOps - 2) { break; } continue; } CAmount nTxFees = iter->GetFee(); // Added pblock->vtx.push_back(tx); pblocktemplate->vTxFees.push_back(nTxFees); pblocktemplate->vTxSigOps.push_back(nTxSigOps); nBlockSize += nTxSize; ++nBlockTx; nBlockSigOps += nTxSigOps; nFees += nTxFees; if (fPrintPriority) { double dPriority = iter->GetPriority(nHeight); CAmount dummy; mempool.ApplyDeltas(tx.GetHash(), dPriority, dummy); LogPrintf("priority %.1f fee %s txid %s\n", dPriority , CFeeRate(iter->GetModifiedFee(), nTxSize).ToString(), tx.GetHash().ToString()); } inBlock.insert(iter); // Add transactions that depend on this one to the priority queue BOOST_FOREACH(CTxMemPool::txiter child, mempool.GetMemPoolChildren(iter)) { if (fPriorityBlock) { waitPriIter wpiter = waitPriMap.find(child); if (wpiter != waitPriMap.end()) { vecPriority.push_back(TxCoinAgePriority(wpiter->second,child)); std::push_heap(vecPriority.begin(), vecPriority.end(), pricomparer); waitPriMap.erase(wpiter); } } else { if (waitSet.count(child)) { clearedTxs.push(child); waitSet.erase(child); } } } } } // NOTE: unlike in bitcoin, we need to pass PREVIOUS block height here CAmount blockReward = nFees + GetBlockSubsidy(pindexPrev->nBits, pindexPrev->nHeight, Params().GetConsensus()); // Compute regular coinbase transaction. txNew.vout[0].nValue = blockReward; txNew.vin[0].scriptSig = CScript() << nHeight << OP_0; // Update coinbase transaction with additional info about masternode and governance payments, // get some info back to pass to getblocktemplate FillBlockPayments(txNew, nHeight, blockReward, pblock->txoutMasternode, pblock->voutSuperblock); // LogPrintf("CreateNewBlock -- nBlockHeight %d blockReward %lld txoutMasternode %s txNew %s", // nHeight, blockReward, pblock->txoutMasternode.ToString(), txNew.ToString()); nLastBlockTx = nBlockTx; nLastBlockSize = nBlockSize; LogPrintf("CreateNewBlock(): total size %u txs: %u fees: %ld sigops %d\n", nBlockSize, nBlockTx, nFees, nBlockSigOps); // Update block coinbase pblock->vtx[0] = txNew; pblocktemplate->vTxFees[0] = -nFees; // Fill in header pblock->hashPrevBlock = pindexPrev->GetBlockHash(); UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev); pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus()); pblock->nNonce = 0; pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]); CValidationState state; if (!TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) { throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state))); } } return pblocktemplate.release(); } void IncrementExtraNonce(CBlock* pblock, const CBlockIndex* pindexPrev, unsigned int& nExtraNonce) { // Update nExtraNonce static uint256 hashPrevBlock; if (hashPrevBlock != pblock->hashPrevBlock) { nExtraNonce = 0; hashPrevBlock = pblock->hashPrevBlock; } ++nExtraNonce; unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2 CMutableTransaction txCoinbase(pblock->vtx[0]); txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS; assert(txCoinbase.vin[0].scriptSig.size() <= 100); pblock->vtx[0] = txCoinbase; pblock->hashMerkleRoot = BlockMerkleRoot(*pblock); } ////////////////////////////////////////////////////////////////////////////// // // Internal miner // // ***TODO*** ScanHash is not yet used in master // // ScanHash scans nonces looking for a hash with at least some zero bits. // The nonce is usually preserved between calls, but periodically or if the // nonce is 0xffff0000 or above, the block is rebuilt and nNonce starts over at // zero. // //bool static ScanHash(const CBlockHeader *pblock, uint32_t& nNonce, uint256 *phash) //{ // // Write the first 76 bytes of the block header to a double-SHA256 state. // CHash256 hasher; // CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); // ss << *pblock; // assert(ss.size() == 80); // hasher.Write((unsigned char*)&ss[0], 76); // while (true) { // nNonce++; // // Write the last 4 bytes of the block header (the nonce) to a copy of // // the double-SHA256 state, and compute the result. // CHash256(hasher).Write((unsigned char*)&nNonce, 4).Finalize((unsigned char*)phash); // // Return the nonce if the hash has at least some zero bits, // // caller will check if it has enough to reach the target // if (((uint16_t*)phash)[15] == 0) // return true; // // If nothing found after trying for a while, return -1 // if ((nNonce & 0xfff) == 0) // return false; // } //} static bool ProcessBlockFound(const CBlock* pblock, const CChainParams& chainparams) { LogPrintf("%s\n", pblock->ToString()); LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue)); // Found a solution { LOCK(cs_main); if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash()) return error("ProcessBlockFound -- generated block is stale"); } // Inform about the new block GetMainSignals().BlockFound(pblock->GetHash()); // Process this block the same as if we had received it from another node if (!ProcessNewBlock(chainparams, pblock, true, NULL, NULL)) return error("ProcessBlockFound -- ProcessNewBlock() failed, block not accepted"); return true; } // ***TODO*** that part changed in bitcoin, we are using a mix with old one here for now void static BitcoinMiner(const CChainParams& chainparams, CConnman& connman) { LogPrintf("masterMiner -- started\n"); SetThreadPriority(THREAD_PRIORITY_LOWEST); RenameThread("master-miner"); unsigned int nExtraNonce = 0; boost::shared_ptr<CReserveScript> coinbaseScript; GetMainSignals().ScriptForMining(coinbaseScript); try { // Throw an error if no script was provided. This can happen // due to some internal error but also if the keypool is empty. // In the latter case, already the pointer is NULL. if (!coinbaseScript || coinbaseScript->reserveScript.empty()) throw std::runtime_error("No coinbase script available (mining requires a wallet)"); while (true) { if (chainparams.MiningRequiresPeers()) { // Busy-wait for the network to come online so we don't waste time mining // on an obsolete chain. In regtest mode we expect to fly solo. do { bool fvNodesEmpty = connman.GetNodeCount(CConnman::CONNECTIONS_ALL) == 0; if (!fvNodesEmpty && !IsInitialBlockDownload() && masternodeSync.IsSynced()) break; MilliSleep(1000); } while (true); } // // Create new block // unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); CBlockIndex* pindexPrev = chainActive.Tip(); if(!pindexPrev) break; std::unique_ptr<CBlockTemplate> pblocktemplate(CreateNewBlock(chainparams, coinbaseScript->reserveScript)); if (!pblocktemplate.get()) { LogPrintf("masterMiner -- Keypool ran out, please call keypoolrefill before restarting the mining thread\n"); return; } CBlock *pblock = &pblocktemplate->block; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); LogPrintf("masterMiner -- Running miner with %u transactions in block (%u bytes)\n", pblock->vtx.size(), ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION)); // // Search // int64_t nStart = GetTime(); arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits); while (true) { unsigned int nHashesDone = 0; uint256 hash; while (true) { hash = pblock->GetHash(); if (UintToArith256(hash) <= hashTarget) { // Found a solution SetThreadPriority(THREAD_PRIORITY_NORMAL); LogPrintf("masterMiner:\n proof-of-work found\n hash: %s\n target: %s\n", hash.GetHex(), hashTarget.GetHex()); ProcessBlockFound(pblock, chainparams); SetThreadPriority(THREAD_PRIORITY_LOWEST); coinbaseScript->KeepScript(); // In regression test mode, stop mining after a block is found. This // allows developers to controllably generate a block on demand. if (chainparams.MineBlocksOnDemand()) throw boost::thread_interrupted(); break; } pblock->nNonce += 1; nHashesDone += 1; if ((pblock->nNonce & 0xFF) == 0) break; } // Check for stop or if block needs to be rebuilt boost::this_thread::interruption_point(); // Regtest mode doesn't require peers if (connman.GetNodeCount(CConnman::CONNECTIONS_ALL) == 0 && chainparams.MiningRequiresPeers()) break; if (pblock->nNonce >= 0xffff0000) break; if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60) break; if (pindexPrev != chainActive.Tip()) break; // Update nTime every few seconds if (UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev) < 0) break; // Recreate the block if the clock has run backwards, // so that we can use the correct time. if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks) { // Changing pblock->nTime can change work required on testnet: hashTarget.SetCompact(pblock->nBits); } } } } catch (const boost::thread_interrupted&) { LogPrintf("masterMiner -- terminated\n"); throw; } catch (const std::runtime_error &e) { LogPrintf("masterMiner -- runtime error: %s\n", e.what()); return; } } void GenerateBitcoins(bool fGenerate, int nThreads, const CChainParams& chainparams, CConnman& connman) { static boost::thread_group* minerThreads = NULL; if (nThreads < 0) nThreads = GetNumCores(); if (minerThreads != NULL) { minerThreads->interrupt_all(); delete minerThreads; minerThreads = NULL; } if (nThreads == 0 || !fGenerate) return; minerThreads = new boost::thread_group(); for (int i = 0; i < nThreads; i++) minerThreads->create_thread(boost::bind(&BitcoinMiner, boost::cref(chainparams), boost::ref(connman))); }
7b5e9fd8df42128fa5284b2c4e30183bac8e182f
4f23c24cbf6cdf8ac76d847eeea66b6aea5e9567
/dzz/Dzzxglob.cpp
94dc0bb3eff0d2cc76f6e8a327c457dcc02f5a2b
[]
no_license
MatthewNg3416/Episodus
be2ef0f958274de2fd91e9f6954c9a76c23977aa
fe3ed5a5e92466f98e928c2eafd48faa6eb1b165
refs/heads/master
2021-09-13T07:39:04.985158
2018-04-26T16:23:32
2018-04-26T16:23:32
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
3,143
cpp
/* +-----------------------------------------------------------------+ */ /* ¦ PROGRAMME SECONDAIRE : DGEXGLOB.C ¦ */ /* ¦ ¦ */ /* ¦ Gastroscopie : Classe mère des décodeurs de lésions ¦ */ /* ¦ ¦ */ /* ¦ Début d'écriture : 17 Janvier 1989 (PA) ¦ */ /* ¦ Dernière version : 10 Août 1992 (PA) ¦ */ /* +-----------------------------------------------------------------+ */ #include <owl\olemdifr.h> #include <stdio.h> #include <string.h> #include <cstring.h> #include <stdlib.h> #include <math.h> #include "nssavoir\nssavoir.h" #include "nsbb\nstlibre.h" #include "dzz\dzzglob.h" #include "nautilus\nssuper.h" // // ------------------- decLesion ---------------------------- // decLesion::decLesion(NSContexte* pCtx, int iDecoType) :decodage(pCtx) { iDcType = iDecoType ; bInscrit = false ; } decLesion::decLesion(decodageBase* pBase, int iDecoType) :decodage(pBase) { iDcType = iDecoType ; bInscrit = false ; } void decLesion::initPhrase() { setDcodeur(string("")) ; return ; } void decLesion::debutPhrase() { return ; } void decLesion::finPhrase() { return ; } void decLesion::BioLibLoc(int colonne) { // int refCol = getCol() ; while ((getCol() > colonne) && iBon()) { /* if (*getSt() == "#TLI#") { donnePhrase() ; NSTlibre NSTlibre(pContexte) ; Avance() ; while ((getCol() > refCol) && iBon()) { if (*getSt() == "£??") { bool bOK = NSTlibre.RecupereTexte(pContexte->getPatient()->getNss(), *getCpl(), sDcodeur()) ; Avance() ; if (bOK) metPhrase() ; } else { pContexte->getDico()->donneLibelle(sLangue, getStL(), sDcodeur()) ; Avance() ; *sDcodeur() += "." ; metPhrase() ; } } } else Recupere() ; */ } return ; } // // ------------------- decSousLesion ---------------------------- // decSousLesion::decSousLesion(NSContexte* pCtx, int iDecoType) :decodage(pCtx) { iDcType = iDecoType ; bInscrit = false ; } decSousLesion::decSousLesion(decodageBase* pBase, int iDecoType) :decodage(pBase) { iDcType = iDecoType ; bInscrit = false ; } void decSousLesion::BioLibLoc(int colonne) { int refCol = getCol() ; while ((getCol() > colonne) && iBon()) { if (getSt() == "#TLI#") { donnePhrase() ; // NSTlibre NSTlibre(pContexte) ; Avance() ; while ((getCol() > refCol) && iBon()) { if (getSt() == "£??") { // bool bOK = NSTlibre.RecupereTexte(pContexte->getPatient()->getNss(), *getCpl(), sDcodeur()) ; Avance() ; // if (bOK) metPhrase() ; } else { setDcodeurFromLexique(getStL(), _sLangue) ; Avance() ; addToDcodeur(string(".")) ; metPhrase() ; } } } else Recupere() ; } return ; }
04d10e225ad09f8759cfe805ae6998528fbb67b8
62196b0c2d57a815b796822f226230b826025735
/12/Main.cpp
5b8943b81d16e9fd8b6fe763f5f96a8cac80dd6d
[]
no_license
Amezu/oop-labs-1
b1baf7ec62ff9bf90b550ed0706957291ebfc901
3aa74fb2ebf9e57d83aca8fd19ffb808841d5e17
refs/heads/master
2020-05-05T00:31:30.244266
2019-04-04T21:05:21
2019-04-04T21:05:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,103
cpp
// Nazwa pliku wykonywalnego: Geometria // Uwaga ogolna: // Przeciążenia przewidziane w zadaniu nie są tylko sztuką dla samej sztuki. // Zaproponowane obiekty są np niezbędne w programowaniu grafiki przy użyciu DirectX. // Tutaj przy okazji ilustrują tę ciekawą technikę programistyczną, jaką jest przeciążanie operatorów. // Prosze dopisac kod, dodac nowe pliki, tak aby program wykonywal // sie, a wynik jego dzialania byl taki sam jak podany na końcu tego // pliku. // Prosze napisac klasy CPoint2D i CPoint2DArray, reprezentujace odpowiednio // punkt na plaszczyznie (x,y) oraz tablice punktow, z odpowiednią funkcjonalnością // którą należy wywnioskować z poniższezgo kodu (w niektórych przypadkach znajduje sie // wyjaśniający komentarz) // Pliku Main.cpp, nie wolno modyfikowac. // Ostateczny program powinien byc przyjazny dla programisty (miec // czytelny i dobrze napisany kod). // Makefile dolaczony do rozwiazania powinien tworzyc plik wykonywalny // o nazwie Geometria. Program nalezy kompilowac z flagami -Wall -g. // Makefile powinien zawierac rowniez cel "clean", ktory usuwa pliki // obiektowe i plik wykonywalny. // Przy wykonaniu zadania nie wolno korzystac z internetu, notatek, // ani zadnych innych materialow (w tym wlasnych wczesniej // przygotowanych plikow oprocz makefile) // Kody zrodlowe musza znajdowac sie w katalogu do ktorego nikt oprocz // wlasciciela nie ma praw dostepu. // Rozwiazanie (czyli dodane pliki, makefile i Main.cpp) nalezy wgrac // do UPEL #include <iostream> #include <math.h> #include "Point2D.h" #include "Point2DArray.h" #include <time.h> int main() { srand(time(NULL)); std::cout << "*** POINTS ON THE PLANE ***"<< std::endl; CPoint2D point1(1.2, 0.5), point2(0.8, 0.5), point3; point3 = 0.5 + point1 + point2; point3.Print(); std::cout << "*** ARRAY OF THE POINTS ***"<< std::endl; CPoint2DArray pointV1(5); CPoint2DArray pointV2(5); CPoint2DArray pointV3; // argument: wielkosc wektora CPoint2DArray pointV4(point3,5); // argument: obiekt inicjalizacjalizujacy wszystkie wartosci, wielkosc wektora CPoint2DArray pointV5 = pointV4; pointV4.Print(); pointV4.FillRand(0,100); // Przypisanie wartosci losowych z podanego przedzialu pointV4.Print(); pointV5.Print(); pointV5[1].Print(); pointV1.FillRand(0,10); pointV2.FillRand(11,100); pointV1 = pointV1; pointV1.Print(); pointV2.Print(); pointV3 = pointV2 = pointV1; pointV2.Print(); pointV3.Print(); return 0; } /* Wynik dzialania programu (uwaga, w drugiej czesci zadania sa liczby losowe): *** POINTS ON THE PLANE *** Point:: (2.5,1) *** ARRAY OF THE POINTS *** Point array:: (2.5,1), (2.5,1), (2.5,1), (2.5,1), (2.5,1) Point array:: (40,19), (97,78), (14,94), (22,5), (7,53) Point array:: (2.5,1), (2.5,1), (2.5,1), (2.5,1), (2.5,1) Point:: (2.5,1) Point array:: (7,1), (0,1), (2,7), (0,4), (2,1) Point array:: (61,53), (79,22), (87,35), (84,12), (60,65) Point array:: (7,1), (0,1), (2,7), (0,4), (2,1) Point array:: (7,1), (0,1), (2,7), (0,4), (2,1) */
826e853266dda79f81e8d713aa895f53ad325a2e
249630ace4f18594e43ac8179db3b8d30021370a
/aws-cpp-sdk-redshift/include/aws/redshift/model/DescribeHsmConfigurationsRequest.h
d6547b5b2344094b74063925e0bbb950875ca6a3
[ "JSON", "MIT", "Apache-2.0" ]
permissive
FlyingSquid/aws-sdk-cpp
5e5f2040867b1e1998fa8b06b837b3b19f550469
3fe46f05d1c58fc946045d3b860a79c88d76ceb1
refs/heads/master
2021-01-10T17:19:36.927018
2016-02-27T01:30:38
2016-02-27T01:30:38
52,852,300
0
0
null
null
null
null
UTF-8
C++
false
false
20,648
h
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/redshift/Redshift_EXPORTS.h> #include <aws/redshift/RedshiftRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSVector.h> namespace Aws { namespace Redshift { namespace Model { /** * <p></p> */ class AWS_REDSHIFT_API DescribeHsmConfigurationsRequest : public RedshiftRequest { public: DescribeHsmConfigurationsRequest(); Aws::String SerializePayload() const override; /** * <p>The identifier of a specific Amazon Redshift HSM configuration to be * described. If no identifier is specified, information is returned for all HSM * configurations owned by your AWS customer account.</p> */ inline const Aws::String& GetHsmConfigurationIdentifier() const{ return m_hsmConfigurationIdentifier; } /** * <p>The identifier of a specific Amazon Redshift HSM configuration to be * described. If no identifier is specified, information is returned for all HSM * configurations owned by your AWS customer account.</p> */ inline void SetHsmConfigurationIdentifier(const Aws::String& value) { m_hsmConfigurationIdentifierHasBeenSet = true; m_hsmConfigurationIdentifier = value; } /** * <p>The identifier of a specific Amazon Redshift HSM configuration to be * described. If no identifier is specified, information is returned for all HSM * configurations owned by your AWS customer account.</p> */ inline void SetHsmConfigurationIdentifier(Aws::String&& value) { m_hsmConfigurationIdentifierHasBeenSet = true; m_hsmConfigurationIdentifier = value; } /** * <p>The identifier of a specific Amazon Redshift HSM configuration to be * described. If no identifier is specified, information is returned for all HSM * configurations owned by your AWS customer account.</p> */ inline void SetHsmConfigurationIdentifier(const char* value) { m_hsmConfigurationIdentifierHasBeenSet = true; m_hsmConfigurationIdentifier.assign(value); } /** * <p>The identifier of a specific Amazon Redshift HSM configuration to be * described. If no identifier is specified, information is returned for all HSM * configurations owned by your AWS customer account.</p> */ inline DescribeHsmConfigurationsRequest& WithHsmConfigurationIdentifier(const Aws::String& value) { SetHsmConfigurationIdentifier(value); return *this;} /** * <p>The identifier of a specific Amazon Redshift HSM configuration to be * described. If no identifier is specified, information is returned for all HSM * configurations owned by your AWS customer account.</p> */ inline DescribeHsmConfigurationsRequest& WithHsmConfigurationIdentifier(Aws::String&& value) { SetHsmConfigurationIdentifier(value); return *this;} /** * <p>The identifier of a specific Amazon Redshift HSM configuration to be * described. If no identifier is specified, information is returned for all HSM * configurations owned by your AWS customer account.</p> */ inline DescribeHsmConfigurationsRequest& WithHsmConfigurationIdentifier(const char* value) { SetHsmConfigurationIdentifier(value); return *this;} /** * <p> The maximum number of response records to return in each call. If the number * of remaining response records exceeds the specified <code>MaxRecords</code> * value, a value is returned in a <code>marker</code> field of the response. You * can retrieve the next set of records by retrying the command with the returned * marker value. </p> <p>Default: <code>100</code></p> <p>Constraints: minimum 20, * maximum 100.</p> */ inline long GetMaxRecords() const{ return m_maxRecords; } /** * <p> The maximum number of response records to return in each call. If the number * of remaining response records exceeds the specified <code>MaxRecords</code> * value, a value is returned in a <code>marker</code> field of the response. You * can retrieve the next set of records by retrying the command with the returned * marker value. </p> <p>Default: <code>100</code></p> <p>Constraints: minimum 20, * maximum 100.</p> */ inline void SetMaxRecords(long value) { m_maxRecordsHasBeenSet = true; m_maxRecords = value; } /** * <p> The maximum number of response records to return in each call. If the number * of remaining response records exceeds the specified <code>MaxRecords</code> * value, a value is returned in a <code>marker</code> field of the response. You * can retrieve the next set of records by retrying the command with the returned * marker value. </p> <p>Default: <code>100</code></p> <p>Constraints: minimum 20, * maximum 100.</p> */ inline DescribeHsmConfigurationsRequest& WithMaxRecords(long value) { SetMaxRecords(value); return *this;} /** * <p> An optional parameter that specifies the starting point to return a set of * response records. When the results of a <a>DescribeHsmConfigurations</a> request * exceed the value specified in <code>MaxRecords</code>, AWS returns a value in * the <code>Marker</code> field of the response. You can retrieve the next set of * response records by providing the returned marker value in the * <code>Marker</code> parameter and retrying the request. </p> */ inline const Aws::String& GetMarker() const{ return m_marker; } /** * <p> An optional parameter that specifies the starting point to return a set of * response records. When the results of a <a>DescribeHsmConfigurations</a> request * exceed the value specified in <code>MaxRecords</code>, AWS returns a value in * the <code>Marker</code> field of the response. You can retrieve the next set of * response records by providing the returned marker value in the * <code>Marker</code> parameter and retrying the request. </p> */ inline void SetMarker(const Aws::String& value) { m_markerHasBeenSet = true; m_marker = value; } /** * <p> An optional parameter that specifies the starting point to return a set of * response records. When the results of a <a>DescribeHsmConfigurations</a> request * exceed the value specified in <code>MaxRecords</code>, AWS returns a value in * the <code>Marker</code> field of the response. You can retrieve the next set of * response records by providing the returned marker value in the * <code>Marker</code> parameter and retrying the request. </p> */ inline void SetMarker(Aws::String&& value) { m_markerHasBeenSet = true; m_marker = value; } /** * <p> An optional parameter that specifies the starting point to return a set of * response records. When the results of a <a>DescribeHsmConfigurations</a> request * exceed the value specified in <code>MaxRecords</code>, AWS returns a value in * the <code>Marker</code> field of the response. You can retrieve the next set of * response records by providing the returned marker value in the * <code>Marker</code> parameter and retrying the request. </p> */ inline void SetMarker(const char* value) { m_markerHasBeenSet = true; m_marker.assign(value); } /** * <p> An optional parameter that specifies the starting point to return a set of * response records. When the results of a <a>DescribeHsmConfigurations</a> request * exceed the value specified in <code>MaxRecords</code>, AWS returns a value in * the <code>Marker</code> field of the response. You can retrieve the next set of * response records by providing the returned marker value in the * <code>Marker</code> parameter and retrying the request. </p> */ inline DescribeHsmConfigurationsRequest& WithMarker(const Aws::String& value) { SetMarker(value); return *this;} /** * <p> An optional parameter that specifies the starting point to return a set of * response records. When the results of a <a>DescribeHsmConfigurations</a> request * exceed the value specified in <code>MaxRecords</code>, AWS returns a value in * the <code>Marker</code> field of the response. You can retrieve the next set of * response records by providing the returned marker value in the * <code>Marker</code> parameter and retrying the request. </p> */ inline DescribeHsmConfigurationsRequest& WithMarker(Aws::String&& value) { SetMarker(value); return *this;} /** * <p> An optional parameter that specifies the starting point to return a set of * response records. When the results of a <a>DescribeHsmConfigurations</a> request * exceed the value specified in <code>MaxRecords</code>, AWS returns a value in * the <code>Marker</code> field of the response. You can retrieve the next set of * response records by providing the returned marker value in the * <code>Marker</code> parameter and retrying the request. </p> */ inline DescribeHsmConfigurationsRequest& WithMarker(const char* value) { SetMarker(value); return *this;} /** * <p>A tag key or keys for which you want to return all matching HSM * configurations that are associated with the specified key or keys. For example, * suppose that you have HSM configurations that are tagged with keys called * <code>owner</code> and <code>environment</code>. If you specify both of these * tag keys in the request, Amazon Redshift returns a response with the HSM * configurations that have either or both of these tag keys associated with * them.</p> */ inline const Aws::Vector<Aws::String>& GetTagKeys() const{ return m_tagKeys; } /** * <p>A tag key or keys for which you want to return all matching HSM * configurations that are associated with the specified key or keys. For example, * suppose that you have HSM configurations that are tagged with keys called * <code>owner</code> and <code>environment</code>. If you specify both of these * tag keys in the request, Amazon Redshift returns a response with the HSM * configurations that have either or both of these tag keys associated with * them.</p> */ inline void SetTagKeys(const Aws::Vector<Aws::String>& value) { m_tagKeysHasBeenSet = true; m_tagKeys = value; } /** * <p>A tag key or keys for which you want to return all matching HSM * configurations that are associated with the specified key or keys. For example, * suppose that you have HSM configurations that are tagged with keys called * <code>owner</code> and <code>environment</code>. If you specify both of these * tag keys in the request, Amazon Redshift returns a response with the HSM * configurations that have either or both of these tag keys associated with * them.</p> */ inline void SetTagKeys(Aws::Vector<Aws::String>&& value) { m_tagKeysHasBeenSet = true; m_tagKeys = value; } /** * <p>A tag key or keys for which you want to return all matching HSM * configurations that are associated with the specified key or keys. For example, * suppose that you have HSM configurations that are tagged with keys called * <code>owner</code> and <code>environment</code>. If you specify both of these * tag keys in the request, Amazon Redshift returns a response with the HSM * configurations that have either or both of these tag keys associated with * them.</p> */ inline DescribeHsmConfigurationsRequest& WithTagKeys(const Aws::Vector<Aws::String>& value) { SetTagKeys(value); return *this;} /** * <p>A tag key or keys for which you want to return all matching HSM * configurations that are associated with the specified key or keys. For example, * suppose that you have HSM configurations that are tagged with keys called * <code>owner</code> and <code>environment</code>. If you specify both of these * tag keys in the request, Amazon Redshift returns a response with the HSM * configurations that have either or both of these tag keys associated with * them.</p> */ inline DescribeHsmConfigurationsRequest& WithTagKeys(Aws::Vector<Aws::String>&& value) { SetTagKeys(value); return *this;} /** * <p>A tag key or keys for which you want to return all matching HSM * configurations that are associated with the specified key or keys. For example, * suppose that you have HSM configurations that are tagged with keys called * <code>owner</code> and <code>environment</code>. If you specify both of these * tag keys in the request, Amazon Redshift returns a response with the HSM * configurations that have either or both of these tag keys associated with * them.</p> */ inline DescribeHsmConfigurationsRequest& AddTagKeys(const Aws::String& value) { m_tagKeysHasBeenSet = true; m_tagKeys.push_back(value); return *this; } /** * <p>A tag key or keys for which you want to return all matching HSM * configurations that are associated with the specified key or keys. For example, * suppose that you have HSM configurations that are tagged with keys called * <code>owner</code> and <code>environment</code>. If you specify both of these * tag keys in the request, Amazon Redshift returns a response with the HSM * configurations that have either or both of these tag keys associated with * them.</p> */ inline DescribeHsmConfigurationsRequest& AddTagKeys(Aws::String&& value) { m_tagKeysHasBeenSet = true; m_tagKeys.push_back(value); return *this; } /** * <p>A tag key or keys for which you want to return all matching HSM * configurations that are associated with the specified key or keys. For example, * suppose that you have HSM configurations that are tagged with keys called * <code>owner</code> and <code>environment</code>. If you specify both of these * tag keys in the request, Amazon Redshift returns a response with the HSM * configurations that have either or both of these tag keys associated with * them.</p> */ inline DescribeHsmConfigurationsRequest& AddTagKeys(const char* value) { m_tagKeysHasBeenSet = true; m_tagKeys.push_back(value); return *this; } /** * <p>A tag value or values for which you want to return all matching HSM * configurations that are associated with the specified tag value or values. For * example, suppose that you have HSM configurations that are tagged with values * called <code>admin</code> and <code>test</code>. If you specify both of these * tag values in the request, Amazon Redshift returns a response with the HSM * configurations that have either or both of these tag values associated with * them.</p> */ inline const Aws::Vector<Aws::String>& GetTagValues() const{ return m_tagValues; } /** * <p>A tag value or values for which you want to return all matching HSM * configurations that are associated with the specified tag value or values. For * example, suppose that you have HSM configurations that are tagged with values * called <code>admin</code> and <code>test</code>. If you specify both of these * tag values in the request, Amazon Redshift returns a response with the HSM * configurations that have either or both of these tag values associated with * them.</p> */ inline void SetTagValues(const Aws::Vector<Aws::String>& value) { m_tagValuesHasBeenSet = true; m_tagValues = value; } /** * <p>A tag value or values for which you want to return all matching HSM * configurations that are associated with the specified tag value or values. For * example, suppose that you have HSM configurations that are tagged with values * called <code>admin</code> and <code>test</code>. If you specify both of these * tag values in the request, Amazon Redshift returns a response with the HSM * configurations that have either or both of these tag values associated with * them.</p> */ inline void SetTagValues(Aws::Vector<Aws::String>&& value) { m_tagValuesHasBeenSet = true; m_tagValues = value; } /** * <p>A tag value or values for which you want to return all matching HSM * configurations that are associated with the specified tag value or values. For * example, suppose that you have HSM configurations that are tagged with values * called <code>admin</code> and <code>test</code>. If you specify both of these * tag values in the request, Amazon Redshift returns a response with the HSM * configurations that have either or both of these tag values associated with * them.</p> */ inline DescribeHsmConfigurationsRequest& WithTagValues(const Aws::Vector<Aws::String>& value) { SetTagValues(value); return *this;} /** * <p>A tag value or values for which you want to return all matching HSM * configurations that are associated with the specified tag value or values. For * example, suppose that you have HSM configurations that are tagged with values * called <code>admin</code> and <code>test</code>. If you specify both of these * tag values in the request, Amazon Redshift returns a response with the HSM * configurations that have either or both of these tag values associated with * them.</p> */ inline DescribeHsmConfigurationsRequest& WithTagValues(Aws::Vector<Aws::String>&& value) { SetTagValues(value); return *this;} /** * <p>A tag value or values for which you want to return all matching HSM * configurations that are associated with the specified tag value or values. For * example, suppose that you have HSM configurations that are tagged with values * called <code>admin</code> and <code>test</code>. If you specify both of these * tag values in the request, Amazon Redshift returns a response with the HSM * configurations that have either or both of these tag values associated with * them.</p> */ inline DescribeHsmConfigurationsRequest& AddTagValues(const Aws::String& value) { m_tagValuesHasBeenSet = true; m_tagValues.push_back(value); return *this; } /** * <p>A tag value or values for which you want to return all matching HSM * configurations that are associated with the specified tag value or values. For * example, suppose that you have HSM configurations that are tagged with values * called <code>admin</code> and <code>test</code>. If you specify both of these * tag values in the request, Amazon Redshift returns a response with the HSM * configurations that have either or both of these tag values associated with * them.</p> */ inline DescribeHsmConfigurationsRequest& AddTagValues(Aws::String&& value) { m_tagValuesHasBeenSet = true; m_tagValues.push_back(value); return *this; } /** * <p>A tag value or values for which you want to return all matching HSM * configurations that are associated with the specified tag value or values. For * example, suppose that you have HSM configurations that are tagged with values * called <code>admin</code> and <code>test</code>. If you specify both of these * tag values in the request, Amazon Redshift returns a response with the HSM * configurations that have either or both of these tag values associated with * them.</p> */ inline DescribeHsmConfigurationsRequest& AddTagValues(const char* value) { m_tagValuesHasBeenSet = true; m_tagValues.push_back(value); return *this; } private: Aws::String m_hsmConfigurationIdentifier; bool m_hsmConfigurationIdentifierHasBeenSet; long m_maxRecords; bool m_maxRecordsHasBeenSet; Aws::String m_marker; bool m_markerHasBeenSet; Aws::Vector<Aws::String> m_tagKeys; bool m_tagKeysHasBeenSet; Aws::Vector<Aws::String> m_tagValues; bool m_tagValuesHasBeenSet; }; } // namespace Model } // namespace Redshift } // namespace Aws
a1d37d35a5d55442952051d4b115c3d0318b3997
3568c5dc63425b843582eb0e4460857712fb5ac1
/util.h
b5b8730dfccf06051a3b217831ce973ff32b1495
[]
no_license
Backtrackhhh/matrix-calculator
6d40a6119e6fab7219357d06e66ce139a3f2a8a4
006a0af22a74127c2b999e17af45bcddf969e876
refs/heads/master
2020-06-02T04:00:59.145646
2019-06-09T16:19:34
2019-06-09T16:19:34
191,028,482
0
0
null
null
null
null
UTF-8
C++
false
false
993
h
// // Created by Tristan on 2019/6/7. // #ifndef OOP_LAB4_UTIL_H #define OOP_LAB4_UTIL_H #include <stdio.h> #include <fstream> #include <iostream> #include "matrix.h" #include <map> #include <stack> using namespace std; //void openFile(){ // ifstream in("expression.in"); // char str[20]; // if (in.fail()){ // cout<<"error"<<endl; // } // else{ // in>>str; // cout<<str<<endl; // } //} vector<matrix> handleExpression(string filename, map<string, matrix> &map) ; void SplitString(const string& s, vector<string>& v, const string& c); void readMatrix(string filename,map<string,matrix>& MAP); void writeResults(vector<matrix> in); string matrixToString(matrix tmp); vector<bignum> transToBignum(vector<string> tmp); int priority(char c); stack<string> transToPostfix(string expression, map <string, matrix> map); matrix computeResult(stack<string> in,map<string,matrix> MAP); #endif //OOP_LAB4_UTIL_H
6bd28df5675e092a01286f2ed363fd7d05663e03
251cbafe74684a091486ac87715b5c09c3548476
/cj2016/1C-B/Slides.cpp
bce04708d5d47c01a895a953473bec4738e1af24
[]
no_license
gsz/codejam
1ad214eea0e1911405d1fff48c9d59e8e3a97b78
be7174552c97209458e202f0f026742ff65ba959
refs/heads/master
2020-06-03T17:05:30.838128
2020-04-11T11:56:53
2020-04-11T12:17:44
13,606,256
0
0
null
null
null
null
UTF-8
C++
false
false
1,513
cpp
#include <cassert> #include <limits> #include <memory> #include <ios> #include <iomanip> #include <iostream> #include <sstream> #include <algorithm> #include <queue> #include <stack> #include <unordered_map> #include <unordered_set> #include <vector> using namespace std; typedef int i32; typedef unsigned int u32; typedef long long int i64; typedef unsigned long long int u64; typedef vector<vector<bool>> Graph; Graph read_solve_case() { u64 B, M; cin >> B >> M; if (M > 1ull << (B-2)) { return Graph(); } Graph G; for (u64 i = 0; i < B; ++i) { G.emplace_back(B, false); } for (u64 i = 1; i < B-1; ++i) { for (u64 j = i+1; j < B; ++j) { G[i][j] = true; } } if (M == 1ull << (B-2)) { for (u64 i = 1; i < B; ++i) { G[0][i] = true; } return G; } for (u64 i = 0; i < B-2; ++i) { G[0][B-2-i] = (M >> i) & 1; } return G; } int main(int argc, char *argv[]) { ios_base::sync_with_stdio(false); int T; cin >> T; for (int ci = 1; ci <= T; ++ci) { Graph G = read_solve_case(); cout << "Case #" << ci << ": "; if (G.size() == 0) { cout << "IMPOSSIBLE" << endl; } else { cout << "POSSIBLE" << endl; for (size_t i = 0; i < G.size(); ++i) { for (size_t j = 0; j < G[i].size(); ++j) { cout << (int)G[i][j]; } cout << endl; } } } return 0; }
ee6d9e7a2400d807bfcfe9177c8c3098b916b351
b67c6e15a5f08b5a10d009e3e2cc9232aac7c7c9
/VulkanRenderBackend/private/include/RenderBackendSettings.h
41e73010d4305867323a473ccf7ce3ed2d744a2d
[ "MIT" ]
permissive
A-RAVEN/Crimson
06a9a9204738a1abd635503a755370384b0911f1
1e7f43ee751b50bc271067822a95e16ccb1f6ee3
refs/heads/master
2023-08-06T13:08:27.483713
2023-08-06T09:19:55
2023-08-06T09:19:55
229,404,396
3
0
null
null
null
null
UTF-8
C++
false
false
1,485
h
#pragma once #include "VulkanIncludes.h" #include <cstdint> namespace graphics_backend { constexpr uint32_t FRAMEBOUND_RESOURCE_POOL_SWAP_COUNT_PER_CONTEXT = 3; constexpr uint32_t SWAPCHAIN_BUFFER_COUNT = 3; using FrameType = uint64_t; constexpr FrameType INVALID_FRAMEID = std::numeric_limits<FrameType>::max(); static std::vector<const char*> GetInstanceExtensionNames() { return std::vector<const char*>{ VK_EXT_DEBUG_UTILS_EXTENSION_NAME, VK_KHR_SURFACE_EXTENSION_NAME, #if defined( VK_USE_PLATFORM_ANDROID_KHR ) VK_KHR_ANDROID_SURFACE_EXTENSION_NAME, #elif defined( VK_USE_PLATFORM_IOS_MVK ) VK_MVK_IOS_SURFACE_EXTENSION_NAME, #elif defined( VK_USE_PLATFORM_MACOS_MVK ) VK_MVK_MACOS_SURFACE_EXTENSION_NAME, #elif defined( VK_USE_PLATFORM_MIR_KHR ) VK_KHR_MIR_SURFACE_EXTENSION_NAME, #elif defined( VK_USE_PLATFORM_VI_NN ) VK_NN_VI_SURFACE_EXTENSION_NAME, #elif defined( VK_USE_PLATFORM_WAYLAND_KHR ) VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, #elif defined( VK_USE_PLATFORM_WIN32_KHR ) VK_KHR_WIN32_SURFACE_EXTENSION_NAME, #elif defined( VK_USE_PLATFORM_XCB_KHR ) VK_KHR_XCB_SURFACE_EXTENSION_NAME, #elif defined( VK_USE_PLATFORM_XLIB_KHR ) VK_KHR_XLIB_SURFACE_EXTENSION_NAME, #elif defined( VK_USE_PLATFORM_XLIB_XRANDR_EXT ) VK_EXT_ACQUIRE_XLIB_DISPLAY_EXTENSION_NAME, #endif }; } static std::vector<const char*> GetDeviceExtensionNames() { return std::vector<const char*>{ VK_KHR_SWAPCHAIN_EXTENSION_NAME, }; } }
b197016aa273c9b073b2f58a2725f3fefd8e773d
6a50586d4e73dd3382811a8725b820297e56617e
/likelihood.cxx
55fa9c72f3e2ea035e4fab6f46a66758f0641675
[]
no_license
xligit/atmFitTools
bbd50832db35f1d06f920e36e54e2fcd192b79c4
74c208e9183503b4a17fb1eb8a331e7264e9ff1c
refs/heads/master
2021-01-17T23:04:18.967811
2016-05-23T05:20:11
2016-05-23T05:20:11
55,114,065
0
0
null
2016-03-31T02:35:09
2016-03-31T02:35:09
null
UTF-8
C++
false
false
8,415
cxx
#include "TMath.h" #include "TH1D.h" #include "TGraph.h" #include <iostream> #include <math.h> using namespace std; ////////////////////////////////////////////////////////// //Scaled Poisson function since it's not in ROOT double PoissonS(double nobs, double mean, double scale){ return TMath::Poisson(nobs/scale,mean); } /////////////////////////////////////////////////// //plot scaled Poisson TGraph* plotPossonS(double mean, double scale, int npts=50){ double X[npts]; double Y[npts]; double rangemin = 0; double rangemax = 20; double dx = 20/(double)npts; double x = 0.; for (int ipt=0;ipt<npts;ipt++){ X[ipt] = x; Y[ipt] = PoissonS(x,mean,scale); x+=dx; } TGraph* g = new TGraph(npts,X,Y); g->Draw("a*"); return g; } ///////////////////////////////////////////////////////////// //Log Likelihood evaluation functions ///////////////////////////////////////// //likelihood from tn186 double evalLnL(double ndata, double nmc, double norm = 1.){ if (nmc==0) return 0.; if (ndata==0) return nmc*norm; double Nmc = nmc*norm; double ngLnL = (Nmc-ndata) + ndata*TMath::Log(ndata/Nmc); return ngLnL; } ///////////////////////////////////////// //likelihood from tn186 double evalLnLMean(double ndata, double nmc, double mcerr, double norm = 1.){ if (nmc==0) return 0.; if (ndata==0) return nmc*norm; double Nmc = nmc*norm; double ss = (mcerr*mcerr/nmc); ss = 1.; double mean = ((ndata*ss) + (nmc/norm))/((1./norm)+ss); double diff = ((1./norm)*ndata) - nmc; cout<<"mean: "<<mean<<endl; cout<<"ss: "<<ss<<endl; double ngLnL = (mean-ndata) + ndata*TMath::Log(ndata/mean); // double ngLnL = (diff*diff)/mean; return ngLnL; } ////////////////////////////////////////////////////////// //Use full approximation for comparing to numeric method double evalLnLRamanujan(double ndata, double nmc, double norm=1.){ nmc*=norm; if (nmc==0) return 0.; if (ndata==0) return nmc*norm; double Nmc = nmc*norm; double lnL = (Nmc-ndata) + ndata*TMath::Log(ndata/Nmc) + (0.166666)*TMath::Log(ndata*(1+ ((4*ndata)*(1+(2*ndata))))) + (0.5)*TMath::Log(TMath::Pi()); return lnL; } ////////////////////////////////////////////////////////////////////// //full numeric calculation double evalLnLNumeric(double ndata, double mcmean, double mcsig, double norm=1., int ntotpts = 100){ // mcmean*=norm; // mcsig*=norm; if (mcsig==0) return 0.; if (mcmean<0) return 0.; double I = 0.; double rangemin = fmax((mcmean - (4.*mcsig)),0)*norm; double rangemax = (mcmean + (4.*mcsig))*norm; double dx = (rangemax-rangemin)/(double)ntotpts; double x = rangemin; for (int ipt = 0;ipt<ntotpts;ipt++){ double value = TMath::Poisson(ndata,x)*TMath::Gaus(x,mcmean*norm,mcsig*norm,kTRUE); I+=(value*dx); x+=dx; } return -1*2*TMath::Log(I); } ///////////////////////////////////////////////////////////////////////// // double evalLnLScaled(double ndata, double mcmean, double mcsig,double norm=1.,double ascale=1.){ if (mcmean==0) return 0.; // double scale = mcmean/(mcsig*mcsig); double scale = (mcsig); double ngLnL = evalLnL(ndata,mcmean,norm); // cout<<"scale: "<<scale<<endl; // ngLnL+= +0.5*TMath::Log(scale)*norm*ascale; ngLnL+= 0.5*TMath::Log(scale)*norm*ascale; return ngLnL; } ///////////////////////////////////////////////////////////////////////// //Assume Gaussian errors //double evalLnLGauss(double ndata, double mcmean, double mcsig, int ntotpts = 100){ // return (ndata-mcmean)*(ndata-mcmean)/(2.*mcsig*mcsig); //} ///////////////////////////////////////////////////////////////////////// //Assume scaled Gaussian errors, and mcmean has been normalized double evalLnLMyChi2(double ndata, double mcmean, double mcsig, double norm=1.){ double ss = mcsig; // double deltasq = ( (ndata/(norm*norm)) + (mcsig*mcsig) ); // double deltasq = ( ((ss*ndata) + (mcmean/norm))/(ss + (1./norm)) ); double deltasq = (1./(norm*ss))*(mcmean*ss + ndata); // double diff = (ndata/norm) - deltasq; double diff =(ndata/norm) - mcmean; // deltasq = mcsig*mcsig; cout<<"diff: "<<diff<<endl; cout<<"ss "<<ss<<endl; cout<<"deltasq: "<<deltasq<<endl; // cout<<"log: "<<TMath::Log(deltasq); // return -2*TMath::Log(TMath::Gaus(diff,0.,TMath::Sqrt(deltasq),kTRUE)); // return (diff*diff)/(2*(deltasq)); return (diff*diff)/(2.*deltasq); } //////////////////////////////////////////////////////////////////////////// double evalLnLDiff(double ndata, double mcmean, double mcsig, double norm){ double diff = TMath::Abs(ndata-(mcmean*norm)); return diff; } ///////////////////////////////////////////////////////////////////////// //Assume scaled Gaussian errors, and mcmean has been normalized double evalLnLMyChi2NoWeight(double ndata, double mcmean, double mcsig, double norm){ double diff = ndata - (norm*mcmean); double deltasq = ( ndata + (norm*mcmean) ); // deltasq = mcsig*mcsig; cout<<"diff: "<<diff<<endl; cout<<"deltasq: "<<deltasq<<endl; cout<<"log: "<<TMath::Log(deltasq); return -2*TMath::Log(TMath::Gaus(diff,0.,TMath::Sqrt(deltasq),kTRUE)); // return (diff*diff)/(deltasq) + 2.*TMath::Log(deltasq); } ///////////////////////////////////////////////////////////////////////// //Assume scaled Gaussian errors, and mcmean has been normalized double evalLnLChi2N(double ndata, double mcmean, double mcsig, double norm){ double diff = ndata - (mcmean*norm); double deltasq = ( ndata ); // deltasq = mcsig*mcsig; cout<<"diff: "<<diff<<endl; cout<<"deltasq: "<<deltasq<<endl; cout<<"log: "<<TMath::Log(deltasq); return -2*TMath::Log(TMath::Gaus(diff,0.,TMath::Sqrt(deltasq),kTRUE)); // return (diff*diff)/(deltasq) + 2.*TMath::Log(deltasq); } ///////////////////////////////////////////////////////////////////////// //Assume scaled Gaussian errors double evalLnLChi2Numeric(double ndata, double mcmean, double mcsig,double norm, int npts = 100){ double diff = ndata - (norm*mcmean); double deltasq = ( (ndata) + (norm*norm*mcsig*mcsig) ); double sigmasq = ndata; double rangemin = fmax(0, mcmean - (5*mcsig))*norm; double rangemax = (mcmean + (5*mcsig))*norm; double dx = (rangemax-rangemin)/(double)npts; double I = 0.; double x = rangemin; for (int i=0;i<npts;i++){ double value = TMath::Gaus((x-ndata),0.,deltasq,kTRUE)*TMath::Gaus((x-mcmean),norm*mcmean,mcsig*norm,kTRUE); I+=(dx*value); x+=dx; } return -2*TMath::Log(I); } void plotLnL(int itype, double nmc = 16, double mcsig = 4., double norm=1, int npts=100){ double rangemin = 2; double rangemax = 40; double dx = (rangemax-rangemin)/(double)npts; double xx = rangemin; static TH1D* hreal = new TH1D("hreal","hreal",npts,rangemin,rangemax); double lnL=0.; for (int i=0;i<=npts;i++){ if (itype==0) lnL=evalLnLRamanujan(xx,nmc,norm); //< tn186 if (itype==1) lnL=evalLnLNumeric(xx,nmc,mcsig,norm); //< my numerical method if (itype==2) lnL=evalLnLMyChi2(xx,nmc,mcsig,norm); //< chi-2 style errors if (itype==3) lnL=evalLnLChi2N(xx,nmc,mcsig,norm); //< standard chi2 if (itype==4) lnL=evalLnLChi2Numeric(xx,nmc,mcsig,norm); hreal->SetBinContent(i,lnL); xx+=dx; } hreal->SetLineColor(kBlue); hreal->Draw(); return; } void plotL2(double nmc = 4, double errfrac = 0.1, int npts=100){ double rangemin = 0; double rangemax = 20; static TH1D* hreal = new TH1D("hreal","hreal",npts,rangemin,rangemax); static TH1D* happrox = new TH1D("happrox","happrox",npts,rangemin,rangemax); for (int i=0;i<=npts;i++){ hreal->SetBinContent(i,evalLnLNumeric(hreal->GetBinCenter(i),nmc,errfrac)); happrox->SetBinContent(i,evalLnLRamanujan(happrox->GetBinCenter(i),nmc)); } hreal->SetLineColor(kBlue); hreal->Draw(); happrox->Draw("same"); return; } void plotL(double ndata = 4, double nmc = 4, int npts=100){ double rangemin = 0.01; double rangemax = 0.8; static TH1D* hreal = new TH1D("hreal","hreal",npts,rangemin,rangemax); static TH1D* happrox = new TH1D("happrox","happrox",npts,rangemin,rangemax); for (int i=0;i<=npts;i++){ hreal->SetBinContent(i,evalLnLNumeric(ndata,nmc,hreal->GetBinCenter(i))); happrox->SetBinContent(i,evalLnLRamanujan(ndata,nmc)); } hreal->SetLineColor(kBlue); hreal->Draw(); happrox->Draw("same"); return; }
cea7961ef05af6a4c2bd45dd9f64c0577e476ccc
893106348b8f342b0102ac7feee028cd62c9c1f3
/lab_5/library.cpp
8f6037b5ab60bbd181da78f656a3f8597a97820a
[]
no_license
isaychris/CSCI222
f17ee1b241607f8763c445ef3bf5cab5115e1954
4fb1a1790437a1cdcea13823c63bf4ea3833c572
refs/heads/master
2021-09-03T15:57:54.971274
2018-01-10T08:17:26
2018-01-10T08:17:26
65,824,124
0
0
null
null
null
null
UTF-8
C++
false
false
2,752
cpp
// library.cpp #include <fstream> #include "holding.h" #include "library.h" using namespace std; ofstream csis; int main() { //Chris Banci //010031304 Holding** HoldingObjects = new Holding*[5]; //creates 5 array pointers to holding objects csis.open("csis.txt"); cout << "Enter holdings to be stored in a list: " << endl << endl; csis << "Enter holdings to be stored in a list: " << endl << endl; for (int i = 0; i < 5; i++) { HoldingObjects[i] = libraryFunct(); //library function called and returns pHolding to array object. } cout << endl << "Here are the holdings: " << endl << endl; csis << endl << "Here are the holdings: " << endl << endl; for (int i = 0; i < 5; i++) { HoldingObjects[i]->print(); //virtual printing for holding array object. } csis.close(); delete [] HoldingObjects; //deallocate memory return 0; } Holding * libraryFunct() { //function that creates a new holding and returns book or recording Holding * pHolding = nullptr; char holding_title[SIZE]; int holding_num; char option; tryagain: //jump to label cout << "Enter B for book, R for recording: "; cin >> option; cin.ignore(); csis << "Enter B for book, R for recording: " << option << endl; //.................case switch.................// switch (option) { default: cout << "[Error] Invalid option. Try again." << endl; goto tryagain; break; case 'B': case 'b': //book case char book_author[SIZE]; cout << "Enter book title: "; cin.getline(holding_title, SIZE); csis << "Enter book title: " << holding_title << endl; cout << "Enter book author: "; cin.getline(book_author, SIZE); csis << "Enter book author: " << book_author << endl; cout << "Enter call number: "; cin >> holding_num; csis << "Enter call number: " << holding_num << endl; pHolding = new Book(holding_title, book_author, holding_num); //pointer holds book. return pHolding; break; case 'R': case 'r': //recording case char rec_performer[SIZE]; char rec_format; cout << "Enter recording title: "; cin.getline(holding_title, SIZE); csis << "Enter recording title: " << holding_title << endl; cout << "Enter performer: "; cin.getline(rec_performer, SIZE); csis << "Enter performer: " << rec_performer << endl; cout << "Enter format: (M)P3, (W)AV, (A)IFF: "; cin >> rec_format; cin.ignore(); csis << "Enter format: (M)P3, (W)AV, (A)IFF: " << rec_format << endl; cout << "Enter call number: "; cin >> holding_num; csis << "Enter call number: " << holding_num << endl; pHolding = new Recording(holding_title, rec_format, rec_performer, holding_num); //pointer holds recording return pHolding; break; } return pHolding; //pointer returns as either a book or recording }
9fd19cf6e65b7cd3a8fa53259e5753856501c878
b0076d650c7af369d73704fdaaee1f07ba2abaf9
/CourseProject/Server/Time.h
10ae1e8432cd4690060613972521fda677ec12b0
[]
no_license
FroznShadow/Network-Project
d8e0903db23bc3493a9bb7daf4eafac1016f23e2
6b7978f945934b5f2c887959b2f9b985c7911d0b
refs/heads/master
2020-07-15T07:30:13.579771
2020-02-11T09:15:33
2020-02-11T09:15:33
94,305,495
0
0
null
null
null
null
UTF-8
C++
false
false
433
h
#pragma once #include <chrono> class DeltaTime { public: DeltaTime() :Start(std::chrono::high_resolution_clock::now()), End(Start) {}; double update() { Start = End; End = std::chrono::high_resolution_clock::now(); return std::chrono::duration<double>(End - Start).count(); } private: std::chrono::time_point<std::chrono::high_resolution_clock> Start; std::chrono::time_point<std::chrono::high_resolution_clock> End; };
f20da064c90f5586bbc492f2f2f1f9a768e3700a
539dd5a508f5b21bf9cd28f6d8276d5e85710bd1
/LongSubstrWithoutRepeating.cpp
40bf87bf011a99ec6c526d90bab22c4f5c683751
[]
no_license
vimalprogrammer/Leetcode_Solutions
76a7d44032b569e02861945ed8ae4818e92846dd
a651e12a6f35de37341aef95c33112f8ca818552
refs/heads/main
2023-08-18T17:05:06.440223
2021-10-01T15:10:08
2021-10-01T15:10:08
396,447,729
0
0
null
null
null
null
UTF-8
C++
false
false
2,423
cpp
#include <bits/stdc++.h> using namespace std; /*Longest Substring Without Repeating Characters: Given a string s, find the length of the longest substring without repeating characters. Example: Input: s = "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. */ class Solution { public: int lengthOfLongestSubstring(string s) { int A[127]={0}; int cnt=0,max=0; for(int i=0;i<s.length();i++) { for(int j=i;j>=0;j--) { char c=s[j]; if(A[c]==0) { cnt++; A[c]+=1; if(cnt>max) max=cnt; } else { cnt=0; for(int i=0;i<127;i++) A[i]=0; break; } } } return max; } }; int main() { string s = "helloo"; Solution ob; int res=ob.lengthOfLongestSubstring(s); cout<<res<<endl; return 0; } /* #include <bits/stdc++.h> using namespace std; class Solution { public: int lengthOfLongestSubstring(string s) { int n=s.size(); int j=0; int maxx=0; int i=0; unordered_set<int> st; while(j<n) { //char c=s[j]; if (st.find(s[j]) == st.end())// c not in st so add it { st.insert(s[j++]); // st=v and goes on and finally st=vimals // then 'a' already in st hence insertion will not happen // cnt=6 } else st.erase(s[i++]); //deleting all letters before 's' then st='s' and again cnting from 's' // st=sa and goes on and finally st=sa --> cnt-->2 // then 'a' already in st hence deletion will not happen // check for max cnt (6,2) --> max=6 // then again doing the same after 'a' i.e. deleting before 'a' //then st='a' and again cnting from 'a' doing same int stsize=st.size(); maxx= max(maxx,stsize); } return maxx; } }; int main() { string s = "vimalsasi"; Solution ob; int res=ob.lengthOfLongestSubstring(s); cout<<res<<endl; return 0; } */
540baddf25a1bfd01e6d7fa02fd2d9b9f1ea9c33
e911a874b4feb6bdf275d65c59887047319dc432
/src/rpc/net.cpp
bfb1c53fab9ea6a12d2f7dd50429423675908b39
[ "MIT" ]
permissive
ida-pay/idapay-refresh
c34742aa926623847aa792fdc5ba9baa26de8d0b
fa4c24c819ad2c211895930fc1f08a1811a4da65
refs/heads/master
2021-07-11T18:45:16.607382
2020-07-06T10:45:46
2020-07-06T10:45:46
161,047,918
1
4
MIT
2020-07-06T10:45:47
2018-12-09T14:30:08
C++
UTF-8
C++
false
false
26,453
cpp
// Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2014-2017 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpc/server.h" #include "chainparams.h" #include "clientversion.h" #include "validation.h" #include "net.h" #include "net_processing.h" #include "netbase.h" #include "protocol.h" #include "sync.h" #include "timedata.h" #include "ui_interface.h" #include "util.h" #include "utilstrencodings.h" #include "version.h" #include <boost/foreach.hpp> #include <univalue.h> using namespace std; UniValue getconnectioncount(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getconnectioncount\n" "\nReturns the number of connections to other nodes.\n" "\nResult:\n" "n (numeric) The connection count\n" "\nExamples:\n" + HelpExampleCli("getconnectioncount", "") + HelpExampleRpc("getconnectioncount", "") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); return (int)g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL); } UniValue ping(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "ping\n" "\nRequests that a ping be sent to all other nodes, to measure ping time.\n" "Results provided in getpeerinfo, pingtime and pingwait fields are decimal seconds.\n" "Ping command is handled in queue with all other commands, so it measures processing backlog, not just network ping.\n" "\nExamples:\n" + HelpExampleCli("ping", "") + HelpExampleRpc("ping", "") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); // Request that each node send a ping during next message processing pass g_connman->ForEachNode([](CNode* pnode) { pnode->fPingQueued = true; }); return NullUniValue; } UniValue getpeerinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getpeerinfo\n" "\nReturns data about each connected network node as a json array of objects.\n" "\nResult:\n" "[\n" " {\n" " \"id\": n, (numeric) Peer index\n" " \"addr\":\"host:port\", (string) The ip address and port of the peer\n" " \"addrlocal\":\"ip:port\", (string) local address\n" " \"services\":\"xxxxxxxxxxxxxxxx\", (string) The services offered\n" " \"relaytxes\":true|false, (boolean) Whether peer has asked us to relay transactions to it\n" " \"lastsend\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last send\n" " \"lastrecv\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last receive\n" " \"bytessent\": n, (numeric) The total bytes sent\n" " \"bytesrecv\": n, (numeric) The total bytes received\n" " \"conntime\": ttt, (numeric) The connection time in seconds since epoch (Jan 1 1970 GMT)\n" " \"timeoffset\": ttt, (numeric) The time offset in seconds\n" " \"pingtime\": n, (numeric) ping time (if available)\n" " \"minping\": n, (numeric) minimum observed ping time (if any at all)\n" " \"pingwait\": n, (numeric) ping wait (if non-zero)\n" " \"version\": v, (numeric) The peer version, such as 7001\n" " \"subver\": \"/IDAPay Core:x.x.x/\", (string) The string version\n" " \"inbound\": true|false, (boolean) Inbound (true) or Outbound (false)\n" " \"startingheight\": n, (numeric) The starting height (block) of the peer\n" " \"banscore\": n, (numeric) The ban score\n" " \"synced_headers\": n, (numeric) The last header we have in common with this peer\n" " \"synced_blocks\": n, (numeric) The last block we have in common with this peer\n" " \"inflight\": [\n" " n, (numeric) The heights of blocks we're currently asking from this peer\n" " ...\n" " ]\n" " \"bytessent_per_msg\": {\n" " \"addr\": n, (numeric) The total bytes sent aggregated by message type\n" " ...\n" " }\n" " \"bytesrecv_per_msg\": {\n" " \"addr\": n, (numeric) The total bytes received aggregated by message type\n" " ...\n" " }\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("getpeerinfo", "") + HelpExampleRpc("getpeerinfo", "") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); vector<CNodeStats> vstats; g_connman->GetNodeStats(vstats); UniValue ret(UniValue::VARR); BOOST_FOREACH(const CNodeStats& stats, vstats) { UniValue obj(UniValue::VOBJ); CNodeStateStats statestats; bool fStateStats = GetNodeStateStats(stats.nodeid, statestats); obj.push_back(Pair("id", stats.nodeid)); obj.push_back(Pair("addr", stats.addrName)); if (!(stats.addrLocal.empty())) obj.push_back(Pair("addrlocal", stats.addrLocal)); obj.push_back(Pair("services", strprintf("%016x", stats.nServices))); obj.push_back(Pair("relaytxes", stats.fRelayTxes)); obj.push_back(Pair("lastsend", stats.nLastSend)); obj.push_back(Pair("lastrecv", stats.nLastRecv)); obj.push_back(Pair("bytessent", stats.nSendBytes)); obj.push_back(Pair("bytesrecv", stats.nRecvBytes)); obj.push_back(Pair("conntime", stats.nTimeConnected)); obj.push_back(Pair("timeoffset", stats.nTimeOffset)); if (stats.dPingTime > 0.0) obj.push_back(Pair("pingtime", stats.dPingTime)); if (stats.dMinPing < std::numeric_limits<int64_t>::max()/1e6) obj.push_back(Pair("minping", stats.dMinPing)); if (stats.dPingWait > 0.0) obj.push_back(Pair("pingwait", stats.dPingWait)); obj.push_back(Pair("version", stats.nVersion)); // Use the sanitized form of subver here, to avoid tricksy remote peers from // corrupting or modifiying the JSON output by putting special characters in // their ver message. obj.push_back(Pair("subver", stats.cleanSubVer)); obj.push_back(Pair("inbound", stats.fInbound)); obj.push_back(Pair("startingheight", stats.nStartingHeight)); if (fStateStats) { obj.push_back(Pair("banscore", statestats.nMisbehavior)); obj.push_back(Pair("synced_headers", statestats.nSyncHeight)); obj.push_back(Pair("synced_blocks", statestats.nCommonHeight)); UniValue heights(UniValue::VARR); BOOST_FOREACH(int height, statestats.vHeightInFlight) { heights.push_back(height); } obj.push_back(Pair("inflight", heights)); } obj.push_back(Pair("whitelisted", stats.fWhitelisted)); UniValue sendPerMsgCmd(UniValue::VOBJ); BOOST_FOREACH(const mapMsgCmdSize::value_type &i, stats.mapSendBytesPerMsgCmd) { if (i.second > 0) sendPerMsgCmd.push_back(Pair(i.first, i.second)); } obj.push_back(Pair("bytessent_per_msg", sendPerMsgCmd)); UniValue recvPerMsgCmd(UniValue::VOBJ); BOOST_FOREACH(const mapMsgCmdSize::value_type &i, stats.mapRecvBytesPerMsgCmd) { if (i.second > 0) recvPerMsgCmd.push_back(Pair(i.first, i.second)); } obj.push_back(Pair("bytesrecv_per_msg", recvPerMsgCmd)); ret.push_back(obj); } return ret; } UniValue addnode(const UniValue& params, bool fHelp) { string strCommand; if (params.size() == 2) strCommand = params[1].get_str(); if (fHelp || params.size() != 2 || (strCommand != "onetry" && strCommand != "add" && strCommand != "remove")) throw runtime_error( "addnode \"node\" \"add|remove|onetry\"\n" "\nAttempts add or remove a node from the addnode list.\n" "Or try a connection to a node once.\n" "\nArguments:\n" "1. \"node\" (string, required) The node (see getpeerinfo for nodes)\n" "2. \"command\" (string, required) 'add' to add a node to the list, 'remove' to remove a node from the list, 'onetry' to try a connection to the node once\n" "\nExamples:\n" + HelpExampleCli("addnode", "\"192.168.0.6:19285\" \"onetry\"") + HelpExampleRpc("addnode", "\"192.168.0.6:19285\", \"onetry\"") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); string strNode = params[0].get_str(); if (strCommand == "onetry") { CAddress addr; g_connman->OpenNetworkConnection(addr, NULL, strNode.c_str()); return NullUniValue; } if (strCommand == "add") { if(!g_connman->AddNode(strNode)) throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: Node already added"); } else if(strCommand == "remove") { if(!g_connman->RemoveAddedNode(strNode)) throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node has not been added."); } return NullUniValue; } UniValue disconnectnode(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "disconnectnode \"node\" \n" "\nImmediately disconnects from the specified node.\n" "\nArguments:\n" "1. \"node\" (string, required) The node (see getpeerinfo for nodes)\n" "\nExamples:\n" + HelpExampleCli("disconnectnode", "\"192.168.0.6:19285\"") + HelpExampleRpc("disconnectnode", "\"192.168.0.6:19285\"") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); bool ret = g_connman->DisconnectNode(params[0].get_str()); if (!ret) throw JSONRPCError(RPC_CLIENT_NODE_NOT_CONNECTED, "Node not found in connected nodes"); return NullUniValue; } UniValue getaddednodeinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getaddednodeinfo dummy ( \"node\" )\n" "\nReturns information about the given added node, or all added nodes\n" "(note that onetry addnodes are not listed here)\n" "\nArguments:\n" "1. dummy (boolean, required) Kept for historical purposes but ignored\n" "2. \"node\" (string, optional) If provided, return information about this specific node, otherwise all nodes are returned.\n" "\nResult:\n" "[\n" " {\n" " \"addednode\" : \"192.168.0.201\", (string) The node ip address or name (as provided to addnode)\n" " \"connected\" : true|false, (boolean) If connected\n" " \"addresses\" : [ (list of objects) Only when connected = true\n" " {\n" " \"address\" : \"192.168.0.201:19285\", (string) The idapay server IP and port we're connected to\n" " \"connected\" : \"outbound\" (string) connection, inbound or outbound\n" " }\n" " ]\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("getaddednodeinfo", "true") + HelpExampleCli("getaddednodeinfo", "true \"192.168.0.201\"") + HelpExampleRpc("getaddednodeinfo", "true, \"192.168.0.201\"") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); std::vector<AddedNodeInfo> vInfo = g_connman->GetAddedNodeInfo(); if (params.size() == 2) { bool found = false; for (const AddedNodeInfo& info : vInfo) { if (info.strAddedNode == params[1].get_str()) { vInfo.assign(1, info); found = true; break; } } if (!found) { throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node has not been added."); } } UniValue ret(UniValue::VARR); for (const AddedNodeInfo& info : vInfo) { UniValue obj(UniValue::VOBJ); obj.push_back(Pair("addednode", info.strAddedNode)); obj.push_back(Pair("connected", info.fConnected)); UniValue addresses(UniValue::VARR); if (info.fConnected) { UniValue address(UniValue::VOBJ); address.push_back(Pair("address", info.resolvedAddress.ToString())); address.push_back(Pair("connected", info.fInbound ? "inbound" : "outbound")); addresses.push_back(address); } obj.push_back(Pair("addresses", addresses)); ret.push_back(obj); } return ret; } UniValue getnettotals(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "getnettotals\n" "\nReturns information about network traffic, including bytes in, bytes out,\n" "and current time.\n" "\nResult:\n" "{\n" " \"totalbytesrecv\": n, (numeric) Total bytes received\n" " \"totalbytessent\": n, (numeric) Total bytes sent\n" " \"timemillis\": t, (numeric) Total cpu time\n" " \"uploadtarget\":\n" " {\n" " \"timeframe\": n, (numeric) Length of the measuring timeframe in seconds\n" " \"target\": n, (numeric) Target in bytes\n" " \"target_reached\": true|false, (boolean) True if target is reached\n" " \"serve_historical_blocks\": true|false, (boolean) True if serving historical blocks\n" " \"bytes_left_in_cycle\": t, (numeric) Bytes left in current time cycle\n" " \"time_left_in_cycle\": t (numeric) Seconds left in current time cycle\n" " }\n" "}\n" "\nExamples:\n" + HelpExampleCli("getnettotals", "") + HelpExampleRpc("getnettotals", "") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); UniValue obj(UniValue::VOBJ); obj.push_back(Pair("totalbytesrecv", g_connman->GetTotalBytesRecv())); obj.push_back(Pair("totalbytessent", g_connman->GetTotalBytesSent())); obj.push_back(Pair("timemillis", GetTimeMillis())); UniValue outboundLimit(UniValue::VOBJ); outboundLimit.push_back(Pair("timeframe", g_connman->GetMaxOutboundTimeframe())); outboundLimit.push_back(Pair("target", g_connman->GetMaxOutboundTarget())); outboundLimit.push_back(Pair("target_reached", g_connman->OutboundTargetReached(false))); outboundLimit.push_back(Pair("serve_historical_blocks", !g_connman->OutboundTargetReached(true))); outboundLimit.push_back(Pair("bytes_left_in_cycle", g_connman->GetOutboundTargetBytesLeft())); outboundLimit.push_back(Pair("time_left_in_cycle", g_connman->GetMaxOutboundTimeLeftInCycle())); obj.push_back(Pair("uploadtarget", outboundLimit)); return obj; } static UniValue GetNetworksInfo() { UniValue networks(UniValue::VARR); for(int n=0; n<NET_MAX; ++n) { enum Network network = static_cast<enum Network>(n); if(network == NET_UNROUTABLE) continue; proxyType proxy; UniValue obj(UniValue::VOBJ); GetProxy(network, proxy); obj.push_back(Pair("name", GetNetworkName(network))); obj.push_back(Pair("limited", IsLimited(network))); obj.push_back(Pair("reachable", IsReachable(network))); obj.push_back(Pair("proxy", proxy.IsValid() ? proxy.proxy.ToStringIPPort() : string())); obj.push_back(Pair("proxy_randomize_credentials", proxy.randomize_credentials)); networks.push_back(obj); } return networks; } UniValue getnetworkinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getnetworkinfo\n" "Returns an object containing various state info regarding P2P networking.\n" "\nResult:\n" "{\n" " \"version\": xxxxx, (numeric) the server version\n" " \"subversion\": \"/IDAPay Core:x.x.x/\", (string) the server subversion string\n" " \"protocolversion\": xxxxx, (numeric) the protocol version\n" " \"localservices\": \"xxxxxxxxxxxxxxxx\", (string) the services we offer to the network\n" " \"localrelay\": true|false, (bool) true if transaction relay is requested from peers\n" " \"timeoffset\": xxxxx, (numeric) the time offset\n" " \"connections\": xxxxx, (numeric) the number of connections\n" " \"networkactive\": true|false, (bool) whether p2p networking is enabled\n" " \"networks\": [ (array) information per network\n" " {\n" " \"name\": \"xxx\", (string) network (ipv4, ipv6 or onion)\n" " \"limited\": true|false, (boolean) is the network limited using -onlynet?\n" " \"reachable\": true|false, (boolean) is the network reachable?\n" " \"proxy\": \"host:port\" (string) the proxy that is used for this network, or empty if none\n" " }\n" " ,...\n" " ],\n" " \"relayfee\": x.xxxxxxxx, (numeric) minimum relay fee for non-free transactions in " + CURRENCY_UNIT + "/kB\n" " \"localaddresses\": [ (array) list of local addresses\n" " {\n" " \"address\": \"xxxx\", (string) network address\n" " \"port\": xxx, (numeric) network port\n" " \"score\": xxx (numeric) relative score\n" " }\n" " ,...\n" " ]\n" " \"warnings\": \"...\" (string) any network warnings (such as alert messages) \n" "}\n" "\nExamples:\n" + HelpExampleCli("getnetworkinfo", "") + HelpExampleRpc("getnetworkinfo", "") ); LOCK(cs_main); UniValue obj(UniValue::VOBJ); obj.push_back(Pair("version", CLIENT_VERSION)); obj.push_back(Pair("subversion", strSubVersion)); obj.push_back(Pair("protocolversion",PROTOCOL_VERSION)); if(g_connman) obj.push_back(Pair("localservices", strprintf("%016x", g_connman->GetLocalServices()))); obj.push_back(Pair("localrelay", fRelayTxes)); obj.push_back(Pair("timeoffset", GetTimeOffset())); if (g_connman) { obj.push_back(Pair("networkactive", g_connman->GetNetworkActive())); obj.push_back(Pair("connections", (int)g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL))); } obj.push_back(Pair("networks", GetNetworksInfo())); obj.push_back(Pair("relayfee", ValueFromAmount(::minRelayTxFee.GetFeePerK()))); UniValue localAddresses(UniValue::VARR); { LOCK(cs_mapLocalHost); BOOST_FOREACH(const PAIRTYPE(CNetAddr, LocalServiceInfo) &item, mapLocalHost) { UniValue rec(UniValue::VOBJ); rec.push_back(Pair("address", item.first.ToString())); rec.push_back(Pair("port", item.second.nPort)); rec.push_back(Pair("score", item.second.nScore)); localAddresses.push_back(rec); } } obj.push_back(Pair("localaddresses", localAddresses)); obj.push_back(Pair("warnings", GetWarnings("statusbar"))); return obj; } UniValue setban(const UniValue& params, bool fHelp) { string strCommand; if (params.size() >= 2) strCommand = params[1].get_str(); if (fHelp || params.size() < 2 || (strCommand != "add" && strCommand != "remove")) throw runtime_error( "setban \"ip(/netmask)\" \"add|remove\" (bantime) (absolute)\n" "\nAttempts add or remove a IP/Subnet from the banned list.\n" "\nArguments:\n" "1. \"ip(/netmask)\" (string, required) The IP/Subnet (see getpeerinfo for nodes ip) with a optional netmask (default is /32 = single ip)\n" "2. \"command\" (string, required) 'add' to add a IP/Subnet to the list, 'remove' to remove a IP/Subnet from the list\n" "3. \"bantime\" (numeric, optional) time in seconds how long (or until when if [absolute] is set) the ip is banned (0 or empty means using the default time of 24h which can also be overwritten by the -bantime startup argument)\n" "4. \"absolute\" (boolean, optional) If set, the bantime must be a absolute timestamp in seconds since epoch (Jan 1 1970 GMT)\n" "\nExamples:\n" + HelpExampleCli("setban", "\"192.168.0.6\" \"add\" 86400") + HelpExampleCli("setban", "\"192.168.0.0/24\" \"add\"") + HelpExampleRpc("setban", "\"192.168.0.6\", \"add\" 86400") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); CSubNet subNet; CNetAddr netAddr; bool isSubnet = false; if (params[0].get_str().find("/") != string::npos) isSubnet = true; if (!isSubnet) { CNetAddr resolved; LookupHost(params[0].get_str().c_str(), resolved, false); netAddr = resolved; } else LookupSubNet(params[0].get_str().c_str(), subNet); if (! (isSubnet ? subNet.IsValid() : netAddr.IsValid()) ) throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: Invalid IP/Subnet"); if (strCommand == "add") { if (isSubnet ? g_connman->IsBanned(subNet) : g_connman->IsBanned(netAddr)) throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: IP/Subnet already banned"); int64_t banTime = 0; //use standard bantime if not specified if (params.size() >= 3 && !params[2].isNull()) banTime = params[2].get_int64(); bool absolute = false; if (params.size() == 4 && params[3].isTrue()) absolute = true; isSubnet ? g_connman->Ban(subNet, BanReasonManuallyAdded, banTime, absolute) : g_connman->Ban(netAddr, BanReasonManuallyAdded, banTime, absolute); } else if(strCommand == "remove") { if (!( isSubnet ? g_connman->Unban(subNet) : g_connman->Unban(netAddr) )) throw JSONRPCError(RPC_MISC_ERROR, "Error: Unban failed"); } return NullUniValue; } UniValue listbanned(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "listbanned\n" "\nList all banned IPs/Subnets.\n" "\nExamples:\n" + HelpExampleCli("listbanned", "") + HelpExampleRpc("listbanned", "") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); banmap_t banMap; g_connman->GetBanned(banMap); UniValue bannedAddresses(UniValue::VARR); for (banmap_t::iterator it = banMap.begin(); it != banMap.end(); it++) { CBanEntry banEntry = (*it).second; UniValue rec(UniValue::VOBJ); rec.push_back(Pair("address", (*it).first.ToString())); rec.push_back(Pair("banned_until", banEntry.nBanUntil)); rec.push_back(Pair("ban_created", banEntry.nCreateTime)); rec.push_back(Pair("ban_reason", banEntry.banReasonToString())); bannedAddresses.push_back(rec); } return bannedAddresses; } UniValue clearbanned(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "clearbanned\n" "\nClear all banned IPs.\n" "\nExamples:\n" + HelpExampleCli("clearbanned", "") + HelpExampleRpc("clearbanned", "") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); g_connman->ClearBanned(); return NullUniValue; } UniValue setnetworkactive(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) { throw runtime_error( "setnetworkactive true|false\n" "Disable/enable all p2p network activity." ); } if (!g_connman) { throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); } g_connman->SetNetworkActive(params[0].get_bool()); return g_connman->GetNetworkActive(); }
37b9651cfa25dbc536c176c24fa90d12012280b2
788c1404e18d6e11c0e179b8f52bb50d05dbf99c
/v1/Query/Range.cpp
f601288c4225009e8e62a2c82da9a516ce6d4ece
[]
no_license
helloyichu/PRESS
08b4fad52bfcb77fa444bf94aae4778b9e357b07
5bbc3c5d827ecc44078bf6107fdebccc5bafa616
refs/heads/master
2021-01-18T03:40:03.092228
2015-01-18T03:43:45
2015-01-18T03:43:45
null
0
0
null
null
null
null
GB18030
C++
false
false
21,284
cpp
/** 核心程序,进行MMTC的SPATIAl部分的压缩的程序 */ #include <iostream> #include <fstream> #include <stdio.h> #include <time.h> #include "define2.h" #include "file.h" #include <string.h> #include <stdlib.h> #include <math.h> #include <vector> #define MAXN 95000000 using namespace std; ofstream fout("E:\\TC\\OUTPUT.TXT"); int nodeInRegion[2000000],edgeInRegion[2000000]; //double latMax2 = 47.30329376225394, latMin2 = 46.83389173208538; //double longMax2 = -121.827392578125, longMin2 = -121.9557373046875; double latMax2 = 47.86523461231467, latMin2 = 47.427622733649606; double longMax2 = -122.213037109375, longMin2 = -122.43576049804688; union Int2Binary { int value; unsigned char data[4]; }; union Int2Binary int2Binary; union Double2Binary { double value; unsigned char data[8]; }; union Double2Binary double2Binary; void writeInt(FILE* file, int value) { int2Binary.value = value; fwrite(int2Binary.data,sizeof(unsigned char), 4,file); } int readInt(FILE* file) { //unsigned char buf[4]; if (fread(int2Binary.data,sizeof(unsigned char), 4,file) < 4) return -1; return int2Binary.value; } void writeDouble(FILE* file, double value) { double2Binary.value = value; fwrite(double2Binary.data,sizeof(unsigned char), 8,file); } double readDouble(FILE* file) { if (fread(double2Binary.data,sizeof(unsigned char), 8,file) < 8) return -1; return double2Binary.value; } //============ int nodeIndex[1000000][2]; //0:文件 1:偏移 int spSize; //到多少个点有最短路 int spPre[1000000]; //每个点的上一条边,-1表示不存在 int path[100000]; //记录原始SPATIAL路径 int ansSize; //压缩后实体个数 int ansList[10000]; //压缩后的轨迹,测试解压用 int SPNUM[40000]; int** SPLINK;/*-1表示两点间不连通*/ int MAP[2000000]; int save[10000]; //计算几何 /** * Get Distance between two points */ double circleDistance(double lat1,double long1,double lat2,double long2) { double deltaLat=lat1-lat2; double deltaLong=(long2-long1)*cos(lat1 * PI180); return LENGTH_PER_RAD*sqrt(deltaLat*deltaLat+deltaLong*deltaLong); } /** *description:计算球面一点到一条路径的距离 *param: double double 点坐标 int 边标号 double* 最近点距离边的前端点距离 double* 道路长度 *return:地球面距离,单位米 */ double nodeToEdgeDistanceAndNodeSide(double nodeX,double nodeY,int edgeId,double *sideLen,double *roadLen){ int i,j; double tmpSideLen=0,tmpRoadLen=0; double result=1e80,tmp=0; for (i=edgeStart[edgeId];i<edgeStart[edgeId+1];++i){ double x=coordNet[i << 1],y=coordNet[(i << 1)+1],x2=coordNet[(i << 1)+2],y2=coordNet[(i << 1)+3]; double dist=circleDistance(x,y,nodeX,nodeY); if (dist<result){ result=dist; tmpSideLen=tmp; } if (i<edgeStart[edgeId+1]-1) { double vecX1=x2-x,vecY1=y2-y, vecX2=nodeX-x,vecY2=nodeY-y, vecX3=nodeX-x2,vecY3=nodeY-y2; if (vecX1*vecX2+vecY1*vecY2>0 && -vecX1*vecX3-vecY1*vecY3>0 && (vecX1!=0 || vecY1!=0)){ double rate=((nodeX-x2)*vecX1+(nodeY-y2)*vecY1)/(-vecX1*vecX1-vecY1*vecY1); double nearX=rate*x+(1-rate)*x2,nearY=rate*y+(1-rate)*y2; double dist=circleDistance(nearX,nearY,nodeX,nodeY); if (dist<result){ result=dist; tmpSideLen=tmp+circleDistance(x,y,nearX,nearY); } } tmpRoadLen+=circleDistance(x,y,x2,y2); } tmp+=circleDistance(x,y,x2,y2); } *sideLen=tmpSideLen; *roadLen=tmpRoadLen; return result; } //两路口间路径长度 double pathLen(int node1, int node2) {/*两点之间的最短距离*/ //printf("\n%d %d\n",node1,node2); double res = 0, sideLen,roadLen; int count = 0; while (node2!=node1) { save[count] = SPLINK[node1][node2]; if (save[count] == -1) break; node2 = thisSide[save[count]]; ++count; } int i; for (i = count-1; i >=0; --i) { nodeToEdgeDistanceAndNodeSide(0,0,save[i],&sideLen,&roadLen); res += roadLen; } return res; } //两路口间mbr void edgeMBR(int edgeId, double* x1, double* x2, double* y1, double* y2) { int i,j; double minX = 1e100, minY = 1e100, maxX = -1e100, maxY = -1e100; for (i=edgeStart[edgeId];i<edgeStart[edgeId+1];++i){ double x=coordNet[i << 1],y=coordNet[(i << 1)+1],x2=coordNet[(i << 1)+2],y2=coordNet[(i << 1)+3]; if (x > maxX) maxX = x; if (x < minX) minX = x; if (x2 > maxX) maxX = x2; if (x2 < minX) minX = x2; if (y > maxY) maxY = y; if (y < minY) minY = y; if (y2 > maxY) maxY = y2; if (y2 < minY) minY = y2; } *x1 = minX; *x2 = maxX; *y1 = minY; *y2 = maxY; } void pathMBR(int node1, int node2, double* x1, double* x2, double* y1, double* y2) { //printf("\n%d %d\n",node1,node2); double mx1, mx2, my1, my2; double res = 0, sideLen,roadLen; double minX = 1e100, minY = 1e100, maxX = -1e100, maxY = -1e100; int count = 0; while (node2!=node1) { save[count] = SPLINK[node1][node2]; if (save[count] == -1) break; node2 = thisSide[save[count]]; ++count; } int i; for (i = count-1; i >=0; --i) { edgeMBR(save[i], &mx1, &mx2, &my1, &my2); if (mx1 < minX) minX = mx1; if (mx2 > maxX) maxX = mx2; if (my1 < minY) minY = my1; if (my2 > maxY) maxY = my2; } *x1 = minX; *x2 = maxX; *y1 = minY; *y2 = maxY; } void loadSPAll2() { int t; int s; int f; int c = 0; //memset(SPLINK,255,sizeof(SPLINK)); //SPLINK = (int**)malloc(40000*sizeof(int)); SPLINK = new int*[30000]; for (t = 0; t < 30000; ++t) { SPLINK[t] = new int[30000]; } for (t = 0; t < 30000; ++t) for (s = 0; s < 30000; ++s) SPLINK[t][s] = -1; char fileName[100]="../ShortestPath/SP00.txt"; ////// for (f = 0; f < 21; ++f) { //-- //cout << f << endl; fileName[18] = (f / 10) + 48; fileName[19] = (f % 10) + 48; cout << fileName << endl; //-- //printf("%d %s\n",nodeId,fileName); FILE* file = fopen(fileName,"rb"); //点数 int number = readInt(file); int j; for (j = 0; j < number; ++j) { //id int id = readInt(file); //MAP[id] = c; //个数 int many = readInt(file); int i; //memset(spPre,255,sizeof(spPre)); for (i = 0; i < many; ++i){ int q = readInt(file); SPLINK[id][q] = readInt(file); } //++c; } //fseek(file,nodeIndex[nodeId][1],0); //spSize = readInt(file); fclose(file); } } int* son/*节点孩子编号*/, *righting/*右兄弟编号*/, *value/*路段编号*/, counting, *father/*父节点标号*/, *father2/*最远祖先标号,根的直接孩子存的是本身编号*/, *L, *R, *F, *map/*-1代表不是叶子节点*/, *rvsmap, *fail, depth; double *trielen/*trie树上记录的距离*/,*mbr1,*mbr2,*mbr3,*mbr4/*xxyy*/; int e = 0,p,q; int halfRoot;/*哈夫曼树根节点编号,L[i]=i节点左孩子编号,R[i]=i节点右孩子编号,F[i]=i节点父亲编号,map[i]=trie树节点编号j,rvsmap[j]=哈夫曼树i节点*/ double tmpDist[100000], tmpTime[100000]; char spCode[100000]; pair<double,double> query(int T, string code, int spNumber) { double d; int s,e; if(tmpTime[0] > T || tmpTime[spNumber-1] < T) return make_pair(-1,-1); for(int i = 0;i < spNumber;i++) { if(tmpTime[i] > T) { s = i-1; e = i; d = tmpDist[s] + (tmpDist[e]-tmpDist[s])/(tmpTime[e]-tmpTime[s])*(T-tmpTime[s]); break; } } int count = 0; int c = halfRoot; double curD = 0.0; double lastD = 0.0; bool mark = 0; int last;//上一段最后节点 int trieNum; int trieTarget; int result = -1; int final_s,final_t; for(int i = 0;i < code.length();i++) { int cur = code[i]-'0'; if(cur == 0) c = L[c]; else c = R[c]; if(map[c] != -1) { // cout << curD << endl; // cout << map[c] << endl; if(mark == 0) { curD = trielen[map[c]]; mark = 1; last = other[value[map[c]]]; count++; } else { lastD = curD; curD += pathLen(last,thisSide[value[father2[map[c]]]]); // cout << lastD << "\t" << curD << "\t 1"<< endl; count++; if(curD > d) { /*落在两段边之间的最短路径上*/ final_s = last; final_t = thisSide[value[father2[map[c]]]]; result = 0; break; } lastD = curD; curD += trielen[map[c]]; // cout << lastD << "\t" << curD << "\t 2" << endl; count++; if(curD > d) { /*落在trie树保存的链上*/ result = 1; trieTarget = map[c]; break; } last = other[value[map[c]]]; } c = halfRoot; } } if(count <= 2) return make_pair(-1,-1); if(curD <= d) { return make_pair(coordNode[last*2],coordNode[last*2+1]); } // cout << result << endl; if(result == 0) { /*在final_s,final_t之间的最短路径上*/ int final_e; int curs,cure; double endD; while(curD > d) { final_e = SPLINK[final_s][final_t]; curs = thisSide[final_e]; cure = other[final_e]; endD = curD; curD -= pathLen(curs,cure); } double x1 = coordNode[curs*2]; double y1 = coordNode[curs*2+1]; double x2 = coordNode[cure*2]; double y2 = coordNode[cure*2+1]; pair<double, double> re = make_pair((d-curD)/(endD-curD)*(x2-x1)+x1,(d-curD)/(endD-curD)*(y2-y1)+y1); return re; } else if(result == 1) { while(lastD+trielen[father[trieTarget]] > d) { trieTarget = father[trieTarget]; //cout << lastD <<"\t" << trielen[father[trieTarget]] << endl; } if(lastD + trielen[father[trieTarget]] + pathLen(other[value[father[trieTarget]]],thisSide[value[trieTarget]]) > d) { /*在other[value[father[trieTarget]]],thisSide[trieTarget]之间*/ // cout << 3 << endl; final_t = thisSide[value[trieTarget]]; // cout << final_s << "\t" << final_t << endl; if(pathLen(final_s,final_t) < 1e-3 || final_s == final_t) return make_pair(coordNode[final_s*2],coordNode[final_s*2+1]); int final_e; int curs,cure; double endD; int cc = 0; while(curD >= d) { cc++; // system("pause"); final_e = SPLINK[final_s][final_t]; if(final_e == -1) return make_pair(-1,-1); final_t = thisSide[final_e]; curs = thisSide[final_e]; cure = other[final_e]; endD = curD; curD -= pathLen(curs,cure); // cout << final_e << endl; // cout << curs << " " << cure << endl; // cout << curD << endl; } double x1 = coordNode[curs*2]; double y1 = coordNode[curs*2+1]; double x2 = coordNode[cure*2]; double y2 = coordNode[cure*2+1]; pair<double, double> re = make_pair((d-curD)/(endD-curD)*(x2-x1)+x1,(d-curD)/(endD-curD)*(y2-y1)+y1); return re; } else { /*sonTarget边上*/ double startD = lastD + trielen[trieTarget] + pathLen(other[value[trieTarget]],thisSide[value[trieTarget]]); double endD = lastD + trielen[trieTarget]; double len = endD-startD; double x1 = coordNode[thisSide[value[trieTarget]]*2]; double y1 = coordNode[thisSide[value[trieTarget]]*2+1]; double x2 = coordNode[other[value[trieTarget]]*2]; double y2 = coordNode[other[value[trieTarget]]*2+1]; pair<double, double> re = make_pair((d-startD)/(endD-startD)*(x2-x1)+x1,(d-startD)/(endD-startD)*(y2-y1)+y1); return re; } } } double dis(double x1,double y1,double x2,double y2,double x,double y) { if(x > x2) { if(y > y2) return (x-x2)*(x-x2)+(y-y2)*(y-y2); if(y < y1) return (x-x2)*(x-x2)+(y1-y)*(y1-y); return (x-x2)*(x-x2); } if(x < x1) { if(y > y2) return (x1-x)*(x1-x)+(y-y2)*(y-y2); if(y < y1) return (x1-x)*(x1-x)+(y1-y)*(y1-y); return (x1-x)*(x1-x); } if(y > y2) return (y-y2)*(y-y2); if(y < y1) return (y1-y)*(y1-y); return 0.0; } int queryWhenAt(string code, double x, double y, int spNumber) { int count = 0; int c = halfRoot; double curD = 0.0; bool mark = 0; int last;//上一段最后节点 double mindis = 1e10; double tdis; int trieNum; int trieTarget; int result = -1; int final_s,final_t; int inSP = -1; for(int i = 0;i < code.length();i++) { int cur = code[i]-'0'; if(cur == 0) c = L[c]; else c = R[c]; if(map[c] != -1) { if(mark == 0) { if(mbr1[map[c]] <= x && mbr2[map[c]] >= x && mbr3[map[c]] <= y && mbr4[map[c]] >= y) { trieTarget = map[c]; result = 0; break; } mindis = dis(mbr1[map[c]],mbr3[map[c]],mbr2[map[c]],mbr4[map[c]],x,y); curD = trielen[map[c]]; last = other[value[map[c]]]; mark = 1; } else { int endP = thisSide[value[father2[map[c]]]]; double cx1,cy1,cx2,cy2; pathMBR(last,endP,&cx1,&cx2,&cy1,&cy2); if(cx1 <= x && cx2 >= x && cy1 <= y && cy2 >= y) { // cout << 1 << endl; result = 1; final_s = last; final_t = endP; break; } tdis = dis(cx1,cy1,cx2,cy2,x,y); if(mindis > tdis) { result = 1; final_s = last; final_t = endP; mindis = tdis; } curD += pathLen(last,endP); if(mbr1[map[c]] <= x && mbr2[map[c]] >= x && mbr3[map[c]] <= y && mbr4[map[c]] >= y) { // cout << 2 << endl; trieTarget = map[c]; result = 0; break; } tdis = dis(mbr1[map[c]],mbr3[map[c]],mbr2[map[c]],mbr4[map[c]],x,y); if(mindis > tdis) { result = 0; trieTarget = map[c]; mindis = tdis; } curD += trielen[map[c]]; last = other[value[map[c]]]; } c = halfRoot; } } //cout << result << endl; if(result == 1) { //在final_s和final_t的最短路径上 curD += pathLen(final_s,final_t); double x1,x2,y1,y2; mindis = 1e10; int ts,tt; double td; int curE; while(thisSide[curE] != final_s) { curE = SPLINK[final_s][final_t]; pathMBR(thisSide[curE],other[curE],&x1,&x2,&y1,&y2); tdis = dis(x1,y1,x2,y2,x,y); curD -= pathLen(thisSide[curE],other[curE]); if(tdis < mindis) { ts = thisSide[curE]; tt = other[curE]; mindis = tdis; td = curD; } final_t = thisSide[curE]; // cout << final_t << "\t" << final_s << endl; //system("pause"); } curD = td; //cout << result << "\t" << trieTarget << endl; } // 在final_s,final_t之间的边上,final_s距离为curD for(int i = 0;i < spNumber;i++) { if(tmpDist[i] > curD) { return tmpTime[i-1] + (curD-tmpDist[i-1])/(tmpDist[i]-tmpDist[i-1]) * (tmpTime[i]-tmpTime[i-1]); } } } #define TIME1 13102826 #define TIME2 13122826 double RANGE[5][4] = { {1.182,103.62,1.31074,103.802}, {1.39658,103.924,1.52533,104.106}, {1.39658,103.62,1.52533,103.802}, {1.182,103.924,1.31074,104.106}, {1.28929,103.772,1.41804,103.954} }; bool MBRmixed(double x1,double x2,double y1,double y2,double qx1,double qx2,double qy1,double qy2) { if(x1 > qx2 || x2 < qx1 || y1 > qy2 || y2 < qy1) return 0; return 1; } bool cross(double x11,double y11,double x12,double y12,double x21,double y21,double x22,double y22) { double Ex1 = x11-x21; double Ey1 = y11-y21; double Ex2 = x22-x21; double Ey2 = y22-y21; double Ex3 = x12-x21; double Ey3 = y12-y21; if((Ex2*Ey1-Ex1*Ey2)*(Ex2*Ey3-Ey2*Ex3) >= 0) return 0; Ex1 = -Ex1; Ey1 = -Ey1; Ex2 = x12-x11; Ey2 = y12-y11; Ex3 = x22-x11; Ey3 = y22-y11; if((Ex2*Ey1-Ex1*Ey2)*(Ex2*Ey3-Ey2*Ex3) >= 0) return 0; return 1; } bool crossMBR(double lx1,double ly1,double lx2,double ly2,double x1,double y1,double x2,double y2) { if(lx1 < x2 && lx1 > x1 && ly1 < y2 && ly1 > y1) return 1; if(cross(lx1,ly1,lx2,ly2,x1,y1,x1,y2)) return 1; if(cross(lx1,ly1,lx2,ly2,x1,y1,x2,y1)) return 1; if(cross(lx1,ly1,lx2,ly2,x2,y1,x2,y2)) return 1; if(cross(lx1,ly1,lx2,ly2,x1,y2,x2,y2)) return 1; return 0; } bool crossEdge(int edgeID,double x1,double y1,double x2,double y2) { for (int i=edgeStart[edgeID];i<edgeStart[edgeID+1];++i){ double lx1=coordNet[i << 1],ly1=coordNet[(i << 1)+1],lx2=coordNet[(i << 1)+2],ly2=coordNet[(i << 1)+3]; if(crossMBR(lx1,ly1,lx2,ly2,x1,y1,x2,y2) == 1) return 1; } return 0; } int spatialNumber; int rangeQuery(int startT, int endT, double qx1,double qy1, double qx2,double qy2, int spNumber) { int s,e; double d1,d2; if(tmpTime[0] > TIME2 || tmpTime[spNumber-1] < TIME1) return 0; for(int i = 0;i < spNumber;i++) { if(tmpTime[i] > TIME1) { s = i-1; e = i; d1 = tmpDist[s] + (tmpDist[e]-tmpDist[s])/(tmpTime[e]-tmpTime[s])*(TIME1-tmpTime[s]); } if(tmpTime[i] > TIME2) { s = i-1; e = i; d2 = tmpDist[s] + (tmpDist[e]-tmpDist[s])/(tmpTime[e]-tmpTime[s])*(TIME2-tmpTime[s]); break; } } double dist = 0; double sideLen, roadLen; for (int i = 0; i < spatialNumber; ++i) { if (dist > d2) break; nodeToEdgeDistanceAndNodeSide(0,0,path[i],&sideLen,&roadLen); if (dist + roadLen <= d1) { dist += roadLen; continue; } if (crossEdge(path[i],qx1,qy1,qx2,qy2)) return 1; } return 0; } int main(int argc, char *argv[]) { //Load Road Network from File char sss[20] = ""; //读入路网 loadData(sss); //=============== int nodeUseful = 0; int i; //============Part 1 用最短路压缩轨迹===================== //全内存载入最短路 //最短路表 loadSPAll2(); //读入Trie FILE* fp = fopen("./suffix_03.txt","r"); son = (int*)malloc(MAXN*sizeof(int)); righting = (int*)malloc(MAXN*sizeof(int)); value = (int*)malloc(MAXN*sizeof(int)); father = (int*)malloc(MAXN*sizeof(int)); father2 = (int*)malloc(MAXN*sizeof(int)); mbr1 = (double*)malloc(MAXN*sizeof(double)); mbr2 = (double*)malloc(MAXN*sizeof(double)); mbr3 = (double*)malloc(MAXN*sizeof(double)); mbr4 = (double*)malloc(MAXN*sizeof(double)); trielen = (double*)malloc(MAXN*sizeof(double)); fail = (int*)malloc(MAXN*sizeof(int)); map = (int*)malloc(MAXN*sizeof(int)); rvsmap = (int*)malloc(MAXN*sizeof(int)); L = (int*)malloc(MAXN*sizeof(int)); R = (int*)malloc(MAXN*sizeof(int)); F = (int*)malloc(MAXN*sizeof(int)); fscanf(fp,"%d",&e); for (int i = 0; i <= e; ++i) fscanf(fp,"%d%d%d%d%d",&son[i],&righting[i],&father[i],&value[i],&counting); fclose(fp); for (int i = 1; i <=e; ++i) if (father[i] == 0) father2[i] = i; else father2[i] = father2[father[i]]; //读入failure function fp = fopen("./ac_03.txt","r"); for (int i = 0; i <=e; ++i) fscanf(fp,"%d%d",&fail[i],&depth); fclose(fp); //Halfman树编码 fp = fopen("./halfman_03.txt","r"); // Huffman Root fscanf(fp,"%d",&halfRoot); for (int i = 0; i <= halfRoot; ++i) { int id; fscanf(fp,"%d",&id); fscanf(fp,"%d%d%d",&L[id],&R[id],&map[id]); if (L[id] > -1) F[L[id]] = id; if (R[id] > -1) F[R[id]] = id; rvsmap[map[id]] = id; } fclose(fp); //Len & MBR fp = fopen("./LenMBR.txt","r"); for (int i = 0; i <=e; ++i) fscanf(fp,"%lf%lf%lf%lf%lf",&trielen[i],&mbr1[i],&mbr2[i],&mbr3[i],&mbr4[i]); fclose(fp); //读入Spatial & Temporal 然后处理 long ttr = clock(); fp =fopen(argv[1],"rb"); //Temporal文件 FILE* spatial = fopen("./DBTrajectory_Spatial_005.txt","rb"); readInt(spatial); //cout << 1 << endl; FILE* q = fopen("./WhenAt.txt","r"); int queryNumber; fscanf(q,"%d",&queryNumber); int tjNumber = readInt(fp); int kk; //fscanf(spatial,"%d\n",&kk); int qcount = 0; int pNumber; //cout << 1 << endl; FILE* oup = fopen(argv[2],"w"); for(int j = 0;j < queryNumber;j++) { double qx,qy; int qNumber; //fscanf(q,"%d %lf %lf",&qNumber,&qx, &qy); //while(qcount <= qNumber) { //cout << qcount << "\t" << qNumber << endl; spatialNumber = readInt(spatial); for (int u = 0; u < spatialNumber; ++u) path[u] = readInt(spatial); //qcount ++; pNumber = readInt(fp); for(int i = 0;i < pNumber;i++) { tmpDist[i] = readInt(fp); tmpTime[i] = readInt(fp); } //if(j == 1052) /*cout << j<< "\t" << rangeQuery(spCode,TIME1,TIME2,RANGE[0][0],RANGE[0][1],RANGE[0][2],RANGE[0][3],pNumber) << endl; cout << j<< "\t" << rangeQuery(spCode,TIME1,TIME2,RANGE[1][0],RANGE[1][1],RANGE[1][2],RANGE[1][3],pNumber) << endl; cout << j<< "\t" << rangeQuery(spCode,TIME1,TIME2,RANGE[2][0],RANGE[2][1],RANGE[2][2],RANGE[2][3],pNumber) << endl; cout << j<< "\t" << rangeQuery(spCode,TIME1,TIME2,RANGE[3][0],RANGE[3][1],RANGE[3][2],RANGE[3][3],pNumber) << endl; cout << j<< "\t" << rangeQuery(spCode,TIME1,TIME2,RANGE[4][0],RANGE[4][1],RANGE[4][2],RANGE[4][3],pNumber) << endl; */ fprintf(oup,"%d",rangeQuery(TIME1,TIME2,RANGE[0][0],RANGE[0][1],RANGE[0][2],RANGE[0][3],pNumber)); fprintf(oup,"%d",rangeQuery(TIME1,TIME2,RANGE[1][0],RANGE[1][1],RANGE[1][2],RANGE[1][3],pNumber)); fprintf(oup,"%d",rangeQuery(TIME1,TIME2,RANGE[2][0],RANGE[2][1],RANGE[2][2],RANGE[2][3],pNumber)); fprintf(oup,"%d",rangeQuery(TIME1,TIME2,RANGE[3][0],RANGE[3][1],RANGE[3][2],RANGE[3][3],pNumber)); fprintf(oup,"%d\n",rangeQuery(TIME1,TIME2,RANGE[4][0],RANGE[4][1],RANGE[4][2],RANGE[4][3],pNumber)); //system("pause"); } fclose(oup); fclose(fp); fclose(spatial); FILE* fff = fopen("yao.txt","a+"); fprintf(fff,"%ld\n",clock()-ttr); fclose(fff); //system("pause"); return 0; }
bd20ea70548b4642167021753088eae5d27e689e
c6b0381b303a5b192a159305759e58681d7a4835
/AVL tree/main.cpp
eda5f3f6fc5e5c1cd1e537ed94a0d101cb9d9309
[]
no_license
rajeshkumarsinha/Important-codes
1163d92da501f90a6364462bb3084de982cba460
1146419a1ea93f57c69dbb4397152ae2a62df8fa
refs/heads/master
2020-12-10T21:26:32.750014
2016-08-25T12:03:06
2016-08-25T12:03:06
41,245,607
0
0
null
null
null
null
UTF-8
C++
false
false
2,095
cpp
#include <iostream> using namespace std; struct node{ int val; int c; node* lc; node* rc; int height; }; node* getnode(int val,int c) { node* temp=new node; temp->c=c; temp->val=val; temp->lc=NULL; temp->rc=NULL; temp->height=1; return temp; } int height(node* root) { if(root==NULL)return 0; return root->height; } node* rcrotate(node* y) { node* x=y->lc; node* t2=x->rc; x->rc=y; y->lc=t2; y->height=max(height(y->lc),height(y->rc))+1; x->height=max(height(x->lc),height(x->rc))+1; return x; } node* lcrotate(node* x) { node* y=x->rc; node* t2=y->lc; y->lc=x; x->rc=t2; x->height=max(height(x->lc),height(x->rc))+1; y->height=max(height(y->lc),height(y->rc))+1; return y; } int getbalance(node* root) { if(root==NULL)return 0; return height(root->lc)-height(root->rc); } node* insert(node* root,int val,int c) { if(root==NULL) { return getnode(val,c); } if(root->val>val) { root->lc=insert(root->lc,val,c); } else if(root->val<val) { root->rc=insert(root->rc,val,c); } else { root->c+=c; } root->height=max(height(root->lc),height(root->rc))+1; int balance=getbalance(root); if(balance>1&&val<root->lc->val) { return rcrotate(root); } if(balance<-1&&val>root->rc->val) { return lcrotate(root); } if(balance>1&&val>root->lc->val) { root->lc=lcrotate(root->lc); return rcrotate(root); } if(balance<-1&&val<root->rc->val) { root->rc=rcrotate(root->rc); return lcrotate(root); } return root; } void preorder(node* root) { if(root==NULL)return; cout<<root->val<<" "; preorder(root->lc); preorder(root->rc); } int main() { node* root=NULL; root = insert(root, 10); root = insert(root, 20); root = insert(root, 30); root = insert(root, 40); root = insert(root, 50); root = insert(root, 25); preorder(root); return 0; }
[ "valkyrie@valkyrie-300E4Z-300E5Z-300E7Z.(none)" ]
valkyrie@valkyrie-300E4Z-300E5Z-300E7Z.(none)
cd476676a7125b6f8c9edcf0bce81edde4c01271
b17f0249c689d30242b30ea8f05854b577efe988
/libnodes/include/nodes/internal/NodeStyle.hpp
0a1f4c61dd3a5c87cfe62c1d009990c0ad1e3015
[ "MIT" ]
permissive
hojjatabdollahi/StoryWriter
d8b37d7580ec92042971b65bbe29c67cad80536c
5df36618ebfa237f826a9965ff2699b7b2422177
refs/heads/master
2020-03-24T02:43:22.115578
2018-07-28T06:53:23
2018-07-28T06:53:23
142,387,919
0
0
null
null
null
null
UTF-8
C++
false
false
955
hpp
#pragma once #include <QtGui/QColor> #include "Export.hpp" #include "Style.hpp" namespace QtNodes { class NODE_EDITOR_PUBLIC NodeStyle : public Style { public: NodeStyle(); NodeStyle(QString jsonText); public: static void setNodeStyle(QString jsonText); private: void loadJsonText(QString jsonText) override; void loadJsonFile(QString fileName) override; void loadJsonFromByteArray(QByteArray const &byteArray) override; public: QColor NormalBoundaryColor; QColor SelectedBoundaryColor; QColor GradientColor0; QColor GradientColor1; QColor GradientColor2; QColor GradientColor3; QColor ShadowColor; QColor FontColor; QColor FontColorFaded; QColor ConnectionPointColor; QColor FilledConnectionPointColor; QColor WarningColor; QColor ErrorColor; float PenWidth; float HoveredPenWidth; float ConnectionPointDiameter; float Opacity; }; }
7dc5bb14e484d5ce0c1b84edea0a8216d2413f47
d0fb46aecc3b69983e7f6244331a81dff42d9595
/paifeaturestore/src/model/GetLabelTableRequest.cc
96f8dfc7031db9ff9dfac6188ef0d5efc21e7b09
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-cpp-sdk
3d8d051d44ad00753a429817dd03957614c0c66a
e862bd03c844bcb7ccaa90571bceaa2802c7f135
refs/heads/master
2023-08-29T11:54:00.525102
2023-08-29T03:32:48
2023-08-29T03:32:48
115,379,460
104
82
NOASSERTION
2023-09-14T06:13:33
2017-12-26T02:53:27
C++
UTF-8
C++
false
false
1,572
cc
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/paifeaturestore/model/GetLabelTableRequest.h> using AlibabaCloud::PaiFeatureStore::Model::GetLabelTableRequest; GetLabelTableRequest::GetLabelTableRequest() : RoaServiceRequest("paifeaturestore", "2023-06-21") { setResourcePath("/api/v1/instances/[InstanceId]/labeltables/[LabelTableId]"}; setMethod(HttpRequest::Method::Get); } GetLabelTableRequest::~GetLabelTableRequest() {} std::string GetLabelTableRequest::getInstanceId() const { return instanceId_; } void GetLabelTableRequest::setInstanceId(const std::string &instanceId) { instanceId_ = instanceId; setParameter(std::string("InstanceId"), instanceId); } std::string GetLabelTableRequest::getLabelTableId() const { return labelTableId_; } void GetLabelTableRequest::setLabelTableId(const std::string &labelTableId) { labelTableId_ = labelTableId; setParameter(std::string("LabelTableId"), labelTableId); }
5ff5b5edf7ee270e0c4c6e11053f5a498adc2414
7f67fb29806bf037b1f0b1ec2134f82435c73082
/plugins/osgaudio/include2/openalpp/NetUpdater.h
27a87f249cac6d09791abaa8b64b5307ced1f3e6
[]
no_license
popoca/OSG_ShootingGallery
a65f92c121ea8741750c8a572123a0062a331db9
75f9b58b0dddc274d05deda716072354f7e23f31
refs/heads/master
2020-04-09T02:40:51.579783
2010-12-17T10:11:01
2010-12-17T10:11:01
1,242,956
0
1
null
null
null
null
IBM852
C++
false
false
2,423
h
/* -*-c++-*- */ /** * osgAudio - OpenSceneGraph Audio Library * Copyright (C) 2010 AlphaPixel, LLC * based on a fork of: * Osg AL - OpenSceneGraph Audio Library * Copyright (C) 2004 VRlab, Umeň University * * This library 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. * Please see COPYING file for special static-link exemption to LGPL. * * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #ifndef OPENALPP_NETUPDATER_H #define OPENALPP_NETUPDATER_H 1 #if ALPP_USE_NETSTREAM #include <cc++/socket.h> #include "stdlib.h" #include <openalpp/Export.h> #include <openalpp/StreamUpdater.h> namespace openalpp { /** * Updater for streams through sockets. */ class OPENALPP_API NetUpdater : public StreamUpdater { /** * Socket to receive sound data from. */ ost::UDPSocket *socket_; /** * Stream to receive control messages from. */ ost::TCPStream *controlsocket_; /** * Size of sound buffer (in bytes). */ unsigned int buffersize_; public: /** * Constructor. * @param socket is the socket to receive sound data from. * @param controlsocket is the stream to receive control messages from. Set * to NULL if control messages are not used. * @param buffer1 and... * @param buffer2 are the sound buffers to use. * @param format is the (OpenAL) format of the sound data. * @param frequency is the frequency of the sound data. * @param buffersize is how much data to buffer before adding to the stream. */ NetUpdater(ost::UDPSocket *socket,ost::TCPStream *controlsocket, const ALuint buffer1,ALuint buffer2, ALenum format,unsigned int frequency, unsigned int buffersize); /** * Inherited from Thread. * This will be called when the updater is Start():ed.. */ void run(); }; } #endif /* OPENALPP_NETUPDATER_H */ #endif
115dce0eb1669d6b956be59de241ec4d6e4d7b7f
b137f5bb9d3b77266f46073bc2da72bf445854d6
/1140B.cpp
b3a04f0e0d378fe8cac2d95e8fea0d1b81d17ba7
[]
no_license
killzdesu/cpp-archive
307fa05be71618f2a64b3c852078eef88696da86
70f62a7bbc2f3398ac28818849841f18b1145f91
refs/heads/master
2023-04-08T20:16:57.460572
2021-04-20T06:23:31
2021-04-20T06:23:31
359,705,314
0
0
null
null
null
null
UTF-8
C++
false
false
641
cpp
#include<bits/stdc++.h> #define fi first #define se second #define mp make_pair #define pb push_back #define REP(x,y) for(x=0;x<(int)y;x++) #define REPI(x,y) for(x=1;x<=(int)y;x++) #define pii pair<int,int> #define ll long long #define ALL(x) (x).begin(),(x).end() #define len(x) (int)(x).size() using namespace std; int i, N, M, K, k; string S; int main(){ int a, b, c, d; int T; cin >> T; while(T--){ scanf("%d", &N); cin >> S; for(a=0;a<N;a++){ if(S[a] == '>') break; } c = a; for(a=N-1;a>=0;a--){ if(S[a] == '<') break; } d = a; printf("%d\n", min(c, N-d-1)); } return 0; }
31932c190dc08433c538bcb4c78b3c60bab39ac6
7aff96862d76799862f0cfdf27e6679b565874a7
/Graphics/GraphicsEngine/interface/GraphicsTypes.h
d402fb187453111aaa105a43e74bab3d3933b7af
[ "Apache-2.0" ]
permissive
MonkeyFirst/DiligentCore
4f207a19869904f74ab966813970dd9e34e93458
9123bf5473976f6be87313b11676b337071ece10
refs/heads/master
2020-04-25T04:15:21.468714
2019-02-25T00:53:55
2019-02-25T00:53:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
96,238
h
/* Copyright 2015-2019 Egor Yusov * * 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 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 OF ANY PROPRIETARY RIGHTS. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #pragma once /// \file /// Contains basic graphics engine type defintions #include "../../../Primitives/interface/BasicTypes.h" #include "../../../Primitives/interface/DebugOutput.h" #include "../../../Primitives/interface/FlagEnum.h" /// Graphics engine namespace namespace Diligent { class ITexture; class IBuffer; /// Value type /// This enumeration describes value type. It is used by /// - BufferDesc structure to describe value type of a formatted buffer /// - DrawAttribs structure to describe index type for an indexed draw call enum VALUE_TYPE : Uint8 { VT_UNDEFINED = 0, ///< Undefined type VT_INT8, ///< Signed 8-bit integer VT_INT16, ///< Signed 16-bit integer VT_INT32, ///< Signed 32-bit integer VT_UINT8, ///< Unsigned 8-bit integer VT_UINT16, ///< Unsigned 16-bit integer VT_UINT32, ///< Unsigned 32-bit integer VT_FLOAT16, ///< Half-precision 16-bit floating point VT_FLOAT32, ///< Full-precision 32-bit floating point VT_NUM_TYPES ///< Helper value storing total number of types in the enumeration }; /// Resource binding flags /// [D3D11_BIND_FLAG]: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476085(v=vs.85).aspx /// /// This enumeration describes which parts of the pipeline a resource can be bound to. /// It generally mirrors [D3D11_BIND_FLAG][] enumeration. It is used by /// - BufferDesc to describe bind flags for a buffer /// - TextureDesc to describe bind flags for a texture enum BIND_FLAGS : Uint32 { BIND_NONE = 0x0L, ///< Undefined binding BIND_VERTEX_BUFFER = 0x1L, ///< A buffer can be bound as a vertex buffer BIND_INDEX_BUFFER = 0x2L, ///< A buffer can be bound as an index buffer BIND_UNIFORM_BUFFER = 0x4L, ///< A buffer can be bound as a uniform buffer /// \warning This flag may not be combined with any other bind flag BIND_SHADER_RESOURCE = 0x8L, ///< A buffer or a texture can be bound as a shader resource /// \warning This flag cannot be used with MAP_WRITE_NO_OVERWRITE flag BIND_STREAM_OUTPUT = 0x10L,///< A buffer can be bound as a target for stream output stage BIND_RENDER_TARGET = 0x20L,///< A texture can be bound as a render target BIND_DEPTH_STENCIL = 0x40L,///< A texture can be bound as a depth-stencil target BIND_UNORDERED_ACCESS = 0x80L,///< A buffer or a texture can be bound as an unordered access view BIND_INDIRECT_DRAW_ARGS = 0x100L///< A buffer can be bound as the source buffer for indirect draw commands }; DEFINE_FLAG_ENUM_OPERATORS(BIND_FLAGS) /// Resource usage /// [D3D11_USAGE]: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476259(v=vs.85).aspx /// This enumeration describes expected resource usage. It generally mirrors [D3D11_USAGE] enumeration. /// The enumeration is used by /// - BufferDesc to describe usage for a buffer /// - TextureDesc to describe usage for a texture enum USAGE : Uint8 { /// A resource that can only be read by the GPU. It cannot be written by the GPU, /// and cannot be accessed at all by the CPU. This type of resource must be initialized /// when it is created, since it cannot be changed after creation. \n /// D3D11 Counterpart: D3D11_USAGE_IMMUTABLE. OpenGL counterpart: GL_STATIC_DRAW USAGE_STATIC = 0, /// A resource that requires read and write access by the GPU and can also be occasionally /// written by the CPU. \n /// D3D11 Counterpart: D3D11_USAGE_DEFAULT. OpenGL counterpart: GL_DYNAMIC_DRAW USAGE_DEFAULT, /// A resource that can be read by the GPU and written at least once per frame by the CPU. \n /// D3D11 Counterpart: D3D11_USAGE_DYNAMIC. OpenGL counterpart: GL_STREAM_DRAW USAGE_DYNAMIC, /// A resource that facilitates transferring data from GPU to CPU. \n /// D3D11 Counterpart: D3D11_USAGE_STAGING. OpenGL counterpart: GL_DYNAMIC_READ USAGE_CPU_ACCESSIBLE }; /// Allowed CPU access mode flags when mapping a resource /// The enumeration is used by /// - BufferDesc to describe CPU access mode for a buffer /// - TextureDesc to describe CPU access mode for a texture /// \note Only USAGE_DYNAMIC resources can be mapped enum CPU_ACCESS_FLAGS : Uint8 { CPU_ACCESS_NONE = 0x00, ///< No CPU access CPU_ACCESS_READ = 0x01, ///< A resource can be mapped for reading CPU_ACCESS_WRITE = 0x02 ///< A resource can be mapped for writing }; DEFINE_FLAG_ENUM_OPERATORS(CPU_ACCESS_FLAGS) /// Resource mapping type /// [D3D11_MAP]: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476181(v=vs.85).aspx /// Describes how a mapped resource will be accessed. This enumeration generally /// mirrors [D3D11_MAP][] enumeration. It is used by /// - IBuffer::Map to describe buffer mapping type /// - ITexture::Map to describe texture mapping type enum MAP_TYPE : Uint8 { /// The resource is mapped for reading. \n /// D3D11 counterpart: D3D11_MAP_READ. OpenGL counterpart: GL_MAP_READ_BIT MAP_READ = 0x01, /// The resource is mapped for writing. \n /// D3D11 counterpart: D3D11_MAP_WRITE. OpenGL counterpart: GL_MAP_WRITE_BIT MAP_WRITE = 0x02, /// The resource is mapped for reading and writing. \n /// D3D11 counterpart: D3D11_MAP_READ_WRITE. OpenGL counterpart: GL_MAP_WRITE_BIT | GL_MAP_READ_BIT MAP_READ_WRITE = 0x03 }; /// Special map flags /// Describes special arguments for a map operation. /// This enumeration is used by /// - IBuffer::Map to describe buffer mapping flags /// - ITexture::Map to describe texture mapping flags enum MAP_FLAGS : Uint8 { MAP_FLAG_NONE = 0x000, /// Specifies that map operation should not wait until previous command that /// using the same resource completes. Map returns null pointer if the resource /// is still in use.\n /// D3D11 counterpart: D3D11_MAP_FLAG_DO_NOT_WAIT /// \note: OpenGL does not have corresponding flag, so a buffer will always be mapped MAP_FLAG_DO_NOT_WAIT = 0x001, /// Previous contents of the resource will be undefined. This flag is only compatible with MAP_WRITE\n /// D3D11 counterpart: D3D11_MAP_WRITE_DISCARD. OpenGL counterpart: GL_MAP_INVALIDATE_BUFFER_BIT /// \note OpenGL implementation may orphan a buffer instead MAP_FLAG_DISCARD = 0x002, /// The system will not synchronize pending operations before mapping the buffer. It is responsibility /// of the application to make sure that the buffer contents is not overwritten while it is in use by /// the GPU.\n /// D3D11 counterpart: D3D11_MAP_WRITE_NO_OVERWRITE. OpenGL counterpart: GL_MAP_UNSYNCHRONIZED_BIT MAP_FLAG_DO_NOT_SYNCHRONIZE = 0x004 }; DEFINE_FLAG_ENUM_OPERATORS(MAP_FLAGS) /// Describes resource dimension /// This enumeration is used by /// - TextureDesc to describe texture type /// - TextureViewDesc to describe texture view type enum RESOURCE_DIMENSION : Uint8 { RESOURCE_DIM_UNDEFINED = 0, ///< Texture type undefined RESOURCE_DIM_BUFFER, ///< Buffer RESOURCE_DIM_TEX_1D, ///< One-dimensional texture RESOURCE_DIM_TEX_1D_ARRAY, ///< One-dimensional texture array RESOURCE_DIM_TEX_2D, ///< Two-dimensional texture RESOURCE_DIM_TEX_2D_ARRAY, ///< Two-dimensional texture array RESOURCE_DIM_TEX_3D, ///< Three-dimensional texture RESOURCE_DIM_TEX_CUBE, ///< Cube-map texture RESOURCE_DIM_TEX_CUBE_ARRAY, ///< Cube-map array texture RESOURCE_DIM_NUM_DIMENSIONS ///< Helper value that stores the total number of texture types in the enumeration }; /// Texture view type /// This enumeration describes allowed view types for a texture view. It is used by TextureViewDesc /// structure. enum TEXTURE_VIEW_TYPE : Uint8 { /// Undefined view type TEXTURE_VIEW_UNDEFINED = 0, /// A texture view will define a shader resource view that will be used /// as the source for the shader read operations TEXTURE_VIEW_SHADER_RESOURCE, /// A texture view will define a render target view that will be used /// as the target for rendering operations TEXTURE_VIEW_RENDER_TARGET, /// A texture view will define a depth stencil view that will be used /// as the target for rendering operations TEXTURE_VIEW_DEPTH_STENCIL, /// A texture view will define an unordered access view that will be used /// for unordered read/write operations from the shaders TEXTURE_VIEW_UNORDERED_ACCESS, /// Helper value that stores that total number of texture views TEXTURE_VIEW_NUM_VIEWS }; /// Buffer view type /// This enumeration describes allowed view types for a buffer view. It is used by BufferViewDesc /// structure. enum BUFFER_VIEW_TYPE : Uint8 { /// Undefined view type BUFFER_VIEW_UNDEFINED = 0, /// A buffer view will define a shader resource view that will be used /// as the source for the shader read operations BUFFER_VIEW_SHADER_RESOURCE, /// A buffer view will define an unordered access view that will be used /// for unordered read/write operations from the shaders BUFFER_VIEW_UNORDERED_ACCESS, /// Helper value that stores that total number of buffer views BUFFER_VIEW_NUM_VIEWS }; /// Texture formats /// This enumeration describes available texture formats and generally mirrors DXGI_FORMAT enumeration. /// The table below provides detailed information on each format. Most of the formats are widely supported /// by all modern APIs (DX10+, OpenGL3.3+ and OpenGLES3.0+). Specific requirements are additionally indicated. /// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb173059(v=vs.85).aspx">DXGI_FORMAT enumeration on MSDN</a>, /// <a href = "https://www.opengl.org/wiki/Image_Format">OpenGL Texture Formats</a> /// enum TEXTURE_FORMAT : Uint16 { /// Unknown format TEX_FORMAT_UNKNOWN = 0, /// Four-component 128-bit typeless format with 32-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R32G32B32A32_TYPELESS. OpenGL does not have direct counterpart, GL_RGBA32F is used. TEX_FORMAT_RGBA32_TYPELESS, /// Four-component 128-bit floating-point format with 32-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R32G32B32A32_FLOAT. OpenGL counterpart: GL_RGBA32F. TEX_FORMAT_RGBA32_FLOAT, /// Four-component 128-bit unsigned-integer format with 32-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R32G32B32A32_UINT. OpenGL counterpart: GL_RGBA32UI. TEX_FORMAT_RGBA32_UINT, /// Four-component 128-bit signed-integer format with 32-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R32G32B32A32_SINT. OpenGL counterpart: GL_RGBA32I. TEX_FORMAT_RGBA32_SINT, /// Three-component 96-bit typeless format with 32-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R32G32B32_TYPELESS. OpenGL does not have direct counterpart, GL_RGB32F is used. /// \warning This format has weak hardware support and is not recommended TEX_FORMAT_RGB32_TYPELESS, /// Three-component 96-bit floating-point format with 32-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R32G32B32_FLOAT. OpenGL counterpart: GL_RGB32F. /// \warning This format has weak hardware support and is not recommended TEX_FORMAT_RGB32_FLOAT, /// Three-component 96-bit unsigned-integer format with 32-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R32G32B32_UINT. OpenGL counterpart: GL_RGB32UI. /// \warning This format has weak hardware support and is not recommended TEX_FORMAT_RGB32_UINT, /// Three-component 96-bit signed-integer format with 32-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R32G32B32_SINT. OpenGL counterpart: GL_RGB32I. /// \warning This format has weak hardware support and is not recommended TEX_FORMAT_RGB32_SINT, /// Four-component 64-bit typeless format with 16-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R16G16B16A16_TYPELESS. OpenGL does not have direct counterpart, GL_RGBA16F is used. TEX_FORMAT_RGBA16_TYPELESS, /// Four-component 64-bit half-precision floating-point format with 16-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R16G16B16A16_FLOAT. OpenGL counterpart: GL_RGBA16F. TEX_FORMAT_RGBA16_FLOAT, /// Four-component 64-bit unsigned-normalized-integer format with 16-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R16G16B16A16_UNORM. OpenGL counterpart: GL_RGBA16. \n /// [GL_EXT_texture_norm16]: https://www.khronos.org/registry/gles/extensions/EXT/EXT_texture_norm16.txt /// OpenGLES: [GL_EXT_texture_norm16][] extension is required TEX_FORMAT_RGBA16_UNORM, /// Four-component 64-bit unsigned-integer format with 16-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R16G16B16A16_UINT. OpenGL counterpart: GL_RGBA16UI. TEX_FORMAT_RGBA16_UINT, /// [GL_EXT_texture_norm16]: https://www.khronos.org/registry/gles/extensions/EXT/EXT_texture_norm16.txt /// Four-component 64-bit signed-normalized-integer format with 16-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R16G16B16A16_SNORM. OpenGL counterpart: GL_RGBA16_SNORM. \n /// [GL_EXT_texture_norm16]: https://www.khronos.org/registry/gles/extensions/EXT/EXT_texture_norm16.txt /// OpenGLES: [GL_EXT_texture_norm16][] extension is required TEX_FORMAT_RGBA16_SNORM, /// Four-component 64-bit signed-integer format with 16-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R16G16B16A16_SINT. OpenGL counterpart: GL_RGBA16I. TEX_FORMAT_RGBA16_SINT, /// Two-component 64-bit typeless format with 32-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R32G32_TYPELESS. OpenGL does not have direct counterpart, GL_RG32F is used. TEX_FORMAT_RG32_TYPELESS, /// Two-component 64-bit floating-point format with 32-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R32G32_FLOAT. OpenGL counterpart: GL_RG32F. TEX_FORMAT_RG32_FLOAT, /// Two-component 64-bit unsigned-integer format with 32-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R32G32_UINT. OpenGL counterpart: GL_RG32UI. TEX_FORMAT_RG32_UINT, /// Two-component 64-bit signed-integer format with 32-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R32G32_SINT. OpenGL counterpart: GL_RG32I. TEX_FORMAT_RG32_SINT, /// Two-component 64-bit typeless format with 32-bits for R channel and 8 bits for G channel. \n /// D3D counterpart: DXGI_FORMAT_R32G8X24_TYPELESS. OpenGL does not have direct counterpart, GL_DEPTH32F_STENCIL8 is used. TEX_FORMAT_R32G8X24_TYPELESS, /// Two-component 64-bit format with 32-bit floating-point depth channel and 8-bit stencil channel. \n /// D3D counterpart: DXGI_FORMAT_D32_FLOAT_S8X24_UINT. OpenGL counterpart: GL_DEPTH32F_STENCIL8. TEX_FORMAT_D32_FLOAT_S8X24_UINT, /// Two-component 64-bit format with 32-bit floating-point R channel and 8+24-bits of typeless data. \n /// D3D counterpart: DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS. OpenGL does not have direct counterpart, GL_DEPTH32F_STENCIL8 is used. TEX_FORMAT_R32_FLOAT_X8X24_TYPELESS, /// Two-component 64-bit format with 32-bit typeless data and 8-bit G channel. \n /// D3D counterpart: DXGI_FORMAT_X32_TYPELESS_G8X24_UINT /// \warning This format is currently not implemented in OpenGL version TEX_FORMAT_X32_TYPELESS_G8X24_UINT, /// Four-component 32-bit typeless format with 10 bits for RGB and 2 bits for alpha channel. \n /// D3D counterpart: DXGI_FORMAT_R10G10B10A2_TYPELESS. OpenGL does not have direct counterpart, GL_RGB10_A2 is used. TEX_FORMAT_RGB10A2_TYPELESS, /// Four-component 32-bit unsigned-normalized-integer format with 10 bits for each color and 2 bits for alpha channel. \n /// D3D counterpart: DXGI_FORMAT_R10G10B10A2_UNORM. OpenGL counterpart: GL_RGB10_A2. TEX_FORMAT_RGB10A2_UNORM, /// Four-component 32-bit unsigned-integer format with 10 bits for each color and 2 bits for alpha channel. \n /// D3D counterpart: DXGI_FORMAT_R10G10B10A2_UINT. OpenGL counterpart: GL_RGB10_A2UI. TEX_FORMAT_RGB10A2_UINT, /// Three-component 32-bit format encoding three partial precision channels using 11 bits for red and green and 10 bits for blue channel. \n /// D3D counterpart: DXGI_FORMAT_R11G11B10_FLOAT. OpenGL counterpart: GL_R11F_G11F_B10F. TEX_FORMAT_R11G11B10_FLOAT, /// Four-component 32-bit typeless format with 8-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R8G8B8A8_TYPELESS. OpenGL does not have direct counterpart, GL_RGBA8 is used. TEX_FORMAT_RGBA8_TYPELESS, /// Four-component 32-bit unsigned-normalized-integer format with 8-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R8G8B8A8_UNORM. OpenGL counterpart: GL_RGBA8. TEX_FORMAT_RGBA8_UNORM, /// Four-component 32-bit unsigned-normalized-integer sRGB format with 8-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R8G8B8A8_UNORM_SRGB. OpenGL counterpart: GL_SRGB8_ALPHA8. TEX_FORMAT_RGBA8_UNORM_SRGB, /// Four-component 32-bit unsigned-integer format with 8-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R8G8B8A8_UINT. OpenGL counterpart: GL_RGBA8UI. TEX_FORMAT_RGBA8_UINT, /// Four-component 32-bit signed-normalized-integer format with 8-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R8G8B8A8_SNORM. OpenGL counterpart: GL_RGBA8_SNORM. TEX_FORMAT_RGBA8_SNORM, /// Four-component 32-bit signed-integer format with 8-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R8G8B8A8_SINT. OpenGL counterpart: GL_RGBA8I. TEX_FORMAT_RGBA8_SINT, /// Two-component 32-bit typeless format with 16-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R16G16_TYPELESS. OpenGL does not have direct counterpart, GL_RG16F is used. TEX_FORMAT_RG16_TYPELESS, /// Two-component 32-bit half-precision floating-point format with 16-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R16G16_FLOAT. OpenGL counterpart: GL_RG16F. TEX_FORMAT_RG16_FLOAT, /// Two-component 32-bit unsigned-normalized-integer format with 16-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R16G16_UNORM. OpenGL counterpart: GL_RG16. \n /// [GL_EXT_texture_norm16]: https://www.khronos.org/registry/gles/extensions/EXT/EXT_texture_norm16.txt /// OpenGLES: [GL_EXT_texture_norm16][] extension is required TEX_FORMAT_RG16_UNORM, /// Two-component 32-bit unsigned-integer format with 16-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R16G16_UINT. OpenGL counterpart: GL_RG16UI. TEX_FORMAT_RG16_UINT, /// Two-component 32-bit signed-normalized-integer format with 16-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R16G16_SNORM. OpenGL counterpart: GL_RG16_SNORM. \n /// [GL_EXT_texture_norm16]: https://www.khronos.org/registry/gles/extensions/EXT/EXT_texture_norm16.txt /// OpenGLES: [GL_EXT_texture_norm16][] extension is required TEX_FORMAT_RG16_SNORM, /// Two-component 32-bit signed-integer format with 16-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R16G16_SINT. OpenGL counterpart: GL_RG16I. TEX_FORMAT_RG16_SINT, /// Single-component 32-bit typeless format. \n /// D3D counterpart: DXGI_FORMAT_R32_TYPELESS. OpenGL does not have direct counterpart, GL_R32F is used. TEX_FORMAT_R32_TYPELESS, /// Single-component 32-bit floating-point depth format. \n /// D3D counterpart: DXGI_FORMAT_D32_FLOAT. OpenGL counterpart: GL_DEPTH_COMPONENT32F. TEX_FORMAT_D32_FLOAT, /// Single-component 32-bit floating-point format. \n /// D3D counterpart: DXGI_FORMAT_R32_FLOAT. OpenGL counterpart: GL_R32F. TEX_FORMAT_R32_FLOAT, /// Single-component 32-bit unsigned-integer format. \n /// D3D counterpart: DXGI_FORMAT_R32_UINT. OpenGL counterpart: GL_R32UI. TEX_FORMAT_R32_UINT, /// Single-component 32-bit signed-integer format. \n /// D3D counterpart: DXGI_FORMAT_R32_SINT. OpenGL counterpart: GL_R32I. TEX_FORMAT_R32_SINT, /// Two-component 32-bit typeless format with 24 bits for R and 8 bits for G channel. \n /// D3D counterpart: DXGI_FORMAT_R24G8_TYPELESS. OpenGL does not have direct counterpart, GL_DEPTH24_STENCIL8 is used. TEX_FORMAT_R24G8_TYPELESS, /// Two-component 32-bit format with 24 bits for unsigned-normalized-integer depth and 8 bits for stencil. \n /// D3D counterpart: DXGI_FORMAT_D24_UNORM_S8_UINT. OpenGL counterpart: GL_DEPTH24_STENCIL8. TEX_FORMAT_D24_UNORM_S8_UINT, /// Two-component 32-bit format with 24 bits for unsigned-normalized-integer data and 8 bits of unreferenced data. \n /// D3D counterpart: DXGI_FORMAT_R24_UNORM_X8_TYPELESS. OpenGL does not have direct counterpart, GL_DEPTH24_STENCIL8 is used. TEX_FORMAT_R24_UNORM_X8_TYPELESS, /// Two-component 32-bit format with 24 bits of unreferenced data and 8 bits of unsigned-integer data. \n /// D3D counterpart: DXGI_FORMAT_X24_TYPELESS_G8_UINT /// \warning This format is currently not implemented in OpenGL version TEX_FORMAT_X24_TYPELESS_G8_UINT, /// Two-component 16-bit typeless format with 8-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R8G8_TYPELESS. OpenGL does not have direct counterpart, GL_RG8 is used. TEX_FORMAT_RG8_TYPELESS, /// Two-component 16-bit unsigned-normalized-integer format with 8-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R8G8_UNORM. OpenGL counterpart: GL_RG8. TEX_FORMAT_RG8_UNORM, /// Two-component 16-bit unsigned-integer format with 8-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R8G8_UINT. OpenGL counterpart: GL_RG8UI. TEX_FORMAT_RG8_UINT, /// Two-component 16-bit signed-normalized-integer format with 8-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R8G8_SNORM. OpenGL counterpart: GL_RG8_SNORM. TEX_FORMAT_RG8_SNORM, /// Two-component 16-bit signed-integer format with 8-bit channels. \n /// D3D counterpart: DXGI_FORMAT_R8G8_SINT. OpenGL counterpart: GL_RG8I. TEX_FORMAT_RG8_SINT, /// Single-component 16-bit typeless format. \n /// D3D counterpart: DXGI_FORMAT_R16_TYPELESS. OpenGL does not have direct counterpart, GL_R16F is used. TEX_FORMAT_R16_TYPELESS, /// Single-component 16-bit half-precisoin floating-point format. \n /// D3D counterpart: DXGI_FORMAT_R16_FLOAT. OpenGL counterpart: GL_R16F. TEX_FORMAT_R16_FLOAT, /// Single-component 16-bit unsigned-normalized-integer depth format. \n /// D3D counterpart: DXGI_FORMAT_D16_UNORM. OpenGL counterpart: GL_DEPTH_COMPONENT16. TEX_FORMAT_D16_UNORM, /// Single-component 16-bit unsigned-normalized-integer format. \n /// D3D counterpart: DXGI_FORMAT_R16_UNORM. OpenGL counterpart: GL_R16. /// [GL_EXT_texture_norm16]: https://www.khronos.org/registry/gles/extensions/EXT/EXT_texture_norm16.txt /// OpenGLES: [GL_EXT_texture_norm16][] extension is required TEX_FORMAT_R16_UNORM, /// Single-component 16-bit unsigned-integer format. \n /// D3D counterpart: DXGI_FORMAT_R16_UINT. OpenGL counterpart: GL_R16UI. TEX_FORMAT_R16_UINT, /// Single-component 16-bit signed-normalized-integer format. \n /// D3D counterpart: DXGI_FORMAT_R16_SNORM. OpenGL counterpart: GL_R16_SNORM. \n /// [GL_EXT_texture_norm16]: https://www.khronos.org/registry/gles/extensions/EXT/EXT_texture_norm16.txt /// OpenGLES: [GL_EXT_texture_norm16][] extension is required TEX_FORMAT_R16_SNORM, /// Single-component 16-bit signed-integer format. \n /// D3D counterpart: DXGI_FORMAT_R16_SINT. OpenGL counterpart: GL_R16I. TEX_FORMAT_R16_SINT, /// Single-component 8-bit typeless format. \n /// D3D counterpart: DXGI_FORMAT_R8_TYPELESS. OpenGL does not have direct counterpart, GL_R8 is used. TEX_FORMAT_R8_TYPELESS, /// Single-component 8-bit unsigned-normalized-integer format. \n /// D3D counterpart: DXGI_FORMAT_R8_UNORM. OpenGL counterpart: GL_R8. TEX_FORMAT_R8_UNORM, /// Single-component 8-bit unsigned-integer format. \n /// D3D counterpart: DXGI_FORMAT_R8_UINT. OpenGL counterpart: GL_R8UI. TEX_FORMAT_R8_UINT, /// Single-component 8-bit signed-normalized-integer format. \n /// D3D counterpart: DXGI_FORMAT_R8_SNORM. OpenGL counterpart: GL_R8_SNORM. TEX_FORMAT_R8_SNORM, /// Single-component 8-bit signed-integer format. \n /// D3D counterpart: DXGI_FORMAT_R8_SINT. OpenGL counterpart: GL_R8I. TEX_FORMAT_R8_SINT, /// Single-component 8-bit unsigned-normalized-integer format for alpha only. \n /// D3D counterpart: DXGI_FORMAT_A8_UNORM /// \warning This format is not availanle in OpenGL TEX_FORMAT_A8_UNORM, /// Single-component 1-bit format. \n /// D3D counterpart: DXGI_FORMAT_R1_UNORM /// \warning This format is not availanle in OpenGL TEX_FORMAT_R1_UNORM, /// Three partial-precision floating pointer numbers sharing single exponent encoded into a 32-bit value. \n /// D3D counterpart: DXGI_FORMAT_R9G9B9E5_SHAREDEXP. OpenGL counterpart: GL_RGB9_E5. TEX_FORMAT_RGB9E5_SHAREDEXP, /// Four-component unsigned-normalized integer format analogous to UYVY encoding. \n /// D3D counterpart: DXGI_FORMAT_R8G8_B8G8_UNORM /// \warning This format is not availanle in OpenGL TEX_FORMAT_RG8_B8G8_UNORM, /// Four-component unsigned-normalized integer format analogous to YUY2 encoding. \n /// D3D counterpart: DXGI_FORMAT_G8R8_G8B8_UNORM /// \warning This format is not availanle in OpenGL TEX_FORMAT_G8R8_G8B8_UNORM, /// Four-component typeless block-compression format with 1:8 compression ratio.\n /// D3D counterpart: DXGI_FORMAT_BC1_TYPELESS. OpenGL does not have direct counterpart, GL_COMPRESSED_RGB_S3TC_DXT1_EXT is used. \n /// [GL_EXT_texture_compression_s3tc]: https://www.khronos.org/registry/gles/extensions/EXT/texture_compression_s3tc.txt /// OpenGL & OpenGLES: [GL_EXT_texture_compression_s3tc][] extension is required /// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC1">BC1 on MSDN </a>, /// <a href = "https://www.opengl.org/wiki/S3_Texture_Compression#DXT1_Format">DXT1 on OpenGL.org </a> TEX_FORMAT_BC1_TYPELESS, /// Four-component unsigned-normalized-integer block-compression format with 5 bits for R, 6 bits for G, 5 bits for B, and 0 or 1 bit for A channel. /// The pixel data is encoded using 8 bytes per 4x4 block (4 bits per pixel) providing 1:8 compression ratio against RGBA8 format. \n /// D3D counterpart: DXGI_FORMAT_BC1_UNORM. OpenGL counterpart: GL_COMPRESSED_RGB_S3TC_DXT1_EXT.\n /// [GL_EXT_texture_compression_s3tc]: https://www.khronos.org/registry/gles/extensions/EXT/texture_compression_s3tc.txt /// OpenGL & OpenGLES: [GL_EXT_texture_compression_s3tc][] extension is required /// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC1">BC1 on MSDN </a>, /// <a href = "https://www.opengl.org/wiki/S3_Texture_Compression#DXT1_Format">DXT1 on OpenGL.org </a> TEX_FORMAT_BC1_UNORM, /// Four-component unsigned-normalized-integer block-compression sRGB format with 5 bits for R, 6 bits for G, 5 bits for B, and 0 or 1 bit for A channel. \n /// The pixel data is encoded using 8 bytes per 4x4 block (4 bits per pixel) providing 1:8 compression ratio against RGBA8 format. \n /// D3D counterpart: DXGI_FORMAT_BC1_UNORM_SRGB. OpenGL counterpart: GL_COMPRESSED_SRGB_S3TC_DXT1_EXT.\n /// [GL_EXT_texture_compression_s3tc]: https://www.khronos.org/registry/gles/extensions/EXT/texture_compression_s3tc.txt /// OpenGL & OpenGLES: [GL_EXT_texture_compression_s3tc][] extension is required /// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC1">BC1 on MSDN </a>, /// <a href = "https://www.opengl.org/wiki/S3_Texture_Compression#DXT1_Format">DXT1 on OpenGL.org </a> TEX_FORMAT_BC1_UNORM_SRGB, /// Four component typeless block-compression format with 1:4 compression ratio.\n /// D3D counterpart: DXGI_FORMAT_BC2_TYPELESS. OpenGL does not have direct counterpart, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT is used. \n /// [GL_EXT_texture_compression_s3tc]: https://www.khronos.org/registry/gles/extensions/EXT/texture_compression_s3tc.txt /// OpenGL & OpenGLES: [GL_EXT_texture_compression_s3tc][] extension is required /// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC2">BC2 on MSDN </a>, /// <a href = "https://www.opengl.org/wiki/S3_Texture_Compression#DXT3_Format">DXT3 on OpenGL.org </a> TEX_FORMAT_BC2_TYPELESS, /// Four-component unsigned-normalized-integer block-compression format with 5 bits for R, 6 bits for G, 5 bits for B, and 4 bits for low-coherent separate A channel. /// The pixel data is encoded using 16 bytes per 4x4 block (8 bits per pixel) providing 1:4 compression ratio against RGBA8 format. \n /// D3D counterpart: DXGI_FORMAT_BC2_UNORM. OpenGL counterpart: GL_COMPRESSED_RGBA_S3TC_DXT3_EXT. \n /// [GL_EXT_texture_compression_s3tc]: https://www.khronos.org/registry/gles/extensions/EXT/texture_compression_s3tc.txt /// OpenGL & OpenGLES: [GL_EXT_texture_compression_s3tc][] extension is required /// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC2">BC2 on MSDN </a>, /// <a href = "https://www.opengl.org/wiki/S3_Texture_Compression#DXT3_Format">DXT3 on OpenGL.org </a> TEX_FORMAT_BC2_UNORM, /// Four-component signed-normalized-integer block-compression sRGB format with 5 bits for R, 6 bits for G, 5 bits for B, and 4 bits for low-coherent separate A channel. /// The pixel data is encoded using 16 bytes per 4x4 block (8 bits per pixel) providing 1:4 compression ratio against RGBA8 format. \n /// D3D counterpart: DXGI_FORMAT_BC2_UNORM_SRGB. OpenGL counterpart: GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT. \n /// [GL_EXT_texture_compression_s3tc]: https://www.khronos.org/registry/gles/extensions/EXT/texture_compression_s3tc.txt /// OpenGL & OpenGLES: [GL_EXT_texture_compression_s3tc][] extension is required /// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC2">BC2 on MSDN </a>, /// <a href = "https://www.opengl.org/wiki/S3_Texture_Compression#DXT3_Format">DXT3 on OpenGL.org </a> TEX_FORMAT_BC2_UNORM_SRGB, /// Four-component typeless block-compression format with 1:4 compression ratio.\n /// D3D counterpart: DXGI_FORMAT_BC3_TYPELESS. OpenGL does not have direct counterpart, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT is used. \n /// [GL_EXT_texture_compression_s3tc]: https://www.khronos.org/registry/gles/extensions/EXT/texture_compression_s3tc.txt /// OpenGL & OpenGLES: [GL_EXT_texture_compression_s3tc][] extension is required /// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC3">BC3 on MSDN </a>, /// <a href = "https://www.opengl.org/wiki/S3_Texture_Compression#DXT5_Format">DXT5 on OpenGL.org </a> TEX_FORMAT_BC3_TYPELESS, /// Four-component unsigned-normalized-integer block-compression format with 5 bits for R, 6 bits for G, 5 bits for B, and 8 bits for highly-coherent A channel. /// The pixel data is encoded using 16 bytes per 4x4 block (8 bits per pixel) providing 1:4 compression ratio against RGBA8 format. \n /// D3D counterpart: DXGI_FORMAT_BC3_UNORM. OpenGL counterpart: GL_COMPRESSED_RGBA_S3TC_DXT5_EXT. \n /// [GL_EXT_texture_compression_s3tc]: https://www.khronos.org/registry/gles/extensions/EXT/texture_compression_s3tc.txt /// OpenGL & OpenGLES: [GL_EXT_texture_compression_s3tc][] extension is required /// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC3">BC3 on MSDN </a>, /// <a href = "https://www.opengl.org/wiki/S3_Texture_Compression#DXT5_Format">DXT5 on OpenGL.org </a> TEX_FORMAT_BC3_UNORM, /// Four-component unsigned-normalized-integer block-compression sRGB format with 5 bits for R, 6 bits for G, 5 bits for B, and 8 bits for highly-coherent A channel. /// The pixel data is encoded using 16 bytes per 4x4 block (8 bits per pixel) providing 1:4 compression ratio against RGBA8 format. \n /// D3D counterpart: DXGI_FORMAT_BC3_UNORM_SRGB. OpenGL counterpart: GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT. \n /// [GL_EXT_texture_compression_s3tc]: https://www.khronos.org/registry/gles/extensions/EXT/texture_compression_s3tc.txt /// OpenGL & OpenGLES: [GL_EXT_texture_compression_s3tc][] extension is required /// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC3">BC3 on MSDN </a>, /// <a href = "https://www.opengl.org/wiki/S3_Texture_Compression#DXT5_Format">DXT5 on OpenGL.org </a> TEX_FORMAT_BC3_UNORM_SRGB, /// One-component typeless block-compression format with 1:2 compression ratio. \n /// D3D counterpart: DXGI_FORMAT_BC4_TYPELESS. OpenGL does not have direct counterpart, GL_COMPRESSED_RED_RGTC1 is used. \n /// [GL_ARB_texture_compression_rgtc]: https://www.opengl.org/registry/specs/ARB/texture_compression_rgtc.txt /// OpenGL & OpenGLES: [GL_ARB_texture_compression_rgtc][] extension is required /// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC4">BC4 on MSDN </a>, /// <a href = "https://www.opengl.org/wiki/Image_Format#Compressed_formats">Compressed formats on OpenGL.org </a> TEX_FORMAT_BC4_TYPELESS, /// One-component unsigned-normalized-integer block-compression format with 8 bits for R channel. /// The pixel data is encoded using 8 bytes per 4x4 block (4 bits per pixel) providing 1:2 compression ratio against R8 format. \n /// D3D counterpart: DXGI_FORMAT_BC4_UNORM. OpenGL counterpart: GL_COMPRESSED_RED_RGTC1. \n /// [GL_ARB_texture_compression_rgtc]: https://www.opengl.org/registry/specs/ARB/texture_compression_rgtc.txt /// OpenGL & OpenGLES: [GL_ARB_texture_compression_rgtc][] extension is required /// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC4">BC4 on MSDN </a>, /// <a href = "https://www.opengl.org/wiki/Image_Format#Compressed_formats">Compressed formats on OpenGL.org </a> TEX_FORMAT_BC4_UNORM, /// One-component signed-normalized-integer block-compression format with 8 bits for R channel. /// The pixel data is encoded using 8 bytes per 4x4 block (4 bits per pixel) providing 1:2 compression ratio against R8 format. \n /// D3D counterpart: DXGI_FORMAT_BC4_SNORM. OpenGL counterpart: GL_COMPRESSED_SIGNED_RED_RGTC1. \n /// [GL_ARB_texture_compression_rgtc]: https://www.opengl.org/registry/specs/ARB/texture_compression_rgtc.txt /// OpenGL & OpenGLES: [GL_ARB_texture_compression_rgtc][] extension is required /// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC4">BC4 on MSDN </a>, /// <a href = "https://www.opengl.org/wiki/Image_Format#Compressed_formats">Compressed formats on OpenGL.org </a> TEX_FORMAT_BC4_SNORM, /// Two-component typeless block-compression format with 1:2 compression ratio. \n /// D3D counterpart: DXGI_FORMAT_BC5_TYPELESS. OpenGL does not have direct counterpart, GL_COMPRESSED_RG_RGTC2 is used. \n /// [GL_ARB_texture_compression_rgtc]: https://www.opengl.org/registry/specs/ARB/texture_compression_rgtc.txt /// OpenGL & OpenGLES: [GL_ARB_texture_compression_rgtc][] extension is required /// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC5">BC5 on MSDN </a>, /// <a href = "https://www.opengl.org/wiki/Image_Format#Compressed_formats">Compressed formats on OpenGL.org </a> TEX_FORMAT_BC5_TYPELESS, /// Two-component unsigned-normalized-integer block-compression format with 8 bits for R and 8 bits for G channel. /// The pixel data is encoded using 16 bytes per 4x4 block (8 bits per pixel) providing 1:2 compression ratio against RG8 format. \n /// D3D counterpart: DXGI_FORMAT_BC5_UNORM. OpenGL counterpart: GL_COMPRESSED_RG_RGTC2. \n /// [GL_ARB_texture_compression_rgtc]: https://www.opengl.org/registry/specs/ARB/texture_compression_rgtc.txt /// OpenGL & OpenGLES: [GL_ARB_texture_compression_rgtc][] extension is required /// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC5">BC5 on MSDN </a>, /// <a href = "https://www.opengl.org/wiki/Image_Format#Compressed_formats">Compressed formats on OpenGL.org </a> TEX_FORMAT_BC5_UNORM, /// Two-component signed-normalized-integer block-compression format with 8 bits for R and 8 bits for G channel. /// The pixel data is encoded using 16 bytes per 4x4 block (8 bits per pixel) providing 1:2 compression ratio against RG8 format. \n /// D3D counterpart: DXGI_FORMAT_BC5_SNORM. OpenGL counterpart: GL_COMPRESSED_SIGNED_RG_RGTC2. \n /// [GL_ARB_texture_compression_rgtc]: https://www.opengl.org/registry/specs/ARB/texture_compression_rgtc.txt /// OpenGL & OpenGLES: [GL_ARB_texture_compression_rgtc][] extension is required /// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC5">BC5 on MSDN </a>, /// <a href = "https://www.opengl.org/wiki/Image_Format#Compressed_formats">Compressed formats on OpenGL.org </a> TEX_FORMAT_BC5_SNORM, /// Three-component 16-bit unsigned-normalized-integer format with 5 bits for blue, 6 bits for green, and 5 bits for red channel. \n /// D3D counterpart: DXGI_FORMAT_B5G6R5_UNORM /// \warning This format is not available until D3D11.1 and Windows 8. It is also not available in OpenGL TEX_FORMAT_B5G6R5_UNORM, /// Four-component 16-bit unsigned-normalized-integer format with 5 bits for each color channel and 1-bit alpha. \n /// D3D counterpart: DXGI_FORMAT_B5G5R5A1_UNORM /// \warning This format is not available until D3D11.1 and Windows 8. It is also not available in OpenGL TEX_FORMAT_B5G5R5A1_UNORM, /// Four-component 32-bit unsigned-normalized-integer format with 8 bits for each channel. \n /// D3D counterpart: DXGI_FORMAT_B8G8R8A8_UNORM. /// \warning This format is not available in OpenGL TEX_FORMAT_BGRA8_UNORM, /// Four-component 32-bit unsigned-normalized-integer format with 8 bits for each color channel and 8 bits unused. \n /// D3D counterpart: DXGI_FORMAT_B8G8R8X8_UNORM. /// \warning This format is not available in OpenGL TEX_FORMAT_BGRX8_UNORM, /// Four-component 32-bit 2.8-biased fixed-point format with 10 bits for each color channel and 2-bit alpha. \n /// D3D counterpart: DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM. /// \warning This format is not available in OpenGL TEX_FORMAT_R10G10B10_XR_BIAS_A2_UNORM, /// Four-component 32-bit typeless format with 8 bits for each channel. \n /// D3D counterpart: DXGI_FORMAT_B8G8R8A8_TYPELESS. /// \warning This format is not available in OpenGL TEX_FORMAT_BGRA8_TYPELESS, /// Four-component 32-bit unsigned-normalized sRGB format with 8 bits for each channel. \n /// D3D counterpart: DXGI_FORMAT_B8G8R8A8_UNORM_SRGB. /// \warning This format is not available in OpenGL. TEX_FORMAT_BGRA8_UNORM_SRGB, /// Four-component 32-bit typeless format that with 8 bits for each color channel, and 8 bits are unused. \n /// D3D counterpart: DXGI_FORMAT_B8G8R8X8_TYPELESS. /// \warning This format is not available in OpenGL. TEX_FORMAT_BGRX8_TYPELESS, /// Four-component 32-bit unsigned-normalized sRGB format with 8 bits for each color channel, and 8 bits are unused. \n /// D3D counterpart: DXGI_FORMAT_B8G8R8X8_UNORM_SRGB. /// \warning This format is not available in OpenGL. TEX_FORMAT_BGRX8_UNORM_SRGB, /// Three-component typeless block-compression format. \n /// D3D counterpart: DXGI_FORMAT_BC6H_TYPELESS. OpenGL does not have direct counterpart, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT is used. \n /// [GL_ARB_texture_compression_bptc]: https://cvs.khronos.org/svn/repos/ogl/trunk/doc/registry/public/specs/ARB/texture_compression_bptc.txt /// OpenGL: [GL_ARB_texture_compression_bptc][] extension is required. Not supported in at least OpenGLES3.1 /// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/hh308952(v=vs.85).aspx">BC6H on MSDN </a>, /// <a href = "https://www.opengl.org/wiki/BPTC_Texture_Compression">BPTC Texture Compression on OpenGL.org </a> TEX_FORMAT_BC6H_TYPELESS, /// Three-component unsigned half-precision floating-point format with 16 bits for each channel. \n /// D3D counterpart: DXGI_FORMAT_BC6H_UF16. OpenGL counterpart: GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT. \n /// [GL_ARB_texture_compression_bptc]: https://cvs.khronos.org/svn/repos/ogl/trunk/doc/registry/public/specs/ARB/texture_compression_bptc.txt /// OpenGL: [GL_ARB_texture_compression_bptc][] extension is required. Not supported in at least OpenGLES3.1 /// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/hh308952(v=vs.85).aspx">BC6H on MSDN </a>, /// <a href = "https://www.opengl.org/wiki/BPTC_Texture_Compression">BPTC Texture Compression on OpenGL.org </a> TEX_FORMAT_BC6H_UF16, /// Three-channel signed half-precision floating-point format with 16 bits per each channel. \n /// D3D counterpart: DXGI_FORMAT_BC6H_SF16. OpenGL counterpart: GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT. \n /// [GL_ARB_texture_compression_bptc]: https://cvs.khronos.org/svn/repos/ogl/trunk/doc/registry/public/specs/ARB/texture_compression_bptc.txt /// OpenGL: [GL_ARB_texture_compression_bptc][] extension is required. Not supported in at least OpenGLES3.1 /// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/hh308952(v=vs.85).aspx">BC6H on MSDN </a>, /// <a href = "https://www.opengl.org/wiki/BPTC_Texture_Compression">BPTC Texture Compression on OpenGL.org </a> TEX_FORMAT_BC6H_SF16, /// Three-component typeless block-compression format. \n /// D3D counterpart: DXGI_FORMAT_BC7_TYPELESS. OpenGL does not have direct counterpart, GL_COMPRESSED_RGBA_BPTC_UNORM is used. \n /// [GL_ARB_texture_compression_bptc]: https://cvs.khronos.org/svn/repos/ogl/trunk/doc/registry/public/specs/ARB/texture_compression_bptc.txt /// OpenGL: [GL_ARB_texture_compression_bptc][] extension is required. Not supported in at least OpenGLES3.1 /// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/hh308953(v=vs.85).aspx">BC7 on MSDN </a>, /// <a href = "https://www.opengl.org/wiki/BPTC_Texture_Compression">BPTC Texture Compression on OpenGL.org </a> TEX_FORMAT_BC7_TYPELESS, /// Three-component block-compression unsigned-normalized-integer format with 4 to 7 bits per color channel and 0 to 8 bits of alpha. \n /// D3D counterpart: DXGI_FORMAT_BC7_UNORM. OpenGL counterpart: GL_COMPRESSED_RGBA_BPTC_UNORM. \n /// [GL_ARB_texture_compression_bptc]: https://cvs.khronos.org/svn/repos/ogl/trunk/doc/registry/public/specs/ARB/texture_compression_bptc.txt /// OpenGL: [GL_ARB_texture_compression_bptc][] extension is required. Not supported in at least OpenGLES3.1 /// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/hh308953(v=vs.85).aspx">BC7 on MSDN </a>, /// <a href = "https://www.opengl.org/wiki/BPTC_Texture_Compression">BPTC Texture Compression on OpenGL.org </a> TEX_FORMAT_BC7_UNORM, /// Three-component block-compression unsigned-normalized-integer sRGB format with 4 to 7 bits per color channel and 0 to 8 bits of alpha. \n /// D3D counterpart: DXGI_FORMAT_BC7_UNORM_SRGB. OpenGL counterpart: GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM. \n /// [GL_ARB_texture_compression_bptc]: https://cvs.khronos.org/svn/repos/ogl/trunk/doc/registry/public/specs/ARB/texture_compression_bptc.txt /// OpenGL: [GL_ARB_texture_compression_bptc][] extension is required. Not supported in at least OpenGLES3.1 /// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/hh308953(v=vs.85).aspx">BC7 on MSDN </a>, /// <a href = "https://www.opengl.org/wiki/BPTC_Texture_Compression">BPTC Texture Compression on OpenGL.org </a> TEX_FORMAT_BC7_UNORM_SRGB, /// Helper member containing the total number of texture formats in the enumeration TEX_FORMAT_NUM_FORMATS }; /// Filter type /// This enumeration defines filter type. It is used by SamplerDesc structure to define min, mag and mip filters. /// \note On D3D11, comparison filters only work with textures that have the following formats: /// R32_FLOAT_X8X24_TYPELESS, R32_FLOAT, R24_UNORM_X8_TYPELESS, R16_UNORM. enum FILTER_TYPE : Uint8 { FILTER_TYPE_UNKNOWN = 0, ///< Unknown filter type FILTER_TYPE_POINT, ///< Point filtering FILTER_TYPE_LINEAR, ///< Linear filtering FILTER_TYPE_ANISOTROPIC, ///< Anisotropic filtering FILTER_TYPE_COMPARISON_POINT, ///< Comparison-point filtering FILTER_TYPE_COMPARISON_LINEAR, ///< Comparison-linear filtering FILTER_TYPE_COMPARISON_ANISOTROPIC, ///< Comparison-anisotropic filtering FILTER_TYPE_MINIMUM_POINT, ///< Minimum-point filtering (DX12 only) FILTER_TYPE_MINIMUM_LINEAR, ///< Minimum-linear filtering (DX12 only) FILTER_TYPE_MINIMUM_ANISOTROPIC, ///< Minimum-anisotropic filtering (DX12 only) FILTER_TYPE_MAXIMUM_POINT, ///< Maximum-point filtering (DX12 only) FILTER_TYPE_MAXIMUM_LINEAR, ///< Maximum-linear filtering (DX12 only) FILTER_TYPE_MAXIMUM_ANISOTROPIC, ///< Maximum-anisotropic filtering (DX12 only) FILTER_TYPE_NUM_FILTERS ///< Helper value that stores the total number of filter types in the enumeration }; /// Texture address mode /// [D3D11_TEXTURE_ADDRESS_MODE]: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476256(v=vs.85).aspx /// [D3D12_TEXTURE_ADDRESS_MODE]: https://msdn.microsoft.com/en-us/library/windows/desktop/dn770441(v=vs.85).aspx /// Defines a technique for resolving texture coordinates that are outside of /// the boundaries of a texture. The enumeration generally mirrors [D3D11_TEXTURE_ADDRESS_MODE][]/[D3D12_TEXTURE_ADDRESS_MODE][] enumeration. /// It is used by SamplerDesc structure to define the address mode for U,V and W texture coordinates. enum TEXTURE_ADDRESS_MODE : Uint8 { /// Unknown mode TEXTURE_ADDRESS_UNKNOWN = 0, /// Tile the texture at every integer junction. \n /// Direct3D Counterpart: D3D11_TEXTURE_ADDRESS_WRAP/D3D12_TEXTURE_ADDRESS_MODE_WRAP. OpenGL counterpart: GL_REPEAT TEXTURE_ADDRESS_WRAP = 1, /// Flip the texture at every integer junction. \n /// Direct3D Counterpart: D3D11_TEXTURE_ADDRESS_MIRROR/D3D12_TEXTURE_ADDRESS_MODE_MIRROR. OpenGL counterpart: GL_MIRRORED_REPEAT TEXTURE_ADDRESS_MIRROR = 2, /// Texture coordinates outside the range [0.0, 1.0] are set to the /// texture color at 0.0 or 1.0, respectively. \n /// Direct3D Counterpart: D3D11_TEXTURE_ADDRESS_CLAMP/D3D12_TEXTURE_ADDRESS_MODE_CLAMP. OpenGL counterpart: GL_CLAMP_TO_EDGE TEXTURE_ADDRESS_CLAMP = 3, /// Texture coordinates outside the range [0.0, 1.0] are set to the border color specified /// specified in SamplerDesc structure. \n /// Direct3D Counterpart: D3D11_TEXTURE_ADDRESS_BORDER/D3D12_TEXTURE_ADDRESS_MODE_BORDER. OpenGL counterpart: GL_CLAMP_TO_BORDER TEXTURE_ADDRESS_BORDER = 4, /// Similar to TEXTURE_ADDRESS_MIRROR and TEXTURE_ADDRESS_CLAMP. Takes the absolute /// value of the texture coordinate (thus, mirroring around 0), and then clamps to /// the maximum value. \n /// Direct3D Counterpart: D3D11_TEXTURE_ADDRESS_MIRROR_ONCE/D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE. OpenGL counterpart: GL_MIRROR_CLAMP_TO_EDGE /// \note GL_MIRROR_CLAMP_TO_EDGE is only available in OpenGL4.4+, and is not available until at least OpenGLES3.1 TEXTURE_ADDRESS_MIRROR_ONCE = 5, /// Helper value that stores the total number of texture address modes in the enumeration TEXTURE_ADDRESS_NUM_MODES }; /// Comparison function /// [D3D11_COMPARISON_FUNC]: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476101(v=vs.85).aspx /// [D3D12_COMPARISON_FUNC]: https://msdn.microsoft.com/en-us/library/windows/desktop/dn770349(v=vs.85).aspx /// This enumeartion defines a comparison function. It generally mirrors [D3D11_COMPARISON_FUNC]/[D3D12_COMPARISON_FUNC] enum and is used by /// - SamplerDesc to define a comparison function if one of the comparison mode filters is used /// - StencilOpDesc to define a stencil function /// - DepthStencilStateDesc to define a depth function enum COMPARISON_FUNCTION : Uint8 { /// Unknown comparison function COMPARISON_FUNC_UNKNOWN = 0, /// Comparison never passes. \n /// Direct3D counterpart: D3D11_COMPARISON_NEVER/D3D12_COMPARISON_FUNC_NEVER. OpenGL counterpart: GL_NEVER. COMPARISON_FUNC_NEVER, /// Comparison passes if the source data is less than the destination data.\n /// Direct3D counterpart: D3D11_COMPARISON_LESS/D3D12_COMPARISON_FUNC_LESS. OpenGL counterpart: GL_LESS. COMPARISON_FUNC_LESS, /// Comparison passes if the source data is equal to the destination data.\n /// Direct3D counterpart: D3D11_COMPARISON_EQUAL/D3D12_COMPARISON_FUNC_EQUAL. OpenGL counterpart: GL_EQUAL. COMPARISON_FUNC_EQUAL, /// Comparison passes if the source data is less than or equal to the destination data.\n /// Direct3D counterpart: D3D11_COMPARISON_LESS_EQUAL/D3D12_COMPARISON_FUNC_LESS_EQUAL. OpenGL counterpart: GL_LEQUAL. COMPARISON_FUNC_LESS_EQUAL, /// Comparison passes if the source data is greater than the destination data.\n /// Direct3D counterpart: 3D11_COMPARISON_GREATER/D3D12_COMPARISON_FUNC_GREATER. OpenGL counterpart: GL_GREATER. COMPARISON_FUNC_GREATER, /// Comparison passes if the source data is not equal to the destination data.\n /// Direct3D counterpart: D3D11_COMPARISON_NOT_EQUAL/D3D12_COMPARISON_FUNC_NOT_EQUAL. OpenGL counterpart: GL_NOTEQUAL. COMPARISON_FUNC_NOT_EQUAL, /// Comparison passes if the source data is greater than or equal to the destination data.\n /// Direct3D counterpart: D3D11_COMPARISON_GREATER_EQUAL/D3D12_COMPARISON_FUNC_GREATER_EQUAL. OpenGL counterpart: GL_GEQUAL. COMPARISON_FUNC_GREATER_EQUAL, /// Comparison always passes. \n /// Direct3D counterpart: D3D11_COMPARISON_ALWAYS/D3D12_COMPARISON_FUNC_ALWAYS. OpenGL counterpart: GL_ALWAYS. COMPARISON_FUNC_ALWAYS, /// Helper value that stores the total number of comparison functions in the enumeration COMPARISON_FUNC_NUM_FUNCTIONS }; /// Miscellaneous texture flags /// The enumeration is used by TextureDesc to describe misc texture flags enum MISC_TEXTURE_FLAGS : Uint8 { MISC_TEXTURE_FLAG_NONE = 0x00, /// Allow automatic mipmap generation with ITextureView::GenerateMips() /// \note A texture must be created with BIND_RENDER_TARGET bind flag MISC_TEXTURE_FLAG_GENERATE_MIPS = 0x01 }; DEFINE_FLAG_ENUM_OPERATORS(MISC_TEXTURE_FLAGS) /// Input primitive topology. /// This enumeration is used by DrawAttribs structure to define input primitive topology. enum PRIMITIVE_TOPOLOGY : Uint8 { /// Undefined topology PRIMITIVE_TOPOLOGY_UNDEFINED = 0, /// Interpret the vertex data as a list of triangles.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST. OpenGL counterpart: GL_TRIANGLES. PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, /// Interpret the vertex data as a triangle strip.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP. OpenGL counterpart: GL_TRIANGLE_STRIP. PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP, /// Interpret the vertex data as a list of points.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_POINTLIST. OpenGL counterpart: GL_POINTS. PRIMITIVE_TOPOLOGY_POINT_LIST, /// Interpret the vertex data as a list of lines.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_LINELIST. OpenGL counterpart: GL_LINES. PRIMITIVE_TOPOLOGY_LINE_LIST, /// Interpret the vertex data as a list of one control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of two control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_2_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_2_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of three control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of four control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of five control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_5_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_5_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of six control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_6_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_6_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of seven control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_7_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_7_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of eight control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_8_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_8_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of nine control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_9_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_9_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of ten control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_10_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_10_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of 11 control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_11_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_11_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of 12 control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_12_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_12_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of 13 control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_13_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_13_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of 14 control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_14_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_14_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of 15 control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_15_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_15_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of 16 control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_16_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_16_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of 17 control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_17_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_17_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of 18 control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_18_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_18_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of 19 control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_19_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_19_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of 20 control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_20_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_20_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of 21 control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_21_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_21_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of 22 control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_22_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_22_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of 23 control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_23_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_23_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of 24 control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_24_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_24_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of 25 control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_25_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_25_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of 26 control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_26_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_26_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of 27 control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_27_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_27_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of 28 control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_28_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_28_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of 29 control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_29_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_29_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of 30 control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_30_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_30_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of 31 control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_31_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_31_CONTROL_POINT_PATCHLIST, /// Interpret the vertex data as a list of 32 control point patches.\n /// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES. PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST, /// Helper value that stores the total number of topologies in the enumeration PRIMITIVE_TOPOLOGY_NUM_TOPOLOGIES }; /// Describes common device object attributes struct DeviceObjectAttribs { /// Object name const Char* Name = nullptr; // We have to explicitly define constructors because otherwise Apple's clang fails to compile the following legitimate code: // DeviceObjectAttribs{"Name"} DeviceObjectAttribs()noexcept{} explicit DeviceObjectAttribs(const Char* _Name) : Name(_Name) {} }; /// Hardware adapter attributes struct HardwareAdapterAttribs { /// A string that contains the adapter description char Description[128] = {}; /// Dedicated video memory, in bytes size_t DedicatedVideoMemory = 0; /// Dedicated system memory, in bytes size_t DedicatedSystemMemory = 0; /// Dedicated shared memory, in bytes size_t SharedSystemMemory = 0; /// The PCI ID of the hardware vendor Uint32 VendorId = 0; /// The PCI ID of the hardware device Uint32 DeviceId = 0; /// Number of outputs this device has Uint32 NumOutputs = 0; }; /// Display mode attributes struct DisplayModeAttribs { /// Flags indicating how an image is stretched to fit a given monitor's resolution. /// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb173066(v=vs.85).aspx">DXGI_MODE_SCALING enumeration on MSDN</a>, enum SCALING { /// Unspecified scaling. /// D3D Counterpart: DXGI_MODE_SCALING_UNSPECIFIED. SCALING_UNSPECIFIED = 0, /// Specifies no scaling. The image is centered on the display. /// This flag is typically used for a fixed-dot-pitch display (such as an LED display). /// D3D Counterpart: DXGI_MODE_SCALING_CENTERED. SCALING_CENTERED = 1, /// Specifies stretched scaling. /// D3D Counterpart: DXGI_MODE_SCALING_STRETCHED. SCALING_STRETCHED = 2 }; /// Flags indicating the method the raster uses to create an image on a surface. /// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb173067">DXGI_MODE_SCANLINE_ORDER enumeration on MSDN</a>, enum SCANLINE_ORDER { /// Scanline order is unspecified /// D3D Counterpart: DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED. SCANLINE_ORDER_UNSPECIFIED = 0, /// The image is created from the first scanline to the last without skipping any /// D3D Counterpart: DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE. SCANLINE_ORDER_PROGRESSIVE = 1, /// The image is created beginning with the upper field /// D3D Counterpart: DXGI_MODE_SCANLINE_ORDER_UPPER_FIELD_FIRST. SCANLINE_ORDER_UPPER_FIELD_FIRST = 2, /// The image is created beginning with the lower field /// D3D Counterpart: DXGI_MODE_SCANLINE_ORDER_LOWER_FIELD_FIRST. SCANLINE_ORDER_LOWER_FIELD_FIRST = 3 }; /// Display resolution width Uint32 Width = 0; /// Display resolution height Uint32 Height = 0; /// Display format TEXTURE_FORMAT Format = TEX_FORMAT_UNKNOWN; /// Refresh rate numerator Uint32 RefreshRateNumerator = 0; /// Refresh rate denominator Uint32 RefreshRateDenominator = 0; /// The scanline drawing mode. SCALING Scaling = SCALING_UNSPECIFIED; /// The scaling mode. SCANLINE_ORDER ScanlineOrder = SCANLINE_ORDER_UNSPECIFIED; }; /// Swap chain description struct SwapChainDesc { /// The swap chain width. Default value is 0 Uint32 Width = 0; /// The swap chain height. Default value is 0 Uint32 Height = 0; /// Back buffer format. Default value is Diligent::TEX_FORMAT_RGBA8_UNORM_SRGB TEXTURE_FORMAT ColorBufferFormat = TEX_FORMAT_RGBA8_UNORM_SRGB; /// Depth buffer format. Default value is Diligent::TEX_FORMAT_D32_FLOAT TEXTURE_FORMAT DepthBufferFormat = TEX_FORMAT_D32_FLOAT; /// Sample count. Default value is 1 Uint32 SamplesCount = 1; /// Number of buffers int the swap chain Uint32 BufferCount = 2; /// Default depth value, which is used as optimized depth clear value in D3D12 Float32 DefaultDepthValue = 1.f; /// Default stencil value, which is used as optimized stencil clear value in D3D12 Uint8 DefaultStencilValue = 0; SwapChainDesc()noexcept{} /// Constructor intializes the structure members with default values SwapChainDesc(Uint32 _Width, Uint32 _Height, TEXTURE_FORMAT _ColorBufferFormat, TEXTURE_FORMAT _DepthBufferFormat, Uint32 _SamplesCount = SwapChainDesc{}.SamplesCount, Uint32 _BufferCount = SwapChainDesc{}.BufferCount, Float32 _DefaultDepthValue = SwapChainDesc{}.DefaultDepthValue, Uint8 _DefaultStencilValue = SwapChainDesc{}.DefaultStencilValue) : Width (_Width), Height (_Height), ColorBufferFormat (_ColorBufferFormat), DepthBufferFormat (_DepthBufferFormat), SamplesCount (_SamplesCount), BufferCount (_BufferCount), DefaultDepthValue (_DefaultDepthValue), DefaultStencilValue(_DefaultStencilValue) {} }; /// Full screen mode description /// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/hh404531(v=vs.85).aspx">DXGI_SWAP_CHAIN_FULLSCREEN_DESC structure on MSDN</a>, struct FullScreenModeDesc { /// A Boolean value that specifies whether the swap chain is in fullscreen mode. Bool Fullscreen = False; /// Refresh rate numerator Uint32 RefreshRateNumerator = 0; /// Refresh rate denominator Uint32 RefreshRateDenominator = 0; /// The scanline drawing mode. DisplayModeAttribs::SCALING Scaling = DisplayModeAttribs::SCALING_UNSPECIFIED; /// The scaling mode. DisplayModeAttribs::SCANLINE_ORDER ScanlineOrder = DisplayModeAttribs::SCANLINE_ORDER_UNSPECIFIED; }; /// Engine creation attibutes struct EngineCreationAttribs { /// Pointer to the raw memory allocator that will be used for all memory allocation/deallocation /// operations in the engine class IMemoryAllocator* pRawMemAllocator = nullptr; /// Pointer to the user-specified debug message callback function DebugMessageCallbackType DebugMessageCallback = nullptr; }; /// Attributes specific to D3D12 engine struct EngineD3D12Attribs : public EngineCreationAttribs { static constexpr Uint32 DefaultAdapterId = 0xFFFFFFFF; /// Id of the hardware adapter the engine should be initialized on Uint32 AdapterId = DefaultAdapterId; /// Size of the CPU descriptor heap allocations for different heap types. Uint32 CPUDescriptorHeapAllocationSize[4] = { 8192, // D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV 2048, // D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER 1024, // D3D12_DESCRIPTOR_HEAP_TYPE_RTV 1024 // D3D12_DESCRIPTOR_HEAP_TYPE_DSV }; /// Size of the GPU descriptor heap allocations for different heap types. Uint32 GPUDescriptorHeapSize[2] = { 16384, // D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV 1024 // D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER }; /// Size of the dynamic GPU descriptor heap region for different heap types. Uint32 GPUDescriptorHeapDynamicSize[2] = { 8192, // D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV 1024 // D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER }; /// This is the size of the chunk that dynamic descriptor allocations manager /// request from the main GPU descriptor heap. Uint32 DynamicDescriptorAllocationChunkSize[2] = { 256, // D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV 32 // D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER }; /// Number of commands to flush the command list. Only draw/dispatch commands count /// towards the limit. Command lists are only flushed when pipeline state is changed /// or when backbuffer is presented. Uint32 NumCommandsToFlushCmdList = 256; /// A device context uses dynamic heap when it needs to allocate temporary /// CPU-accessible memory to update a resource via IBufer::UpdateData() or /// ITexture::UpdateData(), or to map dynamic resources. /// Device contexts first request a chunk of memory from global dynamic /// resource manager and then suballocate from this chunk in a lock-free /// fashion. DynamicHeapPageSize defines the size of this chunk. Uint32 DynamicHeapPageSize = 1 << 20; /// Number of dynamic heap pages that will be reserved by the /// global dynamic heap manager to avoid page creation at run time. Uint32 NumDynamicHeapPagesToReserve = 1; }; /// Attributes specific to Vulkan engine struct EngineVkAttribs : public EngineCreationAttribs { /// Enable validation layers. Validation is always enabled in Debug mode bool EnableValidation = false; /// Number of global Vulkan extensions Uint32 GlobalExtensionCount = 0; /// List of global Vulkan extensions to enable. const char* const* ppGlobalExtensionNames = nullptr; /// Allocator used as pAllocator parameter in callse to Vulkan Create* functions void *pVkAllocator = nullptr; /// Number of commands to flush the command buffer. Only draw/dispatch commands count /// towards the limit. Command buffers are only flushed when pipeline state is changed /// or when backbuffer is presented. Uint32 NumCommandsToFlushCmdBuffer = 256; /// List of device features to be enabled /// see https://www.khronos.org/registry/vulkan/specs/1.0/html/vkspec.html#VkPhysicalDeviceFeatures struct DeviceFeatures { bool depthBiasClamp = false; bool fillModeNonSolid = false; bool depthClamp = false; bool independentBlend = false; bool samplerAnisotropy = false; bool geometryShader = false; bool tessellationShader = false; bool dualSrcBlend = false; bool multiViewport = false; bool imageCubeArray = false; bool textureCompressionBC = false; bool vertexPipelineStoresAndAtomics = false; bool fragmentStoresAndAtomics = false; bool shaderStorageImageExtendedFormats = false; }EnabledFeatures; /// Descriptor pool size struct DescriptorPoolSize { Uint32 MaxDescriptorSets = 0; Uint32 NumSeparateSamplerDescriptors = 0; Uint32 NumCombinedSamplerDescriptors = 0; Uint32 NumSampledImageDescriptors = 0; Uint32 NumStorageImageDescriptors = 0; Uint32 NumUniformBufferDescriptors = 0; Uint32 NumStorageBufferDescriptors = 0; Uint32 NumUniformTexelBufferDescriptors = 0; Uint32 NumStorageTexelBufferDescriptors = 0; DescriptorPoolSize()noexcept {} DescriptorPoolSize( Uint32 _MaxDescriptorSets, Uint32 _NumSeparateSamplerDescriptors, Uint32 _NumCombinedSamplerDescriptors, Uint32 _NumSampledImageDescriptors, Uint32 _NumStorageImageDescriptors, Uint32 _NumUniformBufferDescriptors, Uint32 _NumStorageBufferDescriptors, Uint32 _NumUniformTexelBufferDescriptors, Uint32 _NumStorageTexelBufferDescriptors)noexcept : MaxDescriptorSets (_MaxDescriptorSets ), NumSeparateSamplerDescriptors (_NumSeparateSamplerDescriptors ), NumCombinedSamplerDescriptors (_NumCombinedSamplerDescriptors ), NumSampledImageDescriptors (_NumSampledImageDescriptors ), NumStorageImageDescriptors (_NumStorageImageDescriptors ), NumUniformBufferDescriptors (_NumUniformBufferDescriptors ), NumStorageBufferDescriptors (_NumStorageBufferDescriptors ), NumUniformTexelBufferDescriptors(_NumUniformTexelBufferDescriptors), NumStorageTexelBufferDescriptors(_NumStorageTexelBufferDescriptors) { // On clang aggregate initialization fails to compile if // structure members have default initializers } }; /// Size of the main descriptor pool that is used to allocate descriptor sets /// for static and mutable variables. If allocation from the current pool fails, /// the engine creates another one. // Max SepSm CmbSm SmpImg StrImg UB SB UTxB StTxB DescriptorPoolSize MainDescriptorPoolSize {8192, 1024, 8192, 8192, 1024, 4096, 4096, 1024, 1024}; /// Size of the dynamic descriptor pool that is used to allocate descriptor sets /// for dynamic variables. Every device context has its own dynamic descriptor set allocator. /// The allocator requests pools from global dynamic descriptor pool manager, and then /// performs lock-free suballocations from the pool. // Max SepSm CmbSm SmpImg StrImg UB SB UTxB StTxB DescriptorPoolSize DynamicDescriptorPoolSize {2048, 256, 2048, 2048, 256, 1024, 1024, 256, 256}; /// Allocation granularity for device-local memory Uint32 DeviceLocalMemoryPageSize = 16 << 20; /// Allocation granularity for host-visible memory Uint32 HostVisibleMemoryPageSize = 16 << 20; /// Amount of device-local memory reserved by the engine. /// The engine does not pre-allocate the memory, but rather keeps free /// pages when resources are released Uint32 DeviceLocalMemoryReserveSize = 256 << 20; /// Amount of host-visible memory reserved by the engine. /// The engine does not pre-allocate the memory, but rather keeps free /// pages when resources are released Uint32 HostVisibleMemoryReserveSize = 256 << 20; /// Page size of the upload heap that is allocated by immediate/deferred /// contexts from the global memory manager to perform lock-free dynamic /// suballocations. /// Upload heap is used to update resources with UpdateData() Uint32 UploadHeapPageSize = 1 << 20; /// Size of the dynamic heap (the buffer that is used to suballocate /// memory for dynamic resources) shared by all contexts. Uint32 DynamicHeapSize = 8 << 20; /// Size of the memory chunk suballocated by immediate/deferred context from /// the global dynamic heap to perform lock-free dynamic suballocations Uint32 DynamicHeapPageSize = 256 << 10; }; /// Box struct Box { Uint32 MinX = 0; ///< Minimal X coordinate. Default value is 0 Uint32 MaxX = 0; ///< Maximal X coordinate. Default value is 0 Uint32 MinY = 0; ///< Minimal Y coordinate. Default value is 0 Uint32 MaxY = 0; ///< Maximal Y coordinate. Default value is 0 Uint32 MinZ = 0; ///< Minimal Z coordinate. Default value is 0 Uint32 MaxZ = 1; ///< Maximal Z coordinate. Default value is 1 Box(Uint32 _MinX, Uint32 _MaxX, Uint32 _MinY, Uint32 _MaxY, Uint32 _MinZ, Uint32 _MaxZ) : MinX(_MinX), MaxX(_MaxX), MinY(_MinY), MaxY(_MaxY), MinZ(_MinZ), MaxZ(_MaxZ) {} Box(Uint32 _MinX, Uint32 _MaxX, Uint32 _MinY, Uint32 _MaxY) : Box(_MinX, _MaxX, _MinY, _MaxY, 0, 1) {} Box(Uint32 _MinX, Uint32 _MaxX) : Box(_MinX, _MaxX, 0, 0, 0, 1) {} Box(){} }; /// Describes texture format component type enum COMPONENT_TYPE : Uint8 { /// Undefined component type COMPONENT_TYPE_UNDEFINED, /// Floating point component type COMPONENT_TYPE_FLOAT, /// Signed-normalized-integer component type COMPONENT_TYPE_SNORM, /// Unsigned-normalized-integer component type COMPONENT_TYPE_UNORM, /// Unsigned-normalized-integer sRGB component type COMPONENT_TYPE_UNORM_SRGB, /// Signed-integer component type COMPONENT_TYPE_SINT, /// Unsigned-integer component type COMPONENT_TYPE_UINT, /// Depth component type COMPONENT_TYPE_DEPTH, /// Depth-stencil component type COMPONENT_TYPE_DEPTH_STENCIL, /// Compound component type (example texture formats: TEX_FORMAT_R11G11B10_FLOAT or TEX_FORMAT_RGB9E5_SHAREDEXP) COMPONENT_TYPE_COMPOUND, /// Compressed component type COMPONENT_TYPE_COMPRESSED, }; /// Describes invariant texture format attributes. These attributes are /// intrinsic to the texture format itself and do not depend on the /// format support. struct TextureFormatAttribs { /// Literal texture format name (for instance, for TEX_FORMAT_RGBA8_UNORM format, this /// will be "TEX_FORMAT_RGBA8_UNORM") const Char* Name; /// Texture format, see Diligent::TEXTURE_FORMAT for a list of supported texture formats TEXTURE_FORMAT Format; /// Size of one component in bytes (for instance, for TEX_FORMAT_RGBA8_UNORM format, this will be 1) /// For compressed formats, this is the block size in bytes (for TEX_FORMAT_BC1_UNORM format, this will be 8) Uint8 ComponentSize; /// Number of components Uint8 NumComponents; /// Component type, see Diligent::COMPONENT_TYPE for details. COMPONENT_TYPE ComponentType; /// Bool flag indicating if the format is a typeless format bool IsTypeless; /// For block-compressed formats, compression block width Uint8 BlockWidth; /// For block-compressed formats, compression block height Uint8 BlockHeight; /// Initializes the structure TextureFormatAttribs( const Char* _Name, TEXTURE_FORMAT _Format, Uint8 _ComponentSize, Uint8 _NumComponents, COMPONENT_TYPE _ComponentType, bool _IsTypeless, Uint8 _BlockWidth, Uint8 _BlockHeight)noexcept : Name (_Name), Format (_Format), ComponentSize(_ComponentSize), NumComponents(_NumComponents), ComponentType(_ComponentType), IsTypeless (_IsTypeless), BlockWidth (_BlockWidth), BlockHeight (_BlockHeight) { } TextureFormatAttribs()noexcept : Name ("TEX_FORMAT_UNKNOWN"), Format (TEX_FORMAT_UNKNOWN), ComponentSize(0), NumComponents(0), ComponentType(COMPONENT_TYPE_UNDEFINED), IsTypeless (false), BlockWidth (0), BlockHeight (0) {} }; /// Basic texture format description /// This structure is returned by IRenderDevice::GetTextureFormatInfo() struct TextureFormatInfo : public TextureFormatAttribs { /// Indicates if the format is supported by the device bool Supported = false; }; /// Extended texture format description /// This structure is returned by IRenderDevice::GetTextureFormatInfoExt() struct TextureFormatInfoExt : TextureFormatInfo { /// Indicates if the format can be filtered bool Filterable = false; /// Indicates if the format can be used as a render target format bool ColorRenderable = false; /// Indicates if the format can be used as a depth format bool DepthRenderable = false; /// Indicates if the format can be used to create a 1D texture bool Tex1DFmt = false; /// Indicates if the format can be used to create a 2D texture bool Tex2DFmt = false; /// Indicates if the format can be used to create a 3D texture bool Tex3DFmt = false; /// Indicates if the format can be used to create a cube texture bool TexCubeFmt = false; /// A bitmask specifying all the supported sample counts for this texture format. /// If the format supports n samples, then (SampleCounts & n) != 0 Uint32 SampleCounts = 0; }; /// Resource usage state enum RESOURCE_STATE : Uint32 { /// The resource state is not known to the engine and is managed by the application RESOURCE_STATE_UNKNOWN = 0x0000, /// The resource state is known to the engine, but is undefined. A resource is typically in an undefined state right after initialization. RESOURCE_STATE_UNDEFINED = 0x0001, /// The resource is accessed as vertex buffer RESOURCE_STATE_VERTEX_BUFFER = 0x0002, /// The resource is accessed as constant (uniform) buffer RESOURCE_STATE_CONSTANT_BUFFER = 0x0004, /// The resource is accessed as index buffer RESOURCE_STATE_INDEX_BUFFER = 0x0008, /// The resource is accessed as render target RESOURCE_STATE_RENDER_TARGET = 0x0010, /// The resource is used for unordered access RESOURCE_STATE_UNORDERED_ACCESS = 0x0020, /// The resource is used in a writable depth-stencil view or in clear operation RESOURCE_STATE_DEPTH_WRITE = 0x0040, /// The resource is used in a read-only depth-stencil view RESOURCE_STATE_DEPTH_READ = 0x0080, /// The resource is accessed from a shader RESOURCE_STATE_SHADER_RESOURCE = 0x0100, /// The resource is used as the destination for stream output RESOURCE_STATE_STREAM_OUT = 0x0200, /// The resource is used as indirect draw/dispatch arguments buffer RESOURCE_STATE_INDIRECT_ARGUMENT = 0x0400, /// The resource is used as the destination in a copy operation RESOURCE_STATE_COPY_DEST = 0x0800, /// The resource is used as the source in a copy operation RESOURCE_STATE_COPY_SOURCE = 0x1000, /// The resource is used as the destination in a resolve operation RESOURCE_STATE_RESOLVE_DEST = 0x2000, /// The resource is used as the source in a resolve operation RESOURCE_STATE_RESOLVE_SOURCE = 0x4000, /// The resource is used for present RESOURCE_STATE_PRESENT = 0x8000, RESOURCE_STATE_MAX_BIT = 0x8000, RESOURCE_STATE_GENERIC_READ = RESOURCE_STATE_VERTEX_BUFFER | RESOURCE_STATE_CONSTANT_BUFFER | RESOURCE_STATE_INDEX_BUFFER | RESOURCE_STATE_SHADER_RESOURCE | RESOURCE_STATE_INDIRECT_ARGUMENT | RESOURCE_STATE_COPY_SOURCE }; /// State transition barrier type enum STATE_TRANSITION_TYPE : Uint8 { /// Perform state transition immediately. STATE_TRANSITION_TYPE_IMMEDIATE = 0, /// Begin split barrier. This mode only has effect in Direct3D12 backend, and corresponds to /// [D3D12_RESOURCE_BARRIER_FLAG_BEGIN_ONLY](https://docs.microsoft.com/en-us/windows/desktop/api/d3d12/ne-d3d12-d3d12_resource_barrier_flags) /// flag. See https://docs.microsoft.com/en-us/windows/desktop/direct3d12/using-resource-barriers-to-synchronize-resource-states-in-direct3d-12#split-barriers. /// In other backends, begin-split barriers are ignored. STATE_TRANSITION_TYPE_BEGIN, /// End split barrier. This mode only has effect in Direct3D12 backend, and corresponds to /// [D3D12_RESOURCE_BARRIER_FLAG_END_ONLY](https://docs.microsoft.com/en-us/windows/desktop/api/d3d12/ne-d3d12-d3d12_resource_barrier_flags) /// flag. See https://docs.microsoft.com/en-us/windows/desktop/direct3d12/using-resource-barriers-to-synchronize-resource-states-in-direct3d-12#split-barriers. /// In other backends, this mode is similar to STATE_TRANSITION_TYPE_IMMEDIATE. STATE_TRANSITION_TYPE_END }; /// Resource state transition barrier description struct StateTransitionDesc { static constexpr const Uint32 RemainingMipLevels = static_cast<Uint32>(-1); static constexpr const Uint32 RemainingArraySlices = static_cast<Uint32>(-1); /// Texture to transition. /// \note Exactly one of pTexture or pBuffer must be non-null. ITexture* pTexture = nullptr; /// Buffer to transition. /// \note Exactly one of pTexture or pBuffer must be non-null. IBuffer* pBuffer = nullptr; /// When transitioning a texture, first mip level of the subresource range to transition. Uint32 FirstMipLevel = 0; /// When transitioning a texture, number of mip levels of the subresource range to transition. Uint32 MipLevelsCount = RemainingMipLevels; /// When transitioning a texture, first array slice of the subresource range to transition. Uint32 FirstArraySlice = 0; /// When transitioning a texture, number of array slices of the subresource range to transition. Uint32 ArraySliceCount = RemainingArraySlices; /// Resource state before transition. If this value is RESOURCE_STATE_UNKNOWN, /// internal resource state will be used, which must be defined in this case. RESOURCE_STATE OldState = RESOURCE_STATE_UNKNOWN; /// Resource state after transition. RESOURCE_STATE NewState = RESOURCE_STATE_UNKNOWN; /// State transition type, see Diligent::STATE_TRANSITION_TYPE. /// \note When issuing UAV barrier (i.e. OldState and NewState equal RESOURCE_STATE_UNORDERED_ACCESS), /// TransitionType must be STATE_TRANSITION_TYPE_IMMEDIATE. STATE_TRANSITION_TYPE TransitionType = STATE_TRANSITION_TYPE_IMMEDIATE; /// If set to true, the internal resource state will be set to NewState and the engine /// will be able to take over the resource state management. In this case it is the /// responsibility of the application to make sure that all subresources are indeed in /// designated state. /// If set to false, internal resource state will be unchanged. /// \note When TransitionType is STATE_TRANSITION_TYPE_BEGIN, this member must be false. bool UpdateResourceState = false; StateTransitionDesc()noexcept{} StateTransitionDesc(ITexture* _pTexture, RESOURCE_STATE _OldState, RESOURCE_STATE _NewState, Uint32 _FirstMipLevel = 0, Uint32 _MipLevelsCount = RemainingMipLevels, Uint32 _FirstArraySlice = 0, Uint32 _ArraySliceCount = RemainingArraySlices, STATE_TRANSITION_TYPE _TransitionType = STATE_TRANSITION_TYPE_IMMEDIATE, bool _UpdateState = false)noexcept : pTexture (_pTexture), FirstMipLevel (_FirstMipLevel), MipLevelsCount (_MipLevelsCount), FirstArraySlice (_FirstArraySlice), ArraySliceCount (_ArraySliceCount), OldState (_OldState), NewState (_NewState), TransitionType (_TransitionType), UpdateResourceState (_UpdateState) {} StateTransitionDesc(ITexture* _pTexture, RESOURCE_STATE _OldState, RESOURCE_STATE _NewState, bool _UpdateState)noexcept : StateTransitionDesc(_pTexture, _OldState, _NewState, 0, RemainingMipLevels, 0, RemainingArraySlices, STATE_TRANSITION_TYPE_IMMEDIATE, _UpdateState) {} StateTransitionDesc(IBuffer* _pBuffer, RESOURCE_STATE _OldState, RESOURCE_STATE _NewState, bool _UpdateState)noexcept : pBuffer (_pBuffer), OldState (_OldState), NewState (_NewState), UpdateResourceState (_UpdateState) {} }; }
0ad5c7ca1de80203f56eb0ab5a74af1a2a28cf30
da2222b25af048b2e4b85d71e5583a9d9a489c9b
/Source/PluginProcessor.h
15e0647b6b7f56fdf4265bf8638b843da09f410f
[]
no_license
marcandrelabelle/PFMProject0-01
093dac9a38a00990ea146ce5264219d943d20ecc
748b32dd0ced856175f029fe653debde0e7bcefa
refs/heads/master
2023-02-13T22:33:20.176909
2021-01-17T20:04:33
2021-01-17T20:04:33
315,801,332
0
0
null
null
null
null
UTF-8
C++
false
false
2,354
h
/* ============================================================================== This file was auto-generated! It contains the basic framework code for a JUCE plugin processor. ============================================================================== */ #pragma once #include <JuceHeader.h> //============================================================================== /** */ class Pfmproject001AudioProcessor : public AudioProcessor { public: //============================================================================== Pfmproject001AudioProcessor(); ~Pfmproject001AudioProcessor(); //============================================================================== void prepareToPlay (double sampleRate, int samplesPerBlock) override; void releaseResources() override; #ifndef JucePlugin_PreferredChannelConfigurations bool isBusesLayoutSupported (const BusesLayout& layouts) const override; #endif void processBlock (AudioBuffer<float>&, MidiBuffer&) override; //============================================================================== AudioProcessorEditor* createEditor() override; bool hasEditor() const override; //============================================================================== const String getName() const override; bool acceptsMidi() const override; bool producesMidi() const override; bool isMidiEffect() const override; double getTailLengthSeconds() const override; //============================================================================== int getNumPrograms() override; int getCurrentProgram() override; void setCurrentProgram (int index) override; const String getProgramName (int index) override; void changeProgramName (int index, const String& newName) override; //============================================================================== void getStateInformation (MemoryBlock& destData) override; void setStateInformation (const void* data, int sizeInBytes) override; bool shouldPlaySound = false; private: Random r; //============================================================================== JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pfmproject001AudioProcessor) };
e39804b420463fb7f39faf4fef1772f95648903f
9368949953681f84e524636686843d7cc06fe2ad
/Part1-Modeling/objects-standard/torus.cpp
38f53500f38d78b0f496db50ac2f67ca876fee31
[]
no_license
Blz-Galaxy/OpenGL_Animation_MT
edfc20fbcdf086a31648ba54da079cad56668919
9d47c57f30edcdd6d2bc57f1042df665a1f55a20
refs/heads/master
2021-01-17T12:06:23.210468
2015-07-21T16:54:41
2015-07-21T16:54:54
39,453,685
5
1
null
null
null
null
UTF-8
C++
false
false
4,031
cpp
// ========================================================================================= // KXC354 - Computer Graphics & Animation, 2012 // Assignment 1 & 2 // 3D Engine Code // ========================================================================================= // // Author: Tony Gray // // torus.cpp // // This file defines the class for torus objects // ----------------------------------------------------------------------------------------- // includes // ----------------------------------------------------------------------------------------- #include "prefix.h" #include "torus.h" #include "utility.h" // ----------------------------------------------------------------------------------------- // globals // ----------------------------------------------------------------------------------------- extern vector<object3d*> gShapeVector; // ----------------------------------------------------------------------------------------- // default constructor // ----------------------------------------------------------------------------------------- torus::torus(int density, int slices, float radius, float height) { setColour(1.0, 1.0, 0.0); // default colour (yellow) setName("torus"); // calculate the number of vertices and faces from the mesh density vertexCount = density * slices; faceCount = density * slices; polygonCount = faceCount; // allocate memory for the vertex and face arrays vertices.resize(vertexCount); faces.resize(faceCount); float yStepSize = 360.0 / slices; // rotating around Y axis by this amount float zStepSize = 360.0 / density; // rotating around Z axis by this amount // generate the vertex information unsigned int v = 0; // init the vertex counter float zRot = 0; for (int i=0; i<density; i++) // outer loop (Z Rot) { // calculate angle around Z axis - this is the "height" of the horizontal // disc, and the Y coordinate of all vertices on the circumference of that disc float y = height * sin_d(zRot); // also calculate X - this is subtracted from the torus radius to // calculate the radius for the horizontal disc float x = height * cos_d(zRot); float discRad = radius - x; float yRot=0; // OK - now split the disc into slices for (int j=0; j<slices; j++) // inner loop (Y rotation) { vertices[v++].set(discRad * cos_d(yRot), y, discRad * sin_d(yRot)); yRot+=yStepSize; // step around for the next division } zRot+=zStepSize; // step around for the next disc } // this first test may never execute if we've overflowed the array (since the program will have crashed by now) if (v > vertexCount) fatal("generated more vertices than you said you would"); if (v < vertexCount) fatal("allocated space for more vertices than you generated"); // now generate the face list unsigned int k=0; // face counter for (int zLoop=0; zLoop<density; zLoop++) // loop for each disc { int offset1 = (zLoop * slices); // this is the "first vertex" for this disc int offset2 = ((offset1 + slices)% (slices * density)); // this is the "first vertex" of the NEXT disc for (int yLoop=0; yLoop<slices; yLoop++) // loop around each disc faces[k++].init(offset1 + yLoop, // the first vertex of this disc offset1 + ((yLoop+1)%slices), // the next is on this disc, one around offset2 + ((yLoop+1)%slices), // the next is on next disc, one around offset2 + yLoop); // the last is on the next disc, below first } // this first test may never execute if we've overflowed the array (since the program will have crashed by now) if (k > faceCount) fatal("generated more faces than you said you would"); if (k < faceCount) fatal("allocated space for more faces than you generated"); // calculate the face and vertex normals calculateNormals(); diffuseShading = false; // put the shape onto the shapeVector so it gets draw messages gShapeVector.push_back(this); }
e9f256ff2d156f073e7804a938f0283007f1c8b1
b52175555ca450b332774b98bf113ed8ea6baa63
/Sources/Components/FastReport5/LibD19/frxDesgnWorkspace.hpp
2645f8f558630135957428bd875a0f2f7360c6a6
[]
no_license
bravesoftdz/shsmeta
a262d860e8d5df1b0656cb9352725a8af79a84c1
f24ebf7f52258f40783200e38222420784acf4d7
refs/heads/master
2021-05-31T11:24:35.015982
2016-05-27T14:01:42
2016-05-27T14:01:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,198
hpp
// CodeGear C++Builder // Copyright (c) 1995, 2013 by Embarcadero Technologies, Inc. // All rights reserved // (DO NOT EDIT: machine generated header) 'frxDesgnWorkspace.pas' rev: 26.00 (Windows) #ifndef FrxdesgnworkspaceHPP #define FrxdesgnworkspaceHPP #pragma delphiheader begin #pragma option push #pragma option -w- // All warnings off #pragma option -Vx // Zero-length empty class member #pragma pack(push,8) #include <System.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <Winapi.Windows.hpp> // Pascal unit #include <Winapi.Messages.hpp> // Pascal unit #include <System.Types.hpp> // Pascal unit #include <System.SysUtils.hpp> // Pascal unit #include <System.Classes.hpp> // Pascal unit #include <Vcl.Graphics.hpp> // Pascal unit #include <Vcl.Controls.hpp> // Pascal unit #include <Vcl.Forms.hpp> // Pascal unit #include <Vcl.Dialogs.hpp> // Pascal unit #include <Vcl.ExtCtrls.hpp> // Pascal unit #include <Vcl.Buttons.hpp> // Pascal unit #include <frxClass.hpp> // Pascal unit #include <frxUnicodeCtrls.hpp> // Pascal unit #include <System.Variants.hpp> // Pascal unit #include <Vcl.StdCtrls.hpp> // Pascal unit #include <System.UITypes.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Frxdesgnworkspace { //-- type declarations ------------------------------------------------------- enum DECLSPEC_DENUM TfrxDesignMode : unsigned char { dmSelect, dmInsert, dmDrag }; enum DECLSPEC_DENUM TfrxDesignMode1 : unsigned char { dmNone, dmMove, dmSize, dmSizeBand, dmScale, dmInplaceEdit, dmSelectionRect, dmInsertObject, dmInsertLine, dmMoveGuide, dmContainer }; enum DECLSPEC_DENUM TfrxGridType : unsigned char { gt1pt, gt1cm, gt1in, gtDialog, gtChar, gtNone }; enum DECLSPEC_DENUM TfrxCursorType : unsigned char { ct0, ct1, ct2, ct3, ct4, ct5, ct6, ct7, ct8, ct9, ct10 }; typedef void __fastcall (__closure *TfrxNotifyPositionEvent)(const Frxclass::TfrxRect &ARect); #pragma pack(push,1) struct DECLSPEC_DRECORD TfrxInsertion { public: Frxclass::TfrxComponentClass ComponentClass; System::Extended Left; System::Extended Top; System::Extended Width; System::Extended Height; System::Extended OriginalWidth; System::Extended OriginalHeight; System::Word Flags; }; #pragma pack(pop) class DELPHICLASS TfrxDesignerWorkspace; class PASCALIMPLEMENTATION TfrxDesignerWorkspace : public Vcl::Extctrls::TPanel { typedef Vcl::Extctrls::TPanel inherited; protected: System::Extended FBandHeader; Vcl::Graphics::TCanvas* FCanvas; System::Uitypes::TColor FColor; TfrxCursorType FCT; bool FDblClicked; bool FDisableUpdate; bool FFreeBandsPlacement; int FGapBetweenBands; bool FGridAlign; bool FGridLCD; TfrxGridType FGridType; System::Extended FGridX; System::Extended FGridY; Frxunicodectrls::TUnicodeMemo* FInplaceMemo; Frxclass::TfrxCustomMemoView* FInplaceObject; TfrxInsertion FInsertion; System::Extended FLastMousePointX; System::Extended FLastMousePointY; System::Types::TRect FMargins; Vcl::Extctrls::TPanel* FMarginsPanel; TfrxDesignMode FMode; TfrxDesignMode1 FMode1; bool FModifyFlag; bool FMouseDown; System::Classes::TList* FObjects; System::Extended FOffsetX; System::Extended FOffsetY; Frxclass::TfrxPage* FPage; int FPageHeight; int FPageWidth; System::Extended FScale; Frxclass::TfrxRect FScaleRect; Frxclass::TfrxRect FScaleRect1; System::Classes::TList* FSelectedObjects; System::Classes::TList* FSavedAlign; Frxclass::TfrxRect FSelectionRect; bool FShowBandCaptions; bool FShowEdges; bool FShowGrid; Frxclass::TfrxBand* FSizedBand; System::Classes::TNotifyEvent FOnModify; System::Classes::TNotifyEvent FOnEdit; System::Classes::TNotifyEvent FOnInsert; TfrxNotifyPositionEvent FOnNotifyPosition; System::Classes::TNotifyEvent FOnSelectionChanged; System::Classes::TNotifyEvent FOnTopLeftChanged; void __fastcall DoModify(void); void __fastcall AdjustBandHeight(Frxclass::TfrxBand* Bnd); virtual void __fastcall CheckGuides(System::Extended &kx, System::Extended &ky, bool &Result); void __fastcall DoNudge(System::Extended dx, System::Extended dy, bool Smooth); void __fastcall DoSize(System::Extended dx, System::Extended dy); void __fastcall DoStick(int dx, int dy); void __fastcall DoTab(void); void __fastcall DrawBackground(void); void __fastcall DrawCross(bool Down); void __fastcall DrawInsertionRect(void); virtual void __fastcall DrawObjects(void); void __fastcall DrawSelectionRect(void); void __fastcall FindNearest(int dx, int dy); void __fastcall MouseLeave(void); void __fastcall NormalizeCoord(Frxclass::TfrxComponent* c); void __fastcall NormalizeRect(Frxclass::TfrxRect &R); void __fastcall SelectionChanged(void); void __fastcall SetScale(System::Extended Value); void __fastcall SetShowBandCaptions(const bool Value); void __fastcall UpdateBandHeader(void); DYNAMIC void __fastcall DblClick(void); DYNAMIC void __fastcall KeyDown(System::Word &Key, System::Classes::TShiftState Shift); DYNAMIC void __fastcall KeyUp(System::Word &Key, System::Classes::TShiftState Shift); DYNAMIC void __fastcall MouseDown(System::Uitypes::TMouseButton Button, System::Classes::TShiftState Shift, int X, int Y); DYNAMIC void __fastcall MouseMove(System::Classes::TShiftState Shift, int X, int Y); DYNAMIC void __fastcall MouseUp(System::Uitypes::TMouseButton Button, System::Classes::TShiftState Shift, int X, int Y); HIDESBASE MESSAGE void __fastcall CMMouseLeave(Winapi::Messages::TMessage &Message); HIDESBASE MESSAGE void __fastcall WMMove(Winapi::Messages::TWMMove &Message); MESSAGE void __fastcall WMEraseBackground(Winapi::Messages::TMessage &Message); void __fastcall PrepareShiftTree(Frxclass::TfrxBand* Band); void __fastcall SetColor_(const System::Uitypes::TColor Value); void __fastcall SetGridType(const TfrxGridType Value); void __fastcall SetOrigin(const System::Types::TPoint &Value); virtual void __fastcall SetParent(Vcl::Controls::TWinControl* AParent); void __fastcall SetShowGrid(const bool Value); System::Types::TPoint __fastcall GetOrigin(void); Frxclass::TfrxComponent* __fastcall GetRightBottomObject(void); Frxclass::TfrxRect __fastcall GetSelectionBounds(void); bool __fastcall ListsEqual(System::Classes::TList* List1, System::Classes::TList* List2); int __fastcall SelectedCount(void); public: __fastcall virtual TfrxDesignerWorkspace(System::Classes::TComponent* AOwner); __fastcall virtual ~TfrxDesignerWorkspace(void); virtual void __fastcall Paint(void); void __fastcall AdjustBands(bool AttachObjects = true); virtual void __fastcall DeleteObjects(void); void __fastcall DisableUpdate(void); void __fastcall EnableUpdate(void); virtual void __fastcall EditObject(void); void __fastcall GroupObjects(void); void __fastcall UngroupObjects(void); virtual void __fastcall SetInsertion(Frxclass::TfrxComponentClass AClass, System::Extended AWidth, System::Extended AHeight, System::Word AFlag); void __fastcall SetPageDimensions(int AWidth, int AHeight, const System::Types::TRect &AMargins); void __fastcall UpdateView(void); __property System::Extended BandHeader = {read=FBandHeader, write=FBandHeader}; __property System::Uitypes::TColor Color = {read=FColor, write=SetColor_, nodefault}; __property bool FreeBandsPlacement = {read=FFreeBandsPlacement, write=FFreeBandsPlacement, nodefault}; __property int GapBetweenBands = {read=FGapBetweenBands, write=FGapBetweenBands, nodefault}; __property bool GridAlign = {read=FGridAlign, write=FGridAlign, nodefault}; __property bool GridLCD = {read=FGridLCD, write=FGridLCD, nodefault}; __property TfrxGridType GridType = {read=FGridType, write=SetGridType, nodefault}; __property System::Extended GridX = {read=FGridX, write=FGridX}; __property System::Extended GridY = {read=FGridY, write=FGridY}; __property TfrxInsertion Insertion = {read=FInsertion}; __property bool IsMouseDown = {read=FMouseDown, nodefault}; __property TfrxDesignMode1 Mode = {read=FMode1, nodefault}; __property System::Classes::TList* Objects = {read=FObjects, write=FObjects}; __property System::Extended OffsetX = {read=FOffsetX, write=FOffsetX}; __property System::Extended OffsetY = {read=FOffsetY, write=FOffsetY}; __property System::Types::TPoint Origin = {read=GetOrigin, write=SetOrigin}; __property Frxclass::TfrxPage* Page = {read=FPage, write=FPage}; __property System::Extended Scale = {read=FScale, write=SetScale}; __property System::Classes::TList* SelectedObjects = {read=FSelectedObjects, write=FSelectedObjects}; __property bool ShowBandCaptions = {read=FShowBandCaptions, write=SetShowBandCaptions, nodefault}; __property bool ShowEdges = {read=FShowEdges, write=FShowEdges, nodefault}; __property bool ShowGrid = {read=FShowGrid, write=SetShowGrid, nodefault}; __property System::Classes::TNotifyEvent OnModify = {read=FOnModify, write=FOnModify}; __property System::Classes::TNotifyEvent OnEdit = {read=FOnEdit, write=FOnEdit}; __property System::Classes::TNotifyEvent OnInsert = {read=FOnInsert, write=FOnInsert}; __property TfrxNotifyPositionEvent OnNotifyPosition = {read=FOnNotifyPosition, write=FOnNotifyPosition}; __property System::Classes::TNotifyEvent OnSelectionChanged = {read=FOnSelectionChanged, write=FOnSelectionChanged}; __property System::Classes::TNotifyEvent OnTopLeftChanged = {read=FOnTopLeftChanged, write=FOnTopLeftChanged}; public: /* TWinControl.CreateParented */ inline __fastcall TfrxDesignerWorkspace(HWND ParentWindow) : Vcl::Extctrls::TPanel(ParentWindow) { } }; class DELPHICLASS TInplaceMemo; class PASCALIMPLEMENTATION TInplaceMemo : public Frxunicodectrls::TUnicodeMemo { typedef Frxunicodectrls::TUnicodeMemo inherited; private: TfrxDesignerWorkspace* FDesigner; Frxclass::TfrxCustomMemoView* FObject; System::Types::TSize FOriginalSize; void __fastcall LinesChange(System::TObject* Sender); public: __fastcall virtual TInplaceMemo(System::Classes::TComponent* AOwner); void __fastcall Edit(Frxclass::TfrxCustomMemoView* c); void __fastcall EditDone(void); DYNAMIC void __fastcall KeyPress(System::WideChar &Key); DYNAMIC void __fastcall MouseDown(System::Uitypes::TMouseButton Button, System::Classes::TShiftState Shift, int X, int Y); public: /* TCustomMemo.Destroy */ inline __fastcall virtual ~TInplaceMemo(void) { } public: /* TWinControl.CreateParented */ inline __fastcall TInplaceMemo(HWND ParentWindow) : Frxunicodectrls::TUnicodeMemo(ParentWindow) { } }; //-- var, const, procedure --------------------------------------------------- static const System::Int8 crPencil = System::Int8(0xb); } /* namespace Frxdesgnworkspace */ #if !defined(DELPHIHEADER_NO_IMPLICIT_NAMESPACE_USE) && !defined(NO_USING_NAMESPACE_FRXDESGNWORKSPACE) using namespace Frxdesgnworkspace; #endif #pragma pack(pop) #pragma option pop #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // FrxdesgnworkspaceHPP
cf095cbecc8312e6a5b935365bfaf9f4a9162241
422b67f05e244b7898b0e74a9d75709f16c4ef89
/day_10/main.cpp
0552014986c04b5eb9e15a236ae94f235b5d71c3
[]
no_license
Andurian/AdventOfCode2019
42236998fe3924d9affdc13d4513ff08b63c49d8
997a123f7c19ff27e96181e9ebcd95894ad8421b
refs/heads/main
2023-01-28T09:49:07.280308
2020-12-06T15:00:43
2020-12-06T15:00:43
318,000,745
0
0
null
null
null
null
UTF-8
C++
false
false
636
cpp
#include <iostream> #include "asteroids.h" #include "read_file.h" #include "multicall.h" void solve(const std::string& filename) { std::vector<Asteroid> asteroids = convert_image(read_collection(filename, "\n")); const auto & pos = best_asteroid(asteroids); asteroids.erase(std::find(asteroids.begin(), asteroids.end(), pos)); std::cout << "Result A: " << num_can_see(pos, asteroids) << std::endl; const auto vap = vaporization_order(pos, asteroids); std::cout << "Result B: " << vap[199].x() * 100 + vap[199].y() << std::endl; } int main() { multicall(solve, "input_account_01.txt", "input_account_02.txt"); return 0; }
18b4c9eef42e05eedd6571e5a8585819d99a37ed
0dfe837ecdbd331b6532459b7c5ef5fb10557982
/1287b.cpp
704d3e52a447443a3f00cc206640214ec0553a90
[]
no_license
janani271/CP-solutions-1
5dfe89e371c98c0b3c70684c75361c55dbff9ee3
677105b38c7676f677c29fc1516660050a505c0e
refs/heads/master
2022-04-01T17:48:00.457697
2020-01-16T12:44:32
2020-01-16T12:44:32
234,316,515
0
0
null
null
null
null
UTF-8
C++
false
false
759
cpp
#include<bits/stdc++.h> using namespace std; long long n , k , i , j , ans , g , cn; string f[2500] , a , b , res; map<char,long long>c; map<string,long long>m; int main() { cin>>n>>k; for(i=0;i<n;i++) { cin>>f[i]; m[f[i]]=i; } c['S']=0; c['E']=1; c['T']=2; ans=0; for(i=0;i<n-2;i++) { for(j=i+1;j<n-1;j++) { a = f[i]; b = f[j]; res=""; for(g=0;g<k;g++) { cn = (3 - ((c[a[g]]+c[b[g]])%3))%3; if(cn==0) res += 'S'; else if(cn==1) res += 'E'; else res += 'T'; } if(m[res]!=0 && m[res]>j) { //cout<<"a: "<<a<<"\tb: "<<b<<"\tres: "<<res<<"\n"; ans++; } // cout<<"i: "<<i<<"\tj: "<<j<<"\tk : "<<k<<"\n"; } } cout<<ans; return 0; }
a8cea3a1989a514be88a9d95b10fcd982e5c2142
b67ab5f64c4f562bfce5d871c75821d85aa45733
/src/core/enumerate.hpp
805aae0acd66109b5651782a8655c162b129ac36
[]
no_license
aamshukov/algorithms
ba20e29c886d80942b347fcf9662f84316aa28f5
cc248526544a559fc82b235c40747206e809b802
refs/heads/master
2023-04-07T07:59:03.319751
2023-03-28T23:02:05
2023-03-28T23:02:05
195,858,169
0
0
null
null
null
null
UTF-8
C++
false
false
1,511
hpp
//.............................. // UI Lab Inc. Arthur Amshukov . //.............................. #ifndef __ENUMERATE_H__ #define __ENUMERATE_H__ #pragma once BEGIN_NAMESPACE(algorithms) template <typename T> struct enumerate_wrapper { using iterator_type = std::conditional_t<std::is_const_v<T>, typename T::const_iterator, typename T::iterator>; using pointer_type = std::conditional_t<std::is_const_v<T>, typename T::const_pointer, typename T::pointer>; using reference_type = std::conditional_t<std::is_const_v<T>, typename T::const_reference, typename T::reference>; T& container; constexpr enumerate_wrapper(T& c) : container(c) { } struct enumerate_wrapper_iter { std::size_t index; iterator_type value; bool operator != (const iterator_type& other) const { return value != other; } enumerate_wrapper_iter& operator ++ () { ++index; ++value; return *this; } constexpr std::pair<size_t, reference_type> operator * () { return std::pair<size_t, reference_type>{index, *value}; } }; constexpr enumerate_wrapper_iter begin() { return { 0, std::begin(container) }; } constexpr iterator_type end() { return std::end(container); } }; template <typename T> constexpr auto enumerate(T& c) { return enumerate_wrapper<T>(c); } END_NAMESPACE #endif // __ENUMERATE_H__
fafc417401acb5531eed9c165edd32d310fc62c6
da38abf5d9a94f82a66b506805bde8566ab52c12
/PWGLF/STRANGENESS/Cascades/Run2/AliAnalysisTaskStrEffStudy.cxx
62eb0131b4bb3f34cd952698e6281f243d47fe6d
[]
no_license
pisanos/AliPhysics
3517b7fbf405743e52bffd04353d17c701089f84
44f5631e2a38dd144b2b2e37725e83476c634a82
refs/heads/master
2021-01-21T09:49:39.080004
2017-07-05T09:13:21
2017-07-05T09:13:21
91,668,202
0
0
null
2017-05-18T08:26:24
2017-05-18T08:26:24
null
UTF-8
C++
false
false
172,957
cxx
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ //+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // // This task is meant to study V0 and cascade detection efficiencies // decomposing tracking and pos/neg, V0/bach pairing efficiencies. // // The main intent is to compare 'findable' V0s and cascades, i.e. those // whose daughter particles have been successfully tracked, and correctly // reconstructed candidates. // // The output is composed of two TTree objects storing all 'findable' // candidates and all reconstruction info (if available) and intermediate // vertexing information to determine why that particular findable V0 or // cascade was not found by ALICE. // // --- Questions? Bugs? Please write to: // [email protected] // //+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ class TTree; class TParticle; class TVector3; //class AliMCEventHandler; //class AliMCEvent; //class AliStack; class AliESDVertex; class AliAODVertex; class AliESDv0; class AliAODv0; #include <numeric> #include <Riostream.h> #include "TList.h" #include "TH1.h" #include "TH2.h" #include "TH3.h" #include "TFile.h" #include "THnSparse.h" #include "TVector3.h" #include "TCanvas.h" #include "TMath.h" #include "TLegend.h" #include "TRandom3.h" #include "TProfile.h" //#include "AliLog.h" #include "AliESDEvent.h" #include "AliAODEvent.h" #include "AliV0vertexer.h" #include "AliCascadeVertexer.h" #include "AliLightV0vertexer.h" #include "AliLightCascadeVertexer.h" #include "AliESDpid.h" #include "AliExternalTrackParam.h" #include "AliESDtrack.h" #include "AliESDtrackCuts.h" #include "AliInputEventHandler.h" #include "AliAnalysisManager.h" #include "AliMCEventHandler.h" #include "AliMCEvent.h" #include "AliStack.h" #include "AliCentrality.h" #include "AliOADBContainer.h" #include "AliOADBMultSelection.h" #include "AliMultEstimator.h" #include "AliMultVariable.h" #include "AliMultInput.h" #include "AliMultSelection.h" #include "AliAODForwardMult.h" #include "AliForwardUtil.h" #include "AliCFContainer.h" #include "AliMultiplicity.h" #include "AliAODMCParticle.h" #include "AliESDcascade.h" #include "AliAODcascade.h" #include "AliESDUtils.h" #include "AliGenEventHeader.h" #include "AliAnalysisTaskSE.h" #include "AliAnalysisUtils.h" #include "AliEventCuts.h" #include "AliV0Result.h" #include "AliCascadeResult.h" #include "AliAnalysisTaskStrEffStudy.h" using std::cout; using std::endl; ClassImp(AliAnalysisTaskStrEffStudy) AliAnalysisTaskStrEffStudy::AliAnalysisTaskStrEffStudy() : AliAnalysisTaskSE(), fListHist(0), fListV0(0), fListCascade(0), fTreeEvent(0), fTreeV0(0), fTreeCascade(0), fPIDResponse(0), fESDtrackCuts(0), fESDtrackCutsITSsa2010(0), fESDtrackCutsGlobal2015(0), fUtils(0), fRand(0), //---> Flags controlling Event Tree output fkSaveEventTree ( kTRUE ), //no downscaling in this tree so far //---> Flags controlling V0 TTree output fkSaveV0Tree ( kTRUE ), fkDownScaleV0 ( kTRUE ), fDownScaleFactorV0 ( 0.001 ), fkPreselectDedx ( kFALSE ), fkPreselectPID ( kTRUE ), fkUseOnTheFlyV0Cascading( kFALSE ), fkDoImprovedCascadeVertexFinding(kFALSE), fkIfImprovedPerformInitialLinearPropag( kFALSE ), fkIfImprovedExtraPrecisionFactor ( 1.0 ), fkDebugWrongPIDForTracking ( kFALSE ), fkDebugBump( kFALSE ), fkDebugOOBPileup(kFALSE), fkDoExtraEvSels( kTRUE ), fPrecisionCutoffCascadeDCA(1e-4), fMaxIterationsCascadeDCA(27), //---> Flags controlling Cascade TTree output fkSaveCascadeTree ( kTRUE ), fkDownScaleCascade ( kTRUE ), fDownScaleFactorCascade ( 0.001 ), fMinPtToSave( 0.00 ) , fMaxPtToSave( 100.00 ) , //---> Flags controlling Vertexers fkRunVertexers ( kFALSE ), fkUseLightVertexer ( kTRUE ), fkDoV0Refit ( kTRUE ), fkExtraCleanup ( kTRUE ), fkSaveGoodTracks( kTRUE ), //---> Flag controlling trigger selection fTrigType(AliVEvent::kMB), //---> Variables for fTreeEvent fCentrality(0), fMVPileupFlag(kFALSE), fOOBPileupFlag(kFALSE), fNTOFClusters(-1), fNTOFMatches(-1), fNTracksITSsa2010(-1), fNTracksGlobal2015(-1), fNTracksGlobal2015TriggerPP(-1), fAmplitudeV0A(-1.), fAmplitudeV0C(-1.), fNHitsFMDA(-1.), fNHitsFMDC(-1.), //---> Variables for fTreeV0 fTreeVariablePosLength(0), fTreeVariableNegLength(0), fTreeVariablePosCrossedRows(0), fTreeVariableNegCrossedRows(0), fTreeVariablePosTrackStatus(0), fTreeVariableNegTrackStatus(0), fTreeVariablePosDxy(0), fTreeVariableNegDxy(0), fTreeVariablePosDz(0), fTreeVariableNegDz(0), fTreeVariableDcaV0Daughters(0), fTreeVariablePosPropagStatus(0), fTreeVariableNegPropagStatus(0), fTreeVariableV0Radius(0), fTreeVariableV0CosineOfPointingAngle(0), fTreeVariableDecayX(0), fTreeVariableDecayY(0), fTreeVariableDecayZ(0), fTreeVariableInvMassK0s(0), fTreeVariableInvMassLambda(0), fTreeVariableInvMassAntiLambda(0), fTreeVariablePID(0), fTreeVariablePIDPositive(0), fTreeVariablePIDNegative(0), fTreeVariablePtMC(0), fTreeVariableRapMC(0), //---> Variables for fTreeCascade fTreeCascVarCentrality(0), fTreeCascVarPosLength(0), fTreeCascVarNegLength(0), fTreeCascVarBachLength(0), fTreeCascVarPosCrossedRows(0), fTreeCascVarNegCrossedRows(0), fTreeCascVarBachCrossedRows(0), //Tracking flags fTreeCascVarPosTrackStatus(0), fTreeCascVarNegTrackStatus(0), fTreeCascVarBachTrackStatus(0), //DCAxy to PV fTreeCascVarPosDxy(0), fTreeCascVarNegDxy(0), fTreeCascVarBachDxy(0), //DCAz fTreeCascVarPosDz(0), fTreeCascVarNegDz(0), fTreeCascVarBachDz(0), fTreeCascVarDcaV0Daughters(0), fTreeCascVarNegPropagStatus(0), fTreeCascVarPosPropagStatus(0), fTreeCascVarV0Radius(0), fTreeCascVarV0DecayX(0), fTreeCascVarV0DecayY(0), fTreeCascVarV0DecayZ(0), fTreeCascVarV0DecayXMC(0), fTreeCascVarV0DecayYMC(0), fTreeCascVarV0DecayZMC(0), fTreeCascVarV0CosineOfPointingAngle(0), fTreeCascVarDCAV0ToPrimVtx(0), fTreeCascVarDCAxyV0ToPrimVtx(0), fTreeCascVarInvMassLambda(0), fTreeCascVarInvMassAntiLambda(0), fTreeCascVarDCACascDaughtersClassical(0), fTreeCascVarCascPropagationClassical(0), fTreeCascVarDecayX(0), fTreeCascVarDecayY(0), fTreeCascVarDecayZ(0), fTreeCascVarDecayXMC(0), fTreeCascVarDecayYMC(0), fTreeCascVarDecayZMC(0), fTreeCascVarCascCosPointingAngle(0), fTreeCascVarInvMassXiMinus(0), fTreeCascVarInvMassXiPlus(0), fTreeCascVarInvMassOmegaMinus(0), fTreeCascVarInvMassOmegaPlus(0), fTreeCascVarCascPropagationImprovedIterations(0), fTreeCascVarCascPropagationImprovedStatus(0), fTreeCascVarDCACascDaughtersImproved(0), fTreeCascVarImprovedDecayX(0), fTreeCascVarImprovedDecayY(0), fTreeCascVarImprovedDecayZ(0), fTreeCascVarImprovedCascCosPointingAngle(0), fTreeCascVarImprovedCascDCAxyToPV(0), fTreeCascVarImprovedCascDCAzToPV(0), fTreeCascVarImprovedInvMassXiMinus(0), fTreeCascVarImprovedInvMassXiPlus(0), fTreeCascVarImprovedInvMassOmegaMinus(0), fTreeCascVarImprovedInvMassOmegaPlus(0), fTreeCascVarPIDPositive(0), fTreeCascVarPIDNegative(0), fTreeCascVarPIDBachelor(0), fTreeCascVarPID(0), fTreeCascVarPtMC(0), fTreeCascVarRapMC(0), fTreeCascVarPosDistanceToTrueDecayPt(0), fTreeCascVarNegDistanceToTrueDecayPt(0), fTreeCascVarBachDistanceToTrueDecayPt(0), fTreeCascVarV0DistanceToTrueDecayPt(0), fTreeCascVarBachPropagationParameterClassical(0), fTreeCascVarBachPropagationParameterImproved(0), //Full momentum information fTreeCascVarNegPx(0), fTreeCascVarNegPy(0), fTreeCascVarNegPz(0), fTreeCascVarPosPx(0), fTreeCascVarPosPy(0), fTreeCascVarPosPz(0), fTreeCascVarBachPx(0), fTreeCascVarBachPy(0), fTreeCascVarBachPz(0), fTreeCascVarNegPxMC(0), fTreeCascVarNegPyMC(0), fTreeCascVarNegPzMC(0), fTreeCascVarPosPxMC(0), fTreeCascVarPosPyMC(0), fTreeCascVarPosPzMC(0), fTreeCascVarBachPxMC(0), fTreeCascVarBachPyMC(0), fTreeCascVarBachPzMC(0), //Histos fHistEventCounter(0), fHistCentrality(0), //V0s fHistGeneratedPtVsYVsCentralityK0Short(0), fHistGeneratedPtVsYVsCentralityLambda(0), fHistGeneratedPtVsYVsCentralityAntiLambda(0), //Cascades fHistGeneratedPtVsYVsCentralityXiMinus(0), fHistGeneratedPtVsYVsCentralityXiPlus(0), fHistGeneratedPtVsYVsCentralityOmegaMinus(0), fHistGeneratedPtVsYVsCentralityOmegaPlus(0) //------------------------------------------------ // Tree Variables { } AliAnalysisTaskStrEffStudy::AliAnalysisTaskStrEffStudy(Bool_t lSaveEventTree, Bool_t lSaveV0Tree, Bool_t lSaveCascadeTree, const char *name, TString lExtraOptions) : AliAnalysisTaskSE(name), fListHist(0), fListV0(0), fListCascade(0), fTreeEvent(0), fTreeV0(0), fTreeCascade(0), fPIDResponse(0), fESDtrackCuts(0), fESDtrackCutsITSsa2010(0), fESDtrackCutsGlobal2015(0), fUtils(0), fRand(0), //---> Flags controlling Event Tree output fkSaveEventTree ( kFALSE ), //no downscaling in this tree so far //---> Flags controlling V0 TTree output fkSaveV0Tree ( kTRUE ), fkDownScaleV0 ( kTRUE ), fDownScaleFactorV0 ( 0.001 ), fkPreselectDedx ( kFALSE ), fkPreselectPID ( kTRUE ), fkUseOnTheFlyV0Cascading( kFALSE ), fkDoImprovedCascadeVertexFinding(kFALSE), fkIfImprovedPerformInitialLinearPropag( kFALSE ), fkIfImprovedExtraPrecisionFactor ( 1.0 ), fkDebugWrongPIDForTracking ( kFALSE ), //also for cascades... fkDebugBump( kFALSE ), fkDebugOOBPileup(kFALSE), fkDoExtraEvSels( kTRUE ), fPrecisionCutoffCascadeDCA(1e-4), fMaxIterationsCascadeDCA(27), //---> Flags controlling Cascade TTree output fkSaveCascadeTree ( kTRUE ), fkDownScaleCascade ( kTRUE ), fDownScaleFactorCascade ( 0.001 ), fMinPtToSave( 0.00 ) , fMaxPtToSave( 100.00 ) , //---> Flags controlling Vertexers fkRunVertexers ( kFALSE ), fkUseLightVertexer ( kTRUE ), fkDoV0Refit ( kTRUE ), fkExtraCleanup ( kTRUE ), fkSaveGoodTracks( kTRUE ), //---> Flag controlling trigger selection fTrigType(AliVEvent::kMB), //---> Variables for fTreeEvent fCentrality(0), fMVPileupFlag(kFALSE), fOOBPileupFlag(kFALSE), fNTOFClusters(-1), fNTOFMatches(-1), fNTracksITSsa2010(-1), fNTracksGlobal2015(-1), fNTracksGlobal2015TriggerPP(-1), fAmplitudeV0A(-1.), fAmplitudeV0C(-1.), fNHitsFMDA(-1.), fNHitsFMDC(-1.), //---> Variables for fTreeV0 fTreeVariablePosLength(0), fTreeVariableNegLength(0), fTreeVariablePosCrossedRows(0), fTreeVariableNegCrossedRows(0), fTreeVariablePosTrackStatus(0), fTreeVariableNegTrackStatus(0), fTreeVariablePosDxy(0), fTreeVariableNegDxy(0), fTreeVariablePosDz(0), fTreeVariableNegDz(0), fTreeVariableDcaV0Daughters(0), fTreeVariablePosPropagStatus(0), fTreeVariableNegPropagStatus(0), fTreeVariableV0Radius(0), fTreeVariableV0CosineOfPointingAngle(0), fTreeVariableDecayX(0), fTreeVariableDecayY(0), fTreeVariableDecayZ(0), fTreeVariableInvMassK0s(0), fTreeVariableInvMassLambda(0), fTreeVariableInvMassAntiLambda(0), fTreeVariablePID(0), fTreeVariablePIDPositive(0), fTreeVariablePIDNegative(0), fTreeVariablePtMC(0), fTreeVariableRapMC(0), //---> Variables for fTreeCascade fTreeCascVarCentrality(0), fTreeCascVarPosLength(0), fTreeCascVarNegLength(0), fTreeCascVarBachLength(0), fTreeCascVarPosCrossedRows(0), fTreeCascVarNegCrossedRows(0), fTreeCascVarBachCrossedRows(0), //Tracking flags fTreeCascVarPosTrackStatus(0), fTreeCascVarNegTrackStatus(0), fTreeCascVarBachTrackStatus(0), //DCAxy to PV fTreeCascVarPosDxy(0), fTreeCascVarNegDxy(0), fTreeCascVarBachDxy(0), //DCAz fTreeCascVarPosDz(0), fTreeCascVarNegDz(0), fTreeCascVarBachDz(0), fTreeCascVarDcaV0Daughters(0), fTreeCascVarNegPropagStatus(0), fTreeCascVarPosPropagStatus(0), fTreeCascVarV0Radius(0), fTreeCascVarV0DecayX(0), fTreeCascVarV0DecayY(0), fTreeCascVarV0DecayZ(0), fTreeCascVarV0CosineOfPointingAngle(0), fTreeCascVarDCAV0ToPrimVtx(0), fTreeCascVarDCAxyV0ToPrimVtx(0), fTreeCascVarInvMassLambda(0), fTreeCascVarInvMassAntiLambda(0), fTreeCascVarDCACascDaughtersClassical(0), fTreeCascVarCascPropagationClassical(0), fTreeCascVarDecayX(0), fTreeCascVarDecayY(0), fTreeCascVarDecayZ(0), fTreeCascVarCascCosPointingAngle(0), fTreeCascVarInvMassXiMinus(0), fTreeCascVarInvMassXiPlus(0), fTreeCascVarInvMassOmegaMinus(0), fTreeCascVarInvMassOmegaPlus(0), fTreeCascVarCascPropagationImprovedIterations(0), fTreeCascVarCascPropagationImprovedStatus(0), fTreeCascVarDCACascDaughtersImproved(0), fTreeCascVarImprovedDecayX(0), fTreeCascVarImprovedDecayY(0), fTreeCascVarImprovedDecayZ(0), fTreeCascVarImprovedCascCosPointingAngle(0), fTreeCascVarImprovedCascDCAxyToPV(0), fTreeCascVarImprovedCascDCAzToPV(0), fTreeCascVarImprovedInvMassXiMinus(0), fTreeCascVarImprovedInvMassXiPlus(0), fTreeCascVarImprovedInvMassOmegaMinus(0), fTreeCascVarImprovedInvMassOmegaPlus(0), fTreeCascVarPIDPositive(0), fTreeCascVarPIDNegative(0), fTreeCascVarPIDBachelor(0), fTreeCascVarPID(0), fTreeCascVarPtMC(0), fTreeCascVarRapMC(0), fTreeCascVarPosDistanceToTrueDecayPt(0), fTreeCascVarNegDistanceToTrueDecayPt(0), fTreeCascVarBachDistanceToTrueDecayPt(0), fTreeCascVarV0DistanceToTrueDecayPt(0), fTreeCascVarBachPropagationParameterClassical(0), fTreeCascVarBachPropagationParameterImproved(0), //Full momentum information fTreeCascVarNegPx(0), fTreeCascVarNegPy(0), fTreeCascVarNegPz(0), fTreeCascVarPosPx(0), fTreeCascVarPosPy(0), fTreeCascVarPosPz(0), fTreeCascVarBachPx(0), fTreeCascVarBachPy(0), fTreeCascVarBachPz(0), fTreeCascVarNegPxMC(0), fTreeCascVarNegPyMC(0), fTreeCascVarNegPzMC(0), fTreeCascVarPosPxMC(0), fTreeCascVarPosPyMC(0), fTreeCascVarPosPzMC(0), fTreeCascVarBachPxMC(0), fTreeCascVarBachPyMC(0), fTreeCascVarBachPzMC(0), //Histos fHistEventCounter(0), fHistCentrality(0), //V0s fHistGeneratedPtVsYVsCentralityK0Short(0), fHistGeneratedPtVsYVsCentralityLambda(0), fHistGeneratedPtVsYVsCentralityAntiLambda(0), //Cascades fHistGeneratedPtVsYVsCentralityXiMinus(0), fHistGeneratedPtVsYVsCentralityXiPlus(0), fHistGeneratedPtVsYVsCentralityOmegaMinus(0), fHistGeneratedPtVsYVsCentralityOmegaPlus(0) { //Re-vertex: Will only apply for cascade candidates fV0VertexerSels[0] = 33. ; // max allowed chi2 fV0VertexerSels[1] = 0.02; // min allowed impact parameter for the 1st daughter (LHC09a4 : 0.05) fV0VertexerSels[2] = 0.02; // min allowed impact parameter for the 2nd daughter (LHC09a4 : 0.05) fV0VertexerSels[3] = 2.0 ; // max allowed DCA between the daughter tracks (LHC09a4 : 0.5) fV0VertexerSels[4] = 0.95; // min allowed cosine of V0's pointing angle (LHC09a4 : 0.99) fV0VertexerSels[5] = 1.0 ; // min radius of the fiducial volume (LHC09a4 : 0.2) fV0VertexerSels[6] = 200. ; // max radius of the fiducial volume (LHC09a4 : 100.0) fCascadeVertexerSels[0] = 33. ; // max allowed chi2 (same as PDC07) fCascadeVertexerSels[1] = 0.05 ; // min allowed V0 impact parameter (PDC07 : 0.05 / LHC09a4 : 0.025 ) fCascadeVertexerSels[2] = 0.010; // "window" around the Lambda mass (PDC07 : 0.008 / LHC09a4 : 0.010 ) fCascadeVertexerSels[3] = 0.03 ; // min allowed bachelor's impact parameter (PDC07 : 0.035 / LHC09a4 : 0.025 ) fCascadeVertexerSels[4] = 2.0 ; // max allowed DCA between the V0 and the bachelor (PDC07 : 0.1 / LHC09a4 : 0.2 ) fCascadeVertexerSels[5] = 0.95 ; // min allowed cosine of the cascade pointing angle (PDC07 : 0.9985 / LHC09a4 : 0.998 ) fCascadeVertexerSels[6] = 0.4 ; // min radius of the fiducial volume (PDC07 : 0.9 / LHC09a4 : 0.2 ) fCascadeVertexerSels[7] = 100. ; // max radius of the fiducial volume (PDC07 : 100 / LHC09a4 : 100 ) //[0]+[1]*TMath::Exp([2]*x)+[3]*TMath::Exp([4]*x) fLambdaMassMean[0]=1.116; //standard fixed fLambdaMassMean[1]=0.0; fLambdaMassMean[2]=0.0; fLambdaMassMean[3]=0.0; fLambdaMassMean[4]=0.0; //[0]+[1]*x+[2]*TMath::Exp([3]*x) fLambdaMassSigma[0]=0.002; //standard at roughly the integ val fLambdaMassSigma[1]=0.0; fLambdaMassSigma[2]=0.0; fLambdaMassSigma[3]=0.0; fkSaveEventTree = lSaveEventTree; fkSaveV0Tree = lSaveV0Tree; fkSaveCascadeTree = lSaveCascadeTree; //Standard output DefineOutput(1, TList::Class()); // Basic Histograms DefineOutput(2, TList::Class()); // V0 Histogram Output DefineOutput(3, TList::Class()); // Cascade Histogram Output //Optional output if (fkSaveEventTree) DefineOutput(4, TTree::Class()); // Event Tree output DefineOutput(5, TTree::Class()); // V0 Tree output DefineOutput(6, TTree::Class()); // Cascade Tree output //Special Debug Options (more to be added as needed) // A - Study Wrong PID for tracking bug // B - Study invariant mass *B*ump // C - Study OOB pileup in pp 2016 data if ( lExtraOptions.Contains("A") ) fkDebugWrongPIDForTracking = kTRUE; if ( lExtraOptions.Contains("B") ) fkDebugBump = kTRUE; if ( lExtraOptions.Contains("C") ) fkDebugOOBPileup = kTRUE; } AliAnalysisTaskStrEffStudy::~AliAnalysisTaskStrEffStudy() { //------------------------------------------------ // DESTRUCTOR //------------------------------------------------ //Destroy output objects if present if (fListHist) { delete fListHist; fListHist = 0x0; } if (fListV0) { delete fListV0; fListV0 = 0x0; } if (fListCascade) { delete fListCascade; fListCascade = 0x0; } if (fTreeEvent) { delete fTreeEvent; fTreeEvent = 0x0; } if (fTreeV0) { delete fTreeV0; fTreeV0 = 0x0; } if (fTreeCascade) { delete fTreeCascade; fTreeCascade = 0x0; } if (fUtils) { delete fUtils; fUtils = 0x0; } if (fRand) { delete fRand; fRand = 0x0; } } //________________________________________________________________________ void AliAnalysisTaskStrEffStudy::UserCreateOutputObjects() { //------------------------------------------------ // fTreeEvent: EbyE information //------------------------------------------------ fTreeEvent = new TTree("fTreeEvent","Event"); //Branch Definitions fTreeEvent->Branch("fCentrality",&fCentrality,"fCentrality/F"); fTreeEvent->Branch("fMVPileupFlag",&fMVPileupFlag,"fMVPileupFlag/O"); // if ( fkDebugOOBPileup ){ fTreeEvent->Branch("fOOBPileupFlag",&fOOBPileupFlag,"fOOBPileupFlag/O"); fTreeEvent->Branch("fNTOFClusters",&fNTOFClusters,"fNTOFClusters/I"); fTreeEvent->Branch("fNTOFMatches",&fNTOFMatches,"fNTOFMatches/I"); fTreeEvent->Branch("fNTracksITSsa2010",&fNTracksITSsa2010,"fNTracksITSsa2010/I"); fTreeEvent->Branch("fNTracksGlobal2015",&fNTracksGlobal2015,"fNTracksGlobal2015/I"); fTreeEvent->Branch("fNTracksGlobal2015TriggerPP",&fNTracksGlobal2015TriggerPP,"fNTracksGlobal2015TriggerPP/I"); fTreeEvent->Branch("fAmplitudeV0A",&fAmplitudeV0A,"fAmplitudeV0A/F"); fTreeEvent->Branch("fAmplitudeV0C",&fAmplitudeV0C,"fAmplitudeV0C/F"); fTreeEvent->Branch("fNHitsFMDA",&fNHitsFMDA,"fNHitsFMDA/F"); fTreeEvent->Branch("fNHitsFMDC",&fNHitsFMDC,"fNHitsFMDC/F"); } //------------------------------------------------ // fTreeV0: V0 Candidate Information //------------------------------------------------ //Create Basic V0 Output Tree fTreeV0 = new TTree( "fTreeV0", "Findable V0 Candidates"); //-----------BASIC-INFO--------------------------- fTreeV0->Branch("fTreeVariablePosLength",&fTreeVariablePosLength,"fTreeVariablePosLength/F"); fTreeV0->Branch("fTreeVariableNegLength",&fTreeVariableNegLength,"fTreeVariableNegLength/F"); fTreeV0->Branch("fTreeVariablePosCrossedRows",&fTreeVariablePosCrossedRows,"fTreeVariablePosCrossedRows/F"); fTreeV0->Branch("fTreeVariableNegCrossedRows",&fTreeVariableNegCrossedRows,"fTreeVariableNegCrossedRows/F"); fTreeV0->Branch("fTreeVariableNegTrackStatus",&fTreeVariableNegTrackStatus,"fTreeVariableNegTrackStatus/l"); fTreeV0->Branch("fTreeVariablePosTrackStatus",&fTreeVariablePosTrackStatus,"fTreeVariablePosTrackStatus/l"); fTreeV0->Branch("fTreeVariablePosDxy",&fTreeVariablePosDxy,"fTreeVariablePosDxy/F"); fTreeV0->Branch("fTreeVariableNegDxy",&fTreeVariableNegDxy,"fTreeVariableNegDxy/F"); fTreeV0->Branch("fTreeVariablePosDz",&fTreeVariablePosDz,"fTreeVariablePosDz/F"); fTreeV0->Branch("fTreeVariableNegDz",&fTreeVariableNegDz,"fTreeVariableNegDz/F"); fTreeV0->Branch("fTreeVariableDcaV0Daughters",&fTreeVariableDcaV0Daughters,"fTreeVariableDcaV0Daughters/F"); fTreeV0->Branch("fTreeVariablePosPropagStatus",&fTreeVariablePosPropagStatus,"fTreeVariablePosPropagStatus/O"); fTreeV0->Branch("fTreeVariableNegPropagStatus",&fTreeVariableNegPropagStatus,"fTreeVariableNegPropagStatus/O"); fTreeV0->Branch("fTreeVariableV0Radius",&fTreeVariableV0Radius,"fTreeVariableV0Radius/F"); fTreeV0->Branch("fTreeVariableV0CosineOfPointingAngle",&fTreeVariableV0CosineOfPointingAngle,"fTreeVariableV0CosineOfPointingAngle/F"); fTreeV0->Branch("fTreeVariableDecayX",&fTreeVariableDecayX,"fTreeVariableDecayX/F"); fTreeV0->Branch("fTreeVariableDecayY",&fTreeVariableDecayY,"fTreeVariableDecayY/F"); fTreeV0->Branch("fTreeVariableDecayZ",&fTreeVariableDecayZ,"fTreeVariableDecayZ/F"); fTreeV0->Branch("fTreeVariableInvMassK0s", &fTreeVariableInvMassK0s, "fTreeVariableInvMassK0s/F"); fTreeV0->Branch("fTreeVariableInvMassLambda", &fTreeVariableInvMassLambda, "fTreeVariableInvMassLambda/F"); fTreeV0->Branch("fTreeVariableInvMassAntiLambda",&fTreeVariableInvMassAntiLambda,"fTreeVariableInvMassAntiLambda/F"); fTreeV0->Branch("fTreeVariablePID",&fTreeVariablePID,"fTreeVariablePID/I"); fTreeV0->Branch("fTreeVariablePIDPositive",&fTreeVariablePIDPositive,"fTreeVariablePIDPositive/I"); fTreeV0->Branch("fTreeVariablePIDNegative",&fTreeVariablePIDNegative,"fTreeVariablePIDNegative/I"); fTreeV0->Branch("fTreeVariablePtMC",&fTreeVariablePtMC,"fTreeVariablePtMC/F"); fTreeV0->Branch("fTreeVariableRapMC",&fTreeVariableRapMC,"fTreeVariableRapMC/F"); //------------------------------------------------ //------------------------------------------------ // fTreeCascade Branch definitions - Cascade Tree //------------------------------------------------ //Create Cascade output tree fTreeCascade = new TTree("fTreeCascade","CascadeCandidates"); fTreeCascade->Branch("fTreeCascVarCentrality",&fTreeCascVarCentrality,"fTreeCascVarCentrality/F"); //-----------BASIC-INFO--------------------------- fTreeCascade->Branch("fTreeCascVarPosSign",&fTreeCascVarPosSign,"fTreeCascVarPosSign/I"); fTreeCascade->Branch("fTreeCascVarNegSign",&fTreeCascVarNegSign,"fTreeCascVarNegSign/I"); fTreeCascade->Branch("fTreeCascVarBachSign",&fTreeCascVarBachSign,"fTreeCascVarBachSign/I"); fTreeCascade->Branch("fTreeCascVarPosLength",&fTreeCascVarPosLength,"fTreeCascVarPosLength/F"); fTreeCascade->Branch("fTreeCascVarNegLength",&fTreeCascVarNegLength,"fTreeCascVarNegLength/F"); fTreeCascade->Branch("fTreeCascVarBachLength",&fTreeCascVarBachLength,"fTreeCascVarBachLength/F"); fTreeCascade->Branch("fTreeCascVarPosCrossedRows",&fTreeCascVarPosCrossedRows,"fTreeCascVarPosCrossedRows/F"); fTreeCascade->Branch("fTreeCascVarNegCrossedRows",&fTreeCascVarNegCrossedRows,"fTreeCascVarNegCrossedRows/F"); fTreeCascade->Branch("fTreeCascVarBachCrossedRows",&fTreeCascVarBachCrossedRows,"fTreeCascVarBachCrossedRows/F"); fTreeCascade->Branch("fTreeCascVarPosTrackStatus",&fTreeCascVarPosTrackStatus,"fTreeCascVarPosTrackStatus/l"); fTreeCascade->Branch("fTreeCascVarNegTrackStatus",&fTreeCascVarNegTrackStatus,"fTreeCascVarNegTrackStatus/l"); fTreeCascade->Branch("fTreeCascVarBachTrackStatus",&fTreeCascVarBachTrackStatus,"fTreeCascVarBachTrackStatus/l"); //DCAxy to PV fTreeCascade->Branch("fTreeCascVarPosDxy",&fTreeCascVarPosDxy,"fTreeCascVarPosDxy/F"); fTreeCascade->Branch("fTreeCascVarNegDxy",&fTreeCascVarNegDxy,"fTreeCascVarNegDxy/F"); fTreeCascade->Branch("fTreeCascVarBachDxy",&fTreeCascVarBachDxy,"fTreeCascVarBachDxy/F"); //DCAz fTreeCascade->Branch("fTreeCascVarPosDz",&fTreeCascVarPosDz,"fTreeCascVarPosDz/F"); fTreeCascade->Branch("fTreeCascVarNegDz",&fTreeCascVarNegDz,"fTreeCascVarNegDz/F"); fTreeCascade->Branch("fTreeCascVarBachDz",&fTreeCascVarBachDz,"fTreeCascVarBachDz/F"); fTreeCascade->Branch("fTreeCascVarDcaV0Daughters",&fTreeCascVarDcaV0Daughters,"fTreeCascVarDcaV0Daughters/F"); fTreeCascade->Branch("fTreeCascVarNegPropagStatus",&fTreeCascVarNegPropagStatus,"fTreeCascVarNegPropagStatus/O"); fTreeCascade->Branch("fTreeCascVarPosPropagStatus",&fTreeCascVarPosPropagStatus,"fTreeCascVarPosPropagStatus/O"); fTreeCascade->Branch("fTreeCascVarDcaV0Daughters",&fTreeCascVarDcaV0Daughters,"fTreeCascVarDcaV0Daughters/F"); fTreeCascade->Branch("fTreeCascVarV0DecayX",&fTreeCascVarV0DecayX,"fTreeCascVarV0DecayX/F"); fTreeCascade->Branch("fTreeCascVarV0DecayY",&fTreeCascVarV0DecayY,"fTreeCascVarV0DecayY/F"); fTreeCascade->Branch("fTreeCascVarV0DecayZ",&fTreeCascVarV0DecayZ,"fTreeCascVarV0DecayZ/F"); fTreeCascade->Branch("fTreeCascVarV0DecayXMC",&fTreeCascVarV0DecayXMC,"fTreeCascVarV0DecayXMC/F"); fTreeCascade->Branch("fTreeCascVarV0DecayYMC",&fTreeCascVarV0DecayYMC,"fTreeCascVarV0DecayYMC/F"); fTreeCascade->Branch("fTreeCascVarV0DecayZMC",&fTreeCascVarV0DecayZMC,"fTreeCascVarV0DecayZMC/F"); fTreeCascade->Branch("fTreeCascVarV0CosineOfPointingAngle",&fTreeCascVarV0CosineOfPointingAngle,"fTreeCascVarV0CosineOfPointingAngle/F"); fTreeCascade->Branch("fTreeCascVarDCAV0ToPrimVtx",&fTreeCascVarDCAV0ToPrimVtx,"fTreeCascVarDCAV0ToPrimVtx/F"); fTreeCascade->Branch("fTreeCascVarDCAxyV0ToPrimVtx",&fTreeCascVarDCAxyV0ToPrimVtx,"fTreeCascVarDCAxyV0ToPrimVtx/F"); fTreeCascade->Branch("fTreeCascVarInvMassLambda",&fTreeCascVarInvMassLambda,"fTreeCascVarInvMassLambda/F"); fTreeCascade->Branch("fTreeCascVarInvMassAntiLambda",&fTreeCascVarInvMassAntiLambda,"fTreeCascVarInvMassAntiLambda/F"); //CLASSICAL BACK-PROPAGATION VARIABLES fTreeCascade->Branch("fTreeCascVarDCACascDaughtersClassical",&fTreeCascVarDCACascDaughtersClassical,"fTreeCascVarDCACascDaughtersClassical/F"); fTreeCascade->Branch("fTreeCascVarCascPropagationClassical",&fTreeCascVarCascPropagationClassical,"fTreeCascVarCascPropagationClassical/O"); fTreeCascade->Branch("fTreeCascVarDecayX",&fTreeCascVarDecayX,"fTreeCascVarDecayX/F"); fTreeCascade->Branch("fTreeCascVarDecayY",&fTreeCascVarDecayY,"fTreeCascVarDecayY/F"); fTreeCascade->Branch("fTreeCascVarDecayZ",&fTreeCascVarDecayZ,"fTreeCascVarDecayZ/F"); fTreeCascade->Branch("fTreeCascVarDecayXMC",&fTreeCascVarDecayXMC,"fTreeCascVarDecayXMC/F"); fTreeCascade->Branch("fTreeCascVarDecayYMC",&fTreeCascVarDecayYMC,"fTreeCascVarDecayYMC/F"); fTreeCascade->Branch("fTreeCascVarDecayZMC",&fTreeCascVarDecayZMC,"fTreeCascVarDecayZMC/F"); fTreeCascade->Branch("fTreeCascVarCascCosPointingAngle",&fTreeCascVarCascCosPointingAngle,"fTreeCascVarCascCosPointingAngle/F"); fTreeCascade->Branch("fTreeCascVarInvMassXiMinus",&fTreeCascVarInvMassXiMinus,"fTreeCascVarInvMassXiMinus/F"); fTreeCascade->Branch("fTreeCascVarInvMassXiPlus",&fTreeCascVarInvMassXiPlus,"fTreeCascVarInvMassXiPlus/F"); fTreeCascade->Branch("fTreeCascVarInvMassOmegaMinus",&fTreeCascVarInvMassOmegaMinus,"fTreeCascVarInvMassOmegaMinus/F"); fTreeCascade->Branch("fTreeCascVarInvMassOmegaPlus",&fTreeCascVarInvMassOmegaPlus,"fTreeCascVarInvMassOmegaPlus/F"); //IMPROVED BACK-PROPAGATION VARIABLES fTreeCascade->Branch("fTreeCascVarCascPropagationImprovedIterations",&fTreeCascVarCascPropagationImprovedIterations,"fTreeCascVarCascPropagationImprovedIterations/I"); fTreeCascade->Branch("fTreeCascVarCascPropagationImprovedStatus",&fTreeCascVarCascPropagationImprovedStatus,"fTreeCascVarCascPropagationImprovedStatus/I"); fTreeCascade->Branch("fTreeCascVarDCACascDaughtersImproved",&fTreeCascVarDCACascDaughtersImproved,"fTreeCascVarDCACascDaughtersImproved/F"); fTreeCascade->Branch("fTreeCascVarImprovedDecayX",&fTreeCascVarImprovedDecayX,"fTreeCascVarImprovedDecayX/F"); fTreeCascade->Branch("fTreeCascVarImprovedDecayY",&fTreeCascVarImprovedDecayY,"fTreeCascVarImprovedDecayY/F"); fTreeCascade->Branch("fTreeCascVarImprovedDecayZ",&fTreeCascVarImprovedDecayZ,"fTreeCascVarImprovedDecayZ/F"); fTreeCascade->Branch("fTreeCascVarImprovedCascCosPointingAngle",&fTreeCascVarImprovedCascCosPointingAngle,"fTreeCascVarImprovedCascCosPointingAngle/F"); fTreeCascade->Branch("fTreeCascVarImprovedCascDCAxyToPV",&fTreeCascVarImprovedCascDCAxyToPV,"fTreeCascVarImprovedCascDCAxyToPV/F"); fTreeCascade->Branch("fTreeCascVarImprovedCascDCAzToPV",&fTreeCascVarImprovedCascDCAzToPV,"fTreeCascVarImprovedCascDCAzToPV/F"); fTreeCascade->Branch("fTreeCascVarImprovedInvMassXiMinus",&fTreeCascVarImprovedInvMassXiMinus,"fTreeCascVarImprovedInvMassXiMinus/F"); fTreeCascade->Branch("fTreeCascVarImprovedInvMassXiPlus",&fTreeCascVarImprovedInvMassXiPlus,"fTreeCascVarImprovedInvMassXiPlus/F"); fTreeCascade->Branch("fTreeCascVarImprovedInvMassOmegaMinus",&fTreeCascVarImprovedInvMassOmegaMinus,"fTreeCascVarImprovedInvMassOmegaMinus/F"); fTreeCascade->Branch("fTreeCascVarImprovedInvMassOmegaPlus",&fTreeCascVarImprovedInvMassOmegaPlus,"fTreeCascVarImprovedInvMassOmegaPlus/F"); //MC VARIABLES fTreeCascade->Branch("fTreeCascVarPIDPositive",&fTreeCascVarPIDPositive,"fTreeCascVarPIDPositive/I"); fTreeCascade->Branch("fTreeCascVarPIDNegative",&fTreeCascVarPIDNegative,"fTreeCascVarPIDNegative/I"); fTreeCascade->Branch("fTreeCascVarPIDBachelor",&fTreeCascVarPIDBachelor,"fTreeCascVarPIDBachelor/I"); fTreeCascade->Branch("fTreeCascVarPID",&fTreeCascVarPID,"fTreeCascVarPID/I"); fTreeCascade->Branch("fTreeCascVarPtMC",&fTreeCascVarPtMC,"fTreeCascVarPtMC/F"); fTreeCascade->Branch("fTreeCascVarRapMC",&fTreeCascVarRapMC,"fTreeCascVarRapMC/F"); fTreeCascade->Branch("fTreeCascVarPosDistanceToTrueDecayPt",&fTreeCascVarPosDistanceToTrueDecayPt,"fTreeCascVarPosDistanceToTrueDecayPt/F"); fTreeCascade->Branch("fTreeCascVarNegDistanceToTrueDecayPt",&fTreeCascVarNegDistanceToTrueDecayPt,"fTreeCascVarNegDistanceToTrueDecayPt/F"); fTreeCascade->Branch("fTreeCascVarBachDistanceToTrueDecayPt",&fTreeCascVarBachDistanceToTrueDecayPt,"fTreeCascVarBachDistanceToTrueDecayPt/F"); fTreeCascade->Branch("fTreeCascVarV0DistanceToTrueDecayPt",&fTreeCascVarV0DistanceToTrueDecayPt,"fTreeCascVarV0DistanceToTrueDecayPt/F"); fTreeCascade->Branch("fTreeCascVarBachPropagationParameterClassical",&fTreeCascVarBachPropagationParameterClassical,"fTreeCascVarBachPropagationParameterClassical/F"); fTreeCascade->Branch("fTreeCascVarBachPropagationParameterImproved",&fTreeCascVarBachPropagationParameterImproved,"fTreeCascVarBachPropagationParameterImproved/F"); //full momentum info fTreeCascade->Branch("fTreeCascVarPosPx",&fTreeCascVarPosPx,"fTreeCascVarPosPx/F"); fTreeCascade->Branch("fTreeCascVarPosPy",&fTreeCascVarPosPy,"fTreeCascVarPosPy/F"); fTreeCascade->Branch("fTreeCascVarPosPz",&fTreeCascVarPosPz,"fTreeCascVarPosPz/F"); fTreeCascade->Branch("fTreeCascVarNegPx",&fTreeCascVarNegPx,"fTreeCascVarNegPx/F"); fTreeCascade->Branch("fTreeCascVarNegPy",&fTreeCascVarNegPy,"fTreeCascVarNegPy/F"); fTreeCascade->Branch("fTreeCascVarNegPz",&fTreeCascVarNegPz,"fTreeCascVarNegPz/F"); fTreeCascade->Branch("fTreeCascVarBachPx",&fTreeCascVarBachPx,"fTreeCascVarBachPx/F"); fTreeCascade->Branch("fTreeCascVarBachPy",&fTreeCascVarBachPy,"fTreeCascVarBachPy/F"); fTreeCascade->Branch("fTreeCascVarBachPz",&fTreeCascVarBachPz,"fTreeCascVarBachPz/F"); fTreeCascade->Branch("fTreeCascVarPosPxMC",&fTreeCascVarPosPxMC,"fTreeCascVarPosPxMC/F"); fTreeCascade->Branch("fTreeCascVarPosPyMC",&fTreeCascVarPosPyMC,"fTreeCascVarPosPyMC/F"); fTreeCascade->Branch("fTreeCascVarPosPzMC",&fTreeCascVarPosPzMC,"fTreeCascVarPosPzMC/F"); fTreeCascade->Branch("fTreeCascVarNegPxMC",&fTreeCascVarNegPxMC,"fTreeCascVarNegPxMC/F"); fTreeCascade->Branch("fTreeCascVarNegPyMC",&fTreeCascVarNegPyMC,"fTreeCascVarNegPyMC/F"); fTreeCascade->Branch("fTreeCascVarNegPzMC",&fTreeCascVarNegPzMC,"fTreeCascVarNegPzMC/F"); fTreeCascade->Branch("fTreeCascVarBachPxMC",&fTreeCascVarBachPxMC,"fTreeCascVarBachPxMC/F"); fTreeCascade->Branch("fTreeCascVarBachPyMC",&fTreeCascVarBachPyMC,"fTreeCascVarBachPyMC/F"); fTreeCascade->Branch("fTreeCascVarBachPzMC",&fTreeCascVarBachPzMC,"fTreeCascVarBachPzMC/F"); //------------------------------------------------ //------------------------------------------------ // Particle Identification Setup //------------------------------------------------ AliAnalysisManager *man=AliAnalysisManager::GetAnalysisManager(); AliInputEventHandler* inputHandler = (AliInputEventHandler*) (man->GetInputEventHandler()); fPIDResponse = inputHandler->GetPIDResponse(); inputHandler->SetNeedField(); // Multiplicity if(! fESDtrackCuts ) { fESDtrackCuts = AliESDtrackCuts::GetStandardITSTPCTrackCuts2010(kTRUE,kFALSE); fESDtrackCuts->SetPtRange(0.15); // adding pt cut fESDtrackCuts->SetEtaRange(-1.0, 1.0); } //Analysis Utils if(! fUtils ) { fUtils = new AliAnalysisUtils(); } if(! fRand ){ fRand = new TRandom3(); // From TRandom3 reference: // if seed is 0 (default value) a TUUID is generated and // used to fill the first 8 integers of the seed array. fRand->SetSeed(0); } // OOB Pileup in pp 2016 if( !fESDtrackCutsGlobal2015 && fkDebugOOBPileup ) { fESDtrackCutsGlobal2015 = AliESDtrackCuts::GetStandardITSTPCTrackCuts2015PbPb(kTRUE,kFALSE); //Initial set of cuts - to be adjusted fESDtrackCutsGlobal2015->SetPtRange(0.15); fESDtrackCutsGlobal2015->SetEtaRange(-1.0, 1.0); } if( !fESDtrackCutsITSsa2010 && fkDebugOOBPileup ) { fESDtrackCutsITSsa2010 = AliESDtrackCuts::GetStandardITSSATrackCuts2010(); } //------------------------------------------------ // V0 Multiplicity Histograms //------------------------------------------------ // Create histograms fListHist = new TList(); fListHist->SetOwner(); // See http://root.cern.ch/root/html/TCollection.html#TCollection:SetOwner fEventCuts.AddQAplotsToList(fListHist); if(! fHistEventCounter ) { //Histogram Output: Event-by-Event fHistEventCounter = new TH1D( "fHistEventCounter", ";Evt. Sel. Step;Count",2,0,2); fHistEventCounter->GetXaxis()->SetBinLabel(1, "Processed"); fHistEventCounter->GetXaxis()->SetBinLabel(2, "Selected"); fListHist->Add(fHistEventCounter); } if(! fHistCentrality ) { //Histogram Output: Event-by-Event fHistCentrality = new TH1D( "fHistCentrality", "WARNING: no pileup rejection applied!;Centrality;Event Count",100,0,100); fListHist->Add(fHistCentrality); } if(! fHistGeneratedPtVsYVsCentralityK0Short ) { //Histogram Output: Efficiency Denominator fHistGeneratedPtVsYVsCentralityK0Short = new TH3D( "fHistGeneratedPtVsYVsCentralityK0Short", ";pT;y;centrality",500,0,25,40,-1.0,1.0,100,0,100); fListHist->Add(fHistGeneratedPtVsYVsCentralityK0Short); } if(! fHistGeneratedPtVsYVsCentralityLambda ) { //Histogram Output: Efficiency Denominator fHistGeneratedPtVsYVsCentralityLambda = new TH3D( "fHistGeneratedPtVsYVsCentralityLambda", ";pT;y;centrality",500,0,25,40,-1.0,1.0,100,0,100); fListHist->Add(fHistGeneratedPtVsYVsCentralityLambda); } if(! fHistGeneratedPtVsYVsCentralityAntiLambda ) { //Histogram Output: Efficiency Denominator fHistGeneratedPtVsYVsCentralityAntiLambda = new TH3D( "fHistGeneratedPtVsYVsCentralityAntiLambda", ";pT;y;centrality",500,0,25,40,-1.0,1.0,100,0,100); fListHist->Add(fHistGeneratedPtVsYVsCentralityAntiLambda); } if(! fHistGeneratedPtVsYVsCentralityXiMinus ) { //Histogram Output: Efficiency Denominator fHistGeneratedPtVsYVsCentralityXiMinus = new TH3D( "fHistGeneratedPtVsYVsCentralityXiMinus", ";pT;y;centrality",500,0,25,40,-1.0,1.0,100,0,100); fListHist->Add(fHistGeneratedPtVsYVsCentralityXiMinus); } if(! fHistGeneratedPtVsYVsCentralityXiPlus ) { //Histogram Output: Efficiency Denominator fHistGeneratedPtVsYVsCentralityXiPlus = new TH3D( "fHistGeneratedPtVsYVsCentralityXiPlus", ";pT;y;centrality",500,0,25,40,-1.0,1.0,100,0,100); fListHist->Add(fHistGeneratedPtVsYVsCentralityXiPlus); } if(! fHistGeneratedPtVsYVsCentralityOmegaMinus ) { //Histogram Output: Efficiency Denominator fHistGeneratedPtVsYVsCentralityOmegaMinus = new TH3D( "fHistGeneratedPtVsYVsCentralityOmegaMinus", ";pT;y;centrality",500,0,25,40,-1.0,1.0,100,0,100); fListHist->Add(fHistGeneratedPtVsYVsCentralityOmegaMinus); } if(! fHistGeneratedPtVsYVsCentralityOmegaPlus ) { //Histogram Output: Efficiency Denominator fHistGeneratedPtVsYVsCentralityOmegaPlus = new TH3D( "fHistGeneratedPtVsYVsCentralityOmegaPlus", ";pT;y;centrality",500,0,25,40,-1.0,1.0,100,0,100); fListHist->Add(fHistGeneratedPtVsYVsCentralityOmegaPlus); } //Superlight mode output if ( !fListV0 ){ fListV0 = new TList(); fListV0->SetOwner(); } if ( !fListCascade ){ //Superlight mode output fListCascade = new TList(); fListCascade->SetOwner(); } //Regular Output: Slots 1, 2, 3 PostData(1, fListHist ); PostData(2, fListV0 ); PostData(3, fListCascade ); //TTree Objects: Slots 4, 5, 6 PostData(4, fTreeEvent ); PostData(5, fTreeV0 ); PostData(6, fTreeCascade ); }// end UserCreateOutputObjects //________________________________________________________________________ void AliAnalysisTaskStrEffStudy::UserExec(Option_t *) { // Main loop // Called for each event AliESDEvent *lESDevent = 0x0; AliMCEvent *lMCevent = 0x0; AliStack *lMCstack = 0x0; // Connect to the InputEvent // After these lines, we should have an ESD/AOD event + the number of V0s in it. // Appropriate for ESD analysis! lESDevent = dynamic_cast<AliESDEvent*>( InputEvent() ); if (!lESDevent) { AliWarning("ERROR: lESDevent not available \n"); return; } //================================================= // Monte Carlo-related information lMCevent = MCEvent(); if (!lMCevent) { Printf("ERROR: Could not retrieve MC event \n"); cout << "Name of the file with pb :" << fInputHandler->GetTree()->GetCurrentFile()->GetName() << endl; return; } lMCstack = lMCevent->Stack(); if (!lMCstack) { Printf("ERROR: Could not retrieve MC stack \n"); cout << "Name of the file with pb :" << fInputHandler->GetTree()->GetCurrentFile()->GetName() << endl; return; } //================================================= //Get VZERO Information for multiplicity later AliVVZERO* esdV0 = lESDevent->GetVZEROData(); if (!esdV0) { AliError("AliVVZERO not available"); return; } Double_t lMagneticField = -10; lMagneticField = lESDevent->GetMagneticField( ); //------------------------------------------------ // Event Selection --- // --- Performed entirely via AliPPVsMultUtils // (except removal of incomplete events and SPDClusterVsTracklets cut) //------------------------------------------------ //Copy-paste of steps done in AliAnalysisTaskSkeleton fHistEventCounter->Fill(0.5); //------------------------------------------------ // Primary Vertex Requirements Section: // ---> pp: has vertex, |z|<10cm //------------------------------------------------ //classical Proton-proton like selection const AliESDVertex *lPrimaryBestESDVtx = lESDevent->GetPrimaryVertex(); const AliESDVertex *lPrimaryTrackingESDVtx = lESDevent->GetPrimaryVertexTracks(); const AliESDVertex *lPrimarySPDVtx = lESDevent->GetPrimaryVertexSPD(); Double_t lBestPrimaryVtxPos[3] = {-100.0, -100.0, -100.0}; lPrimaryBestESDVtx->GetXYZ( lBestPrimaryVtxPos ); //------------------------------------------------ // Multiplicity Information Acquistion //------------------------------------------------ Float_t lPercentile = 500; Float_t lPercentileEmbeddedSelection = 500; Int_t lEvSelCode = 100; AliMultSelection *MultSelection = (AliMultSelection*) lESDevent -> FindListObject("MultSelection"); if( !MultSelection) { //If you get this warning (and lPercentiles 300) please check that the AliMultSelectionTask actually ran (before your task) AliWarning("AliMultSelection object not found!"); } else { //V0M Multiplicity Percentile lPercentile = MultSelection->GetMultiplicityPercentile("V0M"); lPercentileEmbeddedSelection = MultSelection->GetMultiplicityPercentile("V0M", kTRUE ); //Event Selection Code lEvSelCode = MultSelection->GetEvSelCode(); } //just ask AliMultSelection. It will know. fMVPileupFlag = kFALSE; fMVPileupFlag = MultSelection->GetThisEventIsNotPileupMV(); fCentrality = lPercentile; //Let's find out why efficiency is so centrality dependent, please fTreeCascVarCentrality = lPercentile; if( lEvSelCode != 0 ) { PostData(1, fListHist ); PostData(2, fListV0 ); PostData(3, fListCascade ); PostData(4, fTreeEvent ); PostData(5, fTreeV0 ); PostData(6, fTreeCascade ); return; } AliVEvent *ev = InputEvent(); if( fkDoExtraEvSels ) { if( !fEventCuts.AcceptEvent(ev) ) { PostData(1, fListHist ); PostData(2, fListV0 ); PostData(3, fListCascade ); PostData(4, fTreeEvent ); PostData(5, fTreeV0 ); PostData(6, fTreeCascade ); return; } } fHistEventCounter->Fill(1.5); //Fill centrality histogram fHistCentrality->Fill(fCentrality); //Event-level fill if ( fkSaveEventTree ) fTreeEvent->Fill() ; //STOP HERE if skipping event selections (no point in doing the rest...) //------------------------------------------------ //----- Loop on Generated Particles -------------- Int_t lThisPDG = 0; Double_t lThisRap = 0; Double_t lThisPt = 0; for (Int_t ilab = 0; ilab < (lMCstack->GetNtrack()); ilab++) { // This is the begining of the loop on tracks TParticle* lPart = 0x0; lPart = lMCstack->Particle( ilab ); if(!lPart) { Printf("Generated loop %d - MC TParticle pointer to current stack particle = 0x0 ! Skip ...\n", ilab ); continue; } lThisPDG = lPart->GetPdgCode(); //This if is necessary in some situations (rapidity calculation and PYTHIA junctions, etc) if ( (TMath::Abs(lThisPDG) == 3312) || (TMath::Abs(lThisPDG) == 3334) || (TMath::Abs(lThisPDG) == 3122) || lThisPDG == 310 ) { lThisRap = MyRapidity(lPart->Energy(),lPart->Pz()); lThisPt = lPart->Pt(); //Use Physical Primaries only for filling These Histos if ( lMCstack->IsPhysicalPrimary(ilab)!=kTRUE ) continue; if( lThisPDG == 310 ) { fHistGeneratedPtVsYVsCentralityK0Short -> Fill (lThisPt, lThisRap, lPercentileEmbeddedSelection); } if( lThisPDG == 3122 ) { fHistGeneratedPtVsYVsCentralityLambda -> Fill (lThisPt, lThisRap, lPercentileEmbeddedSelection); } if( lThisPDG == -3122 ) { fHistGeneratedPtVsYVsCentralityAntiLambda -> Fill (lThisPt, lThisRap, lPercentileEmbeddedSelection); } if( lThisPDG == 3312 ) { fHistGeneratedPtVsYVsCentralityXiMinus -> Fill (lThisPt, lThisRap, lPercentileEmbeddedSelection); } if( lThisPDG == -3312 ) { fHistGeneratedPtVsYVsCentralityXiPlus -> Fill (lThisPt, lThisRap, lPercentileEmbeddedSelection); } if( lThisPDG == 3334 ) { fHistGeneratedPtVsYVsCentralityOmegaMinus -> Fill (lThisPt, lThisRap, lPercentileEmbeddedSelection); } if( lThisPDG == -3334 ) { fHistGeneratedPtVsYVsCentralityOmegaPlus -> Fill (lThisPt, lThisRap, lPercentileEmbeddedSelection); } } }//End of loop on tracks //----- End Loop on Cascades ------------------------------------------------------------ //------------------------------------------------ // Fill V0 Tree as needed //------------------------------------------------ //Variable definition Int_t lOnFlyStatus = 0;// nv0sOn = 0, nv0sOff = 0; Double_t lChi2V0 = 0; Double_t lDcaV0Daughters = 0, lDcaV0ToPrimVertex = 0; Double_t lDcaPosToPrimVertex = 0, lDcaNegToPrimVertex = 0; Double_t lV0CosineOfPointingAngle = 0; Double_t lV0Radius = 0, lPt = 0; Double_t lRapK0Short = 0, lRapLambda = 0; Double_t lInvMassK0s = 0, lInvMassLambda = 0, lInvMassAntiLambda = 0; Double_t lAlphaV0 = 0, lPtArmV0 = 0; Double_t fMinV0Pt = 0; Double_t fMaxV0Pt = 100; //------------------------------------------------- // V0s from scratch: locate findable V0 candidates //------------------------------------------------- //Particles of interest Int_t lV0Types[3] = { 310, 3122, -3122}; Int_t lV0TypesPDau[3] = { 211, 2212, 211}; Int_t lV0TypesNDau[3] = {-211, -211, -2212}; //Number of tracks Long_t lNTracks = lESDevent->GetNumberOfTracks(); Double_t b = lESDevent->GetMagneticField(); //pos/neg daughters TArrayI lTrackArray (lNTracks); TArrayI lTrackMotherArray(lNTracks); Long_t nTracksOfInterest = 0; //____________________________________________________________________________ //Step 1: establish list of tracks coming from desired type for(Long_t iTrack = 0; iTrack<lNTracks; iTrack++){ AliESDtrack *esdTrack = lESDevent->GetTrack(iTrack); if(!esdTrack) continue; Int_t lLabel = (Int_t) TMath::Abs( esdTrack->GetLabel() ); TParticle* lParticle = lMCstack->Particle( lLabel ); Int_t lLabelMother = lParticle->GetFirstMother(); if( lLabelMother < 0 ) continue; //Do not select on primaries so that this list can be used for cascades too //if( lMCstack->IsPhysicalPrimary(lLabelMother) ) continue; TParticle *lParticleMother = lMCstack->Particle( lLabelMother ); Int_t lParticleMotherPDG = lParticleMother->GetPdgCode(); //Skip three-body decays and the like if ( lParticleMother->GetNDaughters()!=2 ) continue; Bool_t lOfDesiredType = kFALSE; for(Int_t iType=0; iType<3; iType++){ if( lParticleMotherPDG == lV0Types[iType] ) lOfDesiredType = kTRUE; } if( !lOfDesiredType ) continue; //If here: this is a daughter of a mother particle of desired type, add lTrackArray [nTracksOfInterest] = iTrack; lTrackMotherArray [nTracksOfInterest] = lLabelMother; nTracksOfInterest++; } TArrayI lPosTrackArray (lNTracks); TArrayI lNegTrackArray (lNTracks); Long_t lFindableV0s = 0; //____________________________________________________________________________ //Step 2: determine findable V0s: look for pairs having shared mother label for(Long_t iTrack = 0; iTrack<nTracksOfInterest; iTrack++){ //Start nested loop from iTrack+1: avoid permutations + combination with self for(Long_t jTrack = iTrack+1; jTrack<nTracksOfInterest; jTrack++){ if( lTrackMotherArray[iTrack]==lTrackMotherArray[jTrack]){ //This is a findable V0! Yay! Check daughters before indexing AliESDtrack *esdTrack1 = lESDevent->GetTrack( lTrackArray[iTrack] ); AliESDtrack *esdTrack2 = lESDevent->GetTrack( lTrackArray[jTrack] ); if( esdTrack1->GetSign() < 0 && esdTrack2->GetSign() < 0 ) continue; if( esdTrack1->GetSign() > 0 && esdTrack2->GetSign() > 0 ) continue; //1 = Positive, 2 = Negative case if( esdTrack1->GetSign() > 0 && esdTrack2->GetSign() < 0 ){ lPosTrackArray[lFindableV0s] = lTrackArray[iTrack]; lNegTrackArray[lFindableV0s] = lTrackArray[jTrack]; lFindableV0s++; //add this to findable }else{ lPosTrackArray[lFindableV0s] = lTrackArray[jTrack]; lNegTrackArray[lFindableV0s] = lTrackArray[iTrack]; lFindableV0s++; //add this to findable } } } } //____________________________________________________________________________ //Step 3: Loop over findable V0s and save their relevant characteristics for(Long_t iV0 = 0; iV0<lFindableV0s; iV0++){ //Get the two tracks we're talking about AliESDtrack *esdTrackPos = lESDevent->GetTrack( lPosTrackArray[iV0] ); AliESDtrack *esdTrackNeg = lESDevent->GetTrack( lNegTrackArray[iV0] ); //----------------------------------------------------------------- //3a: get basic track characteristics fTreeVariablePosLength = -1; fTreeVariableNegLength = -1; if( esdTrackPos->GetInnerParam() ) fTreeVariablePosLength = esdTrackPos->GetLengthInActiveZone(1, 2.0, 220.0, lESDevent->GetMagneticField()); if( esdTrackNeg->GetInnerParam() ) fTreeVariableNegLength = esdTrackNeg->GetLengthInActiveZone(1, 2.0, 220.0, lESDevent->GetMagneticField()); fTreeVariablePosCrossedRows = esdTrackPos ->GetTPCClusterInfo(2,1); fTreeVariableNegCrossedRows = esdTrackNeg ->GetTPCClusterInfo(2,1); //Tracking flags fTreeVariablePosTrackStatus = esdTrackPos->GetStatus(); fTreeVariableNegTrackStatus = esdTrackNeg->GetStatus(); //DCAxy to PV fTreeVariablePosDxy = TMath::Abs(esdTrackPos->GetD(lBestPrimaryVtxPos[0], lBestPrimaryVtxPos[1], lMagneticField) ); fTreeVariableNegDxy = TMath::Abs(esdTrackNeg->GetD(lBestPrimaryVtxPos[0], lBestPrimaryVtxPos[1], lMagneticField) ); //DCAz Float_t dz[2]; esdTrackPos->GetDZ(lBestPrimaryVtxPos[0],lBestPrimaryVtxPos[1],lBestPrimaryVtxPos[2], lMagneticField, dz ); fTreeVariablePosDz = dz[1]; esdTrackNeg->GetDZ(lBestPrimaryVtxPos[0],lBestPrimaryVtxPos[1],lBestPrimaryVtxPos[2], lMagneticField, dz ); fTreeVariableNegDz = dz[1]; //----------------------------------------------------------------- //3b: Do V0 combination and see if it works, please //Step 1: propagate to DCA fTreeVariableDcaV0Daughters = -1; Double_t xn, xp, dca=esdTrackNeg->GetDCA(esdTrackPos,lMagneticField,xn,xp); //Correct for beam pipe material //Warning: this is an unfinished implementation and should not do much at this stage AliExternalTrackParam nt(*esdTrackNeg), pt(*esdTrackPos); Bool_t corrected=kFALSE; if ((nt.GetX() > 3.) && (xn < 3.)) { //correct for the beam pipe material corrected=kTRUE; } if ((pt.GetX() > 3.) && (xp < 3.)) { //correct for the beam pipe material corrected=kTRUE; } if (corrected) { dca=nt.GetDCA(&pt,lMagneticField,xn,xp); } fTreeVariableDcaV0Daughters = dca; //Pass to TTree object, please //Actual propagation fTreeVariableNegPropagStatus = nt.PropagateTo(xn,lMagneticField); fTreeVariablePosPropagStatus = pt.PropagateTo(xp,lMagneticField); //Step 2: Attempt creation of a V0 vertex in these conditions AliESDv0 vertex(nt,lNegTrackArray[iV0],pt,lPosTrackArray[iV0]); //Get 2D decay radius from V0 vertex Double_t x=vertex.Xv(), y=vertex.Yv(); Double_t r2D = TMath::Sqrt(x*x + y*y); fTreeVariableV0Radius = r2D; //Get Estimated decay position fTreeVariableDecayX = x; fTreeVariableDecayY = y; fTreeVariableDecayZ = vertex.Zv(); //Get Cosine of pointing angle Float_t cpa=vertex.GetV0CosineOfPointingAngle(lBestPrimaryVtxPos[0],lBestPrimaryVtxPos[1],lBestPrimaryVtxPos[2]); fTreeVariableV0CosineOfPointingAngle = cpa; //Final step: get estimated masses under different mass hypotheses vertex.ChangeMassHypothesis(310); fTreeVariableInvMassK0s = vertex.GetEffMass(); vertex.ChangeMassHypothesis(3122); fTreeVariableInvMassLambda = vertex.GetEffMass(); vertex.ChangeMassHypothesis(-3122); fTreeVariableInvMassAntiLambda = vertex.GetEffMass(); //----------------------------------------------------------------- //3c: Get perfect MC information for bookkeeping Int_t lblPosV0Dghter = (Int_t) TMath::Abs( esdTrackPos->GetLabel() ); Int_t lblNegV0Dghter = (Int_t) TMath::Abs( esdTrackNeg->GetLabel() ); TParticle* mcPosV0Dghter = lMCstack->Particle( lblPosV0Dghter ); TParticle* mcNegV0Dghter = lMCstack->Particle( lblNegV0Dghter ); fTreeVariablePIDPositive = mcPosV0Dghter -> GetPdgCode(); fTreeVariablePIDNegative = mcNegV0Dghter -> GetPdgCode(); Int_t lblMotherV0 = mcPosV0Dghter->GetFirstMother(); TParticle* pThisV0 = lMCstack->Particle( lblMotherV0 ); //Set tree variables fTreeVariablePID = pThisV0->GetPdgCode(); //PDG Code fTreeVariablePtMC = pThisV0->Pt(); //Perfect Pt fTreeVariableRapMC = pThisV0->Y(); //IMPORTANT: select only physical primaries, please if( ! lMCstack->IsPhysicalPrimary( lblMotherV0 ) ) continue; //won't fill TTree if( fkSaveGoodTracks ){ //...where good -> kTPCrefit, at least length zero (more still needed!) if ((fTreeVariablePosTrackStatus&AliESDtrack::kTPCrefit)==0) continue; if ((fTreeVariableNegTrackStatus&AliESDtrack::kTPCrefit)==0) continue; if(fTreeVariablePosLength<0) continue; if(fTreeVariableNegLength<0) continue; } //End step 3: fill findable ttree if( fkSaveV0Tree ) fTreeV0->Fill(); } //--] END V0 PART [------------------------------- //------------------------------------------------ // Cascades from scratch: locate findable cascades //------------------------------------------------ //Particles of interest Int_t lCascadeTypes[4] = {3312, -3312, 3334, -3334}; //pos/neg daughters TArrayI lBachelorArray (lNTracks); TArrayI lBachelorMotherArray(lNTracks); Long_t nBachelorsOfInterest = 0; //____________________________________________________________________________ //Step 1: establish list of bachelors from cascades for(Long_t iTrack = 0; iTrack<lNTracks; iTrack++){ AliESDtrack *esdTrack = lESDevent->GetTrack(iTrack); if(!esdTrack) continue; Int_t lLabel = (Int_t) TMath::Abs( esdTrack->GetLabel() ); TParticle* lParticle = lMCstack->Particle( lLabel ); Int_t lLabelMother = lParticle->GetFirstMother(); if( lLabelMother < 0 ) continue; //Only interested in tracks whose mother was a primary (cascade) if( !lMCstack->IsPhysicalPrimary(lLabelMother) ) continue; TParticle *lParticleMother = lMCstack->Particle( lLabelMother ); Int_t lParticleMotherPDG = lParticleMother->GetPdgCode(); //Skip three-body decays and the like (has to be bach+V0) if ( lParticleMother->GetNDaughters()!=2 ) continue; Bool_t lOfDesiredType = kFALSE; for(Int_t iType=0; iType<4; iType++){ if( lParticleMotherPDG == lCascadeTypes[iType] ) lOfDesiredType = kTRUE; } if( !lOfDesiredType ) continue; //If here: this is a daughter of a mother particle of desired type, add lBachelorArray [nBachelorsOfInterest] = iTrack; lBachelorMotherArray [nBachelorsOfInterest] = lLabelMother; nBachelorsOfInterest++; } cout<<"Findable bachelors: "<<nBachelorsOfInterest<<endl; TArrayI lCascPosTrackArray (lNTracks); TArrayI lCascNegTrackArray (lNTracks); TArrayI lCascBachTrackArray (lNTracks); Long_t lFindableCascades = 0; //____________________________________________________________________________ //Step 2: Loop over findable V0s and check if they share a mother with bach for(Long_t iV0 = 0; iV0<lFindableV0s; iV0++){ //Get the two tracks we're talking about AliESDtrack *esdTrackPos = lESDevent->GetTrack( lPosTrackArray[iV0] ); AliESDtrack *esdTrackNeg = lESDevent->GetTrack( lNegTrackArray[iV0] ); //3c: Get perfect MC information for bookkeeping Int_t lblPosV0Dghter = (Int_t) TMath::Abs( esdTrackPos->GetLabel() ); Int_t lblNegV0Dghter = (Int_t) TMath::Abs( esdTrackNeg->GetLabel() ); TParticle* mcPosV0Dghter = lMCstack->Particle( lblPosV0Dghter ); TParticle* mcNegV0Dghter = lMCstack->Particle( lblNegV0Dghter ); Int_t lblMotherV0 = mcPosV0Dghter->GetFirstMother(); TParticle* pThisV0 = lMCstack->Particle( lblMotherV0 ); //Only interested in lambdas if( TMath::Abs( pThisV0 -> GetPdgCode() ) != 3122 ) continue; Int_t lblGrandMotherV0 = pThisV0->GetFirstMother(); if( lblGrandMotherV0 < 0 ) continue; //Not a cascade TParticle* pV0Origin = lMCstack->Particle( lblGrandMotherV0 ); Int_t pV0OriginPDG = pV0Origin->GetPdgCode(); //Pre-filter on primaries if( ! lMCstack->IsPhysicalPrimary( lblGrandMotherV0 ) ) continue; //Check if this is actually from a real cascade Bool_t lOfDesiredType = kFALSE; for(Int_t iType=0; iType<4; iType++){ if( pV0OriginPDG == lCascadeTypes[iType] ) lOfDesiredType = kTRUE; } if( !lOfDesiredType ) continue; //Nested loop (all filters pre-applied already), combine with bach for(Long_t iBach=0; iBach<nBachelorsOfInterest; iBach++){ if( lblGrandMotherV0 == lBachelorMotherArray[iBach] ){ //Interesting! This is a valid cascade. Please save the track indices lCascNegTrackArray [lFindableCascades] = lNegTrackArray[iV0]; lCascPosTrackArray [lFindableCascades] = lPosTrackArray[iV0]; lCascBachTrackArray[lFindableCascades] = lBachelorArray[iBach]; lFindableCascades++; } } } cout<<"Findable Cascades: "<<lFindableCascades<<endl; //____________________________________________________________________________ //Step 3: Loop over findable cascades and determine their relevant characteristics for(Long_t iCasc = 0; iCasc<lFindableCascades; iCasc++){ //Get the three tracks we're talking about AliESDtrack *esdTrackPos = lESDevent->GetTrack( lCascPosTrackArray[iCasc] ); AliESDtrack *esdTrackNeg = lESDevent->GetTrack( lCascNegTrackArray[iCasc] ); AliESDtrack *esdTrackBach = lESDevent->GetTrack( lCascBachTrackArray[iCasc] ); fTreeCascVarNegPx = 0.0; fTreeCascVarNegPy = 0.0; fTreeCascVarNegPz = 0.0; fTreeCascVarPosPx = 0.0; fTreeCascVarPosPy = 0.0; fTreeCascVarPosPz = 0.0; fTreeCascVarBachPx = 0.0; fTreeCascVarBachPy = 0.0; fTreeCascVarBachPz = 0.0; fTreeCascVarNegPxMC = 0.0; fTreeCascVarNegPyMC = 0.0; fTreeCascVarNegPzMC = 0.0; fTreeCascVarPosPxMC = 0.0; fTreeCascVarPosPyMC = 0.0; fTreeCascVarPosPzMC = 0.0; fTreeCascVarBachPxMC = 0.0; fTreeCascVarBachPyMC = 0.0; fTreeCascVarBachPzMC = 0.0; //----------------------------------------------------------------- //3a: get basic track characteristics fTreeCascVarPosLength = -1; fTreeCascVarNegLength = -1; fTreeCascVarBachLength = -1; if( esdTrackPos->GetInnerParam() ) fTreeCascVarPosLength = esdTrackPos->GetLengthInActiveZone(1, 2.0, 220.0, lESDevent->GetMagneticField()); if( esdTrackNeg->GetInnerParam() ) fTreeCascVarNegLength = esdTrackNeg->GetLengthInActiveZone(1, 2.0, 220.0, lESDevent->GetMagneticField()); if( esdTrackBach->GetInnerParam() ) fTreeCascVarBachLength = esdTrackBach->GetLengthInActiveZone(1, 2.0, 220.0, lESDevent->GetMagneticField()); fTreeCascVarPosCrossedRows = esdTrackPos ->GetTPCClusterInfo(2,1); fTreeCascVarNegCrossedRows = esdTrackNeg ->GetTPCClusterInfo(2,1); fTreeCascVarBachCrossedRows = esdTrackBach ->GetTPCClusterInfo(2,1); //Tracking flags fTreeCascVarPosTrackStatus = esdTrackPos->GetStatus(); fTreeCascVarNegTrackStatus = esdTrackNeg->GetStatus(); fTreeCascVarBachTrackStatus = esdTrackBach->GetStatus(); //Charge fTreeCascVarPosSign = esdTrackPos -> GetSign(); fTreeCascVarNegSign = esdTrackNeg -> GetSign(); fTreeCascVarBachSign = esdTrackBach -> GetSign(); //DCAxy to PV fTreeCascVarPosDxy = TMath::Abs(esdTrackPos->GetD(lBestPrimaryVtxPos[0], lBestPrimaryVtxPos[1], lMagneticField) ); fTreeCascVarNegDxy = TMath::Abs(esdTrackNeg->GetD(lBestPrimaryVtxPos[0], lBestPrimaryVtxPos[1], lMagneticField) ); fTreeCascVarBachDxy = TMath::Abs(esdTrackBach->GetD(lBestPrimaryVtxPos[0], lBestPrimaryVtxPos[1], lMagneticField) ); //DCAz Float_t dztrack[2]; esdTrackPos->GetDZ(lBestPrimaryVtxPos[0],lBestPrimaryVtxPos[1],lBestPrimaryVtxPos[2], lMagneticField, dztrack ); fTreeCascVarPosDz = dztrack[1]; esdTrackNeg->GetDZ(lBestPrimaryVtxPos[0],lBestPrimaryVtxPos[1],lBestPrimaryVtxPos[2], lMagneticField, dztrack ); fTreeCascVarNegDz = dztrack[1]; esdTrackBach->GetDZ(lBestPrimaryVtxPos[0],lBestPrimaryVtxPos[1],lBestPrimaryVtxPos[2], lMagneticField, dztrack ); fTreeCascVarBachDz = dztrack[1]; //----------------------------------------------------------------- //3b: Do V0+cascade combination and see if it works, please //---] V0 PART [--------------------------------------------------- //Step 1: propagate to DCA fTreeCascVarDcaV0Daughters = -1; Double_t xn, xp, dca=esdTrackNeg->GetDCA(esdTrackPos,lMagneticField,xn,xp); //Correct for beam pipe material //Warning: this is an unfinished implementation and should not do much at this stage AliExternalTrackParam nt(*esdTrackNeg), pt(*esdTrackPos); Bool_t corrected=kFALSE; if ((nt.GetX() > 3.) && (xn < 3.)) { //correct for the beam pipe material corrected=kTRUE; } if ((pt.GetX() > 3.) && (xp < 3.)) { //correct for the beam pipe material corrected=kTRUE; } if (corrected) { dca=nt.GetDCA(&pt,lMagneticField,xn,xp); } fTreeCascVarDcaV0Daughters = dca; //Pass to TTree object, please //Actual propagation fTreeCascVarNegPropagStatus = nt.PropagateTo(xn,lMagneticField); fTreeCascVarPosPropagStatus = pt.PropagateTo(xp,lMagneticField); //Step 2: Attempt creation of a V0 vertex in these conditions AliESDv0 vertex(nt,lCascNegTrackArray[iCasc],pt,lCascPosTrackArray[iCasc]); //Get 2D decay radius from V0 vertex Double_t x=vertex.Xv(), y=vertex.Yv(); Double_t r2D = TMath::Sqrt(x*x + y*y); fTreeCascVarV0Radius = r2D; //Get Estimated decay position fTreeCascVarV0DecayX = x; fTreeCascVarV0DecayY = y; fTreeCascVarV0DecayZ = vertex.Zv(); //Get Cosine of pointing angle Float_t cpa=vertex.GetV0CosineOfPointingAngle(lBestPrimaryVtxPos[0],lBestPrimaryVtxPos[1],lBestPrimaryVtxPos[2]); fTreeCascVarV0CosineOfPointingAngle = cpa; //DCA to PV fTreeCascVarDCAV0ToPrimVtx = vertex.GetD(lBestPrimaryVtxPos[0],lBestPrimaryVtxPos[1],lBestPrimaryVtxPos[2]); fTreeCascVarDCAxyV0ToPrimVtx = vertex.GetD(lBestPrimaryVtxPos[0],lBestPrimaryVtxPos[1]); //Final step: get estimated masses under different mass hypotheses vertex.ChangeMassHypothesis(3122); fTreeCascVarInvMassLambda = vertex.GetEffMass(); vertex.ChangeMassHypothesis(-3122); fTreeCascVarInvMassAntiLambda = vertex.GetEffMass(); //---] Cascade PART [---------------------------------------------- //Step 1: propagation (CLASSICAL) AliESDv0 v0(vertex); AliESDv0 *pv0=&v0; AliExternalTrackParam bt(*esdTrackBach), *pbt=&bt; Double_t cascdca = PropagateToDCA(pv0,pbt,lESDevent,lMagneticField); fTreeCascVarDCACascDaughtersClassical = 1e+10; fTreeCascVarCascPropagationClassical = kFALSE; fTreeCascVarBachPropagationParameterClassical = -100; fTreeCascVarDecayX = -100; fTreeCascVarDecayY = -100; fTreeCascVarDecayZ = -100; fTreeCascVarCascCosPointingAngle = -100; fTreeCascVarInvMassXiMinus = -100; fTreeCascVarInvMassXiPlus = -100; fTreeCascVarInvMassOmegaMinus = -100; fTreeCascVarInvMassOmegaPlus = -100; //Check if propagation successful if (cascdca < 1e+32){ fTreeCascVarDCACascDaughtersClassical = cascdca; fTreeCascVarCascPropagationClassical = kTRUE; fTreeCascVarBachPropagationParameterClassical = pbt->GetX(); //Construct cascade AliESDcascade cascade(*pv0,*pbt,lCascBachTrackArray[iCasc]); //Decay Position Double_t xcasc,ycasc,zcasc; cascade.GetXYZcascade(xcasc,ycasc,zcasc); fTreeCascVarDecayX = xcasc; fTreeCascVarDecayY = ycasc; fTreeCascVarDecayZ = zcasc; fTreeCascVarCascCosPointingAngle = cascade.GetCascadeCosineOfPointingAngle(lBestPrimaryVtxPos[0],lBestPrimaryVtxPos[1],lBestPrimaryVtxPos[2]); Double_t lV0quality = 0.; cascade.ChangeMassHypothesis(lV0quality , 3312); fTreeCascVarInvMassXiMinus = cascade.GetEffMassXi(); cascade.ChangeMassHypothesis(lV0quality ,-3312); fTreeCascVarInvMassXiPlus = cascade.GetEffMassXi(); cascade.ChangeMassHypothesis(lV0quality , 3334); fTreeCascVarInvMassOmegaMinus = cascade.GetEffMassXi(); cascade.ChangeMassHypothesis(lV0quality ,-3334); fTreeCascVarInvMassOmegaPlus = cascade.GetEffMassXi(); Double_t lBMom[3], lNMom[3], lPMom[3]; cascade.GetBPxPyPz( lBMom[0], lBMom[1], lBMom[2] ); cascade.GetPPxPyPz( lPMom[0], lPMom[1], lPMom[2] ); cascade.GetNPxPyPz( lNMom[0], lNMom[1], lNMom[2] ); fTreeCascVarNegPx = lNMom[0]; fTreeCascVarNegPy = lNMom[1]; fTreeCascVarNegPz = lNMom[2]; fTreeCascVarPosPx = lPMom[0]; fTreeCascVarPosPy = lPMom[1]; fTreeCascVarPosPz = lPMom[2]; fTreeCascVarBachPx = lBMom[0]; fTreeCascVarBachPy = lBMom[1]; fTreeCascVarBachPz = lBMom[2]; } //+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ //Step 1 IMPROVED: Propagate one to each other using improved techniques //+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ //Status code fTreeCascVarCascPropagationImprovedStatus = 0; //started fTreeCascVarImprovedDecayX = -100; fTreeCascVarImprovedDecayY = -100; fTreeCascVarImprovedDecayZ = -100; fTreeCascVarImprovedCascCosPointingAngle = -100; fTreeCascVarImprovedCascDCAxyToPV = -100; fTreeCascVarImprovedCascDCAzToPV = -100; fTreeCascVarBachPropagationParameterImproved = -100; fTreeCascVarImprovedInvMassXiMinus = -100; fTreeCascVarImprovedInvMassXiPlus = -100; fTreeCascVarImprovedInvMassOmegaMinus = -100; fTreeCascVarImprovedInvMassOmegaPlus = -100; //Use copy AliESDv0 v0imp(vertex); AliESDv0 *pv0imp=&v0imp; AliExternalTrackParam btimp(*esdTrackBach), *pbtimp=&btimp; //Uncertainties: bachelor track as well as V0 //Harmonic mean-like: errors as weights to combine the errors (approx) Double_t dy2V0 = TMath::Power(1/(esdTrackPos->GetSigmaY2()+1e-8)+1/(esdTrackNeg->GetSigmaY2()+1e-8)+1e-8,-1); Double_t dz2V0 = TMath::Power(1/(esdTrackPos->GetSigmaZ2()+1e-8)+1/(esdTrackNeg->GetSigmaZ2()+1e-8)+1e-8,-1); Double_t dy2=pbtimp->GetSigmaY2() + dy2V0; Double_t dz2=pbtimp->GetSigmaZ2() + dz2V0; Double_t dx2=dy2; //For testing purposes: try geometric criterion only, disregard uncertainties if( fkIfImprovedExtraPrecisionFactor<0.9){ dx2 = fkIfImprovedExtraPrecisionFactor; dy2 = fkIfImprovedExtraPrecisionFactor; dz2 = fkIfImprovedExtraPrecisionFactor; } //Create dummy V0 track //V0 properties to get started Double_t xyz[3], pxpypz[3], cv[21]; for(Int_t ii=0;ii<21;ii++) cv[ii]=0.0; //something small pv0imp->GetXYZ(xyz[0],xyz[1],xyz[2]); pv0imp->GetPxPyPz( pxpypz[0],pxpypz[1],pxpypz[2] ); //Mockup track for V0 trajectory (no covariance) AliExternalTrackParam lV0TrajObject(xyz,pxpypz,cv,+1), *hV0Traj = &lV0TrajObject; hV0Traj->ResetCovariance(1); //won't use Double_t p1[8]; pbtimp->GetHelixParameters(p1,lMagneticField); p1[6]=TMath::Sin(p1[2]); p1[7]=TMath::Cos(p1[2]); Double_t p2[8]; hV0Traj->GetHelixParameters(p2,0.0); //p2[4]=0 -> no curvature (fine, predicted in Evaluate) p2[6]=TMath::Sin(p2[2]); p2[7]=TMath::Cos(p2[2]); Double_t r1[3],g1[3],gg1[3]; Double_t t1=0.; Evaluate(p1,t1,r1,g1,gg1); Double_t r2[3],g2[3],gg2[3]; Double_t t2=0.; Evaluate(p2,t2,r2,g2,gg2); Double_t dx=r2[0]-r1[0], dy=r2[1]-r1[1], dz=r2[2]-r1[2]; Double_t dm=dx*dx/dx2 + dy*dy/dy2 + dz*dz/dz2; Int_t max=fMaxIterationsCascadeDCA; while (max--) { Double_t gt1=-(dx*g1[0]/dx2 + dy*g1[1]/dy2 + dz*g1[2]/dz2); Double_t gt2=+(dx*g2[0]/dx2 + dy*g2[1]/dy2 + dz*g2[2]/dz2); Double_t h11=(g1[0]*g1[0] - dx*gg1[0])/dx2 + (g1[1]*g1[1] - dy*gg1[1])/dy2 + (g1[2]*g1[2] - dz*gg1[2])/dz2; Double_t h22=(g2[0]*g2[0] + dx*gg2[0])/dx2 + (g2[1]*g2[1] + dy*gg2[1])/dy2 + (g2[2]*g2[2] + dz*gg2[2])/dz2; Double_t h12=-(g1[0]*g2[0]/dx2 + g1[1]*g2[1]/dy2 + g1[2]*g2[2]/dz2); Double_t det=h11*h22-h12*h12; Double_t dt1,dt2; if (TMath::Abs(det)<1.e-33) { //(quasi)singular Hessian dt1=-gt1; dt2=-gt2; } else { dt1=-(gt1*h22 - gt2*h12)/det; dt2=-(h11*gt2 - h12*gt1)/det; } if ((dt1*gt1+dt2*gt2)>0) {dt1=-dt1; dt2=-dt2;} //check delta(phase1) ? //check delta(phase2) ? if (TMath::Abs(dt1)/(TMath::Abs(t1)+1.e-3) < fPrecisionCutoffCascadeDCA) if (TMath::Abs(dt2)/(TMath::Abs(t2)+1.e-3) < fPrecisionCutoffCascadeDCA) { if ((gt1*gt1+gt2*gt2) > 1.e-4/dy2/dy2){ AliDebug(1," stopped at not a stationary point !"); //Count not stationary point fTreeCascVarCascPropagationImprovedStatus += 1; //not stationary } Double_t lmb=h11+h22; lmb=lmb-TMath::Sqrt(lmb*lmb-4*det); if (lmb < 0.){ AliDebug(1," stopped at not a minimum !"); //Count stopped at not a minimum fTreeCascVarCascPropagationImprovedStatus += 10; //not minimum } break; } Double_t dd=dm; for (Int_t div=1 ; ; div*=2) { Evaluate(p1,t1+dt1,r1,g1,gg1); Evaluate(p2,t2+dt2,r2,g2,gg2); dx=r2[0]-r1[0]; dy=r2[1]-r1[1]; dz=r2[2]-r1[2]; dd=dx*dx/dx2 + dy*dy/dy2 + dz*dz/dz2; if (dd<dm) break; dt1*=0.5; dt2*=0.5; if (div>512) { AliDebug(1," overshoot !"); break; //Count overshoots fTreeCascVarCascPropagationImprovedStatus += 100; //overshoot! } } dm=dd; t1+=dt1; t2+=dt2; } if (max<=0){ AliDebug(1," too many iterations !"); } fTreeCascVarCascPropagationImprovedIterations = max; Double_t cs=TMath::Cos(pbtimp->GetAlpha()); Double_t sn=TMath::Sin(pbtimp->GetAlpha()); Double_t xthis=r1[0]*cs + r1[1]*sn; fTreeCascVarBachPropagationParameterImproved = xthis; //Memory cleanup hV0Traj->Delete(); hV0Traj=0x0; //Propagate bachelor to the point of DCA if (!pbtimp->PropagateTo(xthis,lMagneticField)) { //AliWarning(" propagation failed !"; //HOLY CRAP, propagation failed! fTreeCascVarCascPropagationImprovedStatus += 1000; //failure: add 1000 } if( fTreeCascVarCascPropagationImprovedStatus < 999 ){ //V0 distance to bachelor: the desired distance Double_t rBachDCAPt[3]; pbtimp->GetXYZ(rBachDCAPt); fTreeCascVarDCACascDaughtersImproved = pv0imp->GetD(rBachDCAPt[0],rBachDCAPt[1],rBachDCAPt[2]); //Construct cascade AliESDcascade cascadeimproved(*pv0imp,*pbtimp,lCascBachTrackArray[iCasc]); //Decay Position Double_t xcascimp,ycascimp,zcascimp; cascadeimproved.GetXYZcascade(xcascimp,ycascimp,zcascimp); fTreeCascVarImprovedDecayX = xcascimp; fTreeCascVarImprovedDecayY = ycascimp; fTreeCascVarImprovedDecayZ = zcascimp; fTreeCascVarImprovedCascCosPointingAngle = cascadeimproved.GetCascadeCosineOfPointingAngle(lBestPrimaryVtxPos[0],lBestPrimaryVtxPos[1],lBestPrimaryVtxPos[2]); //V0 properties to get started Double_t xyzCascade[3], pxpypzCascade[3], cvCascade[21]; for(Int_t ii=0;ii<21;ii++) cvCascade[ii]=0.0; //something small Int_t lChargeCascade = -1; if ( fTreeCascVarBachSign > 0 ) lChargeCascade = +1; //Don't forget: set properties, please... cascadeimproved.GetXYZcascade( xyzCascade[0], xyzCascade[1], xyzCascade[2] ); cascadeimproved.GetPxPyPz( pxpypzCascade[0], pxpypzCascade[1], pxpypzCascade[2] ); AliExternalTrackParam lCascTrajObject(xyzCascade,pxpypzCascade,cvCascade,lChargeCascade), *hCascTraj = &lCascTrajObject; fTreeCascVarImprovedCascDCAxyToPV = TMath::Abs(hCascTraj->GetD(lBestPrimaryVtxPos[0], lBestPrimaryVtxPos[1], lMagneticField) ); Float_t dzcascade[2]; hCascTraj->GetDZ(lBestPrimaryVtxPos[0],lBestPrimaryVtxPos[1],lBestPrimaryVtxPos[2], lMagneticField, dzcascade ); fTreeCascVarImprovedCascDCAzToPV = dzcascade[1]; Double_t lV0quality = 0.; cascadeimproved.ChangeMassHypothesis(lV0quality , 3312); fTreeCascVarImprovedInvMassXiMinus = cascadeimproved.GetEffMassXi(); cascadeimproved.ChangeMassHypothesis(lV0quality ,-3312); fTreeCascVarImprovedInvMassXiPlus = cascadeimproved.GetEffMassXi(); cascadeimproved.ChangeMassHypothesis(lV0quality , 3334); fTreeCascVarImprovedInvMassOmegaMinus = cascadeimproved.GetEffMassXi(); cascadeimproved.ChangeMassHypothesis(lV0quality ,-3334); fTreeCascVarImprovedInvMassOmegaPlus = cascadeimproved.GetEffMassXi(); } //+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ //----------------------------------------------------------------- //3c: Get perfect MC information for bookkeeping Int_t lblPosCascDghter = (Int_t) TMath::Abs( esdTrackPos->GetLabel() ); Int_t lblNegCascDghter = (Int_t) TMath::Abs( esdTrackNeg->GetLabel() ); Int_t lblBachCascDghter = (Int_t) TMath::Abs( esdTrackBach->GetLabel() ); TParticle* mcPosCascDghter = lMCstack->Particle( lblPosCascDghter ); TParticle* mcNegCascDghter = lMCstack->Particle( lblNegCascDghter ); TParticle* mcBachCascDghter = lMCstack->Particle( lblBachCascDghter ); //Get V0/bachelor decay position //Be careful: Vx, Vy, Vz: Creation vertex. So decay position is the //Creation vertex of any one of the daughters! fTreeCascVarV0DecayXMC = mcPosCascDghter->Vx(); fTreeCascVarV0DecayYMC = mcPosCascDghter->Vy(); fTreeCascVarV0DecayZMC = mcPosCascDghter->Vz(); fTreeCascVarDecayXMC = mcBachCascDghter->Vx(); fTreeCascVarDecayYMC = mcBachCascDghter->Vy(); fTreeCascVarDecayZMC = mcBachCascDghter->Vz(); //Get MC information fTreeCascVarNegPxMC = mcNegCascDghter->Px(); fTreeCascVarNegPyMC = mcNegCascDghter->Py(); fTreeCascVarNegPzMC = mcNegCascDghter->Pz(); fTreeCascVarPosPxMC = mcPosCascDghter->Px(); fTreeCascVarPosPyMC = mcPosCascDghter->Py(); fTreeCascVarPosPzMC = mcPosCascDghter->Pz(); fTreeCascVarBachPxMC = mcBachCascDghter->Px(); fTreeCascVarBachPyMC = mcBachCascDghter->Py(); fTreeCascVarBachPzMC = mcBachCascDghter->Pz(); fTreeCascVarPIDPositive = mcPosCascDghter -> GetPdgCode(); fTreeCascVarPIDNegative = mcNegCascDghter -> GetPdgCode(); fTreeCascVarPIDBachelor = mcBachCascDghter -> GetPdgCode(); Int_t lLabelMother = mcBachCascDghter->GetFirstMother(); TParticle *lParticleMother = lMCstack->Particle( lLabelMother ); Int_t lParticleMotherPDG = lParticleMother->GetPdgCode(); //Set tree variables fTreeCascVarPID = lParticleMother->GetPdgCode(); //PDG Code fTreeCascVarPtMC = lParticleMother->Pt(); //Perfect Pt fTreeCascVarRapMC = lParticleMother->Y(); if( fkSaveGoodTracks ){ //...where good -> kTPCrefit, at least length zero (more still needed!) if ((fTreeCascVarPosTrackStatus&AliESDtrack::kTPCrefit)==0) continue; if ((fTreeCascVarNegTrackStatus&AliESDtrack::kTPCrefit)==0) continue; if ((fTreeCascVarBachTrackStatus&AliESDtrack::kTPCrefit)==0) continue; if(fTreeCascVarPosLength<0) continue; if(fTreeCascVarNegLength<0) continue; if(fTreeCascVarBachLength<0) continue; } //Check how close the daughter tracks passed to the relevant decay points Float_t dzspec[2]; esdTrackPos->GetDZ( fTreeCascVarV0DecayXMC, fTreeCascVarV0DecayYMC, fTreeCascVarV0DecayZMC, lMagneticField, dzspec ); fTreeCascVarPosDistanceToTrueDecayPt = TMath::Sqrt(dzspec[0]*dzspec[0]+dzspec[1]*dzspec[1]); esdTrackNeg->GetDZ( fTreeCascVarV0DecayXMC, fTreeCascVarV0DecayYMC, fTreeCascVarV0DecayZMC, lMagneticField, dzspec ); fTreeCascVarNegDistanceToTrueDecayPt = TMath::Sqrt(dzspec[0]*dzspec[0]+dzspec[1]*dzspec[1]); esdTrackBach->GetDZ( fTreeCascVarDecayXMC, fTreeCascVarDecayYMC, fTreeCascVarDecayZMC, lMagneticField, dzspec ); fTreeCascVarBachDistanceToTrueDecayPt = TMath::Sqrt(dzspec[0]*dzspec[0]+dzspec[1]*dzspec[1]); //Check how close the reconstructed V0 passed to the actual cascade decay point fTreeCascVarV0DistanceToTrueDecayPt = vertex.GetD(fTreeCascVarDecayXMC,fTreeCascVarDecayYMC,fTreeCascVarDecayZMC); //Fill Findable cascade tree if( fkSaveCascadeTree ) fTreeCascade->Fill(); } //--] END CASCADE PART [-------------------------- // Post output data. PostData(1, fListHist ); PostData(2, fListV0 ); PostData(3, fListCascade ); PostData(4, fTreeEvent ); PostData(5, fTreeV0 ); PostData(6, fTreeCascade ); } //________________________________________________________________________ void AliAnalysisTaskStrEffStudy::Terminate(Option_t *) { // Draw result to the screen // Called once at the end of the query TList *cRetrievedList = 0x0; cRetrievedList = (TList*)GetOutputData(1); if(!cRetrievedList) { Printf("ERROR - AliAnalysisTaskStrEffStudy : ouput data container list not available\n"); return; } fHistEventCounter = dynamic_cast<TH1D*> ( cRetrievedList->FindObject("fHistEventCounter") ); if (!fHistEventCounter) { Printf("ERROR - AliAnalysisTaskStrEffStudy : fHistEventCounter not available"); return; } TCanvas *canCheck = new TCanvas("AliAnalysisTaskStrEffStudy","V0 Multiplicity",10,10,510,510); canCheck->cd(1)->SetLogy(); fHistEventCounter->SetMarkerStyle(22); fHistEventCounter->DrawCopy("E"); } //________________________________________________________________________ Double_t AliAnalysisTaskStrEffStudy::MyRapidity(Double_t rE, Double_t rPz) const { // Local calculation for rapidity Double_t ReturnValue = -100; if( (rE-rPz+1.e-13) != 0 && (rE+rPz) != 0 ) { ReturnValue = 0.5*TMath::Log((rE+rPz)/(rE-rPz+1.e-13)); } return ReturnValue; } //________________________________________________________________________ void AliAnalysisTaskStrEffStudy::AddConfiguration( AliV0Result *lV0Result ) { if (!fListV0){ Printf("fListV0 does not exist. Creating..."); fListV0 = new TList(); fListV0->SetOwner(); } fListV0->Add(lV0Result); } //________________________________________________________________________ void AliAnalysisTaskStrEffStudy::AddConfiguration( AliCascadeResult *lCascadeResult ) { if (!fListCascade){ Printf("fListCascade does not exist. Creating..."); fListCascade = new TList(); fListCascade->SetOwner(); } fListCascade->Add(lCascadeResult); } //________________________________________________________________________ void AliAnalysisTaskStrEffStudy::SetupStandardVertexing() //Meant to store standard re-vertexing configuration { //Tell the task to re-run vertexers SetRunVertexers(kTRUE); SetDoV0Refit(kTRUE); //V0-Related topological selections SetV0VertexerDCAFirstToPV(0.05); SetV0VertexerDCASecondtoPV(0.05); SetV0VertexerDCAV0Daughters(1.20); SetV0VertexerCosinePA(0.98); SetV0VertexerMinRadius(0.9); SetV0VertexerMaxRadius(200); //Cascade-Related topological selections SetCascVertexerMinV0ImpactParameter(0.05); SetCascVertexerV0MassWindow(0.006); SetCascVertexerDCABachToPV(0.02); SetCascVertexerDCACascadeDaughters(1.2); SetCascVertexerCascadeMinRadius(.8); SetCascVertexerCascadeCosinePA(.98); } //________________________________________________________________________ void AliAnalysisTaskStrEffStudy::SetupLooseVertexing() //Meant to store standard re-vertexing configuration { //Tell the task to re-run vertexers SetRunVertexers(kTRUE); SetDoV0Refit(kTRUE); //V0-Related topological selections SetV0VertexerDCAFirstToPV(0.1); SetV0VertexerDCASecondtoPV(0.1); SetV0VertexerDCAV0Daughters(1.40); SetV0VertexerCosinePA(0.95); SetV0VertexerMinRadius(0.9); SetV0VertexerMaxRadius(200); //Cascade-Related topological selections SetCascVertexerMinV0ImpactParameter(0.05); SetCascVertexerV0MassWindow(0.006); SetCascVertexerDCABachToPV(0.02); SetCascVertexerDCACascadeDaughters(1.4); SetCascVertexerCascadeMinRadius(.5); SetCascVertexerCascadeCosinePA(.95); } //________________________________________________________________________ void AliAnalysisTaskStrEffStudy::AddTopologicalQAV0(Int_t lRecNumberOfSteps) //Add all configurations to do QA of topological variables for the V0 analysis { // STEP 1: Decide on binning (needed to improve on memory consumption) // pT binning Double_t lPtbinlimits[] ={0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0, 4.5, 5.0, 5.5, 6.5, 8.0, 10, 12, 15}; Long_t lPtbinnumb = sizeof(lPtbinlimits)/sizeof(Double_t) - 1; Double_t lPtbinlimitsCascade[] ={0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0, 4.5, 5.0, 5.5, 6.5, 8.0, 10, 12, 14, 17, 20}; Long_t lPtbinnumbCascade = sizeof(lPtbinlimitsCascade)/sizeof(Double_t) - 1; // centrality binning Double_t lCentbinlimits[] = {0, 10}; Long_t lCentbinnumb = sizeof(lCentbinlimits)/sizeof(Double_t) - 1; // TStrings for output names TString lParticleName[] = {"K0Short", "Lambda", "AntiLambda"}; //STEP 3: Creation of output objects //Map to mass hypothesis AliV0Result::EMassHypo lMassHypoV0[3]; lMassHypoV0[0] = AliV0Result::kK0Short; lMassHypoV0[1] = AliV0Result::kLambda; lMassHypoV0[2] = AliV0Result::kAntiLambda; Float_t lLifetimeCut[3]; lLifetimeCut[0] = 20.0; lLifetimeCut[1] = 30.0; lLifetimeCut[2] = 30.0; Float_t lMass[3]; lMass[0] = 0.497; lMass[1] = 1.116; lMass[2] = 1.116; Float_t lMWindow[3]; lMWindow[0] = 0.075; lMWindow[1] = 0.050; lMWindow[2] = 0.050; //Array of results AliV0Result *lV0Result[5000]; Long_t lNV0 = 0; //Central results: Stored in indices 0, 1, 2 (careful!) for(Int_t i = 0 ; i < 3 ; i ++){ //Central result, customized binning: the one to use, usually lV0Result[lNV0] = new AliV0Result( Form("%s_Central",lParticleName[i].Data() ),lMassHypoV0[i],"",lCentbinnumb,lCentbinlimits, lPtbinnumb,lPtbinlimits, 100,lMass[i]-lMWindow[i],lMass[i]+lMWindow[i]); if ( i>0 ) lV0Result[lNV0]->InitializeFeeddownMatrix( lPtbinnumb, lPtbinlimits, lPtbinnumbCascade, lPtbinlimitsCascade, lCentbinnumb, lCentbinlimits ); //Setters for V0 Cuts lV0Result[lNV0]->SetCutDCANegToPV ( 0.05 ) ; lV0Result[lNV0]->SetCutDCAPosToPV ( 0.05 ) ; lV0Result[lNV0]->SetCutDCAV0Daughters ( 1.2 ) ; lV0Result[lNV0]->SetCutV0CosPA ( 0.98 ) ; lV0Result[lNV0]->SetCutV0Radius ( 0.9 ) ; //Miscellaneous lV0Result[lNV0]->SetCutProperLifetime ( lLifetimeCut[i] ) ; lV0Result[lNV0]->SetCutLeastNumberOfCrossedRows ( 70 ) ; lV0Result[lNV0]->SetCutLeastNumberOfCrossedRowsOverFindable ( 0.8 ) ; lV0Result[lNV0]->SetCutTPCdEdx ( 4 ) ; //Add result to pool lNV0++; } //Will now proceed to sweep individual variables //Number of steps used for the variable sweeps const Int_t lNumberOfSteps = lRecNumberOfSteps; //________________________________________________________ // Variable 1: DCA Neg to PV Float_t lMaxDCANegToPV = 20.00; for(Int_t i = 0 ; i < 3 ; i ++){ for(Int_t icut = 0; icut<lNumberOfSteps; icut++){ lV0Result[lNV0] = new AliV0Result( lV0Result[i], Form("%s_%s_%i",lParticleName[i].Data(),"DCANegToPVSweep",icut) ); //Add result to pool Float_t lThisCut = ((Float_t)icut+1)*lMaxDCANegToPV / ((Float_t) lNumberOfSteps) ; lV0Result[lNV0] -> SetCutDCANegToPV ( lThisCut ); lNV0++; } } //________________________________________________________ // Variable 2: DCA Pos to PV Float_t lMaxDCAPosToPV = 20.00; for(Int_t i = 0 ; i < 3 ; i ++){ for(Int_t icut = 0; icut<lNumberOfSteps; icut++){ lV0Result[lNV0] = new AliV0Result( lV0Result[i], Form("%s_%s_%i",lParticleName[i].Data(),"DCAPosToPVSweep",icut) ); //Add result to pool Float_t lThisCut = ((Float_t)icut+1)*lMaxDCAPosToPV / ((Float_t) lNumberOfSteps) ; lV0Result[lNV0] -> SetCutDCAPosToPV ( lThisCut ); lNV0++; } } //________________________________________________________ // Variable 3: DCA V0 Daughters Float_t lMaxDCAV0Daughters = 1.20; for(Int_t i = 0 ; i < 3 ; i ++){ for(Int_t icut = 0; icut<lNumberOfSteps; icut++){ lV0Result[lNV0] = new AliV0Result( lV0Result[i], Form("%s_%s_%i",lParticleName[i].Data(),"DCAV0DaughtersSweep",icut) ); //Add result to pool Float_t lThisCut = ((Float_t)icut+1)*lMaxDCAV0Daughters / ((Float_t) lNumberOfSteps) ; lV0Result[lNV0] -> SetCutDCAV0Daughters ( lThisCut ); lNV0++; } } //________________________________________________________ // Variable 4: V0 CosPA Float_t lMinV0CosPA = 0.98; Float_t lMaxV0CosPA = 1.00; Double_t lV0CosPAVals[lNumberOfSteps]; Double_t lMinV0PA = 0.0; Double_t lMaxV0PA = TMath::ACos(lMinV0CosPA); Double_t lDeltaV0PA = lMaxV0PA / ((Double_t)(lNumberOfSteps)); for(Int_t iStep = 0; iStep<lNumberOfSteps; iStep++){ lV0CosPAVals[iStep] = TMath::Cos( ((Float_t)(iStep+1))*lDeltaV0PA ); } for(Int_t i = 0 ; i < 3 ; i ++){ for(Int_t icut = 0; icut<lNumberOfSteps; icut++){ lV0Result[lNV0] = new AliV0Result( lV0Result[i], Form("%s_%s_%i",lParticleName[i].Data(),"V0CosPASweep",icut) ); //Add result to pool lV0Result[lNV0] -> SetCutV0CosPA ( lV0CosPAVals[icut] ); lNV0++; } } //________________________________________________________ // Variable 5: V0 Radius Float_t lMinV0Radius = 2.0; Float_t lMaxV0Radius = 20.00; for(Int_t i = 0 ; i < 3 ; i ++){ for(Int_t icut = 0; icut<lNumberOfSteps; icut++){ lV0Result[lNV0] = new AliV0Result( lV0Result[i], Form("%s_%s_%i",lParticleName[i].Data(),"V0RadiusSweep",icut) ); //Add result to pool Float_t lThisCut = lMinV0Radius + (lMaxV0Radius-lMinV0Radius)*(((Float_t)icut)+1)/((Float_t)lNumberOfSteps); lV0Result[lNV0] -> SetCutV0Radius ( lThisCut ); lNV0++; } } for (Int_t iconf = 0; iconf<lNV0; iconf++) AddConfiguration(lV0Result[iconf]); cout<<"Added "<<lNV0<<" V0 configurations to output."<<endl; } //________________________________________________________________________ void AliAnalysisTaskStrEffStudy::AddTopologicalQACascade(Int_t lRecNumberOfSteps) //Add all configurations to do QA of topological variables for the V0 analysis { // STEP 1: Decide on binning (needed to improve on memory consumption) // pT binning Double_t lPtbinlimits[] = {0.4, 0.5, 0.6, 0.7,0.8,.9,1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0, 2.1,2.2,2.3,2.4,2.5,2.6,2.7,2.8,3.0,3.2,3.4,3.6,3.8,4.0,4.2, 4.4,4.6,4.8,5.0,5.5,6.0,6.5,7.0,8.0,9.0,10.,11.,12.}; //Double_t lPtbinlimits[] = {0.2,0.3, 0.4, 0.5, 0.6, // 0.7,0.8,.9,1.0,1.2, 1.4, 1.6, 1.8 ,2.0, // 2.2, 2.4, 2.6, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0, // 4.4,4.8,5.0,6.0,7.0,8.0,9.0,10.,11.,12.}; //Double_t lPtbinlimits[] = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.4, 2.8, 3.2, //3.6, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.5, 8.5, 10, 12}; Long_t lPtbinnumb = sizeof(lPtbinlimits)/sizeof(Double_t) - 1; // centrality binning Double_t lCentbinlimits[] = {0, 10}; //optimize in 0-10% Long_t lCentbinnumb = sizeof(lCentbinlimits)/sizeof(Double_t) - 1; //Just a counter and one array, please. Nothing else needed AliCascadeResult *lCascadeResult[5000]; Long_t lN = 0; //Map to mass hypothesis AliCascadeResult::EMassHypo lMassHypo[4]; lMassHypo[0] = AliCascadeResult::kXiMinus; lMassHypo[1] = AliCascadeResult::kXiPlus; lMassHypo[2] = AliCascadeResult::kOmegaMinus; lMassHypo[3] = AliCascadeResult::kOmegaPlus; Float_t lLifetimeCut[4]; lLifetimeCut[0] = 15.0; lLifetimeCut[1] = 15.0; lLifetimeCut[2] = 12.0; lLifetimeCut[3] = 12.0; Float_t lMass[4]; lMass[0] = 1.322; lMass[1] = 1.322; lMass[2] = 1.672; lMass[3] = 1.672; TString lParticleName[] = {"XiMinus", "XiPlus", "OmegaMinus", "OmegaPlus"}; //Number of steps used for the variable sweeps const Int_t lNumberOfSteps = lRecNumberOfSteps; //Central results: Stored in indices 0, 1, 2, 3 (careful!) for(Int_t i = 0 ; i < 4 ; i ++){ //Central result, customized binning: the one to use, usually lCascadeResult[lN] = new AliCascadeResult( Form("%s_VertexerLevel",lParticleName[i].Data() ),lMassHypo[i],"",lCentbinnumb,lCentbinlimits, lPtbinnumb,lPtbinlimits,100,lMass[i]-0.050,lMass[i]+0.050); //Default cuts: use vertexer level ones //Setters for V0 Cuts lCascadeResult[lN]->SetCutDCANegToPV ( 0.2 ) ; lCascadeResult[lN]->SetCutDCAPosToPV ( 0.2 ) ; lCascadeResult[lN]->SetCutDCAV0Daughters ( 1. ) ; lCascadeResult[lN]->SetCutV0CosPA ( 0.95 ) ; //+variable lCascadeResult[lN]->SetCutVarV0CosPA (TMath::Exp(10.853), -25.0322, TMath::Exp(-0.843948), -0.890794, 0.057553); lCascadeResult[lN]->SetCutV0Radius ( 3 ) ; //Setters for Cascade Cuts lCascadeResult[lN]->SetCutDCAV0ToPV ( 0.1 ) ; lCascadeResult[lN]->SetCutV0Mass ( 0.006 ) ; lCascadeResult[lN]->SetCutDCABachToPV ( 0.1 ) ; lCascadeResult[lN]->SetCutDCACascDaughters ( 1.0) ; lCascadeResult[lN]->SetCutCascRadius ( 1.2 ) ; if(i==2||i==3) lCascadeResult[lN]->SetCutCascRadius ( 1.0 ) ; //omega case lCascadeResult[lN]->SetCutCascCosPA ( 0.95 ) ; //+variable lCascadeResult[lN]->SetCutVarCascCosPA (TMath::Exp(4.86664), -10.786, TMath::Exp(-1.33411), -0.729825, 0.0695724); //Miscellaneous lCascadeResult[lN]->SetCutProperLifetime ( lLifetimeCut[i] ) ; lCascadeResult[lN]->SetCutLeastNumberOfClusters ( 70.0 ) ; lCascadeResult[lN]->SetCutTPCdEdx ( 4.0 ) ; lCascadeResult[lN]->SetCutXiRejection ( 0.008 ) ; lCascadeResult[lN]->SetCutBachBaryonCosPA ( TMath::Cos(0.04) ) ; //+variable lCascadeResult[lN]->SetCutVarBBCosPA (TMath::Exp(-2.29048), -20.2016, TMath::Exp(-2.9581), -0.649153, 0.00526455); //Add result to pool lN++; } //Will now proceed to sweep individual variables //________________________________________________________ // Variable 1: DCA Neg to PV Float_t lMaxDCANegToPV = 1.5; for(Int_t i = 0 ; i < 4 ; i ++){ for(Int_t icut = 0; icut<lNumberOfSteps; icut++){ lCascadeResult[lN] = new AliCascadeResult( lCascadeResult[i], Form("%s_%s_%i",lParticleName[i].Data(),"DCANegToPVSweep",icut) ); //Add result to pool Float_t lThisCut = ((Float_t)icut+1)*lMaxDCANegToPV / ((Float_t) lNumberOfSteps) ; lCascadeResult[lN] -> SetCutDCANegToPV ( lThisCut ); lN++; } } //________________________________________________________ // Variable 2: DCA Pos to PV Float_t lMaxDCAPosToPV = 1.5; for(Int_t i = 0 ; i < 4 ; i ++){ for(Int_t icut = 0; icut<lNumberOfSteps; icut++){ lCascadeResult[lN] = new AliCascadeResult( lCascadeResult[i], Form("%s_%s_%i",lParticleName[i].Data(),"DCAPosToPVSweep",icut) ); //Add result to pool Float_t lThisCut = ((Float_t)icut+1)*lMaxDCAPosToPV / ((Float_t) lNumberOfSteps) ; lCascadeResult[lN] -> SetCutDCAPosToPV ( lThisCut ); lN++; } } //________________________________________________________ // Variable 3: DCA V0 Daughters Float_t lMaxDCAV0Daughters = 1.40; for(Int_t i = 0 ; i < 4 ; i ++){ for(Int_t icut = 0; icut<lNumberOfSteps; icut++){ lCascadeResult[lN] = new AliCascadeResult( lCascadeResult[i], Form("%s_%s_%i",lParticleName[i].Data(),"DCAV0DaughtersSweep",icut) ); //Add result to pool Float_t lThisCut = ((Float_t)icut+1)*lMaxDCAV0Daughters / ((Float_t) lNumberOfSteps) ; lCascadeResult[lN] -> SetCutDCAV0Daughters ( lThisCut ); lN++; } } //________________________________________________________ // Variable 4: V0 CosPA Float_t lMinV0CosPA = 0.95; Float_t lMaxV0CosPA = 1.00; Double_t lV0CosPAVals[lNumberOfSteps]; Double_t lMinV0PA = 0.0; Double_t lMaxV0PA = TMath::ACos(lMinV0CosPA); Double_t lDeltaV0PA = lMaxV0PA / ((Double_t)(lNumberOfSteps)); for(Int_t iStep = 0; iStep<lNumberOfSteps; iStep++){ lV0CosPAVals[iStep] = TMath::Cos( ((Float_t)(iStep+1))*lDeltaV0PA ); } for(Int_t i = 0 ; i < 4 ; i ++){ for(Int_t icut = 0; icut<lNumberOfSteps; icut++){ lCascadeResult[lN] = new AliCascadeResult( lCascadeResult[i], Form("%s_%s_%i",lParticleName[i].Data(),"V0CosPASweep",icut) ); //Add result to pool lCascadeResult[lN] -> SetCutUseVarV0CosPA( kFALSE ); lCascadeResult[lN] -> SetCutV0CosPA ( lV0CosPAVals[icut] ); lN++; } } //________________________________________________________ // Variable 5: V0 Radius Float_t lMinV0Radius = 0.0; Float_t lMaxV0Radius = 20.00; for(Int_t i = 0 ; i < 4 ; i ++){ for(Int_t icut = 0; icut<lNumberOfSteps; icut++){ lCascadeResult[lN] = new AliCascadeResult( lCascadeResult[i], Form("%s_%s_%i",lParticleName[i].Data(),"V0RadiusSweep",icut) ); //Add result to pool Float_t lThisCut = lMinV0Radius + (lMaxV0Radius-lMinV0Radius)*(((Float_t)icut)+1)/((Float_t)lNumberOfSteps); lCascadeResult[lN] -> SetCutV0Radius ( lThisCut ); lN++; } } //________________________________________________________ // Variable 6: Float_t lMaxDCAV0ToPV = 0.5; for(Int_t i = 0 ; i < 4 ; i ++){ for(Int_t icut = 0; icut<lNumberOfSteps; icut++){ lCascadeResult[lN] = new AliCascadeResult( lCascadeResult[i], Form("%s_%s_%i",lParticleName[i].Data(),"DCAV0ToPVSweep",icut) ); //Add result to pool Float_t lThisCut = ((Float_t)icut+1)*lMaxDCAV0ToPV / ((Float_t) lNumberOfSteps) ; lCascadeResult[lN] -> SetCutDCAV0ToPV ( lThisCut ); lN++; } } //________________________________________________________ // Variable 7: DCA Bach To PV Float_t lMaxDCABachToPV = 0.5; for(Int_t i = 0 ; i < 4 ; i ++){ for(Int_t icut = 0; icut<lNumberOfSteps; icut++){ lCascadeResult[lN] = new AliCascadeResult( lCascadeResult[i], Form("%s_%s_%i",lParticleName[i].Data(),"DCABachToPVSweep",icut) ); //Add result to pool Float_t lThisCut = ((Float_t)icut+1)*lMaxDCABachToPV / ((Float_t) lNumberOfSteps) ; lCascadeResult[lN] -> SetCutDCABachToPV ( lThisCut ); lN++; } } //________________________________________________________ // Variable 8: DCA Casc Daughters Float_t lMaxDCACascDaughters = 1.40; for(Int_t i = 0 ; i < 4 ; i ++){ for(Int_t icut = 0; icut<lNumberOfSteps; icut++){ lCascadeResult[lN] = new AliCascadeResult( lCascadeResult[i], Form("%s_%s_%i",lParticleName[i].Data(),"DCACascDaughtersSweep",icut) ); //Add result to pool Float_t lThisCut = ((Float_t)icut+1)*lMaxDCACascDaughters / ((Float_t) lNumberOfSteps) ; lCascadeResult[lN] -> SetCutDCACascDaughters ( lThisCut ); lN++; } } //________________________________________________________ // Variable 9: Cascade Radius Float_t lMinCascRadius = 0.5; Float_t lMaxCascRadius = 7.0; for(Int_t i = 0 ; i < 4 ; i ++){ for(Int_t icut = 0; icut<lNumberOfSteps; icut++){ lCascadeResult[lN] = new AliCascadeResult( lCascadeResult[i], Form("%s_%s_%i",lParticleName[i].Data(),"CascRadiusSweep",icut) ); //Add result to pool Float_t lThisCut = lMinCascRadius + (lMaxCascRadius-lMinCascRadius)*(((Float_t)icut)+1)/((Float_t)lNumberOfSteps); lCascadeResult[lN] -> SetCutCascRadius ( lThisCut ); lN++; } } //________________________________________________________ // Variable 10: Cascade CosPA Float_t lMinCascCosPA = 0.95; Float_t lMaxCascCosPA = 1.00; Double_t lCascCosPAVals[lNumberOfSteps]; Double_t lMinCascPA = 0.0; Double_t lMaxCascPA = TMath::ACos(lMinCascCosPA); Double_t lDeltaCascPA = lMaxCascPA / ((Double_t)(lNumberOfSteps)); for(Int_t iStep = 0; iStep<lNumberOfSteps; iStep++){ lCascCosPAVals[iStep] = TMath::Cos( ((Float_t)(iStep+1))*lDeltaCascPA ); } for(Int_t i = 0 ; i < 4 ; i ++){ for(Int_t icut = 0; icut<lNumberOfSteps; icut++){ lCascadeResult[lN] = new AliCascadeResult( lCascadeResult[i], Form("%s_%s_%i",lParticleName[i].Data(),"CascCosPASweep",icut) ); //Add result to pool lCascadeResult[lN] -> SetCutUseVarCascCosPA( kFALSE ); lCascadeResult[lN] -> SetCutCascCosPA ( lCascCosPAVals[icut] ); lN++; } } //________________________________________________________ // Variable 11: Bach-Baryon CosPA Float_t lMinBBCosPA = TMath::Cos(0.1); Float_t lMaxBBCosPA = 1.000; Double_t lBBCosPAVals[lNumberOfSteps]; Double_t lMinBBPA = 0.0; Double_t lMaxBBPA = TMath::ACos(lMinBBCosPA); Double_t lDeltaBBPA = lMaxBBPA / ((Double_t)(lNumberOfSteps)); for(Int_t iStep = 0; iStep<lNumberOfSteps; iStep++){ lBBCosPAVals[iStep] = TMath::Cos( ((Float_t)(iStep+1))*lDeltaBBPA ); } for(Int_t i = 0 ; i < 4 ; i ++){ for(Int_t icut = 0; icut<lNumberOfSteps; icut++){ lCascadeResult[lN] = new AliCascadeResult( lCascadeResult[i], Form("%s_%s_%i",lParticleName[i].Data(),"BBCosPASweep",icut) ); //Add result to pool lCascadeResult[lN] -> SetCutUseVarBBCosPA( kFALSE ); lCascadeResult[lN] -> SetCutBachBaryonCosPA ( lBBCosPAVals[icut] ); lN++; } } //________________________________________________________ // Variable 12: Cascade Lifetime Sweep Int_t lLifetimeSteps = 15; for(Int_t i = 0 ; i < 4 ; i ++){ Float_t lMinLifetime = 5.00; Float_t lMaxLifetime = 20.00; for(Int_t icut = 0; icut<lLifetimeSteps; icut++){ lCascadeResult[lN] = new AliCascadeResult( lCascadeResult[i], Form("%s_%s_%i",lParticleName[i].Data(),"CascLifetimeSweep",icut) ); Float_t lThisCut = lMinLifetime + (lMaxLifetime-lMinLifetime)*(((Float_t)icut)+1)/((Float_t)lLifetimeSteps); //Add result to pool lCascadeResult[lN] -> SetCutProperLifetime ( lThisCut ); lN++; } } //________________________________________________________ // Variable 13: V0 Lifetime Sweep Float_t lMinV0Lifetime = 8.00; Float_t lMaxV0Lifetime = 40.00; Int_t lV0LifetimeSteps = 32; for(Int_t i = 0 ; i < 4 ; i ++){ for(Int_t icut = 0; icut<lV0LifetimeSteps; icut++){ lCascadeResult[lN] = new AliCascadeResult( lCascadeResult[i], Form("%s_%s_%i",lParticleName[i].Data(),"MaxV0LifetimeSweep",icut) ); Float_t lThisCut = lMinV0Lifetime + (lMaxV0Lifetime-lMinV0Lifetime)*(((Float_t)icut)+1)/((Float_t)lV0LifetimeSteps); //Add result to pool lCascadeResult[lN] -> SetCutMaxV0Lifetime ( lThisCut ); lN++; } } for (Int_t iconf = 0; iconf<lN; iconf++) AddConfiguration(lCascadeResult[iconf]); cout<<"Added "<<lN<<" Cascade configurations to output."<<endl; } //________________________________________________________________________ void AliAnalysisTaskStrEffStudy::AddStandardV0Configuration() //Meant to add some standard V0 analysis Configuration + its corresponding systematics { // STEP 1: Decide on binning (needed to improve on memory consumption) // pT binning Double_t lPtbinlimitsV0[] ={0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0, 4.5, 5.0, 5.5, 6.5, 8.0, 10, 12, 14, 15, 17, 20}; Long_t lPtbinnumbV0 = sizeof(lPtbinlimitsV0)/sizeof(Double_t) - 1; Double_t lPtbinlimitsXi[] ={0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0, 4.5, 5.0, 5.5, 6.5, 8.0, 10, 12, 14, 17, 20}; Long_t lPtbinnumbXi = sizeof(lPtbinlimitsXi)/sizeof(Double_t) - 1; // centrality binning Double_t lCentbinlimitsV0[] = {0, 1, 5, 10, 20, 30, 40, 50, 60, 70, 80, 85, 90}; Long_t lCentbinnumbV0 = sizeof(lCentbinlimitsV0)/sizeof(Double_t) - 1; // centrality binning Double_t lCentbinlimits[] = {0, 1, 5, 10, 20, 30, 40, 50, 60, 70, 80, 85, 90}; Long_t lCentbinnumb = sizeof(lCentbinlimits)/sizeof(Double_t) - 1; // TStrings for output names TString lParticleName[] = {"K0Short", "Lambda", "AntiLambda"}; TString lConfName[] = {"Loose", "Central", "Tight" }; TString lCutName[] = {"DCANegToPV","DCAPosToPV","DCAV0Daughters","V0CosPA","V0Radius", "ProperLifetime","LeastNbrCrs","LeastNbrCrsOvFind","TPCdEdx"}; // STEP 2: Decide on a set of selections //1st index: Particle Species //2nd index: Loose / Central / Tight //3rd index: Number of selection (as ordered above) Double_t lcutsV0[3][3][9]; //N.B.: These are mostly symmetric, except for the proper lifetime, which is different // for the two particle species. Another potential improvement could be asymmetric // DCA selections for the Neg / Pos tracks for the (anti)Lambda decay, as decay // kinematics would prefer having the pion daughter with a larger DCA. /*** //Information from Michal, 09th April === Lambda === --- 0-10% --- Signal loss: 5% Parameters from real data: par 0 0.18945 par 1 -0.57882 par 2 0.01302 Signal loss: 5% Parameters from MC: par 0 0.26081 par 1 -1.16285 par 2 0.02692 === AntiLambda === --- 0-10% --- Signal loss: 5% Parameters from real data: par 0 0.21861 par 1 -0.67273 par 2 0.01200 Signal loss: 5% Parameters from MC: par 0 0.24144 par 1 -1.04444 par 2 0.02684 === K0Short === --- 0-10% --- Signal loss: 5% Parameters from real data: par 0 0.21320 par 1 -0.91380 par 2 0.02483 Signal loss: 5% Parameters from MC: par 0 0.17816 par 1 -0.79000 par 2 0.02184 */ Double_t parExpConst[3] = { 0.26081, 0.24144, 0.17816 }; Double_t parExpSlope[3] = { -1.16285, -1.04444, -0.79000 }; Double_t parConst[3] = { 0.02692, 0.02684, 0.02184 }; //================================================================================ // K0SHORT SELECTIONS //-------------------------------------------------------------------------------- // LOOSE CENTRAL TIGHT lcutsV0[0][0][ 0] = 0.06; lcutsV0[0][1][ 0] = 0.1; lcutsV0[0][2][0] = 0.17; //DCANegToPV lcutsV0[0][0][ 1] = 0.06; lcutsV0[0][1][ 1] = 0.1; lcutsV0[0][2][1] = 0.17; //DCAPosToPV lcutsV0[0][0][ 2] = 0.95; lcutsV0[0][1][ 2] = 0.8; lcutsV0[0][2][2] = 0.7; //DCAV0Daughters lcutsV0[0][0][ 3] = 0.95; lcutsV0[0][1][ 3] = 0.95; lcutsV0[0][2][3] = 0.95; //V0CosPA lcutsV0[0][0][ 4] = 4.50; lcutsV0[0][1][ 4] = 5.00; lcutsV0[0][2][4] = 5.50; //V0Radius lcutsV0[0][0][ 5] = 12; lcutsV0[0][1][ 5] = 10; lcutsV0[0][2][5] = 8; //Proper Lifetime (in cm) lcutsV0[0][0][ 6] = 70; lcutsV0[0][1][ 6] = 70; lcutsV0[0][2][6] = 80; //Least Nbr Crossed Rows lcutsV0[0][0][ 7] = 0.7; lcutsV0[0][1][ 7] = 0.8; lcutsV0[0][2][7] = 0.85; //Least Ratio CrdRows/Findable lcutsV0[0][0][ 8] = 4.0; lcutsV0[0][1][ 8] = 3.0; lcutsV0[0][2][8] = 2.5; //TPC dE/dx //================================================================================ //================================================================================ // LAMBDA SELECTIONS //-------------------------------------------------------------------------------- // LOOSE CENTRAL TIGHT lcutsV0[1][0][ 0] = 0.1; lcutsV0[1][1][ 0] = 0.2; lcutsV0[1][2][0] = 0.30; //DCANegToPV lcutsV0[1][0][ 1] = 0.08; lcutsV0[1][1][ 1] = 0.1; lcutsV0[1][2][1] = 0.13; //DCAPosToPV lcutsV0[1][0][ 2] = 1.0; lcutsV0[1][1][ 2] = 0.8; lcutsV0[1][2][2] = 0.65; //DCAV0Daughters lcutsV0[1][0][ 3] = 0.95; lcutsV0[1][1][ 3] = 0.95; lcutsV0[1][2][3] = 0.95; //V0CosPA lcutsV0[1][0][ 4] = 4.00; lcutsV0[1][1][ 4] = 5.00; lcutsV0[1][2][4] = 6.00; //V0Radius lcutsV0[1][0][ 5] = 24; lcutsV0[1][1][ 5] = 20; lcutsV0[1][2][5] = 17; //Proper Lifetime (in cm) lcutsV0[1][0][ 6] = 70; lcutsV0[1][1][ 6] = 70; lcutsV0[1][2][6] = 80; //Least Nbr Crossed Rows lcutsV0[1][0][ 7] = 0.7; lcutsV0[1][1][ 7] = 0.8; lcutsV0[1][2][7] = 0.85; //Least Ratio CrdRows/Findable lcutsV0[1][0][ 8] = 4.0; lcutsV0[1][1][ 8] = 3.0; lcutsV0[1][2][8] = 2.5; //TPC dE/dx //================================================================================ //================================================================================ // ANTILAMBDA SELECTIONS //-------------------------------------------------------------------------------- // LOOSE CENTRAL TIGHT lcutsV0[2][0][ 0] = 0.08; lcutsV0[2][1][ 0] = 0.1; lcutsV0[2][2][0] = 0.13; //DCANegToPV lcutsV0[2][0][ 1] = 0.1; lcutsV0[2][1][ 1] = 0.2; lcutsV0[2][2][1] = 0.30; //DCAPosToPV lcutsV0[2][0][ 2] = 1.0; lcutsV0[2][1][ 2] = 0.8; lcutsV0[2][2][2] = 0.65; //DCAV0Daughters lcutsV0[2][0][ 3] = 0.95; lcutsV0[2][1][ 3] = 0.95; lcutsV0[2][2][3] = 0.95; //V0CosPA lcutsV0[2][0][ 4] = 4.00; lcutsV0[2][1][ 4] = 5.00; lcutsV0[2][2][4] = 6.00; //V0Radius lcutsV0[2][0][ 5] = 24; lcutsV0[2][1][ 5] = 20; lcutsV0[2][2][5] = 17; //Proper Lifetime (in cm) lcutsV0[2][0][ 6] = 70; lcutsV0[2][1][ 6] = 70; lcutsV0[2][2][6] = 80; //Least Nbr Crossed Rows lcutsV0[2][0][ 7] = 0.7; lcutsV0[2][1][ 7] = 0.8; lcutsV0[2][2][7] = 0.85; //Least Ratio CrdRows/Findable lcutsV0[2][0][ 8] = 4.0; lcutsV0[2][1][ 8] = 3.0; lcutsV0[2][2][8] = 2.5; //TPC dE/dx //================================================================================ //STEP 3: Creation of output objects //Map to mass hypothesis AliV0Result::EMassHypo lMassHypoV0[3]; lMassHypoV0[0] = AliV0Result::kK0Short; lMassHypoV0[1] = AliV0Result::kLambda; lMassHypoV0[2] = AliV0Result::kAntiLambda; //Array of results AliV0Result *lV0Result[500]; Long_t lNV0 = 0; //Central results: Stored in indices 0, 1, 2 (careful!) for(Int_t i = 0 ; i < 3 ; i ++){ //Central result, customized binning: the one to use, usually lV0Result[lNV0] = new AliV0Result( Form("%s_Central",lParticleName[i].Data() ),lMassHypoV0[i],"",lCentbinnumbV0,lCentbinlimitsV0, lPtbinnumbV0,lPtbinlimitsV0); if ( i!=0 ) lV0Result[lNV0] -> InitializeFeeddownMatrix( lPtbinnumbV0,lPtbinlimitsV0, lPtbinnumbXi,lPtbinlimitsXi, lCentbinnumbV0,lCentbinlimitsV0); //Setters for V0 Cuts lV0Result[lNV0]->SetCutDCANegToPV ( lcutsV0[i][1][ 0] ) ; lV0Result[lNV0]->SetCutDCAPosToPV ( lcutsV0[i][1][ 1] ) ; lV0Result[lNV0]->SetCutDCAV0Daughters ( lcutsV0[i][1][ 2] ) ; lV0Result[lNV0]->SetCutV0CosPA ( lcutsV0[i][1][ 3] ) ; //Set Variable cut lV0Result[lNV0]->SetCutVarV0CosPA ( parExpConst[i], parExpSlope[i], 0.0, 1.0, parConst[i] ) ; lV0Result[lNV0]->SetCutV0Radius ( lcutsV0[i][1][ 4] ) ; //Miscellaneous lV0Result[lNV0]->SetCutProperLifetime ( lcutsV0[i][1][ 5] ) ; lV0Result[lNV0]->SetCutLeastNumberOfCrossedRows ( lcutsV0[i][1][ 6] ) ; lV0Result[lNV0]->SetCutLeastNumberOfCrossedRowsOverFindable ( lcutsV0[i][1][ 7] ) ; lV0Result[lNV0]->SetCutTPCdEdx ( lcutsV0[i][1][ 8] ) ; //Add result to pool lNV0++; } //Central full results: indices 2, 3, 4 for(Int_t i = 0 ; i < 3 ; i ++){ //Central Result, Full: No rebinning. Will use a significant amount of memory, //not to be replicated several times for systematics! lV0Result[lNV0] = new AliV0Result( Form("%s_Central_Full",lParticleName[i].Data() ),lMassHypoV0[i]); if ( i!=0 ) lV0Result[lNV0] -> InitializeFeeddownMatrix( lPtbinnumbV0,lPtbinlimitsV0, lPtbinnumbXi,lPtbinlimitsXi, lCentbinnumbV0,lCentbinlimitsV0); //Setters for V0 Cuts lV0Result[lNV0]->SetCutDCANegToPV ( lcutsV0[i][1][ 0] ) ; lV0Result[lNV0]->SetCutDCAPosToPV ( lcutsV0[i][1][ 1] ) ; lV0Result[lNV0]->SetCutDCAV0Daughters ( lcutsV0[i][1][ 2] ) ; lV0Result[lNV0]->SetCutV0CosPA ( lcutsV0[i][1][ 3] ) ; //Set Variable cut lV0Result[lNV0]->SetCutVarV0CosPA ( parExpConst[i], parExpSlope[i], 0.0, 1.0, parConst[i] ) ; lV0Result[lNV0]->SetCutV0Radius ( lcutsV0[i][1][ 4] ) ; //Miscellaneous lV0Result[lNV0]->SetCutProperLifetime ( lcutsV0[i][1][ 5] ) ; lV0Result[lNV0]->SetCutLeastNumberOfCrossedRows ( lcutsV0[i][1][ 6] ) ; lV0Result[lNV0]->SetCutLeastNumberOfCrossedRowsOverFindable ( lcutsV0[i][1][ 7] ) ; lV0Result[lNV0]->SetCutTPCdEdx ( lcutsV0[i][1][ 8] ) ; //Add result to pool lNV0++; } // STEP 4: Creation of objects to be used in systematics // Optimized via use of copy constructors for(Int_t i = 0 ; i < 3 ; i ++){ for(Int_t iCut = 0 ; iCut < 9 ; iCut ++){ //LOOSE VARIATIONS //Create a new object from default lV0Result[lNV0] = new AliV0Result( lV0Result[i], Form("%s_%s_%s",lParticleName[i].Data(),lCutName[iCut].Data(),lConfName[0].Data()) ); if(iCut == 0 ) lV0Result[lNV0]->SetCutDCANegToPV ( lcutsV0[i][0][iCut] ) ; if(iCut == 1 ) lV0Result[lNV0]->SetCutDCAPosToPV ( lcutsV0[i][0][iCut] ) ; if(iCut == 2 ) lV0Result[lNV0]->SetCutDCAV0Daughters ( lcutsV0[i][0][iCut] ) ; if(iCut == 3 ) lV0Result[lNV0]->SetCutV0CosPA ( lcutsV0[i][0][iCut] ) ; if(iCut == 4 ) lV0Result[lNV0]->SetCutV0Radius ( lcutsV0[i][0][iCut] ) ; //Miscellaneous if(iCut == 5 ) lV0Result[lNV0]->SetCutProperLifetime ( lcutsV0[i][0][iCut] ) ; if(iCut == 6 ) lV0Result[lNV0]->SetCutLeastNumberOfCrossedRows ( lcutsV0[i][0][iCut] ) ; if(iCut == 7 ) lV0Result[lNV0]->SetCutLeastNumberOfCrossedRowsOverFindable ( lcutsV0[i][0][iCut] ) ; if(iCut == 8 ) lV0Result[lNV0]->SetCutTPCdEdx ( lcutsV0[i][0][iCut] ) ; //Print this variation, add to pool lV0Result[lNV0]->Print(); lNV0++; //TIGHT VARIATIONS //Create a new object from default lV0Result[lNV0] = new AliV0Result( lV0Result[i], Form("%s_%s_%s",lParticleName[i].Data(),lCutName[iCut].Data(),lConfName[2].Data()) ); if(iCut == 0 ) lV0Result[lNV0]->SetCutDCANegToPV ( lcutsV0[i][2][iCut] ) ; if(iCut == 1 ) lV0Result[lNV0]->SetCutDCAPosToPV ( lcutsV0[i][2][iCut] ) ; if(iCut == 2 ) lV0Result[lNV0]->SetCutDCAV0Daughters ( lcutsV0[i][2][iCut] ) ; if(iCut == 3 ) lV0Result[lNV0]->SetCutV0CosPA ( lcutsV0[i][2][iCut] ) ; if(iCut == 4 ) lV0Result[lNV0]->SetCutV0Radius ( lcutsV0[i][2][iCut] ) ; //Miscellaneous if(iCut == 5 ) lV0Result[lNV0]->SetCutProperLifetime ( lcutsV0[i][2][iCut] ) ; if(iCut == 6 ) lV0Result[lNV0]->SetCutLeastNumberOfCrossedRows ( lcutsV0[i][2][iCut] ) ; if(iCut == 7 ) lV0Result[lNV0]->SetCutLeastNumberOfCrossedRowsOverFindable ( lcutsV0[i][2][iCut] ) ; if(iCut == 8 ) lV0Result[lNV0]->SetCutTPCdEdx ( lcutsV0[i][2][iCut] ) ; //Print this variation, add to pool lV0Result[lNV0]->Print(); lNV0++; } } for (Int_t iconf = 0; iconf<lNV0; iconf++) AddConfiguration(lV0Result[iconf]); cout<<"Added "<<lNV0<<" V0 configurations to output."<<endl; } //________________________________________________________________________ void AliAnalysisTaskStrEffStudy::AddStandardCascadeConfiguration() //Meant to add some standard cascade analysis Configuration + its corresponding systematics { // STEP 1: Decide on binning (needed to improve on memory consumption) // pT binning Double_t lPtbinlimits[] = {0.4, 0.5, 0.6, 0.7,0.8,.9,1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0, 2.1,2.2,2.3,2.4,2.5,2.6,2.7,2.8,3.0,3.2,3.4,3.6,3.8,4.0,4.2, 4.4,4.6,4.8,5.0,5.5,6.0,6.5,7.0,8.0,9.0,10.,11.,12.}; Long_t lPtbinnumb = sizeof(lPtbinlimits)/sizeof(Double_t) - 1; // centrality binning Double_t lCentbinlimits[] = {0, 1, 5, 10, 20, 30, 40, 50, 60, 70, 80, 85, 90}; Long_t lCentbinnumb = sizeof(lCentbinlimits)/sizeof(Double_t) - 1; // TStrings for output names TString lParticleName[] = {"XiMinus", "XiPlus", "OmegaMinus", "OmegaPlus"}; TString lConfName[] = {"Loose", "Central", "Tight" }; TString lCutName[] = { "DCANegToPV", //1 "DCAPosToPV", //2 "DCAV0Daughters", //3 "V0Radius", //4 "DCAV0ToPV", //5 "V0Mass", //6 "DCABachToPV", //7 "DCACascDaughters", //8 "CascRadius", //9 "ProperLifetime", //10 "ProperLifetimeV0", //11 "LeastNumberOfClusters", //12 "TPCdEdx", //13 "Competing" //14 }; // STEP 2: Decide on a set of selections //1st index: Particle Species //2nd index: Loose / Central / Tight //3rd index: Number of selection (as ordered above) Double_t lcuts[4][3][14]; //N.B.: These are mostly symmetric, except for the proper lifetime, which is different // for the two particle species. Another potential improvement could be asymmetric // DCA selections for the Neg / Pos tracks for the (anti)Lambda decay, as decay // kinematics would prefer having the pion daughter with a larger DCA. Int_t lIdx = 0; //================================================================================ // XIMINUS SELECTIONS lIdx = 0; //Master XiMinus Index //-------------------------------------------------------------------------------- // LOOSE CENTRAL TIGHT lcuts[lIdx][0][ 0] = 0.10; lcuts[lIdx][1][ 0] = 0.20; lcuts[lIdx][2][ 0] = 0.30; //DCANegToPV 1 lcuts[lIdx][0][ 1] = 0.10; lcuts[lIdx][1][ 1] = 0.20; lcuts[lIdx][2][ 1] = 0.30; //DCAPostToPV 2 lcuts[lIdx][0][ 2] = 1.2; lcuts[lIdx][1][ 2] = 1.0; lcuts[lIdx][2][ 2] = 0.8; //DCAV0Daughters 3 lcuts[lIdx][0][ 3] = 2.00; lcuts[lIdx][1][ 3] = 3.00; lcuts[lIdx][2][ 3] = 4.0; //V0Radius 4 lcuts[lIdx][0][ 4] = 0.05; lcuts[lIdx][1][ 4] = 0.1; lcuts[lIdx][2][ 4] = 0.15; //DCAV0ToPV 5 lcuts[lIdx][0][ 5] =0.006; lcuts[lIdx][1][ 5] = 0.005; lcuts[lIdx][2][ 5] = 0.004; //V0Mass 6 lcuts[lIdx][0][ 6] = 0.05; lcuts[lIdx][1][ 6] = 0.10; lcuts[lIdx][2][ 6] = 0.15; //DCABachToPV 7 lcuts[lIdx][0][ 7] = 1.20; lcuts[lIdx][1][ 7] = 1.0; lcuts[lIdx][2][ 7] = 0.8; //DCACascDaughters 8 lcuts[lIdx][0][ 8] = 0.8; lcuts[lIdx][1][ 8] = 1.2; lcuts[lIdx][2][ 8] = 3.00; //CascRadius 9 lcuts[lIdx][0][ 9] = 17.5; lcuts[lIdx][1][ 9] = 15.0; lcuts[lIdx][2][ 9] = 12.5; //ProperLifetime 10 lcuts[lIdx][0][10] = 40.0; lcuts[lIdx][1][10] = 30.0; lcuts[lIdx][2][10] = 20.0; //ProperLifetimeV0 11 lcuts[lIdx][0][11] = -1; lcuts[lIdx][1][11] = 70; lcuts[lIdx][2][11] = 80; //LeastNumberOfClusters 12 lcuts[lIdx][0][12] = 5; lcuts[lIdx][1][12] = 4; lcuts[lIdx][2][12] = 3; //TPCdEdx 13 lcuts[lIdx][0][13] = 0.0; lcuts[lIdx][1][13] = 0.008; lcuts[lIdx][2][13] = 0.010; //Competing 14 //================================================================================ //================================================================================ // XIPLUS SELECTIONS lIdx = 1; //Master XiPlus Index //-------------------------------------------------------------------------------- // LOOSE CENTRAL TIGHT lcuts[lIdx][0][ 0] = 0.10; lcuts[lIdx][1][ 0] = 0.20; lcuts[lIdx][2][ 0] = 0.30; //DCANegToPV 1 lcuts[lIdx][0][ 1] = 0.10; lcuts[lIdx][1][ 1] = 0.20; lcuts[lIdx][2][ 1] = 0.30; //DCAPostToPV 2 lcuts[lIdx][0][ 2] = 1.2; lcuts[lIdx][1][ 2] = 1.0; lcuts[lIdx][2][ 2] = 0.8; //DCAV0Daughters 3 lcuts[lIdx][0][ 3] = 2.00; lcuts[lIdx][1][ 3] = 3.00; lcuts[lIdx][2][ 3] = 4.0; //V0Radius 4 lcuts[lIdx][0][ 4] = 0.05; lcuts[lIdx][1][ 4] = 0.1; lcuts[lIdx][2][ 4] = 0.15; //DCAV0ToPV 5 lcuts[lIdx][0][ 5] =0.006; lcuts[lIdx][1][ 5] = 0.005; lcuts[lIdx][2][ 5] = 0.004; //V0Mass 6 lcuts[lIdx][0][ 6] = 0.05; lcuts[lIdx][1][ 6] = 0.10; lcuts[lIdx][2][ 6] = 0.15; //DCABachToPV 7 lcuts[lIdx][0][ 7] = 1.20; lcuts[lIdx][1][ 7] = 1.0; lcuts[lIdx][2][ 7] = 0.8; //DCACascDaughters 8 lcuts[lIdx][0][ 8] = 0.8; lcuts[lIdx][1][ 8] = 1.2; lcuts[lIdx][2][ 8] = 3.00; //CascRadius 9 lcuts[lIdx][0][ 9] = 17.5; lcuts[lIdx][1][ 9] = 15.0; lcuts[lIdx][2][ 9] = 12.5; //ProperLifetime 10 lcuts[lIdx][0][10] = 40.0; lcuts[lIdx][1][10] = 30.0; lcuts[lIdx][2][10] = 20.0; //ProperLifetimeV0 11 lcuts[lIdx][0][11] = -1; lcuts[lIdx][1][11] = 70; lcuts[lIdx][2][11] = 80; //LeastNumberOfClusters 12 lcuts[lIdx][0][12] = 5; lcuts[lIdx][1][12] = 4; lcuts[lIdx][2][12] = 3; //TPCdEdx 13 lcuts[lIdx][0][13] = 0.0; lcuts[lIdx][1][13] = 0.008; lcuts[lIdx][2][13] = 0.010; //Competing 14 //================================================================================ //================================================================================ // OMEGAMINUS SELECTIONS lIdx = 2; //Master OmegaMinus Index //-------------------------------------------------------------------------------- // LOOSE CENTRAL TIGHT lcuts[lIdx][0][ 0] = 0.10; lcuts[lIdx][1][ 0] = 0.20; lcuts[lIdx][2][ 0] = 0.30; //DCANegToPV 1 lcuts[lIdx][0][ 1] = 0.10; lcuts[lIdx][1][ 1] = 0.20; lcuts[lIdx][2][ 1] = 0.30; //DCAPostToPV 2 lcuts[lIdx][0][ 2] = 1.2; lcuts[lIdx][1][ 2] = 1.0; lcuts[lIdx][2][ 2] = 0.8; //DCAV0Daughters 3 lcuts[lIdx][0][ 3] = 2.00; lcuts[lIdx][1][ 3] = 3.00; lcuts[lIdx][2][ 3] = 4.0; //V0Radius 4 lcuts[lIdx][0][ 4] = 0.05; lcuts[lIdx][1][ 4] = 0.1; lcuts[lIdx][2][ 4] = 0.15; //DCAV0ToPV 5 lcuts[lIdx][0][ 5] =0.006; lcuts[lIdx][1][ 5] = 0.005; lcuts[lIdx][2][ 5] = 0.004; //V0Mass 6 lcuts[lIdx][0][ 6] = 0.05; lcuts[lIdx][1][ 6] = 0.10; lcuts[lIdx][2][ 6] = 0.15; //DCABachToPV 7 lcuts[lIdx][0][ 7] = 1.00; lcuts[lIdx][1][ 7] = 0.7; lcuts[lIdx][2][ 7] = 0.5; //DCACascDaughters 8 lcuts[lIdx][0][ 8] = 0.6; lcuts[lIdx][1][ 8] = 1.0; lcuts[lIdx][2][ 8] = 2.50; //CascRadius 9 lcuts[lIdx][0][ 9] = 14.0; lcuts[lIdx][1][ 9] = 12.0; lcuts[lIdx][2][ 9] = 10.0; //ProperLifetime 10 lcuts[lIdx][0][10] = 40.0; lcuts[lIdx][1][10] = 30.0; lcuts[lIdx][2][10] = 20.0; //ProperLifetimeV0 11 lcuts[lIdx][0][11] = -1; lcuts[lIdx][1][11] = 70; lcuts[lIdx][2][11] = 80; //LeastNumberOfClusters 12 lcuts[lIdx][0][12] = 5; lcuts[lIdx][1][12] = 4; lcuts[lIdx][2][12] = 3; //TPCdEdx 13 lcuts[lIdx][0][13] = 0.0; lcuts[lIdx][1][13] = 0.008; lcuts[lIdx][2][13] = 0.010; //Competing 14 //================================================================================ //================================================================================ // OMEGAPLUS SELECTIONS lIdx = 3; //Master OmegaPlus Index //-------------------------------------------------------------------------------- // LOOSE CENTRAL TIGHT lcuts[lIdx][0][ 0] = 0.10; lcuts[lIdx][1][ 0] = 0.20; lcuts[lIdx][2][ 0] = 0.30; //DCANegToPV 1 lcuts[lIdx][0][ 1] = 0.10; lcuts[lIdx][1][ 1] = 0.20; lcuts[lIdx][2][ 1] = 0.30; //DCAPostToPV 2 lcuts[lIdx][0][ 2] = 1.2; lcuts[lIdx][1][ 2] = 1.0; lcuts[lIdx][2][ 2] = 0.8; //DCAV0Daughters 3 lcuts[lIdx][0][ 3] = 2.00; lcuts[lIdx][1][ 3] = 3.00; lcuts[lIdx][2][ 3] = 4.0; //V0Radius 4 lcuts[lIdx][0][ 4] = 0.05; lcuts[lIdx][1][ 4] = 0.1; lcuts[lIdx][2][ 4] = 0.15; //DCAV0ToPV 5 lcuts[lIdx][0][ 5] =0.006; lcuts[lIdx][1][ 5] = 0.005; lcuts[lIdx][2][ 5] = 0.004; //V0Mass 6 lcuts[lIdx][0][ 6] = 0.05; lcuts[lIdx][1][ 6] = 0.10; lcuts[lIdx][2][ 6] = 0.15; //DCABachToPV 7 lcuts[lIdx][0][ 7] = 1.00; lcuts[lIdx][1][ 7] = 0.7; lcuts[lIdx][2][ 7] = 0.5; //DCACascDaughters 8 lcuts[lIdx][0][ 8] = 0.6; lcuts[lIdx][1][ 8] = 1.0; lcuts[lIdx][2][ 8] = 2.50; //CascRadius 9 lcuts[lIdx][0][ 9] = 14.0; lcuts[lIdx][1][ 9] = 12.0; lcuts[lIdx][2][ 9] = 10.0; //ProperLifetime 10 lcuts[lIdx][0][10] = 40.0; lcuts[lIdx][1][10] = 30.0; lcuts[lIdx][2][10] = 20.0; //ProperLifetimeV0 11 lcuts[lIdx][0][11] = -1; lcuts[lIdx][1][11] = 70; lcuts[lIdx][2][11] = 80; //LeastNumberOfClusters 12 lcuts[lIdx][0][12] = 5; lcuts[lIdx][1][12] = 4; lcuts[lIdx][2][12] = 3; //TPCdEdx 13 lcuts[lIdx][0][13] = 0.0; lcuts[lIdx][1][13] = 0.008; lcuts[lIdx][2][13] = 0.010; //Competing 14 //================================================================================ //STEP 3: Creation of output objects //Just a counter and one array, please. Nothing else needed AliCascadeResult *lCascadeResult[600]; Long_t lN = 0; //Map to mass hypothesis AliCascadeResult::EMassHypo lMassHypo[4]; lMassHypo[0] = AliCascadeResult::kXiMinus; lMassHypo[1] = AliCascadeResult::kXiPlus; lMassHypo[2] = AliCascadeResult::kOmegaMinus; lMassHypo[3] = AliCascadeResult::kOmegaPlus; //Central results: Stored in indices 0, 1, 2, 3 (careful!) for(Int_t i = 0 ; i < 4 ; i ++){ //Central result, customized binning: the one to use, usually lCascadeResult[lN] = new AliCascadeResult( Form("%s_Central",lParticleName[i].Data() ),lMassHypo[i],"",lCentbinnumb,lCentbinlimits, lPtbinnumb,lPtbinlimits); //This is MC: generate profile for G3/F (if ever needed) lCascadeResult[lN] -> InitializeProtonProfile(lPtbinnumb,lPtbinlimits); //Setters for V0 Cuts lCascadeResult[lN]->SetCutDCANegToPV ( lcuts[i][1][ 0] ) ; lCascadeResult[lN]->SetCutDCAPosToPV ( lcuts[i][1][ 1] ) ; lCascadeResult[lN]->SetCutDCAV0Daughters ( lcuts[i][1][ 2] ) ; lCascadeResult[lN]->SetCutV0Radius ( lcuts[i][1][ 3] ) ; //Setters for Cascade Cuts lCascadeResult[lN]->SetCutDCAV0ToPV ( lcuts[i][1][ 4] ) ; lCascadeResult[lN]->SetCutV0Mass ( lcuts[i][1][ 5] ) ; lCascadeResult[lN]->SetCutDCABachToPV ( lcuts[i][1][ 6] ) ; lCascadeResult[lN]->SetCutDCACascDaughters ( lcuts[i][1][ 7] ) ; lCascadeResult[lN]->SetCutCascRadius ( lcuts[i][1][ 8] ) ; //Miscellaneous lCascadeResult[lN]->SetCutProperLifetime ( lcuts[i][1][ 9] ) ; lCascadeResult[lN]->SetCutMaxV0Lifetime ( lcuts[i][1][10] ) ; lCascadeResult[lN]->SetCutLeastNumberOfClusters ( lcuts[i][1][11] ) ; lCascadeResult[lN]->SetCutTPCdEdx ( lcuts[i][1][12] ) ; lCascadeResult[lN]->SetCutXiRejection ( lcuts[i][1][13] ) ; //Parametric angle cut initializations //V0 cosine of pointing angle lCascadeResult[lN]->SetCutV0CosPA ( 0.95 ) ; //+variable lCascadeResult[lN]->SetCutVarV0CosPA (TMath::Exp(10.853), -25.0322, TMath::Exp(-0.843948), -0.890794, 0.057553); //Cascade cosine of pointing angle lCascadeResult[lN]->SetCutCascCosPA ( 0.95 ) ; //+variable lCascadeResult[lN]->SetCutVarCascCosPA (TMath::Exp(4.86664), -10.786, TMath::Exp(-1.33411), -0.729825, 0.0695724); //BB cosine of pointing angle lCascadeResult[lN]->SetCutBachBaryonCosPA ( TMath::Cos(0.04) ) ; //+variable lCascadeResult[lN]->SetCutVarBBCosPA (TMath::Exp(-2.29048), -20.2016, TMath::Exp(-2.9581), -0.649153, 0.00526455); //Add result to pool lN++; } //Central Full results: Stored in indices 4, 5, 6, 7 (careful!) for(Int_t i = 0 ; i < 4 ; i ++){ lCascadeResult[lN] = new AliCascadeResult( Form("%s_Central_Full",lParticleName[i].Data() ),lMassHypo[i]); //This is MC: generate profile for G3/F (if ever needed) lCascadeResult[lN] -> InitializeProtonProfile(lPtbinnumb,lPtbinlimits); //Setters for V0 Cuts lCascadeResult[lN]->SetCutDCANegToPV ( lcuts[i][1][ 0] ) ; lCascadeResult[lN]->SetCutDCAPosToPV ( lcuts[i][1][ 1] ) ; lCascadeResult[lN]->SetCutDCAV0Daughters ( lcuts[i][1][ 2] ) ; lCascadeResult[lN]->SetCutV0Radius ( lcuts[i][1][ 3] ) ; //Setters for Cascade Cuts lCascadeResult[lN]->SetCutDCAV0ToPV ( lcuts[i][1][ 4] ) ; lCascadeResult[lN]->SetCutV0Mass ( lcuts[i][1][ 5] ) ; lCascadeResult[lN]->SetCutDCABachToPV ( lcuts[i][1][ 6] ) ; lCascadeResult[lN]->SetCutDCACascDaughters ( lcuts[i][1][ 7] ) ; lCascadeResult[lN]->SetCutCascRadius ( lcuts[i][1][ 8] ) ; //Miscellaneous lCascadeResult[lN]->SetCutProperLifetime ( lcuts[i][1][ 9] ) ; lCascadeResult[lN]->SetCutMaxV0Lifetime ( lcuts[i][1][10] ) ; lCascadeResult[lN]->SetCutLeastNumberOfClusters ( lcuts[i][1][11] ) ; lCascadeResult[lN]->SetCutTPCdEdx ( lcuts[i][1][12] ) ; lCascadeResult[lN]->SetCutXiRejection ( lcuts[i][1][13] ) ; //Parametric angle cut initializations //V0 cosine of pointing angle lCascadeResult[lN]->SetCutV0CosPA ( 0.95 ) ; //+variable lCascadeResult[lN]->SetCutVarV0CosPA (TMath::Exp(10.853), -25.0322, TMath::Exp(-0.843948), -0.890794, 0.057553); //Cascade cosine of pointing angle lCascadeResult[lN]->SetCutCascCosPA ( 0.95 ) ; //+variable lCascadeResult[lN]->SetCutVarCascCosPA (TMath::Exp(4.86664), -10.786, TMath::Exp(-1.33411), -0.729825, 0.0695724); //BB cosine of pointing angle lCascadeResult[lN]->SetCutBachBaryonCosPA ( TMath::Cos(0.04) ) ; //+variable lCascadeResult[lN]->SetCutVarBBCosPA (TMath::Exp(-2.29048), -20.2016, TMath::Exp(-2.9581), -0.649153, 0.00526455); //Add result to pool lN++; } //Explore restricted rapidity range check for(Int_t i = 0 ; i < 4 ; i ++){ lCascadeResult[lN] = new AliCascadeResult( lCascadeResult[i], Form("%s_Central_y03",lParticleName[i].Data() ) ); lCascadeResult[lN] -> SetCutMinRapidity(-0.3); lCascadeResult[lN] -> SetCutMaxRapidity(+0.3); //Add result to pool lN++; } Float_t lLowRap = -0.6; Float_t lHighRap = -0.5; for(Int_t i=0;i<4;i++){ lLowRap = -0.6; lHighRap = -0.5; for(Int_t irapbin=0;irapbin<12;irapbin++){ lCascadeResult[lN] = new AliCascadeResult( lCascadeResult[i], Form("%s_%s_%f_%f",lParticleName[i].Data(),"DefaultRapiditySweep",lLowRap,lHighRap ) ); lCascadeResult[lN]->SetCutMinRapidity(lLowRap); lCascadeResult[lN]->SetCutMaxRapidity(lHighRap); lN++; lLowRap+=0.1; lHighRap+=0.1; } } // STEP 4: Creation of objects to be used in systematics // Optimized via use of copy constructors for(Int_t i = 0 ; i < 4 ; i ++){ for(Int_t iCut = 0 ; iCut < 14 ; iCut ++){ //LOOSE VARIATIONS //Create a new object from default lCascadeResult[lN] = new AliCascadeResult( lCascadeResult[i], Form("%s_%s_%s",lParticleName[i].Data(),lCutName[iCut].Data(),lConfName[0].Data()) ); if(iCut == 0 ) lCascadeResult[lN]->SetCutDCANegToPV ( lcuts[i][0][iCut] ) ; if(iCut == 1 ) lCascadeResult[lN]->SetCutDCAPosToPV ( lcuts[i][0][iCut] ) ; if(iCut == 2 ) lCascadeResult[lN]->SetCutDCAV0Daughters ( lcuts[i][0][iCut] ) ; if(iCut == 3 ) lCascadeResult[lN]->SetCutV0Radius ( lcuts[i][0][iCut] ) ; //Setters for Cascade Cuts if(iCut == 4 ) lCascadeResult[lN]->SetCutDCAV0ToPV ( lcuts[i][0][iCut] ) ; if(iCut == 5 ) lCascadeResult[lN]->SetCutV0Mass ( lcuts[i][0][iCut] ) ; if(iCut == 6 ) lCascadeResult[lN]->SetCutDCABachToPV ( lcuts[i][0][iCut] ) ; if(iCut == 7 ) lCascadeResult[lN]->SetCutDCACascDaughters ( lcuts[i][0][iCut] ) ; if(iCut == 8 ) lCascadeResult[lN]->SetCutCascRadius ( lcuts[i][0][iCut] ) ; //Miscellaneous if(iCut == 9 ) lCascadeResult[lN]->SetCutProperLifetime ( lcuts[i][0][iCut] ) ; if(iCut == 10 ) lCascadeResult[lN]->SetCutMaxV0Lifetime ( lcuts[i][0][iCut] ) ; if(iCut == 11 ) lCascadeResult[lN]->SetCutLeastNumberOfClusters ( lcuts[i][0][iCut] ) ; if(iCut == 12 ) lCascadeResult[lN]->SetCutTPCdEdx ( lcuts[i][0][iCut] ) ; if(iCut == 13 ) lCascadeResult[lN]->SetCutXiRejection ( lcuts[i][0][iCut] ) ; //Print this variation, add to pool //lCascadeResult[lN]->Print(); lN++; //TIGHT VARIATIONS //Create a new object from default lCascadeResult[lN] = new AliCascadeResult( lCascadeResult[i], Form("%s_%s_%s",lParticleName[i].Data(),lCutName[iCut].Data(),lConfName[2].Data()) ); if(iCut == 0 ) lCascadeResult[lN]->SetCutDCANegToPV ( lcuts[i][2][iCut] ) ; if(iCut == 1 ) lCascadeResult[lN]->SetCutDCAPosToPV ( lcuts[i][2][iCut] ) ; if(iCut == 2 ) lCascadeResult[lN]->SetCutDCAV0Daughters ( lcuts[i][2][iCut] ) ; if(iCut == 3 ) lCascadeResult[lN]->SetCutV0Radius ( lcuts[i][2][iCut] ) ; //Setters for Cascade Cuts if(iCut == 4 ) lCascadeResult[lN]->SetCutDCAV0ToPV ( lcuts[i][2][iCut] ) ; if(iCut == 5 ) lCascadeResult[lN]->SetCutV0Mass ( lcuts[i][2][iCut] ) ; if(iCut == 6 ) lCascadeResult[lN]->SetCutDCABachToPV ( lcuts[i][2][iCut] ) ; if(iCut == 7 ) lCascadeResult[lN]->SetCutDCACascDaughters ( lcuts[i][2][iCut] ) ; if(iCut == 8 ) lCascadeResult[lN]->SetCutCascRadius ( lcuts[i][2][iCut] ) ; //Miscellaneous if(iCut == 9 ) lCascadeResult[lN]->SetCutProperLifetime ( lcuts[i][2][iCut] ) ; if(iCut == 10 ) lCascadeResult[lN]->SetCutMaxV0Lifetime ( lcuts[i][2][iCut] ) ; if(iCut == 11 ) lCascadeResult[lN]->SetCutLeastNumberOfClusters ( lcuts[i][2][iCut] ) ; if(iCut == 12 ) lCascadeResult[lN]->SetCutTPCdEdx ( lcuts[i][2][iCut] ) ; if(iCut == 13 ) lCascadeResult[lN]->SetCutXiRejection ( lcuts[i][2][iCut] ) ; //Print this variation, add to pool //lCascadeResult[lN]->Print(); lN++; } } //STEP 5: re-parametrization of cosines for tight and loose variations (done manually) for(Int_t i = 0 ; i < 4 ; i ++){ //====================================================== //V0CosPA Variations //====================================================== lCascadeResult[lN] = new AliCascadeResult( lCascadeResult[i], Form("%s_%s_%s",lParticleName[i].Data(),"V0CosPA","Loose") ); lCascadeResult[lN]->SetCutVarV0CosPA(TMath::Exp( -1.77429), -0.692453, TMath::Exp( -2.01938), -0.201574, 0.0776465); lN++; lCascadeResult[lN] = new AliCascadeResult( lCascadeResult[i], Form("%s_%s_%s",lParticleName[i].Data(),"V0CosPA","Tight") ); lCascadeResult[lN]->SetCutVarV0CosPA(TMath::Exp( -1.21892), -41.8521, TMath::Exp( -1.278), -0.894064, 0.0303932); lN++; lCascadeResult[lN] = new AliCascadeResult( lCascadeResult[i], Form("%s_%s_%s",lParticleName[i].Data(),"V0CosPA","VeryTight") ); lCascadeResult[lN]->SetCutVarV0CosPA(TMath::Exp( 12.8077), -21.2944, TMath::Exp( -1.53357), -0.920017, 0.0262315); lN++; //====================================================== //CascCosPA Variations //====================================================== lCascadeResult[lN] = new AliCascadeResult( lCascadeResult[i], Form("%s_%s_%s",lParticleName[i].Data(),"CascCosPA","Loose") ); lCascadeResult[lN]->SetCutVarCascCosPA(TMath::Exp( -1.77429), -0.692453, TMath::Exp( -2.01938), -0.201574, 0.0776465); lN++; lCascadeResult[lN] = new AliCascadeResult( lCascadeResult[i], Form("%s_%s_%s",lParticleName[i].Data(),"CascCosPA","Tight") ); lCascadeResult[lN]->SetCutVarCascCosPA(TMath::Exp( 12.8752), -21.522, TMath::Exp( -1.49906), -0.813472, 0.0480962); lN++; lCascadeResult[lN] = new AliCascadeResult( lCascadeResult[i], Form("%s_%s_%s",lParticleName[i].Data(),"CascCosPA","VeryTight") ); lCascadeResult[lN]->SetCutVarCascCosPA(TMath::Exp( 12.801), -21.6157, TMath::Exp( -1.66297), -0.889246, 0.0346838); lN++; //====================================================== //BBCosPA Variations //====================================================== lCascadeResult[lN] = new AliCascadeResult( lCascadeResult[i], Form("%s_%s_%s",lParticleName[i].Data(),"BBCosPA","Loose") ); lCascadeResult[lN]->SetCutBachBaryonCosPA ( TMath::Cos(0.03) ) ; lCascadeResult[lN]->SetCutVarBBCosPA(TMath::Exp( -2.8798), -20.9876, TMath::Exp( -3.10847), -0.73045, 0.00235147); lN++; lCascadeResult[lN] = new AliCascadeResult( lCascadeResult[i], Form("%s_%s_%s",lParticleName[i].Data(),"BBCosPA","Tight") ); lCascadeResult[lN]->SetCutBachBaryonCosPA ( TMath::Cos(0.05) ) ; lCascadeResult[lN]->SetCutVarBBCosPA(TMath::Exp( 12.4606), -20.578, TMath::Exp( -2.41442), -0.709588, 0.01079); lN++; } //STEP 6: V0 Mass sweep //for(Int_t i = 0 ; i < 4 ; i ++){ // for(Int_t isweep=0; isweep<20;isweep++){ // lCascadeResult[lN] = new AliCascadeResult( lCascadeResult[i], Form("%s_V0MassSweep_%i",lParticleName[i].Data(),isweep) ); // lCascadeResult[lN]->SetCutV0MassSigma( ((Double_t)(isweep)/4000.0)); //in GeV/c^2 // lN++; // } //} Float_t lLifetimeCut[4]; lLifetimeCut[0] = 15.0; lLifetimeCut[1] = 15.0; lLifetimeCut[2] = 12.0; lLifetimeCut[3] = 12.0; Float_t lMass[4]; lMass[0] = 1.322; lMass[1] = 1.322; lMass[2] = 1.672; lMass[3] = 1.672; //Old vertexer-level configuration for cross-checks for(Int_t i = 0 ; i < 4 ; i ++){ //Central result, customized binning: the one to use, usually lCascadeResult[lN] = new AliCascadeResult( Form("%s_VertexerLevel",lParticleName[i].Data() ),lMassHypo[i],"",lCentbinnumb,lCentbinlimits, lPtbinnumb,lPtbinlimits,100,lMass[i]-0.050,lMass[i]+0.050); //This is MC: generate profile for G3/F (if ever needed) lCascadeResult[lN] -> InitializeProtonProfile(lPtbinnumb,lPtbinlimits); //Default cuts: use vertexer level ones //Setters for V0 Cuts lCascadeResult[lN]->SetCutDCANegToPV ( 0.2 ) ; lCascadeResult[lN]->SetCutDCAPosToPV ( 0.2 ) ; lCascadeResult[lN]->SetCutDCAV0Daughters ( 1. ) ; lCascadeResult[lN]->SetCutV0CosPA ( 0.98 ) ; lCascadeResult[lN]->SetCutV0Radius ( 3 ) ; //Setters for Cascade Cuts lCascadeResult[lN]->SetCutDCAV0ToPV ( 0.1 ) ; lCascadeResult[lN]->SetCutV0Mass ( 0.006 ) ; lCascadeResult[lN]->SetCutDCABachToPV ( 0.03 ) ; lCascadeResult[lN]->SetCutDCACascDaughters ( 1. ) ; lCascadeResult[lN]->SetCutCascRadius ( 1.2 ) ; if(i==2||i==3) lCascadeResult[lN]->SetCutCascRadius ( 1.0 ) ; //omega case lCascadeResult[lN]->SetCutCascCosPA ( 0.98 ) ; //Miscellaneous lCascadeResult[lN]->SetCutProperLifetime ( lLifetimeCut[i] ) ; lCascadeResult[lN]->SetCutLeastNumberOfClusters ( 70.0 ) ; lCascadeResult[lN]->SetCutTPCdEdx ( 4.0 ) ; lCascadeResult[lN]->SetCutXiRejection ( 0.008 ) ; lCascadeResult[lN]->SetCutBachBaryonCosPA ( TMath::Cos(0.006) ) ; //Add result to pool lN++; } cout<<"Added "<<lN<<" Cascade configurations to output."<<endl; for (Int_t iconf = 0; iconf<lN; iconf++) AddConfiguration(lCascadeResult[iconf]); //Add V0 configuration for the determination of mass and width of the Lambda peak //Map to mass hypothesis AliV0Result::EMassHypo lMassHypoV0[3]; lMassHypoV0[0] = AliV0Result::kK0Short; lMassHypoV0[1] = AliV0Result::kLambda; lMassHypoV0[2] = AliV0Result::kAntiLambda; //Array of results AliV0Result *lV0Result[500]; Long_t lNV0 = 0; TString lParticleNameV0[] = {"K0Short", "Lambda", "AntiLambda"}; //Central results: Stored in indices 0, 1, 2 (careful!) for(Int_t i = 0 ; i < 3 ; i ++){ //Central result, customized binning: the one to use, usually lV0Result[lNV0] = new AliV0Result( Form("%s_Central",lParticleNameV0[i].Data() ),lMassHypoV0[i],"",lCentbinnumb,lCentbinlimits, lPtbinnumb,lPtbinlimits); //Setters for V0 Cuts lV0Result[lNV0]->SetCutDCANegToPV ( lcuts[0][1][ 0] ) ; lV0Result[lNV0]->SetCutDCAPosToPV ( lcuts[0][1][ 1] ) ; lV0Result[lNV0]->SetCutDCAV0Daughters ( lcuts[0][1][ 2] ) ; lV0Result[lNV0]->SetCutV0CosPA ( 0.95 ) ; //+variable lV0Result[lNV0]->SetCutVarV0CosPA (TMath::Exp(10.853), -25.0322, TMath::Exp(-0.843948), -0.890794, 0.057553); lV0Result[lNV0]->SetCutV0Radius ( lcuts[0][1][ 3] ) ; //Add result to pool lNV0++; } for (Int_t iconf = 0; iconf<lNV0; iconf++) AddConfiguration(lV0Result[iconf]); cout<<"Added "<<lN<<" Cascade configurations to output."<<endl; cout<<"Added "<<lNV0<<" V0 configurations to output."<<endl; } //________________________________________________________________________ void AliAnalysisTaskStrEffStudy::AddCascadeConfiguration276TeV() //Adds 2.76 TeV cascade analysis configuration { // STEP 1: Decide on binning (needed to improve on memory consumption) // pT binning Double_t lPtbinlimits[] = {0.4, 0.5, 0.6, 0.7,0.8,.9,1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0, 2.1,2.2,2.3,2.4,2.5,2.6,2.7,2.8,3.0,3.2,3.4,3.6,3.8,4.0,4.2, 4.4,4.6,4.8,5.0,5.5,6.0,6.5,7.0,8.0,9.0,10.,11.,12.}; Long_t lPtbinnumb = sizeof(lPtbinlimits)/sizeof(Double_t) - 1; // centrality binning Double_t lCentbinlimits[] = {0, 1, 5, 10, 20, 30, 40, 50, 60, 70, 80, 85, 90}; Long_t lCentbinnumb = sizeof(lCentbinlimits)/sizeof(Double_t) - 1; // TStrings for output names TString lParticleName[] = {"XiMinus", "XiPlus", "OmegaMinus", "OmegaPlus"}; //Just a counter and one array, please. Nothing else needed AliCascadeResult *lCascadeResult[100]; Long_t lN = 0; //Map to mass hypothesis AliCascadeResult::EMassHypo lMassHypo[4]; lMassHypo[0] = AliCascadeResult::kXiMinus; lMassHypo[1] = AliCascadeResult::kXiPlus; lMassHypo[2] = AliCascadeResult::kOmegaMinus; lMassHypo[3] = AliCascadeResult::kOmegaPlus; for(Int_t i = 0 ; i < 4 ; i ++){ //2.76 Config result, customized binning: the one to use, usually lCascadeResult[lN] = new AliCascadeResult( Form("%s_276TeV",lParticleName[i].Data() ),lMassHypo[i],"",lCentbinnumb,lCentbinlimits, lPtbinnumb,lPtbinlimits); lCascadeResult[lN] -> InitializeProtonProfile(lPtbinnumb,lPtbinlimits); //Setters for V0 Cuts lCascadeResult[lN]->SetCutDCANegToPV ( 0.1 ) ; lCascadeResult[lN]->SetCutDCAPosToPV ( 0.1 ) ; lCascadeResult[lN]->SetCutDCAV0Daughters ( 0.8 ) ; lCascadeResult[lN]->SetCutV0CosPA ( 0.998 ) ; lCascadeResult[lN]->SetCutV0Radius ( 3.0 ) ; //Setters for Cascade Cuts lCascadeResult[lN]->SetCutDCAV0ToPV ( 0.1 ) ; lCascadeResult[lN]->SetCutV0Mass ( 0.005 ) ; lCascadeResult[lN]->SetCutDCABachToPV ( 0.03 ) ; lCascadeResult[lN]->SetCutDCACascDaughters ( 0.3 ) ; lCascadeResult[lN]->SetCutCascRadius ( 1.5 ) ; lCascadeResult[lN]->SetCutCascCosPA ( 0.9992 ) ; //Miscellaneous lCascadeResult[lN]->SetCutProperLifetime ( 15.0 ) ; lCascadeResult[lN]->SetCutLeastNumberOfClusters ( 70 ) ; lCascadeResult[lN]->SetCutTPCdEdx ( 4 ) ; lCascadeResult[lN]->SetCutXiRejection ( 0.008 ) ; lCascadeResult[lN]->SetCutDCABachToBaryon ( 0 ) ; if(i > 1){ lCascadeResult[lN]->SetCutCascRadius ( 1.0 ) ; lCascadeResult[lN]->SetCutProperLifetime ( 8.0 ) ; } //Add result to pool lN++; } //Explore restricted rapidity range check for(Int_t i = 0 ; i < 4 ; i ++){ lCascadeResult[lN] = new AliCascadeResult( lCascadeResult[i], Form("%s_276TeV_y03",lParticleName[i].Data() ) ); lCascadeResult[lN] -> SetCutMinRapidity(-0.3); lCascadeResult[lN] -> SetCutMaxRapidity(+0.3); //Add result to pool lN++; } Float_t lLowRap = -0.6; Float_t lHighRap = -0.5; for(Int_t i=0;i<4;i++){ lLowRap = -0.6; lHighRap = -0.5; for(Int_t irapbin=0;irapbin<12;irapbin++){ lCascadeResult[lN] = new AliCascadeResult( lCascadeResult[i], Form("%s_%s_%f_%f",lParticleName[i].Data(),"276TeVRapiditySweep",lLowRap,lHighRap ) ); lCascadeResult[lN]->SetCutMinRapidity(lLowRap); lCascadeResult[lN]->SetCutMaxRapidity(lHighRap); lN++; lLowRap+=0.1; lHighRap+=0.1; } } for (Int_t iconf = 0; iconf<lN; iconf++) AddConfiguration(lCascadeResult[iconf]); cout<<"Added "<<lN<<" cascade configurations to output (corresponding to 2.76 TeV analysis cuts)"<<endl; } //________________________________________________________________________ Float_t AliAnalysisTaskStrEffStudy::GetDCAz(AliESDtrack *lTrack) //Encapsulation of DCAz calculation { Float_t b[2]; Float_t bCov[3]; lTrack->GetImpactParameters(b,bCov); if (bCov[0]<=0 || bCov[2]<=0) { AliDebug(1, "Estimated b resolution lower or equal to zero!"); bCov[0]=0; bCov[2]=0; } Float_t dcaToVertexXY = b[0]; Float_t dcaToVertexZ = b[1]; return dcaToVertexZ; } //________________________________________________________________________ Float_t AliAnalysisTaskStrEffStudy::GetCosPA(AliESDtrack *lPosTrack, AliESDtrack *lNegTrack, AliESDEvent *lEvent) //Encapsulation of CosPA calculation (warning: considers AliESDtrack clones) { Float_t lCosPA = -1; AliESDtrack* lNegClone = (AliESDtrack*) lNegTrack->Clone("lNegClone"); //need clone, in order not to change track parameters AliESDtrack* lPosClone = (AliESDtrack*) lPosTrack->Clone("lPosClone"); //need clone, in order not to change track parameters //Get Magnetic field and primary vertex Double_t b=lEvent->GetMagneticField(); const AliESDVertex *vtxT3D=lEvent->GetPrimaryVertex(); Double_t xPrimaryVertex=vtxT3D->GetX(); Double_t yPrimaryVertex=vtxT3D->GetY(); Double_t zPrimaryVertex=vtxT3D->GetZ(); //Get ExternalTrackParam AliExternalTrackParam nt(*lNegClone), pt(*lPosClone); //Find DCA Double_t xn, xp, dca=lNegClone->GetDCA(lPosClone,b,xn,xp); //Propagate to it nt.PropagateTo(xn,b); pt.PropagateTo(xp,b); //Create V0 object to do propagation AliESDv0 vertex(nt,1,pt,2); //Never mind indices, won't use //Get CosPA lCosPA=vertex.GetV0CosineOfPointingAngle(xPrimaryVertex,yPrimaryVertex,zPrimaryVertex); //Cleanup delete lNegClone; delete lPosClone; //Return value return lCosPA; } //________________________________________________________________________ void AliAnalysisTaskStrEffStudy::CheckChargeV0(AliESDv0 *v0) { // This function checks charge of negative and positive daughter tracks. // If incorrectly defined (onfly vertexer), swaps out. if( v0->GetParamN()->Charge() > 0 && v0->GetParamP()->Charge() < 0 ) { //V0 daughter track swapping is required! Note: everything is swapped here... P->N, N->P Long_t lCorrectNidx = v0->GetPindex(); Long_t lCorrectPidx = v0->GetNindex(); Double32_t lCorrectNmom[3]; Double32_t lCorrectPmom[3]; v0->GetPPxPyPz( lCorrectNmom[0], lCorrectNmom[1], lCorrectNmom[2] ); v0->GetNPxPyPz( lCorrectPmom[0], lCorrectPmom[1], lCorrectPmom[2] ); AliExternalTrackParam lCorrectParamN( v0->GetParamP()->GetX() , v0->GetParamP()->GetAlpha() , v0->GetParamP()->GetParameter() , v0->GetParamP()->GetCovariance() ); AliExternalTrackParam lCorrectParamP( v0->GetParamN()->GetX() , v0->GetParamN()->GetAlpha() , v0->GetParamN()->GetParameter() , v0->GetParamN()->GetCovariance() ); lCorrectParamN.SetMostProbablePt( v0->GetParamP()->GetMostProbablePt() ); lCorrectParamP.SetMostProbablePt( v0->GetParamN()->GetMostProbablePt() ); //Get Variables___________________________________________________ Double_t lDcaV0Daughters = v0 -> GetDcaV0Daughters(); Double_t lCosPALocal = v0 -> GetV0CosineOfPointingAngle(); Bool_t lOnFlyStatusLocal = v0 -> GetOnFlyStatus(); //Create Replacement Object_______________________________________ AliESDv0 *v0correct = new AliESDv0(lCorrectParamN,lCorrectNidx,lCorrectParamP,lCorrectPidx); v0correct->SetDcaV0Daughters ( lDcaV0Daughters ); v0correct->SetV0CosineOfPointingAngle ( lCosPALocal ); v0correct->ChangeMassHypothesis ( kK0Short ); v0correct->SetOnFlyStatus ( lOnFlyStatusLocal ); //Reverse Cluster info..._________________________________________ v0correct->SetClusters( v0->GetClusters( 1 ), v0->GetClusters ( 0 ) ); *v0 = *v0correct; //Proper cleanup..._______________________________________________ v0correct->Delete(); v0correct = 0x0; //Just another cross-check and output_____________________________ if( v0->GetParamN()->Charge() > 0 && v0->GetParamP()->Charge() < 0 ) { AliWarning("Found Swapped Charges, tried to correct but something FAILED!"); } else { //AliWarning("Found Swapped Charges and fixed."); } //________________________________________________________________ } else { //Don't touch it! --- //Printf("Ah, nice. Charges are already ordered..."); } return; } //______________________________________________________________________ AliAnalysisTaskStrEffStudy::FMDhits AliAnalysisTaskStrEffStudy::GetFMDhits(AliAODEvent* aodEvent) const // Relies on the event being vaild (no extra checks if object exists done here) { AliAODForwardMult* aodForward = static_cast<AliAODForwardMult*>(aodEvent->FindListObject("Forward")); // Shape of d2Ndetadphi: 200, -4, 6, 20, 0, 2pi const TH2D& d2Ndetadphi = aodForward->GetHistogram(); Int_t nEta = d2Ndetadphi.GetXaxis()->GetNbins(); Int_t nPhi = d2Ndetadphi.GetYaxis()->GetNbins(); FMDhits ret_vector; for (Int_t iEta = 1; iEta <= nEta; iEta++) { Int_t valid = Int_t(d2Ndetadphi.GetBinContent(iEta, 0)); if (!valid) { // No data expected for this eta continue; } Float_t eta = d2Ndetadphi.GetXaxis()->GetBinCenter(iEta); for (Int_t iPhi = 1; iPhi <= nPhi; iPhi++) { // Bin content is most likely number of particles! Float_t mostProbableN = d2Ndetadphi.GetBinContent(iEta, iPhi); if (mostProbableN > 0) { Float_t phi = d2Ndetadphi.GetYaxis()->GetBinCenter(iPhi); ret_vector.push_back(AliAnalysisTaskStrEffStudy::FMDhit(eta, phi, mostProbableN)); } } } return ret_vector; } //________________________________________________________________________ Double_t AliAnalysisTaskStrEffStudy::Det(Double_t a00, Double_t a01, Double_t a10, Double_t a11) const { //-------------------------------------------------------------------- // This function calculates locally a 2x2 determinant //-------------------------------------------------------------------- return a00*a11 - a01*a10; } //________________________________________________________________________ Double_t AliAnalysisTaskStrEffStudy::Det(Double_t a00,Double_t a01,Double_t a02, Double_t a10,Double_t a11,Double_t a12, Double_t a20,Double_t a21,Double_t a22) const { //-------------------------------------------------------------------- // This function calculates locally a 3x3 determinant //-------------------------------------------------------------------- return a00*Det(a11,a12,a21,a22)-a01*Det(a10,a12,a20,a22)+a02*Det(a10,a11,a20,a21); } //________________________________________________________________________ Double_t AliAnalysisTaskStrEffStudy::PropagateToDCA(AliESDv0 *v, AliExternalTrackParam *t, AliESDEvent *event, Double_t b) { //-------------------------------------------------------------------- // This function returns the DCA between the V0 and the track //-------------------------------------------------------------------- Double_t alpha=t->GetAlpha(), cs1=TMath::Cos(alpha), sn1=TMath::Sin(alpha); Double_t r[3]; t->GetXYZ(r); Double_t x1=r[0], y1=r[1], z1=r[2]; Double_t p[3]; t->GetPxPyPz(p); Double_t px1=p[0], py1=p[1], pz1=p[2]; Double_t x2,y2,z2; // position and momentum of V0 Double_t px2,py2,pz2; v->GetXYZ(x2,y2,z2); v->GetPxPyPz(px2,py2,pz2); Double_t dca = 1e+33; if ( !fkDoImprovedCascadeVertexFinding || fkIfImprovedPerformInitialLinearPropag ){ // calculation dca Double_t dd= Det(x2-x1,y2-y1,z2-z1,px1,py1,pz1,px2,py2,pz2); Double_t ax= Det(py1,pz1,py2,pz2); Double_t ay=-Det(px1,pz1,px2,pz2); Double_t az= Det(px1,py1,px2,py2); dca=TMath::Abs(dd)/TMath::Sqrt(ax*ax + ay*ay + az*az); //points of the DCA Double_t t1 = Det(x2-x1,y2-y1,z2-z1,px2,py2,pz2,ax,ay,az)/ Det(px1,py1,pz1,px2,py2,pz2,ax,ay,az); x1 += px1*t1; y1 += py1*t1; //z1 += pz1*t1; //propagate track to the points of DCA x1=x1*cs1 + y1*sn1; if (!t->PropagateTo(x1,b)) { Error("PropagateToDCA","Propagation failed !"); return 1.e+33; } } if( fkDoImprovedCascadeVertexFinding ){ //DCA Calculation improved -> non-linear propagation //Preparatory step 1: get two tracks corresponding to V0 UInt_t lKeyPos = (UInt_t)TMath::Abs(v->GetPindex()); UInt_t lKeyNeg = (UInt_t)TMath::Abs(v->GetNindex()); AliESDtrack *pTrack=((AliESDEvent*)event)->GetTrack(lKeyPos); AliESDtrack *nTrack=((AliESDEvent*)event)->GetTrack(lKeyNeg); //Uncertainties: bachelor track as well as V0 Double_t dy2=t->GetSigmaY2() + pTrack->GetSigmaY2() + nTrack->GetSigmaY2(); Double_t dz2=t->GetSigmaZ2() + pTrack->GetSigmaZ2() + nTrack->GetSigmaZ2(); Double_t dx2=dy2; //For testing purposes dx2 = dx2/fkIfImprovedExtraPrecisionFactor; dy2 = dy2/fkIfImprovedExtraPrecisionFactor; dz2 = dz2/fkIfImprovedExtraPrecisionFactor; //Create dummy V0 track //V0 properties to get started Double_t xyz[3], pxpypz[3], cv[21]; for(Int_t ii=0;ii<21;ii++) cv[ii]=0.0; //something small v->GetXYZ(xyz[0],xyz[1],xyz[2]); v->GetPxPyPz( pxpypz[0],pxpypz[1],pxpypz[2] ); //Mockup track for V0 trajectory (no covariance) AliExternalTrackParam *hV0Traj = new AliExternalTrackParam(xyz,pxpypz,cv,+1); hV0Traj->ResetCovariance(1); //won't use Double_t p1[8]; t->GetHelixParameters(p1,b); p1[6]=TMath::Sin(p1[2]); p1[7]=TMath::Cos(p1[2]); Double_t p2[8]; hV0Traj->GetHelixParameters(p2,0.0); //p2[4]=0 -> no curvature (fine, predicted in Evaluate) p2[6]=TMath::Sin(p2[2]); p2[7]=TMath::Cos(p2[2]); Double_t r1[3],g1[3],gg1[3]; Double_t t1=0.; Evaluate(p1,t1,r1,g1,gg1); Double_t r2[3],g2[3],gg2[3]; Double_t t2=0.; Evaluate(p2,t2,r2,g2,gg2); Double_t dx=r2[0]-r1[0], dy=r2[1]-r1[1], dz=r2[2]-r1[2]; Double_t dm=dx*dx/dx2 + dy*dy/dy2 + dz*dz/dz2; Int_t max=27; while (max--) { Double_t gt1=-(dx*g1[0]/dx2 + dy*g1[1]/dy2 + dz*g1[2]/dz2); Double_t gt2=+(dx*g2[0]/dx2 + dy*g2[1]/dy2 + dz*g2[2]/dz2); Double_t h11=(g1[0]*g1[0] - dx*gg1[0])/dx2 + (g1[1]*g1[1] - dy*gg1[1])/dy2 + (g1[2]*g1[2] - dz*gg1[2])/dz2; Double_t h22=(g2[0]*g2[0] + dx*gg2[0])/dx2 + (g2[1]*g2[1] + dy*gg2[1])/dy2 + (g2[2]*g2[2] + dz*gg2[2])/dz2; Double_t h12=-(g1[0]*g2[0]/dx2 + g1[1]*g2[1]/dy2 + g1[2]*g2[2]/dz2); Double_t det=h11*h22-h12*h12; Double_t dt1,dt2; if (TMath::Abs(det)<1.e-33) { //(quasi)singular Hessian dt1=-gt1; dt2=-gt2; } else { dt1=-(gt1*h22 - gt2*h12)/det; dt2=-(h11*gt2 - h12*gt1)/det; } if ((dt1*gt1+dt2*gt2)>0) {dt1=-dt1; dt2=-dt2;} //check delta(phase1) ? //check delta(phase2) ? if (TMath::Abs(dt1)/(TMath::Abs(t1)+1.e-3) < 1.e-4) if (TMath::Abs(dt2)/(TMath::Abs(t2)+1.e-3) < 1.e-4) { if ((gt1*gt1+gt2*gt2) > 1.e-4/dy2/dy2) AliDebug(1," stopped at not a stationary point !"); Double_t lmb=h11+h22; lmb=lmb-TMath::Sqrt(lmb*lmb-4*det); if (lmb < 0.) AliDebug(1," stopped at not a minimum !"); break; } Double_t dd=dm; for (Int_t div=1 ; ; div*=2) { Evaluate(p1,t1+dt1,r1,g1,gg1); Evaluate(p2,t2+dt2,r2,g2,gg2); dx=r2[0]-r1[0]; dy=r2[1]-r1[1]; dz=r2[2]-r1[2]; dd=dx*dx/dx2 + dy*dy/dy2 + dz*dz/dz2; if (dd<dm) break; dt1*=0.5; dt2*=0.5; if (div>512) { AliDebug(1," overshoot !"); break; } } dm=dd; t1+=dt1; t2+=dt2; } if (max<=0) AliDebug(1," too many iterations !"); Double_t cs=TMath::Cos(t->GetAlpha()); Double_t sn=TMath::Sin(t->GetAlpha()); Double_t xthis=r1[0]*cs + r1[1]*sn; //Memory cleanup hV0Traj->Delete(); hV0Traj=0x0; //Propagate bachelor to the point of DCA if (!t->PropagateTo(xthis,b)) { //AliWarning(" propagation failed !"; return 1e+33; } //V0 distance to bachelor: the desired distance Double_t rBachDCAPt[3]; t->GetXYZ(rBachDCAPt); dca = v->GetD(rBachDCAPt[0],rBachDCAPt[1],rBachDCAPt[2]); } return dca; } //________________________________________________________________________ void AliAnalysisTaskStrEffStudy::Evaluate(const Double_t *h, Double_t t, Double_t r[3], //radius vector Double_t g[3], //first defivatives Double_t gg[3]) //second derivatives { //-------------------------------------------------------------------- // Calculate position of a point on a track and some derivatives //-------------------------------------------------------------------- Double_t phase=h[4]*t+h[2]; Double_t sn=TMath::Sin(phase), cs=TMath::Cos(phase); r[0] = h[5]; r[1] = h[0]; if (TMath::Abs(h[4])>kAlmost0) { r[0] += (sn - h[6])/h[4]; r[1] -= (cs - h[7])/h[4]; } else { r[0] += t*cs; r[1] -= -t*sn; } r[2] = h[1] + h[3]*t; g[0] = cs; g[1]=sn; g[2]=h[3]; gg[0]=-h[4]*sn; gg[1]=h[4]*cs; gg[2]=0.; } //________________________________________________________________________ Double_t AliAnalysisTaskStrEffStudy::GetErrorInPosition(AliExternalTrackParam *t1) const { Double_t alpha=t1->GetAlpha(), cs=TMath::Cos(alpha), sn=TMath::Sin(alpha); Double_t tmp[3]; t1->GetPxPyPz(tmp); Double_t px1=tmp[0], py1=tmp[1], pz1=tmp[2]; t1->GetXYZ(tmp); Double_t x1=tmp[0], y1=tmp[1], z1=tmp[2]; const Double_t ss=0.0005*0.0005;//a kind of a residual misalignment precision Double_t sx1=sn*sn*t1->GetSigmaY2()+ss, sy1=cs*cs*t1->GetSigmaY2()+ss; return sx1; }
d83696545f645cfe95046a523030845cd925ab1d
3047545349bf224a182b2c33bf1f110aef1ce9b6
/Transims60/Converge_Service/Get_Trip_Gap.cpp
a731f934f9d772667b4803808fe5869d14fe52bd
[]
no_license
qingswu/Transim
585afe71d9666557cff53f6683cf54348294954c
f182d1639a4db612dd7b43a379a3fa344c2de9ea
refs/heads/master
2021-01-10T21:04:50.576267
2015-04-08T19:07:28
2015-04-08T19:07:28
35,232,171
1
1
null
null
null
null
UTF-8
C++
false
false
3,071
cpp
//********************************************************* // Get_Trip_Gap.cpp - process trip gap data //********************************************************* #include "Converge_Service.hpp" //--------------------------------------------------------- // Get_Trip_Gap //--------------------------------------------------------- double Converge_Service::Get_Trip_Gap (void) { int i, num, period; double diff, imp, sum_diff, total, gap; bool gap_flag; Trip_Gap_Map_Itr itr; Gap_Sum gap_sum; Doubles period_diff, period_sum; num = 0; sum_diff = total = gap = 0.0; memset (&gap_sum, '\0', sizeof (gap_sum)); gap_flag = (trip_gap_flag || trip_report_flag); if (gap_flag) { num = dat->sum_periods.Num_Periods (); period_diff.assign (num, 0); period_sum.assign (num, 0); } //---- process each trip ---- if (memory_flag) { Gap_Data_Itr gap_itr; for (gap_itr = gap_data_array.begin (); gap_itr != gap_data_array.end (); gap_itr++) { total += imp = gap_itr->current; sum_diff += diff = abs (imp - gap_itr->previous); gap_itr->previous = gap_itr->current; gap_itr->current = 0; if (trip_report_flag) { gap_sum.count++; gap_sum.abs_diff += diff; gap_sum.diff_sq += diff * diff; gap_sum.current += imp; if (imp > 0) { gap = diff / imp; if (gap > gap_sum.max_gap) gap_sum.max_gap = gap; } } if (gap_flag) { period = dat->sum_periods.Period (gap_itr->time); if (period >= 0) { period_diff [period] += diff; period_sum [period] += imp; } } } } else { for (i=0; i < num_parts; i++) { Trip_Gap_Map *trip_gap_map_ptr = trip_gap_map_array [i]; for (itr = trip_gap_map_ptr->begin (); itr != trip_gap_map_ptr->end (); itr++) { total += imp = itr->second.current; sum_diff += diff = abs (imp - itr->second.previous); itr->second.previous = itr->second.current; itr->second.current = 0; if (trip_report_flag) { gap_sum.count++; gap_sum.abs_diff += diff; gap_sum.diff_sq += diff * diff; gap_sum.current += imp; if (imp > 0) { gap = diff / imp; if (gap > gap_sum.max_gap) gap_sum.max_gap = gap; } } if (gap_flag) { period = dat->sum_periods.Period (itr->second.time); if (period >= 0) { period_diff [period] += diff; period_sum [period] += imp; } } } } } //---- process the iteration data ---- if (total > 0) { gap = sum_diff / total; } else if (sum_diff > 0) { gap = 1.0; } else { gap = 0.0; } //---- write the trip gap file ---- if (gap_flag) { for (i=0; i < num; i++) { imp = period_sum [i]; diff = period_diff [i]; if (imp > 0) { diff = diff / imp; } else if (diff > 0) { diff = 1.0; } else { diff = 0.0; } Write_Trip_Gap (diff); } Write_Trip_Gap (gap, true); if (trip_report_flag) { trip_gap_array.push_back (gap_sum); } } return (gap); }
[ "davidroden@7728d46c-9721-0410-b1ea-f014b4b56054" ]
davidroden@7728d46c-9721-0410-b1ea-f014b4b56054
f01021e74cec747e76b19f235b3ef4432b3204e9
9f25ac38773b5ccdc0247c9d43948d50e60ab97a
/third_party/blink/renderer/core/layout/ng/ng_replaced_layout_algorithm.cc
e2b05dad4d9d9d076d1fc7d9fde6c6b0d17c1844
[ "LGPL-2.0-only", "BSD-2-Clause", "LGPL-2.1-only", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "GPL-1.0-or-later", "GPL-2.0-only", "LicenseRef-scancode-other-copyleft", "MIT", "Apache-2.0", "BSD-3-Clause" ]
permissive
liang0/chromium
e206553170eab7b4ac643ef7edc8cc57d4c74342
7a028876adcc46c7f7079f894a810ea1f511c3a7
refs/heads/main
2023-03-25T05:49:21.688462
2021-04-28T06:07:52
2021-04-28T06:07:52
362,370,889
1
0
BSD-3-Clause
2021-04-28T07:04:42
2021-04-28T07:04:41
null
UTF-8
C++
false
false
1,971
cc
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/layout/ng/ng_replaced_layout_algorithm.h" #include "third_party/blink/renderer/core/layout/layout_box.h" #include "third_party/blink/renderer/core/layout/layout_replaced.h" namespace blink { NGReplacedLayoutAlgorithm::NGReplacedLayoutAlgorithm( const NGLayoutAlgorithmParams& params) : NGLayoutAlgorithm(params), // TODO(dgrogan): Use something from NGLayoutInputNode instead of // accessing LayoutBox directly. natural_size_(PhysicalSize(Node().GetLayoutBox()->IntrinsicSize()) .ConvertToLogical(Style().GetWritingMode())) {} const NGLayoutResult* NGReplacedLayoutAlgorithm::Layout() { DCHECK(!BreakToken() || BreakToken()->IsBreakBefore()); // Set this as a legacy root so that legacy painters are used. container_builder_.SetIsLegacyLayoutRoot(); // TODO(dgrogan): |natural_size_.block_size| is frequently not the correct // intrinsic block size. Move |ComputeIntrinsicBlockSizeForAspectRatioElement| // from NGFlexLayoutAlgorithm to ng_length_utils and call it here. LayoutUnit intrinsic_block_size = natural_size_.block_size; container_builder_.SetIntrinsicBlockSize(intrinsic_block_size + BorderPadding().BlockSum()); return container_builder_.ToBoxFragment(); } // TODO(dgrogan): |natural_size_.inline_size| is frequently not the correct // intrinsic inline size. Move NGFlexLayoutAlgorithm's // |ComputeIntrinsicInlineSizeForAspectRatioElement| to here. MinMaxSizesResult NGReplacedLayoutAlgorithm::ComputeMinMaxSizes( const MinMaxSizesFloatInput&) const { MinMaxSizes sizes({natural_size_.inline_size, natural_size_.inline_size}); sizes += BorderScrollbarPadding().InlineSum(); return {sizes, false}; } } // namespace blink
8ff9882f0930025ebf5e27a11b51f81b58326ded
d6fcbc713b0e720be2cf96abfca5abfdda33279e
/DragonCore/src/Platform/SFML/Graphics/SfmlTexture.cpp
16f5e7eb676027d11301165e137397b8bb7190e4
[]
no_license
dylanwijnen1/DragonEngine
b72ed0f4c95802319862b65999ba769e384a1115
9ee3d248882a6c0d309b173e2198b8bb2b4ca784
refs/heads/master
2020-05-30T01:32:26.071862
2020-03-12T05:03:49
2020-03-12T05:03:49
189,479,199
0
0
null
null
null
null
UTF-8
C++
false
false
964
cpp
#include "SfmlTexture.h" #include <SFML/Graphics/Texture.hpp> namespace dragon { SfmlTexture::~SfmlTexture() { delete m_pTexture; m_pTexture = nullptr; } bool SfmlTexture::LoadFromFile(const char* filename) { m_pTexture = new sf::Texture(); if (!m_pTexture->loadFromFile(filename)) { Destroy(); return false; } return true; } bool SfmlTexture::LoadFromMemory(const dragon::Byte* pData, size_t size) { m_pTexture = new sf::Texture(); if (!m_pTexture->loadFromMemory((void*)pData, size)) { Destroy(); return false; } return true; } void SfmlTexture::Destroy() { delete m_pTexture; m_pTexture = nullptr; } Vector2f SfmlTexture::GetSize() const { dragon::Vector2f size = { 0.f, 0.f }; if (m_pTexture) { sf::Vector2u texSize = m_pTexture->getSize(); size.x = (float)texSize.x; size.y = (float)texSize.y; } return size; } }
3f0e431f043c62cde3f44d8021f5d16e498d8880
2e59275322981cf8662fe6de525eb747a0a21371
/project_1/DFA.cpp
78224cf0771fdb7b45fcfc206da32523f9425b09
[]
no_license
colesteaks/EECS_665
e72e62f3c5b94beac1a8ce625bd55dd55f77a368
7b7a2b61ac88c80be1fe90e0e435e8f7752b28f0
refs/heads/master
2021-06-08T20:27:29.353025
2016-12-02T01:18:24
2016-12-02T01:18:53
66,558,895
1
0
null
null
null
null
UTF-8
C++
false
false
976
cpp
#include "DFA.h" using namespace std; DFA::DFA() { this->startStates = {}; this->finalStates = {}; this->inputs = {}; this->totalStates = -1; this->states = {}; } DFA::~DFA() {} //Checks to see if a set of NFA states is already in the DFA asa state int DFA::checkDFA(unordered_set<int> set) { int id; for(auto itr = this->states.begin(); itr != this->states.end(); ++itr) { unordered_set<int> test = itr->second->nStates; unordered_set<int> diff; std::set_difference(set.begin(), set.end(), test.begin(), test.end(),std::inserter(diff, diff.begin())); if(diff.empty()) { return itr->first; } } return -1; } //checks to see if the DState should be included in final states. bool DFA::isFinal(unordered_set<int> dstates, unordered_set<int> nfinals) { for (auto ns = dstates.begin(); ns != dstates.end(); ++ns) { int sfind = *ns; if(nfinals.find(sfind) != nfinals.end()) { return true; } } return false; }
837a39eb2f5b4a64656313855f4de103cbfd5d26
fca339684dfe174fa5fb075a4a323fd32bc673ab
/Test4_Code/Header_Code_Dependencies/Source/h1_d4.cpp
1b4ef1a75ca2851bad118abe6c1fb494fbde045b
[]
no_license
Jwcob/BA21_MODULE_TESTS
e2e44869f44de420d64fb0fb37885d079e8b8395
0d8ab1551d01a59c6475c24f2717589545de5237
refs/heads/main
2023-05-13T01:09:50.418445
2021-05-25T23:28:08
2021-05-25T23:28:08
370,734,048
0
0
null
null
null
null
UTF-8
C++
false
false
18,802
cpp
#include "h1_d4.hpp" int h1d4_ns::return0(){ int x = 0 * 2; x += x; return x; } int h1d4_ns::return1(){ int x = 1 * 2; x += x; return x; } int h1d4_ns::return2(){ int x = 2 * 2; x += x; return x; } int h1d4_ns::return3(){ int x = 3 * 2; x += x; return x; } int h1d4_ns::return4(){ int x = 4 * 2; x += x; return x; } int h1d4_ns::return5(){ int x = 5 * 2; x += x; return x; } int h1d4_ns::return6(){ int x = 6 * 2; x += x; return x; } int h1d4_ns::return7(){ int x = 7 * 2; x += x; return x; } int h1d4_ns::return8(){ int x = 8 * 2; x += x; return x; } int h1d4_ns::return9(){ int x = 9 * 2; x += x; return x; } int h1d4_ns::return10(){ int x = 10 * 2; x += x; return x; } int h1d4_ns::return11(){ int x = 11 * 2; x += x; return x; } int h1d4_ns::return12(){ int x = 12 * 2; x += x; return x; } int h1d4_ns::return13(){ int x = 13 * 2; x += x; return x; } int h1d4_ns::return14(){ int x = 14 * 2; x += x; return x; } int h1d4_ns::return15(){ int x = 15 * 2; x += x; return x; } int h1d4_ns::return16(){ int x = 16 * 2; x += x; return x; } int h1d4_ns::return17(){ int x = 17 * 2; x += x; return x; } int h1d4_ns::return18(){ int x = 18 * 2; x += x; return x; } int h1d4_ns::return19(){ int x = 19 * 2; x += x; return x; } int h1d4_ns::return20(){ int x = 20 * 2; x += x; return x; } int h1d4_ns::return21(){ int x = 21 * 2; x += x; return x; } int h1d4_ns::return22(){ int x = 22 * 2; x += x; return x; } int h1d4_ns::return23(){ int x = 23 * 2; x += x; return x; } int h1d4_ns::return24(){ int x = 24 * 2; x += x; return x; } int h1d4_ns::return25(){ int x = 25 * 2; x += x; return x; } int h1d4_ns::return26(){ int x = 26 * 2; x += x; return x; } int h1d4_ns::return27(){ int x = 27 * 2; x += x; return x; } int h1d4_ns::return28(){ int x = 28 * 2; x += x; return x; } int h1d4_ns::return29(){ int x = 29 * 2; x += x; return x; } int h1d4_ns::return30(){ int x = 30 * 2; x += x; return x; } int h1d4_ns::return31(){ int x = 31 * 2; x += x; return x; } int h1d4_ns::return32(){ int x = 32 * 2; x += x; return x; } int h1d4_ns::return33(){ int x = 33 * 2; x += x; return x; } int h1d4_ns::return34(){ int x = 34 * 2; x += x; return x; } int h1d4_ns::return35(){ int x = 35 * 2; x += x; return x; } int h1d4_ns::return36(){ int x = 36 * 2; x += x; return x; } int h1d4_ns::return37(){ int x = 37 * 2; x += x; return x; } int h1d4_ns::return38(){ int x = 38 * 2; x += x; return x; } int h1d4_ns::return39(){ int x = 39 * 2; x += x; return x; } int h1d4_ns::return40(){ int x = 40 * 2; x += x; return x; } int h1d4_ns::return41(){ int x = 41 * 2; x += x; return x; } int h1d4_ns::return42(){ int x = 42 * 2; x += x; return x; } int h1d4_ns::return43(){ int x = 43 * 2; x += x; return x; } int h1d4_ns::return44(){ int x = 44 * 2; x += x; return x; } int h1d4_ns::return45(){ int x = 45 * 2; x += x; return x; } int h1d4_ns::return46(){ int x = 46 * 2; x += x; return x; } int h1d4_ns::return47(){ int x = 47 * 2; x += x; return x; } int h1d4_ns::return48(){ int x = 48 * 2; x += x; return x; } int h1d4_ns::return49(){ int x = 49 * 2; x += x; return x; } int h1d4_ns::return50(){ int x = 50 * 2; x += x; return x; } int h1d4_ns::return51(){ int x = 51 * 2; x += x; return x; } int h1d4_ns::return52(){ int x = 52 * 2; x += x; return x; } int h1d4_ns::return53(){ int x = 53 * 2; x += x; return x; } int h1d4_ns::return54(){ int x = 54 * 2; x += x; return x; } int h1d4_ns::return55(){ int x = 55 * 2; x += x; return x; } int h1d4_ns::return56(){ int x = 56 * 2; x += x; return x; } int h1d4_ns::return57(){ int x = 57 * 2; x += x; return x; } int h1d4_ns::return58(){ int x = 58 * 2; x += x; return x; } int h1d4_ns::return59(){ int x = 59 * 2; x += x; return x; } int h1d4_ns::return60(){ int x = 60 * 2; x += x; return x; } int h1d4_ns::return61(){ int x = 61 * 2; x += x; return x; } int h1d4_ns::return62(){ int x = 62 * 2; x += x; return x; } int h1d4_ns::return63(){ int x = 63 * 2; x += x; return x; } int h1d4_ns::return64(){ int x = 64 * 2; x += x; return x; } int h1d4_ns::return65(){ int x = 65 * 2; x += x; return x; } int h1d4_ns::return66(){ int x = 66 * 2; x += x; return x; } int h1d4_ns::return67(){ int x = 67 * 2; x += x; return x; } int h1d4_ns::return68(){ int x = 68 * 2; x += x; return x; } int h1d4_ns::return69(){ int x = 69 * 2; x += x; return x; } int h1d4_ns::return70(){ int x = 70 * 2; x += x; return x; } int h1d4_ns::return71(){ int x = 71 * 2; x += x; return x; } int h1d4_ns::return72(){ int x = 72 * 2; x += x; return x; } int h1d4_ns::return73(){ int x = 73 * 2; x += x; return x; } int h1d4_ns::return74(){ int x = 74 * 2; x += x; return x; } int h1d4_ns::return75(){ int x = 75 * 2; x += x; return x; } int h1d4_ns::return76(){ int x = 76 * 2; x += x; return x; } int h1d4_ns::return77(){ int x = 77 * 2; x += x; return x; } int h1d4_ns::return78(){ int x = 78 * 2; x += x; return x; } int h1d4_ns::return79(){ int x = 79 * 2; x += x; return x; } int h1d4_ns::return80(){ int x = 80 * 2; x += x; return x; } int h1d4_ns::return81(){ int x = 81 * 2; x += x; return x; } int h1d4_ns::return82(){ int x = 82 * 2; x += x; return x; } int h1d4_ns::return83(){ int x = 83 * 2; x += x; return x; } int h1d4_ns::return84(){ int x = 84 * 2; x += x; return x; } int h1d4_ns::return85(){ int x = 85 * 2; x += x; return x; } int h1d4_ns::return86(){ int x = 86 * 2; x += x; return x; } int h1d4_ns::return87(){ int x = 87 * 2; x += x; return x; } int h1d4_ns::return88(){ int x = 88 * 2; x += x; return x; } int h1d4_ns::return89(){ int x = 89 * 2; x += x; return x; } int h1d4_ns::return90(){ int x = 90 * 2; x += x; return x; } int h1d4_ns::return91(){ int x = 91 * 2; x += x; return x; } int h1d4_ns::return92(){ int x = 92 * 2; x += x; return x; } int h1d4_ns::return93(){ int x = 93 * 2; x += x; return x; } int h1d4_ns::return94(){ int x = 94 * 2; x += x; return x; } int h1d4_ns::return95(){ int x = 95 * 2; x += x; return x; } int h1d4_ns::return96(){ int x = 96 * 2; x += x; return x; } int h1d4_ns::return97(){ int x = 97 * 2; x += x; return x; } int h1d4_ns::return98(){ int x = 98 * 2; x += x; return x; } int h1d4_ns::return99(){ int x = 99 * 2; x += x; return x; } int h1d4_ns::return100(){ int x = 100 * 2; x += x; return x; } int h1d4_ns::return101(){ int x = 101 * 2; x += x; return x; } int h1d4_ns::return102(){ int x = 102 * 2; x += x; return x; } int h1d4_ns::return103(){ int x = 103 * 2; x += x; return x; } int h1d4_ns::return104(){ int x = 104 * 2; x += x; return x; } int h1d4_ns::return105(){ int x = 105 * 2; x += x; return x; } int h1d4_ns::return106(){ int x = 106 * 2; x += x; return x; } int h1d4_ns::return107(){ int x = 107 * 2; x += x; return x; } int h1d4_ns::return108(){ int x = 108 * 2; x += x; return x; } int h1d4_ns::return109(){ int x = 109 * 2; x += x; return x; } int h1d4_ns::return110(){ int x = 110 * 2; x += x; return x; } int h1d4_ns::return111(){ int x = 111 * 2; x += x; return x; } int h1d4_ns::return112(){ int x = 112 * 2; x += x; return x; } int h1d4_ns::return113(){ int x = 113 * 2; x += x; return x; } int h1d4_ns::return114(){ int x = 114 * 2; x += x; return x; } int h1d4_ns::return115(){ int x = 115 * 2; x += x; return x; } int h1d4_ns::return116(){ int x = 116 * 2; x += x; return x; } int h1d4_ns::return117(){ int x = 117 * 2; x += x; return x; } int h1d4_ns::return118(){ int x = 118 * 2; x += x; return x; } int h1d4_ns::return119(){ int x = 119 * 2; x += x; return x; } int h1d4_ns::return120(){ int x = 120 * 2; x += x; return x; } int h1d4_ns::return121(){ int x = 121 * 2; x += x; return x; } int h1d4_ns::return122(){ int x = 122 * 2; x += x; return x; } int h1d4_ns::return123(){ int x = 123 * 2; x += x; return x; } int h1d4_ns::return124(){ int x = 124 * 2; x += x; return x; } int h1d4_ns::return125(){ int x = 125 * 2; x += x; return x; } int h1d4_ns::return126(){ int x = 126 * 2; x += x; return x; } int h1d4_ns::return127(){ int x = 127 * 2; x += x; return x; } int h1d4_ns::return128(){ int x = 128 * 2; x += x; return x; } int h1d4_ns::return129(){ int x = 129 * 2; x += x; return x; } int h1d4_ns::return130(){ int x = 130 * 2; x += x; return x; } int h1d4_ns::return131(){ int x = 131 * 2; x += x; return x; } int h1d4_ns::return132(){ int x = 132 * 2; x += x; return x; } int h1d4_ns::return133(){ int x = 133 * 2; x += x; return x; } int h1d4_ns::return134(){ int x = 134 * 2; x += x; return x; } int h1d4_ns::return135(){ int x = 135 * 2; x += x; return x; } int h1d4_ns::return136(){ int x = 136 * 2; x += x; return x; } int h1d4_ns::return137(){ int x = 137 * 2; x += x; return x; } int h1d4_ns::return138(){ int x = 138 * 2; x += x; return x; } int h1d4_ns::return139(){ int x = 139 * 2; x += x; return x; } int h1d4_ns::return140(){ int x = 140 * 2; x += x; return x; } int h1d4_ns::return141(){ int x = 141 * 2; x += x; return x; } int h1d4_ns::return142(){ int x = 142 * 2; x += x; return x; } int h1d4_ns::return143(){ int x = 143 * 2; x += x; return x; } int h1d4_ns::return144(){ int x = 144 * 2; x += x; return x; } int h1d4_ns::return145(){ int x = 145 * 2; x += x; return x; } int h1d4_ns::return146(){ int x = 146 * 2; x += x; return x; } int h1d4_ns::return147(){ int x = 147 * 2; x += x; return x; } int h1d4_ns::return148(){ int x = 148 * 2; x += x; return x; } int h1d4_ns::return149(){ int x = 149 * 2; x += x; return x; } int h1d4_ns::return150(){ int x = 150 * 2; x += x; return x; } int h1d4_ns::return151(){ int x = 151 * 2; x += x; return x; } int h1d4_ns::return152(){ int x = 152 * 2; x += x; return x; } int h1d4_ns::return153(){ int x = 153 * 2; x += x; return x; } int h1d4_ns::return154(){ int x = 154 * 2; x += x; return x; } int h1d4_ns::return155(){ int x = 155 * 2; x += x; return x; } int h1d4_ns::return156(){ int x = 156 * 2; x += x; return x; } int h1d4_ns::return157(){ int x = 157 * 2; x += x; return x; } int h1d4_ns::return158(){ int x = 158 * 2; x += x; return x; } int h1d4_ns::return159(){ int x = 159 * 2; x += x; return x; } int h1d4_ns::return160(){ int x = 160 * 2; x += x; return x; } int h1d4_ns::return161(){ int x = 161 * 2; x += x; return x; } int h1d4_ns::return162(){ int x = 162 * 2; x += x; return x; } int h1d4_ns::return163(){ int x = 163 * 2; x += x; return x; } int h1d4_ns::return164(){ int x = 164 * 2; x += x; return x; } int h1d4_ns::return165(){ int x = 165 * 2; x += x; return x; } int h1d4_ns::return166(){ int x = 166 * 2; x += x; return x; } int h1d4_ns::return167(){ int x = 167 * 2; x += x; return x; } int h1d4_ns::return168(){ int x = 168 * 2; x += x; return x; } int h1d4_ns::return169(){ int x = 169 * 2; x += x; return x; } int h1d4_ns::return170(){ int x = 170 * 2; x += x; return x; } int h1d4_ns::return171(){ int x = 171 * 2; x += x; return x; } int h1d4_ns::return172(){ int x = 172 * 2; x += x; return x; } int h1d4_ns::return173(){ int x = 173 * 2; x += x; return x; } int h1d4_ns::return174(){ int x = 174 * 2; x += x; return x; } int h1d4_ns::return175(){ int x = 175 * 2; x += x; return x; } int h1d4_ns::return176(){ int x = 176 * 2; x += x; return x; } int h1d4_ns::return177(){ int x = 177 * 2; x += x; return x; } int h1d4_ns::return178(){ int x = 178 * 2; x += x; return x; } int h1d4_ns::return179(){ int x = 179 * 2; x += x; return x; } int h1d4_ns::return180(){ int x = 180 * 2; x += x; return x; } int h1d4_ns::return181(){ int x = 181 * 2; x += x; return x; } int h1d4_ns::return182(){ int x = 182 * 2; x += x; return x; } int h1d4_ns::return183(){ int x = 183 * 2; x += x; return x; } int h1d4_ns::return184(){ int x = 184 * 2; x += x; return x; } int h1d4_ns::return185(){ int x = 185 * 2; x += x; return x; } int h1d4_ns::return186(){ int x = 186 * 2; x += x; return x; } int h1d4_ns::return187(){ int x = 187 * 2; x += x; return x; } int h1d4_ns::return188(){ int x = 188 * 2; x += x; return x; } int h1d4_ns::return189(){ int x = 189 * 2; x += x; return x; } int h1d4_ns::return190(){ int x = 190 * 2; x += x; return x; } int h1d4_ns::return191(){ int x = 191 * 2; x += x; return x; } int h1d4_ns::return192(){ int x = 192 * 2; x += x; return x; } int h1d4_ns::return193(){ int x = 193 * 2; x += x; return x; } int h1d4_ns::return194(){ int x = 194 * 2; x += x; return x; } int h1d4_ns::return195(){ int x = 195 * 2; x += x; return x; } int h1d4_ns::return196(){ int x = 196 * 2; x += x; return x; } int h1d4_ns::return197(){ int x = 197 * 2; x += x; return x; } int h1d4_ns::return198(){ int x = 198 * 2; x += x; return x; } int h1d4_ns::return199(){ int x = 199 * 2; x += x; return x; } int h1d4_ns::return200(){ int x = 200 * 2; x += x; return x; } int h1d4_ns::return201(){ int x = 201 * 2; x += x; return x; } int h1d4_ns::return202(){ int x = 202 * 2; x += x; return x; } int h1d4_ns::return203(){ int x = 203 * 2; x += x; return x; } int h1d4_ns::return204(){ int x = 204 * 2; x += x; return x; } int h1d4_ns::return205(){ int x = 205 * 2; x += x; return x; } int h1d4_ns::return206(){ int x = 206 * 2; x += x; return x; } int h1d4_ns::return207(){ int x = 207 * 2; x += x; return x; } int h1d4_ns::return208(){ int x = 208 * 2; x += x; return x; } int h1d4_ns::return209(){ int x = 209 * 2; x += x; return x; } int h1d4_ns::return210(){ int x = 210 * 2; x += x; return x; } int h1d4_ns::return211(){ int x = 211 * 2; x += x; return x; } int h1d4_ns::return212(){ int x = 212 * 2; x += x; return x; } int h1d4_ns::return213(){ int x = 213 * 2; x += x; return x; } int h1d4_ns::return214(){ int x = 214 * 2; x += x; return x; } int h1d4_ns::return215(){ int x = 215 * 2; x += x; return x; } int h1d4_ns::return216(){ int x = 216 * 2; x += x; return x; } int h1d4_ns::return217(){ int x = 217 * 2; x += x; return x; } int h1d4_ns::return218(){ int x = 218 * 2; x += x; return x; } int h1d4_ns::return219(){ int x = 219 * 2; x += x; return x; } int h1d4_ns::return220(){ int x = 220 * 2; x += x; return x; } int h1d4_ns::return221(){ int x = 221 * 2; x += x; return x; } int h1d4_ns::return222(){ int x = 222 * 2; x += x; return x; } int h1d4_ns::return223(){ int x = 223 * 2; x += x; return x; } int h1d4_ns::return224(){ int x = 224 * 2; x += x; return x; } int h1d4_ns::return225(){ int x = 225 * 2; x += x; return x; } int h1d4_ns::return226(){ int x = 226 * 2; x += x; return x; } int h1d4_ns::return227(){ int x = 227 * 2; x += x; return x; } int h1d4_ns::return228(){ int x = 228 * 2; x += x; return x; } int h1d4_ns::return229(){ int x = 229 * 2; x += x; return x; } int h1d4_ns::return230(){ int x = 230 * 2; x += x; return x; } int h1d4_ns::return231(){ int x = 231 * 2; x += x; return x; } int h1d4_ns::return232(){ int x = 232 * 2; x += x; return x; } int h1d4_ns::return233(){ int x = 233 * 2; x += x; return x; } int h1d4_ns::return234(){ int x = 234 * 2; x += x; return x; } int h1d4_ns::return235(){ int x = 235 * 2; x += x; return x; } int h1d4_ns::return236(){ int x = 236 * 2; x += x; return x; } int h1d4_ns::return237(){ int x = 237 * 2; x += x; return x; } int h1d4_ns::return238(){ int x = 238 * 2; x += x; return x; } int h1d4_ns::return239(){ int x = 239 * 2; x += x; return x; } int h1d4_ns::return240(){ int x = 240 * 2; x += x; return x; } int h1d4_ns::return241(){ int x = 241 * 2; x += x; return x; } int h1d4_ns::return242(){ int x = 242 * 2; x += x; return x; } int h1d4_ns::return243(){ int x = 243 * 2; x += x; return x; } int h1d4_ns::return244(){ int x = 244 * 2; x += x; return x; } int h1d4_ns::return245(){ int x = 245 * 2; x += x; return x; } int h1d4_ns::return246(){ int x = 246 * 2; x += x; return x; } int h1d4_ns::return247(){ int x = 247 * 2; x += x; return x; } int h1d4_ns::return248(){ int x = 248 * 2; x += x; return x; } int h1d4_ns::return249(){ int x = 249 * 2; x += x; return x; }
7d7c50a322dad92486c2ad21466def734605e54e
9f88366f38ca7e74dc7d6a12be927f154d15f528
/684A.cpp
90c717155ff9b93df63747b488122cda7265f5d4
[]
no_license
shreyas-mante/Codeforces
6b6d038065ab5439e5d45d8ff88d2ae9d5fc6965
fb8c3609c2410c55626201a0980b21645d27a591
refs/heads/main
2023-07-15T01:32:45.987702
2021-08-26T09:20:53
2021-08-26T09:20:53
363,723,401
2
0
null
null
null
null
UTF-8
C++
false
false
501
cpp
#include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ll t; cin>>t; while(t--) { ll n,c0,c1,h; cin>>n>>c0>>c1>>h; string s; cin>>s; ll cnt0 = 0; ll cnt1 = 0; for(ll i=0;i<n;i++) { if(s[i]=='1') { cnt1++; } if(s[i]=='0') { cnt0++; } } ll a1 , a2 ,a3; a1 = cnt1*c1 + cnt0*c0; a2 = h*cnt1 + n*c0; a3 = h*cnt0 + n*c1; ll res = min(a1,a2); ll res1 = min(res,a3); cout<<res1<<endl; } }
8b6bb8c58e1006e33b2ab364e9ae77d3201147c3
97aa1181a8305fab0cfc635954c92880460ba189
/c10/test/util/typeid_test.cpp
65e93c569169a4bc74cd56b250a786204b73ae8a
[ "BSD-2-Clause" ]
permissive
zhujiang73/pytorch_mingw
64973a4ef29cc10b96e5d3f8d294ad2a721ccacb
b0134a0acc937f875b7c4b5f3cef6529711ad336
refs/heads/master
2022-11-05T12:10:59.045925
2020-08-22T12:10:32
2020-08-22T12:10:32
123,688,924
8
4
NOASSERTION
2022-10-17T12:30:52
2018-03-03T12:15:16
C++
UTF-8
C++
false
false
4,449
cpp
#include <c10/util/typeid.h> #include <gtest/gtest.h> using std::string; namespace caffe2 { namespace { class TypeMetaTestFoo {}; class TypeMetaTestBar {}; } CAFFE_KNOWN_TYPE(TypeMetaTestFoo); CAFFE_KNOWN_TYPE(TypeMetaTestBar); namespace { TEST(TypeMetaTest, TypeMetaStatic) { EXPECT_EQ(TypeMeta::ItemSize<int>(), sizeof(int)); EXPECT_EQ(TypeMeta::ItemSize<float>(), sizeof(float)); EXPECT_EQ(TypeMeta::ItemSize<TypeMetaTestFoo>(), sizeof(TypeMetaTestFoo)); EXPECT_EQ(TypeMeta::ItemSize<TypeMetaTestBar>(), sizeof(TypeMetaTestBar)); EXPECT_NE(TypeMeta::Id<int>(), TypeMeta::Id<float>()); EXPECT_NE(TypeMeta::Id<int>(), TypeMeta::Id<TypeMetaTestFoo>()); EXPECT_NE(TypeMeta::Id<TypeMetaTestFoo>(), TypeMeta::Id<TypeMetaTestBar>()); EXPECT_EQ(TypeMeta::Id<int>(), TypeMeta::Id<int>()); EXPECT_EQ(TypeMeta::Id<TypeMetaTestFoo>(), TypeMeta::Id<TypeMetaTestFoo>()); } TEST(TypeMetaTest, Names) { TypeMeta null_meta; EXPECT_EQ("nullptr (uninitialized)", null_meta.name()); TypeMeta int_meta = TypeMeta::Make<int>(); EXPECT_EQ("int", int_meta.name()); TypeMeta string_meta = TypeMeta::Make<string>(); EXPECT_TRUE(c10::string_view::npos != string_meta.name().find("string")); } TEST(TypeMetaTest, TypeMeta) { TypeMeta int_meta = TypeMeta::Make<int>(); TypeMeta float_meta = TypeMeta::Make<float>(); TypeMeta foo_meta = TypeMeta::Make<TypeMetaTestFoo>(); TypeMeta bar_meta = TypeMeta::Make<TypeMetaTestBar>(); TypeMeta another_int_meta = TypeMeta::Make<int>(); TypeMeta another_foo_meta = TypeMeta::Make<TypeMetaTestFoo>(); EXPECT_EQ(int_meta, another_int_meta); EXPECT_EQ(foo_meta, another_foo_meta); EXPECT_NE(int_meta, float_meta); EXPECT_NE(int_meta, foo_meta); EXPECT_NE(foo_meta, bar_meta); EXPECT_TRUE(int_meta.Match<int>()); EXPECT_TRUE(foo_meta.Match<TypeMetaTestFoo>()); EXPECT_FALSE(int_meta.Match<float>()); EXPECT_FALSE(int_meta.Match<TypeMetaTestFoo>()); EXPECT_FALSE(foo_meta.Match<int>()); EXPECT_FALSE(foo_meta.Match<TypeMetaTestBar>()); EXPECT_EQ(int_meta.id(), TypeMeta::Id<int>()); EXPECT_EQ(float_meta.id(), TypeMeta::Id<float>()); EXPECT_EQ(foo_meta.id(), TypeMeta::Id<TypeMetaTestFoo>()); EXPECT_EQ(bar_meta.id(), TypeMeta::Id<TypeMetaTestBar>()); EXPECT_EQ(int_meta.itemsize(), TypeMeta::ItemSize<int>()); EXPECT_EQ(float_meta.itemsize(), TypeMeta::ItemSize<float>()); EXPECT_EQ(foo_meta.itemsize(), TypeMeta::ItemSize<TypeMetaTestFoo>()); EXPECT_EQ(bar_meta.itemsize(), TypeMeta::ItemSize<TypeMetaTestBar>()); EXPECT_EQ(int_meta.name(), "int"); EXPECT_EQ(float_meta.name(), "float"); EXPECT_NE(foo_meta.name().find("TypeMetaTestFoo"), c10::string_view::npos); EXPECT_NE(bar_meta.name().find("TypeMetaTestBar"), c10::string_view::npos); } class ClassAllowAssignment { public: ClassAllowAssignment() : x(42) {} ClassAllowAssignment(const ClassAllowAssignment& src) : x(src.x) {} ClassAllowAssignment& operator=(const ClassAllowAssignment& src) = default; int x; }; class ClassNoAssignment { public: ClassNoAssignment() : x(42) {} ClassNoAssignment(const ClassNoAssignment& src) = delete; ClassNoAssignment& operator=(const ClassNoAssignment& src) = delete; int x; }; } CAFFE_KNOWN_TYPE(ClassAllowAssignment); CAFFE_KNOWN_TYPE(ClassNoAssignment); namespace { TEST(TypeMetaTest, CtorDtorAndCopy) { TypeMeta fundamental_meta = TypeMeta::Make<int>(); EXPECT_EQ(fundamental_meta.placementNew(), nullptr); EXPECT_EQ(fundamental_meta.placementDelete(), nullptr); EXPECT_EQ(fundamental_meta.copy(), nullptr); TypeMeta meta_a = TypeMeta::Make<ClassAllowAssignment>(); EXPECT_TRUE(meta_a.placementNew() != nullptr); EXPECT_TRUE(meta_a.placementDelete() != nullptr); EXPECT_TRUE(meta_a.copy() != nullptr); ClassAllowAssignment src; src.x = 10; ClassAllowAssignment dst; EXPECT_EQ(dst.x, 42); meta_a.copy()(&src, &dst, 1); EXPECT_EQ(dst.x, 10); TypeMeta meta_b = TypeMeta::Make<ClassNoAssignment>(); EXPECT_TRUE(meta_b.placementNew() != nullptr); EXPECT_TRUE(meta_b.placementDelete() != nullptr); #ifndef __clang__ // gtest seems to have some problem with function pointers and // clang right now... Disabling it. // TODO: figure out the real cause. EXPECT_EQ(meta_b.copy(), &(detail::_CopyNotAllowed<ClassNoAssignment>)); #endif } TEST(TypeMetaTest, Float16IsNotUint16) { EXPECT_NE(TypeMeta::Id<uint16_t>(), TypeMeta::Id<at::Half>()); } } // namespace } // namespace caffe2
30423ffe7e0abf60011f8c22241965b9e7a27bdd
6cf257a0febcd24234777b44c68191e824662715
/src/hls_lfcd_lds_driver/include/hls_lfcd_lds_driver/lfcd_laser.h
82daed3fecee2c4adf6ddefe7b0789c1c6b83291
[ "BSD-3-Clause" ]
permissive
levanson1998/ros_mbrb_pi
6126e6a0e4fb9c65744503d8f371f09fe156d20f
eb6dd66a570e501d292cdffc21d65008795a98b5
refs/heads/main
2023-02-19T13:45:15.876617
2021-01-21T03:57:10
2021-01-21T03:57:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,429
h
/******************************************************************************* * Copyright (c) 2016, Hitachi-LG Data Storage * Copyright (c) 2017, ROBOTIS * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL 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. *******************************************************************************/ /* Authors: SP Kong, JH Yang */ /* maintainer: Pyo */ #include <string> #include <sensor_msgs/LaserScan.h> #include <boost/asio.hpp> #include <boost/array.hpp> namespace hls_lfcd_lds { class LFCDLaser { public: uint16_t rpms; ///< @brief RPMS derived from the rpm bytes in an LFCD packet /** * @brief Constructs a new LFCDLaser attached to the given serial port * @param port The string for the serial port device to attempt to connect to, e.g. "/dev/ttyUSB0" * @param baud_rate The baud rate to open the serial port at. * @param io Boost ASIO IO Service to use when creating the serial port object */ LFCDLaser(const std::string& port, uint32_t baud_rate, boost::asio::io_service& io); /** * @brief Default destructor */ ~LFCDLaser(); /** * @brief Poll the laser to get a new scan. Blocks until a complete new scan is received or close is called. * @param scan LaserScan message pointer to fill in with the scan. The caller is responsible for filling in the ROS timestamp and frame_id */ void poll(sensor_msgs::LaserScan::Ptr scan); /** * @brief Close the driver down and prevent the polling loop from advancing */ void close() { shutting_down_ = true; } private: std::string port_; ///< @brief The serial port the driver is attached to uint32_t baud_rate_; ///< @brief The baud rate for the serial connection bool shutting_down_; ///< @brief Flag for whether the driver is supposed to be shutting down or not boost::asio::io_service m_ioService; boost::asio::serial_port serial_; ///< @brief Actual serial port object for reading/writing to the LFCD Laser Scanner uint16_t motor_speed_; ///< @brief current motor speed as reported by the LFCD. }; }
1e88ff46fca2b5d21cc3a83716c21992b6055182
a2a4e687061a675efb484e2e3b1cecdfbfd27d3e
/problem set 2/codefocesless1300pro10.cpp
92355bc988cf0ee1d8ae12de3a9d397c03b84b0d
[]
no_license
stormbreaker07/CodingQuestions
6060761fe8c692af50aa01b976dc9da80307462f
3e6345941ee316db92f73875481e6b541cbe6bdb
refs/heads/master
2021-07-14T20:49:48.507648
2020-08-24T05:34:09
2020-08-24T05:34:09
196,558,918
1
0
null
null
null
null
UTF-8
C++
false
false
234
cpp
#include <bits/stdc++.h> #include<iostream> #include<string> using namespace std; int main() {int w; string s; cin>>w; cin>>s; for(int i=0;i<s.length();i++) { while(s[i]==s[i+1]) {s.erase(i+1,1); } } cout<<w-s.length(); return 0; }
df8fadb692783252b1f810a09cb4e5e2b1f51c4e
a194511dea15e82780072fb88dad81b17e24919f
/libs/habutil/habit/HLoggerWidget.h
2884e15ff7c6ad88d6e767f4e6a82d937645b40b
[]
no_license
djsperka/habit2-src
3056b07c664f2cbc1e32874cdf442b13a511b205
a35117864de3c8cff55ff05d7b20fcc479e4ee8c
refs/heads/master
2023-01-07T19:56:59.382117
2023-01-06T00:23:50
2023-01-06T00:23:50
157,589,849
0
0
null
2023-01-05T22:00:14
2018-11-14T18:03:09
C++
UTF-8
C++
false
false
443
h
/* * HLoggerWidget.h * * Created on: Jun 6, 2018 * Author: dan */ #ifndef LIBS_HABUTIL_HABIT_HLOGGERWIDGET_H_ #define LIBS_HABUTIL_HABIT_HLOGGERWIDGET_H_ #include <QtWidgets/qplaintextedit.h> class HLoggerWidget: public QPlainTextEdit { Q_OBJECT public: HLoggerWidget(QWidget *parent = NULL); virtual ~HLoggerWidget(); public slots: void appendMessage(const QString&); }; #endif /* LIBS_HABUTIL_HABIT_HLOGGERWIDGET_H_ */
b0863dfe9761ad8348e45fd2a9f418cb9b6a566d
2413d71a07074043233874f114c303a9d1df7705
/动态规划/樱花.cpp
673c006d81a7bf962b54980b8a40e07e74bb4050
[]
no_license
ferapontqiezi/AlgorithmDesign
fe21ccc5983c9622e4e6200209f0124b4360eeb4
cdeefa760f1c55fa32ebc4a0f034fcbfa1da0ac1
refs/heads/master
2023-08-26T18:29:07.171850
2021-11-12T05:20:14
2021-11-12T05:20:14
421,362,539
1
0
null
null
null
null
UTF-8
C++
false
false
858
cpp
#include<cstdio> #include<algorithm> using namespace std; int nx, ny, ex, ey, n, f[1010]; int a[10005], b[10005], c[10005]; int cnt = 0, co[1000005], v[1000005];//尽可能开大,不要把空间开爆了 int main() { scanf("%d:%d %d:%d%d", &nx, &ny, &ex, &ey, &n); int t = (ex * 60 + ey) - (nx * 60 + ny); for(int i = 1; i <= n; ++ i) { scanf("%d%d%d", &a[i], &b[i], &c[i]); if(!c[i]) c[i] = 999999; int at = a[i], bt = b[i], ct = c[i]; for(int j = 1; j <= ct; j <<= 1) { co[++cnt] = j*at, v[cnt] = j*bt; ct -= j; } if(c) co[++cnt] = at*ct, v[cnt] = bt*ct; //二进制优化,拆分 } for(int i = 1; i <= cnt; ++ i) {//考虑每个拆出来的物品 for(int j = t; j >= co[i]; -- j)//01背包板子 f[j] = max(f[j], f[j - co[i]] + v[i]); } printf("%d", f[t]); return 0; }