blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
1a91fd69b846ab4cb9cb1e429e02b506d70993cd
bbde14e3268e9ce97ccd36ba61f1695cd3d709bc
/Algorithm Practice/attemptPrimeNumberFinder.cpp
0453eb9f35b88f3e659663c055b232c5d57feb09
[]
no_license
johnwsmithv/Programming-Projects
1ff5359014a2ecd286e291b7dc2df21fdc37c038
77273abc3a6ebfd015afbbbad48f6e3221914735
refs/heads/master
2022-05-30T16:25:03.278416
2022-05-28T13:48:15
2022-05-28T13:48:15
237,014,814
1
0
null
2020-10-14T00:21:19
2020-01-29T15:24:12
Java
UTF-8
C++
false
false
2,134
cpp
attemptPrimeNumberFinder.cpp
#include <vector> #include <iostream> #include <Windows.h> #include <omp.h> inline long double PerformanceCounter() noexcept { LARGE_INTEGER li; ::QueryPerformanceCounter(&li); return li.QuadPart; } inline long double PerformanceFrequency() noexcept { LARGE_INTEGER li; ::QueryPerformanceFrequency(&li); return li.QuadPart; } /** * The point of this function is to find the prime numbers from 2 to n * */ std::vector<long long> primeNumberFinder(int primeSearchMax){ std::vector<long long> primeNumbers; for(int i = 2; i < primeSearchMax; i++){ for(int j = 1; j <= i / 2; j++){ if((i % j == 0) && j != 1){ break; } else if(j == i / 2){ primeNumbers.insert(primeNumbers.end(), i); } } } return primeNumbers; } std::vector<long long> primeNumberFinderOMP(int primeSearchMax){ int i; int j; std::vector<long long> primeNumbers; #pragma omp parallel for default(none) shared(primeSearchMax, primeNumbers) private(i, j) for(i = 2; i < primeSearchMax; i++){ for(j = 1; j <= i / 2; j++){ if((i % j == 0) && j != 1){ break; } else if(j == i / 2){ primeNumbers.insert(primeNumbers.end(), i); } } } return primeNumbers; } int main(){ int primeNumberMax; std::cout << "Enter a number that you want to find prime numbers up to: "; std::cin >> primeNumberMax; long double start = PerformanceCounter(); // std::vector<long long> primes = primeNumberFinder(primeNumberMax); std::vector<long long> primes = primeNumberFinderOMP(primeNumberMax); long double finish = PerformanceCounter(); long double frequency = PerformanceFrequency(); long double elapsedTime = ((finish - start)) / frequency; for(int i = 0; i < primes.size(); i++){ std::cout << primes[i] << " "; if(i % 10 == 0){ std::cout << "\n"; } } std::cout << "\nFinding the number of prime numbers took: " << elapsedTime << " seconds.\n"; }
3f5a5c79230548f392fb2c12313f20c5d00470ea
7f3b8c3110a0b2d037082cca05afd5ab6bb07384
/模拟-官员点人/模拟-官员点人/main.cpp
11cc87747cbc9575e24d5a81c2fbecadad913e56
[]
no_license
SHIELD-SKY/Practice-of-Date-Structures
5c1cffd98f58f42a61b7f8a562e08823209bb7e3
2b3b61d3d24709c044e8f09550ec287bb0532ccd
refs/heads/master
2021-07-08T15:24:11.466778
2020-07-10T12:39:04
2020-07-10T12:39:04
147,606,635
0
0
null
null
null
null
UTF-8
C++
false
false
1,381
cpp
main.cpp
// // main.cpp // 模拟-官员点人 // // Created by APTX on 9/2/2019. // Copyright © 2019 APTX. All rights reserved. // #include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <string> #include <algorithm> #include <cmath> const int maxn = 25; int flag[maxn]; void shu(int &a, int t, int d, int n){ //在a上沿d方向走t步 while (t--) { do{ a += d; if(a > n) a = 1; if(a < 1) a = n; }while(flag[a]); //flag[a] == 1表示a所指这个人不在队伍里,这一步不算,继续走 } } int main(int argc, const char * argv[]) { int n, k, m; while (scanf("%d%d%d",&n, &k, &m) == 3) { memset(flag, 0, sizeof(flag)); //初始化为0表示全部在队伍里 int a = n, b = 1; //初始化所指位置 int left = n; //队伍里剩余的人 while (left > 0) { shu(a, k, 1, n); //a 从小到大数 shu(b, m, -1, n); //b从大往小数 flag[a] = flag[b] = 1; if(a == b) { printf("%d", a); left--; } else { printf("%d %d", a, b); left -= 2; } if (left) { printf(","); } else printf("\n"); } } return 0; }
e1afbb0341292ea3c9c194ebc655f81ec521fef6
2b2da3c294d188fa7c2795364ab26859e29ffb87
/OFSample-Windows/depends/dwinternal/framework2015/include/yycomponent/yychannellogic/private/yychannelLogic_i.h
d72e3b7388370175623004e9f576cc1933f62ac0
[]
no_license
JocloudSDK/OFSample
1de97d416402b91276f9992197bc0c64961fb9bd
fa678d674b3886fa8e6a1c4a0ba6b712124e671a
refs/heads/master
2022-12-28T05:03:05.563734
2020-10-19T07:11:55
2020-10-19T07:11:55
294,078,053
4
2
null
null
null
null
UTF-8
C++
false
false
1,509
h
yychannelLogic_i.h
#pragma once #include "dwbase/dwcomex.h" #ifndef DW_COMPONENT_ENV #include "biz/biz_channel.h" #endif #include "yycomponent/yychannel/yychannelinfo_i.h" #include "yycomponent/yychannel/yychannelecho_i.h" class IPannelButtonMagr; class IBulletinMagr; define_interface(IChannel); class YYChannelComponentServiceImpl { public: virtual ~YYChannelComponentServiceImpl() { } virtual bool queryInterface(REFDWUUID iid, void **ppv) { return false; } virtual HRESULT finalRelease() { return S_OK; } virtual void setBizChannelPtr(IChannelPtrCR spChannel, IUnk* outter) { } }; DWDEFINE_INTERFACE(IChannelServiceInner): public IUnk { virtual void setAddonHandler(IPannelButtonMagr* pannel,IBulletinMagr* bulletinMgr) = 0; }; DWDEFINE_INTERFACE(IYYChannelLogicInner):public IUnk { virtual IChannelPtr getChannel() = 0; }; DWDEFINE_INTERFACE(IYYBizInilizer): public IUnk { virtual void setBizChannelPtr(IChannelPtr spChannel) = 0; }; DWDEFINE_INTERFACE(IYYChannelInfomationInner) : public IYYChannelInfomation { virtual _SIG_ERROR* getInnerErroredSignal() = 0; virtual void emitInChannelAlreadySignal(UINT32 sid, UINT32 ssid); virtual void emitChannelActionTakeoverSig(const QMap<int,QVariant>&) = 0; }; DWDEFINE_INTERFACE(IYYChannelEchoInner) : public IYYChannelEcho { virtual _SIG_ECHO_OPERATION_EX_RES* getInnerEchoOperationExSignal() = 0; virtual _SIG_ECHO_KICKOUT* getInnerKickoutExSignal() = 0; }; #include "../yychannelLogic_i.h"
9cc0d45cd749dda6de88bf092e8e40cdab51237a
78b28019e10962bb62a09fa1305264bbc9a113e3
/common/modular/static/modular_io.h
d84a04cdae8cd037be3ad8134bb9053e2de46f17
[ "MIT" ]
permissive
Loks-/competitions
49d253c398bc926bfecc78f7d468410702f984a0
26a1b15f30bb664a308edc4868dfd315eeca0e0b
refs/heads/master
2023-06-08T06:26:36.756563
2023-05-31T03:16:41
2023-05-31T03:16:41
135,969,969
5
2
null
null
null
null
UTF-8
C++
false
false
614
h
modular_io.h
#pragma once #include "common/modular/static/modular.h" #include <istream> #include <ostream> namespace modular { namespace mstatic { template <uint64_t mod, bool is_prime, bool is_32bit> inline std::ostream& operator<<(std::ostream& s, const Modular<mod, is_prime, is_32bit>& m) { return s << m.Get(); } template <uint64_t mod, bool is_prime, bool is_32bit> inline std::istream& operator>>(std::istream& s, Modular<mod, is_prime, is_32bit>& m) { int64_t t; s >> t; m.SetS(t); return s; } } // namespace mstatic } // namespace modular
555c7607adaa2b6d4c7e1daa8c013c5fc9701cdc
f73a36db6fa9f53cb1524fda87a341f494ae60a4
/doubly-linked-list/genDLList.h
7ab64d3822a5230ac36dfd6e1f6818d3a477c946
[]
no_license
tianyuyifang/data-structures-and-algorithms-c-
ac7b5bfc99881e5da4a5404eb10e1f9f603584d6
ab38070bff543377fcbd925e77a72c53f9ce0f37
refs/heads/master
2021-05-14T03:04:58.090041
2018-01-10T00:32:33
2018-01-10T00:32:33
116,612,087
0
0
null
null
null
null
UTF-8
C++
false
false
727
h
genDLList.h
#ifndef DOUBLY_LINKED_LIST #define DOUBLY_LINKED_LIST template<class T> class DLLNode{ public: DLLNode() { next = prev = 0; } DLLNode(const T& val, DLLNode *n = 0, DLLNode *p = 0) { info = val; next = n; prev = p; } T info; DLLNode *next, *prev; }; template<class T> class DoublyLinkedList { public: DoublyLinkedList() { head = tail = 0; } ~DoublyLinkedList(); bool isEmpty() { return head == 0; } void addToDLLHead(const T&); void addToDLLTail(const T&); T deleteFromDLLHead(); // delete the head and return its info; T deleteFromDLLTail(); // delete the tail and return its info; void deleteNode(const T&); bool isInList(const T&) const; private: DLLNode<T> *head, *tail; }; #endif
4e252f8f2077e653e6966d06a453000adc732f4f
fe843923c3e8dc09e445229ea1e18cd3f0910587
/mystring/string.hpp
cf7dd35b43535715197248aeb79e72757a2f2519
[ "MIT" ]
permissive
dtoma/cpp
815d5613a87db602a800d754391e8b989a0aefd7
1c6c726071092d9e238c6fb3de22fed833a148b2
refs/heads/master
2021-01-18T17:38:56.027685
2020-04-22T07:09:37
2020-04-22T07:09:37
70,047,111
0
0
null
null
null
null
UTF-8
C++
false
false
7,958
hpp
string.hpp
#pragma once #include <climits> #include <cstring> #include <iterator> #include <memory> #include <string> /** * Implement bit-fiddling helper functions for the SSO. */ namespace { static std::size_t const high_bit_mask = static_cast<std::size_t>(1) << (sizeof(std::size_t) * CHAR_BIT - 1); static std::size_t const sec_high_bit_mask = static_cast<std::size_t>(1) << (sizeof(std::size_t) * CHAR_BIT - 2); template <typename T> unsigned char *uchar_cast(T *p) { return reinterpret_cast<unsigned char *>(p); } template <typename T> unsigned char const *uchar_cast(T const *p) { return reinterpret_cast<unsigned char const *>(p); } template <typename T> unsigned char &most_sig_byte(T &obj) { return *(reinterpret_cast<unsigned char *>(&obj) + sizeof(obj) - 1); } template <int N> bool lsb(unsigned char byte) { return byte & (1u << N); } template <int N> bool msb(unsigned char byte) { return byte & (1u << (CHAR_BIT - N - 1)); } template <int N> void set_lsb(unsigned char &byte, bool bit) { if (bit) { byte |= 1u << N; } else { byte &= ~(1u << N); } } template <int N> void set_msb(unsigned char &byte, bool bit) { if (bit) { byte |= 1u << (CHAR_BIT - N - 1); } else { byte &= ~(1u << (CHAR_BIT - N - 1)); } } } // namespace namespace dtoma { /** * String class. * * Features: * - SSO * - iterators * * Non-features: * - templated value type/type traits * - templated allocator * * This simple class should be usable by the STL algorithms, * be somewhat performant thanks to SSO, compile quickly, * and be easy to debug since it doesn't have template magic. * * Inspiration: https://github.com/elliotgoodrich/SSO-23/blob/master/include/string.hpp * * TODO: * - move constructors * + rule of 5: https://en.cppreference.com/w/cpp/language/rule_of_three * + assertions: https://howardhinnant.github.io/classdecl.html * - comparison operators * */ class String final { /** * SSO union. */ union Data { struct NonSSO { char *ptr; std::size_t size; std::size_t capacity; } non_sso; struct SSO { char ptr[sizeof(NonSSO) / sizeof(char) - 1]; std::make_unsigned_t<char> size; } sso; static_assert(sizeof(NonSSO) == sizeof(SSO)); } _data; /** * SSO helper member functions. */ std::pair<std::size_t, std::size_t> read_non_sso_data() const { auto size = this->_data.non_sso.size; auto capacity = this->_data.non_sso.capacity; auto &size_hsb = most_sig_byte(size); auto &cap_hsb = most_sig_byte(capacity); // Remember to negate the high bits auto const cap_high_bit = lsb<0>(cap_hsb); auto const size_high_bit = !lsb<1>(cap_hsb); auto const cap_sec_high_bit = msb<0>(size_hsb); set_msb<0>(size_hsb, size_high_bit); cap_hsb >>= 2; set_msb<0>(cap_hsb, cap_high_bit); set_msb<1>(cap_hsb, cap_sec_high_bit); return std::make_pair(size, capacity); } void set_sso_size(unsigned char size) noexcept { _data.sso.size = static_cast<value_type>(sso_capacity - size) << 2; } std::size_t sso_size() const { return sso_capacity - ((this->_data.sso.size >> 2) & 63u); } public: /** * Types * Define enough types to be somewhat compatible with the STL (eg. algorithms). */ using value_type = char; using traits_type = std::char_traits<value_type>; using size_type = std::size_t; using difference_type = std::ptrdiff_t; using pointer = value_type *; using const_pointer = value_type const *; using reference = value_type &; using const_reference = value_type const &; using iterator_category = std::random_access_iterator_tag; using iterator = pointer; using const_iterator = const_pointer; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; /** * Helper that contains the maximum size we can use for SSO. */ static std::size_t const sso_capacity = // sizeof(typename Data::NonSSO) / sizeof(value_type) - 1; /** * Constructors & destructors. */ String() : String("", 0){}; String(char const *str, std::size_t size) { if (size <= sso_capacity) { traits_type::copy(this->_data.sso.ptr, str, size); // TODO: move? traits_type::assign(this->_data.sso.ptr[size], '\0'); this->set_sso_size(size); return; } this->_data.non_sso.ptr = new value_type[size + 1]; traits_type::copy(this->_data.non_sso.ptr, str, size); // TODO: move? traits_type::assign(this->_data.non_sso.ptr[size], '\0'); auto capacity = size; auto &size_hsb = most_sig_byte(size); auto const size_high_bit = msb<0>(size_hsb); auto &cap_hsb = most_sig_byte(capacity); auto const cap_high_bit = msb<0>(cap_hsb); auto const cap_sec_high_bit = msb<1>(cap_hsb); set_msb<0>(size_hsb, cap_sec_high_bit); cap_hsb <<= 2; set_lsb<0>(cap_hsb, cap_high_bit); set_lsb<1>(cap_hsb, !size_high_bit); _data.non_sso.size = size; _data.non_sso.capacity = capacity; } String(char const *str) : String(str, std::strlen(str)) { } String(String const &other) { if (other.sso()) { this->_data.sso = other._data.sso; } new (this) String(other.data(), other.size()); }; String &operator=(String const &other) { auto tmp = other; std::swap(tmp, *this); return *this; }; ~String() { if (!this->sso() && this->_data.non_sso.ptr != nullptr) { delete[] this->_data.non_sso.ptr; } }; /** * Public interface. */ char const *data() const noexcept { if (this->sso()) { return this->_data.sso.ptr; } return this->_data.non_sso.ptr; } char *data() noexcept { if (this->sso()) { return this->_data.sso.ptr; } return this->_data.non_sso.ptr; } std::size_t size() const noexcept { if (this->sso()) { return this->sso_size(); } return this->read_non_sso_data().first; } std::size_t capacity() const noexcept { if (sso()) { return sizeof(_data) - 1; } return read_non_sso_data().second; } bool sso() const noexcept { auto last_bit = lsb<0>(this->_data.sso.size); auto second_last_bit = lsb<1>(this->_data.sso.size); return !last_bit && !second_last_bit; } /** * Iterator interface. */ iterator begin() { return this->data(); } iterator end() { return this->data() + this->size(); } const_iterator begin() const { return this->data(); } const_iterator end() const { return this->data() + this->size(); } reverse_iterator rbegin() { return reverse_iterator(this->end()); } reverse_iterator rend() { return reverse_iterator(this->begin()); } const_reverse_iterator crbegin() const { return const_reverse_iterator(this->end()); } const_reverse_iterator crend() const { return const_reverse_iterator(this->begin()); } reference operator[](size_type pos) { return this->data()[pos]; } const_reference operator[](size_type pos) const { return this->data()[pos]; } }; static_assert(std::is_destructible<String>{}); static_assert(std::is_default_constructible<String>{}); static_assert(std::is_copy_constructible<String>{}); static_assert(std::is_copy_assignable<String>{}); } // namespace dtoma
eeb7cabc6d70f95e3565018e263f861901e0304b
7b1a4f705d331ca543cc46641ada12df616a684b
/example/Analyzer.hxx
2dcf0129b6706f8a3c88dbc5d73758326f093ba5
[]
no_license
gchristian321/rootbeer
5070b229d377e1e7841464a080df322b57e87be0
16734e566d711a0734b890a50777bbb51aa8ef54
refs/heads/master
2020-05-30T06:45:04.205238
2013-09-18T03:00:09
2013-09-18T03:00:09
3,372,154
0
1
null
null
null
null
UTF-8
C++
false
false
1,054
hxx
Analyzer.hxx
/// /// \file Analyzer.hxx /// \brief Example analysis codes for an experiment. /// #ifndef ROOTBEER_ANALYZER_ANALYZER_HXX #define ROOTBEER_ANALYZER_ANALYZER_HXX /// Number of detector channels static const int NUM_CHANNELS = 32; /// Sample Class for a detector class Detector { public: // Methods /// Calls Reset(); Detector(); /// Empty ~Detector(); /// Unpack event data into class members void Unpack(const void* addr); /// Reset data after an event void Reset(); public: // Data /// Energies for a 32-channel array of detectors double energy[NUM_CHANNELS]; /// Times for a 32-channel array of detectors double time[NUM_CHANNELS]; /// Highest energy in the array of 32 detectors double emax; }; /// Example analysis class for an experiment class Experiment { public: // Methods /// Empy Experiment(); /// Empty ~Experiment(); /// Unpacks data into class structure void Unpack(const void* pbuffer); /// Resets all data to defaults void Reset(); public: // Data /// Instance of detector class Detector detector; }; #endif
21b59d53b77eb368d1a19bb14d3a98c77328a117
8f11b828a75180161963f082a772e410ad1d95c6
/packages/sonar/test/src/TestFFTWSpectrum.cpp
754e13dae5a04898f1d870c000921eafb3db13bf
[]
no_license
venkatarajasekhar/tortuga
c0d61703d90a6f4e84d57f6750c01786ad21d214
f6336fb4d58b11ddfda62ce114097703340e9abd
refs/heads/master
2020-12-25T23:57:25.036347
2017-02-17T05:01:47
2017-02-17T05:01:47
43,284,285
0
0
null
2017-02-17T05:01:48
2015-09-28T06:39:21
C++
UTF-8
C++
false
false
1,532
cpp
TestFFTWSpectrum.cpp
/** * TestSparseSDFTSpectrum.cpp * * @author Leo Singer * @author Copyright 2008 Robotics@Maryland. All rights reserved. * */ #include <UnitTest++/UnitTest++.h> #include <cstdlib> #include "Sonar.h" #include "spectrum/FFTWSpectrum.h" #include "spectrum/SDFTSpectrum.h" using namespace ram::sonar; using namespace std; TEST(FFTWSpectrumGivesSameResultsAsSDFT) { static const int nSamples = 100; // Number of samples static const int nChannels = 1; // Number of input channels static const int N = 512; // Fourier window size typedef adc<16> myadc; FFTWSpectrum<myadc, N, nChannels> refSpectrum; SDFTSpectrum<myadc, N, nChannels> sbjSpectrum; for (long i = 0 ; i < nSamples ; i ++) { myadc::SIGNED sample[nChannels]; for (int channel = 0 ; channel < nChannels ; channel ++) sample[channel] = (myadc::SIGNED)(((double)rand() / RAND_MAX) * myadc::SIGNED_MAX); refSpectrum.update(sample); sbjSpectrum.update(sample); for (int channel = 0 ; channel < nChannels ; channel ++) { for (int k = 0 ; k < N ; k++) { const std::complex<myadc::DOUBLE_WIDE::SIGNED>& refResult = refSpectrum.getAmplitude(k, channel); const std::complex<myadc::DOUBLE_WIDE::SIGNED>& sbjResult = sbjSpectrum.getAmplitude(k, channel); // Answer diverges from FFTW as the spectrum analzyer becomes older. // Need to quantify rate of divergence. CHECK_CLOSE(refResult.real(), sbjResult.real(), 4096); CHECK_CLOSE(refResult.imag(), sbjResult.imag(), 4096); } } } }
797a960a32ad5746e401d12364b2b2dc39c945a7
69e1199b2daffa17e4842e94a54be152df540828
/暑假集训/暑假集训2/图论/最大流模板(通过北大1273但是考虑残留的话应该可以更快一些).cpp
94b4fe64c3f0c0d15bb980d70608ad43d61451cf
[]
no_license
shaobozhong/myAcmCodes
8c63e7992d0975626e6e583a49e59fe03f73017c
55b31b8a4600fd3084795f71ac0d244cbdc58800
refs/heads/master
2023-08-04T20:05:29.165456
2023-07-26T03:19:52
2023-07-26T03:19:52
21,147,335
0
1
null
2023-07-26T03:19:53
2014-06-24T00:49:13
null
GB18030
C++
false
false
1,732
cpp
最大流模板(通过北大1273但是考虑残留的话应该可以更快一些).cpp
#include<iostream> #include<queue> using namespace std; #define MAX 1000 struct Node { int la; struct Node *next; }; int map[MAX][MAX];//存储图 bool find_path(int n,int s,int t,int *pre )//利用广度遍历 寻找增广路 总个数 n个 数组要往后放一个 { queue<int> q; bool vis[MAX]; int top;//队列中头的值 int i;// 循环变量 for(i=1;i<=n;++i) { vis[i]=true; } q.push(s); vis[s]=false; while(!q.empty())//广度优先 用队列实现 { top=q.front(); q.pop(); for(i=1;i<=n;++i)//点就只能从1开始了 { if (vis[i] && map[top][i]>0) { vis[i]=false; pre[i]=top; if (i==t) { return true; } q.push(i); } } } return false; } int Ford_Fulkerson(int n,int s,int t) { int pre[MAX];//用于记录从源点s到汇点t的增广路 int Flood;//总流量的值 int min1;//增广路的课增量中最小的那个 int i;//循环变量 Flood=0;//初始化 最大流量为0 while(find_path(n,s,t,pre)) { min1=INT_MAX; for(i=t;i!=s;i=pre[i])//找到可增量中最小的那个 { if (map[pre[i]][i]<min1) { min1=map[pre[i]][i]; } } //增大流量,同时使该增广路变为不可增广 for(i=t;i!=s;i=pre[i]) { map[pre[i]][i]-=min1; map[i][pre[i]]+=min1;//建逆向边 } Flood+=min1;//增大总流量 } return Flood; } int main() { int n,m; int num1,num2,flow; int i,j; int Flood; //freopen("1.txt","r",stdin); //freopen("2.txt","w",stdout); while(cin>>n>>m) { for(i=0;i<=m;++i) { for(j=0;j<=m;++j) { map[i][j]=0; } } for(i=1;i<=n;++i) { cin>>num1>>num2>>flow; map[num1][num2]+=flow; } Flood=Ford_Fulkerson(m,1,m); cout<<Flood<<endl; } return 0; }
5eb9ad231635a135943523e299b9c3f41b199d5f
411dade9424ceaa085d1798ab11083b6e657bb52
/Unnamed/Source/Unnamed/Public/Bush.h
a2fe42314a29da0768328b957def3c2a0f83865f
[]
no_license
ApprenticeSoft/unnamed_ue4_project
30635006611cdd5c1282cb4fe62eb522161333e7
58bd5fabac4a65018e52d44935ff23b679bbcba2
refs/heads/master
2020-04-14T22:48:25.222334
2019-07-01T05:45:44
2019-07-01T05:45:44
164,178,603
0
0
null
null
null
null
UTF-8
C++
false
false
1,001
h
Bush.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "Bush.generated.h" class UActorComponent; class ASingleLeave; class ASol; UCLASS() class UNNAMED_API ABush : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties ABush(); protected: virtual void BeginPlay() override; virtual void Tick(float DeltaTime) override; UPROPERTY(EditDefaultsOnly, Category = Setup) TSubclassOf<ASingleLeave> SingleLeaveBluePrint; TArray<UActorComponent*> Meshes; bool IsLeaning = false; FRotator DefaultRotator, NewRotator; float LeaningAlfa = 0; void Impact(); void RotateBack(); void SpawnLeaves(FVector Location, FVector ImpulseDirection); ASol* Soil = nullptr; public: UFUNCTION(BlueprintCallable) void ClearBush(); void SetSoil(ASol* NewSoil); ASol* GetSoil() const; bool IsInteractionEnabled(); void GenerateOverlapEvents(bool value); };
0689acc4df5ffa09e362495464ec98c49ba710dc
1df85af2b19f93220edf661c1cc6a893283da6ba
/cpu_tromp/cpu_tromp.hpp
cfdb2ab87a8f37d39783d76b77a0ec11282786d6
[ "MIT" ]
permissive
omittones/nheqminer
7e8931fbed9e9990db160b93ecd6c4bbf761aa0e
14b6c1d07761644cbad083b5880375da035befab
refs/heads/master
2021-01-12T14:40:32.026039
2016-11-11T14:48:36
2016-11-11T14:48:36
72,042,137
2
0
null
2016-10-26T20:34:56
2016-10-26T20:34:55
null
UTF-8
C++
false
false
701
hpp
cpu_tromp.hpp
#ifdef _LIB #define DLL_PREFIX __declspec(dllexport) #else #define DLL_PREFIX #endif #include "solver/solver.h" #if defined(__AVX__) #define CPU_TROMP_NAME "CPU-TROMP-AVX" #else #define CPU_TROMP_NAME "CPU-TROMP-SSE2" #endif struct DLL_PREFIX cpu_tromp : Solver { public: cpu_tromp() { } std::string getdevinfo() { return "CPU"; } void start(); void stop(); void solve(const char *header, unsigned int header_len, const char* nonce, unsigned int nonce_len, std::function<bool()> cancelf, std::function<void(const std::vector<uint32_t>&, size_t, const unsigned char*)> solutionf, std::function<void(void)> hashdonef); std::string getname() { return CPU_TROMP_NAME; } };
307db23038a651659d9d0a92da984ffc80affa38
989aa92c9dab9a90373c8f28aa996c7714a758eb
/HydraIRC/ServerMonitor.cpp
c620ec5c1d4e2dbb29690644a9cedd6b93d596e5
[]
no_license
john-peterson/hydrairc
5139ce002e2537d4bd8fbdcebfec6853168f23bc
f04b7f4abf0de0d2536aef93bd32bea5c4764445
refs/heads/master
2021-01-16T20:14:03.793977
2010-04-03T02:10:39
2010-04-03T02:10:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,528
cpp
ServerMonitor.cpp
/* HydraIRC Copyright (C) 2002-2006 Dominic Clifton aka Hydra HydraIRC limited-use source license 1) You can: 1.1) Use the source to create improvements and bug-fixes to send to the author to be incorporated in the main program. 1.2) Use it for review/educational purposes. 2) You can NOT: 2.1) Use the source to create derivative works. (That is, you can't release your own version of HydraIRC with your changes in it) 2.2) Compile your own version and sell it. 2.3) Distribute unmodified, modified source or compiled versions of HydraIRC without first obtaining permission from the author. (I want one place for people to come to get HydraIRC from) 2.4) Use any of the code or other part of HydraIRC in anything other than HydraIRC. 3) All code submitted to the project: 3.1) Must not be covered by any license that conflicts with this license (e.g. GPL code) 3.2) Will become the property of the author. */ // ServerMonitorView.cpp : implementation of the COutput class // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "HydraIRC.h" void CServerMonitorView::OnDocked(HDOCKBAR hBar,bool bHorizontal) { // we add remove these window types when the app is minimized/restored now /* DWORD dwStyle = GetWindowLong(GWL_EXSTYLE) & (~(WS_EX_APPWINDOW | WS_EX_TOPMOST)); // remove the flags.. SetWindowLong( GWL_EXSTYLE , dwStyle); */ baseClass::OnDocked(hBar,bHorizontal); } void CServerMonitorView::OnUndocked(HDOCKBAR hBar) { baseClass::OnUndocked(hBar); // we add remove these window types when the app is minimized/restored now /* DWORD dwStyle = GetWindowLong(GWL_EXSTYLE); dwStyle |= WS_EX_APPWINDOW | WS_EX_TOPMOST; // add the flags SetWindowLong( GWL_EXSTYLE , dwStyle); // this ignores the WS_EX_TOPMOST style. SetWindowPos(HWND_TOPMOST,0,0,0,0,SWP_NOMOVE | SWP_NOSIZE); // so we have to do this too. */ } LRESULT CServerMonitorView::OnSize(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled) { if(wParam != SIZE_MINIMIZED ) { RECT rc; GetClientRect(&rc); ::SetWindowPos(m_MsgView.m_hWnd, NULL, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top ,SWP_NOZORDER | SWP_NOACTIVATE); } // m_MsgView.ScrollToEnd(); // calling this directly doesn't work as the richedit control window hasn't updated yet // so we do this instead: g_pMainWnd->PostMessage(WM_REQUESTSCROLLTOEND,0,(LPARAM)m_MsgView.m_hWnd); // and then it gets round to it... bHandled = FALSE; return bHandled ? 0 : 1; // WM_SIZE - If an application processes this message, it should return zero. } LRESULT CServerMonitorView::OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { HICON hIconSmall = (HICON)::LoadImage(_Module.GetResourceInstance(), MAKEINTRESOURCE(m_dwIcon), IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR); SetIcon(hIconSmall, FALSE); #ifdef USE_XPCOMMANDBAR HWND hWndCmdBar = m_CmdBar.Create(m_hWnd, rcDefault, NULL, ATL_SIMPLE_CMDBAR_PANE_STYLE); m_CmdBar.Prepare(); #endif HWND out = m_MsgView.Create(m_hWnd,NULL,NULL, WS_CHILD | WS_VISIBLE | WS_VSCROLL | ES_MULTILINE | ES_DISABLENOSCROLL | ES_READONLY | ES_NOHIDESEL | ES_SAVESEL, WS_EX_CLIENTEDGE); m_MsgView.SetControlCodeMode(CTRLCODE_MODE_INTERPRET); m_MsgView.SetContextMenu(IDR_SERVERMONITOR_CONTEXT,m_hWnd); // the resource id of the menu, and the pointer to the window to receive the messages UpdateSettings(); return 0; } void CServerMonitorView::UpdateSettings( void ) { if (IsDocking()) { DWORD dwStyle = GetWindowLong(GWL_EXSTYLE) & (~(WS_EX_APPWINDOW | WS_EX_TOPMOST)); // remove the flags.. SetWindowLong( GWL_EXSTYLE , dwStyle); } // m_MsgView.SetFilterList(g_DefaultFilterList_ServerMonitor); // TODO: we don't do this anymore, BUT we will need to add m_Filter to CServerMonitorView instead if (g_pPrefs) { m_MsgView.SetTimeStamps(BOOLPREF(PREF_bServerMonitorTimestamps)); m_MsgView.SetMaxBufferLines(INTPREF(PREF_nMaxScrollBufferLines)); m_MsgView.SetFont(FONTPREF(PREF_fServerMonitorFont)); m_MsgView.SetColors(g_pPrefs->m_ColorPrefs); } m_MsgView.RedrawWindow(); } BOOL CServerMonitorView::IsMonitoring(IRCServer *pServer) { return (m_ServerList.Find(pServer) != -1); } void CServerMonitorView::AddServer(IRCServer *pServer) { if (!pServer) return; if (IsMonitoring(pServer)) return; m_ServerList.Add(pServer); Message(pServer,"\002Server Monitoring Started!"); } void CServerMonitorView::RemoveServer(IRCServer *pServer) { if (m_ServerList.Remove(pServer)) { Message(pServer,"\002Server Monitoring Stopped"); } } void CServerMonitorView::Message(IRCServer *pServer, char *Buffer) { BufferItem BI(BIC_UNKNOWN,strdup(Buffer)); Put(pServer,&BI); } void CServerMonitorView::Put(IRCServer *pServer, BufferItem *pBI) { char *monitorstr; if (!ProcessSimpleFilter(g_DefaultFilterList_ServerMonitor,pBI->m_Contents)) { monitorstr = HydraIRC_BuildString(1024,"%s: %s",pServer->m_pDetails->m_Name, pBI->m_Buffer); if (monitorstr) { m_MsgView.Put(pBI->m_Contents, monitorstr); free(monitorstr); } } } LRESULT CServerMonitorView::OnBnClickedStopAllMonitoring(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& bHandled) { while (m_ServerList.GetSize() > 0) { RemoveServer(m_ServerList[0]); } return 0; } void CServerMonitorView::OnEvent(int EventID, void *pData) { switch(EventID) { case EV_PREFSCHANGED: CServerMonitorView::UpdateSettings(); break; } } #ifdef USE_XPCOMMANDBAR LRESULT CServerMonitorView::OnMsgViewContextMenu(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/) { UINT ContextMenuID = (UINT)wParam; CMenu menuContext; menuContext.LoadMenu(IDR_SERVERMONITOR_CONTEXT); CMenuHandle menuPopup(menuContext.GetSubMenu(0)); POINT pt; ::GetCursorPos(&pt); m_CmdBar.TrackPopupMenu(menuPopup, TPM_LEFTALIGN | TPM_RIGHTBUTTON, pt.x, pt.y); //::TrackPopupMenu(menuPopup, 0, pt.x, pt.y, 0, m_hWnd, NULL); return 0; // ignored. } #endif
76ce0f65ab93af55cb8fbd9d67311d43e3cd60a8
ab60cf7ed7c5b7c5808624eebffd773dc2a678a6
/module/extension/Director/tests/util/diff_string.hpp
0367bc98d64e650e2cea034f08f9b6b35097e9fc
[]
no_license
NUbots/NUbots
a5faa92669e866abed7b075359faa05e6dc61911
e42a510a67684027fbd581ff696cc31af5047455
refs/heads/main
2023-09-02T19:32:50.457094
2023-09-01T19:54:01
2023-09-01T19:54:01
23,809,180
34
20
null
2023-09-12T12:55:08
2014-09-08T21:30:48
C++
UTF-8
C++
false
false
1,300
hpp
diff_string.hpp
/* * This file is part of the NUbots Codebase. * * The NUbots Codebase 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. * * The NUbots Codebase 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 the NUbots Codebase. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2022 NUbots <nubots@nubots.net> */ #include <string> #include <vector> namespace util { /** * Using an LCS algorithm prints out the two sets of string (expected and actual) side by side to show the * differences * * @param expected the expected series of events * @param actual the actual series of events * * @return a multiline string showing a human output of the difference */ std::string diff_string(const std::vector<std::string>& expected, const std::vector<std::string>& actual); } // namespace util
3e47aff1d5398f27b58a40248f6d71fb2979b466
c06a4d9938428058abdfc8ea5bfc3a9d5f58acc1
/DP/DP/src.cc
1681ccba38865b3ed82aa6419f664a6fc0cce42b
[]
no_license
TMACCAMTTT/LeetCode__
400a74a05aae604e868978129471b2f669084287
687100ca6d2bd86f822279b60cd3ff5c52c62f8d
refs/heads/master
2020-04-08T04:35:12.366378
2019-01-20T04:35:27
2019-01-20T04:35:27
159,023,353
2
0
null
null
null
null
GB18030
C++
false
false
10,131
cc
src.cc
#include "head.h" int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { //63 if (obstacleGrid.empty()) return 0; int n = obstacleGrid.size();//n行m列 int m = obstacleGrid[0].size(); if (obstacleGrid[0][0] || obstacleGrid[n - 1][m - 1]) return 0; vector<vector<int>> dp(n, vector<int>(m, 0)); for (int i = 0; i < m; i++) { if (!obstacleGrid[0][i]) { dp[0][i] = 1; } else { break; } } for (int i = 1; i < n; i++) { if (!obstacleGrid[i][0]) { dp[i][0] = 1; } else { break; } } for (int i = 1; i < n; i++) { for (int j = 1; j < m; j++) { if (obstacleGrid[i][j]) { dp[i][j] = 0; } else if (!obstacleGrid[i - 1][j] && !obstacleGrid[i][j - 1]) { dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; } else if (obstacleGrid[i - 1][j] && obstacleGrid[i][j - 1]) { dp[i][j] = 0; } else if (obstacleGrid[i - 1][j]) { dp[i][j] = dp[i][j - 1]; } else { dp[i][j] = dp[i - 1][j]; } } } return dp[n - 1][m - 1]; } int minPathSum(vector<vector<int>>& grid) { //64 if (grid.empty()) return 0; int m = grid.size(); int n = grid[0].size(); vector<vector<int>> dp(m, vector<int>(n, 0)); dp[0][0] = 1; for (int i = 1; i < n; i++) { dp[0][i] = dp[0][i - 1] + grid[0][i]; } for (int i = 1; i < m; i++) { dp[i][0] = dp[i - 1][0] + grid[i][0]; } for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]; } } return dp[m - 1][n - 1]; } int numDecodings(string s) { //91编码方法数 //设字符串s大小为n;dp[i]为走到s的第i位时,对应的解码方法数目,i=0,1,...,n-1; //1. i < 0 => dp[i] = 0; //2. 若s[i]==0 : (1)s[i-1] == 0 || s[i-1] > 2 => dp[i]=0; // (2)s[i-1] = 1 || s[i - 1] = 2 => dp[i] = dp[i - 2]; // 若s[i] != 0 : (1)s[i-1] == 0 || s[i-1] > 2 => dp[i] = dp[i - 1]; // (2)s[i-1] = 1 || s[i - 1] = 2 => dp[i] = dp[i - 1] + 2dp[i - 2];考虑最后两位组成27,28,29时的情况 int n = s.size(); if (!n) return 0; vector<int> v(n, 0); for (int i = 0; i < n; i++) { v[i] = int(s[i] - '0'); } vector<int> dp(n, 0); if (v[0]) dp[0] = 1;//字符串第一位不为0,则dp[0] = 1; for (int i = 1; i < n; i++) { if (!v[i]) {//s[i] = 0时的情况; if (!v[i - 1] || v[i - 1] > 2) dp[i] = 0; else { if (i == 1) dp[i] = 1; else dp[i] = dp[i - 2]; } } else {//s[i] != 0时的情况; if (!v[i - 1] || v[i - 1] > 2) dp[i] = dp[i - 1]; else { if (v[i - 1] == 2 && v[i] > 6) dp[i] = dp[i - 1]; else { if (i == 1) dp[i] = 2; else dp[i] = dp[i - 1] + dp[i - 2]; } } } } return dp[n - 1]; } int rob(vector<int>& nums) { //213 if (nums.empty()) return 0; if (nums.size() == 1) return nums[0]; if (nums.size() == 2) return max(nums[0], nums[1]); int n = nums.size(); vector<int> dp(n, 0); dp[0] = nums[0]; dp[1] = max(nums[0], nums[1]); for (int i = 2; i < n - 1; i++) { dp[i] = max(nums[i] + dp[i - 2], dp[i - 1]); } int res = dp[n - 2]; dp[1] = nums[1]; dp[2] = max(nums[1], nums[2]); for (int i = 3; i < n; i++) { dp[i] = max(nums[i] + dp[i - 2], dp[i - 1]); } return max(res, dp[n - 1]); } int maximalSquare(vector<vector<char>>& matrix) { //用二维dp数组,记录以矩阵中每个点为终点的最大正方形的边长;同时记录其中最大值; //设k = dp[i - 1][j - 1], 若当前点左边k个点,上方k个点均为1,则状态转移方程为:dp[i][j] = dp[i - 1][j - 1] + 1; //否则取左边和上方连续1的长度的较小者,作为当前点的dp数值; if (matrix.empty()) return 0; int length = matrix.size(); int breadth = matrix[0].size(); vector<vector<int>> dp(length, vector<int>(breadth, 0)); int res = 0; //初始化dp数组的第一行和第一列; for (int i = 0; i < breadth; i++) { dp[0][i] = matrix[0][i] - '0'; res = max(res, dp[0][i]); } for (int i = 1; i < length; i++) { dp[i][0] = matrix[i][0] - '0'; res = max(res, dp[i][0]); } for (int i = 1; i < length; i++) { for (int j = 1; j < breadth; j++) { if (matrix[i][j] == '1') { int flagx = 1, flagy = 1; int x = 1, y = 1; int l = dp[i - 1][j - 1]; for (int k = 1; k <= l; k++) { if (!(matrix[i - k][j] - '0')) { flagy = 0; break; } y++; } for (int k = 1; k <= l; k++) { if (!(matrix[i][j - k] - '0')) { flagx = 0; break; } x++; } if (flagx && flagy) dp[i][j] = dp[i - 1][j - 1] + 1; else dp[i][j] = min(x, y); res = max(res, dp[i][j]); } } } return res * res; } int nthUglyNumber(int n) { //264丑数 vector<int> res(1, 1); int i = 0, j = 0, k = 0; while (res.size() < n) { int curr = min(res[i] * 2, min(res[j] * 3, res[k] * 5)); res.push_back(curr); if (curr == res[i] * 2) i++; if (curr == res[j] * 3) j++; if (curr == res[k] * 5) k++; } return res[n - 1]; } int integerBreak(int n) { //343状态转移方程:dp[n]=max(i * dp[n - i]); if (!n) return 0; if (n == 1) return 0; if (n == 2) return 1; vector<int> dp(n + 1, 0); dp[1] = 1; dp[2] = 1; for (int i = 3; i < n + 1; i++) { int temp = 0; for (int j = 1; j < i; j++) { int t = max(i - j, dp[i - j]);//对每个数i - j,取它自身和它的最大积的较大者作为此时参与运算的,因为此时前面有j作为一个乘数,i-j不需要分解。 temp = max(temp, j * t); } dp[i] = temp; } return dp[n]; } bool PredictTheWinner(vector<int>& nums) { if (nums.empty()) return false; int n = nums.size(); if (n == 1) return true; vector<vector<int>> dp(n, vector<int>(n, 0)); for (int i = 0; i < n; i++) { dp[i][i] = nums[i]; } for (int i = n - 2; i >= 0; i--) { for (int j = i + 1; j < n; j++) { dp[i][j] = max(nums[i] - dp[i + 1][j], nums[j] - dp[i][j - 1]); } } if (dp[0][n - 1] >= 0) return true; return false; } bool stoneGame(vector<int>& piles) { int res = game(piles, 0, piles.size() - 1); if (res) return true; return false; } int game(vector<int>& piles, int left, int right) { //877递归算法:返回Alice做出最优选择的情况下,Alice与Lee得分的差值; if (piles.empty()) return 0; int left_diff; int right_diff; if (right - left == 1) return abs(piles[left] - piles[right]); else { left_diff = min(piles[left] - piles[left + 1] + game(piles, left + 2, right), piles[left] - piles[right] + game(piles, left + 1, right - 1));//Alice选左边时,Lee做出最优选择后,得分的差值; right_diff = min(piles[right] - piles[left] + game(piles, left + 1, right - 1), piles[right] - piles[right - 1] + game(piles, left, right - 2));//Alice选右边时,Lee做出最优选择后,得分的差值; } return max(left_diff, right_diff);//只要两者中有一个大于零,Alice就稳操胜券; } bool stoneGameDp(vector<int>& piles) { if (piles.empty()) return true; if (piles.size() == 2) return true; int n = piles.size(); vector<vector<int>> dp(n, vector<int>(n, 0)); for (int i = 0; i < n; i++) { dp[i][i] = piles[i]; } for (int i = n - 2; i >= 0; i--) { for (int j = i + 1; j < n; j++) { dp[i][j] = max(piles[i] - dp[i + 1][j], piles[j] - dp[i][j - 1]); } } if (dp[0][n - 1]) return true; return false; } int maxWidthRamp(vector<int>& A) { //962首先将给定数组分成若干段;规则为从第一个数开始,一直遍历,直到遇到一个比第一个小的数为止,作为第一段,将这段首尾的下标存入数组,然后开始寻找下一段; //分段完成之后,对每一段做如下操作:记录初始的段首段尾;从段首往左遍历,直到遇到一个大于段尾的数为止,若段首有变化,则做出标记;从段尾往右遍历,直到遇到一个小于段首的数为止,同理要标记; //若段首段尾都有变化:若新的段中段首小于等于段尾,则将新段长度插入结果数组;若段首大于段尾,选择变化较大的一个插入结果数组; //若只有段首或者段尾有变化,将相应的新段的长度插入结果数组;否则将原段长度插入; int n = A.size(); if (!n) return 0; int left = 0, right = 0; vector<pair<int, int>> vec; for (int i = 1; i < n; i++) { if (A[i] >= A[left]) { right = i; } else { pair<int, int> p; p = make_pair(left, right); vec.push_back(p); left = i; right = i; } } vec.push_back(make_pair(left, right)); int size = vec.size(); vector<int> res; for (int i = 0; i < size; i++) { bool l = 0, r = 0; int min, MAX; int left = vec[i].first; while (vec[i].first > 0) { vec[i].first--; if (A[vec[i].second] >= A[vec[i].first]) { min = vec[i].first; l = 1; } } int right = vec[i].second; while (vec[i].second < n - 1) { vec[i].second++; if (A[left] <= A[vec[i].second]) { MAX = vec[i].second; r = 1; } } if (l && r) { if (A[min] <= A[MAX]) res.push_back(MAX - min); else res.push_back(max(vec[i].second - min, MAX - vec[i].first)); } else if (l) { res.push_back(vec[i].second - min); } else if (r) { res.push_back(MAX - vec[i].first); } else { res.push_back(vec[i].second - vec[i].first); } } sort(res.begin(), res.end()); return res[res.size() - 1]; } int maxTurbulenceSize(vector<int>& A) { //978.交叉排序数组:1<2>3<4>5;求一个数组中交叉排序子数组的最大长度; if (A.empty()) return 0; int size = A.size(); int res = 0; vector<int> dp(size, 0); dp[0] = 1; if (size == 1) return 1; int preflag, curflag; if (A[0] == A[1]) { preflag = 0; dp[1] = 1; } else if (A[0] < A[1]) { preflag = -1; dp[1] = 2; } else { preflag = 1; dp[1] = 2; } if (size == 2) return 2 - (preflag == 0); for (int i = 2; i < size; i++) { if (A[i - 1] == A[i]) curflag = 0; else if (A[i - 1] < A[i]) curflag = -1; else curflag = 1; if (!curflag) dp[i] = 1; else { if (curflag + preflag == 0) { dp[i] = dp[i - 1] + 1; res = max(res, dp[i]); } else { dp[i] = 2; res = max(res, dp[i - 1]); } } preflag = curflag; } return res; }
8b4fd57f5531316a1369e8a5cef1152837f35bb2
1408c9b234d8d94f182c11c53f92dd0c8f80c16d
/ACore/test/TestStr.cpp
c3998ee29a53a1dc883dbe647db0a4496147d06a
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference", "MIT", "BSL-1.0" ]
permissive
XiaoLinhong/ecflow
8f324250d0a5308b3e39f3dd5bd7a297a2e49c90
57ba5b09a35b064026a10638a10b31d660587a75
refs/heads/master
2023-06-19T04:07:54.150363
2021-05-19T14:58:16
2021-05-19T14:58:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
32,846
cpp
TestStr.cpp
//============================================================================ // Name : // Author : Avi // Revision : $Revision: #24 $ // // Copyright 2009-2020 ECMWF. // This software is licensed under the terms of the Apache Licence version 2.0 // which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. // In applying this licence, ECMWF does not waive the privileges and immunities // granted to it by virtue of its status as an intergovernmental organisation // nor does it submit to any jurisdiction. // // Description : //============================================================================ #include <string> #include <iostream> #include <algorithm> //#include <fstream> #include <boost/test/unit_test.hpp> //#include <boost/timer/timer.hpp> //#include <boost/lexical_cast.hpp> //#include <boost/algorithm/string.hpp> #include "Str.hpp" #include "StringSplitter.hpp" using namespace std; using namespace ecf; using namespace boost; BOOST_AUTO_TEST_SUITE( CoreTestSuite ) BOOST_AUTO_TEST_CASE( test_str ) { cout << "ACore:: ...test_str\n"; { std::string str; std::string expected; Str::removeQuotes(str); BOOST_CHECK_MESSAGE(str == expected," Expected " << expected << " but found " << str); str = "\"\""; expected = ""; Str::removeQuotes(str); BOOST_CHECK_MESSAGE(str == expected," Expected " << expected << " but found " << str); str = "fred"; expected = "fred"; Str::removeQuotes(str); BOOST_CHECK_MESSAGE(str == expected," Expected " << expected << " but found " << str); str = "\"fred\""; expected = "fred"; Str::removeQuotes(str); BOOST_CHECK_MESSAGE(str == expected," Expected " << expected << " but found " << str); } { std::string str; std::string expected; Str::removeSingleQuotes(str); BOOST_CHECK_MESSAGE(str == expected," Expected " << expected << " but found " << str); str = "''"; expected = ""; Str::removeSingleQuotes(str); BOOST_CHECK_MESSAGE(str == expected," Expected " << expected << " but found " << str); str = "fred"; expected = "fred"; Str::removeSingleQuotes(str); BOOST_CHECK_MESSAGE(str == expected," Expected " << expected << " but found " << str); str = "'fred'"; expected = "fred"; Str::removeSingleQuotes(str); BOOST_CHECK_MESSAGE(str == expected," Expected " << expected << " but found " << str); } { string test; BOOST_CHECK_MESSAGE(!Str::truncate_at_start(test,7),"Empty sring should return false"); test= "this\nis\na\nstring\nwith\nlots\nof\nnew\nline"; string expected = "line"; BOOST_CHECK_MESSAGE(Str::truncate_at_start(test,1) && test==expected,"Expected:\n" << expected << "\nbut found:\n" << test); test= "this\nis\na\nstring\nwith\nlots\nof\nnew\nline"; expected = "a\nstring\nwith\nlots\nof\nnew\nline"; BOOST_CHECK_MESSAGE(Str::truncate_at_start(test,7) && test==expected,"Expected:\n" << expected << "\nbut found:\n" << test); test= "this\nis\na\nstring\nwith\nlots\nof\nnew\nline"; expected = test; BOOST_CHECK_MESSAGE(!Str::truncate_at_start(test,9) && test==expected,"Expected:\n" << expected << "\nbut found:\n" << test); } { string test; BOOST_CHECK_MESSAGE(!Str::truncate_at_end(test,7),"Empty string should return false"); test= "this\nis\na\nstring\nwith\nlots\nof\nnew\nline"; string expected = "this\n"; BOOST_CHECK_MESSAGE(Str::truncate_at_end(test,1) && test==expected,"Expected:\n" << expected << "\nbut found:\n" << test); test= "this\nis\na\nstring\nwith\nlots\nof\nnew\nline"; expected = "this\nis\n"; BOOST_CHECK_MESSAGE(Str::truncate_at_end(test,2) && test==expected,"Expected:\n" << expected << "\nbut found:\n" << test); test= "this\nis\na\nstring\nwith\nlots\nof\nnew\nline"; expected= "this\nis\na\nstring\nwith\nlots\nof\n"; BOOST_CHECK_MESSAGE(Str::truncate_at_end(test,7) && test==expected,"Expected:\n" << expected << "\nbut found:\n" << test); test= "this\nis\na\nstring\nwith\nlots\nof\nnew\nline"; expected = test; BOOST_CHECK_MESSAGE(!Str::truncate_at_end(test,9) && test==expected,"Expected:\n" << expected << "\nbut found:\n" << test); } } static void check(const std::string& line, const std::vector<std::string>& result, const std::vector<std::string>& expected ) { BOOST_CHECK_MESSAGE(result.size() == expected.size(),"expected size " << expected.size() << " but found " << result.size() << " for '" << line << "'"); BOOST_CHECK_MESSAGE(result == expected,"failed for '" << line << "'"); if (result != expected) { cout << "Line :'" << line << "'\n"; cout << "Actual :"; for(const string& t: result) { cout << "'" << t << "'"; } cout << "\n"; cout << "Expected:"; for(const string& t: expected) { cout << "'" << t << "'"; } cout << "\n"; } } static void check(const std::string& line, const std::vector<boost::string_view>& result2, const std::vector<std::string>& expected ) { std::vector<std::string> result; for(auto ref : result2) { result.emplace_back(ref.begin(),ref.end()); } check(line,result,expected); } static void check(const std::string& line, boost::split_iterator<std::string::const_iterator> res, const std::vector<std::string>& expected ) { std::vector<std::string> result; typedef boost::split_iterator<std::string::const_iterator> split_iter_t; for(; res!= split_iter_t(); res++) result.push_back(boost::copy_range<std::string>(*res)); check(line,result,expected); } static void check_splitters(const std::string& line,const std::vector<std::string>& expected) { std::vector<std::string> result,result1,result2,result3; std::vector<boost::string_view> result4; Str::split_orig(line,result); check(line,result,expected); Str::split_orig1(line,result1); check(line,result1,expected); Str::split_using_string_view(line,result2); check(line,result2,expected); Str::split_using_string_view2(line,result3);check(line,result3,expected); StringSplitter::split(line,result4); check(line,result4,expected); // While were at it also check get_token for(size_t i=0; i < result1.size(); i++){ std::string token; BOOST_CHECK_MESSAGE(Str::get_token(line,i,token) && token == result1[i],"Str::get_token failed for pos " << i << " line:'" << line << "' expected '" << result1[i] << "' but found '" << token << "'"); token.clear(); BOOST_CHECK_MESSAGE(Str::get_token2(line,i,token) && token == result1[i],"Str::get_token2 failed for pos " << i << " line:'" << line << "' expected '" << result1[i] << "' but found '" << token << "'"); token.clear(); BOOST_CHECK_MESSAGE(Str::get_token3(line,i,token) && token == result1[i],"Str::get_token3 failed for pos " << i << " line:'" << line << "' expected '" << result1[i] << "' but found '" << token << "'"); token.clear(); BOOST_CHECK_MESSAGE(StringSplitter::get_token(line,i,token) && token == result1[i],"StringSplitter::get_token failed for pos " << i << " line:'" << line << "' expected '" << result1[i] << "' but found '" << token << "'"); } } BOOST_AUTO_TEST_CASE( test_str_split ) { cout << "ACore:: ...test_str_split\n"; std::vector<std::string> expected; std::string line = "This is a string"; expected.emplace_back("This"); expected.emplace_back("is"); expected.emplace_back("a"); expected.emplace_back("string"); check_splitters(line,expected); expected.clear(); line = " "; check_splitters(line,expected); line = "a"; expected.clear(); expected.emplace_back("a"); check_splitters(line,expected); // Some implementation fail this test line = "\n"; expected.clear(); expected.emplace_back("\n"); check_splitters(line,expected); line = "a "; expected.clear(); expected.emplace_back("a"); check_splitters(line,expected); line = " a"; expected.clear(); expected.emplace_back("a"); check_splitters(line,expected); line = " a"; // check tabs expected.clear(); expected.emplace_back("a"); check_splitters(line,expected); line = " a "; // check sequential tabs expected.clear(); expected.emplace_back("a"); check_splitters(line,expected); line = " a "; expected.clear(); expected.emplace_back("a"); check_splitters(line,expected); line = " a b c d "; expected.clear(); expected.emplace_back("a"); expected.emplace_back("b"); expected.emplace_back("c"); expected.emplace_back("d"); check_splitters(line,expected); line = " - ! $ % ^ & * ( ) - + ?"; expected.clear(); expected.emplace_back("-"); expected.emplace_back("!"); expected.emplace_back("$"); expected.emplace_back("%"); expected.emplace_back("^"); expected.emplace_back("&"); expected.emplace_back("*"); expected.emplace_back("("); expected.emplace_back(")"); expected.emplace_back("-"); expected.emplace_back("+"); expected.emplace_back("?"); check_splitters(line,expected); // Check tabs line = " verify complete:8 # 4 sundays in october hence expect 8 task completions"; expected.clear(); expected.emplace_back("verify");expected.emplace_back("complete:8");expected.emplace_back("#");expected.emplace_back("4"); expected.emplace_back("sundays");expected.emplace_back("in");expected.emplace_back("october");expected.emplace_back("hence"); expected.emplace_back("expect");expected.emplace_back("8");expected.emplace_back("task");expected.emplace_back("completions"); check_splitters(line,expected); } BOOST_AUTO_TEST_CASE( test_str_split_make_split_iterator ) { cout << "ACore:: ...test_str_split_make_split_iterator\n"; std::string line = "This is a string"; std::vector<std::string> expected; expected.emplace_back("This"); expected.emplace_back("is"); expected.emplace_back("a"); expected.emplace_back("string"); check(line,Str::make_split_iterator(line),expected); expected.clear(); expected.emplace_back(""); line = ""; check(line,Str::make_split_iterator(line),expected); expected.clear(); expected.emplace_back(""); expected.emplace_back(""); line = " "; // If start/end is delimeter, then preserved as empty token check(line,Str::make_split_iterator(line),expected); expected.clear(); line = "a"; expected.emplace_back("a"); check(line,Str::make_split_iterator(line),expected); // Some implementation fail this test expected.clear(); line = "\n"; expected.emplace_back("\n"); check(line,Str::make_split_iterator(line),expected); expected.clear(); line = "a "; expected.emplace_back("a");expected.emplace_back(""); // delimeter at start/end preserved, as empty token check(line,Str::make_split_iterator(line),expected); expected.clear(); line = " a"; expected.emplace_back(""); expected.emplace_back("a"); // delimeter at start/end preserved, as empty token check(line,Str::make_split_iterator(line),expected); expected.clear(); line = " a"; // check tabs expected.emplace_back(""); expected.emplace_back("a"); // delimeter at start/end preserved, as empty token check(line,Str::make_split_iterator(line),expected); expected.clear(); line = " a "; // check sequential tabs expected.emplace_back(""); expected.emplace_back("a"); // delimeter at start/end preserved, as empty token expected.emplace_back(""); check(line,Str::make_split_iterator(line),expected); expected.clear(); line = " a "; expected.emplace_back(""); expected.emplace_back("a"); // delimeter at start/end preserved, as empty token expected.emplace_back(""); check(line,Str::make_split_iterator(line),expected); expected.clear(); line = " a b c d "; expected.emplace_back(""); // delimeter at start/end preserved, as empty token expected.emplace_back("a"); expected.emplace_back("b"); expected.emplace_back("c"); expected.emplace_back("d"); expected.emplace_back(""); check(line,Str::make_split_iterator(line),expected); expected.clear(); line = " - ! $ % ^ & * ( ) - + ?"; expected.emplace_back(""); // delimeter at start/end preserved, as empty token expected.emplace_back("-"); expected.emplace_back("!"); expected.emplace_back("$"); expected.emplace_back("%"); expected.emplace_back("^"); expected.emplace_back("&"); expected.emplace_back("*"); expected.emplace_back("("); expected.emplace_back(")"); expected.emplace_back("-"); expected.emplace_back("+"); expected.emplace_back("?"); check(line,Str::make_split_iterator(line),expected); // Check tabs expected.clear(); line = " verify complete:8 # 4 sundays in october hence expect 8 task completions"; expected.emplace_back(""); // delimeter at start/end preserved, as empty token expected.emplace_back("verify");expected.emplace_back("complete:8");expected.emplace_back("#");expected.emplace_back("4"); expected.emplace_back("sundays");expected.emplace_back("in");expected.emplace_back("october");expected.emplace_back("hence"); expected.emplace_back("expect");expected.emplace_back("8");expected.emplace_back("task");expected.emplace_back("completions"); check(line,Str::make_split_iterator(line),expected); } static void test_replace( std::string& testStr, const std::string& find, const std::string& replace, const std::string& expected) { BOOST_CHECK_MESSAGE(Str::replace(testStr,find,replace), "Replace failed for " << testStr << " find(" << find << ") replace(" << replace << ")"); BOOST_CHECK_MESSAGE(testStr == expected,"Expected '" << expected << "' but found '" << testStr <<"'"); } static void test_replace_all( std::string& testStr, const std::string& find, const std::string& replace, const std::string& expected) { std::string testStrCopy = testStr; BOOST_CHECK_MESSAGE(Str::replace_all(testStr,find,replace), "Replace failed for " << testStr << " find(" << find << ") replace(" << replace << ")"); BOOST_CHECK_MESSAGE(testStr == expected,"Expected '" << expected << "' but found '" << testStr <<"'"); Str::replaceall(testStrCopy,find,replace); BOOST_CHECK_MESSAGE(testStr == testStrCopy,"Expected '" << testStrCopy << "' but found '" << testStr <<"'"); } BOOST_AUTO_TEST_CASE( test_str_replace ) { cout << "ACore:: ...test_str_replace\n"; std::string testStr = "This is a string"; test_replace(testStr,"This","That","That is a string"); testStr = "This is a string"; test_replace(testStr,"This is a string","",""); testStr = "This is a string"; test_replace(testStr,"is a","was a","This was a string"); testStr = "This\n is a string"; test_replace(testStr,"\n","\\n","This\\n is a string"); testStr = "This\n is\n a\n string\n"; test_replace_all(testStr,"\n","\\n",R"(This\n is\n a\n string\n)"); // Test case insenstive string comparison BOOST_CHECK_MESSAGE(Str::caseInsCompare("","")," bug1"); BOOST_CHECK_MESSAGE(!Str::caseInsCompare("Str","Str1")," bug1"); BOOST_CHECK_MESSAGE(!Str::caseInsCompare("","Str1")," bug1"); BOOST_CHECK_MESSAGE(Str::caseInsCompare("Str","STR")," bug1"); BOOST_CHECK_MESSAGE(Str::caseInsCompare("Case","CaSE")," bug1"); } BOOST_AUTO_TEST_CASE( test_str_replace_all ) { cout << "ACore:: ...test_str_replace_all\n"; std::string testStr = "This is a string"; test_replace_all(testStr,"This","That","That is a string"); testStr = "This is a string"; test_replace_all(testStr,"This is a string","",""); testStr = "This is a string"; test_replace_all(testStr,"is a","was a","This was a string"); testStr = "This\n is a string"; test_replace_all(testStr,"\n","\\n","This\\n is a string"); testStr = "This\n is\n a\n string\n"; test_replace_all(testStr,"\n","\\n",R"(This\n is\n a\n string\n)"); testStr = "This\n is\n a\n string\n"; test_replace_all(testStr,"\n","","This is a string"); } BOOST_AUTO_TEST_CASE( test_str_to_int ) { cout << "ACore:: ...test_str(to_int)\n"; BOOST_CHECK_MESSAGE(Str::to_int("0") == 0,"Expected 0"); BOOST_CHECK_MESSAGE(Str::to_int("1") == 1,"Expected 1"); BOOST_CHECK_MESSAGE(Str::to_int("-0") == 0,"Expected 0"); BOOST_CHECK_MESSAGE(Str::to_int("-1") == -1,"Expected -1"); BOOST_CHECK_MESSAGE(Str::to_int("") == std::numeric_limits<int>::max(),"Expected max int"); BOOST_CHECK_MESSAGE(Str::to_int("-") == std::numeric_limits<int>::max(),"Expected max int"); BOOST_CHECK_MESSAGE(Str::to_int(" ") == std::numeric_limits<int>::max(),"Expected max int"); BOOST_CHECK_MESSAGE(Str::to_int("q") == std::numeric_limits<int>::max(),"Expected max int"); BOOST_CHECK_MESSAGE(Str::to_int("q22") == std::numeric_limits<int>::max(),"Expected max int"); BOOST_CHECK_MESSAGE(Str::to_int("q22",-1) == -1,"Expected -1 on failure"); BOOST_CHECK_MESSAGE(Str::to_int("99 99") == std::numeric_limits<int>::max(),"Expected max int"); BOOST_CHECK_MESSAGE(Str::to_int("99 99",0) == 0,"Expected 0 for failure"); } BOOST_AUTO_TEST_CASE( test_extract_data_member_value ) { cout << "ACore:: ...test_extract_data_member_value\n"; std::string expected = "value"; std::string actual; std::string str = "aa bb c fred:value"; BOOST_CHECK_MESSAGE(Str::extract_data_member_value(str,"fred:",actual)," failed"); BOOST_CHECK_MESSAGE(expected == actual,"expected '" << expected << "' but found '" << actual << "'"); str = "fred:x bill:zzz jake:12345 1234:99 6677"; expected = "x"; BOOST_CHECK_MESSAGE(Str::extract_data_member_value(str,"fred:",actual)," failed"); BOOST_CHECK_MESSAGE(expected == actual,"expected '" << expected << "' but found '" << actual << "'"); expected = "zzz"; BOOST_CHECK_MESSAGE(Str::extract_data_member_value(str,"bill:",actual)," failed"); BOOST_CHECK_MESSAGE(expected == actual,"expected '" << expected << "' but found '" << actual << "'"); expected = "12345"; BOOST_CHECK_MESSAGE(Str::extract_data_member_value(str,"jake:",actual)," failed"); BOOST_CHECK_MESSAGE(expected == actual,"expected '" << expected << "' but found '" << actual << "'"); expected = "99"; BOOST_CHECK_MESSAGE(Str::extract_data_member_value(str,"1234:",actual)," failed"); BOOST_CHECK_MESSAGE(expected == actual,"expected '" << expected << "' but found '" << actual << "'"); expected = "77"; BOOST_CHECK_MESSAGE(Str::extract_data_member_value(str,"66",actual)," failed"); BOOST_CHECK_MESSAGE(expected == actual,"expected '" << expected << "' but found '" << actual << "'"); } std::string toString(const std::vector<std::string>& c) { std::stringstream ss; std::copy (c.begin(), c.end(), std::ostream_iterator <std::string> (ss, ", ")); return ss.str(); } BOOST_AUTO_TEST_CASE( test_str_less_greater) { cout << "ACore:: ...test_str_less_greater\n"; std::vector<std::string> expected; expected.emplace_back("a1"); expected.emplace_back("A2"); expected.emplace_back("b1"); expected.emplace_back("B2"); expected.emplace_back("c"); std::vector<std::string> expectedGreater; expectedGreater.emplace_back("c"); expectedGreater.emplace_back("B2"); expectedGreater.emplace_back("b1"); expectedGreater.emplace_back("A2"); expectedGreater.emplace_back("a1"); std::vector<std::string> vec; vec.emplace_back("c"); vec.emplace_back("A2"); vec.emplace_back("a1"); vec.emplace_back("b1"); vec.emplace_back("B2"); std::sort(vec.begin(),vec.end(),Str::caseInsLess); BOOST_REQUIRE_MESSAGE( vec == expected,"expected " << toString(expected) << " but found " << toString(vec) ); std::sort(vec.begin(),vec.end(),Str::caseInsGreater); BOOST_REQUIRE_MESSAGE( vec == expectedGreater,"expected " << toString(expectedGreater) << " but found " << toString(vec) ); // -------------------------------------------------------------------- expected.clear(); expected.emplace_back("a"); expected.emplace_back("A"); expected.emplace_back("b"); expected.emplace_back("B"); expected.emplace_back("c"); expectedGreater.clear(); expectedGreater.emplace_back("c"); expectedGreater.emplace_back("B"); expectedGreater.emplace_back("b"); expectedGreater.emplace_back("A"); expectedGreater.emplace_back("a"); vec.clear(); vec.emplace_back("c"); vec.emplace_back("B"); vec.emplace_back("A"); vec.emplace_back("b"); vec.emplace_back("a"); std::sort(vec.begin(),vec.end(),Str::caseInsLess); BOOST_REQUIRE_MESSAGE( vec == expected,"expected " << toString(expected) << " but found " << toString(vec) ); std::sort(vec.begin(),vec.end(),Str::caseInsGreater); BOOST_REQUIRE_MESSAGE( vec == expectedGreater,"expected " << toString(expectedGreater) << " but found " << toString(vec) ); // -------------------------------------------------------------------- expected.clear(); expected.emplace_back("1234"); expected.emplace_back("baSE"); expected.emplace_back("Base"); expected.emplace_back("case"); expected.emplace_back("CaSe"); expected.emplace_back("suite"); expected.emplace_back("SUITE"); expectedGreater.clear(); expectedGreater.emplace_back("SUITE"); expectedGreater.emplace_back("suite"); expectedGreater.emplace_back("CaSe"); expectedGreater.emplace_back("case"); expectedGreater.emplace_back("Base"); expectedGreater.emplace_back("baSE"); expectedGreater.emplace_back("1234"); vec.clear(); vec.emplace_back("suite"); vec.emplace_back("SUITE"); vec.emplace_back("baSE"); vec.emplace_back("Base"); vec.emplace_back("case"); vec.emplace_back("CaSe"); vec.emplace_back("1234"); std::sort(vec.begin(),vec.end(),Str::caseInsLess); BOOST_REQUIRE_MESSAGE( vec == expected,"expected " << toString(expected) << " but found " << toString(vec) ); std::sort(vec.begin(),vec.end(),Str::caseInsGreater); BOOST_REQUIRE_MESSAGE( vec == expectedGreater,"expected " << toString(expectedGreater) << " but found " << toString(vec) ); } //// ============================================================== //// Timing to find the fastest looping //// ============================================================== //class Fred { //public: // Fred(int i = 0) : i_(i) { /*std::cout << "Fred constructor\n"*/;} // Fred(const Fred& rhs) : i_(rhs.i_) { /*std::cout << "Fred copy constructor\n";*/ } // Fred& operator=(const Fred& rhs) { /*std::cout << "assignment operator\n";*/ i_ = rhs.i_; return *this;} // ~Fred() { /*std::cout << "Fred destructor\n";*/} // // void inc() { i_++;} //private: // int i_; //}; //BOOST_AUTO_TEST_CASE( test_loop ) //{ // size_t vecSize = 200000000; // std::vector<Fred> vec; // vec.reserve(vecSize); // for (size_t i = 0; i < vecSize ; i++) { vec.push_back(Fred(i));} // // boost::timer::cpu_timer timer; // measures CPU, replace with cpu_timer with boost > 1.51, measures cpu & elapsed// // timer.restart(); // for(auto &fred : vec) { fred.inc(); } // cout << "Time: for(auto &fred : vec) { fred.inc(); } " << timer.format(3,Str::cpu_timer_format()) << "\n"; // // timer.restart(); // std::for_each(vec.begin(),vec.end(),[](Fred& fred) { fred.inc();} ); // cout << "Time: std::for_each(vec.begin(),vec.end(),[](Fred& fred) { fred.inc();} ); " << timer.format(3,Str::cpu_timer_format()) << "\n"; // // timer.restart(); // std::vector<Fred>::iterator theEnd = vec.end(); // for (std::vector<Fred>::iterator i = vec.begin(); i < theEnd ; i++) { (*i).inc(); } // cout << "Time: for (std::vector<Fred>::iterator i = vec.begin(); i < theEnd ; i++) { (*i).inc(); } " << timer.format(3,Str::cpu_timer_format()) << "\n"; // // timer.restart(); // std::for_each(vec.begin(),vec.end(),std::mem_fun_ref(&Fred::inc) ); // cout << "Time: std::for_each(vec.begin();vec.end(),std::mem_fun_ref(&Fred::inc)) " << timer.format(3,Str::cpu_timer_format()) << "\n"; // // timer.restart(); // size_t theSize = vec.size(); // for (size_t i = 0; i < theSize ; i++) { vec[i].inc(); } // cout << "Time: for (size_t i = 0; i < theSize ; i++) { vec[i].inc(); } " << timer.format(3,Str::cpu_timer_format()) << "\n"; //} /// ============================================================== /// Timing to find the fastest conversion from string to int /// ============================================================== //static void methodX( const std::string& str, // std::vector<std::string>& stringRes, // std::vector<int>& numberRes) //{ // // 0.81 // // for bad conversion istringstream seems to return 0, hence add guard // if ( str.find_first_of( Str::NUMERIC(), 0 ) == 0 ) { // int number = 0; // std::istringstream ( str ) >> number; // numberRes.push_back( number ); // } // else { // stringRes.push_back( str ); // } //} // // //static void method1( const std::string& str, // std::vector<std::string>& stringRes, // std::vector<int>& numberRes) //{ // // 12.2 // try { // int number = boost::lexical_cast< int >( str ); // numberRes.push_back( number ); // } // catch ( boost::bad_lexical_cast& ) { // stringRes.push_back( str ); // } //} // //static void method2( const std::string& str, // std::vector<std::string>& stringRes, // std::vector<int>& numberRes) //{ // // 0.6 // if ( str.find_first_of( Str::NUMERIC(), 0 ) == 0 ) { // try { // int number = boost::lexical_cast< int >( str ); // numberRes.push_back( number ); // } // catch ( boost::bad_lexical_cast& ) { // stringRes.push_back( str ); // } // } // else { // stringRes.push_back( str ); // } //} // //static void method3( const std::string& str, // std::vector<std::string>& stringRes, // std::vector<int>& numberRes) //{ // // 0.14 // // atoi return 0 for errors, // int number = atoi(str.c_str()); //does not handle errors // if (number == 0 && str.size() != 1) { // stringRes.push_back( str ); // } // else { // numberRes.push_back( number ); // } //} // // //BOOST_AUTO_TEST_CASE( test_lexical_cast_perf ) //{ // cout << "ACore:: ...test_string_to_int_conversion\n"; // // size_t the_size = 1000000; // std::vector<std::string> stringTokens; // std::vector<std::string> numberTokens; // std::vector<int> expectedNumberRes; // for(size_t i=0; i < the_size; i++) { stringTokens.push_back("astring");} // for(size_t i=0; i < the_size; i++) { // numberTokens.push_back(boost::lexical_cast<string>(i)); // expectedNumberRes.push_back(i); // } // // std::vector<std::string> stringRes; stringTokens.reserve(stringTokens.size()); // std::vector<int> numberRes; numberRes.reserve(expectedNumberRes.size()); // // { // boost::timer::cpu_timer timer; // measures CPU, replace with cpu_timer with boost > 1.51, measures cpu & elapsed // for(size_t i =0; i < stringTokens.size(); i++) { // method1(stringTokens[i], stringRes, numberRes ); // } // for(size_t i =0; i < numberTokens.size(); i++) { // method1(numberTokens[i], stringRes, numberRes ); // } // cout << "Time for method1 elapsed time = " << timer.format(3,Str::cpu_timer_format()) << "\n"; // BOOST_CHECK_MESSAGE(numberRes == expectedNumberRes," method 1 wrong"); // BOOST_CHECK_MESSAGE(stringTokens == stringRes,"method 1 wrong"); // numberRes.clear(); // stringRes.clear(); // } // // { // boost::timer::cpu_timer timer; // measures CPU, replace with cpu_timer with boost > 1.51, measures cpu & elapsed // for(size_t i =0; i < stringTokens.size(); i++) { // methodX(stringTokens[i], stringRes, numberRes ); // } // for(size_t i =0; i < numberTokens.size(); i++) { // methodX(numberTokens[i], stringRes, numberRes ); // } // cout << "Time for methodX elapsed time = " << timer.format(3,Str::cpu_timer_format()) << "\n"; // BOOST_CHECK_MESSAGE(numberRes == expectedNumberRes," method X wrong"); // BOOST_CHECK_MESSAGE(stringTokens == stringRes,"method X wrong"); // numberRes.clear(); // stringRes.clear(); // } // // { // boost::timer::cpu_timer timer; // measures CPU, replace with cpu_timer with boost > 1.51, measures cpu & elapsed // for(size_t i =0; i < stringTokens.size(); i++) { // method2(stringTokens[i], stringRes, numberRes ); // } // for(size_t i =0; i < numberTokens.size(); i++) { // method2(numberTokens[i], stringRes, numberRes ); // } // cout << "Time for method2 elapsed time = " << timer.format(3,Str::cpu_timer_format()) << "\n"; // BOOST_CHECK_MESSAGE(numberRes == expectedNumberRes,"method 2 wrong"); // BOOST_CHECK_MESSAGE(stringTokens == stringRes,"method 2 wrong"); // numberRes.clear(); // stringRes.clear(); // } // // { // boost::timer::cpu_timer timer; // measures CPU, replace with cpu_timer with boost > 1.51, measures cpu & elapsed // for(size_t i =0; i < stringTokens.size(); i++) { // method3(stringTokens[i], stringRes, numberRes ); // } // for(size_t i =0; i < numberTokens.size(); i++) { // method3(numberTokens[i], stringRes, numberRes ); // } // cout << "Time for method3 elapsed time = " << timer.format(3,Str::cpu_timer_format()) << "\n"; // BOOST_CHECK_MESSAGE(numberRes == expectedNumberRes," method3 wrong numberRes.size()=" << numberRes.size() << " expected size = " << expectedNumberRes.size()); // BOOST_CHECK_MESSAGE(stringTokens == stringRes," method3 wrong stringRes.size()=" << stringRes.size() << " expected size = " << stringTokens.size()); // numberRes.clear(); // stringRes.clear(); // } //} //BOOST_AUTO_TEST_CASE( test_int_to_str_perf ) //{ // cout << "ACore:: ...test_int_to_str_perf\n"; // // // Lexical_cast is approx twice as fast as using streams // // time for ostream = 0.97 // // time for lexical_cast = 0.45 // // const int the_size = 1000000; // { // boost::timer::cpu_timer timer; // measures CPU, replace with cpu_timer with boost > 1.51, measures cpu & elapsed // for(size_t i =0; i < the_size; i++) { // std::ostringstream st; // st << i; // std::string s = st.str(); // } // cout << "Time for int to string using ostringstream elapsed time = " << timer.format(3,Str::cpu_timer_format()) << "\n"; // } // // // { // boost::timer::cpu_timer timer; // measures CPU, replace with cpu_timer with boost > 1.51, measures cpu & elapsed // for(size_t i =0; i < the_size; i++) { // std::string s = boost::lexical_cast<std::string>(i); // } // cout << "Time for int to string using boost::lexical_cast elapsed time = " << timer.format(3,Str::cpu_timer_format()) << "\n"; // } //} BOOST_AUTO_TEST_CASE( test_str_valid_name ) { cout << "ACore:: ...test_str_valid_name\n"; std::vector<std::string> valid; valid.emplace_back("a"); valid.emplace_back("a122345"); valid.emplace_back("_a122345"); valid.emplace_back("_"); valid.emplace_back("0"); valid.emplace_back("1"); valid.emplace_back("2"); valid.emplace_back("3"); valid.emplace_back("4"); valid.emplace_back("5"); valid.emplace_back("6"); valid.emplace_back("7"); valid.emplace_back("8"); valid.emplace_back("9"); valid.emplace_back("11"); valid.emplace_back("111"); for(const auto & i : valid) { std::string msg; BOOST_CHECK_MESSAGE( Str::valid_name( i,msg ) ,"Expected " << i << " to be valid" ); BOOST_CHECK_MESSAGE( Str::valid_name( i) ,"Expected " << i << " to be valid" ); } BOOST_CHECK_MESSAGE( !Str::valid_name( "") ,"Expected empty string to be in-valid" ); BOOST_CHECK_MESSAGE( !Str::valid_name( ".") ,"Expected '.' string to be in-valid" ); std::vector<std::string> invalid; invalid.emplace_back("?"); invalid.emplace_back("!"); invalid.emplace_back("\""); invalid.emplace_back("$"); invalid.emplace_back("%"); invalid.emplace_back("^"); invalid.emplace_back("*"); invalid.emplace_back("("); invalid.emplace_back(")"); invalid.emplace_back("-"); invalid.emplace_back("+"); invalid.emplace_back(":"); invalid.emplace_back(";"); invalid.emplace_back("@"); invalid.emplace_back("~"); invalid.emplace_back("<"); invalid.emplace_back(">"); invalid.emplace_back("!"); for(const auto & i : invalid) { std::string msg; BOOST_CHECK_MESSAGE( !Str::valid_name( i,msg ) ,"Expected " << i << " to be in-valid" ); BOOST_CHECK_MESSAGE( !Str::valid_name( i) ,"Expected " << i << " to be in-valid" ); std::string s = "a" + i; BOOST_CHECK_MESSAGE( !Str::valid_name( s,msg ) ,"Expected " << s << " to be in-valid" ); BOOST_CHECK_MESSAGE( !Str::valid_name( s ) ,"Expected " << s << " to be in-valid" ); } } BOOST_AUTO_TEST_SUITE_END()
0f5b9f0bfb0db77826099bdbdfb779ad1b9a382c
e9b59c72580f82e2ef735cb84b56afb55f59d4b4
/include/Reconstructor.h
9f4350d551e80f819788c52f9c9f98d6b0b5d41a
[ "MIT" ]
permissive
lty972100804/template-based-3d-reconstruction
5a8980e6333a8e54dbfda5d8dff8e75d11b9a068
4df604d9ad276358482d07d7547c275bfe86ae12
refs/heads/master
2023-03-18T08:13:05.867901
2017-07-06T09:59:08
2017-07-06T09:59:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,714
h
Reconstructor.h
/*********************************************************************/ /* */ /* BASED ON: */ /* Template-Based Monocular 3D Shape Recovery Using Laplacian Meshes */ /* */ /*********************************************************************/ #ifndef _RECONSTRUCTOR_H_ #define _RECONSTRUCTOR_H_ #include <iostream> #include <iomanip> #include <armadillo> #include <opencv2/core/core.hpp> #include <opencv2/features2d/features2d.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/opencv.hpp> #include <opencv2/xfeatures2d.hpp> #include <opencv2/calib3d.hpp> #include "../epfl/Mesh/LaplacianMesh.h" #include "../epfl/Linear/ObjectiveFunction.h" #include "../epfl/Linear/IneqConstrFunction.h" #include "../epfl/Linear/IneqConstrOptimize.h" #include "../epfl/Camera.h" #include "SimulatedAnnealing.h" class Reconstructor { private: // Path and file names std::string modelCamIntrFile; // Camera used for building the model std::string modelCamExtFile; std::string trigFile; std::string refImgFile; std::string imCornerFile; std::string ctrlPointsFile; arma::urowvec ctrPointIds; // Set of control points arma::urowvec ctrPointCompIds; // Set of control points Camera modelCamCamera, modelWorldCamera, modelFakeCamera; // Camera coordinates // Fake camera only for focal length optimization using simulated annealing alghoritm cv::Mat refImg, inputImg, img; // Reference image and input image arma::mat matchesAll, matchesInlier; arma::uvec inlierMatchIdxs, matchesInitIdxs; arma::mat bary3DRefKeypoints; std::vector<bool> existed3DRefKeypoints; // To indicate a feature points lies on the reference mesh. arma::mat Minit; // Correspondence matrix M given all initial matches: MX = 0 arma::mat MPinit; // Precomputed matrix MP in the term ||MPc|| + wr * ||APc|| // M, MP will be computed w.r.t input matches arma::mat MPwAP; // Matrix [MP; wr*AP]. Stored for later use in constrained reconstruction arma::mat APtAP; // Precomputed (AP)'*(AP): only need to be computed once arma::mat MPwAPtMPwAP; // Precomputed (MPwAP)' * MPwAP used in eigen value decomposition double wrInit; // Initial weight of deformation penalty term ||AX|| double wcInit; // Initial weight of deformation penalty term depending on focal length double radiusInit; // Initial radius of robust estimator int nUncstrIters; // Number of iterations for unconstrained reconstruction float timeSmoothAlpha; // Temporal consistency weight bool useTemporal; // Use temporal consistency or not bool usePrevFrameToInit; // Use the reconstruction in the previous frame to // initalize the constrained recontruction in the current frame static const double ROBUST_SCALE; // Each iteration of unconstrained reconstruction: decrease by this factor static const int DETECT_THRES; std::vector<cv::KeyPoint> kpModel, kpInput; IneqConstrOptimize ineqConstrOptimize; // Due to accumulation of ill-conditioned errors. int tempI, tempIterTO; bool isFocalAdjustment, isFocalRandom; arma::vec reprojErrors; private: void unconstrainedReconstruction(put::Algorithm &opt); void unconstrainedReconstruction(); void updateInternalMatrices(const double& focal); bool find3DPointOnMesh(const cv::Point2d& refPoint, arma::rowvec& intersectionPoint); arma::vec findIntersectionRayTriangle(const arma::vec& source, const arma::vec& destination, const arma::mat& vABC); void buildCorrespondenceMatrix( const arma::mat& matches ); void reconstructPlanarUnconstr(const arma::uvec& matchIdxs, double wr , LaplacianMesh &resMesh); void computeCurrentMatrices( const arma::uvec& matchIdxs, double wr ); arma::vec computeReprojectionErrors(const TriangleMesh& trigMesh, const arma::mat& matchesInit, const arma::uvec& currentMatchIdxs , bool useFakeCamera); void ReconstructIneqConstr(const arma::vec& cInit); const arma::mat& GetMPwAP() const { return this->MPwAP; } double adjustFocal(std::vector<double> params); void setupErrors(); public: LaplacianMesh *refMesh, resMesh; public: Reconstructor(); ~Reconstructor(); void init(cv::Mat &image); void prepareMatches(std::vector<cv::DMatch> &matches, std::vector<cv::KeyPoint> &kp1, std::vector<cv::KeyPoint> &kp2); void deform(); void savePointCloud(std::string fileName); void drawMesh(cv::Mat &inputImg, LaplacianMesh &mesh, std::string fileName); void SetNConstrainedIterations( int pNCstrIters) { this->ineqConstrOptimize.SetNIterations(pNCstrIters); } void SetTimeSmoothAlpha( int pTimeSmoothAlpha) { this->timeSmoothAlpha = pTimeSmoothAlpha; } void SetUseTemporal( bool useTemporal ) { this->useTemporal = useTemporal; } void SetUsePrevFrameToInit( bool usePrevFrameToInit ) { this->usePrevFrameToInit = usePrevFrameToInit; } void SetWrInit(double pWrInit) { this->wrInit = pWrInit; } // Set mu value for inequality reconstruction void SetMu(double mu) { this->ineqConstrOptimize.SetMuValue(mu); } friend class SimulatedAnnealing; }; #endif
6c7cfd0212960f4215ee795cc022d576bda1770c
973f62647c373222e3300cf6ca506f6877a10c9b
/nha_khong_ke_nhau.cpp
1bf392922a8b3ab847df12b237a7f0c07290a97c
[]
no_license
cudevconst/Cau_truc_du_lieu_giai_thuat
a55eb5ecf6cb88c4dc5c5a671590da285113b654
807f76b0df4dbedec40c993b3204eb904322495e
refs/heads/master
2023-06-24T01:26:25.499096
2021-07-12T15:25:48
2021-07-12T15:25:48
384,460,593
0
0
null
null
null
null
UTF-8
C++
false
false
638
cpp
nha_khong_ke_nhau.cpp
#include <bits/stdc++.h> #define ll long long; using namespace std; int res(int arr[], int n) { int check = arr[0]; int ok = 0; int ok1; for (int i = 1; i < n; i++) { if (check > ok) ok1 = check; else ok1 = ok; check = ok + arr[i]; ok = ok1; } if (check > ok) return check; return ok; } int main() { int t; cin >> t; while (t--) { int n, k; cin >> n; int a[n]; for (int i = 0; i < n; ++i) { cin >> a[i]; } cout << res(a, n) << endl; } return 0; }
1fe4afd0d9de2027c8e8773539d1aae3f841d104
9441518348b77e1b64e5418cc4a73d981a6daa84
/swapchain.h
7e309def018cb4cae026134b4013ff7ded0dc73c
[]
no_license
ChuangTseu/DogeVk
7ef4cce50a1e6067b0a49ebf066cd64849a6b60a
5707a6fb22cc745c07584ce056852e978cd77390
refs/heads/master
2021-05-04T09:48:58.684387
2016-11-25T23:25:20
2016-11-25T23:30:20
52,181,190
1
0
null
null
null
null
UTF-8
C++
false
false
969
h
swapchain.h
#pragma once #include "doge_vulkan.h" #include "custom_types.h" #include <vector> #include "physical_device.h" #include "device.h" #include "surface.h" struct SwapChain { void initializeSwapchain(u32 desiredNumberOfCustomSwapchainImages); void initializeSwapchainImageViews(); void Destroy(); u32 ImageCount() { return mSwapchainImageCount; } VkFormat Format() { return mVkSwapchainFormat; } VkColorSpaceKHR ColorSpace() { return mVkSwapchainColorSpace; } const std::vector<VkImage>& Images() { return maSwapImages; } const std::vector<VkImageView>& Views() { return maSwapViews; } VkSwapchainKHR VkHandle() { return mVkSwapchain; } VkSwapchainKHR* VkHandleAddress() { return &mVkSwapchain; } VkSwapchainKHR mVkSwapchain; VkFormat mVkSwapchainFormat; VkColorSpaceKHR mVkSwapchainColorSpace; u32 mSwapchainImageCount; std::vector<VkImage> maSwapImages; std::vector<VkImageView> maSwapViews; }; extern SwapChain gSwapChain;
da6b1d4c2dd7405be08fa041463da963938c3cdb
3c01e15337b8a1c8704feed470e6b1aa75ab6b39
/contest/407/a/63757302.cpp
59ebc163c99caff3e6d9a2f8b7040bacd1e572e6
[]
no_license
varunragu23/codeforces
4a901c6e88f14ba081c8873e7d03647a077b4f66
9a272ca4416fbf8f1478cd07a5eb8fc7f2e535fa
refs/heads/master
2020-09-03T04:42:30.094910
2019-11-04T00:57:12
2019-11-04T00:57:12
219,388,791
0
0
null
null
null
null
UTF-8
C++
false
false
1,367
cpp
63757302.cpp
#include <iostream> #include <iomanip> #include <cstdio> #include <set> #include <vector> #include <map> #include <cmath> #include <algorithm> #include <memory.h> #include <string> #include <cstring> #include <sstream> #include <cstdlib> #include <ctime> #include <cassert> using namespace std; int gcd(int a, int b) { while (a > 0 && b > 0) if (a > b) a %= b; else b %= a; return a + b; } void test(int xa, int ya, int xb, int yb) { if (xa == xb || ya == yb || xb == 0 || yb == 0) { return; } puts("YES"); printf("%d %d\n", 0, 0); printf("%d %d\n", xa, ya); printf("%d %d\n", xb, yb); exit(0); } int main() { int a, b; scanf("%d %d", &a, &b); for (int x = 1; x <= a; x++) for (int y = 1; y <= a; y++) if (x * x + y * y == a * a) { int g = gcd(x, y); int dx = x / g, dy = y / g; int u = dx * dx + dy * dy; int v = b * b; if (v % u != 0) { continue; } if (v % u == 0) { int ratio = v / u; int k = (int)sqrt(1.0 * ratio); while (k * k < ratio) k++; while (k * k > ratio) k--; if (k * k == ratio) { test(x, y, -dy * k, dx * k); test(x, y, dy * k, -dx * k); } } } puts("NO"); return 0; }
aa83c2d2f13dee93ebf0b00647f39bf5c29212b3
31b9721d77a3fb8dd00a9b5415ee6bdb61743099
/Map.cpp
46afef4fe66bc1a54d85e116a418ca68b02977d5
[]
no_license
razvanch/tetris
ceb54dd6a57902ab79e42789fedf5f828eec5184
732c4597e24bbdb2cf8d8657a5eb5799d735c46a
refs/heads/master
2021-01-18T19:00:42.575656
2015-05-01T16:53:34
2015-05-01T16:53:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,197
cpp
Map.cpp
#include "Map.h" #include <iostream> #include <time.h> // A passive tetris arena Map::Map(const int &hght, const int &wdth) { score = 0; height = hght; width = wdth; // Each map has a starting width, but also must be extendable to double // this initial value maxWidth = 2 * wdth; tiles = new int*[height]; for(int i = 0; i < height; ++i) { tiles[i] = new int[maxWidth]; for(int j = 0; j < maxWidth; ++j) tiles[i][j] = EMPTY; } initializeShapes(); // The new shapes are generated based on pseudo-random numbers srand(time(NULL)); nextObject = MapObject(shapes[rand() % NUMBER_OF_SHAPES], height); isFull = 0; } Map::~Map() { for(int i = 0; i < height; ++i) delete[] tiles[i]; delete[] tiles; } // Increase width by shifting elements to the right void Map::increaseWidth(bool isEndOfCycle = 1) { ++width; shiftRightOverColumn(width - 1); } // Decrease width by shifting elements to the left void Map::decreaseWidth(bool isEndOfCycle = 1) { clearCurrentObject(); --width; shiftLeftOverColumn(0); moveForward(); } // Defines the shapes that a map can use // I chose not to store all the possible states of a shape, because // implementing a rotation matrix would be difficult on certain shapes (for // example the square, which has no center Tile) void Map::initializeShapes() { // Square Point relations0[MAX_NUMBER_OF_STATES][MAX_NUMBER_OF_TILES] = {{{0, 1}, {1, 1}, {1, 0}}}; shapes[0] = Shape(4, 1, YELLOW, relations0); // Z Point relations1[MAX_NUMBER_OF_STATES][MAX_NUMBER_OF_TILES] = {{{0, 1}, {1, 0}, {1, -1}}, {{-1, 0}, {0, 1}, {1, 1}}, {{0, -1}, {-1, 0}, {-1, 1}}, {{-1, -1}, {0, -1}, {1, 0}}}; shapes[1] = Shape(4, 4, RED, relations1); // Mirror Z Point relations2[MAX_NUMBER_OF_STATES][MAX_NUMBER_OF_TILES] = {{{0, -1}, {1, 0}, {1, 1}}, {{-1, 1}, {0, 1}, {1, 0}}, {{-1, -1}, {-1, 0}, {0, 1}}, {{-1, 0}, {0, -1}, {1, -1}}}; shapes[2] = Shape(4, 4, GREEN, relations2); // L Point relations3[MAX_NUMBER_OF_STATES][MAX_NUMBER_OF_TILES] = {{{0, -1}, {0, -2}, {1, 0}}, {{1, 0}, {2, 0}, {0, 1}}, {{0, 1}, {0, 2}, {-1, 0}}, {{-1, 0}, {-2, 0}, {0, -1}}}; shapes[3] = Shape(4, 4, ORANGE, relations3); // Mirror L Point relations4[MAX_NUMBER_OF_STATES][MAX_NUMBER_OF_TILES] = {{{1, 0}, {0, 1}, {0, 2}}, {{0, 1}, {-1, 0}, {-2, 0}}, {{-1, 0}, {0, -1}, {0, -2}}, {{0, -1}, {1, 0}, {2, 0}}}; shapes[4] = Shape(4, 4, BLUE, relations4); // T Point relations5[MAX_NUMBER_OF_STATES][MAX_NUMBER_OF_TILES] = {{{0, -1}, {1, 0}, {0, 1}}, {{1, 0}, {0, 1}, {-1, 0}}, {{0, 1}, {-1, 0}, {0, -1}}, {{-1, 0}, {0, -1}, {1, 0}}}; shapes[5] = Shape(4, 4, PURPLE, relations5); // Bar Point relations6[MAX_NUMBER_OF_STATES][MAX_NUMBER_OF_TILES] = {{{0, -1}, {0, 1}, {0, 2}}, {{-1, 0}, {1, 0}, {2, 0}}}; shapes[6] = Shape(4, 2, CYAN, relations6); } // Tests to see if a column is empty bool Map::columnIsEmpty(const int &index) { for(int i = 0; i < height; ++i) if(tiles[i][index] != EMPTY) { return false; } return true; } // Tests to see if a column is full, so it can be emptied bool Map::columnIsFull(const int &index) { for(int i = 0; i < height; ++i) if(tiles[i][index] == EMPTY) return false; return true; } // Shifts matrix to the right, over the column "index" void Map::shiftRightOverColumn(const int &index) { for(int i = index; i >= 0; --i) { for(int j = 0; j < height; ++j) tiles[j][i] = tiles[j][i - 1]; } } // Shifts matrix to the left, over the column "index" void Map::shiftLeftOverColumn(const int &index) { for(int i = index; i <= width ; ++i) { for(int j = 0; j < height; ++j) tiles[j][i] = tiles[j][i + 1]; } } // Tests if the active object can be drawn into the tile matrix, and draws it // if possible bool Map::drawCurrentObject() { for(int i = 0; i < currentObject.size; ++i) { if(tiles[currentObject.coordinates[i].y][currentObject.coordinates[i].x] != EMPTY) { return false; } } for(int i = 0; i < currentObject.size; ++i) tiles[currentObject.coordinates[i].y][currentObject.coordinates[i].x] = currentObject.color; return true; } // Clears the current object from the tile matrix void Map::clearCurrentObject() { for(int i = 0; i < currentObject.size; ++i) tiles[currentObject.coordinates[i].y][currentObject.coordinates[i].x] = EMPTY; } // Checks whether a cycle has ended or not bool Map::cycleIsOver() { int max_x[50]; for(int i = 0; i < height; ++i) max_x[i] = 0; for(int i = 0; i < currentObject.size; ++i) { // Check if the current object is at the end of the arena if(currentObject.coordinates[i].x == width - 1) { return true; } // Find the furthest tile(s) width-wise if(currentObject.coordinates[i].x > max_x[currentObject.coordinates[i].y]) max_x[currentObject.coordinates[i].y] = currentObject.coordinates[i].x; } // Check if there is room for one more movement for(int i = 0; i < height; ++i) if(tiles[i][max_x[i] + 1] != EMPTY) { return true; } return false; } // Starts a new cycle (gives a new active shape) void Map::startNextCycle() { for(int i = width - 1; i >= 0; --i) if(columnIsEmpty(i)) { break; } else while(columnIsFull(i)) { ++score; shiftRightOverColumn(i); increaseWidth(); } currentObject = nextObject; nextObject = MapObject(shapes[rand() % NUMBER_OF_SHAPES], height); isFull = !drawCurrentObject(); } // Move the active shape forward // If the move ends the cycle, start a new one void Map::moveForward() { // std::cout << "WOOP" << '\n'; clearCurrentObject(); currentObject.moveForward(width); drawCurrentObject(); if(cycleIsOver()) { startNextCycle(); } } // Rotate the current shape, if possible void Map::rotate() { MapObject previousObject = currentObject; clearCurrentObject(); if(currentObject.rotateClockwise(height, width)) if(!drawCurrentObject()) { currentObject = previousObject; drawCurrentObject(); } else { // All good } else { drawCurrentObject(); } } // Move the current shape up, if possible void Map::moveUp() { clearCurrentObject(); if(currentObject.moveUp(height)) { if(!drawCurrentObject()) { currentObject.moveDown(height); drawCurrentObject(); } } else { drawCurrentObject(); } } // Move the current shape down, if possible void Map::moveDown() { clearCurrentObject(); if(currentObject.moveDown(height)) { if(!drawCurrentObject()) { currentObject.moveUp(height); drawCurrentObject(); } } else { drawCurrentObject(); } }
77f14268d00c1aa02c03d40fdb04fbd382c35644
7aee2215a936bf30bfb9fb6f7d928768ec3cf1a2
/_old/deprecated/sound_device/sound_device.cc
e2c3226b3d43ac0bdaea6cf859407aa92411cede
[]
no_license
SJMdev/mallib
8d1563d5f9b289868417019dd123a3728ce3e38c
b13933131fa8b99245b775f378fd0d6db7e01ae0
refs/heads/master
2022-09-06T14:26:47.451936
2022-08-28T13:47:47
2022-08-28T13:47:47
190,599,950
2
0
null
null
null
null
UTF-8
C++
false
false
3,280
cc
sound_device.cc
#include "sound_device.h" #ifdef __APPLE__ #include <OpenAL/al.h> #include <OpenAL/alc.h> #elif __linux #include <AL/al.h> #include <AL/alc.h> #endif #include <iostream> #include <string> #include <fstream> #include "../file_handler/file_handler.h" #include <algorithm> using std::cin; using std::cout; using std::cerr; using std::fstream; using std::string; ////////////////////////////////////////////// Sound_Device::Sound_Device() { m_device = alcOpenDevice(nullptr); if (m_device) { m_context = alcCreateContext(m_device, nullptr); alcMakeContextCurrent(m_context); } //@Move: separate the data here. m_num_buffers = 32; m_buffers.reserve(m_num_buffers); m_buffers_occupied.assign(m_num_buffers, 0); alGenBuffers(m_num_buffers, m_buffers.data()); if ((m_error = alGetError()) != AL_NO_ERROR) { printf("alGenBuffers error"); alDeleteBuffers(m_num_buffers, m_buffers.data()); exit(1); } //@Incomplete: this is 32 sound sources. m_num_sound_sources = 32; m_sound_sources.reserve(m_num_sound_sources); m_sound_sources_occupied.assign(m_num_sound_sources, 0); alGenSources(m_num_sound_sources, m_sound_sources.data()); if ((m_error = alGetError()) != AL_NO_ERROR) { printf("alGenSources error"); alDeleteSources(m_num_sound_sources, m_sound_sources.data()); exit(1); } // bind buffers to sound sources. } ////////////////////////////////////////////// Sound_Device::~Sound_Device() { alDeleteSources(m_num_sound_sources, m_sound_sources.data()); alDeleteBuffers(m_num_buffers, m_buffers.data()); alcDestroyContext(m_context); alcCloseDevice(m_device); } ////////////////////////////////////////////// uint32_t Sound_Device::data_to_buffer(const Wav_File& wav_file) // returns source { ALuint buffer_ID = get_free_buffer(); alBufferData(buffer_ID, wav_file.format, wav_file.data[0].data(), wav_file.data[0].size(), wav_file.header.samples_per_sec); if ((m_error = alGetError()) != AL_NO_ERROR) { if (m_error == AL_INVALID_VALUE) cerr << "albufferData error: invalid value." << '\n'; } return buffer_ID; } ////////////////////////////////////////////// uint32_t Sound_Device::buffer_to_source(const uint32_t buffer) { ALuint source_ID = get_free_source(); cerr << "source ID: " << source_ID; alSourcei(source_ID, AL_BUFFER, buffer); return source_ID; } ////////////////////////////////////////////// ALuint Sound_Device::get_free_buffer() { auto result = std::find(m_buffers_occupied.begin(), m_buffers_occupied.end(), 0); size_t idx = std::distance(m_buffers_occupied.begin(), result); //@Leak: result can be end. m_buffers_occupied[idx] = 1; // true? return m_buffers[idx]; } ////////////////////////////////////////////// ALuint Sound_Device::get_free_source() { auto result = std::find(m_sound_sources_occupied.begin(), m_sound_sources_occupied.end(), 0); size_t idx = std::distance(m_sound_sources_occupied.begin(), result); //@Leak: result can be end. m_sound_sources_occupied[idx] = 1; // true? return m_sound_sources[idx]; } ////////////////////////////////////////////// void Sound_Device::play_sound(const uint32_t sound_source) { alSourcePlay(sound_source); } ////////////////////////////////////////////// void Sound_Device::play_music(const char* filename) { }
3efe253c99720c566f7848c31dc2fe63c0ff15cb
091afb7001e86146209397ea362da70ffd63a916
/inst/include/nt2/core/include/functions/cdiff.hpp
7873041b22ef2d6b88f395f3d17409f1ea6b64e0
[]
no_license
RcppCore/RcppNT2
f156b58c08863243f259d1e609c9a7a8cf669990
cd7e548daa2d679b6ccebe19744b9a36f1e9139c
refs/heads/master
2021-01-10T16:15:16.861239
2016-02-02T22:18:25
2016-02-02T22:18:25
50,460,545
15
1
null
2019-11-15T22:08:50
2016-01-26T21:29:34
C++
UTF-8
C++
false
false
296
hpp
cdiff.hpp
#ifndef NT2_CORE_INCLUDE_FUNCTIONS_CDIFF_HPP_INCLUDED #define NT2_CORE_INCLUDE_FUNCTIONS_CDIFF_HPP_INCLUDED #include <nt2/core/functions/cdiff.hpp> #include <nt2/core/functions/common/cdiff.hpp> #include <nt2/core/functions/expr/cdiff.hpp> #include <nt2/core/functions/scalar/cdiff.hpp> #endif
cf609b6d8d5f5ad4d5065b19ebab34389342d2f1
990cf3d5cefa814d8c75f9c25a72fc71baa1d776
/Project4/ices_algs.hpp
419b676092e95ddfe416be481269735c86c3d03f
[ "MIT" ]
permissive
jrubix/Algorithms335
9b14d1601a7445a8f156be5ecc0feb5266af3402
d2c8d7f791007015f8aff05e53793896fde75b3f
refs/heads/master
2022-08-14T19:30:34.585767
2020-05-18T05:10:50
2020-05-18T05:10:50
256,338,338
0
0
null
null
null
null
UTF-8
C++
false
false
2,776
hpp
ices_algs.hpp
/////////////////////////////////////////////////////////////////////////////// // crossing_algs.hpp // // Algorithms that solve the iceberg avoiding problem. // // All of the TODO sections for this project reside in this file. // // This file builds on ices_types.hpp, so you should familiarize yourself // with that file before working on this file. // /////////////////////////////////////////////////////////////////////////////// #pragma once #include <cassert> #include <iostream> #include "ices_types.hpp" namespace ices { // Solve the iceberg avoiding problem for the given grid, using an exhaustive // optimization algorithm. // // This algorithm is expected to run in exponential time, so the grid's // width+height must be small enough to fit in a 64-bit int; this is enforced // with an assertion. // // The grid must be non-empty. unsigned int iceberg_avoiding_exhaustive(const grid& setting) { // grid must be non-empty. assert(setting.rows() > 0); assert(setting.columns() > 0); // Compute the path length, and check that it is legal. const size_t steps = setting.rows() + setting.columns() - 2; assert(steps < 64); unsigned int counter = 0; bool valid = true; for (unsigned int bits = 0; bits <= pow(2, steps)-1; bits++){ path candidate(setting); for(unsigned int k = 0; k <= steps -1; k++){ int bit = (bits >> k) & 1; step_direction s1; if(bit == 1){ s1 = STEP_DIRECTION_RIGHT; } else { s1 = STEP_DIRECTION_DOWN; } if (candidate.is_step_valid(s1)){ candidate.add_step(s1); valid = true; } else { valid = false; break; } } if (valid == true){ counter++; } } return counter; } // Solve the iceberg avoiding problem for the given grid, using a dynamic // programming algorithm. // // The grid must be non-empty. unsigned int iceberg_avoiding_dyn_prog(const grid& setting) { // grid must be non-empty. assert(setting.rows() > 0); assert(setting.columns() > 0); const int DIM=100; std::vector<std::vector<unsigned>> A(DIM, std::vector<unsigned>(DIM)); A[0][0] = 1; unsigned int from_above, from_left; for(unsigned int i = 0; i <= setting.rows() -1; i++){ for(unsigned int j = 0; j<= setting.columns()-1; j++){ if (i==0 && j==0) continue; if (setting.get(i, j) == CELL_ICEBERG){ A[i][j] = 0; continue; } from_left = from_above = 0; if (i > 0 && A[i-1][j]){ from_above = A[i-1][j]; } if (j > 0 && A[i][j-1]){ from_left = A[i][j-1]; } A[i][j] = from_above + from_left; } } return A[setting.rows()-1][setting.columns()-1]; } }
2cfebdba7613db5abbc738bcdc718be1a137f9ae
883e5d18c0486691ef437cfc9f2e9ee168d83343
/DirectDragon/Ex04_Color.cpp
2c6d23c08ad02f1cf3ad1e8dfae912c2b88d92e8
[]
no_license
nevermores88/Direct3D_temp
18521ef24c0c3e68ac6102d37850d3ec7d73b53c
ab72d4aa066ebf37b0eb34d65c5bf605734e8bbc
refs/heads/master
2021-09-08T21:24:21.149241
2018-03-12T09:34:13
2018-03-12T09:34:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,471
cpp
Ex04_Color.cpp
#include "stdafx.h" #include "Ex04_Color.h" CEx04_Color::CEx04_Color() { } CEx04_Color::~CEx04_Color() { } void CEx04_Color::Create(LPDIRECT3DDEVICE9 pdev, DWORD dwExType) { m_dwExType = dwExType; m_pdev = pdev; memset(m_WorldMat, 0, sizeof(m_WorldMat)); VB = NULL; m_pdev->CreateVertexBuffer(3 * sizeof(ColorVertex), D3DUSAGE_WRITEONLY, ColorVertex::FVF, D3DPOOL_MANAGED, &VB, 0); ColorVertex* v; VB->Lock(0, 0, (void**)&v, 0); v[0] = ColorVertex(-1.0f, 0.0f, 2.0f, D3DCOLOR_XRGB(255, 0, 0)); v[1] = ColorVertex(0.0f, 1.0f, 2.0f, D3DCOLOR_XRGB(0, 255, 0)); v[2] = ColorVertex(1.0f, 0.0f, 2.0f, D3DCOLOR_XRGB(0, 0, 255)); VB->Unlock(); } void CEx04_Color::Release() { m_pdev = NULL; memset(m_WorldMat, 0, sizeof(m_WorldMat)); VB->Release(); } void CEx04_Color::OnRender() { if (m_pdev) { m_pdev->SetRenderState(D3DRS_LIGHTING, FALSE); m_pdev->SetFVF(ColorVertex::FVF); m_pdev->SetStreamSource(0, VB, 0, sizeof(ColorVertex)); D3DXMatrixTranslation(&m_WorldMat, -1.25f, 0.0f, -2.0f); m_pdev->SetTransform(D3DTS_WORLD, &m_WorldMat); m_pdev->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_FLAT); m_pdev->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1); D3DXMatrixTranslation(&m_WorldMat, -1.f, 0.0f, 0.0f); m_pdev->SetTransform(D3DTS_WORLD, &m_WorldMat); m_pdev->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD); m_pdev->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1); } } void CEx04_Color::OnUpdate() { if (m_pdev) { } }
fa19d4ca2d8d66f87b47ebc941d8a7838af20a04
16c0e930d5df96886bc9f9915d8923f10db410e6
/ReportSystem/DAL/src/Entities/DTeamReport.cpp
8ad74ffdf6ca7c561b3170d4e09e9cf8eae0cce8
[]
no_license
Rassska/OOP
fbacc6e3022aed44dfef826426d89dd722408d89
2d3f76258c246e0f318a590795d51d2131e211cc
refs/heads/main
2023-03-27T14:27:15.967857
2021-03-21T13:49:46
2021-03-21T13:49:46
306,287,323
0
0
null
null
null
null
UTF-8
C++
false
false
1,475
cpp
DTeamReport.cpp
#include "DAL/src/Entities/DTeamReport.h" #include <iostream> #include <string> #include <vector> #include "DAL/src/Entities/DReport.h" DTeamReport::DTeamReport(std::string_view name, std::string_view description, std::vector <DTeamReport> reports) { m_Name = name; m_Description = description; m_ReportsList = reports; } DTeamReport::~DTeamReport() = default; void DTeamReport::setTeamReportID(std::size_t teamReportID) {m_TeamReportID = teamReportID;} void DTeamReport::setCreatedTime(time_t currCreatedTime) {m_CreatedTime = currCreatedTime;} void DTeamReport::setDescription(std::string_view currDescription) {m_Description = currDescription;} void DTeamReport::setName(std::string_view currName) {m_Name = currName;} void DTeamReport::setReportList(std::vector<DTeamReport> currReportList) {m_ReportsList = currReportList;} std::size_t DTeamReport::getTeamReportID() const {return m_TeamReportID;} time_t DTeamReport::getCreatedTime() const {return m_CreatedTime;} std::string_view DTeamReport::getDescription() const {return m_Description;} std::string_view DTeamReport::getName() const {return m_Name;} std::vector<DTeamReport> DTeamReport::getReportList() const {return m_ReportsList;} DTeamReport* DTeamReport::operator=(const DTeamReport* other) { m_ReportsList = other->m_ReportsList; m_TeamReportID = other->m_TeamReportID; m_CreatedTime = other->m_CreatedTime; m_Name = other->m_Name; m_Description = other->m_Description; }
e96f2daff6cd7d7f326a5b1e394ddea452ca643d
3a187a7c3562714eba8c2b96dd2fe980e7003e0b
/client/view/SkeletonAnimation.cpp
7a17f782f23c6bd4dcc34ab428052128b402ade9
[]
no_license
tomasnocetti/taller-trabajo-final
08ccdfc0d6a398cfbfd525174a65520b7c69816d
366c3089e010418dbae190405172336edab15298
refs/heads/master
2022-11-26T20:19:38.789010
2020-08-03T16:33:32
2020-08-03T16:33:32
268,593,609
0
1
null
null
null
null
UTF-8
C++
false
false
1,431
cpp
SkeletonAnimation.cpp
#include "SkeletonAnimation.h" SkeletonAnimation::SkeletonAnimation(LTexture* texture) : Animation(texture) { forwardFrames = 5; backwardFrames = 5; leftFrames = 5; rightFrames = 5; index = 0; cropAnimationFrames(); } void SkeletonAnimation::cropAnimationFrames() { SDL_Rect frame = {0, 0, 25, 47}; forwardAnim.push_back(frame); frame = {29, 0, 21, 47}; forwardAnim.push_back(frame); frame = {54, 0, 19, 47}; forwardAnim.push_back(frame); frame = {80, 0, 20, 47}; forwardAnim.push_back(frame); frame = {105, 0, 16, 47}; forwardAnim.push_back(frame); frame = {0, 49, 21, 45}; backwardAnim.push_back(frame); frame = {27, 51, 19, 43}; backwardAnim.push_back(frame); frame = {52, 49, 22, 45}; backwardAnim.push_back(frame); frame = {76, 51, 19, 43}; backwardAnim.push_back(frame); frame = {104, 51, 17, 43}; backwardAnim.push_back(frame); frame = {0, 96, 20, 45}; rightAnim.push_back(frame); frame = {31, 98, 14, 43}; rightAnim.push_back(frame); frame = {54, 96, 22, 45}; rightAnim.push_back(frame); frame = {80, 98, 15, 43}; rightAnim.push_back(frame); frame = {104, 97, 14, 44}; rightAnim.push_back(frame); frame = {0, 143, 20, 45}; leftAnim.push_back(frame); frame = {32, 145, 14, 43}; leftAnim.push_back(frame); frame = {55, 144, 17, 44}; leftAnim.push_back(frame); frame = {80, 144, 14, 44}; leftAnim.push_back(frame); frame = {103, 143, 16, 45}; leftAnim.push_back(frame); }
7f6eda924704da7f36862b0f7b570f57adc9cd53
a337de9e586a3db00198ed2bd19b69098c363923
/geo_vector.h
850946b7ed2897e012ff4cfb6d82f8f774aef82d
[ "MIT" ]
permissive
MGauravSaini/Geometric-vector-class
81b59c72be00ea4e5145bcd08ce2e406f0f75fd6
6cd716bf448c0a0184a6a971cccdb96644bf0a49
refs/heads/master
2020-05-05T13:15:03.984406
2019-10-17T07:10:24
2019-10-17T07:10:24
180,068,597
6
1
MIT
2019-10-17T07:10:25
2019-04-08T04:17:25
C++
UTF-8
C++
false
false
14,820
h
geo_vector.h
#ifndef _GEO_VECTOR_ #define _GEO_VECTOR_ #include <iostream> #include <boost/units/quantity.hpp> #include <boost/units/systems/si/io.hpp> #include <boost/geometry.hpp> using namespace boost::units; using namespace boost::units::si; using namespace boost::geometry::model; using namespace boost::geometry::cs; namespace bg = boost::geometry; /* * Below change_dimension() is a temporary template function * it is used to make quantities dimensionless from dimension and vice versa * this fuction is needed because some fuction from boost::geometry * are not able to resolve the dimensions of quantities example in cross product */ template<typename change_to,typename current_dim> point<quantity<change_to> , 3 ,cartesian> change_dimension(const point<quantity<current_dim> , 3 ,cartesian> &input_point); template <typename quant_type> class geo_vector { private: typedef point<quantity <quant_type>, 3, cartesian> Point3D; Point3D p; //This class create a position vector of this point void set_abscissa(const quantity <quant_type> &init_abscissa); //Function to initialise the abscissa of point void set_ordinate(const quantity <quant_type> &init_ordinate); //Similaraly for y coordinate void set_applicate(const quantity <quant_type> &init_applicate); //for z coordinate public: quantity <quant_type> get_abscissa() const; // This function returns the abscissa of point quantity <quant_type> get_ordinate() const; // Returns y coordinate quantity <quant_type> get_applicate() const; //Return z coordinate //======================= Constructor section ================ geo_vector(); //Default constructor create a zero vector object geo_vector(const geo_vector<quant_type> &init_v); //Copy constructor geo_vector(Point3D m_point); //Constructor if a object of point type is passed geo_vector(Point3D initial_point,Point3D terminal_point);//Constructing a vector if two points are passed //================= Member function section ============================= quantity <quant_type> magnitude(); //Returns the magnitude of calling vector void normalize(); //Normalize(changed to unit vector) the calling vector void reset_magnitude(quantity <quant_type> new_mag); //Change the magnitude of calling vector to passed magnitude //Return the quantity getting by dot product of two passed vector /*template argument 1. type of quantity that a particular dot product is return e.g energy 2. type of quantity that calling vector have e.g force 3. type of quantity that passed vector have e.g quant_type Example call:- work = push.dot_prod_with<energy,force,quant_type>(displacement); */ template<typename quant_rtn_type, typename a_unit,typename b_unit> quantity <quant_rtn_type> dot_prod_with(const geo_vector<b_unit> &b); //Return vector getting by cross product of two passed vector geo_vector<quant_type> cross_prod_with(const geo_vector<quant_type> &b); //======================= Angle Handling subsection ======================= /* Coming soon */ //==================== Operators overloading section =================== geo_vector<quant_type> operator+(const geo_vector<quant_type> &a) const; geo_vector<quant_type> operator-(const geo_vector<quant_type> &a) const; //For product of a vector with a scalar e.g (v*5) geo_vector<quant_type> operator*(const double &scalar) const; //For divide a vector by a scalar e.g (v/5) geo_vector<quant_type> operator/(const double &scalar) const; void operator=(const geo_vector<quant_type> &a); void operator+=(const geo_vector<quant_type> &a); void operator-=(const geo_vector<quant_type> &a); bool operator==(const geo_vector<quant_type>& v) const; }; //overloading << operator for geo_vector template<typename quant_type> std::ostream &operator <<(std::ostream &os,geo_vector<quant_type> v); //Definations template<typename change_to,typename current_dim> point<quantity<change_to> , 3 ,cartesian> change_dimension(const point<quantity<current_dim> , 3 ,cartesian> &input_point) { current_dim C; change_to X; quantity<current_dim> x = bg::get<0>(input_point); quantity<current_dim> y = bg::get<1>(input_point); quantity<current_dim> z = bg::get<2>(input_point); point<quantity<change_to> , 3 ,cartesian> A( ((x / C)*X) , ((y / C)*X) , ((z / C)*X) ); return A; } //Function to initialise the abscissa of point i.e x coordinate template <typename quant_type> void geo_vector<quant_type>::set_abscissa(const quantity <quant_type> &init_abscissa) { bg::set<0>(p, init_abscissa); } template <typename quant_type> void geo_vector<quant_type>::set_ordinate(const quantity <quant_type> &init_ordinate) { bg::set<1>(p, init_ordinate); } template <typename quant_type> void geo_vector<quant_type>::set_applicate(const quantity <quant_type> &init_applicate) { bg::set<2>(p, init_applicate); } // This function returns the abscissa(x coordinate) of point template <typename quant_type> quantity <quant_type> geo_vector<quant_type>::get_abscissa() const { return ( bg::get<0>(p) ); } template <typename quant_type> quantity <quant_type> geo_vector<quant_type>::get_ordinate() const { return ( bg::get<1>(p) ); } template <typename quant_type> quantity <quant_type> geo_vector<quant_type>::get_applicate() const { return ( bg::get<2>(p) ); } //======================= Constructor section ================ //Default constructor create a zero vector object template <typename quant_type> geo_vector<quant_type>::geo_vector() { quant_type q_unit; set_abscissa(0 * q_unit); set_ordinate(0 * q_unit); set_applicate(0 * q_unit); } //Copy constructor template <typename quant_type> geo_vector<quant_type>::geo_vector(const geo_vector<quant_type> &init_v) { set_abscissa(init_v.get_abscissa()); set_ordinate(init_v.get_ordinate()); set_applicate(init_v.get_applicate()); } //Constructor if an object of point type is passed template <typename quant_type> geo_vector<quant_type>::geo_vector(Point3D m_point) { set_abscissa(bg::get<0>(m_point)); set_ordinate(bg::get<1>(m_point)); set_applicate(bg::get<2>(m_point)); } //Constructing a vector if two points are given template <typename quant_type> geo_vector<quant_type>::geo_vector(Point3D initial_point,Point3D terminal_point) { set_abscissa(bg::get<0>(terminal_point) - bg::get<0>(initial_point)); set_ordinate(bg::get<1>(terminal_point) - bg::get<1>(initial_point)); set_applicate(bg::get<2>(terminal_point) - bg::get<2>(initial_point)); } //================= Member function section ======================== //Returns the magnitude of calling vector template <typename quant_type> quantity<quant_type> geo_vector<quant_type>::magnitude() { quant_type q_unit; dimensionless d; Point3D X(get_abscissa(),get_ordinate(),get_applicate()); //getting points from vector typedef point<quantity<dimensionless> , 3 ,cartesian> unitless_point; unitless_point origin(0 * d,0 * d,0 * d); //create a dimensionless origin point /* * Since the distance function from boost::geometry is not able to resolve units * we have to make quantities dimensionless before passing to the function * because length*length = area <== boost::geometery.distace() not able to resolve * dimensionless*dimensionless = dimensionless <== boost::geometery.distance() * returns dimensionless quantity which we further rechange to our original dimension */ unitless_point P = change_dimension<dimensionless,quant_type>(X); quantity<dimensionless> D = bg::distance<unitless_point,unitless_point>(origin,P); return (D*q_unit); //multiplying to get our unit back /* An alternate way is to use root() and pow() functions from boost.units.cmath * * return ( root<2> ( pow<2>(get_abscissa()) + pow<2>(get_ordinate()) + pow<2>(get_applicate()) ) ); * */ } template <typename quant_type> void geo_vector<quant_type>::normalize() { quantity <quant_type> l = magnitude(); quant_type q_unit; if(l != 0 * q_unit) { //Dividing by l make coordinate dimensionless //To change them again to original unit I multiply with q_unit set_abscissa((get_abscissa() / l) * q_unit); set_ordinate((get_ordinate() / l) * q_unit); set_applicate((get_applicate() / l) * q_unit); } } //Change the magnitude of calling vector to passed magnitude template <typename quant_type> void geo_vector<quant_type>::reset_magnitude(quantity <quant_type> new_mag) { quantity <quant_type> l = magnitude(); quant_type q_unit; if(l == 0*q_unit) { set_abscissa(new_mag); set_ordinate(new_mag); set_applicate(new_mag); } else { set_abscissa ((get_abscissa() / l) * new_mag); set_ordinate ((get_ordinate() / l) * new_mag); set_applicate ((get_applicate() / l) * new_mag); } } //Dot product of two vectors //Example call: quantity<energy> work = push.dot_prod_with<energy,force,length>(displacement); template <typename quant_type> template<typename quant_rtn_type, typename a_unit,typename b_unit> quantity <quant_rtn_type> geo_vector<quant_type>::dot_prod_with(const geo_vector<b_unit> &b) { typedef point<quantity<a_unit>,3,cartesian> Apoint; typedef point<quantity<b_unit>,3,cartesian> Bpoint; Apoint A(get_abscissa(),get_ordinate(),get_applicate()); Bpoint B(b.get_abscissa(),b.get_ordinate(),b.get_applicate()); typedef point<quantity<dimensionless>,3,cartesian> unitless_point; /* * Again we have to make quanities dimensionless to use boost::geometry::dot_product(); */ unitless_point X = change_dimension<dimensionless,a_unit>(A); unitless_point Y = change_dimension<dimensionless,b_unit>(B); quantity<dimensionless> D = bg::dot_product<unitless_point,unitless_point>(X,Y); //changing to original dimension quant_rtn_type qrt; return (D*qrt); } //cross product of two vectors //Example call: geo_vector<force> Resultant = Force1.cross_prod_with(Force2); template <typename quant_type> geo_vector<quant_type> geo_vector<quant_type>::cross_prod_with(const geo_vector<quant_type> &b) { Point3D X(get_abscissa(),get_ordinate(),get_applicate()); Point3D Y(b.get_abscissa(),b.get_ordinate(),b.get_applicate()); typedef point<quantity<dimensionless> ,3, cartesian> unitless_point; //Making quantities dimensionless unitless_point A = change_dimension<dimensionless,quant_type>(X); unitless_point B = change_dimension<dimensionless,quant_type>(Y); //Storing returning point in a dimensionless point c; unitless_point c = bg::cross_product<unitless_point,unitless_point,unitless_point>(A,B); //creating point C by changing dimension of c to original Point3D C = change_dimension<quant_type,dimensionless>(c); geo_vector<quant_type> result(C); //using geo_vector constructure return result; } //======================= Angle Handling subsection ======================= /* Coming soon */ //=================== Operator section section ========================== template <typename quant_type> geo_vector<quant_type> geo_vector<quant_type>::operator+(const geo_vector<quant_type> &a) const { Point3D P(get_abscissa(),get_ordinate(),get_applicate()); Point3D Q(a.get_abscissa(),a.get_ordinate(),a.get_applicate()); /* boost::geometry::add_point() does not erase dimension conflict * because length+length = length * so we can call add_point without modifying dimensions */ bg::add_point<Point3D,Point3D>(P,Q); //add_point changes P point geo_vector<quant_type> result(P); return result; /* *An alternate procedure is commented below in two lines of code. *i.e without using boost::geometry::add_point() function * *result.set_abscissa( get_abscissa() + a.get_abscissa() ); *result.set_ordinate( get_ordinate() + a.get_ordinate() ); * */ } template <typename quant_type> geo_vector<quant_type> geo_vector<quant_type>::operator-(const geo_vector<quant_type> &a) const { Point3D P(get_abscissa(),get_ordinate(),get_applicate()); Point3D Q(a.get_abscissa(),a.get_ordinate(),a.get_applicate()); bg::subtract_point<Point3D,Point3D>(P,Q); geo_vector<quant_type> result(P); return result; /* * An alternate procedure is commented below in two lines of code. * i.e without using boost::geometry::subtract_point() function * *result.set_abscissa( get_abscissa() - a.get_abscissa() ); *result.set_ordinate( get_ordinate() - a.get_ordinate() ); * */ } //for product of a geo_vector with a scalar (f*5) template <typename quant_type> geo_vector<quant_type> geo_vector<quant_type>::operator*(const double &scalar) const { geo_vector<quant_type> result; result.set_abscissa( scalar * get_abscissa() ); result.set_ordinate( scalar * get_ordinate() ); result.set_applicate( scalar * get_applicate() ); return result; } //for divide of a geo_vector with scalar template <typename quant_type> geo_vector<quant_type> geo_vector<quant_type>::operator/(const double &scalar) const { if(scalar!=0) { geo_vector<quant_type> result; result.set_abscissa( get_abscissa() / scalar ); result.set_ordinate( get_ordinate() / scalar ); result.set_applicate( get_applicate() / scalar ); return result; } else return *this; } template <typename quant_type> void geo_vector<quant_type>::operator=(const geo_vector<quant_type> &a) { set_abscissa(a.get_abscissa()); set_ordinate(a.get_ordinate()); set_applicate(a.get_applicate()); } template <typename quant_type> void geo_vector<quant_type>::operator+=(const geo_vector<quant_type> &a) { set_abscissa( get_abscissa() + a.get_abscissa() ); set_ordinate( get_ordinate() + a.get_ordinate() ); set_applicate( get_applicate() + a.get_applicate() ); } template <typename quant_type> void geo_vector<quant_type>::operator-=(const geo_vector<quant_type> &a) { set_abscissa( get_abscissa() - a.get_abscissa() ); set_ordinate( get_ordinate() - a.get_ordinate() ); set_applicate( get_applicate() - a.get_applicate() ); } template <typename quant_type> bool geo_vector<quant_type>::operator==(const geo_vector<quant_type>& v) const { return ( get_abscissa() == v.get_abscissa() && get_ordinate() == v.get_ordinate() && get_applicate() == v.get_applicate() ); } template<typename quant_type> std::ostream &operator <<(std::ostream &os,geo_vector<quant_type> v) { os<<"("<<v.get_abscissa()<<")i + ("<<v.get_ordinate()<<")j + ("<<v.get_applicate()<<")k"; return os; } #endif
397db56e2737be0d806ad8272e2b6082de647910
4bae230b4972d71ed3e041ef7c6b6d5084074d63
/dsa-roadmaps/Beginners/Problem Solving/non divisible subset/solution.cpp
fd4207c21b7d937dd877d32681cf2daf7b10725b
[]
no_license
AkshataABhat/dsa-roadmaps
14c8699d83d5696831aaf558123f272a8470d2b2
2c80dfe05eba1294b1c452e944ce50094ec2749f
refs/heads/master
2023-08-12T13:23:16.550376
2021-10-09T13:43:51
2021-10-09T13:43:51
417,504,541
1
0
null
null
null
null
UTF-8
C++
false
false
1,312
cpp
solution.cpp
#include <bits/stdc++.h> using namespace std; int nonDivisibleSubset(int k, vector<int> s) { int max=0; int c=0; int d=0; if(k%2==0) { d++; } for(int i=0;i<s.size();i++) { s[i]=s[i]%k; if(s[i]==0) { c++; } if(s[i]==(k/2) && d==1) { d++; } cout<<s[i]<<" "; } cout<<endl; if(c!=0) { max++; } if(d>1) { max++; } for(int i=1;i<=(k/2);i++) { int j=k-i; cout<<i<<" "<<j<<endl; if(i!=j) { int a=0; int b=0; for(int l=0;l<s.size();l++) { if(s[l]==i) { a++; } if(s[l]==j) { b++; } } if(a>b) { max=max+a; } else { max=max+b; } } } return max; } int main() { int n,k; cin>>n>>k; int s[n] ; for (int i = 0; i < n; i++) { int j; cin>>j; s[i]=j; } int result = nonDivisibleSubset(k, s); cout << result << "\n"; return 0; }
77580f3383858b438975982a2f72424b8771ed43
55540f3e86f1d5d86ef6b5d295a63518e274efe3
/toolchain/riscv/Darwin/lib/gcc/riscv64-unknown-elf/10.2.0/plugin/include/lra-int.h
01fcbfa2664a24eea21bb31d46c4ed18d179614c
[ "Apache-2.0" ]
permissive
bouffalolab/bl_iot_sdk
bc5eaf036b70f8c65dd389439062b169f8d09daa
b90664de0bd4c1897a9f1f5d9e360a9631d38b34
refs/heads/master
2023-08-31T03:38:03.369853
2023-08-16T08:50:33
2023-08-18T09:13:27
307,347,250
244
101
Apache-2.0
2023-08-28T06:29:02
2020-10-26T11:16:30
C
UTF-8
C++
false
false
18,683
h
lra-int.h
/* Local Register Allocator (LRA) intercommunication header file. Copyright (C) 2010-2020 Free Software Foundation, Inc. Contributed by Vladimir Makarov <vmakarov@redhat.com>. This file is part of GCC. GCC 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, or (at your option) any later version. GCC 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 GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #ifndef GCC_LRA_INT_H #define GCC_LRA_INT_H #define lra_assert(c) gcc_checking_assert (c) /* The parameter used to prevent infinite reloading for an insn. Each insn operands might require a reload and, if it is a memory, its base and index registers might require a reload too. */ #define LRA_MAX_INSN_RELOADS (MAX_RECOG_OPERANDS * 3) typedef struct lra_live_range *lra_live_range_t; /* The structure describes program points where a given pseudo lives. The live ranges can be used to find conflicts with other pseudos. If the live ranges of two pseudos are intersected, the pseudos are in conflict. */ struct lra_live_range { /* Pseudo regno whose live range is described by given structure. */ int regno; /* Program point range. */ int start, finish; /* Next structure describing program points where the pseudo lives. */ lra_live_range_t next; /* Pointer to structures with the same start. */ lra_live_range_t start_next; }; typedef struct lra_copy *lra_copy_t; /* Copy between pseudos which affects assigning hard registers. */ struct lra_copy { /* True if regno1 is the destination of the copy. */ bool regno1_dest_p; /* Execution frequency of the copy. */ int freq; /* Pseudos connected by the copy. REGNO1 < REGNO2. */ int regno1, regno2; /* Next copy with correspondingly REGNO1 and REGNO2. */ lra_copy_t regno1_next, regno2_next; }; /* Common info about a register (pseudo or hard register). */ class lra_reg { public: /* Bitmap of UIDs of insns (including debug insns) referring the reg. */ bitmap_head insn_bitmap; /* The following fields are defined only for pseudos. */ /* Hard registers with which the pseudo conflicts. */ HARD_REG_SET conflict_hard_regs; /* We assign hard registers to reload pseudos which can occur in few places. So two hard register preferences are enough for them. The following fields define the preferred hard registers. If there are no such hard registers the first field value is negative. If there is only one preferred hard register, the 2nd field is negative. */ int preferred_hard_regno1, preferred_hard_regno2; /* Profits to use the corresponding preferred hard registers. If the both hard registers defined, the first hard register has not less profit than the second one. */ int preferred_hard_regno_profit1, preferred_hard_regno_profit2; #ifdef STACK_REGS /* True if the pseudo should not be assigned to a stack register. */ bool no_stack_p; #endif /* Number of references and execution frequencies of the register in *non-debug* insns. */ int nrefs, freq; int last_reload; /* rtx used to undo the inheritance. It can be non-null only between subsequent inheritance and undo inheritance passes. */ rtx restore_rtx; /* Value holding by register. If the pseudos have the same value they do not conflict. */ int val; /* Offset from relative eliminate register to pesudo reg. */ poly_int64 offset; /* These members are set up in lra-lives.c and updated in lra-coalesce.c. */ /* The biggest size mode in which each pseudo reg is referred in whole function (possibly via subreg). */ machine_mode biggest_mode; /* Live ranges of the pseudo. */ lra_live_range_t live_ranges; /* This member is set up in lra-lives.c for subsequent assignments. */ lra_copy_t copies; }; /* References to the common info about each register. */ extern class lra_reg *lra_reg_info; extern HARD_REG_SET hard_regs_spilled_into; /* Static info about each insn operand (common for all insns with the same ICODE). Warning: if the structure definition is changed, the initializer for debug_operand_data in lra.c should be changed too. */ struct lra_operand_data { /* The machine description constraint string of the operand. */ const char *constraint; /* Alternatives for which early_clobber can be true. */ alternative_mask early_clobber_alts; /* It is taken only from machine description (which is different from recog_data.operand_mode) and can be of VOIDmode. */ ENUM_BITFIELD(machine_mode) mode : 16; /* The type of the operand (in/out/inout). */ ENUM_BITFIELD (op_type) type : 8; /* Through if accessed through STRICT_LOW. */ unsigned int strict_low : 1; /* True if the operand is an operator. */ unsigned int is_operator : 1; /* True if the operand is an address. */ unsigned int is_address : 1; }; /* Info about register occurrence in an insn. */ struct lra_insn_reg { /* Alternatives for which early_clobber can be true. */ alternative_mask early_clobber_alts; /* The biggest mode through which the insn refers to the register occurrence (remember the register can be accessed through a subreg in the insn). */ ENUM_BITFIELD(machine_mode) biggest_mode : 16; /* The type of the corresponding operand which is the register. */ ENUM_BITFIELD (op_type) type : 8; /* True if the reg is accessed through a subreg and the subreg is just a part of the register. */ unsigned int subreg_p : 1; /* The corresponding regno of the register. */ int regno; /* Next reg info of the same insn. */ struct lra_insn_reg *next; }; /* Static part (common info for insns with the same ICODE) of LRA internal insn info. It exists in at most one exemplar for each non-negative ICODE. There is only one exception. Each asm insn has own structure. Warning: if the structure definition is changed, the initializer for debug_insn_static_data in lra.c should be changed too. */ struct lra_static_insn_data { /* Static info about each insn operand. */ struct lra_operand_data *operand; /* Each duplication refers to the number of the corresponding operand which is duplicated. */ int *dup_num; /* The number of an operand marked as commutative, -1 otherwise. */ int commutative; /* Number of operands, duplications, and alternatives of the insn. */ char n_operands; char n_dups; char n_alternatives; /* Insns in machine description (or clobbers in asm) may contain explicit hard regs which are not operands. The following list describes such hard registers. */ struct lra_insn_reg *hard_regs; /* Array [n_alternatives][n_operand] of static constraint info for given operand in given alternative. This info can be changed if the target reg info is changed. */ const struct operand_alternative *operand_alternative; }; /* Negative insn alternative numbers used for special cases. */ #define LRA_UNKNOWN_ALT -1 #define LRA_NON_CLOBBERED_ALT -2 /* LRA internal info about an insn (LRA internal insn representation). */ class lra_insn_recog_data { public: /* The insn code. */ int icode; /* The alternative should be used for the insn, LRA_UNKNOWN_ALT if unknown, or we should assume any alternative, or the insn is a debug insn. LRA_NON_CLOBBERED_ALT means ignoring any earlier clobbers for the insn. */ int used_insn_alternative; /* SP offset before the insn relative to one at the func start. */ poly_int64 sp_offset; /* The insn itself. */ rtx_insn *insn; /* Common data for insns with the same ICODE. Asm insns (their ICODE is negative) do not share such structures. */ struct lra_static_insn_data *insn_static_data; /* Two arrays of size correspondingly equal to the operand and the duplication numbers: */ rtx **operand_loc; /* The operand locations, NULL if no operands. */ rtx **dup_loc; /* The dup locations, NULL if no dups. */ /* Number of hard registers implicitly used/clobbered in given call insn. The value can be NULL or points to array of the hard register numbers ending with a negative value. To differ clobbered and used hard regs, clobbered hard regs are incremented by FIRST_PSEUDO_REGISTER. */ int *arg_hard_regs; /* Cached value of get_preferred_alternatives. */ alternative_mask preferred_alternatives; /* The following member value is always NULL for a debug insn. */ struct lra_insn_reg *regs; }; typedef class lra_insn_recog_data *lra_insn_recog_data_t; /* Whether the clobber is used temporary in LRA. */ #define LRA_TEMP_CLOBBER_P(x) \ (RTL_FLAG_CHECK1 ("TEMP_CLOBBER_P", (x), CLOBBER)->unchanging) /* Cost factor for each additional reload and maximal cost reject for insn reloads. One might ask about such strange numbers. Their values occurred historically from former reload pass. */ #define LRA_LOSER_COST_FACTOR 6 #define LRA_MAX_REJECT 600 /* Maximum allowed number of assignment pass iterations after the latest spill pass when any former reload pseudo was spilled. It is for preventing LRA cycling in a bug case. */ #define LRA_MAX_ASSIGNMENT_ITERATION_NUMBER 30 /* The maximal number of inheritance/split passes in LRA. It should be more 1 in order to perform caller saves transformations and much less MAX_CONSTRAINT_ITERATION_NUMBER to prevent LRA to do as many as permitted constraint passes in some complicated cases. The first inheritance/split pass has a biggest impact on generated code quality. Each subsequent affects generated code in less degree. For example, the 3rd pass does not change generated SPEC2000 code at all on x86-64. */ #define LRA_MAX_INHERITANCE_PASSES 2 #if LRA_MAX_INHERITANCE_PASSES <= 0 \ || LRA_MAX_INHERITANCE_PASSES >= LRA_MAX_ASSIGNMENT_ITERATION_NUMBER - 8 #error wrong LRA_MAX_INHERITANCE_PASSES value #endif /* Analogous macro to the above one but for rematerialization. */ #define LRA_MAX_REMATERIALIZATION_PASSES 2 #if LRA_MAX_REMATERIALIZATION_PASSES <= 0 \ || LRA_MAX_REMATERIALIZATION_PASSES >= LRA_MAX_ASSIGNMENT_ITERATION_NUMBER - 8 #error wrong LRA_MAX_REMATERIALIZATION_PASSES value #endif /* lra.c: */ extern FILE *lra_dump_file; extern bool lra_asm_error_p; extern bool lra_reg_spill_p; extern HARD_REG_SET lra_no_alloc_regs; extern int lra_insn_recog_data_len; extern lra_insn_recog_data_t *lra_insn_recog_data; extern int lra_curr_reload_num; extern void lra_dump_bitmap_with_title (const char *, bitmap, int); extern hashval_t lra_rtx_hash (rtx x); extern void lra_push_insn (rtx_insn *); extern void lra_push_insn_by_uid (unsigned int); extern void lra_push_insn_and_update_insn_regno_info (rtx_insn *); extern rtx_insn *lra_pop_insn (void); extern unsigned int lra_insn_stack_length (void); extern rtx lra_create_new_reg_with_unique_value (machine_mode, rtx, enum reg_class, const char *); extern void lra_set_regno_unique_value (int); extern void lra_invalidate_insn_data (rtx_insn *); extern void lra_set_insn_deleted (rtx_insn *); extern void lra_delete_dead_insn (rtx_insn *); extern void lra_emit_add (rtx, rtx, rtx); extern void lra_emit_move (rtx, rtx); extern void lra_update_dups (lra_insn_recog_data_t, signed char *); extern void lra_process_new_insns (rtx_insn *, rtx_insn *, rtx_insn *, const char *); extern bool lra_substitute_pseudo (rtx *, int, rtx, bool, bool); extern bool lra_substitute_pseudo_within_insn (rtx_insn *, int, rtx, bool); extern lra_insn_recog_data_t lra_set_insn_recog_data (rtx_insn *); extern lra_insn_recog_data_t lra_update_insn_recog_data (rtx_insn *); extern void lra_set_used_insn_alternative (rtx_insn *, int); extern void lra_set_used_insn_alternative_by_uid (int, int); extern void lra_invalidate_insn_regno_info (rtx_insn *); extern void lra_update_insn_regno_info (rtx_insn *); extern struct lra_insn_reg *lra_get_insn_regs (int); extern void lra_free_copies (void); extern void lra_create_copy (int, int, int); extern lra_copy_t lra_get_copy (int); extern bool lra_former_scratch_p (int); extern bool lra_former_scratch_operand_p (rtx_insn *, int); extern void lra_register_new_scratch_op (rtx_insn *, int, int); extern int lra_new_regno_start; extern int lra_constraint_new_regno_start; extern int lra_bad_spill_regno_start; extern bitmap_head lra_inheritance_pseudos; extern bitmap_head lra_split_regs; extern bitmap_head lra_subreg_reload_pseudos; extern bitmap_head lra_optional_reload_pseudos; /* lra-constraints.c: */ extern void lra_init_equiv (void); extern int lra_constraint_offset (int, machine_mode); extern int lra_constraint_iter; extern bool check_and_force_assignment_correctness_p; extern int lra_inheritance_iter; extern int lra_undo_inheritance_iter; extern bool lra_constrain_insn (rtx_insn *); extern bool lra_constraints (bool); extern void lra_constraints_init (void); extern void lra_constraints_finish (void); extern bool spill_hard_reg_in_range (int, enum reg_class, rtx_insn *, rtx_insn *); extern void lra_inheritance (void); extern bool lra_undo_inheritance (void); /* lra-lives.c: */ extern int lra_live_max_point; extern int *lra_point_freq; extern int lra_hard_reg_usage[FIRST_PSEUDO_REGISTER]; extern int lra_live_range_iter; extern void lra_create_live_ranges (bool, bool); extern lra_live_range_t lra_copy_live_range_list (lra_live_range_t); extern lra_live_range_t lra_merge_live_ranges (lra_live_range_t, lra_live_range_t); extern bool lra_intersected_live_ranges_p (lra_live_range_t, lra_live_range_t); extern void lra_print_live_range_list (FILE *, lra_live_range_t); extern void debug (lra_live_range &ref); extern void debug (lra_live_range *ptr); extern void lra_debug_live_range_list (lra_live_range_t); extern void lra_debug_pseudo_live_ranges (int); extern void lra_debug_live_ranges (void); extern void lra_clear_live_ranges (void); extern void lra_live_ranges_init (void); extern void lra_live_ranges_finish (void); extern void lra_setup_reload_pseudo_preferenced_hard_reg (int, int, int); /* lra-assigns.c: */ extern int lra_assignment_iter; extern int lra_assignment_iter_after_spill; extern void lra_setup_reg_renumber (int, int, bool); extern bool lra_assign (bool &); extern bool lra_split_hard_reg_for (void); /* lra-coalesce.c: */ extern int lra_coalesce_iter; extern bool lra_coalesce (void); /* lra-spills.c: */ extern bool lra_need_for_scratch_reg_p (void); extern bool lra_need_for_spills_p (void); extern void lra_spill (void); extern void lra_final_code_change (void); /* lra-remat.c: */ extern int lra_rematerialization_iter; extern bool lra_remat (void); /* lra-elimination.c: */ extern void lra_debug_elim_table (void); extern int lra_get_elimination_hard_regno (int); extern rtx lra_eliminate_regs_1 (rtx_insn *, rtx, machine_mode, bool, bool, poly_int64, bool); extern void eliminate_regs_in_insn (rtx_insn *insn, bool, bool, poly_int64); extern void lra_eliminate (bool, bool); extern void lra_eliminate_reg_if_possible (rtx *); /* Return the hard register which given pseudo REGNO assigned to. Negative value means that the register got memory or we don't know allocation yet. */ static inline int lra_get_regno_hard_regno (int regno) { resize_reg_info (); return reg_renumber[regno]; } /* Change class of pseudo REGNO to NEW_CLASS. Print info about it using TITLE. Output a new line if NL_P. */ static void inline lra_change_class (int regno, enum reg_class new_class, const char *title, bool nl_p) { lra_assert (regno >= FIRST_PSEUDO_REGISTER); if (lra_dump_file != NULL) fprintf (lra_dump_file, "%s class %s for r%d", title, reg_class_names[new_class], regno); setup_reg_classes (regno, new_class, NO_REGS, new_class); if (lra_dump_file != NULL && nl_p) fprintf (lra_dump_file, "\n"); } /* Update insn operands which are duplication of NOP operand. The insn is represented by its LRA internal representation ID. */ static inline void lra_update_dup (lra_insn_recog_data_t id, int nop) { int i; struct lra_static_insn_data *static_id = id->insn_static_data; for (i = 0; i < static_id->n_dups; i++) if (static_id->dup_num[i] == nop) *id->dup_loc[i] = *id->operand_loc[nop]; } /* Process operator duplications in insn with ID. We do it after the operands processing. Generally speaking, we could do this probably simultaneously with operands processing because a common practice is to enumerate the operators after their operands. */ static inline void lra_update_operator_dups (lra_insn_recog_data_t id) { int i; struct lra_static_insn_data *static_id = id->insn_static_data; for (i = 0; i < static_id->n_dups; i++) { int ndup = static_id->dup_num[i]; if (static_id->operand[ndup].is_operator) *id->dup_loc[i] = *id->operand_loc[ndup]; } } /* Return info about INSN. Set up the info if it is not done yet. */ static inline lra_insn_recog_data_t lra_get_insn_recog_data (rtx_insn *insn) { lra_insn_recog_data_t data; unsigned int uid = INSN_UID (insn); if (lra_insn_recog_data_len > (int) uid && (data = lra_insn_recog_data[uid]) != NULL) { /* Check that we did not change insn without updating the insn info. */ lra_assert (data->insn == insn && (INSN_CODE (insn) < 0 || data->icode == INSN_CODE (insn))); return data; } return lra_set_insn_recog_data (insn); } /* Update offset from pseudos with VAL by INCR. */ static inline void lra_update_reg_val_offset (int val, poly_int64 incr) { int i; for (i = FIRST_PSEUDO_REGISTER; i < max_reg_num (); i++) { if (lra_reg_info[i].val == val) lra_reg_info[i].offset += incr; } } /* Return true if register content is equal to VAL with OFFSET. */ static inline bool lra_reg_val_equal_p (int regno, int val, poly_int64 offset) { if (lra_reg_info[regno].val == val && known_eq (lra_reg_info[regno].offset, offset)) return true; return false; } /* Assign value of register FROM to TO. */ static inline void lra_assign_reg_val (int from, int to) { lra_reg_info[to].val = lra_reg_info[from].val; lra_reg_info[to].offset = lra_reg_info[from].offset; } #endif /* GCC_LRA_INT_H */
84395c838a4fc2a61080628a5e32fa1228339f12
f6738ad1752b42ccfdce2ac6b323f9944a8300ad
/PracticeProblems/GCDCNT.cpp
a52b4625c5e5aef27daf948205fbc7b2936fcc69
[]
no_license
ihsakash1994/Prepration
72552a746164394960949d34c9eecd82e0c46bee
677fadcd708386203b35cc385f9532946322de18
refs/heads/master
2021-04-27T08:14:46.102136
2018-03-17T06:22:31
2018-03-17T06:22:31
122,651,326
0
0
null
null
null
null
UTF-8
C++
false
false
4,262
cpp
GCDCNT.cpp
#include<iostream> #include<cstdio> #include<algorithm> #include<vector> #include<cmath> #include<set> #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> #define maxm 51234 #define maxn 100004 using namespace std; using namespace __gnu_pbds; int a[maxm]; vector<int> t[maxm]; bool prime[maxn]; //set<int> akash[maxn]; tree<int, /* key */ null_type, /* mapped */ less<int>, /* compare function */ rb_tree_tag, /* red-black tree tag */ tree_order_statistics_node_update> akash[maxn]; int power2(int x) { int ans = 1; for(int i = 1; i <= x; i++)ans = ans * 2; return ans; } void SieveOfEratosthenes(long long n) { for (int i = 0; i < n+1; i++)prime[i] = true; for (long long p=2; p*p<=n; p++) { if (prime[p] == true) { for (int i=p*2; i<=n; i += p) prime[i] = false; } } } void InsertAndEraseInAkash(int ix, int maxBit, vector<int> v, bool isErase) { for(int j = 1; j <= maxBit; j++) { int y = j, ct = 0, temp = 1; while(y != 0) { if (y%2 == 1) { temp = temp * v[ct]; } y = y/2; ct++; } if (isErase)akash[temp].erase(ix); else akash[temp].insert(ix); } } vector<int> PrimeVec(int num) { vector<int> temp; for (int j = 1; j <= (int)sqrt(num); j++) { if (num % j == 0) { int a = j, b = num / j; if (a != 1 && prime[a])temp.push_back(a); if (a != b && prime[b])temp.push_back(b); } } return temp; } int CalAns(int maxBit, vector<int> v, int l, int r) { int ans = (r - l + 1); //cout << ans << endl; for(int j = 1; j <= maxBit; j++) { int y = j, ct = 0, temp = 1, setc = 0; while(y != 0) { if (y%2 == 1) { setc++; temp = temp * v[ct]; } y = y/2; ct++; } if (setc % 2 == 0) { int ct1 = akash[temp].order_of_key(l);//std::distance(akash[temp].begin(), akash[temp].lower_bound(l)); int ct2 = akash[temp].order_of_key(r+1);//std::distance(akash[temp].begin(), akash[temp].upper_bound(r)); ans += (ct2 - ct1); //cout << setc << " " <<temp << ": " << (ct2 - ct1) << endl; } else { int ct1 = akash[temp].order_of_key(l);//std::distance(akash[temp].begin(), akash[temp].lower_bound(l)); int ct2 = akash[temp].order_of_key(r+1);//std::distance(akash[temp].begin(), akash[temp].upper_bound(r)); ans -= (ct2 - ct1); //cout <<setc << " " << temp << ": " << -(ct2 - ct1)<< endl; } } return ans; } int main() { SieveOfEratosthenes(100000); int n; scanf("%d", &n); for(int i = 1; i <= n; i++) { int x; scanf("%d", &x); a[i] = x; t[i] = PrimeVec(x); } for(int i = 1; i <= n; i++) { //for(int j = 0; j < t[i].size(); j++)cout << t[i][j] << " "; cout << endl; } for (int i = 1; i <= n; i++) { InsertAndEraseInAkash(i, power2(t[i].size()) - 1, t[i], false); } int q; scanf("%d", &q); while(q--) { int type; scanf("%d", &type); if (type == 1) { int x, y; scanf("%d %d", &x, &y); int temp1 = a[x]; vector<int> temp = PrimeVec(a[x]); InsertAndEraseInAkash(x, power2(temp.size()) - 1, temp, true); temp.clear(); temp = PrimeVec(y); InsertAndEraseInAkash(x, power2(temp.size()) - 1, temp, false); a[x] = y; } if (type == 2) { int l, r, g; scanf("%d%d%d", &l, &r, &g); vector<int> temp = PrimeVec(g); //for(int i = 0; i < temp.size(); i++)cout << temp[i] << " "; cout << endl; printf("%d\n", CalAns(power2(temp.size()) - 1, temp, l, r));//<< CalAns(power2(temp.size()) - 1, temp, l, r) << endl;// << " " << ans<< endl; } } }
b92d4216209c6dbac1663ae43ad778677611690c
35b3a9665aaf21a2f9eea8fd99e1fc057daa12e1
/src/Page_GfxTest.h
0084af34dd780121a7a7be87d250c34704d8c036
[]
no_license
OggYiu/rag-engine
04677c3cb4604e5e8b0de78673680cbfdea0132b
986c0ac5008a661dba9151b8216806df0e8f4646
refs/heads/master
2021-01-17T07:41:31.232070
2014-11-08T06:52:57
2014-11-08T06:52:57
24,141,419
0
0
null
null
null
null
UTF-8
C++
false
false
262
h
Page_GfxTest.h
#ifndef __PAGE_GFXTEST_H__ #define __PAGE_GFXTEST_H__ #include "Page.h" class Page_GfxTest : public Page { public: Page_GfxTest(); ~Page_GfxTest(); public: virtual void update(const double dt); protected: virtual void resolved(); protected: }; #endif
ee108adda8f3c7f6f3a8c4391e8f724a4de570b0
f6e477f1d91b84cfe50781d17c8fa6767fe6667f
/node/anagram-node-js.h
7542c60bbf3051d4c9cd2cd0c6c0c1236c58aea8
[]
no_license
dlecocq/anagrammer
5776360335bcbe641057410068637f05d0c9f4ff
2a52ecd60e8c4a93888050431c281026cf94ebb7
refs/heads/master
2016-09-06T05:47:31.718673
2012-02-25T23:39:24
2012-02-25T23:39:24
3,548,123
0
0
null
null
null
null
UTF-8
C++
false
false
696
h
anagram-node-js.h
#ifndef ANAGRAM_NODE_H #define ANAGRAM_NODE_H #include <node.h> // This is the underlying C library #include "../src/anagram.h" class Node : public node::ObjectWrap { public: static void Init(v8::Handle<v8::Object> target); private: Node(); ~Node(); static v8::Handle<v8::Value> New(const v8::Arguments& args); static v8::Handle<v8::Value> Insert(const v8::Arguments& args); static v8::Handle<v8::Value> Del(const v8::Arguments& args); static v8::Handle<v8::Value> Contains(const v8::Arguments& args); static v8::Handle<v8::Value> Anagrams(const v8::Arguments& args); static v8::Handle<v8::Value> Load(const v8::Arguments& args); anagram_node _node; }; #endif
14aaec1c11f5491894b31adacc30fc1d681a7473
608a2e871c7b534a3922914595c294dc147a5310
/Intermediate/Build/Win64/UE4/Inc/FireAndIce/PlatformBase.gen.cpp
4091ef4fa970e9a8b0fdc0bac2a6246d9cfa4412
[]
no_license
aokeefe97/FireAndIce-Test
0214094f2e8f2d1ed3cb06981b67c2265d8e58c9
e665709bc18d384c5046164105b59e7a46d2b27d
refs/heads/master
2020-03-11T10:09:48.629277
2018-04-17T16:31:16
2018-04-17T16:31:16
129,934,656
0
0
null
null
null
null
UTF-8
C++
false
false
7,541
cpp
PlatformBase.gen.cpp
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "GeneratedCppIncludes.h" #include "PlatformBase.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodePlatformBase() {} // Cross Module References FIREANDICE_API UClass* Z_Construct_UClass_APlatformBase_NoRegister(); FIREANDICE_API UClass* Z_Construct_UClass_APlatformBase(); ENGINE_API UClass* Z_Construct_UClass_AActor(); UPackage* Z_Construct_UPackage__Script_FireAndIce(); FIREANDICE_API UFunction* Z_Construct_UFunction_APlatformBase_BeginOverlap(); ENGINE_API UClass* Z_Construct_UClass_AActor_NoRegister(); ENGINE_API UClass* Z_Construct_UClass_UBoxComponent_NoRegister(); ENGINE_API UClass* Z_Construct_UClass_USceneComponent_NoRegister(); ENGINE_API UClass* Z_Construct_UClass_UStaticMeshComponent_NoRegister(); // End Cross Module References void APlatformBase::StaticRegisterNativesAPlatformBase() { UClass* Class = APlatformBase::StaticClass(); static const FNameNativePtrPair Funcs[] = { { "BeginOverlap", (Native)&APlatformBase::execBeginOverlap }, }; FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, ARRAY_COUNT(Funcs)); } UFunction* Z_Construct_UFunction_APlatformBase_BeginOverlap() { struct PlatformBase_eventBeginOverlap_Parms { AActor* OtherActor; }; static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { static const UE4CodeGen_Private::FObjectPropertyParams NewProp_OtherActor = { UE4CodeGen_Private::EPropertyClass::Object, "OtherActor", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000080, 1, nullptr, STRUCT_OFFSET(PlatformBase_eventBeginOverlap_Parms, OtherActor), Z_Construct_UClass_AActor_NoRegister, METADATA_PARAMS(nullptr, 0) }; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_OtherActor, }; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[] = { { "ModuleRelativePath", "PlatformBase.h" }, }; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams = { (UObject*(*)())Z_Construct_UClass_APlatformBase, "BeginOverlap", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x04020401, sizeof(PlatformBase_eventBeginOverlap_Parms), PropPointers, ARRAY_COUNT(PropPointers), 0, 0, METADATA_PARAMS(Function_MetaDataParams, ARRAY_COUNT(Function_MetaDataParams)) }; UE4CodeGen_Private::ConstructUFunction(ReturnFunction, FuncParams); } return ReturnFunction; } UClass* Z_Construct_UClass_APlatformBase_NoRegister() { return APlatformBase::StaticClass(); } UClass* Z_Construct_UClass_APlatformBase() { static UClass* OuterClass = nullptr; if (!OuterClass) { static UObject* (*const DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_AActor, (UObject* (*)())Z_Construct_UPackage__Script_FireAndIce, }; static const FClassFunctionLinkInfo FuncInfo[] = { { &Z_Construct_UFunction_APlatformBase_BeginOverlap, "BeginOverlap" }, // 3726844285 }; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[] = { { "IncludePath", "PlatformBase.h" }, { "ModuleRelativePath", "PlatformBase.h" }, }; #endif #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_BlockCollision_MetaData[] = { { "Category", "Collision" }, { "EditInline", "true" }, { "ModuleRelativePath", "PlatformBase.h" }, }; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_BlockCollision = { UE4CodeGen_Private::EPropertyClass::Object, "BlockCollision", RF_Public|RF_Transient|RF_MarkAsNative, 0x00100000000b0009, 1, nullptr, STRUCT_OFFSET(APlatformBase, BlockCollision), Z_Construct_UClass_UBoxComponent_NoRegister, METADATA_PARAMS(NewProp_BlockCollision_MetaData, ARRAY_COUNT(NewProp_BlockCollision_MetaData)) }; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_OverlapCollision_MetaData[] = { { "Category", "Collision" }, { "EditInline", "true" }, { "ModuleRelativePath", "PlatformBase.h" }, }; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_OverlapCollision = { UE4CodeGen_Private::EPropertyClass::Object, "OverlapCollision", RF_Public|RF_Transient|RF_MarkAsNative, 0x00100000000b0009, 1, nullptr, STRUCT_OFFSET(APlatformBase, OverlapCollision), Z_Construct_UClass_UBoxComponent_NoRegister, METADATA_PARAMS(NewProp_OverlapCollision_MetaData, ARRAY_COUNT(NewProp_OverlapCollision_MetaData)) }; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Origin_MetaData[] = { { "Category", "Scene" }, { "EditInline", "true" }, { "ModuleRelativePath", "PlatformBase.h" }, }; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_Origin = { UE4CodeGen_Private::EPropertyClass::Object, "Origin", RF_Public|RF_Transient|RF_MarkAsNative, 0x00100000000a000d, 1, nullptr, STRUCT_OFFSET(APlatformBase, Origin), Z_Construct_UClass_USceneComponent_NoRegister, METADATA_PARAMS(NewProp_Origin_MetaData, ARRAY_COUNT(NewProp_Origin_MetaData)) }; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_MeshComponent_MetaData[] = { { "Category", "Mesh" }, { "EditInline", "true" }, { "ModuleRelativePath", "PlatformBase.h" }, }; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_MeshComponent = { UE4CodeGen_Private::EPropertyClass::Object, "MeshComponent", RF_Public|RF_Transient|RF_MarkAsNative, 0x00100000000a000d, 1, nullptr, STRUCT_OFFSET(APlatformBase, MeshComponent), Z_Construct_UClass_UStaticMeshComponent_NoRegister, METADATA_PARAMS(NewProp_MeshComponent_MetaData, ARRAY_COUNT(NewProp_MeshComponent_MetaData)) }; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_BlockCollision, (const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_OverlapCollision, (const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_Origin, (const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_MeshComponent, }; static const FCppClassTypeInfoStatic StaticCppClassTypeInfo = { TCppClassTypeTraits<APlatformBase>::IsAbstract, }; static const UE4CodeGen_Private::FClassParams ClassParams = { &APlatformBase::StaticClass, DependentSingletons, ARRAY_COUNT(DependentSingletons), 0x00900080u, FuncInfo, ARRAY_COUNT(FuncInfo), PropPointers, ARRAY_COUNT(PropPointers), nullptr, &StaticCppClassTypeInfo, nullptr, 0, METADATA_PARAMS(Class_MetaDataParams, ARRAY_COUNT(Class_MetaDataParams)) }; UE4CodeGen_Private::ConstructUClass(OuterClass, ClassParams); } return OuterClass; } IMPLEMENT_CLASS(APlatformBase, 4068492277); static FCompiledInDefer Z_CompiledInDefer_UClass_APlatformBase(Z_Construct_UClass_APlatformBase, &APlatformBase::StaticClass, TEXT("/Script/FireAndIce"), TEXT("APlatformBase"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(APlatformBase); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif
e740c839b6239126a389d693da2ecc4765e0a96d
93fbf65a76bbeb5d8e915c14e5601ae363b3057f
/1st sem C/pattern9.cpp
882b893a93841329e8ba8675f4b5f3b13cfbe6cd
[]
no_license
sauravjaiswa/Coding-Problems
fd864a7678a961a422902eef42a29218cdd2367f
cb978f90d7dcaec75af84cba05d141fdf4f243a0
refs/heads/master
2023-04-14T11:34:03.138424
2021-03-25T17:46:47
2021-03-25T17:46:47
309,085,423
0
0
null
null
null
null
UTF-8
C++
false
false
177
cpp
pattern9.cpp
/*pattern- ABCDE BCDE CDE DE E */ #include<stdio.h> int main() { int i,j; for(i=65;i<=69;i++) { for(j=i;j<=69;j++) printf("%c",j); printf("\n"); } }
92c3afb129fdac1c7f2558c6073ae469c0abb3dc
ee762a7468148835a4e375168d4acc507abfc67d
/MasterTroll.cpp
406d8520fb6186d0a8fa024d8d42a83f525ebbda
[]
no_license
MatudaGames/Classes
a7c6ddfadd630bf3a34b33f7a8970a6553ce0221
b2ac0e22f647d916c4842c6c50f8d1f68d40f8d5
refs/heads/master
2020-05-29T16:01:56.421884
2015-04-09T18:07:51
2015-04-09T18:07:51
32,596,808
0
0
null
null
null
null
UTF-8
C++
false
false
7,084
cpp
MasterTroll.cpp
// // MasterTroll.cpp // DwarfForest // // Created by Kristaps Auzins on 06/03/15. // // #include "MasterTroll.h" #include <SimpleAudioEngine.h> #include "GameScene.h" #include "AppMacros.h" #include "Utils.h" #include "User.h" USING_NS_CC; using namespace CocosDenshion; MasterTroll* MasterTroll::create(GameScene* game) { MasterTroll *pRet = new MasterTroll(); if (pRet && pRet->init(game)) { pRet->autorelease(); return pRet; } else { delete pRet; pRet = NULL; return NULL; } } MasterTroll::MasterTroll(): _game(NULL), _animation(NULL), _idleAnim(NULL), _jumpAnim(NULL), _magic_1_Anim(NULL), _magic_2_Anim(NULL), _smashAnim(NULL), _shootAnim(NULL) { } MasterTroll::~MasterTroll() { // if (_game) // { // _game->release(); // } if (_idleAnim) _idleAnim->release(); if (_jumpAnim) _jumpAnim->release(); if (_magic_1_Anim) _magic_1_Anim->release(); if (_magic_2_Anim) _magic_2_Anim->release(); } bool MasterTroll::init(GameScene* game) { if (!CCNode::init()) { return false; } mLastMagicAnimID = 1; _game = game; // The base pad where Object stands _base = CCSprite::create("small_dot_red.png"); addChild(_base); // The bottom of MT mBasePad = CCSprite::create("Characters/master_troll/mt_base.png"); mBasePad->setAnchorPoint(ccp(0.5f,1)); _base->addChild(mBasePad); // The all animations !!! _idleAnim = SpriteAnimation::create("Characters/master_troll/mt_idle.plist"); _idleAnim->retain(); _jumpAnim = SpriteAnimation::create("Characters/master_troll/mt_jumping.plist",false); _jumpAnim->retain(); _jumpAnim->animation->setRestoreOriginalFrame(true); _magic_1_Anim = SpriteAnimation::create("Characters/master_troll/mt_magic1.plist",false); _magic_1_Anim->retain(); _magic_1_Anim->animation->setRestoreOriginalFrame(true); _magic_2_Anim = SpriteAnimation::create("Characters/master_troll/mt_magic2.plist",false); _magic_2_Anim->retain(); _magic_2_Anim->animation->setRestoreOriginalFrame(true); _shootAnim = SpriteAnimation::create("Characters/master_troll/mt_shoot.plist",false); _shootAnim->setPosition(ccp(16,-5)); _shootAnim->retain(); _shootAnim->animation->setRestoreOriginalFrame(true); _smashAnim = SpriteAnimation::create("Characters/master_troll/mt_smash.plist",false); _smashAnim->setPosition(ccp(-4,66)); _smashAnim->retain(); _smashAnim->animation->setRestoreOriginalFrame(true); // Special stuff for splash anim mSplashSprite = CCSprite::create("Characters/master_troll/smash_splash.png"); mSplashSprite->setPosition(ccp(100,-100)); mSplashSprite->setVisible(false); _base->addChild(mSplashSprite); mHitGroundTime = -1; return true; } void MasterTroll::update(float delta) { if(_animation != _idleAnim) { // Check when frames run out - set back to idle !!! if(_animation->_action->isDone()){ // Special case for hit ground with stick !!! if(_animation == _smashAnim) { if(mHitGroundTime == -1) { mSplashSprite->setOpacity(255); mSplashSprite->setScale(0); mSplashSprite->setVisible(true); // Set all the anim stuff CCScaleTo* aScaleImage = CCScaleTo::create(0.5f, 1.0f); CCDelayTime* aDelay = CCDelayTime::create(0.25); CCFadeOut* aFadeOut = CCFadeOut::create(0.25f); CCSequence* aSeq = CCSequence::create(aDelay,aFadeOut,NULL); CCSpawn* aSpawn = CCSpawn::create(aSeq,aScaleImage,NULL); mSplashSprite->runAction(aSpawn); // Shake master troll CCMoveTo* aMove1 = CCMoveTo::create(0.075f,ccp(-4,76)); CCMoveTo* aMove2 = CCMoveTo::create(0.075f,ccp(-4,66)); CCSequence* aSeqMove = CCSequence::create(aMove1,aMove2,NULL); CCRepeat* aRepeat = CCRepeat::create(aSeqMove, 5); _smashAnim->runAction(aRepeat); mHitGroundTime = 0.75f; } else { mHitGroundTime-=delta; if(mHitGroundTime<=0){ mHitGroundTime = -1; setAnimation(_idleAnim); } } } else { setAnimation(_idleAnim); } } } } void MasterTroll::setAnimation(SpriteAnimation* animation) { //Glitch Fix!!! if(animation->getOpacity()<128){ animation->setOpacity(255); } if (_animation != animation) { if (_animation){ removeChild(_animation); } _animation = animation; if (_animation){ addChild(_animation); } } } void MasterTroll::setAnimationByName(const char* theAnimation) { // The checker if all correct and what to play how long? if(strcmp(theAnimation,"HitGround") == 0) { // Lets hit the ground !!! setAnimation(_jumpAnim); // Play sound - whats the timing CCDelayTime* aTime = CCDelayTime::create(0.5f); CCCallFuncN* aFunc1 = CCCallFuncN::create(this, callfuncN_selector(MasterTroll::OnMasterHitGroundSFX)); CCSequence* aSeq = CCSequence::create(aTime,aFunc1,NULL); runAction(aSeq); } else if(strcmp(theAnimation,"Magic") == 0) { // Take random action mLastMagicAnimID+=1; if(mLastMagicAnimID>2){ mLastMagicAnimID = 1; } if(mLastMagicAnimID == 1){ setAnimation(_magic_1_Anim); } else{ setAnimation(_magic_2_Anim); } } else if(strcmp(theAnimation,"Shoot") == 0) { setAnimation(_shootAnim); } else if(strcmp(theAnimation,"SmashGround") == 0) { setAnimation(_smashAnim); } else if(strcmp(theAnimation,"Idle") == 0) { setAnimation(_idleAnim); } } void MasterTroll::OnMasterHitGroundSFX(CCNode* sender) { _game->playInGameSound("meteorite_hit_ground"); } void MasterTroll::onEnter() { CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, true); // Set to default anim !!! setAnimation(_idleAnim); CCNode::onEnter(); } void MasterTroll::onExit() { CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this); CCNode::onExit(); } // The new stuff void MasterTroll::SetMissionStuff(MissionSet theMission) { //Check if circle then use the circle stuff setPosition(ccp(200,200));//Some def value for now !!! }
0c4eab70a4b7a120ba8833a2a2d4017d4d73475d
a5a99f646e371b45974a6fb6ccc06b0a674818f2
/Geometry/MTDGeometryBuilder/src/MTDPixelTopologyBuilder.cc
922569d0214b9e9dd787dd7d1802a4be123a7966
[ "Apache-2.0" ]
permissive
cms-sw/cmssw
4ecd2c1105d59c66d385551230542c6615b9ab58
19c178740257eb48367778593da55dcad08b7a4f
refs/heads/master
2023-08-23T21:57:42.491143
2023-08-22T20:22:40
2023-08-22T20:22:40
10,969,551
1,006
3,696
Apache-2.0
2023-09-14T19:14:28
2013-06-26T14:09:07
C++
UTF-8
C++
false
false
3,236
cc
MTDPixelTopologyBuilder.cc
//#define EDM_ML_DEBUG // Make the change for "big" pixels. 3/06 d.k. #include "Geometry/MTDGeometryBuilder/interface/MTDPixelTopologyBuilder.h" #include "Geometry/MTDGeometryBuilder/interface/RectangularMTDTopology.h" #include "DataFormats/GeometrySurface/interface/Bounds.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" MTDPixelTopologyBuilder::MTDPixelTopologyBuilder(void) {} PixelTopology* MTDPixelTopologyBuilder::build(const Bounds* bs, int pixelROCRows, // Num of Rows per ROC int pixelROCCols, // Num of Cols per ROC int pixelROCsInX, int pixelROCsInY, int GAPxInterpad, int GAPxBorder, int GAPyInterpad, int GAPyBorder) { float width = bs->width(); // module width = Xsize float length = bs->length(); // module length = Ysize // Number of pixel rows (x) and columns (y) per module int nrows = pixelROCRows * pixelROCsInX; int ncols = pixelROCCols * pixelROCsInY; float pitchX = width / nrows; float pitchY = length / ncols; float micronsTocm = 1e-4; float gapxinterpad = float(GAPxInterpad) * micronsTocm; //Convert to cm float gapyinterpad = float(GAPyInterpad) * micronsTocm; //Convert to cm float gapxborder = float(GAPxBorder) * micronsTocm; //Convert to cm float gapyborder = float(GAPyBorder) * micronsTocm; //Convert to cm #ifdef EDM_ML_DEBUG edm::LogInfo("MTDPixelTopologyBuilder") << std::fixed << "Building topology for module of width(X) = " << std::setw(10) << width << " length(Y) = " << std::setw(10) << length << "\n Rows per ROC = " << std::setw(10) << pixelROCRows << " Cols per ROC = " << std::setw(10) << pixelROCCols << "\n ROCs in X = " << std::setw(10) << pixelROCsInX << " ROCs in Y = " << std::setw(10) << pixelROCsInY << "\n # pixel rows X = " << std::setw(10) << nrows << " # pixel cols Y = " << std::setw(10) << ncols << "\n pitch in X = " << std::setw(10) << pitchX << " # pitch in Y = " << std::setw(10) << pitchY << "\n Interpad gap in X = " << std::setw(10) << gapxinterpad << " # Interpad gap in Y = " << std::setw(10) << gapyinterpad << "\n Border gap in X = " << std::setw(10) << gapxborder << " # Border gap in Y = " << std::setw(10) << gapyborder; #endif return (new RectangularMTDTopology(nrows, ncols, pitchX, pitchY, pixelROCRows, // (int)rocRow pixelROCCols, // (int)rocCol pixelROCsInX, pixelROCsInY, gapxinterpad, gapxborder, gapyinterpad, gapyborder)); }
30b332f5e61236bb781118443604874aa0155cfe
dea4fc659757039c4c49b6893ca26cda72ce12a1
/src/bilinear.hpp
d005761f2b0564b20f34b2023db0992f49a9d68a
[]
no_license
bartfrenk/cpp-img
c69e4e897226de6c0e578aad216d094162079f69
d3dc6eb2816371e915ae3e6ce47159d9f8ddf17f
refs/heads/master
2021-01-10T13:22:24.729642
2016-03-29T22:12:02
2016-03-29T22:12:02
54,597,993
0
0
null
null
null
null
UTF-8
C++
false
false
471
hpp
bilinear.hpp
#ifndef INTERPOLATED_HPP #define INTERPOLATED_HPP #include "orthotope.hpp" namespace img { // statically assert that A is float or double template <typename I, typename A> class Bilinear { public: using pixel_t = typename I::pixel_t; using coord_t = A; Bilinear(const I &base) : base_(base) {}; Rectangle<coord_t> domain() const { } pixel_t operator()(const coord_t x, const coord_t y) const {}; private: const I base_; }; } #endif
0832876421f6b24c8bc2e677847cb598a90a0749
c70a796815100246f53c724a2476b392a7606dd7
/testVector/testVector.cpp
936cf14683189ec7fa0f2a4d66154c272f75170c
[]
no_license
xjr01/BouncingBall
cec42cb4b475bf8a763da3e19bafb92dd804885f
38dfa9c981039920e939c08ebf782f5c20a966ca
refs/heads/master
2023-06-13T06:24:24.866594
2021-07-08T16:35:48
2021-07-08T16:35:48
341,279,165
0
0
null
null
null
null
UTF-8
C++
false
false
2,701
cpp
testVector.cpp
#include "pch.h" #include "CppUnitTest.h" #include <vector2d.h> #include <EasyX_Draw.h> #include <Windows.h> using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace testVector { TEST_CLASS(testVector) { public: /*TEST_METHOD(TestAdd) { Vector2D a(2, 3), b(4, 5); Assert::IsTrue(a + b == Vector2D(6, 8)); }*/ TEST_METHOD(TestLineCross) { Line line(Vector2D(1, 1), Vector2D(10, 1), true); Circle circle(Vector2D(5, 2), 1); char buf[500]; for (const auto& p : circle.cross(line)) { sprintf_s(buf, "%.3lf, %.3lf\n", p.x, p.y); OutputDebugStringA(buf); } OutputDebugStringA("-------\n"); circle = Circle(Vector2D(5, 2), 2); for (const auto& p : circle.cross(line)) { sprintf_s(buf, "%.3lf, %.3lf\n", p.x, p.y); OutputDebugStringA(buf); } ; } }; TEST_CLASS(testDraw) { public: /*TEST_METHOD(TestDraw) { createWin(); BeginBatchDraw(); setCurrentColor(Color(0, 0, 127)); drawLine(Segment(Vector2D(100, 80), Vector2D(100, 280)), 10); drawCircle(Vector2D(100, 500), 120, 8); drawCircle(Vector2D(1300, 500), 120, 1.5); drawSolidCircle(Vector2D(500, 400), 120); drawDot(Vector2D(900, 180), 9); cleardevice(); //drawPolygon(std::vector<Vector2D>{ { 134, 154 }, { 725, 166 }, { 263, 532 }, { 484, 33 }, { 531, 568 } }, 1); drawSolidPolygon(std::vector<Vector2D>{ { 134, 154 }, { 725, 166 }, { 263, 532 }, { 484, 33 }, { 531, 568 } }); FlushBatchDraw(); EndBatchDraw(); while (!GetAsyncKeyState(VK_ESCAPE)); closegraph(); exit(0); }*/ /*TEST_METHOD(TestPolygonDraw) { createWin(); BeginBatchDraw(); cleardevice(); setCurrentColor(Color(0, 0, 127)); FlushBatchDraw(); MOUSEMSG mousemsg{}; std::vector<PolygonClass> polygons; PolygonClass cur_polygon; int lst_time = clock(), cur_time; PeekMouseMsg(&mousemsg, false); cur_polygon.vertices.push_back(Vector2D(mousemsg.x, mousemsg.y)); while (!GetAsyncKeyState(VK_ESCAPE)) { bool mousehit = PeekMouseMsg(&mousemsg); cur_polygon.vertices[cur_polygon.vertices.size() - 1] = Vector2D(mousemsg.x, mousemsg.y); if (mousehit) { if (mousemsg.uMsg == WM_LBUTTONDOWN) { cur_polygon.vertices.push_back(Vector2D(mousemsg.x, mousemsg.y)); } if (mousemsg.uMsg == WM_RBUTTONDOWN) { polygons.push_back(cur_polygon); cur_polygon.vertices = std::vector<Vector2D>(1); } } cur_time = clock(); if (cur_time - lst_time >= 100) { lst_time = cur_time; cleardevice(); for (auto p : polygons) drawSolidPolygon(p); drawSolidPolygon(cur_polygon); FlushBatchDraw(); } } EndBatchDraw(); closegraph(); }*/ }; }
4aba0296032899eed130ecbc6e8be801b524bb96
24428e5723e8da29838d104ee125fcd417e4092c
/BaseGraphics/ggGraphicsTextItem.cxx
7ef025f25ed4a38fea48a3765a596e57c31a2c0e
[]
no_license
TheGoofy/ggClassyArchitect
d606013151549f241149c415fbabae3630aeb79d
eec47e6013cd1b057e972a0450087eabeda566bd
refs/heads/master
2021-09-06T18:38:05.439918
2018-02-09T20:04:33
2018-02-09T20:04:33
112,534,809
2
0
null
2017-12-01T11:00:25
2017-11-29T22:23:33
C++
UTF-8
C++
false
false
6,691
cxx
ggGraphicsTextItem.cxx
// 0) include own header #include "ggGraphicsTextItem.h" // 1) include system or QT #include <QMimeData> #include <QClipboard> #include <QFont> #include <QKeyEvent> #include <QDebug> #include <QTextCursor> #include <QTextDocument> #include <QPainter> #include <QGraphicsSceneDragDropEvent> // 2) include own project-related (sort by component dependency) // goofy: eliminate that include (need clipboard in order to re-format mime-data) #include "ClassyMain/ggClassyApplication.h" ggGraphicsTextItem::ggGraphicsTextItem(QGraphicsItem* aParent) : QGraphicsTextItem(aParent), mSubjectText(new ggSubject()), mSubjectEditingFinished(new ggSubject()), mSuppressRichText(true), mSuppressLineBreaks(false), mEnterKeyFinishesEdit(false), mLastMousePressPos(0.0f, 0.0f), mBrush(Qt::NoBrush) { document()->setDocumentMargin(3.0f); setToolTip("Click twice in order to edit the text."); SetEditable(false); connect(document(), SIGNAL(contentsChanged()), this, SLOT(on_document_contentChanged())); } ggGraphicsTextItem::~ggGraphicsTextItem() { delete mSubjectText; delete mSubjectEditingFinished; } void ggGraphicsTextItem::dropEvent(QGraphicsSceneDragDropEvent* aEvent) { // accept only plain text: adjust mime-data if (mSuppressRichText) { aEvent->setMimeData(StripMimeData(aEvent->mimeData())); } // do inherited event handling QGraphicsTextItem::dropEvent(aEvent); } void ggGraphicsTextItem::keyPressEvent(QKeyEvent* aEvent) { // accept only plain text: adjust mime-data if (aEvent->matches(QKeySequence::Paste) && mSuppressRichText) { QClipboard* vClipboard = ggClassyApplication::GetInstance().clipboard(); vClipboard->setMimeData(StripMimeData(vClipboard->mimeData())); } // interpret <return> key ... if ((aEvent->key() == Qt::Key_Return) || (aEvent->key() == Qt::Key_Enter)) { // finish editing unless the shift key is pressed if (GetEnterKeyFinishesEdit()) { if (!(aEvent->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier))) { clearFocus(); aEvent->accept(); return; } } // don't do anything, if line breaks are suppressed if (GetSuppressLineBreaks()) { aEvent->accept(); return; } } // interpret the escape key if (aEvent->key() == Qt::Key_Escape) { setHtml(mHtmlBackup); clearFocus(); aEvent->accept(); } // do inherited event handling QGraphicsTextItem::keyPressEvent(aEvent); } void ggGraphicsTextItem::contextMenuEvent(QGraphicsSceneContextMenuEvent* aEvent) { // accept only plain text: adjust mime-data if (mSuppressRichText) { QClipboard* vClipboard = ggClassyApplication::GetInstance().clipboard(); vClipboard->setMimeData(StripMimeData(vClipboard->mimeData())); } // do inherited event handling QGraphicsTextItem::contextMenuEvent(aEvent); // the base event steals the focus. force it back SetEditable(true); } void ggGraphicsTextItem::mousePressEvent(QGraphicsSceneMouseEvent* aEvent) { // make it editable, if user clicks twice to the same position QPointF vPos = aEvent->pos(); if (vPos == mLastMousePressPos) SetEditable(true); mLastMousePressPos = vPos; // do inherited event handling QGraphicsTextItem::mousePressEvent(aEvent); } void ggGraphicsTextItem::focusInEvent(QFocusEvent* aEvent) { // remember previous text, in case user aborts editing with <esc> mHtmlBackup = toHtml(); // do inherited event handling QGraphicsTextItem::focusOutEvent(aEvent); } void ggGraphicsTextItem::focusOutEvent(QFocusEvent* aEvent) { // editing is finished now SetEditable(false); // do inherited event handling QGraphicsTextItem::focusOutEvent(aEvent); } void ggGraphicsTextItem::paint(QPainter* aPainter, const QStyleOptionGraphicsItem* aStyleOption, QWidget* aWidget) { aPainter->setPen(mPen); aPainter->setBrush(mBrush); aPainter->drawRect(boundingRect()); QGraphicsTextItem::paint(aPainter, aStyleOption, aWidget); } QMimeData* ggGraphicsTextItem::StripMimeData(const QMimeData* aMimeData) const { QString vText = aMimeData->text(); if (GetSuppressLineBreaks()) vText = vText.simplified(); QMimeData* vMimeData = new QMimeData(); vMimeData->setText(vText); return vMimeData; } void ggGraphicsTextItem::SetBrush(const QBrush& aBrush) { if (mBrush != aBrush) { mBrush = aBrush; update(); } } const QBrush& ggGraphicsTextItem::Brush() const { return mBrush; } void ggGraphicsTextItem::SetPen(const QPen& aPen) { if (mPen != aPen) { mPen = aPen; update(); } } const QPen& ggGraphicsTextItem::Pen() const { return mPen; } void ggGraphicsTextItem::SetSuppressRichText(bool aSuppressRichText) { if (mSuppressRichText != aSuppressRichText) { mSuppressRichText = aSuppressRichText; update(); } } bool ggGraphicsTextItem::GetSuppressRichText() const { return mSuppressRichText; } void ggGraphicsTextItem::SetSuppressLineBreaks(bool aSuppressLineBreaks) { if (mSuppressLineBreaks != aSuppressLineBreaks) { mSuppressLineBreaks = aSuppressLineBreaks; update(); } } bool ggGraphicsTextItem::GetSuppressLineBreaks() const { return mSuppressLineBreaks; } void ggGraphicsTextItem::SetEnterKeyFinishesEdit(bool aEnterKeyFinishesEdit) { if (mEnterKeyFinishesEdit != aEnterKeyFinishesEdit) { mEnterKeyFinishesEdit = aEnterKeyFinishesEdit; update(); } } bool ggGraphicsTextItem::GetEnterKeyFinishesEdit() const { return mEnterKeyFinishesEdit; } void ggGraphicsTextItem::SetEditable(bool aEditable) { if (aEditable) { setTextInteractionFlags(Qt::TextEditorInteraction); setCursor(Qt::IBeamCursor); setFocus(); } else { mSubjectEditingFinished->Notify(); setTextInteractionFlags(Qt::NoTextInteraction); unsetCursor(); } } void ggGraphicsTextItem::SetText(const QString& aText) { QSignalBlocker vSignalBlocker(document()); setPlainText(aText); } QString ggGraphicsTextItem::GetText() const { return toPlainText(); } const ggSubject* ggGraphicsTextItem::GetSubjectText() const { return mSubjectText; } const ggSubject* ggGraphicsTextItem::GetSubjectEditingFinished() const { return mSubjectEditingFinished; } void ggGraphicsTextItem::SetAlignment(Qt::Alignment aAlignment) { QTextOption vTextOption = document()->defaultTextOption(); vTextOption.setAlignment(aAlignment); document()->setDefaultTextOption(vTextOption); } Qt::Alignment ggGraphicsTextItem::GetAlignment() const { return document()->defaultTextOption().alignment(); } void ggGraphicsTextItem::on_document_contentChanged() { mSubjectText->Notify(); }
7f67ce73df9f709ddc8bbaddfaf92b86e73792b6
04cdc91f88a137e2f7d470b0ef713d72f79f9d47
/Vitis_Platform_Creation/Feature_Tutorials/03_Vitis_Export_To_Vivado/aie/hb27_2i.cc
406f09938dd6aab34cad658bfed477c37114b012
[ "MIT" ]
permissive
Xilinx/Vitis-Tutorials
80b6945c88406d0669326bb13b222b5a44fcc0c7
ab39b8482dcbd2264ccb9462910609e714f1d10d
refs/heads/2023.1
2023-09-05T11:59:43.272473
2023-08-21T16:43:31
2023-08-21T16:43:31
211,912,254
926
611
MIT
2023-08-03T03:20:33
2019-09-30T17:08:51
C
UTF-8
C++
false
false
3,744
cc
hb27_2i.cc
/* Copyright (C) 2023, Advanced Micro Devices, Inc. All rights reserved. SPDX-License-Identifier: MIT */ #include <adf.h> #include "include.h" #include "aie_api/aie.hpp" #include "aie_api/aie_adf.hpp" #include "aie_api/utils.hpp" /* // 27-tap FIR and 2x up-sampling Interpolation rate: 2x Coefficients: c0 0 c2 0 c4 0 c6 0 c8 0 c10 0 c12 c13 c12 0 c10 0 c8 0 c6 0 c4 0 c2 0 c0 Data is interpolated: d0 0 d1 0 d2 0 d3 0 d4 0 d5 0 d6 0 d7 0 d8 0 d9 0 d10 0 d11 0 d12 0 d13 ... Outputs: o0 = c0*(d0+d13) + c2*(d1+d12) + c4*(d2+d11) + c6*(d3+d10) + c8*(d4+d9) + c10*(d5+d8) + c12*(d6+d7) o1 = c13*d7 o2 = c0*(d1+d14) + c2*(d2+d13) + c4*(d3+d12) + c6*(d4+d11) + c8*(d5+d10) + c10*(d6+d9) + c12*(d7+d8) o3 = c13*d8 ... offset: 3 */ //static int16_t chess_storage(%chess_alignof(v16int16)) coeffs_27_i [INTERPOLATOR27_COEFFICIENTS] = {33, -158, 0, 0, 491, -1214, 2674, 0, 0, -5942, 20503, 32767, 0, 0, 0, 0}; alignas(aie::vector_decl_align) static int16_t coeffs_27_i [INTERPOLATOR27_COEFFICIENTS] = {33, -158,491, -1214, 2674, -5942, 20503, 0, 32767}; void fir_27t_sym_hb_2i ( input_window_cint16 *__restrict cb_input, output_window_cint16 *__restrict cb_output) { const int shift = 0 ; const unsigned output_samples = INTERPOLATOR27_OUTPUT_SAMPLES ; aie::vector<cint16, 32> sbuff; const unsigned LSIZE = (output_samples / 8 /2 ); const aie::vector<int16, 16> coe = aie::load_v<16>(coeffs_27_i); sbuff.insert(0, window_readincr_v<8>(cb_input)); // 0:7|X|X|X constexpr unsigned Lanes = 4; constexpr unsigned CoeffStep = 1; constexpr unsigned DataStep = 1; constexpr unsigned Hi_Points = 4; constexpr unsigned Lo_Points = 14; using mul_ops_hi = aie::sliding_mul_xy_ops <Lanes, Hi_Points, CoeffStep, DataStep, int16, cint16, cacc48>; using mul_ops_lo = aie::sliding_mul_sym_ops<Lanes, Lo_Points, CoeffStep, DataStep, DataStep, int16, cint16, cacc48>; constexpr unsigned Lo_Points_A = 8; constexpr unsigned Lo_Points_B = 6; using mul_ops_lo2_a = aie::sliding_mul_sym_ops<Lanes, Lo_Points_A, CoeffStep, DataStep, DataStep, int16, cint16, cacc48>; using mul_ops_lo2_b = aie::sliding_mul_sym_ops<Lanes, Lo_Points_B, CoeffStep, DataStep, DataStep, int16, cint16, cacc48>; const int sft = shift+15; for (unsigned int l = 0; l < LSIZE; ++l) chess_prepare_for_pipelining chess_loop_range(6, ) { aie::accum<cacc48, 4> acc1a, acc1b; aie::accum<cacc48, 4> acc2a, acc2b; sbuff.insert(1, window_readincr_v<8>(cb_input)); // 0:7|8:15|X|X acc1a = mul_ops_hi::mul( coe, 8, sbuff, 10); //d10..d13 // printf("%u",acc1a); // printf("%u",sbuff); sbuff.insert(2, window_readincr_v<8>(cb_input)); // 0:7|8:15|16:23|X acc1b = mul_ops_lo::mul_sym(coe, 0, sbuff, 3); //d7..d15 window_decr(cb_input, 16); acc2a = mul_ops_hi::mul( coe, 8, sbuff, 14); //d14..d17 acc2b = mul_ops_lo2_a::mul_sym( coe, 0, sbuff, 7, 20); //d7..d23 sbuff.insert(0, window_readincr_v<8>(cb_input)); // 8:15|8:15|16:23|X for next iteration acc2b = mul_ops_lo2_b::mac_sym(acc2b, coe, 4, sbuff, 11); //d11..d19 window_writeincr(cb_output, aie::concat(acc1b, acc1a).to_vector_zip<cint16>(sft)); window_writeincr(cb_output, aie::concat(acc2b, acc2a).to_vector_zip<cint16>(sft)); } window_incr(cb_input, 8); }
9403cacb26163277256c1019c52d684391eef3a2
e8cd536ef02e8635517c4e70798164a1fef65204
/subProj/SubSpectrumEditor/spectrumeditorcustom.h
51cfc4a31a24a082b44ddb612d8fb3a23fe2f837
[]
no_license
DawidMaciazek/Polichromator
1b205c233be3f7687a7aab1d092dd140c40f7df7
092a98d2e9b572630a305ebc1a88f1ef271e03f7
refs/heads/master
2020-12-14T09:43:32.279376
2016-10-24T06:35:51
2016-10-24T06:35:51
68,298,166
0
0
null
null
null
null
UTF-8
C++
false
false
785
h
spectrumeditorcustom.h
#ifndef SPECTRUMEDITORCUSTOM_H #define SPECTRUMEDITORCUSTOM_H #include <QWidget> #include "spectrum.h" #include "spectrumeditorcustomitem.h" #include "expparser.h" namespace Ui { class SpectrumEditorCustom; } class SpectrumEditorCustom : public QWidget { Q_OBJECT public: explicit SpectrumEditorCustom(Spectrum templateSpectrum, QWidget *parent = 0); ~SpectrumEditorCustom(); void initializePlot(); void updatePlot(); Spectrum combinedSpectrum; private slots: void on_buttonAddFunction_clicked(); void deleteItemSlot(SpectrumEditorCustomItem *item); void updatePlotSlot(); void on_comboMerge_currentIndexChanged(int index); private: Ui::SpectrumEditorCustom *ui; Spectrum templateSpectrum; }; #endif // SPECTRUMEDITORCUSTOM_H
94228728bcd15ab75c06bcb67bd8ea7e3e1b4886
1cc5d45273d008e97497dad9ec004505cc68c765
/cheatsheet/ops_doc-master/Qt/pro/sstd_introduce_qmake/simple_library/the_app/main.cpp
c3fb346e5d41b661c1ba08fc2c1e99bf79d6272c
[]
no_license
wangfuli217/ld_note
6efb802989c3ea8acf031a10ccf8a8a27c679142
ad65bc3b711ec00844da7493fc55e5445d58639f
refs/heads/main
2023-08-26T19:26:45.861748
2023-03-25T08:13:19
2023-03-25T08:13:19
375,861,686
5
6
null
null
null
null
UTF-8
C++
false
false
118
cpp
main.cpp
#include <TheLib.hpp> int main(int ,char ** ) { sstd::TheLib varTestLib; varTestLib.printHellowWorld(); }
bc032711027dbfc57d89e4f060a1e7c809615895
df8464ba771a8a5de42fd82b4801d1f039d754ad
/discrete_math/4 term/lab1/B.cpp
6f68bc9a278906aebe2f0f99c0780e45fe877815
[]
no_license
nowiwr01w/itmo
b13c135158de109acdaa9ee324cf5ea5e9c5343f
64c775a7779777e120bc5e6a098b49ee8eebc876
refs/heads/master
2022-12-17T04:50:24.002941
2020-09-13T12:27:33
2020-09-13T12:27:33
220,715,265
1
0
null
null
null
null
UTF-8
C++
false
false
8,897
cpp
B.cpp
#include <vector> #include <iostream> using namespace std; const int MODULE = 998244353; const vector<uint64_t> square_precomputed { 1, 499122177, 124780544, 935854081, 38993920, 970948609, 20471808, 982159361, 13069056, 987353473, 9257248, 990249457, 6995534, 992055996, 255086407, 868491022, 897467357, 972688749, 356174088, 565110919, 750033950, 729603265, 794821570, 993091755, 379172193, 781576701, 127379568, 545193310, 18787235, 963217762, 382660785, 875610143, 709593316, 230155792, 778242493, 353179545, 285438990, 238744826, 7105606, 223531768, 683270591, 35628676, 250856449, 187371579, 715167269, 872587793, 512176419, 831622234, 379781130, 243014835, 912256616, 171539070, 505304410, 639084605, 681931206, 734209012, 461959574, 338284904, 909663730, 382418000, 625386803, 216406968, 593864453, 252145471, 276282717, 674585772, 792737509, 916066078, 146425807, 442683396, 593568297, 353947223, 506093729, 946973666, 407710813, 179425128, 664742981, 119577194, 919360734, 83703831, 285968221, 70561611, 387243336, 329350421, 157827221, 191407476, 554810545, 676743931, 327363987, 536194878, 371161621, 320563813, 471322723, 647228617, 918873943, 78117193, 780969629, 172750090, 369760888, 59339154, 670269311, 441707415, 284111419, 965408644, 603473069, 360610427, 977054588, 408062251, 776088197, 319839217, 288006313, 538762766, 707345352, 503471020, 869172187, 370439415, 645503435, 578582680, 207064392, 433079872, 770226850, 443814603, 195772768, 926596174, 74806646, 141711814, 121420181, 544200119, 316144075, 883103744, 33184635, 100548595, 411059865, 550539720, 185682341, 404235804, 466346456, 143535303, 42483059, 916720867, 601163147, 53029073, 400958986, 992412096, 16169883, 8092945, 706487016, 543434393, 800934902, 861935954, 963488128, 883910298, 234702604, 511388312, 595550795, 70341930, 448653618, 808207006, 27124138, 123810143, 585480165, 576325997, 639843783, 453089581, 260173233, 368363436, 957939593, 464346029, 849995631, 406830843, 87072979, 868152525, 1274889, 342062980, 762396849, 387840797, 3985904, 435952166, 840763544, 895085030, 526553512, 310599679, 226733969, 503351944, 433892929, 948281512, 250818857, 58139852, 122857583, 250478466, 996677478, 542488028, 740750737, 58946850, 152478092, 48343687, 754186931, 642510304, 935348300, 817375606, 421586487, 170076874, 903557482, 327566558, 41843620, 274979055, 664694493, 143057809, 426685184, 197294690 }; const vector<uint64_t> exponent_precomputed { 1, 1, 499122177, 166374059, 291154603, 856826403, 641926577, 376916469, 421456191, 712324701, 370705776, 305948985, 275056837, 405098354, 314148269, 154042465, 945481735, 407938109, 632701444, 33300076, 400962745, 637054254, 664203418, 419495765, 475007652, 657876692, 178879004, 856981449, 707986577, 403057740, 13435258, 676663441, 489072773, 529067478, 837644393, 280624102, 285085212, 574276125, 724391412, 632878356, 714593006, 845241488, 352872915, 936805745, 996848021, 199617841, 416657838, 454889133, 71867129, 470030352, 328838800, 730664311, 263612325, 927878974, 534791127, 118622859, 661672570, 81660526, 448896788, 836658815, 97131343, 934378024, 176077767, 478149339, 584581100, 316145664, 458537519, 453818927, 256234896, 90517406, 400590847, 286837717, 600157568, 350085841, 692710106, 315364403, 490136914, 265649662, 54597783, 670399348, 557414386, 795617938, 131439774, 675097874, 887442619, 210089372, 838182358, 21108353, 442643615, 745244617, 684868335, 961891506, 292567877, 604239265, 590507220, 951921042, 820989381, 512731574, 453423297, 579326782, 65687929, 119253665, 754745773, 462837188, 964300697, 113761796, 584951997, 42784387, 9639155, 796852274, 751389902, 240592280, 643876658, 880266085, 489330750, 4255050, 17247791, 989859767, 16848340, 310520079, 476753735, 540187080, 37157086, 519713786, 342306263, 234331140, 382143334, 828329137, 622575258, 399480909, 517552712, 392580265, 418909240, 783731744, 393227150, 150800846, 250669918, 366152464, 291999468, 59553628, 741978331, 670758493, 461666489, 191708140, 361808434, 911241814, 60939703, 292418006, 42445163, 140977024, 945944501, 845847532, 294530257, 86743182, 674702311, 345688084, 872480257, 380693612, 697389699, 381082081, 395440477, 14856703, 893582024, 127966068, 609465862, 826489078, 341735981, 486224722, 561435678, 546745066, 754835425, 62791105, 157066213, 704872123, 147476902, 805142461, 475337635, 549745988, 238629263, 860157875, 698003900, 836645863, 251415614, 568682122, 35642110, 485825048, 496367234, 766017699, 561604653, 478325907, 848398246, 662969564, 856120018, 769928934, 487654114, 38335203, 942416023, 592582543, 824779859, 977307459, 988157225, 223437357, 174069256, 704054245, 37704729, 229049704, 68953741, 742988329, 958623147, 974173334 }; const vector<uint64_t> logarithm_precomputed { 0, 1, 499122176, 332748118, 249561088, 598946612, 831870294, 855638017, 124780544, 443664157, 698771047, 272248460, 415935147, 460728163, 71303168, 865145106, 62390272, 939524097, 277290098, 105078353, 848507700, 617960790, 862120123, 217009642, 707089750, 319438193, 268758095, 480636170, 35651584, 481911067, 565671800, 128805723, 31195136, 756245722, 29360128, 370776474, 138645049, 242816194, 446583000, 486324172, 424253850, 97389693, 689263958, 510729669, 930182238, 288381702, 889739532, 191153174, 353544875, 692659347, 339403080, 313174699, 633501224, 828731161, 757926268, 54449692, 17825792, 700522353, 258166643, 727534020, 282835900, 654586461, 434719315, 205986930, 15597568, 890741115, 620121492, 432075914, 14680064, 405084665, 812856116, 702988981, 568444701, 382888245, 876836256, 771975633, 223291500, 894530654, 755082267, 404352143, 212126925, 825708292, 450427330, 60135202, 344631979, 387553690, 243757342, 493385140, 465091119, 392568004, 854053502, 65818309, 444869766, 42935241, 902667766, 819611153, 675894614, 699800165, 152792503, 584830025, 169701540, 889524671, 342534827, 38766771, 316750612, 123592158, 84756596, 802327237, 378963134, 622757945, 971019507, 413686849, 8912896, 150178354, 148861000, 243050799, 628205498, 494856175, 634477343, 989855745, 141417950, 24749860, 171828946, 32463231, 716481834, 862483121, 895250888, 322267862, 7798784, 170243223, 53751619, 922042494, 310060746, 728042874, 782206396, 96127234, 7340032, 276885295, 296579844, 854612072, 406428058, 729213960, 147627686, 404882325, 783344527, 296031084, 307678054, 230886449, 438418128, 442175351, 113134360, 323933598, 111645750, 437139684, 550979026, 824356627, 876663310, 953736643, 296946105, 608991838, 605185639, 601426722, 585390207, 202098550, 225213665, 350898015, 968176752, 436358310, 671438166, 572956818, 804467508, 233507451, 121878671, 957852963, 751551783, 473453036, 731667736, 242511340, 801960351, 117112466, 427026751, 193030676, 466213022, 218195487, 222434883, 447860980, 477654556, 720657688, 451333883, 68662310, 89316600, 789187944, 337947307, 920660595, 149222094, 296913705, 575518428, 719546691, 206707164, 837722648, 84850770, 809521540, 54359841, 924482455, 670389590, 818073421, 479738791, 800524457, 158375306, 644798984 }; vector<uint64_t> multiply(const vector<uint64_t> &first, const vector<uint64_t> &second) { vector<uint64_t> result(200, 0); for (int i = 0; i < 200; i++) { for (int j = 0; j <= i; j++) { result[i] += first[j] * second[i - j] % MODULE; result[i] %= MODULE; } } return result; } int main() { int n, m; cin >> n >> m; vector<uint64_t> coeff_base(200); vector<vector<uint64_t>> precomputed { square_precomputed, exponent_precomputed, logarithm_precomputed }; for (int i = 0; i <= n; i++) { cin >> coeff_base[i]; } for (auto coefficients : precomputed) { vector<uint64_t> result(200, 0); vector<uint64_t> coeff_power(200, 0); coeff_power[0] = 1; for (int i = 0; i < 200; i++) { for (uint64_t j = 0; j < coeff_power.size(); j++) { result[j] += coefficients[i] * coeff_power[j] % MODULE; result[j] %= MODULE; } coeff_power = multiply(coeff_power, coeff_base); } for (int i = 0; i < m; i++) { cout << result[i] << " "; } cout << endl; } return 0; }
1f0493af7133d3d5499521c9e2f5a8df2a8eec1d
71e7675390503901564239473b56ad26bdfa13db
/src/iofwdutil/completion/BMIResource.hh
bc6ca6025fe70dd346cedd4b2f90c7af13f30b3b
[]
no_license
radix-io-archived/iofsl
1b5263f066da8ca50c7935009c142314410325d8
35f2973e8648ac66297df551516c06691383997a
refs/heads/main
2023-06-30T13:59:18.734208
2013-09-11T15:24:26
2013-09-11T15:24:26
388,571,488
0
0
null
null
null
null
UTF-8
C++
false
false
3,668
hh
BMIResource.hh
#ifndef IOFWDUTIL_COMPLETION_BMIRESOURCE_HH #define IOFWDUTIL_COMPLETION_BMIRESOURCE_HH extern "C" { #include <bmi.h> } #include <boost/thread.hpp> #include "Resource.hh" #include "ContextBase.hh" #include "IDAllocator.hh" #include "iofwdutil/assert.hh" #include "BMICompletionID.hh" namespace iofwdutil { namespace completion { //=========================================================================== class BMIResource : public Resource { public: BMIResource (); void postSend (BMICompletionID * id, BMI_addr_t dest, const void * buffer, bmi_size_t size, bmi_buffer_type buffer_type, bmi_msg_tag_t tag, bmi_hint hints); void postReceive (BMICompletionID * id, BMI_addr_t src, void * buffer, bmi_size_t expected_size, bmi_buffer_type buffer_type, bmi_msg_tag_t tag, bmi_hint hints); void postSendUnexpected (BMICompletionID * id, BMI_addr_t dest, const void * buffer, bmi_size_t size, bmi_buffer_type buffertype, bmi_msg_tag_t tag, bmi_hint hints); void postSendList (BMICompletionID * id, BMI_addr_t dest, const void * const * buffer_list, const bmi_size_t * size_list, int list_count, bmi_size_t total_size, bmi_buffer_type buffer_type, bmi_msg_tag_t tag, bmi_hint hints); void postReceiveList (BMICompletionID * id, BMI_addr_t dest, void * const * buffer_list, const bmi_size_t * size_list, int list_count, bmi_size_t total_size, bmi_buffer_type buffer_type, bmi_msg_tag_t tag, bmi_hint hints); void postSendUnexpectedList (BMICompletionID * id, BMI_addr_t dest, const void * const * buffer_list, const bmi_size_t * size_list, int list_count, bmi_size_t total_size, bmi_buffer_type buffer_type, bmi_msg_tag_t tag, bmi_hint hints); /// Returns true if there are any requests to be completed virtual bool isActive () const ; /// Returns vector of completed operations ; will append virtual void waitAny (std::vector<CompletionID *> & completed) ; /// Test for completion virtual void testAny (std::vector<CompletionID *> & completed, int maxms) ; /// Test for single item completion virtual bool test (CompletionID * id, int maxms) ; /// Wait for single item virtual void wait (CompletionID * id) ; virtual ~BMIResource (); protected: bool testInternal (CompletionID * id, int maxms); bool testAnyInternal (std::vector<CompletionID *> & c, int maxms); protected: BMICompletionID * castCheck (CompletionID * p) { checkCompletionType (p); return static_cast<BMICompletionID *> (p); } inline void checkCompletionType (CompletionID * p) { #ifndef NDEBUG dynamic_cast<BMICompletionID &> (*p); #endif } /// Called when a BMI post indicates the operation completed before /// returning void quickComplete (BMICompletionID * id) { id->completed_ = true; } protected: int handleBMIError (int ret) const; /// Do a quick check for BMI failure inline int checkBMI (int ret) const { if (ret >= 0) return ret; return handleBMIError (ret); } protected: /// BMI Context bmi_context_id bmictx_; /// Lock for operation counter (outstanding_) boost::mutex lock_; /// Reusable arrays for testcontext (need to have lock) std::vector<bmi_op_id_t> opsarray_; std::vector<bmi_size_t> actualarray_; std::vector<void *> userarray_; std::vector<bmi_error_code_t> errorarray_; unsigned int outstanding_; }; //=========================================================================== } } #endif
c145a573cc9629bd6de2012961f48b14b15309ad
079dc0044cd3cf48223e2012b1588c3332ca32ba
/Packet/packetBuffer.cpp
82e6ee8ab8644842ff6b9cc2fa31699c0490abc0
[]
no_license
3dElf/packet-manipulation-library
dddfdcfce3b35c0b224638960bf8e11e2d74aacf
ab4c12e5a745184daac408b6ec2a237cc520bba8
refs/heads/master
2023-03-17T06:42:24.080775
2013-08-26T20:19:31
2013-08-26T20:19:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,578
cpp
packetBuffer.cpp
/* * PacMan - Packet Manipulation Library * Copyright © 2011 Jeff Scaparra * * This file is a part of PacMan. * * 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/>. */ /** \file packetBuffer.cpp * This is the definition for the class PacketBuffer */ #include "packetBuffer.h" #include <iostream> PacketBuffer::PacketBuffer() { buff_ = NULL; size_ = 0; } PacketBuffer::PacketBuffer( std::vector< uint8_t > buff ) { size_ = buff.size(); if( size_ == 0 ) { buff_ = NULL; } else { buff_ = new uint8_t[ size_ ]; for( int i=0; i < size_; ++i ) { buff_[i] = buff[i]; } } } PacketBuffer::PacketBuffer( const uint8_t* buff, int size ) { size_ = size; buff_= new uint8_t[ size ]; for( int i = 0; i < size_; ++i ) { buff_[i] = buff[i]; } } PacketBuffer::~PacketBuffer() { if( buff_ ) delete [] buff_; } PacketBuffer::PacketBuffer( const PacketBuffer& n ) { size_ = n.size_; if( n.size_ > 0 ) { buff_ = new uint8_t[ n.size_ ]; for( int i = 0; i < size_; ++i ) { buff_[i] = n.buff_[i]; } } else { buff_ = NULL; } } PacketBuffer& PacketBuffer::operator=( const PacketBuffer &n ) { if( buff_ ) delete [] buff_; if( n.size_ > 0 ) { buff_ = new uint8_t[ n.size_ ]; size_ = n.size_; for( int i = 0; i < size_; ++i ) { buff_[i] = n.buff_[i]; } } else { size_ = 0; buff_ = NULL; } return *this; } PacketBuffer& PacketBuffer::operator+=( const PacketBuffer &n ) { int newSize = size_ + n.size_; uint8_t* newBuff = new uint8_t[ newSize ]; for( int i = 0; i < size_; ++i ) { newBuff[i] = buff_[i]; } for( int i = size_; i < size_ + n.size_; ++i ) { newBuff[ i ] = n.buff_[ i - size_ ]; } if( buff_ ) delete [] buff_; buff_ = newBuff; size_ = newSize; return *this; } PacketBuffer PacketBuffer::operator+( const PacketBuffer &n ) { PacketBuffer result; result.size_ = size_ + n.size_; result.buff_ = new uint8_t [ result.size_ ]; for( int i = 0; i < size_; ++i ) { result.buff_[i] = buff_[i]; } for( int i = 0; i < n.size_; ++i ) { result.buff_[size_ + i ] = n.buff_[i]; } return result; } void PacketBuffer::setBuffer( std::vector< uint8_t > buff ) { if( buff_ ) delete [] buff_; size_ = buff.size(); buff_ = new uint8_t[ size_ ]; for( int i = 0; i < size_; ++i ) buff_[i] = buff[i]; } void PacketBuffer::setBuffer( uint8_t* buff, int size ) { if( buff_ ) delete [] buff_; size_ = size; if( size_ > 0 ) { buff_ = new uint8_t[ size_ ]; for( int i = 0; i < size_; ++i ) buff_[i] = buff[i]; } else { buff_ = NULL; } } uint8_t* PacketBuffer::buffer() const { return buff_; } int PacketBuffer::size() const { return size_; } std::vector< uint8_t > PacketBuffer::vector() const { std::vector< uint8_t > vector; for( int i = 0; i < size_; ++i ) { vector.push_back( buff_[i] ); } return vector; }
697b862effc300447a75164173d48a641221a08a
1b0730016881aafc0d7fbdefc58680c96e3a9a78
/src/agents.cpp
48c2bde3ec2bd57d511329102c6740ba6a5d59ce
[]
no_license
dstreett/shybold_2.0
0d9cca91bd50b8d5ae23ef79c1bdd51b1922a616
ed6f01d9e3a25bdaebee2afbf33310ffac8c532c
refs/heads/master
2021-01-16T17:59:09.559871
2017-03-02T00:52:35
2017-03-02T00:52:35
68,311,748
0
1
null
2017-02-24T18:48:17
2016-09-15T16:34:15
C++
UTF-8
C++
false
false
4,860
cpp
agents.cpp
#include <iostream> #include <algorithm> #include <fstream> #include <cmath> #include "agents.h" #define PI 3.14159 void agent::updatePrey() { std::vector<double> inputs; if (input_agent.size() != 0 && input_agent[0]) { //change this (loop througth input_agents and push_back onto inputs saw_last = true; inputs = { g->getRadius() / std::max(0.01, this->distance(input_agent[0])), atan2(input_agent[0]->y - y, input_agent[0]->x - x) , double(saw_last), double(!saw_last), angle_facing, 1.0 } ; } else { saw_last = false; inputs = { 0.0, 0.0, double(saw_last), double(!saw_last), angle_facing, 1.0 } ; } n->update(g, inputs); move_mag_theta(n->output_values[0], n->output_values[1], n->output_values[2], pred_capture); } void agent::updatePred(int time) { std::vector<double> inputs; if (input_agent.size() != 0 && input_agent[0]) { //change this (loop througth input_agents and push_back onto inputs saw_last = true; inputs = { g->getRadius() / std::max(0.01, this->distance(input_agent[0])) , atan2(input_agent[0]->y - y, input_agent[0]->x - x) , double(saw_last), double(!saw_last), angle_facing, 1.0 } ; } else { //make appropariate number of inputs saw_last = false; inputs = { 0.0, 0.0, double(saw_last), double(!saw_last), angle_facing, 1.0 } ; } //you hand it chrome 1 values and chrome 2 values from genome n->update(g, inputs); move_mag_theta(n->output_values[0], n->output_values[1], n->output_values[2], pred_capture); consume(time); } //Need to change to get sorted vector of agents inputs void agent::getNearestAgentPrey(const std::shared_ptr<agent> &a) { if (a->alive && valid_agent(a)) { input_agent[0] = a; } /* if (input_agent.size() == 0) { if (this->distance(a) < sensing_range_prey ) { input_agent.push_back(a); } } else if (!input_agent[0] || this->distance(a) < this->distance(input_agent[0])) { //change it here, sort the input_agents and push them appropriately on if (this->distance(a) < sensing_range_prey) { input_agent[0] = a; } }*/ } void agent::getNearestAgentPred(const std::shared_ptr<agent> &a) { if (valid_agent(a)) { input_agent[0] = a; } /*if (input_agent.size() == 0) { if (this->distance(a) < sensing_range_pred) { input_agent.push_back(a); } } else if ( !input_agent[0] || this->distance(a) < this->distance(input_agent[0]) || !input_agent[0]->alive ) { //same thing here if (this->distance(a) < sensing_range_pred) { input_agent[0] = a; } }*/ } //figure out what you want to do here void agent::consume(int time) { if (input_agent[0]) { if (this->distance(input_agent[0]) < pred_capture) { input_agent[0]->alive = false; input_agent[0]->lastTime = time; ++fitness; } /*if (this->distance(input_agent[0]) < pred_capture && input_agent[0]->alive) { input_agent[0]->alive = false; input_agent[0]->lastTime = time; ++fitness; }*/ } } void agent::move_x_y(double dx, double dy) { x = std::max(0.0, std::min(x + dx, sizeX)); y = std::max(0.0, std::min(y + dy, sizeY)); } void agent::move_mag_theta(double mag, double theta, double direction_facing, double move) { /*std::cout << "X " << sin(theta) * mag << '\n'; std::cout << "Y " << cos(theta) * mag << '\n'; std::cout << "Theta " << theta << '\n'; std::cout << "Mag " << mag << '\n';*/ direction_facing = std::fmod(direction_facing, 2 * PI); if (direction_facing < 0 ) { direction_facing += 2 * PI; } x = std::max(0.0, std::min(cos(theta) * mag * move + x, sizeX)); y = std::max(0.0, std::min(sin(theta) * mag * move + y, sizeY)); //angle_facing = std::fmod(angle_facing + direction_facing, 2 * PI); angle_facing = direction_facing; } void agent::output_data(std::fstream &o, bool prey, int gen, int index) { o << gen << '\t'; o << index << '\t'; if (prey) { o << lastTime << '\t'; } else { o << fitness << '\t'; } for (int i = 0; i < geneNN; ++i) { o << g->getWeight(i) << '\t'; } o << ((g->c1)->metabolic + (g->c2)->metabolic)/2.0 << '\t'; o << ((g->c1)->radius + (g->c2)->radius) /2.0 << '\t'; if (prey) { o << calcFitnessPrey() << '\n'; } else { o << calcFitnessPred() << '\n'; } }
acaf5ae836e7661b751d8c6182c33be1846c80d1
511a5bf496b106ba90984e0348292d8aa0b794d4
/sem_01/lab_01/trash/cxx/inc/Monomial.h
83b1ccfdc82312962546be9e227c0670aad38fbf
[]
no_license
rflban/MathModeling
936b8c0114d982ee5ff4836bd800a4da0b5fcddb
6c04b86cb7bd9a619a8f0c9b936fcb42014545bd
refs/heads/master
2022-07-14T11:12:56.960095
2021-10-05T12:03:01
2021-10-05T12:03:01
240,927,065
0
0
null
2022-06-22T04:34:01
2020-02-16T16:42:40
TeX
UTF-8
C++
false
false
580
h
Monomial.h
#ifndef MMLAB01_MONOMIAL_H_ #define MMLAB01_MONOMIAL_H_ #include <string> template <typename _T> struct Node; class Monomial { public: Monomial(int power=1); Monomial(const Monomial &other); ~Monomial(); double operator()(double x); Monomial &operator*=(double r); Monomial &operator*=(const Monomial &m); Monomial &integrate(); operator std::string() const; int getPower() { return power; } private: int power; int sign; Node<double> *ratiosAboveOne; Node<double> *ratiosBelowOne; }; #endif // MMLAB01_MONOMIAL_H_
2f9bb66b0813608038f8764bb3b64f520d17c2da
af09dc0fd61b78d622b8c4dd641288ef8162947c
/deferred_shading_dx11/profilemarker.cpp
e3d150e2695d32fabd312a8d79f7d7c3de00ec44
[ "LicenseRef-scancode-other-permissive" ]
permissive
alex-leleka/DeferredShadingOptimization
d6eb8d42bc9fd8911d5e3d6d5b0273bb7e942c1f
9913cd073c2a7004724ad90b3545a05b284f6be5
refs/heads/master
2020-09-14T05:26:02.657643
2019-12-11T00:11:41
2019-12-11T00:11:41
223,032,616
1
0
null
null
null
null
UTF-8
C++
false
false
924
cpp
profilemarker.cpp
#include "profilemarker.h" #include <d3d11_1.h> #include <stdexcept> void CProfileMarker::Init(ID3D11DeviceContext* d3dDeviceContext) { HRESULT hr = d3dDeviceContext->QueryInterface(__uuidof(m_pPerf), reinterpret_cast<void**>(&m_pPerf)); if (FAILED(hr)) { throw std::runtime_error("Error when QueryInterface ID3DUserDefinedAnnotation!!!"); } } void CProfileMarker::BeginEvent(_In_ LPCWSTR Name) { if (!m_pPerf) return; m_pPerf->BeginEvent(Name); } void CProfileMarker::EndEvent() { if (!m_pPerf) return; m_pPerf->EndEvent(); } void CProfileMarker::SetMarker(_In_ LPCWSTR Name) { if (!m_pPerf) return; m_pPerf->SetMarker(Name); } CProfileMarker::CScopedMarker::CScopedMarker(LPCWSTR Name, CProfileMarker * pPerf) : m_pPerf(pPerf) { m_pPerf->SetMarker(Name); } CProfileMarker::CScopedMarker::~CScopedMarker() { m_pPerf->EndEvent(); }
1c01f0819679c22e4416deb79ec8a91f0c98a9d6
ba2d4b40fa527cd1a281f9b0fe56a970318a68ad
/FY‘s code/search.cpp
1a6ffcdf1f17360a0cf38abe519e2a95f2513d74
[]
no_license
EventideX/Algorithm-and-Data-Structure
c0f7823bde721c19d5d077be698aee56f34a2edc
1d517cc38e87079984a70ee7e5cb24d63ba4d053
refs/heads/master
2021-08-29T02:05:56.712961
2017-12-13T11:17:54
2017-12-13T11:17:54
108,253,215
0
0
null
null
null
null
UTF-8
C++
false
false
1,223
cpp
search.cpp
#include<stdio.h> #include<string.h> struct TreeNode { int p,son[2],x,FirstTime; }; TreeNode tree[100001]; int n,m; void InitializationSearch(int CurrentNode,int &Time){ tree[CurrentNode].FirstTime=Time; int NextNode=0; if (tree[CurrentNode].son[NextNode]!=0){ if (tree[CurrentNode].son[NextNode^1]!=0){ if (tree[tree[CurrentNode].son[NextNode^1]].x>tree[tree[CurrentNode].son[NextNode]].x){ ++Time; InitializationSearch(tree[CurrentNode].son[NextNode^1],Time); ++Time; InitializationSearch(tree[CurrentNode].son[NextNode],Time); }else{ ++Time; InitializationSearch(tree[CurrentNode].son[NextNode],Time); ++Time; InitializationSearch(tree[CurrentNode].son[NextNode^1],Time); }; }else{ ++Time; InitializationSearch(tree[CurrentNode].son[NextNode],Time); }; }; ++Time; } int main(){ scanf("%d",&n); memset(tree,0,sizeof(tree)); for (int i=2;i<=n;++i){ scanf("%d %d",&tree[i].p,&tree[i].x); if (tree[tree[i].p].son[0]!=0) tree[tree[i].p].son[1]=i; else tree[tree[i].p].son[0]=i; }; int Time=0; InitializationSearch(1,Time); scanf("%d",&m); for (int j=1;j<=m;++j){ int kj; scanf("%d",&kj); printf("%d\n",tree[kj].FirstTime); }; return 0; }
da2517b88956affc207cc7296d6c3c867317d78c
c7ad1dd84604e275ebfc5a7e354b23ceb598fca5
/src/objtools/cleanup/cleanup.cpp
45c7e4f19fa1fe32679414576b4d57e49cdf8771
[]
no_license
svn2github/ncbi_tk
fc8cfcb75dfd79840e420162a8ae867826a3d922
c9580988f9e5f7c770316163adbec8b7a40f89ca
refs/heads/master
2023-09-03T12:30:52.531638
2017-05-15T14:17:27
2017-05-15T14:17:27
60,197,012
1
1
null
null
null
null
UTF-8
C++
false
false
131,031
cpp
cleanup.cpp
/* $Id$ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Robert Smith * * File Description: * Basic Cleanup of CSeq_entries. * */ #include <ncbi_pch.hpp> #include <corelib/ncbistd.hpp> #include <serial/serialbase.hpp> #include <objects/seq/Bioseq.hpp> #include <objects/seq/Seq_annot.hpp> // included for GetPubdescLabels and GetCitationList #include <objects/pub/Pub.hpp> #include <objects/pub/Pub_equiv.hpp> #include <objects/seq/Pubdesc.hpp> #include <objects/biblio/Author.hpp> #include <objects/biblio/Auth_list.hpp> #include <objects/general/Person_id.hpp> #include <objects/general/Name_std.hpp> #include <objects/misc/sequence_macros.hpp> #include <objects/seqset/Seq_entry.hpp> #include <objects/seqset/Bioseq_set.hpp> #include <objects/seqset/seqset_macros.hpp> #include <objects/seqfeat/Org_ref.hpp> #include <objects/seqfeat/Seq_feat.hpp> #include <objects/seqfeat/SeqFeatXref.hpp> #include <objects/general/Object_id.hpp> #include <objects/general/User_object.hpp> #include <objects/submit/Seq_submit.hpp> #include <objects/taxon3/taxon3.hpp> #include <objmgr/object_manager.hpp> #include <objmgr/util/sequence.hpp> #include <objmgr/util/feature.hpp> #include <objmgr/seq_annot_ci.hpp> #include <objmgr/seqdesc_ci.hpp> #include <objmgr/seq_vector.hpp> #include <objmgr/seq_vector_ci.hpp> #include <objtools/cleanup/cleanup.hpp> #include "cleanup_utils.hpp" #include <util/strsearch.hpp> #include "newcleanupp.hpp" BEGIN_NCBI_SCOPE BEGIN_SCOPE(objects) enum EChangeType { eChange_UNKNOWN }; // *********************** CCleanup implementation ********************** CCleanup::CCleanup(CScope* scope, EScopeOptions scope_handling) { if (scope && scope_handling == eScope_UseInPlace) { m_Scope = scope; } else { m_Scope = new CScope(*(CObjectManager::GetInstance())); if (scope) { m_Scope->AddScope(*scope); } } } CCleanup::~CCleanup(void) { } void CCleanup::SetScope(CScope* scope) { m_Scope.Reset(new CScope(*(CObjectManager::GetInstance()))); if (scope) { m_Scope->AddScope(*scope); } } static CRef<CCleanupChange> makeCleanupChange(Uint4 options) { CRef<CCleanupChange> changes; if (! (options & CCleanup::eClean_NoReporting)) { changes.Reset(new CCleanupChange); } return changes; } #define CLEANUP_SETUP \ CRef<CCleanupChange> changes(makeCleanupChange(options)); \ CNewCleanup_imp clean_i(changes, options); \ clean_i.SetScope(*m_Scope); CConstRef<CCleanupChange> CCleanup::BasicCleanup(CSeq_entry& se, Uint4 options) { CLEANUP_SETUP clean_i.BasicCleanupSeqEntry(se); return changes; } CConstRef<CCleanupChange> CCleanup::BasicCleanup(CSeq_submit& ss, Uint4 options) { CLEANUP_SETUP clean_i.BasicCleanupSeqSubmit(ss); return changes; } /// Cleanup a Bioseq. CConstRef<CCleanupChange> CCleanup::BasicCleanup(CBioseq& bs, Uint4 options) { CLEANUP_SETUP clean_i.BasicCleanupBioseq(bs); return changes; } CConstRef<CCleanupChange> CCleanup::BasicCleanup(CBioseq_set& bss, Uint4 options) { CLEANUP_SETUP clean_i.BasicCleanupBioseqSet(bss); return changes; } CConstRef<CCleanupChange> CCleanup::BasicCleanup(CSeq_annot& sa, Uint4 options) { CLEANUP_SETUP clean_i.BasicCleanupSeqAnnot(sa); return changes; } CConstRef<CCleanupChange> CCleanup::BasicCleanup(CSeq_feat& sf, Uint4 options) { CLEANUP_SETUP clean_i.BasicCleanupSeqFeat(sf); return changes; } CConstRef<CCleanupChange> CCleanup::BasicCleanup(CBioSource& src, Uint4 options) { CLEANUP_SETUP clean_i.BasicCleanupBioSource(src); return changes; } CConstRef<CCleanupChange> CCleanup::BasicCleanup(CSeq_entry_Handle& seh, Uint4 options) { CRef<CCleanupChange> changes(makeCleanupChange(options)); CNewCleanup_imp clean_i(changes, options); clean_i.SetScope(seh.GetScope()); clean_i.BasicCleanupSeqEntryHandle(seh); return changes; } CConstRef<CCleanupChange> CCleanup::BasicCleanup(CBioseq_Handle& bsh, Uint4 options) { CRef<CCleanupChange> changes(makeCleanupChange(options)); CNewCleanup_imp clean_i(changes, options); clean_i.SetScope(bsh.GetScope()); clean_i.BasicCleanupBioseqHandle(bsh); return changes; } CConstRef<CCleanupChange> CCleanup::BasicCleanup(CBioseq_set_Handle& bssh, Uint4 options) { CRef<CCleanupChange> changes(makeCleanupChange(options)); CNewCleanup_imp clean_i(changes, options); clean_i.SetScope(bssh.GetScope()); clean_i.BasicCleanupBioseqSetHandle(bssh); return changes; } CConstRef<CCleanupChange> CCleanup::BasicCleanup(CSeq_annot_Handle& sah, Uint4 options) { CRef<CCleanupChange> changes(makeCleanupChange(options)); CNewCleanup_imp clean_i(changes, options); clean_i.SetScope(sah.GetScope()); clean_i.BasicCleanupSeqAnnotHandle(sah); return changes; } CConstRef<CCleanupChange> CCleanup::BasicCleanup(CSeq_feat_Handle& sfh, Uint4 options) { CRef<CCleanupChange> changes(makeCleanupChange(options)); CNewCleanup_imp clean_i(changes, options); clean_i.SetScope(sfh.GetScope()); clean_i.BasicCleanupSeqFeatHandle(sfh); return changes; } // *********************** Extended Cleanup implementation ******************** CConstRef<CCleanupChange> CCleanup::ExtendedCleanup(CSeq_entry& se, Uint4 options) { CLEANUP_SETUP clean_i.ExtendedCleanupSeqEntry(se); return changes; } CConstRef<CCleanupChange> CCleanup::ExtendedCleanup(CSeq_submit& ss, Uint4 options) { CLEANUP_SETUP clean_i.ExtendedCleanupSeqSubmit(ss); return changes; } CConstRef<CCleanupChange> CCleanup::ExtendedCleanup(CSeq_annot& sa, Uint4 options) { CLEANUP_SETUP clean_i.ExtendedCleanupSeqAnnot(sa); // (m_Scope->GetSeq_annotHandle(sa)); return changes; } CConstRef<CCleanupChange> CCleanup::ExtendedCleanup(CSeq_entry_Handle& seh, Uint4 options) { CRef<CCleanupChange> changes(makeCleanupChange(options)); CNewCleanup_imp clean_i(changes, options); clean_i.SetScope(seh.GetScope()); clean_i.ExtendedCleanupSeqEntryHandle(seh); // (m_Scope->GetSeq_annotHandle(sa)); return changes; } // *********************** CCleanupChange implementation ********************** CCleanupChange::CCleanupChange() { } size_t CCleanupChange::ChangeCount() const { return m_Changes.count(); } bool CCleanupChange::IsChanged(CCleanupChange::EChanges e) const { return m_Changes.test(e); } void CCleanupChange::SetChanged(CCleanupChange::EChanges e) { m_Changes.set(e); } vector<CCleanupChange::EChanges> CCleanupChange::GetAllChanges() const { vector<EChanges> result; for (size_t i = eNoChange + 1; i < m_Changes.size(); ++i) { if (m_Changes.test(i)) { result.push_back( (EChanges) i); } } return result; } vector<string> CCleanupChange::GetAllDescriptions() const { vector<string> result; for (size_t i = eNoChange + 1; i < m_Changes.size(); ++i) { if (m_Changes.test(i)) { result.push_back( GetDescription((EChanges) i) ); } } return result; } string CCleanupChange::GetDescription(EChanges e) { if (e <= eNoChange || e >= eNumberofChangeTypes) { return sm_ChangeDesc[eNoChange]; } return sm_ChangeDesc[e]; } // corresponds to the values in CCleanupChange::EChanges. // They must be edited together. const char* const CCleanupChange::sm_ChangeDesc[eNumberofChangeTypes + 1] = { "Invalid Change Code", // set when strings are changed. "Trim Spaces", "Clean Double Quotes", "Append To String", // set when lists are sorted or uniqued. "Clean Qualifiers List", "Clean Dbxrefs List", "Clean CitonFeat List", "Clean Keywords List", "Clean Subsource List", "Clean Orgmod List", // Set when fields are moved or have content changes "Repair BioseqMol", //10 "Change Feature Key", "Normalize Authors", "Change Publication", "Change Qualifiers", "Change Dbxrefs", "Change Keywords", "Change Subsource", "Change Orgmod", "Change Exception", "Change Comment", //20 // Set when fields are rescued "Change tRna", "Change rRna", "Change ITS", "Change Anticodon", "Change Code Break", "Change Genetic Code", "Copy GeneXref", "Copy ProtXref", // set when locations are repaired "Change Seqloc", "Change Strand", //30 "Change WholeLocation", // set when MolInfo descriptors are affected "Change MolInfo Descriptor", // set when prot-xref is removed "Remove ProtXref", // set when gene-xref is removed "Remove GeneXref", // set when protein feature is added "Add Protein Feature", // set when feature is removed "Remove Feature", // set when feature is moved "Move Feature", // set when qualifier is removed "Remove Qualifier", // set when Gene Xref is created "Add GeneXref", // set when descriptor is removed "Remove Descriptor", //40 "Remove Keyword", "Add Descriptor", "Move Descriptor", "Convert Feature to Descriptor", "Collapse Set", "Change Feature Location", "Remove Annotation", "Convert Feature", "Remove Comment", "Add BioSource OrgMod", //50 "Add BioSource SubSource", "Change BioSource Genome", "Change BioSource Origin", "Change BioSource Other", "Change SeqId", "Remove Empty Publication", "Add Qualifier", "Cleanup Date", "Change BioseqInst", "Remove SeqID", // 60 "Add ProtXref", "Change Partial", "Change Prot Names", "Change Prot Activities", "Change Site", "Change PCR Primers", "Change RNA-ref", "Move To Prot Xref", "Compress Spaces", "Strip serial", // 70 "Remove Orgmod", "Remove SubSource", "Create Gene Nomenclature", "Clean Seq-feat xref", "Clean User-Object Or -Field", "Letter Case Change", "Change Bioseq-set Class", "Unique Without Sort", "Add RNA-ref", "Change Gene-ref", // 80 "Clean Dbtag", "Change Biomol", "Change Cdregion", "Clean EC Number", "Remove Exception", "Add NcbiCleanupObject", "Clean Delta-ext", "Trim Flanking Quotes", "Clean Bioseq Title", "Decode XML", // 90 "Remove Dup BioSource", "Clean Org-ref", "Trim Internal Semicolons", "Add SeqFeatXref", // set when any other change is made. "Change Other", "Invalid Change Code" }; CProt_ref::EProcessed s_ProcessedFromKey(const string& key) { if (NStr::Equal(key, "sig_peptide")) { return CProt_ref::eProcessed_signal_peptide; } else if (NStr::Equal(key, "mat_peptide")) { return CProt_ref::eProcessed_mature; } else if (NStr::Equal(key, "transit_peptide")) { return CProt_ref::eProcessed_transit_peptide; } else if (NStr::Equal(key, "preprotein") || NStr::Equal(key, "proprotein")) { return CProt_ref::eProcessed_preprotein; } else if (NStr::Equal(key, "propeptide")) { return CProt_ref::eProcessed_propeptide; } else { return CProt_ref::eProcessed_not_set; } } string s_KeyFromProcessed(CProt_ref::EProcessed processed) { switch (processed) { case CProt_ref::eProcessed_mature: return "mat_peptide"; break; case CProt_ref::eProcessed_preprotein: return "preprotein"; break; case CProt_ref::eProcessed_signal_peptide: return "sig_peptide"; break; case CProt_ref::eProcessed_transit_peptide: return "transit_peptide"; break; case CProt_ref::eProcessed_propeptide: return "propeptide"; break; case CProt_ref::eProcessed_not_set: return kEmptyStr; break; } return kEmptyStr; } bool ConvertProteinToImp(CSeq_feat_Handle fh) { if (fh.GetData().IsProt() && fh.GetData().GetProt().IsSetProcessed()) { string key = s_KeyFromProcessed(fh.GetData().GetProt().GetProcessed()); if (!NStr::IsBlank(key)) { CRef<CSeq_feat> new_feat(new CSeq_feat()); new_feat->Assign(*(fh.GetSeq_feat())); if (fh.GetData().GetProt().IsSetName() && !fh.GetData().GetProt().GetName().empty()) { CRef<CGb_qual> q(new CGb_qual()); q->SetQual("product"); q->SetVal(fh.GetData().GetProt().GetName().front()); new_feat->SetQual().push_back(q); } new_feat->SetData().SetImp().SetKey(key); CSeq_feat_EditHandle efh(fh); efh.Replace(*new_feat); return true; } } return false; } bool s_IsPreprotein(CSeq_feat_Handle fh) { if (!fh.IsSetData()) { return false; } else if (fh.GetData().IsProt() && fh.GetData().GetProt().IsSetProcessed() && fh.GetData().GetProt().GetProcessed() == CProt_ref::eProcessed_preprotein) { return true; } else if (fh.GetData().IsImp() && fh.GetData().GetImp().IsSetKey() && s_ProcessedFromKey(fh.GetData().GetImp().GetKey()) == CProt_ref::eProcessed_preprotein) { return true; } else { return false; } } void RescueProtProductQual(CSeq_feat& feat) { if (!feat.IsSetQual() || !feat.IsSetData() || !feat.GetData().IsProt() || feat.GetData().GetProt().IsSetName()) { return; } CSeq_feat::TQual::iterator it = feat.SetQual().begin(); while (it != feat.SetQual().end()) { if ((*it)->IsSetQual() && NStr::Equal((*it)->GetQual(), "product")) { if ((*it)->IsSetVal() && !NStr::IsBlank((*it)->GetVal())) { feat.SetData().SetProt().SetName().push_back((*it)->GetVal()); } it = feat.SetQual().erase(it); } else { ++it; } } if (feat.SetQual().empty()) { feat.ResetQual(); } } bool CCleanup::MoveFeatToProtein(CSeq_feat_Handle fh) { CProt_ref::EProcessed processed = CProt_ref::eProcessed_not_set; if (fh.GetData().IsImp()) { if (!fh.GetData().GetImp().IsSetKey()) { return false; } processed = s_ProcessedFromKey(fh.GetData().GetImp().GetKey()); if (processed == CProt_ref::eProcessed_not_set || processed == CProt_ref::eProcessed_preprotein) { return false; } } else if (s_IsPreprotein(fh)) { return ConvertProteinToImp(fh); } CBioseq_Handle parent_bsh = fh.GetScope().GetBioseqHandle(fh.GetLocation()); if (!parent_bsh) { // feature is mispackaged return false; } if (parent_bsh.IsAa()) { // feature is already on protein sequence return false; } CConstRef<CSeq_feat> cds = sequence::GetOverlappingCDS(fh.GetLocation(), fh.GetScope()); if (!cds || !cds->IsSetProduct()) { // there is no overlapping coding region feature, so there is no appropriate // protein sequence to move to return ConvertProteinToImp(fh); } bool require_frame = false; ITERATE(CBioseq::TId, id_it, parent_bsh.GetBioseqCore()->GetId()) { if ((*id_it)->IsEmbl() || (*id_it)->IsDdbj()) { require_frame = true; break; } } CRef<CSeq_loc> prot_loc = GetProteinLocationFromNucleotideLocation(fh.GetLocation(), *cds, fh.GetScope(), require_frame); if (!prot_loc) { return false; } CConstRef<CSeq_feat> orig_feat = fh.GetSeq_feat(); CRef<CSeq_feat> new_feat(new CSeq_feat()); new_feat->Assign(*orig_feat); if (new_feat->GetData().Which() == CSeqFeatData::e_Imp) { new_feat->SetData().SetProt().SetProcessed(processed); // if possible, rescue product qual RescueProtProductQual(*new_feat); if (processed == CProt_ref::eProcessed_mature && !new_feat->GetData().GetProt().IsSetName()) { if (orig_feat->IsSetComment() && !NStr::IsBlank(orig_feat->GetComment())) { new_feat->SetData().SetProt().SetName().push_back(orig_feat->GetComment()); new_feat->ResetComment(); } else { new_feat->SetData().SetProt().SetName().push_back("unnamed"); } } } // change location to protein new_feat->ResetLocation(); new_feat->SetLocation(*prot_loc); SetFeaturePartial(*new_feat); CSeq_feat_EditHandle edh(fh); edh.Replace(*new_feat); CRef<CCleanupChange> changes(makeCleanupChange(0)); CNewCleanup_imp clean_i(changes, 0); clean_i.SetScope(fh.GetScope()); clean_i.BasicCleanupSeqFeat(*new_feat); CSeq_annot_Handle ah = fh.GetAnnot(); CBioseq_Handle target_bsh = fh.GetScope().GetBioseqHandle(new_feat->GetLocation()); CBioseq_EditHandle eh = target_bsh.GetEditHandle(); // Find a feature table on the protein sequence to add the feature to. CSeq_annot_Handle ftable; if (target_bsh.GetCompleteBioseq()->IsSetAnnot()) { ITERATE(CBioseq::TAnnot, annot_it, target_bsh.GetCompleteBioseq()->GetAnnot()) { if ((*annot_it)->IsFtable()) { ftable = fh.GetScope().GetSeq_annotHandle(**annot_it); } } } // If there is no feature table present, make one if (!ftable) { CRef<CSeq_annot> new_annot(new CSeq_annot()); ftable = eh.AttachAnnot(*new_annot); } // add feature to the protein bioseq CSeq_annot_EditHandle aeh(ftable); aeh.TakeFeat(edh); // remove old annot if now empty if (CNewCleanup_imp::ShouldRemoveAnnot(*(ah.GetCompleteSeq_annot()))) { CSeq_annot_EditHandle orig(ah); orig.Remove(); } return true; } bool CCleanup::MoveProteinSpecificFeats(CSeq_entry_Handle seh) { bool any_change = false; CBioseq_CI bi(seh, CSeq_inst::eMol_na); while (bi) { SAnnotSelector sel(CSeqFeatData::e_Prot); sel.IncludeFeatType(CSeqFeatData::e_Psec_str); sel.IncludeFeatType(CSeqFeatData::e_Bond); for (CFeat_CI prot_it(*bi, sel); prot_it; ++prot_it) { any_change |= MoveFeatToProtein(*prot_it); } for (CFeat_CI imp_it(*bi, CSeqFeatData::e_Imp); imp_it; ++imp_it) { any_change |= MoveFeatToProtein(*imp_it); } ++bi; } return any_change; } bool CCleanup::IsGeneXrefUnnecessary(const CSeq_feat& sf, CScope& scope, const CGene_ref& gene_xref) { if (gene_xref.IsSuppressed()) { return false; } CConstRef<CSeq_feat> gene = sequence::GetOverlappingGene(sf.GetLocation(), scope); if (!gene || !gene->IsSetData() || !gene->GetData().IsGene()) { return false; } if (!gene->GetData().GetGene().RefersToSameGene(gene_xref)) { return false; } // see if other gene might also match sequence::TFeatScores scores; sequence::GetOverlappingFeatures(sf.GetLocation(), CSeqFeatData::e_Gene, CSeqFeatData::eSubtype_gene, sequence::eOverlap_Contained, scores, scope); if (scores.size() == 1) { return true; } else if (scores.size() == 0) { return false; } ITERATE(sequence::TFeatScores, g, scores) { if (g->second.GetPointer() != gene.GetPointer() && sequence::Compare(g->second->GetLocation(), gene->GetLocation(), &scope, sequence::fCompareOverlapping) == sequence::eSame) { return false; } } return true; } bool CCleanup::RemoveUnnecessaryGeneXrefs(CSeq_feat& f, CScope& scope) { if (!f.IsSetXref()) { return false; } bool any_removed = false; CSeq_feat::TXref::iterator xit = f.SetXref().begin(); while (xit != f.SetXref().end()) { if ((*xit)->IsSetData() && (*xit)->GetData().IsGene() && IsGeneXrefUnnecessary(f, scope, (*xit)->GetData().GetGene())) { xit = f.SetXref().erase(xit); any_removed = true; } else { ++xit; } } if (any_removed) { if (f.IsSetXref() && f.GetXref().empty()) { f.ResetXref(); } } return any_removed; } bool CCleanup::RemoveUnnecessaryGeneXrefs(CSeq_entry_Handle seh) { bool any_change = false; CScope& scope = seh.GetScope(); for (CFeat_CI fi(seh); fi; ++fi) { if (fi->IsSetXref()) { CRef<CSeq_feat> new_feat(new CSeq_feat()); new_feat->Assign(*(fi->GetOriginalSeq_feat())); bool any_removed = RemoveUnnecessaryGeneXrefs(*new_feat, scope); if (any_removed) { CSeq_feat_EditHandle edh(*fi); edh.Replace(*new_feat); any_change = true; } } } return any_change; } bool CCleanup::RemoveNonsuppressingGeneXrefs(CSeq_feat& f) { if (!f.IsSetXref()) { return false; } bool any_removed = false; CSeq_feat::TXref::iterator xit = f.SetXref().begin(); while (xit != f.SetXref().end()) { if ((*xit)->IsSetData() && (*xit)->GetData().IsGene() && !(*xit)->GetData().GetGene().IsSuppressed()) { xit = f.SetXref().erase(xit); any_removed = true; } else { ++xit; } } if (any_removed) { if (f.IsSetXref() && f.GetXref().empty()) { f.ResetXref(); } } return any_removed; } bool CCleanup::RepairXrefs(const CSeq_feat& src, CSeq_feat_Handle& dst, const CTSE_Handle& tse) { if (!src.IsSetId() || !src.GetId().IsLocal()) { // can't create xref if no ID return false; } if (!CSeqFeatData::AllowXref(src.GetData().GetSubtype(), dst.GetData().GetSubtype())) { // only create reciprocal xrefs if permitted return false; } // don't create xref if already have xref or if dst not gene and already has // xref to feature of same type as src bool has_xref = false; if (dst.IsSetXref()) { ITERATE(CSeq_feat::TXref, xit, dst.GetXref()) { if ((*xit)->IsSetId() && (*xit)->GetId().IsLocal()) { if ((*xit)->GetId().Equals(src.GetId())) { // already have xref has_xref = true; break; } else if (!dst.GetData().IsGene()) { const CTSE_Handle::TFeatureId& feat_id = (*xit)->GetId().GetLocal(); CTSE_Handle::TSeq_feat_Handles far_feats = tse.GetFeaturesWithId(CSeqFeatData::e_not_set, feat_id); ITERATE(CTSE_Handle::TSeq_feat_Handles, fit, far_feats) { if (fit->GetData().GetSubtype() == src.GetData().GetSubtype()) { has_xref = true; break; } } if (has_xref) { break; } } } } } bool rval = false; if (!has_xref) { // to put into "editing mode" dst.GetAnnot().GetEditHandle(); CSeq_feat_EditHandle eh(dst); CRef<CSeq_feat> cpy(new CSeq_feat()); cpy->Assign(*(dst.GetSeq_feat())); cpy->AddSeqFeatXref(src.GetId()); eh.Replace(*cpy); rval = true; } return rval; } bool CCleanup::RepairXrefs(const CSeq_feat& f, const CTSE_Handle& tse) { bool rval = false; if (!f.IsSetId() || !f.IsSetXref()) { return rval; } ITERATE(CSeq_feat::TXref, xit, f.GetXref()) { if ((*xit)->IsSetId() && (*xit)->GetId().IsLocal()) { const CTSE_Handle::TFeatureId& x_id = (*xit)->GetId().GetLocal(); CTSE_Handle::TSeq_feat_Handles far_feats = tse.GetFeaturesWithId(CSeqFeatData::e_not_set, x_id); if (far_feats.size() == 1) { rval |= RepairXrefs(f, far_feats[0], tse); } } } return rval; } bool CCleanup::RepairXrefs(CSeq_entry_Handle seh) { bool rval = false; const CTSE_Handle& tse = seh.GetTSE_Handle(); CFeat_CI fi(seh); while (fi) { rval |= RepairXrefs(*(fi->GetSeq_feat()), tse); ++fi; } return rval; } bool CCleanup::FindMatchingLocusGene(CSeq_feat& f, const CGene_ref& gene_xref, CBioseq_Handle bsh) { bool match = false; string locus1; if (gene_xref.IsSetLocus()) locus1 = gene_xref.GetLocus(); for (CFeat_CI feat_ci(bsh, SAnnotSelector(CSeqFeatData::eSubtype_gene)); feat_ci; ++feat_ci) { string locus2; if ( !f.Equals(*feat_ci->GetSeq_feat()) && feat_ci->GetSeq_feat()->IsSetData() && feat_ci->GetSeq_feat()->GetData().IsGene() && feat_ci->GetSeq_feat()->GetData().GetGene().IsSetLocus()) { locus2 = feat_ci->GetSeq_feat()->GetData().GetGene().GetLocus(); } if (!locus1.empty() && !locus2.empty() && locus1 == locus2) { match = true; break; } } return match; } bool CCleanup::RemoveOrphanLocusGeneXrefs(CSeq_feat& f, CBioseq_Handle bsh) { if (!f.IsSetXref()) { return false; } bool any_removed = false; CSeq_feat::TXref::iterator xit = f.SetXref().begin(); while (xit != f.SetXref().end()) { if ((*xit)->IsSetData() && (*xit)->GetData().IsGene() && !(*xit)->GetData().GetGene().IsSuppressed() && !FindMatchingLocusGene(f, (*xit)->GetData().GetGene(), bsh)) { xit = f.SetXref().erase(xit); any_removed = true; } else { ++xit; } } if (any_removed) { if (f.IsSetXref() && f.GetXref().empty()) { f.ResetXref(); } } return any_removed; } bool CCleanup::FindMatchingLocus_tagGene(CSeq_feat& f, const CGene_ref& gene_xref, CBioseq_Handle bsh) { bool match = false; string locus_tag1; if (gene_xref.IsSetLocus_tag()) locus_tag1 = gene_xref.GetLocus_tag(); for (CFeat_CI feat_ci(bsh, SAnnotSelector(CSeqFeatData::eSubtype_gene)); feat_ci; ++feat_ci) { string locus_tag2; if ( !f.Equals(*feat_ci->GetSeq_feat()) && feat_ci->GetSeq_feat()->IsSetData() && feat_ci->GetSeq_feat()->GetData().IsGene() && feat_ci->GetSeq_feat()->GetData().GetGene().IsSetLocus_tag()) { locus_tag2 = feat_ci->GetSeq_feat()->GetData().GetGene().GetLocus_tag(); } if (!locus_tag1.empty() && !locus_tag2.empty() && locus_tag1 == locus_tag2) { match = true; break; } } return match; } bool CCleanup::RemoveOrphanLocus_tagGeneXrefs(CSeq_feat& f, CBioseq_Handle bsh) { if (!f.IsSetXref()) { return false; } bool any_removed = false; CSeq_feat::TXref::iterator xit = f.SetXref().begin(); while (xit != f.SetXref().end()) { if ((*xit)->IsSetData() && (*xit)->GetData().IsGene() && !(*xit)->GetData().GetGene().IsSuppressed() && !FindMatchingLocus_tagGene(f, (*xit)->GetData().GetGene(), bsh)) { xit = f.SetXref().erase(xit); any_removed = true; } else { ++xit; } } if (any_removed) { if (f.IsSetXref() && f.GetXref().empty()) { f.ResetXref(); } } return any_removed; } bool CCleanup::SeqLocExtend(CSeq_loc& loc, size_t pos, CScope& scope) { size_t loc_start = loc.GetStart(eExtreme_Positional); size_t loc_stop = loc.GetStop(eExtreme_Positional); bool partial_start = loc.IsPartialStart(eExtreme_Positional); bool partial_stop = loc.IsPartialStop(eExtreme_Positional); ENa_strand strand = loc.GetStrand(); CRef<CSeq_loc> new_loc(NULL); bool changed = false; if (pos < loc_start) { CRef<CSeq_id> id(new CSeq_id()); id->Assign(*(loc.GetId())); CRef<CSeq_loc> add(new CSeq_loc(*id, pos, loc_start - 1, strand)); add->SetPartialStart(partial_start, eExtreme_Positional); new_loc = sequence::Seq_loc_Add(loc, *add, CSeq_loc::fSort | CSeq_loc::fMerge_AbuttingOnly, &scope); changed = true; } else if (pos > loc_stop) { CRef<CSeq_id> id(new CSeq_id()); id->Assign(*(loc.GetId())); CRef<CSeq_loc> add(new CSeq_loc(*id, loc_stop + 1, pos, strand)); add->SetPartialStop(partial_stop, eExtreme_Positional); new_loc = sequence::Seq_loc_Add(loc, *add, CSeq_loc::fSort | CSeq_loc::fMerge_AbuttingOnly, &scope); changed = true; } if (changed) { loc.Assign(*new_loc); } return changed; } bool CCleanup::ExtendStopPosition(CSeq_feat& f, const CSeq_feat* cdregion, size_t extension) { CRef<CSeq_loc> new_loc(&f.SetLocation()); CRef<CSeq_loc> last_interval; if (new_loc->IsMix()) { last_interval = new_loc->SetMix().SetLastLoc(); } else { last_interval = new_loc; } CConstRef<CSeq_id> id(last_interval->GetId()); TSeqPos new_start; TSeqPos new_stop; // the last element of the mix or the single location MUST be converted into interval // whethe it's whole or point, etc if (last_interval->IsSetStrand() && last_interval->GetStrand() == eNa_strand_minus) { new_start = (cdregion ? cdregion->GetLocation().GetStart(eExtreme_Positional) : last_interval->GetStart(eExtreme_Positional)) - extension; new_stop = last_interval->GetStop(eExtreme_Positional); } else { new_start = last_interval->GetStart(eExtreme_Positional); new_stop = (cdregion ? cdregion->GetLocation().GetStop(eExtreme_Positional) : last_interval->GetStop(eExtreme_Positional)) + extension; } last_interval->SetInt().SetFrom(new_start); last_interval->SetInt().SetTo(new_stop); last_interval->SetInt().SetId().Assign(*id); new_loc->SetPartialStop(false, eExtreme_Biological); return true; } bool CCleanup::ExtendToStopCodon(CSeq_feat& f, CBioseq_Handle bsh, size_t limit) { const CSeq_loc& loc = f.GetLocation(); CCdregion::TFrame frame = CCdregion::eFrame_not_set; const CGenetic_code* code = NULL; // we need to extract frame and cd_region from linked cd_region if (f.IsSetData() && f.GetData().IsCdregion()) { if (f.GetData().GetCdregion().IsSetCode()) code = &(f.GetData().GetCdregion().GetCode()); if (f.GetData().GetCdregion().IsSetFrame()) frame = f.GetData().GetCdregion().GetFrame(); } size_t stop = loc.GetStop(eExtreme_Biological); // figure out if we have a partial codon at the end size_t orig_len = sequence::GetLength(loc, &(bsh.GetScope())); size_t len = orig_len; if (frame == CCdregion::eFrame_two) { len -= 1; } else if (frame == CCdregion::eFrame_three) { len -= 2; } size_t mod = len % 3; CRef<CSeq_loc> vector_loc(new CSeq_loc()); vector_loc->SetInt().SetId().Assign(*(bsh.GetId().front().GetSeqId())); if (loc.IsSetStrand() && loc.GetStrand() == eNa_strand_minus) { vector_loc->SetInt().SetFrom(0); vector_loc->SetInt().SetTo(stop + mod - 1); vector_loc->SetStrand(eNa_strand_minus); } else { vector_loc->SetInt().SetFrom(stop - mod + 1); vector_loc->SetInt().SetTo(bsh.GetInst_Length() - 1); } CSeqVector seq(*vector_loc, bsh.GetScope(), CBioseq_Handle::eCoding_Iupac); // reserve our space size_t usable_size = seq.size(); if (limit > 0 && usable_size > limit) { usable_size = limit; } // get appropriate translation table const CTrans_table & tbl = (code ? CGen_code_table::GetTransTable(*code) : CGen_code_table::GetTransTable(1)); // main loop through bases CSeqVector::const_iterator start = seq.begin(); size_t i; size_t k; size_t state = 0; size_t length = usable_size / 3; for (i = 0; i < length; ++i) { // loop through one codon at a time for (k = 0; k < 3; ++k, ++start) { state = tbl.NextCodonState(state, *start); } if (tbl.GetCodonResidue(state) == '*') { size_t extension = ((i + 1) * 3) - mod; ExtendStopPosition(f, 0, extension); return true; } } bool rval = false; if (usable_size < 3 && limit == 0) { if (loc.GetStrand() == eNa_strand_minus) { rval = SeqLocExtend(f.SetLocation(), 0, bsh.GetScope()); } else { rval = SeqLocExtend(f.SetLocation(), bsh.GetInst_Length() - 1, bsh.GetScope()); } f.SetLocation().SetPartialStop(true, eExtreme_Biological); } return rval; } bool CCleanup::SetBestFrame(CSeq_feat& cds, CScope& scope) { bool changed = false; CCdregion::TFrame frame = CCdregion::eFrame_not_set; if (cds.GetData().GetCdregion().IsSetFrame()) { frame = cds.GetData().GetCdregion().GetFrame(); } CCdregion::TFrame new_frame = CSeqTranslator::FindBestFrame(cds, scope); if (frame != new_frame) { cds.SetData().SetCdregion().SetFrame(new_frame); changed = true; } return changed; } // like C's function GetFrameFromLoc, but better bool CCleanup::SetFrameFromLoc(CCdregion::EFrame &frame, const CSeq_loc& loc, CScope& scope) { if (!loc.IsPartialStart(eExtreme_Biological)) { if (frame != CCdregion::eFrame_one) { frame = CCdregion::eFrame_one; return true; } return false; } if (loc.IsPartialStop(eExtreme_Biological)) { // cannot make a determination if both ends are partial return false; } const TSeqPos seq_len = sequence::GetLength(loc, &scope); CCdregion::EFrame desired_frame = CCdregion::eFrame_not_set; // have complete last codon, get frame from length switch( (seq_len % 3) + 1 ) { case 1: desired_frame = CCdregion::eFrame_one; break; case 2: desired_frame = CCdregion::eFrame_two; break; case 3: desired_frame = CCdregion::eFrame_three; break; default: // mathematically impossible _ASSERT(false); return false; } if (frame != desired_frame) { frame = desired_frame; return true; } return false; } bool CCleanup::SetFrameFromLoc(CCdregion &cdregion, const CSeq_loc& loc, CScope& scope) { CCdregion::EFrame frame = CCdregion::eFrame_not_set; if (cdregion.IsSetFrame()) { frame = cdregion.GetFrame(); } if (SetFrameFromLoc(frame, loc, scope)) { cdregion.SetFrame(frame); return true; } else { return false; } } bool IsTransSpliced(const CSeq_feat& feat) { if (feat.IsSetExcept_text() && NStr::Find(feat.GetExcept_text(), "trans-splicing") != string::npos) { return true; } else { return false; } } bool CCleanup::ExtendToStopIfShortAndNotPartial(CSeq_feat& f, CBioseq_Handle bsh, bool check_for_stop) { if (!f.GetData().IsCdregion()) { // not coding region return false; } if (sequence::IsPseudo(f, bsh.GetScope())) { return false; } if (f.GetLocation().IsPartialStop(eExtreme_Biological)) { return false; } CConstRef<CSeq_feat> mrna = sequence::GetOverlappingmRNA(f.GetLocation(), bsh.GetScope()); if (mrna && mrna->GetLocation().GetStop(eExtreme_Biological) != f.GetLocation().GetStop(eExtreme_Biological)){ return false; } if (check_for_stop) { string translation; try { CSeqTranslator::Translate(f, bsh.GetScope(), translation, true); } catch (CSeqMapException& e) { //unable to translate return false; } catch (CSeqVectorException& e) { //unable to translate return false; } if (NStr::EndsWith(translation, "*")) { //already has stop codon return false; } } return ExtendToStopCodon(f, bsh, 3); } bool CCleanup::LocationMayBeExtendedToMatch(const CSeq_loc& orig, const CSeq_loc& improved) { if ((orig.GetStrand() == eNa_strand_minus && orig.GetStop(eExtreme_Biological) > improved.GetStop(eExtreme_Biological)) || (orig.GetStrand() != eNa_strand_minus && orig.GetStop(eExtreme_Biological) < improved.GetStop(eExtreme_Biological))) { return true; } return false; } void CCleanup::SetProteinName(CProt_ref& prot_ref, const string& protein_name, bool append) { if (append && prot_ref.IsSetName() && prot_ref.GetName().size() > 0 && !NStr::IsBlank(prot_ref.GetName().front())) { prot_ref.SetName().front() += "; " + protein_name; } else { prot_ref.ResetName(); prot_ref.SetName().push_back(protein_name); } } void CCleanup::SetProteinName(CSeq_feat& cds, const string& protein_name, bool append, CScope& scope) { bool added = false; if (cds.IsSetProduct()) { CBioseq_Handle prot = scope.GetBioseqHandle(cds.GetProduct()); if (prot) { // find main protein feature CFeat_CI feat_ci(prot, CSeqFeatData::eSubtype_prot); if (feat_ci) { CRef<CSeq_feat> new_prot(new CSeq_feat()); new_prot->Assign(feat_ci->GetOriginalFeature()); SetProteinName(new_prot->SetData().SetProt(), protein_name, append); CSeq_feat_EditHandle feh(feat_ci->GetSeq_feat_Handle()); feh.Replace(*new_prot); } else { // make new protein feature feature::AddProteinFeature(*(prot.GetCompleteBioseq()), protein_name, cds, scope); } added = true; } } if (!added) { if (cds.IsSetXref()) { // see if this seq-feat already has a prot xref NON_CONST_ITERATE(CSeq_feat::TXref, it, cds.SetXref()) { if ((*it)->IsSetData() && (*it)->GetData().IsProt()) { SetProteinName((*it)->SetData().SetProt(), protein_name, append); added = true; break; } } } if (!added) { CRef<CSeqFeatXref> xref(new CSeqFeatXref()); xref->SetData().SetProt().SetName().push_back(protein_name); cds.SetXref().push_back(xref); } } } const string& CCleanup::GetProteinName(const CProt_ref& prot) { if (prot.IsSetName() && !prot.GetName().empty()) { return prot.GetName().front(); } else { return kEmptyStr; } } const string& CCleanup::GetProteinName(const CSeq_feat& cds, CScope& scope) { if (cds.IsSetProduct()) { CBioseq_Handle prot = scope.GetBioseqHandle(cds.GetProduct()); if (prot) { CFeat_CI f(prot, CSeqFeatData::eSubtype_prot); if (f) { return GetProteinName(f->GetData().GetProt()); } } } if (cds.IsSetXref()) { ITERATE(CSeq_feat::TXref, it, cds.GetXref()) { if ((*it)->IsSetData() && (*it)->GetData().IsProt()) { return GetProteinName((*it)->GetData().GetProt()); } } } return kEmptyStr; } bool CCleanup::SetCDSPartialsByFrameAndTranslation(CSeq_feat& cds, CScope& scope) { bool any_change = false; if (!cds.GetLocation().IsPartialStart(eExtreme_Biological) && cds.GetData().GetCdregion().IsSetFrame() && cds.GetData().GetCdregion().GetFrame() != CCdregion::eFrame_not_set && cds.GetData().GetCdregion().GetFrame() != CCdregion::eFrame_one) { cds.SetLocation().SetPartialStart(true, eExtreme_Biological); any_change = true; } if (!cds.GetLocation().IsPartialStart(eExtreme_Biological) || !cds.GetLocation().IsPartialStop(eExtreme_Biological)) { // look for start and stop codon string transl_prot; try { CSeqTranslator::Translate(cds, scope, transl_prot, true, // include stop codons false); // do not remove trailing X/B/Z } catch (const runtime_error&) { } if (!NStr::IsBlank(transl_prot)) { if (!cds.GetLocation().IsPartialStart(eExtreme_Biological) && !NStr::StartsWith(transl_prot, "M")) { cds.SetLocation().SetPartialStart(true, eExtreme_Biological); any_change = true; } if (!cds.GetLocation().IsPartialStop(eExtreme_Biological) && !NStr::EndsWith(transl_prot, "*")) { cds.SetLocation().SetPartialStop(true, eExtreme_Biological); any_change = true; } } } any_change |= feature::AdjustFeaturePartialFlagForLocation(cds); return any_change; } bool CCleanup::ClearInternalPartials(CSeq_loc& loc, bool is_first, bool is_last) { bool rval = false; switch (loc.Which()) { case CSeq_loc::e_Mix: rval |= ClearInternalPartials(loc.SetMix(), is_first, is_last); break; case CSeq_loc::e_Packed_int: rval |= ClearInternalPartials(loc.SetPacked_int(), is_first, is_last); break; default: break; } return rval; } bool CCleanup::ClearInternalPartials(CSeq_loc_mix& mix, bool is_first, bool is_last) { bool rval = false; NON_CONST_ITERATE(CSeq_loc::TMix::Tdata, it, mix.Set()) { bool this_is_last = is_last && (*it == mix.Set().back()); if ((*it)->IsMix() || (*it)->IsPacked_int()) { rval |= ClearInternalPartials(**it, is_first, this_is_last); } else { if (!is_first && (*it)->IsPartialStart(eExtreme_Biological)) { (*it)->SetPartialStart(false, eExtreme_Biological); rval = true; } if (!this_is_last && (*it)->IsPartialStop(eExtreme_Biological)) { (*it)->SetPartialStop(false, eExtreme_Biological); rval = true; } } is_first = false; } return rval; } bool CCleanup::ClearInternalPartials(CPacked_seqint& pint, bool is_first, bool is_last) { bool rval = false; NON_CONST_ITERATE(CSeq_loc::TPacked_int::Tdata, it, pint.Set()) { bool this_is_last = is_last && (*it == pint.Set().back()); if (!is_first && (*it)->IsPartialStart(eExtreme_Biological)) { (*it)->SetPartialStart(false, eExtreme_Biological); rval = true; } if (!this_is_last && (*it)->IsPartialStop(eExtreme_Biological)) { (*it)->SetPartialStop(false, eExtreme_Biological); rval = true; } is_first = false; } return rval; } bool CCleanup::ClearInternalPartials(CSeq_entry_Handle seh) { bool rval = false; CFeat_CI f(seh); while (f) { CRef<CSeq_feat> new_feat(new CSeq_feat()); new_feat->Assign(*(f->GetSeq_feat())); if (ClearInternalPartials(new_feat->SetLocation())) { CSeq_feat_EditHandle eh(f->GetSeq_feat_Handle()); eh.Replace(*new_feat); } ++f; } return rval; } bool CCleanup::SetFeaturePartial(CSeq_feat& f) { if (!f.IsSetLocation()) { return false; } bool partial = false; CSeq_loc_CI li(f.GetLocation()); while (li && !partial) { if (li.GetFuzzFrom() || li.GetFuzzTo()) { partial = true; break; } ++li; } bool changed = false; if (f.IsSetPartial() && f.GetPartial()) { if (!partial) { f.ResetPartial(); changed = true; } } else { if (partial) { f.SetPartial(true); changed = true; } } return changed; } bool CCleanup::UpdateECNumbers(CProt_ref::TEc & ec_num_list) { bool changed = false; // CProt_ref::TEc is a list, so the iterator stays valid even if we // add new entries after the current one NON_CONST_ITERATE(CProt_ref::TEc, ec_num_iter, ec_num_list) { string & ec_num = *ec_num_iter; size_t tlen = ec_num.length(); CleanVisStringJunk(ec_num); if (tlen != ec_num.length()) { changed = true; } if (CProt_ref::GetECNumberStatus(ec_num) == CProt_ref::eEC_replaced && !CProt_ref::IsECNumberSplit(ec_num)) { string new_val = CProt_ref::GetECNumberReplacement(ec_num); if (!NStr::IsBlank(new_val)) { ec_num = new_val; changed = true; } } } return changed; } bool CCleanup::RemoveBadECNumbers(CProt_ref::TEc & ec_num_list) { bool changed = false; CProt_ref::TEc::iterator ec_num_iter = ec_num_list.begin(); while (ec_num_iter != ec_num_list.end()) { string & ec_num = *ec_num_iter; size_t tlen = ec_num.length(); CleanVisStringJunk(ec_num); if (tlen != ec_num.length()) { changed = true; } CProt_ref::EECNumberStatus ec_status = CProt_ref::GetECNumberStatus(ec_num); if (ec_status == CProt_ref::eEC_deleted || ec_status == CProt_ref::eEC_unknown || CProt_ref::IsECNumberSplit(ec_num)) { ec_num_iter = ec_num_list.erase(ec_num_iter); changed = true; } else { ++ec_num_iter; } } return changed; } bool CCleanup::FixECNumbers(CSeq_entry_Handle entry) { bool any_change = false; CFeat_CI f(entry, CSeqFeatData::e_Prot); while (f) { if (f->GetData().GetProt().IsSetEc()) { bool this_change = false; CRef<CSeq_feat> new_feat(new CSeq_feat()); new_feat->Assign(*(f->GetSeq_feat())); this_change = UpdateECNumbers(new_feat->SetData().SetProt().SetEc()); this_change |= RemoveBadECNumbers(new_feat->SetData().SetProt().SetEc()); if (new_feat->GetData().GetProt().GetEc().empty()) { new_feat->SetData().SetProt().ResetEc(); this_change = true; } if (this_change) { CSeq_feat_EditHandle efh(*f); efh.Replace(*new_feat); } } ++f; } return any_change; } bool CCleanup::SetGenePartialByLongestContainedFeature(CSeq_feat& gene, CScope& scope) { CBioseq_Handle bh = scope.GetBioseqHandle(gene.GetLocation()); if (!bh) { return false; } CFeat_CI under(scope, gene.GetLocation()); size_t longest = 0; CConstRef<CSeq_feat> longest_feat(NULL); while (under) { // ignore genes if (under->GetData().IsGene()) { } else { // must be contained in gene location sequence::ECompare loc_cmp = sequence::Compare(gene.GetLocation(), under->GetLocation(), &scope, sequence::fCompareOverlapping); if (loc_cmp == sequence::eSame || loc_cmp == sequence::eContains) { size_t len = sequence::GetLength(under->GetLocation(), &scope); // if longer than longest, record new length and feature if (len > longest) { longest_feat.Reset(under->GetSeq_feat()); } } } ++under; } bool changed = false; if (longest_feat) { changed = feature::CopyFeaturePartials(gene, *longest_feat); } return changed; } bool CCleanup::SetMolinfoTech(CBioseq_Handle bsh, CMolInfo::ETech tech) { CSeqdesc_CI di(bsh, CSeqdesc::e_Molinfo); if (di) { if (di->GetMolinfo().IsSetTech() && di->GetMolinfo().GetTech() == tech) { // no change necessary return false; } else { CSeqdesc* d = const_cast<CSeqdesc*>(&(*di)); d->SetMolinfo().SetTech(tech); return true; } } CRef<CSeqdesc> m(new CSeqdesc()); m->SetMolinfo().SetTech(tech); if (bsh.IsSetInst() && bsh.GetInst().IsSetMol() && bsh.IsAa()) { m->SetMolinfo().SetBiomol(CMolInfo::eBiomol_peptide); } CBioseq_EditHandle eh = bsh.GetEditHandle(); eh.AddSeqdesc(*m); return true; } bool CCleanup::SetMolinfoBiomol(CBioseq_Handle bsh, CMolInfo::EBiomol biomol) { CSeqdesc_CI di(bsh, CSeqdesc::e_Molinfo); if (di) { if (di->GetMolinfo().IsSetTech() && di->GetMolinfo().GetBiomol() == biomol) { // no change necessary return false; } else { CSeqdesc* d = const_cast<CSeqdesc*>(&(*di)); d->SetMolinfo().SetBiomol(biomol); return true; } } CRef<CSeqdesc> m(new CSeqdesc()); m->SetMolinfo().SetBiomol(biomol); CBioseq_EditHandle eh = bsh.GetEditHandle(); eh.AddSeqdesc(*m); return true; } bool CCleanup::AddMissingMolInfo(CBioseq& seq, bool is_product) { if (!seq.IsSetInst() || !seq.GetInst().IsSetMol()) { return false; } bool needs_molinfo = true; if (seq.IsSetDescr()) { NON_CONST_ITERATE(CBioseq::TDescr::Tdata, it, seq.SetDescr().Set()) { if ((*it)->IsMolinfo()) { needs_molinfo = false; if (seq.IsAa() && (!(*it)->GetMolinfo().IsSetBiomol() || (*it)->GetMolinfo().GetBiomol() == CMolInfo::eBiomol_unknown)) { (*it)->SetMolinfo().SetBiomol(CMolInfo::eBiomol_peptide); } } } } if (needs_molinfo) { if (seq.IsAa()) { CRef<CSeqdesc> m(new CSeqdesc()); m->SetMolinfo().SetBiomol(CMolInfo::eBiomol_peptide); if (is_product) { m->SetMolinfo().SetTech(CMolInfo::eTech_concept_trans); } seq.SetDescr().Set().push_back(m); } else if (seq.GetInst().GetMol() == CSeq_inst::eMol_rna && is_product) { CRef<CSeqdesc> m(new CSeqdesc()); m->SetMolinfo().SetBiomol(CMolInfo::eBiomol_mRNA); m->SetMolinfo().SetTech(CMolInfo::eTech_standard); seq.SetDescr().Set().push_back(m); } } return needs_molinfo; } bool CCleanup::AddProteinTitle(CBioseq_Handle bsh) { if (!bsh.IsSetInst() || !bsh.GetInst().IsSetMol() || !bsh.IsAa()) { return false; } if (bsh.IsSetId()) { ITERATE(CBioseq_Handle::TId, it, bsh.GetId()) { // do not add titles for sequences with certain IDs switch (it->Which()) { case CSeq_id::e_Pir: case CSeq_id::e_Swissprot: case CSeq_id::e_Patent: case CSeq_id::e_Prf: case CSeq_id::e_Pdb: return false; break; default: break; } } } string new_defline = sequence::CDeflineGenerator().GenerateDefline(bsh, sequence::CDeflineGenerator::fIgnoreExisting); CAutoAddDesc title_desc(bsh.GetEditHandle().SetDescr(), CSeqdesc::e_Title); bool modified = title_desc.Set().SetTitle() != new_defline; // get or create a title if (modified) title_desc.Set().SetTitle().swap(new_defline); return modified; } bool CCleanup::RemoveNcbiCleanupObject(CSeq_entry &seq_entry) { bool rval = false; if (seq_entry.IsSetDescr()) { CBioseq::TDescr::Tdata::iterator it = seq_entry.SetDescr().Set().begin(); while (it != seq_entry.SetDescr().Set().end()) { if ((*it)->IsUser() && (*it)->GetUser().GetObjectType() == CUser_object::eObjectType_Cleanup){ it = seq_entry.SetDescr().Set().erase(it); rval = true; } else { ++it; } } if (seq_entry.SetDescr().Set().empty()) { if (seq_entry.IsSeq()) { seq_entry.SetSeq().ResetDescr(); } else if (seq_entry.IsSet()) { seq_entry.SetSet().ResetDescr(); } } } if (seq_entry.IsSet() && seq_entry.GetSet().IsSetSeq_set()) { NON_CONST_ITERATE(CBioseq_set::TSeq_set, it, seq_entry.SetSet().SetSeq_set()) { rval |= RemoveNcbiCleanupObject(**it); } } return rval; } void GetSourceDescriptors(const CSeq_entry& se, vector<const CSeqdesc* >& src_descs) { if (se.IsSetDescr()) { ITERATE(CBioseq::TDescr::Tdata, it, se.GetDescr().Get()) { if ((*it)->IsSource() && (*it)->GetSource().IsSetOrg()) { src_descs.push_back(*it); } } } if (se.IsSet() && se.GetSet().IsSetSeq_set()) { ITERATE(CBioseq_set::TSeq_set, it, se.GetSet().GetSeq_set()) { GetSourceDescriptors(**it, src_descs); } } } bool CCleanup::TaxonomyLookup(CSeq_entry_Handle seh) { bool any_changes = false; vector<CRef<COrg_ref> > rq_list; vector<const CSeqdesc* > src_descs; vector<CConstRef<CSeq_feat> > src_feats; GetSourceDescriptors(*(seh.GetCompleteSeq_entry()), src_descs); vector<const CSeqdesc* >::iterator desc_it = src_descs.begin(); while (desc_it != src_descs.end()) { // add org ref for descriptor to request list CRef<COrg_ref> org(new COrg_ref()); org->Assign((*desc_it)->GetSource().GetOrg()); rq_list.push_back(org); ++desc_it; } CFeat_CI feat(seh, SAnnotSelector(CSeqFeatData::e_Biosrc)); while (feat) { if (feat->GetData().GetBiosrc().IsSetOrg()) { // add org ref for feature to request list CRef<COrg_ref> org(new COrg_ref()); org->Assign(feat->GetData().GetBiosrc().GetOrg()); rq_list.push_back(org); // add feature to list src_feats.push_back(feat->GetOriginalSeq_feat()); } ++feat; } if (rq_list.size() > 0) { CTaxon3 taxon3; taxon3.Init(); CRef<CTaxon3_reply> reply = taxon3.SendOrgRefList(rq_list); if (reply) { CTaxon3_reply::TReply::const_iterator reply_it = reply->GetReply().begin(); // process descriptor responses desc_it = src_descs.begin(); while (reply_it != reply->GetReply().end() && desc_it != src_descs.end()) { if ((*reply_it)->IsData() && !(*desc_it)->GetSource().GetOrg().Equals((*reply_it)->GetData().GetOrg())) { any_changes = true; CSeqdesc* desc = const_cast<CSeqdesc*>(*desc_it); desc->SetSource().SetOrg().Assign((*reply_it)->GetData().GetOrg()); desc->SetSource().SetOrg().ResetSyn(); } ++reply_it; ++desc_it; } // process feature responses vector<CConstRef<CSeq_feat> >::iterator feat_it = src_feats.begin(); while (reply_it != reply->GetReply().end() && feat_it != src_feats.end()) { if ((*reply_it)->IsData() && !(*feat_it)->GetData().GetBiosrc().GetOrg().Equals((*reply_it)->GetData().GetOrg())) { any_changes = true; CRef<CSeq_feat> new_feat(new CSeq_feat()); new_feat->Assign(**feat_it); new_feat->SetData().SetBiosrc().SetOrg().Assign((*reply_it)->GetData().GetOrg()); CSeq_feat_Handle fh = seh.GetScope().GetSeq_featHandle(**feat_it); CSeq_feat_EditHandle efh(fh); efh.Replace(*new_feat); } ++reply_it; ++feat_it; } } } return any_changes; } CRef<CSeq_entry> AddProtein(const CSeq_feat& cds, CScope& scope) { CBioseq_Handle cds_bsh = scope.GetBioseqHandle(cds.GetLocation()); if (!cds_bsh) { return CRef<CSeq_entry>(NULL); } CSeq_entry_Handle seh = cds_bsh.GetSeq_entry_Handle(); if (!seh) { return CRef<CSeq_entry>(NULL); } CRef<CBioseq> new_product = CSeqTranslator::TranslateToProtein(cds, scope); if (new_product.Empty()) { return CRef<CSeq_entry>(NULL); } CRef<CSeqdesc> molinfo(new CSeqdesc()); molinfo->SetMolinfo().SetBiomol(CMolInfo::eBiomol_peptide); molinfo->SetMolinfo().SetTech(CMolInfo::eTech_concept_trans_a); new_product->SetDescr().Set().push_back(molinfo); if (cds.IsSetProduct()) { CRef<CSeq_id> prot_id(new CSeq_id()); prot_id->Assign(*(cds.GetProduct().GetId())); new_product->SetId().push_back(prot_id); } CRef<CSeq_entry> prot_entry(new CSeq_entry()); prot_entry->SetSeq(*new_product); CSeq_entry_EditHandle eh = seh.GetEditHandle(); if (!eh.IsSet()) { CBioseq_set_Handle nuc_parent = eh.GetParentBioseq_set(); if (nuc_parent && nuc_parent.IsSetClass() && nuc_parent.GetClass() == objects::CBioseq_set::eClass_nuc_prot) { eh = nuc_parent.GetParentEntry().GetEditHandle(); } } if (!eh.IsSet()) { eh.ConvertSeqToSet(); // move all descriptors on nucleotide sequence except molinfo, title, and create-date to set eh.SetSet().SetClass(CBioseq_set::eClass_nuc_prot); CConstRef<CBioseq_set> set = eh.GetSet().GetCompleteBioseq_set(); if (set && set->IsSetSeq_set()) { CConstRef<CSeq_entry> nuc = set->GetSeq_set().front(); CSeq_entry_EditHandle neh = eh.GetScope().GetSeq_entryEditHandle(*nuc); CBioseq_set::TDescr::Tdata::const_iterator it = nuc->GetDescr().Get().begin(); while (it != nuc->GetDescr().Get().end()) { if (!(*it)->IsMolinfo() && !(*it)->IsTitle() && !(*it)->IsCreate_date()) { CRef<CSeqdesc> copy(new CSeqdesc()); copy->Assign(**it); eh.AddSeqdesc(*copy); neh.RemoveSeqdesc(**it); if (nuc->IsSetDescr()) { it = nuc->GetDescr().Get().begin(); } else { break; } } else { ++it; } } } } CSeq_entry_EditHandle added = eh.AttachEntry(*prot_entry); return prot_entry; } CRef<objects::CSeq_id> GetNewProteinId(size_t& offset, objects::CSeq_entry_Handle seh, objects::CBioseq_Handle bsh) { string id_base; objects::CSeq_id_Handle hid; ITERATE(objects::CBioseq_Handle::TId, it, bsh.GetId()) { if (!hid || !it->IsBetter(hid)) { hid = *it; } } hid.GetSeqId()->GetLabel(&id_base, objects::CSeq_id::eContent); CRef<objects::CSeq_id> id(new objects::CSeq_id()); string& id_label = id->SetLocal().SetStr(); objects::CBioseq_Handle b_found; do { id_label = id_base + "_" + NStr::NumericToString(offset++); b_found = seh.GetBioseqHandle(*id); } while (b_found); return id; } bool CCleanup::SetGeneticCodes(CBioseq_Handle bsh) { if (!bsh) { return false; } if (!bsh.IsNa()) { return false; } int bioseqGenCode = 0; CSeqdesc_CI src(bsh, CSeqdesc::e_Source); if (src) { bioseqGenCode = src->GetSource().GetGenCode(); } bool any_changed = false; // set Cdregion's gcode from BioSource (unless except-text) SAnnotSelector sel(CSeqFeatData::e_Cdregion); CFeat_CI feat_ci(bsh, sel); for (; feat_ci; ++feat_ci) { const CSeq_feat& feat = feat_ci->GetOriginalFeature(); const CCdregion& cds = feat.GetData().GetCdregion(); int cdregionGenCode = (cds.IsSetCode() ? cds.GetCode().GetId() : 0); if (cdregionGenCode != bioseqGenCode) { // make cdregion's gencode match bioseq's gencode, // if allowed if (!feat.HasExceptionText("genetic code exception")) { CRef<CSeq_feat> new_feat(new CSeq_feat); new_feat->Assign(feat); CCdregion& new_cds = new_feat->SetData().SetCdregion(); new_cds.ResetCode(); new_cds.SetCode().SetId(bioseqGenCode); CSeq_feat_EditHandle edit_handle(*feat_ci); edit_handle.Replace(*new_feat); any_changed = true; } } } return any_changed; } // return position of " [" + sOrganism + "]", but only if it's // at the end and there are characters before it. // Also, returns the position of the organelle prefix in the title. static SIZE_TYPE s_TitleEndsInOrganism( const string & sTitle, const string & sOrganism, SIZE_TYPE * out_piOrganellePos) { if (out_piOrganellePos) { *out_piOrganellePos = NPOS; } SIZE_TYPE answer = NPOS; const string sPattern = " [" + sOrganism + "]"; if (NStr::EndsWith(sTitle, sPattern, NStr::eNocase)) { answer = sTitle.length() - sPattern.length(); if (answer < 1) { // title must have something before the pattern answer = NPOS; } } else { answer = NStr::Find(sTitle, sPattern, NStr::eNocase, NStr::eReverseSearch); if (answer < 1 || answer == NPOS) { // pattern not found answer = NPOS; } } // find organelle prefix if (out_piOrganellePos) { for (unsigned int genome = CBioSource::eGenome_chloroplast; genome <= CBioSource::eGenome_chromatophore; genome++) { if (genome != CBioSource::eGenome_extrachrom && genome != CBioSource::eGenome_transposon && genome != CBioSource::eGenome_insertion_seq && genome != CBioSource::eGenome_proviral && genome != CBioSource::eGenome_virion && genome != CBioSource::eGenome_chromosome) { string organelle = " (" + CBioSource::GetOrganelleByGenome(genome) + ")"; SIZE_TYPE possible_organelle_start_pos = NStr::Find(sTitle, organelle); if (possible_organelle_start_pos != NPOS && NStr::EndsWith(CTempString(sTitle, 0, answer), organelle)) { *out_piOrganellePos = possible_organelle_start_pos; break; } } } } return answer; } static void s_RemoveOrgFromEndOfProtein(CBioseq& seq, string taxname) { if (taxname.empty()) return; SIZE_TYPE taxlen = taxname.length(); EDIT_EACH_SEQANNOT_ON_BIOSEQ(annot_it, seq) { CSeq_annot& annot = **annot_it; if (!annot.IsFtable()) continue; EDIT_EACH_FEATURE_ON_ANNOT(feat_it, annot) { CSeq_feat& feat = **feat_it; CSeqFeatData& data = feat.SetData(); if (!data.IsProt()) continue; CProt_ref& prot_ref = data.SetProt(); EDIT_EACH_NAME_ON_PROTREF(it, prot_ref) { string str = *it; if (str.empty()) continue; int len = str.length(); if (len < 5) continue; if (str[len - 1] != ']') continue; SIZE_TYPE cp = NStr::Find(str, "[", NStr::eCase, NStr::eReverseSearch); if (cp == NPOS) continue; string suffix = str.substr(cp + 1); if (NStr::StartsWith(suffix, "NAD")) continue; if (suffix.length() != taxlen + 1) continue; if (NStr::StartsWith(suffix, taxname)) { str.erase(cp); Asn2gnbkCompressSpaces(str); *it = str; } } } } } bool CCleanup::AddPartialToProteinTitle(CBioseq &bioseq) { // Bail if not protein if (!FIELD_CHAIN_OF_2_IS_SET(bioseq, Inst, Mol) || bioseq.GetInst().GetMol() != NCBI_SEQMOL(aa)) { return false; } // Bail if record is swissprot FOR_EACH_SEQID_ON_BIOSEQ(seqid_itr, bioseq) { const CSeq_id& seqid = **seqid_itr; if (FIELD_IS(seqid, Swissprot)) { return false; } } // gather some info from the Seqdesc's on the bioseq, into // the following variables bool bPartial = false; string sTaxname; string sOldName; string *psTitle = NULL; string organelle = kEmptyStr; // iterate for title EDIT_EACH_SEQDESC_ON_BIOSEQ(descr_iter, bioseq) { CSeqdesc &descr = **descr_iter; if (descr.IsTitle()) { psTitle = &GET_MUTABLE(descr, Title); } } // iterate Seqdescs from bottom to top // accumulate seqdescs into here typedef vector< CConstRef<CSeqdesc> > TSeqdescVec; TSeqdescVec vecSeqdesc; { FOR_EACH_SEQDESC_ON_BIOSEQ(descr_iter, bioseq) { vecSeqdesc.push_back(CConstRef<CSeqdesc>(&**descr_iter)); } // climb up to get parent Seqdescs CConstRef<CBioseq_set> bioseq_set(bioseq.GetParentSet()); for (; bioseq_set; bioseq_set = bioseq_set->GetParentSet()) { FOR_EACH_SEQDESC_ON_SEQSET(descr_iter, *bioseq_set) { vecSeqdesc.push_back(CConstRef<CSeqdesc>(&**descr_iter)); } } } ITERATE(TSeqdescVec, descr_iter, vecSeqdesc) { const CSeqdesc &descr = **descr_iter; if (descr.IsMolinfo() && FIELD_IS_SET(descr.GetMolinfo(), Completeness)) { switch (GET_FIELD(descr.GetMolinfo(), Completeness)) { case NCBI_COMPLETENESS(partial): case NCBI_COMPLETENESS(no_left): case NCBI_COMPLETENESS(no_right): case NCBI_COMPLETENESS(no_ends): bPartial = true; break; default: break; } // stop at first molinfo break; } } ITERATE(TSeqdescVec, descr_iter, vecSeqdesc) { const CSeqdesc &descr = **descr_iter; if (descr.IsSource()) { const TBIOSOURCE_GENOME genome = (descr.GetSource().CanGetGenome() ? descr.GetSource().GetGenome() : CBioSource::eGenome_unknown); if (genome >= CBioSource::eGenome_chloroplast && genome <= CBioSource::eGenome_chromatophore && genome != CBioSource::eGenome_extrachrom && genome != CBioSource::eGenome_transposon && genome != CBioSource::eGenome_insertion_seq && genome != CBioSource::eGenome_proviral && genome != CBioSource::eGenome_virion && genome != CBioSource::eGenome_chromosome) { organelle = CBioSource::GetOrganelleByGenome(genome); } if (FIELD_IS_SET(descr.GetSource(), Org)) { const COrg_ref & org = GET_FIELD(descr.GetSource(), Org); if (!RAW_FIELD_IS_EMPTY_OR_UNSET(org, Taxname)) { sTaxname = GET_FIELD(org, Taxname); } if (NStr::StartsWith(sTaxname, organelle, NStr::eNocase)) { organelle = kEmptyStr; } FOR_EACH_ORGMOD_ON_ORGREF(mod_iter, org) { const COrgMod & orgmod = **mod_iter; if (FIELD_EQUALS(orgmod, Subtype, NCBI_ORGMOD(old_name))) { sOldName = GET_FIELD(orgmod, Subname); } } } // stop at first source break; } } s_RemoveOrgFromEndOfProtein(bioseq, sTaxname); // bail if no title if ((NULL == psTitle) || psTitle->empty()) { return false; } // put title into a reference, // just because it's more convenient than a pointer string & sTitle = *psTitle; // remember original so we can see if we changed it const string sOriginalTitle = sTitle; // search for partial, must be just before bracketed organism SIZE_TYPE partialPos = NStr::Find(sTitle, ", partial ["); if (partialPos == NPOS) { partialPos = NStr::Find(sTitle, ", partial ("); } // find oldname or taxname in brackets at end of protein title SIZE_TYPE penult = NPOS; SIZE_TYPE suffixPos = NPOS; // will point to " [${organism name}]" at end if (!sOldName.empty() && !sTaxname.empty()) { suffixPos = s_TitleEndsInOrganism(sTitle, sOldName, &penult); } if (suffixPos == NPOS && !sTaxname.empty()) { suffixPos = s_TitleEndsInOrganism(sTitle, sTaxname, &penult); if (suffixPos != NPOS) { if (NStr::IsBlank(organelle) && penult != NPOS) { } else if (!NStr::IsBlank(organelle) && penult == NPOS) { } else if (penult != NPOS && sTitle.substr(penult) == organelle) { } else { // bail if no need to change partial text or [organism name] if (bPartial && partialPos != NPOS) { return false; } else if (!bPartial && partialPos == NPOS){ return false; } } } } // do not change unless [genus species] was at the end if (suffixPos == NPOS) { return false; } // truncate bracketed info from end of title, will replace with current taxname sTitle.resize(suffixPos); if (penult != NPOS) { sTitle.resize(penult); } // if ", partial [" was indeed just before the [genus species], it will now be ", partial" // Note: 9 is length of ", partial" if (!bPartial && partialPos != string::npos && (partialPos == (sTitle.length() - 9))) { sTitle.resize(partialPos); } NStr::TruncateSpacesInPlace(sTitle); // if (bPartial && partialPos == NPOS) { sTitle += ", partial"; } if (!NStr::IsBlank(organelle)) { sTitle += " (" + string(organelle) + ")"; } if (!sTaxname.empty()) { sTitle += " [" + sTaxname + "]"; } if (sTitle != sOriginalTitle) { return true; } else { return false; } } bool CCleanup::RemovePseudoProduct(CSeq_feat& cds, CScope& scope) { if (!sequence::IsPseudo(cds, scope) || !cds.IsSetData() || !cds.GetData().IsCdregion() || !cds.IsSetProduct()) { return false; } CBioseq_Handle pseq = scope.GetBioseqHandle(cds.GetProduct()); if (pseq) { CFeat_CI prot(pseq, CSeqFeatData::eSubtype_prot); if (prot) { string label; if (prot->GetData().GetProt().IsSetName() && !prot->GetData().GetProt().GetName().empty()) { label = prot->GetData().GetProt().GetName().front(); } else if (prot->GetData().GetProt().IsSetDesc()) { label = prot->GetData().GetProt().GetDesc(); } if (!NStr::IsBlank(label)) { if (cds.IsSetComment() && !NStr::IsBlank(cds.GetComment())) { cds.SetComment(cds.GetComment() + "; " + label); } else { cds.SetComment(label); } } } CBioseq_EditHandle pseq_e(pseq); pseq_e.Remove(); } cds.ResetProduct(); return true; } bool CCleanup::ExpandGeneToIncludeChildren(CSeq_feat& gene, CTSE_Handle& tse) { if (!gene.IsSetXref() || !gene.IsSetLocation() || !gene.GetLocation().IsInt()) { return false; } bool any_change = false; TSeqPos gene_start = gene.GetLocation().GetStart(eExtreme_Positional); TSeqPos gene_stop = gene.GetLocation().GetStop(eExtreme_Positional); ITERATE(CSeq_feat::TXref, xit, gene.GetXref()) { if ((*xit)->IsSetId() && (*xit)->GetId().IsLocal()) { const CTSE_Handle::TFeatureId& feat_id = (*xit)->GetId().GetLocal(); CTSE_Handle::TSeq_feat_Handles far_feats = tse.GetFeaturesWithId(CSeqFeatData::eSubtype_any, feat_id); ITERATE(CTSE_Handle::TSeq_feat_Handles, f, far_feats) { TSeqPos f_start = f->GetLocation().GetStart(eExtreme_Positional); TSeqPos f_stop = f->GetLocation().GetStop(eExtreme_Positional); if (f_start < gene_start) { gene.SetLocation().SetInt().SetFrom(f_start); gene_start = f_start; any_change = true; } if (f_stop > gene_stop) { gene.SetLocation().SetInt().SetTo(f_stop); gene_stop = f_stop; any_change = true; } } } } return any_change; } bool CCleanup::WGSCleanup(CSeq_entry_Handle entry) { bool any_changes = false; size_t protein_id_counter = 1; SAnnotSelector sel(CSeqFeatData::e_Cdregion); for (CFeat_CI cds_it(entry, sel); cds_it; ++cds_it) { bool change_this_cds = false; CRef<CSeq_feat> new_cds(new CSeq_feat()); new_cds->Assign(*(cds_it->GetSeq_feat())); if (sequence::IsPseudo(*(cds_it->GetSeq_feat()), entry.GetScope())) { change_this_cds = RemovePseudoProduct(*new_cds, entry.GetScope()); } else { change_this_cds |= SetBestFrame(*new_cds, entry.GetScope()); change_this_cds |= SetCDSPartialsByFrameAndTranslation(*new_cds, entry.GetScope()); // retranslate if (new_cds->IsSetProduct() && entry.GetScope().GetBioseqHandle(new_cds->GetProduct())) { any_changes |= feature::RetranslateCDS(*new_cds, entry.GetScope()); } else { // need to set product if not set if (!new_cds->IsSetProduct() && !sequence::IsPseudo(*new_cds, entry.GetScope())) { CRef<CSeq_id> new_id = GetNewProteinId(protein_id_counter, entry, entry.GetScope().GetBioseqHandle(new_cds->GetLocation())); if (new_id) { new_cds->SetProduct().SetWhole().Assign(*new_id); change_this_cds = true; } } if (new_cds->IsSetProduct()) { CRef<CSeq_entry> prot = AddProtein(*new_cds, entry.GetScope()); if (prot) { any_changes = true; } } any_changes |= feature::AdjustForCDSPartials(*new_cds, entry); } //prefer ncbieaa if (new_cds->IsSetProduct()) { CBioseq_Handle p = entry.GetScope().GetBioseqHandle(new_cds->GetProduct()); if (p && p.IsSetInst() && p.GetInst().IsSetSeq_data() && p.GetInst().GetSeq_data().IsIupacaa()) { CBioseq_EditHandle peh(p); string current = p.GetInst().GetSeq_data().GetIupacaa().Get(); CRef<CSeq_inst> new_inst(new CSeq_inst()); new_inst->Assign(p.GetInst()); new_inst->SetSeq_data().SetNcbieaa().Set(current); peh.SetInst(*new_inst); any_changes = true; } } string current_name = GetProteinName(*new_cds, entry.GetScope()); if (NStr::IsBlank(current_name)) { SetProteinName(*new_cds, "hypothetical protein", false, entry.GetScope()); current_name = "hypothetical protein"; change_this_cds = true; } CConstRef<CSeq_feat> mrna = sequence::GetmRNAforCDS(*(cds_it->GetSeq_feat()), entry.GetScope()); if (mrna) { bool change_mrna = false; CRef<CSeq_feat> new_mrna(new CSeq_feat()); new_mrna->Assign(*mrna); // Make mRNA name match coding region protein string mrna_name = new_mrna->GetData().GetRna().GetRnaProductName(); if (NStr::IsBlank(mrna_name) || (!NStr::Equal(current_name, "hypothetical protein") && !NStr::Equal(current_name, mrna_name))) { string remainder; new_mrna->SetData().SetRna().SetRnaProductName(current_name, remainder); change_mrna = true; } // Adjust mRNA partials to match coding region change_mrna |= feature::CopyFeaturePartials(*new_mrna, *new_cds); if (change_mrna) { CSeq_feat_Handle fh = entry.GetScope().GetSeq_featHandle(*mrna); CSeq_feat_EditHandle feh(fh); feh.Replace(*new_mrna); any_changes = true; } } } if (change_this_cds) { CSeq_feat_EditHandle cds_h(*cds_it); cds_h.Replace(*new_cds); any_changes = true; //also need to redo protein title } } CTSE_Handle tse = entry.GetTSE_Handle(); for (CFeat_CI gene_it(entry, SAnnotSelector(CSeqFeatData::e_Gene)); gene_it; ++gene_it) { bool change_this_gene; CRef<CSeq_feat> new_gene(new CSeq_feat()); new_gene->Assign(*(gene_it->GetSeq_feat())); change_this_gene = ExpandGeneToIncludeChildren(*new_gene, tse); change_this_gene |= SetGenePartialByLongestContainedFeature(*new_gene, entry.GetScope()); if (change_this_gene) { CSeq_feat_EditHandle gene_h(*gene_it); gene_h.Replace(*new_gene); any_changes = true; } } NormalizeDescriptorOrder(entry); for (CBioseq_CI bi(entry, CSeq_inst::eMol_na); bi; ++bi) { any_changes |= SetGeneticCodes(*bi); } CRef<CCleanupChange> changes(makeCleanupChange(0)); CNewCleanup_imp exclean(changes, 0); exclean.ExtendedCleanup(entry); return any_changes; } bool CCleanup::x_HasShortIntron(const CSeq_loc& loc, size_t min_len) { CSeq_loc_CI li(loc); while (li && li.IsEmpty()) { ++li; } if (!li) { return false; } while (li) { TSeqPos prev_end; ENa_strand prev_strand; if (li.IsSetStrand() && li.GetStrand() == eNa_strand_minus) { prev_end = li.GetRange().GetFrom(); prev_strand = eNa_strand_minus; } else { prev_end = li.GetRange().GetTo(); prev_strand = eNa_strand_plus; } ++li; while (li && li.IsEmpty()) { ++li; } if (li) { TSeqPos this_start; ENa_strand this_strand; if (li.IsSetStrand() && li.GetStrand() == eNa_strand_minus) { this_start = li.GetRange().GetTo(); this_strand = eNa_strand_minus; } else { this_start = li.GetRange().GetFrom(); this_strand = eNa_strand_plus; } if (this_strand == prev_strand) { if (abs((long int)this_start - (long int)prev_end) < min_len) { return true; } } } } return false; } const string kLowQualitySequence = "low-quality sequence region"; bool CCleanup::x_AddLowQualityException(CSeq_feat& feat) { bool any_change = false; if (!feat.IsSetExcept()) { any_change = true; feat.SetExcept(true); } if (!feat.IsSetExcept_text() || NStr::IsBlank(feat.GetExcept_text())) { feat.SetExcept_text(kLowQualitySequence); any_change = true; } else if (NStr::Find(feat.GetExcept_text(), kLowQualitySequence) == string::npos) { feat.SetExcept_text(feat.GetExcept_text() + "; " + kLowQualitySequence); any_change = true; } return any_change; } bool CCleanup::x_AddLowQualityException(CSeq_entry_Handle entry, CSeqFeatData::ESubtype subtype) { bool any_changes = false; SAnnotSelector sel(subtype); for (CFeat_CI cds_it(entry, sel); cds_it; ++cds_it) { bool change_this_cds = false; CRef<CSeq_feat> new_cds(new CSeq_feat()); new_cds->Assign(*(cds_it->GetSeq_feat())); if (!sequence::IsPseudo(*(cds_it->GetSeq_feat()), entry.GetScope()) && x_HasShortIntron(cds_it->GetLocation())) { change_this_cds = x_AddLowQualityException(*new_cds); } if (change_this_cds) { CSeq_feat_EditHandle cds_h(*cds_it); cds_h.Replace(*new_cds); any_changes = true; } } return any_changes; } bool CCleanup::AddLowQualityException(CSeq_entry_Handle entry) { bool any_changes = x_AddLowQualityException(entry, CSeqFeatData::eSubtype_cdregion); any_changes |= x_AddLowQualityException(entry, CSeqFeatData::eSubtype_mRNA); return any_changes; } // maps the type of seqdesc to the order it should be in // (lowest to highest) typedef SStaticPair<CSeqdesc::E_Choice, int> TSeqdescOrderElem; static const TSeqdescOrderElem sc_seqdesc_order_map[] = { // Note that ordering must match ordering // in CSeqdesc::E_Choice { CSeqdesc::e_Mol_type, 13 }, { CSeqdesc::e_Modif, 14 }, { CSeqdesc::e_Method, 15 }, { CSeqdesc::e_Name, 7 }, { CSeqdesc::e_Title, 1 }, { CSeqdesc::e_Org, 16 }, { CSeqdesc::e_Comment, 6 }, { CSeqdesc::e_Num, 11 }, { CSeqdesc::e_Maploc, 9 }, { CSeqdesc::e_Pir, 18 }, { CSeqdesc::e_Genbank, 22 }, { CSeqdesc::e_Pub, 5 }, { CSeqdesc::e_Region, 10 }, { CSeqdesc::e_User, 8 }, { CSeqdesc::e_Sp, 17 }, { CSeqdesc::e_Dbxref, 12 }, { CSeqdesc::e_Embl, 21 }, { CSeqdesc::e_Create_date, 24 }, { CSeqdesc::e_Update_date, 25 }, { CSeqdesc::e_Prf, 19 }, { CSeqdesc::e_Pdb, 20 }, { CSeqdesc::e_Het, 4 }, { CSeqdesc::e_Source, 2 }, { CSeqdesc::e_Molinfo, 3 }, { CSeqdesc::e_Modelev, 23 } }; typedef CStaticPairArrayMap<CSeqdesc::E_Choice, int> TSeqdescOrderMap; DEFINE_STATIC_ARRAY_MAP(TSeqdescOrderMap, sc_SeqdescOrderMap, sc_seqdesc_order_map); static int s_SeqDescToOrdering(CSeqdesc::E_Choice chs) { // ordering assigned to unknown const int unknown_seqdesc = (1 + sc_SeqdescOrderMap.size()); TSeqdescOrderMap::const_iterator find_iter = sc_SeqdescOrderMap.find(chs); if (find_iter == sc_SeqdescOrderMap.end()) { return unknown_seqdesc; } return find_iter->second; } static bool s_SeqDescLessThan(const CRef<CSeqdesc> &desc1, const CRef<CSeqdesc> &desc2) { CSeqdesc::E_Choice chs1, chs2; chs1 = desc1->Which(); chs2 = desc2->Which(); return (s_SeqDescToOrdering(chs1) < s_SeqDescToOrdering(chs2)); } bool CCleanup::NormalizeDescriptorOrder(CSeq_descr& descr) { bool rval = false; if (!seq_mac_is_sorted(descr.Set().begin(), descr.Set().end(), s_SeqDescLessThan)) { descr.Set().sort(s_SeqDescLessThan); rval = true; } return rval; } bool CCleanup::NormalizeDescriptorOrder(CSeq_entry_Handle seh) { bool rval = false; CSeq_entry_CI ci(seh, CSeq_entry_CI::fRecursive); while (ci) { CSeq_entry_EditHandle edit(*ci); if (edit.IsSetDescr()) { rval |= NormalizeDescriptorOrder(edit.SetDescr()); } ++ci; } return rval; } bool CCleanup::RemoveUnseenTitles(CSeq_entry_EditHandle::TSeq seq) { bool removed = false; if (seq.IsSetDescr()) { CConstRef<CSeqdesc> last_title(NULL); ITERATE(CBioseq::TDescr::Tdata, d, seq.GetDescr().Get()) { if ((*d)->IsTitle()) { if (last_title) { seq.RemoveSeqdesc(*last_title); removed = true; } last_title.Reset(d->GetPointer()); } } } return removed; } bool CCleanup::RemoveUnseenTitles(CSeq_entry_EditHandle::TSet set) { bool removed = false; if (set.IsSetDescr()) { CConstRef<CSeqdesc> last_title(NULL); ITERATE(CBioseq::TDescr::Tdata, d, set.GetDescr().Get()) { if ((*d)->IsTitle()) { if (last_title) { set.RemoveSeqdesc(*last_title); removed = true; } last_title.Reset(d->GetPointer()); } } } return removed; } bool CCleanup::AddGenBankWrapper(CSeq_entry_Handle seh) { if (seh.IsSet() && seh.GetSet().IsSetClass() && seh.GetSet().GetClass() == CBioseq_set::eClass_genbank) { return false; } CSeq_entry_EditHandle eh(seh); eh.ConvertSeqToSet(CBioseq_set::eClass_genbank); return true; } void s_GetAuthorsString(string *out_authors, const CAuth_list& auth_list) { string & auth_str = *out_authors; auth_str.clear(); if (!auth_list.IsSetNames()) { return; } vector<string> name_list; if (auth_list.GetNames().IsStd()) { ITERATE(CAuth_list::TNames::TStd, auth_it, auth_list.GetNames().GetStd()) { if ((*auth_it)->IsSetName()) { string label = ""; (*auth_it)->GetName().GetLabel(&label); name_list.push_back(label); } } } else if (auth_list.GetNames().IsMl()) { copy(BEGIN_COMMA_END(auth_list.GetNames().GetMl()), back_inserter(name_list)); } else if (auth_list.GetNames().IsStr()) { copy(BEGIN_COMMA_END(auth_list.GetNames().GetStr()), back_inserter(name_list)); } if (name_list.size() == 0) { return; } else if (name_list.size() == 1) { auth_str = name_list.back(); return; } // join most of them by commas, but the last one gets an "and" string last_author; last_author.swap(name_list.back()); name_list.pop_back(); // swap is faster than assignment NStr::Join(name_list, ", ").swap(auth_str); auth_str += "and "; auth_str += last_author; return; } void s_GetAuthorsString( string *out_authors_string, const CPubdesc& pd) { string & authors_string = *out_authors_string; authors_string.clear(); FOR_EACH_PUB_ON_PUBDESC(pub, pd) { if ((*pub)->IsSetAuthors()) { s_GetAuthorsString(&authors_string, (*pub)->GetAuthors()); break; } } } void CCleanup::GetPubdescLabels (const CPubdesc& pd, vector<int>& pmids, vector<int>& muids, vector<int>& serials, vector<string>& published_labels, vector<string>& unpublished_labels) { string label = ""; bool is_published = false; bool need_label = false; if (!pd.IsSetPub()) { return; } ITERATE(CPubdesc::TPub::Tdata, it, pd.GetPub().Get()) { if ((*it)->IsPmid()) { pmids.push_back((*it)->GetPmid()); is_published = true; } else if ((*it)->IsMuid()) { muids.push_back((*it)->GetMuid()); is_published = true; } else if ((*it)->IsGen()) { if ((*it)->GetGen().IsSetCit() && NStr::StartsWith((*it)->GetGen().GetCit(), "BackBone id_pub", NStr::eNocase)) { need_label = true; } if ((*it)->GetGen().IsSetSerial_number()) { serials.push_back((*it)->GetGen().GetSerial_number()); if ((*it)->GetGen().IsSetCit() || (*it)->GetGen().IsSetJournal() || (*it)->GetGen().IsSetDate()) { need_label = true; } } else { need_label = true; } } else if ((*it)->IsArticle() && (*it)->GetArticle().IsSetIds()) { is_published = true; ITERATE(CArticleIdSet::Tdata, id, (*it)->GetArticle().GetIds().Get()) { if ((*id)->IsPubmed()) { pmids.push_back((*id)->GetPubmed()); is_published = true; } else if ((*id)->IsMedline()) { muids.push_back((*id)->GetMedline()); } } need_label = true; } else { need_label = true; } if (need_label && NStr::IsBlank(label)) { // create unique label (*it)->GetLabel(&label, CPub::eContent, true); string auth_str; s_GetAuthorsString(&auth_str, pd); label += "; "; label += auth_str; } } if (!NStr::IsBlank(label)) { if (is_published) { published_labels.push_back(label); } else { unpublished_labels.push_back(label); } } } vector<CConstRef<CPub> > CCleanup::GetCitationList(CBioseq_Handle bsh) { vector<CConstRef<CPub> > pub_list; // first get descriptor pubs CSeqdesc_CI di(bsh, CSeqdesc::e_Pub); while (di) { vector<int> pmids; vector<int> muids; vector<int> serials; vector<string> published_labels; vector<string> unpublished_labels; GetPubdescLabels(di->GetPub(), pmids, muids, serials, published_labels, unpublished_labels); if (pmids.size() > 0) { CRef<CPub> pub(new CPub()); pub->SetPmid().Set(pmids[0]); pub_list.push_back(pub); } else if (muids.size() > 0) { CRef<CPub> pub(new CPub()); pub->SetMuid(muids[0]); pub_list.push_back(pub); } else if (serials.size() > 0) { CRef<CPub> pub(new CPub()); pub->SetGen().SetSerial_number(serials[0]); pub_list.push_back(pub); } else if (published_labels.size() > 0) { CRef<CPub> pub(new CPub()); pub->SetGen().SetCit(published_labels[0]); pub_list.push_back(pub); } else if (unpublished_labels.size() > 0) { CRef<CPub> pub(new CPub()); pub->SetGen().SetCit(unpublished_labels[0]); pub_list.push_back(pub); } ++di; } // now get pub features CFeat_CI fi(bsh, SAnnotSelector(CSeqFeatData::e_Pub)); while (fi) { vector<int> pmids; vector<int> muids; vector<int> serials; vector<string> published_labels; vector<string> unpublished_labels; GetPubdescLabels(fi->GetData().GetPub(), pmids, muids, serials, published_labels, unpublished_labels); if (pmids.size() > 0) { CRef<CPub> pub(new CPub()); pub->SetPmid().Set(pmids[0]); pub_list.push_back(pub); } else if (muids.size() > 0) { CRef<CPub> pub(new CPub()); pub->SetMuid(muids[0]); pub_list.push_back(pub); } else if (serials.size() > 0) { CRef<CPub> pub(new CPub()); pub->SetGen().SetSerial_number(serials[0]); pub_list.push_back(pub); } else if (published_labels.size() > 0) { CRef<CPub> pub(new CPub()); pub->SetGen().SetCit(published_labels[0]); pub_list.push_back(pub); } else if (unpublished_labels.size() > 0) { CRef<CPub> pub(new CPub()); pub->SetGen().SetCit(unpublished_labels[0]); pub_list.push_back(pub); } ++fi; } return pub_list; } bool CCleanup::RemoveDuplicatePubs(CSeq_descr& descr) { bool any_change = false; CSeq_descr::Tdata::iterator it1 = descr.Set().begin(); while (it1 != descr.Set().end()) { if ((*it1)->IsPub()) { CSeq_descr::Tdata::iterator it2 = it1; ++it2; while (it2 != descr.Set().end()) { if ((*it2)->IsPub() && (*it1)->GetPub().Equals((*it2)->GetPub())) { it2 = descr.Set().erase(it2); any_change = true; } else { ++it2; } } } ++it1; } return any_change; } bool s_FirstPubMatchesSecond(const CPubdesc& pd1, const CPubdesc& pd2) { if (pd1.Equals(pd2)) { return true; } else if (pd1.IsSetPub() && pd2.IsSetPub() && pd1.GetPub().Get().size() == 1) { ITERATE(CPubdesc::TPub::Tdata, it, pd2.GetPub().Get()) { if (pd1.GetPub().Get().front()->Equals(**it)) { return true; } } } return false; } bool CCleanup::PubAlreadyInSet(const CPubdesc& pd, const CSeq_descr& descr) { ITERATE(CSeq_descr::Tdata, d, descr.Get()) { if ((*d)->IsPub() && s_FirstPubMatchesSecond(pd, (*d)->GetPub())) { return true; } } return false; } bool CCleanup::OkToPromoteNpPub(const CBioseq& b) { bool is_embl_or_ddbj = false; ITERATE(CBioseq::TId, id, b.GetId()) { if ((*id)->IsEmbl() || (*id)->IsDdbj()) { is_embl_or_ddbj = true; break; } } return !is_embl_or_ddbj; } bool CCleanup::OkToPromoteNpPub(const CPubdesc& pd) { if (pd.IsSetNum() || pd.IsSetName() || pd.IsSetFig() || pd.IsSetComment()) { return false; } else { return true; } } void CCleanup::MoveOneFeatToPubdesc(CSeq_feat_Handle feat, CRef<CSeqdesc> d, CBioseq_Handle b, bool remove_feat) { // add descriptor to nuc-prot parent or sequence itself CBioseq_set_Handle parent = b.GetParentBioseq_set(); if (!CCleanup::OkToPromoteNpPub(*(b.GetCompleteBioseq()))) { // add to sequence CBioseq_EditHandle eh(b); eh.AddSeqdesc(*d); RemoveDuplicatePubs(eh.SetDescr()); NormalizeDescriptorOrder(eh.SetDescr()); } else if (parent && parent.IsSetClass() && parent.GetClass() == CBioseq_set::eClass_nuc_prot && parent.IsSetDescr() && PubAlreadyInSet(d->GetPub(), parent.GetDescr())) { // don't add descriptor, just delete feature } else if (OkToPromoteNpPub((d)->GetPub()) && parent && parent.IsSetClass() && parent.GetClass() == CBioseq_set::eClass_nuc_prot) { CBioseq_set_EditHandle eh(parent); eh.AddSeqdesc(*d); RemoveDuplicatePubs(eh.SetDescr()); NormalizeDescriptorOrder(eh.SetDescr()); } else { CBioseq_EditHandle eh(b); eh.AddSeqdesc(*d); RemoveDuplicatePubs(eh.SetDescr()); NormalizeDescriptorOrder(eh.SetDescr()); } if (remove_feat) { // remove feature CSeq_feat_EditHandle feh(feat); feh.Remove(); } } bool CCleanup::ConvertPubFeatsToPubDescs(CSeq_entry_Handle seh) { bool any_change = false; for (CBioseq_CI b(seh); b; ++b) { for (CFeat_CI p(*b, CSeqFeatData::e_Pub); p; ++p) { if (p->GetLocation().IsInt() && p->GetLocation().GetStart(eExtreme_Biological) == 0 && p->GetLocation().GetStop(eExtreme_Biological) == b->GetBioseqLength() - 1) { CRef<CSeqdesc> d(new CSeqdesc()); d->SetPub().Assign(p->GetData().GetPub()); if (p->IsSetComment()) { if (d->GetPub().IsSetComment() && !NStr::IsBlank(d->GetPub().GetComment())) { d->SetPub().SetComment(d->GetPub().GetComment() + "; " + p->GetComment()); } else { d->SetPub().SetComment(); } } MoveOneFeatToPubdesc(*p, d, *b); any_change = true; } } } return any_change; } bool IsSiteRef(const CSeq_feat& sf) { if (sf.GetData().IsImp() && sf.GetData().GetImp().IsSetKey() && NStr::Equal(sf.GetData().GetImp().GetKey(), "Site-ref")) { return true; } else { return false; } } bool CCleanup::IsMinPub(const CPubdesc& pd, bool is_refseq_prot) { if (!pd.IsSetPub()) { return true; } bool found_non_minimal = false; ITERATE(CPubdesc::TPub::Tdata, it, pd.GetPub().Get()) { if ((*it)->IsMuid() || (*it)->IsPmid()) { if (is_refseq_prot) { found_non_minimal = true; break; } } else if ((*it)->IsGen()) { const CCit_gen& gen = (*it)->GetGen(); if (gen.IsSetCit() && !gen.IsSetJournal() && !gen.IsSetAuthors() && !gen.IsSetVolume() && !gen.IsSetPages()) { //minimalish, keep looking } else { found_non_minimal = true; } } else { found_non_minimal = true; break; } } return !found_non_minimal; } bool CCleanup::RescueSiteRefPubs(CSeq_entry_Handle seh) { bool found_site_ref = false; CFeat_CI f(seh, CSeqFeatData::e_Imp); while (f && !found_site_ref) { if (IsSiteRef(*(f->GetSeq_feat()))) { found_site_ref = true; } ++f; } if (!found_site_ref) { return false; } bool any_change = false; for (CBioseq_CI b(seh); b; ++b) { bool is_refseq_prot = false; if (b->IsAa()) { ITERATE(CBioseq::TId, id_it, b->GetCompleteBioseq()->GetId()) { if ((*id_it)->IsOther()) { is_refseq_prot = true; break; } } } for (CFeat_CI p(*b); p; ++p) { if (!p->IsSetCit() || p->GetCit().Which() != CPub_set::e_Pub) { continue; } bool is_site_ref = IsSiteRef(*(p->GetSeq_feat())); ITERATE(CSeq_feat::TCit::TPub, c, p->GetCit().GetPub()) { CRef<CSeqdesc> d(new CSeqdesc()); if ((*c)->IsEquiv()) { ITERATE(CPub_equiv::Tdata, t, (*c)->GetEquiv().Get()) { CRef<CPub> pub_copy(new CPub()); pub_copy->Assign(**t); d->SetPub().SetPub().Set().push_back(pub_copy); } } else { CRef<CPub> pub_copy(new CPub()); pub_copy->Assign(**c); d->SetPub().SetPub().Set().push_back(pub_copy); } if (is_site_ref) { d->SetPub().SetReftype(CPubdesc::eReftype_sites); } else { d->SetPub().SetReftype(CPubdesc::eReftype_feats); } CRef<CCleanupChange> changes(makeCleanupChange(0)); CNewCleanup_imp pubclean(changes, 0); pubclean.BasicCleanup(d->SetPub(), ShouldStripPubSerial(*(b->GetCompleteBioseq()))); if (!IsMinPub(d->SetPub(), is_refseq_prot)) { MoveOneFeatToPubdesc(*p, d, *b, false); } } if (is_site_ref) { CSeq_feat_EditHandle feh(*p); CSeq_annot_Handle annot = feh.GetAnnot(); feh.Remove(); // remove old annot if now empty if (CNewCleanup_imp::ShouldRemoveAnnot(*(annot.GetCompleteSeq_annot()))) { CSeq_annot_EditHandle annot_edit(annot); annot_edit.Remove(); } } any_change = true; } } return any_change; } bool CCleanup::AreBioSourcesMergeable(const CBioSource& src1, const CBioSource& src2) { if (src1.IsSetOrg() && src1.GetOrg().IsSetTaxname() && src2.IsSetOrg() && src2.GetOrg().IsSetTaxname() && NStr::Equal(src1.GetOrg().GetTaxname(), src2.GetOrg().GetTaxname())) { return true; } else { return false; } } bool CCleanup::MergeDupBioSources(CBioSource& src1, const CBioSource& add) { bool any_change = false; // genome if ((!src1.IsSetGenome() || src1.GetGenome() == CBioSource::eGenome_unknown) && add.IsSetGenome() && add.GetGenome() != CBioSource::eGenome_unknown) { src1.SetGenome(add.GetGenome()); any_change = true; } // origin if ((!src1.IsSetOrigin() || src1.GetOrigin() == CBioSource::eOrigin_unknown) && add.IsSetOrigin() && add.GetOrigin() != CBioSource::eOrigin_unknown) { src1.SetOrigin(add.GetOrigin()); any_change = true; } // focus if (!src1.IsSetIs_focus() && add.IsSetIs_focus()) { src1.SetIs_focus(); any_change = true; } // merge subtypes if (add.IsSetSubtype()) { ITERATE(CBioSource::TSubtype, it, add.GetSubtype()) { CRef<CSubSource> a(new CSubSource()); a->Assign(**it); src1.SetSubtype().push_back(a); } any_change = true; } x_MergeDupOrgRefs(src1.SetOrg(), add.GetOrg()); return any_change; } bool CCleanup::x_MergeDupOrgNames(COrgName& on1, const COrgName& add) { bool any_change = false; // OrgMods if (add.IsSetMod()) { ITERATE(COrgName::TMod, it, add.GetMod()) { CRef<COrgMod> a(new COrgMod()); a->Assign(**it); on1.SetMod().push_back(a); } any_change = true; } // gcode if ((!on1.IsSetGcode() || on1.GetGcode() == 0) && add.IsSetGcode() && add.GetGcode() != 0) { on1.SetGcode(add.GetGcode()); any_change = true; } // mgcode if ((!on1.IsSetMgcode() || on1.GetMgcode() == 0) && add.IsSetMgcode() && add.GetMgcode() != 0) { on1.SetMgcode(add.GetMgcode()); any_change = true; } // lineage if (!on1.IsSetLineage() && add.IsSetLineage()) { on1.SetLineage(add.GetLineage()); any_change = true; } // div if (!on1.IsSetDiv() && add.IsSetDiv()) { on1.SetDiv(add.GetDiv()); any_change = true; } return any_change; } bool HasMod(const COrg_ref& org, const string& mod) { if (!org.IsSetMod()) { return false; } ITERATE(COrg_ref::TMod, it, org.GetMod()) { if (NStr::Equal(*it, mod)) { return true; } } return false; } bool CCleanup::x_MergeDupOrgRefs(COrg_ref& org1, const COrg_ref& add) { bool any_change = false; // mods if (add.IsSetMod()) { ITERATE(COrg_ref::TMod, it, add.GetMod()) { if (!HasMod(org1, *it)) { org1.SetMod().push_back(*it); any_change = true; } } } // dbxrefs if (add.IsSetDb()) { ITERATE(COrg_ref::TDb, it, add.GetDb()) { CRef<CDbtag> a(new CDbtag()); a->Assign(**it); org1.SetDb().push_back(a); } any_change = true; } // synonyms if (add.IsSetSyn()) { ITERATE(COrg_ref::TSyn, it, add.GetSyn()) { org1.SetSyn().push_back(*it); } any_change = true; } if (add.IsSetOrgname()) { any_change |= x_MergeDupOrgNames(org1.SetOrgname(), add.GetOrgname()); } return any_change; } bool CCleanup::MergeDupBioSources(CSeq_descr & seq_descr) { bool any_change = false; CSeq_descr::Tdata::iterator src1 = seq_descr.Set().begin(); while (src1 != seq_descr.Set().end()) { if ((*src1)->IsSource() && (*src1)->GetSource().IsSetOrg() && (*src1)->GetSource().GetOrg().IsSetTaxname()) { CSeq_descr::Tdata::iterator src2 = src1; ++src2; while (src2 != seq_descr.Set().end()) { if ((*src2)->IsSource() && AreBioSourcesMergeable((*src1)->GetSource(), (*src2)->GetSource())) { MergeDupBioSources((*src1)->SetSource(), (*src2)->GetSource()); CRef<CCleanupChange> changes(makeCleanupChange(0)); CNewCleanup_imp srcclean(changes, 0); srcclean.ExtendedCleanup((*src1)->SetSource()); src2 = seq_descr.Set().erase(src2); any_change = true; } else { ++src2; } } } ++src1; } return any_change; } /// Remove duplicate biosource descriptors bool CCleanup::RemoveDupBioSource(CSeq_descr& descr) { bool any_change = false; vector<CConstRef<CBioSource> > src_list; CSeq_descr::Tdata::iterator d = descr.Set().begin(); while (d != descr.Set().end()) { if ((*d)->IsSource()) { bool found = false; ITERATE(vector<CConstRef<CBioSource> >, s, src_list) { if ((*d)->GetSource().Equals(**s)) { found = true; break; } } if (found) { d = descr.Set().erase(d); any_change = true; } else { CConstRef<CBioSource> src(&((*d)->GetSource())); src_list.push_back(src); ++d; } } else { ++d; } } return any_change; } CRef<CBioSource> CCleanup::BioSrcFromFeat(const CSeq_feat& f) { if (!f.IsSetData() || !f.GetData().IsBiosrc()) { return CRef<CBioSource>(NULL); } CRef<CBioSource> src(new CBioSource()); src->Assign(f.GetData().GetBiosrc()); // move comment to subsource note if (f.IsSetComment()) { CRef<CSubSource> s(new CSubSource()); s->SetSubtype(CSubSource::eSubtype_other); s->SetName(f.GetComment()); src->SetSubtype().push_back(s); } // move dbxrefs on feature to source if (f.IsSetDbxref()) { ITERATE(CSeq_feat::TDbxref, it, f.GetDbxref()) { CRef<CDbtag> a(new CDbtag()); a->Assign(**it); src->SetOrg().SetDb().push_back(a); } } CRef<CCleanupChange> changes(makeCleanupChange(0)); CNewCleanup_imp srcclean(changes, 0); srcclean.ExtendedCleanup(*src); return src; } bool CCleanup::ConvertSrcFeatsToSrcDescs(CSeq_entry_Handle seh) { bool any_change = false; for (CBioseq_CI b(seh); b; ++b) { bool transgenic_or_focus = false; CSeqdesc_CI existing_src(*b, CSeqdesc::e_Source); while (existing_src && !transgenic_or_focus) { if (existing_src->GetSource().IsSetIs_focus() || existing_src->GetSource().HasSubtype(CSubSource::eSubtype_transgenic)) { transgenic_or_focus = true; } ++existing_src; } if (transgenic_or_focus) { continue; } for (CFeat_CI p(*b, CSeqFeatData::e_Biosrc); p; ++p) { if (p->GetLocation().IsInt() && p->GetLocation().GetStart(eExtreme_Biological) == 0 && p->GetLocation().GetStop(eExtreme_Biological) == b->GetBioseqLength() - 1) { CRef<CSeqdesc> d(new CSeqdesc()); d->SetSource().Assign(*(BioSrcFromFeat(*(p->GetSeq_feat())))); // add descriptor to nuc-prot parent or sequence itself CBioseq_set_Handle parent = b->GetParentBioseq_set(); if (parent && parent.IsSetClass() && parent.GetClass() == CBioseq_set::eClass_nuc_prot) { CBioseq_set_EditHandle eh(parent); eh.AddSeqdesc(*d); MergeDupBioSources(eh.SetDescr()); RemoveDupBioSource(eh.SetDescr()); NormalizeDescriptorOrder(eh.SetDescr()); } else { CBioseq_EditHandle eh(*b); eh.AddSeqdesc(*d); MergeDupBioSources(eh.SetDescr()); RemoveDupBioSource(eh.SetDescr()); NormalizeDescriptorOrder(eh.SetDescr()); } // remove feature CSeq_feat_EditHandle feh(*p); feh.Remove(); any_change = true; } } } return any_change; } bool CCleanup::FixGeneXrefSkew(CSeq_entry_Handle seh) { CFeat_CI fi(seh); size_t num_gene_locus = 0; size_t num_gene_locus_tag = 0; size_t num_gene_xref_locus = 0; size_t num_gene_xref_locus_tag = 0; while (fi) { if (fi->GetData().IsGene()) { if (fi->GetData().GetGene().IsSetLocus()) { num_gene_locus++; } if (fi->GetData().GetGene().IsSetLocus_tag()) { num_gene_locus_tag++; } } else if (fi->IsSetXref()) { const CGene_ref* g = fi->GetGeneXref(); if (g) { if (g->IsSetLocus()) { num_gene_xref_locus++; } if (g->IsSetLocus_tag()) { num_gene_xref_locus_tag++; } } } if (num_gene_locus > 0) { if (num_gene_locus_tag > 0) { return false; } if (num_gene_xref_locus > 0) { return false; } } if (num_gene_locus_tag > 0) { if (num_gene_locus > 0) { return false; } if (num_gene_xref_locus_tag > 0) { return false; } } ++fi; } bool any_change = false; if (num_gene_locus == 0 && num_gene_locus_tag > 0) { if (num_gene_xref_locus > 0 && num_gene_xref_locus_tag == 0) { fi.Rewind(); while (fi) { if (!fi->GetData().IsGene() && fi->GetGeneXref() != NULL) { bool this_change = false; CRef<CSeq_feat> new_f(new CSeq_feat()); new_f->Assign(*(fi->GetSeq_feat())); NON_CONST_ITERATE(CSeq_feat::TXref, it, new_f->SetXref()) { if ((*it)->IsSetData() && (*it)->GetData().IsGene() && (*it)->GetData().GetGene().IsSetLocus()) { (*it)->SetData().SetGene().SetLocus_tag((*it)->GetData().GetGene().GetLocus()); (*it)->SetData().SetGene().ResetLocus(); this_change = true; } } if (this_change) { CSeq_feat_EditHandle eh(*fi); eh.Replace(*new_f); } } ++fi; } } } else if (num_gene_locus > 0 && num_gene_locus_tag == 0) { if (num_gene_xref_locus == 0 && num_gene_xref_locus_tag > 0) { fi.Rewind(); while (fi) { if (!fi->GetData().IsGene() && fi->GetGeneXref() != NULL) { bool this_change = false; CRef<CSeq_feat> new_f(new CSeq_feat()); new_f->Assign(*(fi->GetSeq_feat())); NON_CONST_ITERATE(CSeq_feat::TXref, it, new_f->SetXref()) { if ((*it)->IsSetData() && (*it)->GetData().IsGene() && (*it)->GetData().GetGene().IsSetLocus_tag()) { (*it)->SetData().SetGene().SetLocus((*it)->GetData().GetGene().GetLocus_tag()); (*it)->SetData().SetGene().ResetLocus_tag(); this_change = true; } } if (this_change) { CSeq_feat_EditHandle eh(*fi); eh.Replace(*new_f); any_change = true; } } ++fi; } } } return any_change; } bool CCleanup::ShouldStripPubSerial(const CBioseq& bs) { bool strip_serial = true; ITERATE(CBioseq::TId, id, bs.GetId()) { const CSeq_id& sid = **id; switch (sid.Which()) { case NCBI_SEQID(Genbank): case NCBI_SEQID(Tpg): { const CTextseq_id& tsid = *GET_FIELD(sid, Textseq_Id); if (FIELD_IS_SET(tsid, Accession)) { const string& acc = GET_FIELD(tsid, Accession); if (acc.length() == 6) { strip_serial = false; } } } break; case NCBI_SEQID(Embl): case NCBI_SEQID(Ddbj): strip_serial = false; break; case NCBI_SEQID(not_set): case NCBI_SEQID(Local): case NCBI_SEQID(Other): case NCBI_SEQID(General): break; case NCBI_SEQID(Gibbsq): case NCBI_SEQID(Gibbmt): case NCBI_SEQID(Pir): case NCBI_SEQID(Swissprot): case NCBI_SEQID(Patent): case NCBI_SEQID(Prf): case NCBI_SEQID(Pdb): case NCBI_SEQID(Gpipe): case NCBI_SEQID(Tpe): case NCBI_SEQID(Tpd): strip_serial = false; break; default: break; } } return strip_serial; } bool CCleanup::RenormalizeNucProtSets(CSeq_entry_Handle seh) { bool change_made = false; CConstRef<CSeq_entry> entry = seh.GetCompleteSeq_entry(); if (seh.IsSet() && seh.GetSet().IsSetClass() && entry->GetSet().IsSetSeq_set()) { CBioseq_set::TClass set_class = seh.GetSet().GetClass(); if (set_class == CBioseq_set::eClass_nuc_prot) { if (entry->GetSet().GetSeq_set().size() == 1 && entry->GetSet().GetSeq_set().front()->IsSeq()) { CSeq_entry_EditHandle eh = seh.GetEditHandle(); eh.ConvertSetToSeq(); if (eh.GetSeq().IsSetDescr()) { RemoveUnseenTitles(eh.SetSeq()); NormalizeDescriptorOrder(eh.SetSeq().SetDescr()); } change_made = true; } } else if (set_class == CBioseq_set::eClass_genbank || set_class == CBioseq_set::eClass_mut_set || set_class == CBioseq_set::eClass_pop_set || set_class == CBioseq_set::eClass_phy_set || set_class == CBioseq_set::eClass_eco_set || set_class == CBioseq_set::eClass_wgs_set || set_class == CBioseq_set::eClass_gen_prod_set || set_class == CBioseq_set::eClass_small_genome_set) { ITERATE(CBioseq_set::TSeq_set, s, entry->GetSet().GetSeq_set()) { CSeq_entry_Handle ch = seh.GetScope().GetSeq_entryHandle(**s); change_made |= RenormalizeNucProtSets(ch); } } } return change_made; } bool CCleanup::DecodeXMLMarkChanged(std::string & str) { // return false; bool change_made = false; // This is more complex than you might initially think is necessary // because this needs to be as efficient as possible since it's // called on every single string in an object. SIZE_TYPE amp = str.find('&'); if( NPOS == amp ) { // Check for the common case of no replacements required return change_made; } // transformations done by this function: const static struct { string src_word; string result_word; } transformations[] = { // all start with an implicit ampersand // and end with an implicit semi-colon { "amp", "&" }, { "apos", "\'" }, { "gt", ">" }, { "lt", "<" }, { "quot", "\"" }, { "#13&#10", "" }, { "#13;&#10", "" }, { "#916", "Delta" }, { "#945", "alpha" }, { "#946", "beta" }, { "#947", "gamma" }, { "#952", "theta" }, { "#955", "lambda" }, { "#956", "mu" }, { "#957", "nu" }, { "#8201", "" }, { "#8206", "" }, { "#8242", "'" }, { "#8594", "->" }, { "#8722", "-" }, { "#8710", "delta" }, { "#64257", "fi" }, { "#64258", "fl" }, { "#65292", "," } }; // Collisions should be rare enough that the CFastMutex is // faster than recreating the searcher each time this function is called static CTextFsm<int> searcher; // set searcher's state, if not already done { // just in case of the tiny chance that two threads try to prime // the searcher at the same time. static CFastMutex searcher_mtx; CFastMutexGuard searcher_mtx_guard( searcher_mtx ); if( ! searcher.IsPrimed() ) { for( size_t idx = 0; idx < sizeof(transformations)/sizeof(transformations[0]); ++idx ) { // match type is index into transformations array searcher.AddWord( transformations[idx].src_word, idx ); } searcher.Prime(); } } // a smart compiler probably won't need this manual optimization, // but just in case. const SIZE_TYPE str_len = str.length(); // fill result up to the first '&' string result; result.reserve( str_len ); copy( str.begin(), str.begin() + amp, back_inserter(result) ); // at the start of each loop, the result is filled in // up to the ampersand (amp) while( amp != NPOS && amp < str_len ) { // find out what the ampersand code represents // (if it represents anything) int state = searcher.GetInitialState(); SIZE_TYPE search_pos = (amp + 1); if (str[search_pos] == ' ') { break; } for( ; search_pos < str_len ; ++search_pos ) { const char ch = str[search_pos]; if( ch == ';' ) { break; } if( ch == '&' && state == 0 ) { --search_pos; // so we don't skip over the '&' state = searcher.GetInitialState(); // force "no-match" break; } state = searcher.GetNextState(state, ch); } if( search_pos == str_len && searcher.IsMatchFound(state) ) { // copy the translation of the XML code: _ASSERT( searcher.GetMatches(state).size() == 1 ); const int match_idx = searcher.GetMatches(state)[0]; const string & result_word = transformations[match_idx].result_word; copy( result_word.begin(), result_word.end(), back_inserter(result) ); change_made = true; break; } if( search_pos >= str_len ) { // we reached the end without finding anything, so // copy the rest and break copy( str.begin() + amp, str.end(), back_inserter(result) ); break; } if( searcher.IsMatchFound(state) ) { // copy the translation of the XML code: _ASSERT( searcher.GetMatches(state).size() == 1 ); const int match_idx = searcher.GetMatches(state)[0]; const string & result_word = transformations[match_idx].result_word; copy( result_word.begin(), result_word.end(), back_inserter(result) ); change_made = true; } else { // no match found, so copy the text we looked at // as-is copy( str.begin() + amp, str.begin() + search_pos + 1, back_inserter(result) ); } // find next_amp if( str[search_pos] == '&' ) { // special case that occurs when there are multiple '&' together ++search_pos; result += '&'; } SIZE_TYPE next_amp = str.find('&', search_pos ); if( NPOS == next_amp ) { // no more amps; copy the rest and break copy( str.begin() + search_pos + 1, str.end(), back_inserter(result) ); break; } // copy up to the next amp if( (search_pos + 1) < next_amp ) { copy( str.begin() + search_pos + 1, str.begin() + next_amp, back_inserter(result) ); } amp = next_amp; } if (change_made) { str = result; } return change_made; } CRef<CSeq_loc> CCleanup::GetProteinLocationFromNucleotideLocation(const CSeq_loc& nuc_loc, const CSeq_feat& cds, CScope& scope, bool require_inframe) { if (require_inframe) { feature::ELocationInFrame is_in_frame = feature::IsLocationInFrame(scope.GetSeq_featHandle(cds), nuc_loc); bool is_ok = false; switch (is_in_frame) { case feature::eLocationInFrame_InFrame: is_ok = true; break; case feature::eLocationInFrame_BadStart: if (cds.GetLocation().GetStart(eExtreme_Biological) == nuc_loc.GetStart(eExtreme_Biological)) { is_ok = true; } break; case feature::eLocationInFrame_BadStop: if (cds.GetLocation().GetStop(eExtreme_Biological) == nuc_loc.GetStop(eExtreme_Biological)) { is_ok = true; } break; case feature::eLocationInFrame_BadStartAndStop: if (cds.GetLocation().GetStart(eExtreme_Biological) == nuc_loc.GetStart(eExtreme_Biological) && cds.GetLocation().GetStop(eExtreme_Biological) == nuc_loc.GetStop(eExtreme_Biological)) { is_ok = true; } break; case feature::eLocationInFrame_NotIn: break; } if (!is_ok) { return CRef<CSeq_loc>(NULL); } } CRef<CSeq_loc> new_loc; CRef<CSeq_loc_Mapper> nuc2prot_mapper( new CSeq_loc_Mapper(cds, CSeq_loc_Mapper::eLocationToProduct, &scope)); new_loc = nuc2prot_mapper->Map(nuc_loc); if (!new_loc) { return CRef<CSeq_loc>(NULL); } const CSeq_id* sid = new_loc->GetId(); const CSeq_id* orig_id = nuc_loc.GetId(); if (!sid || (orig_id && sid->Equals(*orig_id))) { // unable to map to protein location return CRef<CSeq_loc>(NULL); } new_loc->ResetStrand(); // if location includes stop codon, remove it CBioseq_Handle prot = scope.GetBioseqHandle(*sid); if (prot && new_loc->GetStop(objects::eExtreme_Positional) >= prot.GetBioseqLength()) { CRef<CSeq_id> sub_id(new CSeq_id()); sub_id->Assign(*sid); CSeq_loc sub(*sub_id, prot.GetBioseqLength(), new_loc->GetStop(objects::eExtreme_Positional), new_loc->GetStrand()); new_loc = sequence::Seq_loc_Subtract(*new_loc, sub, CSeq_loc::fMerge_All | CSeq_loc::fSort, &scope); if (nuc_loc.IsPartialStop(eExtreme_Biological)) { new_loc->SetPartialStop(true, eExtreme_Biological); } } if (!new_loc->IsInt() && !new_loc->IsPnt()) { CRef<CSeq_loc> tmp = sequence::Seq_loc_Merge(*new_loc, CSeq_loc::fMerge_All, &scope); new_loc = tmp; } // fix partials if protein feature starts or ends at beginning or end of protein sequence if (!cds.GetLocation().IsPartialStart(eExtreme_Biological) && new_loc->GetStart(eExtreme_Biological) == 0) { if (new_loc->IsPartialStart(eExtreme_Biological)) { new_loc->SetPartialStart(false, eExtreme_Biological); } } if (!cds.GetLocation().IsPartialStop(eExtreme_Biological) && new_loc->GetStop(eExtreme_Biological) == prot.GetBioseqLength() - 1) { if (new_loc->IsPartialStop(eExtreme_Biological)) { new_loc->SetPartialStop(false, eExtreme_Biological); } } return new_loc; } CRef<CSeq_loc> CCleanup::GetProteinLocationFromNucleotideLocation(const CSeq_loc& nuc_loc, CScope& scope) { CConstRef<CSeq_feat> cds = sequence::GetOverlappingCDS(nuc_loc, scope); if (!cds || !cds->IsSetProduct()) { // there is no overlapping coding region feature, so there is no appropriate // protein sequence to move to return CRef<CSeq_loc>(NULL); } return GetProteinLocationFromNucleotideLocation(nuc_loc, *cds, scope); } bool CCleanup::RepackageProteins(const CSeq_feat& cds, CBioseq_set_Handle np) { if (!cds.IsSetProduct() || !cds.GetProduct().IsWhole()) { // no product, or product is specified weirdly return false; } CBioseq_Handle protein = np.GetTSE_Handle().GetBioseqHandle(cds.GetProduct().GetWhole()); if (!protein) { // protein is not in the same TSE return false; } if (protein.GetParentBioseq_set() == np) { // already in the right set return false; } CBioseq_set_EditHandle eh(np); CSeq_entry_Handle ph = protein.GetSeq_entry_Handle(); CSeq_entry_EditHandle peh(ph); eh.TakeEntry(peh); return true; } bool CCleanup::RepackageProteins(CSeq_entry_Handle seh) { bool changed = false; CSeq_entry_CI si(seh, CSeq_entry_CI::fRecursive | CSeq_entry_CI::fIncludeGivenEntry, CSeq_entry::e_Set); while (si) { CBioseq_set_Handle set = si->GetSet(); if (set.IsSetClass() && set.GetClass() == CBioseq_set::eClass_nuc_prot && set.HasAnnots()) { ITERATE(CBioseq_set::TAnnot, annot_it, set.GetCompleteBioseq_set()->GetAnnot()) { if ((*annot_it)->IsSetData() && (*annot_it)->IsFtable()) { ITERATE(CSeq_annot::TData::TFtable, feat_it, (*annot_it)->GetData().GetFtable()) { if ((*feat_it)->IsSetData() && (*feat_it)->GetData().IsCdregion()) { changed |= RepackageProteins(**feat_it, set); } } } } } ++si; } return changed; } bool CCleanup::ConvertDeltaSeqToRaw(CSeq_entry_Handle seh, CSeq_inst::EMol filter) { bool any_change = false; for (CBioseq_CI bi(seh, filter); bi; ++bi) { CBioseq_Handle bsh = *bi; CRef<CSeq_inst> inst(new CSeq_inst()); inst->Assign(bsh.GetInst()); if (inst->ConvertDeltaToRaw()) { CBioseq_EditHandle beh(bsh); beh.SetInst(*inst); any_change = true; } } return any_change; } bool CCleanup::ParseCodeBreak(const CSeq_feat& feat, CCdregion& cds, const string& str, CScope& scope) { if (str.empty() || !feat.IsSetLocation()) { return false; } const CSeq_id* feat_loc_seq_id = feat.GetLocation().GetId(); if (!feat_loc_seq_id) { return false; } string::size_type aa_pos = NStr::Find(str, "aa:"); string::size_type len = 0; string::size_type loc_pos, end_pos; char protein_letter = 'X'; CRef<CSeq_loc> break_loc; if (aa_pos == string::npos) { aa_pos = NStr::Find(str, ","); if (aa_pos != string::npos) { aa_pos = NStr::Find(str, ":", aa_pos); } if (aa_pos != string::npos) { aa_pos++; } } else { aa_pos += 3; } if (aa_pos != string::npos) { while (aa_pos < str.length() && isspace(str[aa_pos])) { aa_pos++; } while (aa_pos + len < str.length() && isalpha(str[aa_pos + len])) { len++; } if (len != 0) { protein_letter = ValidAminoAcid(str.substr(aa_pos, len)); } } loc_pos = NStr::Find(str, "(pos:"); if (loc_pos == string::npos) { return false; } loc_pos += 5; while (loc_pos < str.length() && isspace(str[loc_pos])) { loc_pos++; } end_pos = NStr::Find(str, ",aa:", loc_pos); if (end_pos == NPOS) { end_pos = NStr::Find(str, ",", loc_pos); if (end_pos == NPOS) { end_pos = str.length(); } } string pos = NStr::TruncateSpaces(str.substr(loc_pos, end_pos - loc_pos)); // handle multi-interval positions by adding a join() around them if (pos.find_first_of(",") != string::npos) { pos = "join(" + pos + ")"; } break_loc = ReadLocFromText(pos, feat_loc_seq_id, &scope); if (FIELD_IS_SET(feat.GetLocation(), Strand) && GET_FIELD(feat.GetLocation(), Strand) == eNa_strand_minus) { break_loc->SetStrand(GET_FIELD(feat.GetLocation(), Strand)); } else { RESET_FIELD(*break_loc, Strand); } if (break_loc == NULL || (break_loc->IsInt() && sequence::Compare(*break_loc, feat.GetLocation(), &scope, sequence::fCompareOverlapping) != sequence::eContained) || (break_loc->IsInt() && sequence::GetLength(*break_loc, &scope) > 3)) { return false; } // need to build code break object and add it to coding region CRef<CCode_break> newCodeBreak(new CCode_break()); CCode_break::TAa& aa = newCodeBreak->SetAa(); aa.SetNcbieaa(protein_letter); newCodeBreak->SetLoc(*break_loc); CCdregion::TCode_break& orig_list = cds.SetCode_break(); orig_list.push_back(newCodeBreak); return true; } bool CCleanup::ParseCodeBreaks(CSeq_feat& feat, CScope& scope) { if (!feat.IsSetData() || !feat.GetData().IsCdregion() || !feat.IsSetQual() || !feat.IsSetLocation()) { return false; } bool any_removed = false; CSeq_feat::TQual::iterator it = feat.SetQual().begin(); while (it != feat.SetQual().end()) { if ((*it)->IsSetQual() && NStr::EqualNocase((*it)->GetQual(), "transl_except") && (*it)->IsSetVal() && ParseCodeBreak(feat, feat.SetData().SetCdregion(), (*it)->GetVal(), scope)) { it = feat.SetQual().erase(it); any_removed = true; } else { ++it; } } if (feat.GetQual().size() == 0) { feat.ResetQual(); } return any_removed; } END_SCOPE(objects) END_NCBI_SCOPE
684349ce94d69b63cb7098a98ebbdce8efa1611e
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/git/old_hunk_8119.cpp
ebb991e06abf951140d3a1ee77849f668e8fcb19
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
557
cpp
old_hunk_8119.cpp
find_unique_abbrev(sha1_new, DEFAULT_ABBREV)); } static int update_ref(const char *action, const char *refname, unsigned char *sha1, unsigned char *oldval) { char msg[1024]; char *rla = getenv("GIT_REFLOG_ACTION"); static struct ref_lock *lock; if (!rla) rla = "(reflog update)"; snprintf(msg, sizeof(msg), "%s: %s", rla, action); lock = lock_any_ref_for_update(refname, oldval, 0); if (!lock) return 1; if (write_ref_sha1(lock, sha1, msg) < 0) return 1; return 0; } static int update_local_ref(const char *name,
a69d8a757eb17518873a3bd481f93675ba2f1d46
cde9f27c01539ab78e3e7e9a26c4c074b4c4026c
/Files/EEPROM_Programmer/ControlUnit/io.ino
f127a44f86b7790af6d6e2c36d6a0f74f41c1fe5
[ "Apache-2.0" ]
permissive
NuwanJ/peraSAP-I
41bea0ea87974e8ab278b92bc842f034e8e8d189
b7d1fe367e5127cf8bb3aac8edbb09615b190156
refs/heads/master
2021-06-25T08:21:16.411527
2020-10-20T05:48:19
2020-10-20T05:48:19
143,249,599
1
5
null
null
null
null
UTF-8
C++
false
false
1,478
ino
io.ino
void writeAddress(int data) { // Write given address to ports if (data == 0) { for (int i = 0; i < 7; i++) { digitalWrite(addPins[i], LOW); } } else { for (int i = 0; i < 7; i++) { digitalWrite(addPins[i], bitRead(data, 6 - i)); //Serial.print(bitRead(data, i)); } } delay(10); } uint16_t readOutput() { // Read current input uint16_t buff = 0; //Serial.print(" ["); for (int i = 0; i < 16; i++) { bitWrite(buff, 15 - i, digitalRead(outPins[i])); //Serial.print(digitalRead(outPins[i])); } //Serial.print("] "); delay(10); return buff; } void writeOutput(uint16_t data) { //Write given output to DataOut pins for (int i = 0; i < 16; i++) { digitalWrite(outPins[i], bitRead(data, 15 - i)); } digitalWrite(pinW, LOW); digitalWrite(pinW2, LOW); delayMicroseconds(500); digitalWrite(pinW, HIGH); digitalWrite(pinW2, HIGH); delay(50); } void setWriteMode() { for (int i = 0; i < 16; i++) { pinMode(outPins[i], OUTPUT); digitalWrite(outPins[i], LOW); } digitalWrite(pinE, LOW); digitalWrite(pinG, HIGH); digitalWrite(pinW, HIGH); digitalWrite(pinG2, HIGH); digitalWrite(pinW2, HIGH); } void setReadMode() { for (int i = 0; i < 16; i++) { digitalWrite(outPins[i], LOW); pinMode(outPins[i], INPUT); } digitalWrite(pinE, LOW); digitalWrite(pinG, LOW); digitalWrite(pinW, HIGH); digitalWrite(pinG2, LOW); digitalWrite(pinW2, HIGH); }
cb6cc7714dbf70aa2187f77fdb928f270a801f6a
acf18a78cba53c9955df152cf9d3af02a6f66e16
/source/YoloMouse/Dll/CursorVault.hpp
2a375b145656a1ea0f4154c93b5d385a75999773
[ "Unlicense" ]
permissive
Mydcj/YoloMouse
7c6435902773ee0b8c8a6a91ee3f6c6461a8243c
ffff8e2fdf5852d54abd5f8e2416bf34a92db47c
refs/heads/master
2020-04-24T17:40:32.598367
2018-08-13T22:59:21
2018-08-13T22:59:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,695
hpp
CursorVault.hpp
#pragma once #include <Core/Container/Array.hpp> #include <YoloMouse/Share/Constants.hpp> #include <YoloMouse/Share/SharedState.hpp> namespace YoloMouse { /**/ class CursorVault { public: /**/ CursorVault(); ~CursorVault(); /**/ Bool Load( Index resource_index, Index size_index ); /**/ void Unload( Index resource_index, Index size_index ); void UnloadAll(); /**/ HCURSOR GetCursor( Index resource_index, Index size_index ); /**/ Bool HasCursor( HCURSOR hcursor ); private: // types enum ResourceState { RESOURCE_NONE, RESOURCE_READY, RESOURCE_FAILED, }; struct CursorResource { HCURSOR handle; ULong referenced; CursorResource(); }; typedef FlatArray<CursorResource, CURSOR_INDEX_COUNT> ResourceTable; struct CacheEntry { ResourceState state; Bool resizable; ULong width; ULong height; PathString path; UINT loadimage_flags; ResourceTable resources; CacheEntry(); }; typedef FlatArray<CacheEntry, CURSOR_RESOURCE_LIMIT> CacheTable; /**/ Bool _CacheInit( CacheEntry& entry, Index resource_index ); Bool _CacheLoad( CacheEntry& entry, Index size_index ); void _CacheUnload( CacheEntry& entry, Index size_index ); // fields CacheTable _table; SharedState& _state; }; }
4ca88b0fb66629a9942c9014556261c423b5fb85
648d3c449ac8bdb46adba4a3baedded7833f5f77
/level-editor/tileselectorview.cc
144466b1a4d6770fc7986dea830538d4d1942b1d
[]
no_license
datalate/another-jrpg
fed3e95cfbbdc10db5738e174ad66900eb3a24e9
6863eb7af7ff3687ec4dfab56977e854fc7d73cc
refs/heads/master
2021-01-20T07:02:16.400848
2018-08-08T23:53:32
2018-08-08T23:53:32
89,947,824
0
0
null
null
null
null
UTF-8
C++
false
false
291
cc
tileselectorview.cc
#include "tileselectorview.hh" #include <QDebug> TileSelectorView::TileSelectorView(QWidget *parent) : QGraphicsView{parent} { } void TileSelectorView::resizeEvent(QResizeEvent *event) { emit sizeChanged(event->oldSize(), event->size()); QGraphicsView::resizeEvent(event); }
4d68236cef8e669e5d2b45d8aa102931aab59baa
45d300db6d241ecc7ee0bda2d73afd011e97cf28
/OTCDerivativesCalculatorModule/Project_Cpp/lib_static/FpmlSerialized/GenClass/fpml-shared-5-4/SharedAmericanExercise.cpp
0781129e6872ec9ac9bd985b42815ce9840b0b3d
[]
no_license
fagan2888/OTCDerivativesCalculatorModule
50076076f5634ffc3b88c52ef68329415725e22d
e698e12660c0c2c0d6899eae55204d618d315532
refs/heads/master
2021-05-30T03:52:28.667409
2015-11-27T06:57:45
2015-11-27T06:57:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,413
cpp
SharedAmericanExercise.cpp
// SharedAmericanExercise.cpp #include "SharedAmericanExercise.hpp" #ifdef ConsolePrint #include <iostream> #endif namespace FpmlSerialized { SharedAmericanExercise::SharedAmericanExercise(TiXmlNode* xmlNode) : Exercise(xmlNode) { #ifdef ConsolePrint std::string initialtap_ = FileManager::instance().tap_; FileManager::instance().tap_.append(" "); #endif //commencementDateNode ---------------------------------------------------------------------------------------------------------------------- TiXmlElement* commencementDateNode = xmlNode->FirstChildElement("commencementDate"); if(commencementDateNode){commencementDateIsNull_ = false;} else{commencementDateIsNull_ = true;} #ifdef ConsolePrint FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- commencementDateNode , address : " << commencementDateNode << std::endl; #endif if(commencementDateNode) { if(commencementDateNode->Attribute("href") || commencementDateNode->Attribute("id")) { if(commencementDateNode->Attribute("id")) { commencementDateIDRef_ = commencementDateNode->Attribute("id"); commencementDate_ = boost::shared_ptr<AdjustableOrRelativeDate>(new AdjustableOrRelativeDate(commencementDateNode)); commencementDate_->setID(commencementDateIDRef_); IDManager::instance().setID(commencementDateIDRef_,commencementDate_); } else if(commencementDateNode->Attribute("href")) { commencementDateIDRef_ = commencementDateNode->Attribute("href");} else { QL_FAIL("id or href error"); } } else { commencementDate_ = boost::shared_ptr<AdjustableOrRelativeDate>(new AdjustableOrRelativeDate(commencementDateNode));} } //expirationDateNode ---------------------------------------------------------------------------------------------------------------------- TiXmlElement* expirationDateNode = xmlNode->FirstChildElement("expirationDate"); if(expirationDateNode){expirationDateIsNull_ = false;} else{expirationDateIsNull_ = true;} #ifdef ConsolePrint FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- expirationDateNode , address : " << expirationDateNode << std::endl; #endif if(expirationDateNode) { if(expirationDateNode->Attribute("href") || expirationDateNode->Attribute("id")) { if(expirationDateNode->Attribute("id")) { expirationDateIDRef_ = expirationDateNode->Attribute("id"); expirationDate_ = boost::shared_ptr<AdjustableOrRelativeDate>(new AdjustableOrRelativeDate(expirationDateNode)); expirationDate_->setID(expirationDateIDRef_); IDManager::instance().setID(expirationDateIDRef_,expirationDate_); } else if(expirationDateNode->Attribute("href")) { expirationDateIDRef_ = expirationDateNode->Attribute("href");} else { QL_FAIL("id or href error"); } } else { expirationDate_ = boost::shared_ptr<AdjustableOrRelativeDate>(new AdjustableOrRelativeDate(expirationDateNode));} } //latestExerciseTimeNode ---------------------------------------------------------------------------------------------------------------------- TiXmlElement* latestExerciseTimeNode = xmlNode->FirstChildElement("latestExerciseTime"); if(latestExerciseTimeNode){latestExerciseTimeIsNull_ = false;} else{latestExerciseTimeIsNull_ = true;} #ifdef ConsolePrint FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- latestExerciseTimeNode , address : " << latestExerciseTimeNode << std::endl; #endif if(latestExerciseTimeNode) { if(latestExerciseTimeNode->Attribute("href") || latestExerciseTimeNode->Attribute("id")) { if(latestExerciseTimeNode->Attribute("id")) { latestExerciseTimeIDRef_ = latestExerciseTimeNode->Attribute("id"); latestExerciseTime_ = boost::shared_ptr<BusinessCenterTime>(new BusinessCenterTime(latestExerciseTimeNode)); latestExerciseTime_->setID(latestExerciseTimeIDRef_); IDManager::instance().setID(latestExerciseTimeIDRef_,latestExerciseTime_); } else if(latestExerciseTimeNode->Attribute("href")) { latestExerciseTimeIDRef_ = latestExerciseTimeNode->Attribute("href");} else { QL_FAIL("id or href error"); } } else { latestExerciseTime_ = boost::shared_ptr<BusinessCenterTime>(new BusinessCenterTime(latestExerciseTimeNode));} } //latestExerciseTimeDeterminationNode ---------------------------------------------------------------------------------------------------------------------- TiXmlElement* latestExerciseTimeDeterminationNode = xmlNode->FirstChildElement("latestExerciseTimeDetermination"); if(latestExerciseTimeDeterminationNode){latestExerciseTimeDeterminationIsNull_ = false;} else{latestExerciseTimeDeterminationIsNull_ = true;} #ifdef ConsolePrint FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- latestExerciseTimeDeterminationNode , address : " << latestExerciseTimeDeterminationNode << std::endl; #endif if(latestExerciseTimeDeterminationNode) { if(latestExerciseTimeDeterminationNode->Attribute("href") || latestExerciseTimeDeterminationNode->Attribute("id")) { if(latestExerciseTimeDeterminationNode->Attribute("id")) { latestExerciseTimeDeterminationIDRef_ = latestExerciseTimeDeterminationNode->Attribute("id"); latestExerciseTimeDetermination_ = boost::shared_ptr<DeterminationMethod>(new DeterminationMethod(latestExerciseTimeDeterminationNode)); latestExerciseTimeDetermination_->setID(latestExerciseTimeDeterminationIDRef_); IDManager::instance().setID(latestExerciseTimeDeterminationIDRef_,latestExerciseTimeDetermination_); } else if(latestExerciseTimeDeterminationNode->Attribute("href")) { latestExerciseTimeDeterminationIDRef_ = latestExerciseTimeDeterminationNode->Attribute("href");} else { QL_FAIL("id or href error"); } } else { latestExerciseTimeDetermination_ = boost::shared_ptr<DeterminationMethod>(new DeterminationMethod(latestExerciseTimeDeterminationNode));} } #ifdef ConsolePrint FileManager::instance().tap_ = initialtap_; #endif } boost::shared_ptr<AdjustableOrRelativeDate> SharedAmericanExercise::getCommencementDate() { if(!this->commencementDateIsNull_){ if(commencementDateIDRef_ != ""){ return boost::shared_static_cast<AdjustableOrRelativeDate>(IDManager::instance().getID(commencementDateIDRef_)); }else{ return this->commencementDate_; } }else { QL_FAIL("null Ptr"); return boost::shared_ptr<AdjustableOrRelativeDate>(); } } boost::shared_ptr<AdjustableOrRelativeDate> SharedAmericanExercise::getExpirationDate() { if(!this->expirationDateIsNull_){ if(expirationDateIDRef_ != ""){ return boost::shared_static_cast<AdjustableOrRelativeDate>(IDManager::instance().getID(expirationDateIDRef_)); }else{ return this->expirationDate_; } }else { QL_FAIL("null Ptr"); return boost::shared_ptr<AdjustableOrRelativeDate>(); } } boost::shared_ptr<BusinessCenterTime> SharedAmericanExercise::getLatestExerciseTime() { if(!this->latestExerciseTimeIsNull_){ if(latestExerciseTimeIDRef_ != ""){ return boost::shared_static_cast<BusinessCenterTime>(IDManager::instance().getID(latestExerciseTimeIDRef_)); }else{ return this->latestExerciseTime_; } }else { QL_FAIL("null Ptr"); return boost::shared_ptr<BusinessCenterTime>(); } } boost::shared_ptr<DeterminationMethod> SharedAmericanExercise::getLatestExerciseTimeDetermination() { if(!this->latestExerciseTimeDeterminationIsNull_){ if(latestExerciseTimeDeterminationIDRef_ != ""){ return boost::shared_static_cast<DeterminationMethod>(IDManager::instance().getID(latestExerciseTimeDeterminationIDRef_)); }else{ return this->latestExerciseTimeDetermination_; } }else { QL_FAIL("null Ptr"); return boost::shared_ptr<DeterminationMethod>(); } } }
531e5b12979fda9c061480cb4ec4bb39ff9ae984
73ff1e7e1ac2d8d5168a6c653f70d5f6d0dc2c45
/PR2_Test3/backup/person.h
184c46888f094ee07267bf42f14c4ed5f3ddf769
[]
no_license
mahdyfalah/Bank_App
187948981dc41597af39ec686cb363e76248d660
d3ff0b6a5587c1fc54565672b6ba80f85786505e
refs/heads/master
2021-12-24T03:06:10.146958
2021-12-21T12:06:08
2021-12-21T12:06:08
237,261,184
1
0
null
null
null
null
UTF-8
C++
false
false
794
h
person.h
#ifndef PERSON_H #define PERSON_H #include<iostream> #include<string> #include<vector> #include<memory> #include"konto.h" using namespace std; class Account; class Person : public enable_shared_from_this<Person>{ string name; vector<shared_ptr<Account>> accounts; public: Person(string); ~Person() { } string get_name() const; int add_account(int); bool share(shared_ptr<Person>, shared_ptr<Account>); bool has_authority(shared_ptr<Account>); bool give_up_account(shared_ptr<Account>); void delete_account(shared_ptr<Account>); ostream& print(ostream&) const; ostream& print_small(ostream&) const; const vector<shared_ptr<Account>>& get_accounts() const; shared_ptr<Account> get_account(size_t i) const; }; ostream& operator<<(ostream&, const Person&); #endif
48cd9c06f90588b9e63a00397c5659ee2c86ac85
5d374665ab5b298ab3af3dd9c188261d632c44c4
/jni/PE-like-PC_hooks.cpp
877dc3fed75e1c99ee42d55aa749052ddb5c686b
[]
no_license
TrinityDevelopers/PE-like-PC-new-api
451529b88739d8496e611af2723f03940bc43533
751f9cc523c5770a3f820d3dcc564fb8055abd61
refs/heads/master
2016-09-10T01:21:20.134127
2015-07-21T00:56:05
2015-07-21T00:56:05
37,752,457
1
0
null
null
null
null
UTF-8
C++
false
false
3,739
cpp
PE-like-PC_hooks.cpp
#include <jni.h> #include <dlfcn.h> #include <android/log.h> #include <string> #include "Substrate.h" #include "mcpe/Common.h" #include "mcpe/world/level/tile/Tile.h" #include "mcpe/world/level/tile/LiquidTileDynamic.h" #include "mcpe/world/material/Material.h" #include "mcpe/world/item/Item.h" #include "mcpe/world/item/TilePlanterItem.h" #include "mcpe/client/render/tile/TileTessellator.h" #include "mcpe/locale/I18n.h" #include "PE-like-PC/world/tile/BrewingStandTile.h" #include "PE-like-PC/world/tile/EnchantmentTableTile.h" #include "PE-like-PC/world/tile/CommandBlockTile.h" #include "PE-like-PC/world/tile/RedstoneLightTile.h" #include "PE-like-PC/world/tile/NoteBlockTile.h" #include "PE-like-PC/world/tile/SoulSandTile.h" const std::string PELIKEPCVERSION = "1.0 DEV"; static std::string (*_Common$getGameVersionString)(); static std::string Common$getGameVersionString() { return "§a§lPE like PC" + PElIKEPCVERSION; } static std::string (*_I18n$get)(std::string const&, std::vector<std::string, std::allocator<std::string>> const&); static std::string I18n$get(std::string const& key, std::vector<std::string, std::allocator<std::string>> const& a) { if(key == "menu.copyright") return "§a§l@SmartDEV Team"; if(key == "menu.play") return "§lSingleplayer"; return _I18n$get(key, a); } static void (*_TileTessellator$tessellateInWorld)(TileTessellator*, Tile*, const TilePos&, bool); static void TileTessellator$tessellateInWorld(TileTessellator* self, Tile* tile, const TilePos& pos, bool b) { switch(tile->renderType) { case 25: self->tessellateBrewingStandTileInWorld((BrewingStandTile*)tile, pos.x, pos.y, pos.z, self->region); break; default: _TileTessellator$tessellateInWorld(self, tile, pos, b); break; } } static void (*_Tile$initTiles)(); static void Tile$initTiles() { _Tile$initTiles(); Tile::brewing_stand = (Tile*)((new BrewingStandTile(117))->init()->setDestroyTime(0.5F)->setLightEmission(0.125F)->setNameId("brewingStand")->setSoundType(Tile::SOUND_METAL)); Tile::enchanting_table = (Tile*)((new EnchantmentTableTile(116))->init()->setDestroyTime(5.0F)->setExplodeable(2000.0F)->setNameId("enchantmentTable")->setCategory(2)->setSoundType(Tile::SOUND_STONE)); Tile::command_block = (Tile*)((new CommandBlockTile(137))->init()->setDestroyTime(-1.0F)->setExplodeable(6000000.0F)->setNameId("commandBlock")->setCategory(2)->setSoundType(Tile::SOUND_METAL)); } static void (*_Item$initItems)(); static void Item$initItems() { Item::brewing_stand = (Item*)((new TilePlanterItem(379, Tile::brewing_stand))->setNameID("brewingStand")->setCategory(2)->setIcon("brewing_stand", 0)); _Item$initItems(); } static void (*_Item$initCreativeItems)(); static void Item$initCreativeItems() { _Item$initCreativeItems(); Item::addCreativeItem(Item::brewing_stand, 0); Item::addCreativeItem(Tile::enchanting_table, 0); Item::addCreativeItem(Tile::command_block, 0); //Item::addCreativeItem(Tile::soul_sand, 0); } JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) { MSHookFunction((void*) &Common::getGameVersionString, (void*) &Common$getGameVersionString, (void**) &_Common$getGameVersionString); MSHookFunction((void*) &TileTessellator::tessellateInWorld, (void*) &TileTessellator$tessellateInWorld, (void**) &_TileTessellator$tessellateInWorld); MSHookFunction((void*) &Tile::initTiles, (void*) &Tile$initTiles, (void**) &_Tile$initTiles); MSHookFunction((void*) &Item::initItems, (void*) &Item$initItems, (void**) &_Item$initItems); MSHookFunction((void*) &Item::initCreativeItems, (void*) &Item$initCreativeItems, (void**) &_Item$initCreativeItems); MSHookFunction((void*) &I18n::get, (void*) &I18n$get, (void**) &_I18n$get); return JNI_VERSION_1_2; }
cdfad1f9f5f552dbd488e5ee5acbba94c9fa6251
dfe17656275246adba7598053461e3ae9ee8cfad
/Db/vCode.h
91f823a48b92cfa04afabb641a6714bba38dba78
[]
no_license
weijunbao/Db
911bbafd524a43bfa1c1619a4d085bc8214decbe
455aa72fd86ee928c31063e88dc7717cc67bc0b0
refs/heads/master
2020-05-27T04:11:20.499418
2013-06-25T07:40:23
2013-06-25T07:40:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
500
h
vCode.h
#pragma once #include "commonType.h" #include <stdint.h> #define ASSERT_VCODE_SIZE(vSize)\ assert(vSize>0 && vSize<10); class vCode : public NonCreate { public: /*vCode(void); virtual ~vCode(void);*/ public: static int vCodei8(uint8_t i,char* pData); static int vCodei16(uint16_t i,char* pData); static int vCodei32(uint32_t i,char* pData); static int vCodei64(uint64_t i,char* pData); static int getVariableSize(uint64_t i); static int getVariableCode(const char* pData,uint64_t& i); };
2780194271cadf8506cee0f660c87ccc902b136d
f8d40ed3f14be5f56831b1bcfbaab13feb056d45
/Sabertooth/Layer.h
58c0f28ce2f6b4a23256aa92e7fba8431f9b70b7
[ "MIT" ]
permissive
matheusmoraesporto/RoadFighter
a14d96ee38b7fe95bbbc2e3c328a149fb33ca2fc
0b6cfa2604cb48a18ecf716c117230eda8b67a82
refs/heads/master
2022-04-26T03:09:27.914362
2020-05-03T21:28:22
2020-05-03T21:28:22
260,494,124
1
0
null
null
null
null
UTF-8
C++
false
false
547
h
Layer.h
#pragma once #include <GL\glew.h> class Layer { public: Layer(); Layer(int widthValue, int heightValue, int tidValue); void setTid(GLuint value); void setId(int value); void setWidth(int value); void setHeight(int value); void setTx(float value); void setTy(float value); void setScrollRateX(float value); void setScrollRateY(float value); void setVao(GLuint value); void setZ(float value); void setName(char value); char name; // properties int width, height, id; float tx, ty, scrollRateX, scrollRateY, z; GLuint tid, vao; };
38327e81af93967ef0e329284f4039343561c419
f7ba28001db6d0b984c1fcfeb8182826985f20fc
/module1/2taskA.cpp
ab1596268457837f36412ae2cd8d7bfe3743c3b5
[]
no_license
artek0chumak/DIHT_3semester
baa139759ec2dba573b4f6875d61efd34d93210d
ad8e4b56a183dd151d3ec269e1c0016dab6dac0d
refs/heads/master
2020-04-13T19:26:27.773487
2018-12-28T11:31:25
2018-12-28T11:31:25
163,402,474
0
0
null
null
null
null
UTF-8
C++
false
false
4,201
cpp
2taskA.cpp
#include <iostream> #include <vector> #include <algorithm> class StringFunctions { public: std::vector<uint> stringToPrefix(std::string_view str) { std::vector<uint> prefixValues(str.size(), 0); for(auto i = 1; i < str.size(); ++i) { prefixValues[i] = prefixValues[i - 1]; while((prefixValues[i] > 0) && (str[i] != str[prefixValues[i]])) { prefixValues[i] = prefixValues[prefixValues[i] - 1]; } if(prefixValues[i] == str[prefixValues[i]]) { ++prefixValues[i]; } } return prefixValues; } std::vector<uint> stringToZ(std::string_view str) { std::vector<uint> zValues(str.size(), 0); uint left = 0, right = 0; zValues[0] = str.size(); for(uint i = 1; i < str.size(); ++i) { zValues[i] = std::max(static_cast<uint>(0), std::min(right - i, zValues[i - left])); while((i + zValues[i] < str.size()) && (str[zValues[i]] == str[i + zValues[i]])) { ++zValues[i]; } if(i + zValues[i] > right) { left = i; right = i + zValues[i]; } } return zValues; } std::string prefixToString(std::vector<uint> prefixValues) { std::string answer; std::vector<bool> usedSymbols(kSizeAlphabet, false); uint itAlphabet = -1; uint maxSymbol = 0; uint prevPrefix = 0; for(auto p: prefixValues) { if(p == 0) { usedSymbols.assign(kSizeAlphabet, false); itAlphabet = -1; while(prevPrefix > 0) { usedSymbols[answer[prevPrefix] - 'a'] = true; prevPrefix = prefixValues[prevPrefix - 1]; } for(auto i = 1; i < maxSymbol; ++i) { if(!usedSymbols[i]) { itAlphabet = i; break; } } if(itAlphabet == -1) { itAlphabet = ++maxSymbol; } answer += kAlphabet[itAlphabet]; } else { answer += answer[p - 1]; } prevPrefix = p; } return answer; } std::string zToString(std::vector<uint>& zValues) { return prefixToString(zToPrefix(zValues)); } std::vector<uint> zToPrefix(std::vector<uint>& zValues) { std::vector<uint> prefixValues(zValues.size(), 0); for(auto i = 1; i < zValues.size(); ++i) { for(int j = zValues[i] - 1; j > -1; --j) { if(prefixValues[i + j] > 0) { break; } else { prefixValues[i + j] = j + 1; } } } return prefixValues; } std::vector<uint> prefixToZ(std::vector<uint>& prefixValues) { std::vector<uint> zValues(prefixValues.size(), 0); zValues[prefixValues.size() - 1] = prefixValues.size(); for(auto i = 1; i < prefixValues.size(); ++i) { if(prefixValues[i] > 0) { zValues[i - prefixValues[i] + 1] = prefixValues[i]; } } auto i = 1; while(i < prefixValues.size()) { auto t = i; if(zValues[i] > 0) { for(auto j = 1; j < zValues[i]; ++j) { if(zValues[i + j] > zValues[j]) { break; } zValues[i + j] = std::min(zValues[j], zValues[i] - j); t = i + j; } } i = t + 1; } return zValues; } private: const std::string kAlphabet = "abcdefghijklmnopqrstuvwxyz"; const size_t kSizeAlphabet = 26; }; int main() { StringFunctions functions; std::vector<uint> prefixValues; uint prefix; while(std::cin >> prefix) { prefixValues.push_back(prefix); } std::cout << functions.prefixToString(prefixValues) << std::endl; }
f67ff626bb7bcb8df3b0efa37dde07f5d07de652
64721ef654f98e1e4b68ed415f6886f6b8775372
/src/common/validation.cpp
b33108957e33151a0ac04df363eee92ae8185cb4
[]
no_license
cloudhc/my_scons_project
67f3df498c150b6da93237f8ba5e72df8e3609aa
7f0d2065c8106da2dbf0f63719c4b35dda3ce49d
refs/heads/master
2022-06-17T00:45:21.915535
2020-04-24T05:40:58
2020-04-24T05:40:58
257,807,994
0
0
null
null
null
null
UTF-8
C++
false
false
1,873
cpp
validation.cpp
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * Copyright (c) 2014 Xabyss Inc. All rights reserved. */ /** * @mainpage Main Page * * Validation helper API documentation. */ /** * @file validation.cpp * * @brief Xabyss's Validation helper library source file. * @details This header file must be included in any xabyss's probe applications. */ #include <arpa/inet.h> #include <netdb.h> #include <string> #include <regex> #include "validation.hpp" namespace pca { namespace validation { /** * Check IP address. * * @param s domainname or ipv4 address. * @return true if validation check is success, false otherwise. */ bool validate_ipv4_address(const std::string& s) { static const std::regex re("([-_0-9-\\.]+)"); std::smatch m; if (std::regex_match(s, m, re)) { // prase ipv4 address static const std::regex re("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"); if (std::regex_match(s, m, re)) { struct in_addr in_addr; if (inet_aton(s.c_str(), &in_addr) != 0) return true; } return false; } else { // parse domainname struct hostent *host_entry; host_entry = gethostbyname(s.c_str()); return (host_entry != NULL); } } /** * Check TCP/UDP port number. * * @param port A tcp port number (range: 1 ~ 65535). * @return true if validation check is success, false otherwise. */ bool validate_port_number(const uint32_t& port) { return (port >= 0 && port <= 65535); } /** * Check IPv4 netmask. * * @param port A netmask (range: 1 ~ 32). * @return true if validation check is success, false otherwise. */ bool validate_netmask(const uint16_t& netmask) { return (netmask > 0 && netmask <= 32); } } // namespace validation } // namespace pca
d3e2f1bb395fdb9c9752dbc0fd311452144be95c
9757b1f64403138b68a1ae3a61e65a5a50114e5a
/2015-contest/0804/a.cc
bbc503f9d5cc9f99cd0f412e0c56732990a5f127
[]
no_license
ailyanlu/acm-code
481290d1b7773a537fe733a813ca5f9d925d8e93
0a5042c16eae3580ea443b5ab4109c8f317350af
refs/heads/master
2018-01-15T11:49:29.599393
2015-10-30T02:39:17
2015-10-30T02:39:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
700
cc
a.cc
#include <cstdio> #include <iostream> #include <string> #include <map> using namespace std; map<string, int> m; string x, y; int main() { int t; scanf("%d", &t); while (t--) { cin >> x >> y; int a = x.length(), b = y.length(), u , v; m.clear(); for (int i = 1; i <= a; ++i) { for (int j = 0; j + i - 1 < a; ++j) { m[x.substr(j, i)] = 1; } } u = m.size(); m.clear(); for (int i = 1; i <= b; ++i) { for (int j = 0; j + i - 1 < b; ++j) { m[y.substr(j, i)] = 1; } } v = m.size(); printf("%d\n", u * v); } return 0; }
32d2409e8756bab3fd5762ab10ffad567a7b0e8b
7985054c887810f37345f6508f1a7d4fdc65b81b
/Development/Core/PlayerSpawn.cpp
cb9971ce20b8746ed682ff0fe0e45bc0f4a8e11c
[]
no_license
ghostuser846/venicelight
95e625a8e9cb8dd3d357318c931ee9247420c28d
cdc5dfac8fbaa82d3d5eeb7d21a64c3e206b7ee2
refs/heads/master
2021-01-01T06:44:51.163612
2009-06-01T02:09:27
2009-06-01T02:09:27
37,787,439
0
0
null
null
null
null
UTF-8
C++
false
false
3,561
cpp
PlayerSpawn.cpp
/* * Copyright (C) 2005-2008 SREmu <http://www.sremu.org/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "GameSocket.h" void GameSocket::SpawnMe() { CreateSpawnPacket(this); Broadcast(false); } void GameSocket::DespawnMe() { Writer.Create(GAME_SERVER_DESPAWN_PLAYER); Writer.WriteDWord(Player.General.UniqueID); Writer.Finalize(); Broadcast(false); } void GameSocket::SpawnPlayers() { for(Objects.pIter = Objects.Players.begin(); Objects.pIter != Objects.Players.end(); ++Objects.pIter) { if(Objects.pIter->first != Player.General.UniqueID) { CreateSpawnPacket(Objects.pIter->second); Send(Writer.Buffer, Writer.Size()); } } } void GameSocket::CreateSpawnPacket(GameSocket* player) { Writer.Create(GAME_SERVER_SPAWN); Writer.WriteDWord(player->Player.Stats.Model); Writer.WriteByte (player->Player.Stats.Volume); Writer.WriteByte (player->Player.Stats.Level < 20 ? 1 : 0); Writer.WriteByte (0x2D); // Max item slot // Item data here. mysqlpp::StoreQueryResult items = db.Query("select * from items where owner=%d and type=0", player->Player.General.CharacterID).store(); Writer.WriteByte (items.num_rows()); for(unsigned int i = 0; i < items.num_rows(); i++) { Writer.WriteDWord(atoi(items[i]["itemtype"])); Writer.WriteByte (atoi(items[i]["plusvalue"])); } // Avatar data here. Writer.WriteByte (4); Writer.WriteByte (0); Writer.WriteByte (0); Writer.WriteDWord(player->Player.General.UniqueID); Writer.WriteByte (player->Player.Position.XSector); Writer.WriteByte (player->Player.Position.YSector); Writer.WriteFloat(player->Player.Position.X); Writer.WriteFloat(player->Player.Position.Z); Writer.WriteFloat(player->Player.Position.X); // Angle & movement flags. Writer.WriteWord (0); // Angle Writer.WriteByte (0); Writer.WriteByte (1); Writer.WriteByte (0); Writer.WriteWord (0); // Angle Writer.WriteWord (1); Writer.WriteByte (player->Player.Flags.Berserk); Writer.WriteFloat(player->Player.Speeds.WalkSpeed); Writer.WriteFloat(player->Player.Speeds.RunSpeed); Writer.WriteFloat(player->Player.Speeds.BerserkSpeed); Writer.WriteByte (0); // Number of active buffs Writer.WriteWord(strlen((char*)player->Player.General.CharacterName)); Writer.WriteString(player->Player.General.CharacterName, strlen((char*)player->Player.General.CharacterName)); // Unknown data. Writer.WriteByte (0); Writer.WriteByte (1); Writer.WriteDWord(0); Writer.WriteDWord(0); Writer.WriteDWord(0); Writer.WriteDWord(0); Writer.WriteDWord(0); Writer.WriteDWord(0); Writer.WriteDWord(0); Writer.WriteByte (1); Writer.WriteByte (player->Player.Flags.PvP); // 0 = blue costume pvp flag, 1 = blue costume no flag Writer.Finalize(); }
1cc7826bcd012020616d5ddd0563ad468f434ed9
7092d3a8dd5d75f30827bdf0d3a06878ba6cc75d
/FeatureTracker.cpp
243b05418a97e18f43e813987727cc966fb391dc
[]
no_license
MarkRunWu/paraft-non-parallel
007cee5826660c9175c1100f9e43cf0852782d6d
f8c196a8476b4616a9831e07057abc1bb3dddf0f
refs/heads/master
2021-01-21T01:06:08.272722
2013-05-19T15:07:56
2013-05-19T15:07:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,142
cpp
FeatureTracker.cpp
#include "FeatureTracker.h" FeatureTracker::FeatureTracker(Vector3i dim) : blockDim(dim) { maskValue = 0.0f; tfRes = 0; pTfMap = NULL; volumeSize = blockDim.Product(); pMaskCurrent = new float[volumeSize](); pMaskPrevious = new float[volumeSize](); if (pMaskCurrent == NULL || pMaskPrevious == NULL) { return; } } FeatureTracker::~FeatureTracker() { delete [] pMaskCurrent; delete [] pMaskPrevious; dataPointList.clear(); surfacePoints.clear(); innerPoints.clear(); if (featureSequence.size() > 0) { for (FeatureVectorSequence::iterator it = featureSequence.begin(); it != featureSequence.end(); it++) { vector<Feature> featureVector = it->second; for (size_t i = 0; i < featureVector.size(); i++) { featureVector.at(i).SurfacePoints.clear(); featureVector.at(i).InnerPoints.clear(); } } } } void FeatureTracker::Reset() { maskValue = 0.0f; numVoxelinFeature = 0; timestepsAvailableForward = 0; timestepsAvailableBackward = 0; sumCoordinateValue.x = sumCoordinateValue.y = sumCoordinateValue.z = 0; std::fill(pMaskCurrent, pMaskCurrent+volumeSize, 0); std::fill(pMaskPrevious, pMaskPrevious+volumeSize, 0); currentFeaturesHolder.clear(); backup1FeaturesHolder.clear(); backup2FeaturesHolder.clear(); backup3FeaturesHolder.clear(); dataPointList.clear(); surfacePoints.clear(); innerPoints.clear(); } void FeatureTracker::ExtractAllFeatures() { int count = 0; for (int z = 0; z < blockDim.z; z++) { for (int y = 0; y < blockDim.y; y++) { for (int x = 0; x < blockDim.x; x++) { int index = GetVoxelIndex(Vector3i(x, y, z)); if (pMaskCurrent[index] != 0) // point already within a feature continue; // most points should stop here int tfIndex = (int)(pVolumeData[index] * (float)(tfRes-1)); if (pTfMap[tfIndex] >= LOW_THRESHOLD && pTfMap[tfIndex] <= HIGH_THRESHOLD) { FindNewFeature(Vector3i(x,y,z)); count++; } } } } #ifdef _DEBUG cout << "find new feature num: " << count << endl; #endif } void FeatureTracker::FindNewFeature(Vector3i point) { sumCoordinateValue = point; dataPointList.clear(); surfacePoints.clear(); innerPoints.clear(); ///////////////////////////////// // Only one point now, take as edge point numVoxelinFeature = 1; surfacePoints.push_back(point); ///////////////////////////////// int index = GetVoxelIndex(point); if (pMaskCurrent[index] == 0) { maskValue += 1.0f; pMaskCurrent[index] = maskValue; } else { return; } ///////////////////////////////// expandRegion(maskValue); ///////////////////////////////// if (innerPoints.size() < (size_t)FEATURE_MIN_VOXEL_NUM) { maskValue -= 1.0f; return; } #ifdef _DEBUG cout << "region growing with: " << maskValue << " index :" << GetVoxelIndex(point) << endl; #endif Feature newFeature; { newFeature.ID = GetVoxelIndex(centroid); newFeature.Centroid = centroid; newFeature.SurfacePoints = surfacePoints; newFeature.InnerPoints = innerPoints; newFeature.MaskValue = maskValue; } #ifdef _DEBUG cout << "new feature: " << newFeature.MaskValue << "number: " << newFeature.InnerPoints.size() << endl; #endif currentFeaturesHolder.push_back(newFeature); backup1FeaturesHolder = currentFeaturesHolder; backup2FeaturesHolder = currentFeaturesHolder; backup3FeaturesHolder = currentFeaturesHolder; timestepsAvailableForward = 0; timestepsAvailableBackward = 0; } void FeatureTracker::TrackFeature(float* pData, int direction, int mode) { pVolumeData = pData; innerPoints.clear(); if (pTfMap == NULL || tfRes <= 0) { cout << "Set TF pointer first." << endl; exit(3); } // save current 0-1 matrix to previous, then clear current maxtrix std::copy(pMaskCurrent, pMaskCurrent+volumeSize, pMaskPrevious); std::fill(pMaskCurrent, pMaskCurrent+volumeSize, 0); for (size_t i = 0; i < currentFeaturesHolder.size(); i++) { Feature f = currentFeaturesHolder[i]; surfacePoints = f.SurfacePoints; #ifdef _DEBUG cout << "before 1st feature: " << f.MaskValue << "number: " << surfacePoints.size() << endl; #endif predictRegion(i, direction, mode); #ifdef _DEBUG cout << "before 2ed feature: " << f.MaskValue << "number: " << surfacePoints.size() << endl; #endif fillRegion(f.MaskValue); #ifdef _DEBUG cout << "before 3st feature: " << f.MaskValue << "number: " << surfacePoints.size() << endl; #endif shrinkRegion(f.MaskValue); #ifdef _DEBUG cout << "before 4st feature: " << f.MaskValue << "number: " << surfacePoints.size() << endl; #endif expandRegion(f.MaskValue); f.ID = GetVoxelIndex(centroid); f.Centroid = centroid; f.SurfacePoints = surfacePoints; f.InnerPoints = innerPoints; #ifdef _DEBUG cout << "feature: " << f.MaskValue << "number: " << innerPoints.size() << endl; #endif currentFeaturesHolder[i] = f; innerPoints.clear(); } backupFeatureInfo(direction); ExtractAllFeatures(); } inline void FeatureTracker::predictRegion(int index, int direction, int mode) { int timestepsAvailable = direction == FT_BACKWARD ? timestepsAvailableBackward : timestepsAvailableForward; delta.x = delta.y = delta.z = 0; Feature b1f = backup1FeaturesHolder[index]; Feature b2f = backup2FeaturesHolder[index]; Feature b3f = backup3FeaturesHolder[index]; int tmp; switch (mode) { case FT_DIRECT: // PREDICT_DIRECT break; case FT_LINEAR: // PREDICT_LINEAR if (timestepsAvailable > 1) { if (direction == FT_BACKWARD) { delta.x = b2f.Centroid.x - b1f.Centroid.x; delta.y = b2f.Centroid.y - b1f.Centroid.y; delta.z = b2f.Centroid.z - b1f.Centroid.z; } else { // Tracking forward as default delta.x = b3f.Centroid.x - b2f.Centroid.x; delta.y = b3f.Centroid.y - b2f.Centroid.y; delta.z = b3f.Centroid.z - b2f.Centroid.z; } for (list<Vector3i>::iterator p = b3f.SurfacePoints.begin(); p != b3f.SurfacePoints.end(); p++) { tmp = (*p).x + (int)floor((float)delta.x); (*p).x = tmp <= 0 ? 0 : (tmp < blockDim.x ? tmp : blockDim.x-1); tmp = (*p).y + (int)floor((float)delta.y); (*p).y = tmp <= 0 ? 0 : (tmp < blockDim.y ? tmp : blockDim.y-1); tmp = (*p).z + (int)floor((float)delta.z); (*p).z = tmp <= 0 ? 0 : (tmp < blockDim.z ? tmp : blockDim.z-1); } } break; case FT_POLYNO: // PREDICT_POLY if (timestepsAvailable > 1) { if (timestepsAvailable > 2) { delta.x = b3f.Centroid.x*2 - b2f.Centroid.x*3 + b1f.Centroid.x; delta.y = b3f.Centroid.y*2 - b2f.Centroid.y*3 + b1f.Centroid.y; delta.z = b3f.Centroid.z*2 - b2f.Centroid.z*3 + b1f.Centroid.z; } else { // [1,2) if (direction == FT_BACKWARD) { delta.x = b2f.Centroid.x - b1f.Centroid.x; delta.y = b2f.Centroid.y - b1f.Centroid.y; delta.z = b2f.Centroid.z - b1f.Centroid.z; } else { // Tracking forward as default delta.x = b3f.Centroid.x - b2f.Centroid.x; delta.y = b3f.Centroid.y - b2f.Centroid.y; delta.z = b3f.Centroid.z - b2f.Centroid.z; } } for (list<Vector3i>::iterator p = b3f.SurfacePoints.begin(); p != b3f.SurfacePoints.end(); p++) { tmp = (*p).x + (int)floor((float)delta.x); (*p).x = tmp <= 0 ? 0 : (tmp < blockDim.x ? tmp : blockDim.x-1); tmp = (*p).y + (int)floor((float)delta.y); (*p).y = tmp <= 0 ? 0 : (tmp < blockDim.y ? tmp : blockDim.y-1); tmp = (*p).z + (int)floor((float)delta.z); (*p).z = tmp <= 0 ? 0 : (tmp < blockDim.z ? tmp : blockDim.z-1); } } break; } } inline void FeatureTracker::fillRegion(float maskValue) { sumCoordinateValue.x = 0; sumCoordinateValue.y = 0; sumCoordinateValue.z = 0; numVoxelinFeature = 0; int index = 0; int indexPrev = 0; list<Vector3i>::iterator p; // predicted to be on edge for (p = surfacePoints.begin(); p != surfacePoints.end(); p++) { index = GetVoxelIndex(*p); if (pMaskCurrent[index] == 0) { pMaskCurrent[index] = maskValue; } sumCoordinateValue += (*p); innerPoints.push_back(*p); numVoxelinFeature++; } // currently not on edge but previously on edge for (p = surfacePoints.begin(); p != surfacePoints.end(); p++) { index = GetVoxelIndex(*p); indexPrev = GetVoxelIndex(Vector3i((*p).x-delta.x, (*p).y-delta.y, (*p).z-delta.z)); (*p).x++; while ((*p).x >= 0 && (*p).x <= blockDim.x && (*p).x - delta.x >= 0 && (*p).x - delta.x <= blockDim.x && (*p).y >= 0 && (*p).y <= blockDim.y && (*p).y - delta.y >= 0 && (*p).y - delta.y <= blockDim.y && (*p).z >= 0 && (*p).z <= blockDim.z && (*p).z - delta.z >= 0 && (*p).z - delta.z <= blockDim.z && pMaskCurrent[index] == 0 && pMaskPrevious[indexPrev] == maskValue) { // Mark all points: 1. currently = 1; 2. currently = 0 but previously = 1; pMaskCurrent[index] = maskValue; sumCoordinateValue += (*p); innerPoints.push_back(*p); numVoxelinFeature++; (*p).x++; } } if (numVoxelinFeature == 0) { return; } centroid = sumCoordinateValue / numVoxelinFeature; } inline void FeatureTracker::shrinkRegion(float maskValue) { Vector3i point; int index = 0; int indexCurr = 0; bool isPointOnEdge; // mark all edge points as 0 while (surfacePoints.empty() == false) { point = surfacePoints.front(); shrinkEdge(point, maskValue); surfacePoints.pop_front(); } while (dataPointList.empty() == false) { point = dataPointList.front(); dataPointList.pop_front(); index = GetVoxelIndex(point); if (getOpacity(pVolumeData[index]) < lowerThreshold || getOpacity(pVolumeData[index]) > upperThreshold) { isPointOnEdge = false; // if point is invisible, mark its adjacent points as 0 // shrinkEdge(point, maskValue); // center if (++point.x < blockDim.x) { shrinkEdge(point, maskValue); } point.x--; // right if (++point.y < blockDim.y) { shrinkEdge(point, maskValue); } point.y--; // top if (++point.z < blockDim.z) { shrinkEdge(point, maskValue); } point.z--; // back if (--point.x > 0) { shrinkEdge(point, maskValue); } point.x++; // left if (--point.y > 0) { shrinkEdge(point, maskValue); } point.y++; // bottom if (--point.z > 0) { shrinkEdge(point, maskValue); } point.z++; // front } else if (pMaskCurrent[index] == 0) { isPointOnEdge = true; } if (isPointOnEdge == true) { surfacePoints.push_back(point); } } for (list<Vector3i>::iterator p = surfacePoints.begin(); p != surfacePoints.end(); ++p) { index = GetVoxelIndex((*p)); indexCurr = GetVoxelIndex(point); if (pMaskCurrent[indexCurr] != maskValue) { sumCoordinateValue += (*p); innerPoints.push_back(*p); numVoxelinFeature++; pMaskCurrent[indexCurr] = maskValue; } } if (numVoxelinFeature == 0) { return; } centroid = sumCoordinateValue / numVoxelinFeature; } inline void FeatureTracker::shrinkEdge(Vector3i point, float maskValue) { int index = GetVoxelIndex(point); if (pMaskCurrent[index] == maskValue) { pMaskCurrent[index] = 0; // shrink sumCoordinateValue -= point; numVoxelinFeature--; for (list<Vector3i>::iterator p = innerPoints.begin(); p != innerPoints.end(); p++) { if (point.x == (*p).x && point.y == (*p).y && point.z == (*p).z) { innerPoints.erase(p); break; } } dataPointList.push_back(point); } } // Grow edge where possible for all the features in the CurrentFeaturesHolder // Say if we have several features in one time step, the number we call GrowRegion is the number of features // Each time before we call this function, we should copy the edges points of one feature we want to grow in edge inline void FeatureTracker::expandRegion(float maskValue) { // put edge points to feature body while (surfacePoints.empty() == false) { dataPointList.push_back(surfacePoints.front()); surfacePoints.pop_front(); } // edgePointList should be empty while (dataPointList.empty() == false) { Vector3i point = dataPointList.front(); dataPointList.pop_front(); bool onBoundary = false; if (++point.x < blockDim.x) { onBoundary |= expandEdge(point, maskValue); } point.x--; // right if (++point.y < blockDim.y) { onBoundary |= expandEdge(point, maskValue); } point.y--; // top if (++point.z < blockDim.z) { onBoundary |= expandEdge(point, maskValue); } point.z--; // front if (--point.x > 0) { onBoundary |= expandEdge(point, maskValue); } point.x++; // left if (--point.y > 0) { onBoundary |= expandEdge(point, maskValue); } point.y++; // bottom if (--point.z > 0) { onBoundary |= expandEdge(point, maskValue); } point.z++; // back if (onBoundary) { surfacePoints.push_back(point); } } if (numVoxelinFeature == 0) { return; } centroid = sumCoordinateValue / numVoxelinFeature; } inline bool FeatureTracker::expandEdge(Vector3i point, float maskValue) { int index = GetVoxelIndex(point); if (pMaskCurrent[index] != 0) { return false; // not on edge, inside feature, no need to adjust } if (getOpacity(pVolumeData[index]) >= lowerThreshold && getOpacity(pVolumeData[index]) <= upperThreshold) { pMaskCurrent[index] = maskValue; dataPointList.push_back(point); innerPoints.push_back(point); sumCoordinateValue += point; numVoxelinFeature++; return false; } else { return true; } } void FeatureTracker::SetCurrentFeatureInfo(vector<Feature> *pFeatures) { currentFeaturesHolder.clear(); for (size_t i = 0; i < pFeatures->size(); i++) { currentFeaturesHolder.push_back(pFeatures->at(i)); } backup1FeaturesHolder = currentFeaturesHolder; backup2FeaturesHolder = currentFeaturesHolder; backup3FeaturesHolder = currentFeaturesHolder; timestepsAvailableForward = 0; timestepsAvailableBackward = 0; } void FeatureTracker::backupFeatureInfo(int direction) { backup1FeaturesHolder = backup2FeaturesHolder; backup2FeaturesHolder = backup3FeaturesHolder; backup3FeaturesHolder = currentFeaturesHolder; if (direction == FT_FORWARD) { if (timestepsAvailableForward < 3) timestepsAvailableForward++; if (timestepsAvailableBackward > 0) timestepsAvailableBackward--; } else { // direction is either FORWARD or BACKWARD if (timestepsAvailableForward > 0) timestepsAvailableForward--; if (timestepsAvailableBackward < 3) timestepsAvailableBackward++; } }
b9a1abba1dbac8aebea126d90b3cd3628589f2fb
fb6df08ae247e17245802c880eb0db783d074f4c
/lesson2/graphcut.cpp
2771b38247b24cd1d267965929a26724e167c0f9
[]
no_license
cvlabmiet/cvclasses16
e64b71aebcd0db060182ddb553594122ef48557b
0d92410629eac97608d30f4025030361120abca3
refs/heads/master
2021-01-20T23:08:49.683823
2016-12-24T08:24:42
2016-12-24T08:24:42
62,642,856
0
10
null
2016-12-26T19:59:27
2016-07-05T14:20:53
C++
UTF-8
C++
false
false
5,669
cpp
graphcut.cpp
#include <iostream> #include <vector> #include <chrono> #include "opencv2/core/utility.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc.hpp" using namespace cv; using namespace std; static string imgname; static Mat imgOrigin, img2Show; static Rect rect; static bool rectIsSet = false; static const string winName = "Grabcut"; static const Scalar lineColor = Scalar(0, 255, 0); static const Scalar bgdChooseColor = Scalar(0, 0, 255); static const Scalar fgdChooseColor = Scalar(255, 0, 0); static const int lineWidth = 2; static int iterCount = 0; static const int BGD_KEY = EVENT_FLAG_CTRLKEY; static const int FGD_KEY = EVENT_FLAG_SHIFTKEY; static vector<Point2i> fgdPoints; static vector<Point2i> bgdPoints; static void help() { cout << "\nThis program demonstrates the grabcut algorithm step-by-step.\n" "Usage:\n" "./..."; } static Mat prepareFrame() { Mat frame; img2Show.copyTo(frame); if (rectIsSet) { rectangle(frame, rect, lineColor, lineWidth); } for (auto i : fgdPoints) { circle(frame, i, 2, fgdChooseColor); } for (auto i : bgdPoints) { circle(frame, i, 2, bgdChooseColor); } return frame; } static void redrawWindow() { Mat frame = prepareFrame(); imshow(winName, frame); } static void onMouse(int event, int x, int y, int flags, void*) { static Point2i rectCorn1; if (x < 0 || x >= imgOrigin.cols || y < 0 || y >= imgOrigin.rows) { return; } if (event == EVENT_LBUTTONDOWN) { if (flags & BGD_KEY) { bgdPoints.push_back(Point2i(x, y)); } else if (flags & FGD_KEY) { fgdPoints.push_back(Point2i(x, y)); } else { rectIsSet = false; rectCorn1 = Point2i(x, y); } } else if (event == EVENT_LBUTTONUP) { } else if (event == EVENT_MOUSEMOVE && (flags & EVENT_FLAG_LBUTTON)) { if (flags & BGD_KEY) { bgdPoints.push_back(Point2i(x, y)); } else if (flags & FGD_KEY) { fgdPoints.push_back(Point2i(x, y)); } else { Point2i rectCorn2 = Point2i(x, y); // Select top left corner and calculate rectangle size int topLeftX = min(rectCorn1.x, rectCorn2.x); int topLeftY = min(rectCorn1.y, rectCorn2.y); int rectWidth = abs(rectCorn1.x - rectCorn2.x); int rectHeight = abs(rectCorn1.y - rectCorn2.y); rect = Rect(topLeftX, topLeftY, rectWidth, rectHeight); rectIsSet = true; } } redrawWindow(); } static void reset() { imgOrigin.copyTo(img2Show); rectIsSet = false; iterCount = 0; bgdPoints.clear(); fgdPoints.clear(); redrawWindow(); } static void dumpImages() { string prefix = "gc_" + imgname + "_" + to_string(iterCount) + "_"; imwrite(prefix + "ui.png", prepareFrame()); imwrite(prefix + "res.png", img2Show); } static void grabCutIter(bool firstIter) { using namespace std::chrono; static Mat mask; static Mat bgdModel; static Mat fgdModel; high_resolution_clock::time_point startTime, endTime; if (firstIter) { if (rectIsSet) { mask = Mat::ones(imgOrigin.size(), CV_8UC1) * GC_BGD; Mat roi = mask(rect); roi.setTo(GC_PR_FGD); } else { mask = Mat::ones(imgOrigin.size(), CV_8UC1) * GC_PR_FGD; } bgdModel = Mat(); fgdModel = Mat(); } for (auto pt : bgdPoints) { mask.at<char>(pt.y, pt.x) = GC_BGD; } for (auto pt : fgdPoints) { mask.at<char>(pt.y, pt.x) = GC_FGD; } startTime = high_resolution_clock::now(); int flags = firstIter? GC_INIT_WITH_MASK : GC_EVAL; grabCut(imgOrigin, mask, rect, bgdModel, fgdModel, 1, flags); endTime = high_resolution_clock::now(); duration<double> time_span = duration_cast<duration<double>>(endTime - startTime); iterCount++; img2Show = Mat(); imgOrigin.copyTo(img2Show, (mask & GC_FGD)); redrawWindow(); cout << "Iteration " << iterCount << ", time: " << time_span.count() << " s." << endl; dumpImages(); } int graphcut(int argc, char** argv) { CommandLineParser parser(argc, argv, "{help h | | }{ @input | ../data/fruits.jpg | }"); if (parser.get<bool>("help")) { help(); return 0; } imgname = parser.get<string>("@input"); imgOrigin = imread(imgname, CV_LOAD_IMAGE_COLOR); if (imgOrigin.empty()) { cout << "Failed to open image " << imgname << "." << endl; exit(EXIT_FAILURE); } imwrite("gc_" + imgname + ".png", imgOrigin); reset(); namedWindow(winName, 1); imshow(winName, imgOrigin); setMouseCallback(winName, onMouse, 0); for(;;) { int c = waitKey(0); // ESC if ((char) c == 27) { break; } // Restore if ((char) c == 'r') { cout << "----Reset----" << endl; reset(); } // Start demo if ((char) c == ' ') { grabCutIter(true); } // Next step if ((char) c == 'n') { if (iterCount > 0) { grabCutIter(false); } else { cout << "Push space to start iterations or push r to reset" << endl; } } } return 0; }
8c81460d549c72ba503bcd952c99da20b63b5eb8
3172e1455ae3d40289c122f1e39da054c3137f40
/Ishrakk_Tawsif-ac/UVA/12442/8272038_AC_670ms_0kB.cpp
860f58285a20f34929ee1a22b518967045301609
[]
no_license
Ishrak-Tawsif/Accepted-Codes
959d2e1b444e3a7727ad78945f0590f62819ba31
24254c00e4b1c5a0b5ffc8eb2a01ee1d53f9a467
refs/heads/master
2020-12-26T19:36:15.048621
2020-02-01T13:27:56
2020-02-01T13:27:56
237,616,661
0
0
null
null
null
null
UTF-8
C++
false
false
2,337
cpp
8272038_AC_670ms_0kB.cpp
#include<bits/stdc++.h> using namespace std; #define mx 50003 vector <int> graph[mx]; //bitset <mx> vis; int dis[mx],vis[mx],vis2[mx],max_; int dfs(int s) { vis[s]=vis2[s]=1; for(int i=0; i<graph[s].size(); i++) { int v=graph[s][i]; if(!vis2[v]) { dis[v]=dis[s]+1; max_=max(max_,dis[v]); dfs(v); } } vis2[s]=0; } ///getting timelimit using bfs because of initiate vis2 to 0 everytime /*int bfs(int s) { memset(vis2,0,sizeof(vis2)); queue <int> q; q.push(s); dis[s]=0; vis2[s]=1; int max_=0; while(!q.empty()) { int u=q.front(); q.pop(); for(int i=0; i<graph[u].size(); i++) { int v=graph[u][i]; if(!vis2[v]) { vis[v]=vis2[v]=1; dis[v]=dis[u]+1;//cout<<".."<<v<<endl; max_=max(max_,dis[v]); q.push(v); } } } return max_; }*/ int main() { int tc,n,u,v; scanf("%d", &tc); for(int tt=1; tt<=tc; tt++) { for(int i=0; i<mx; i++) graph[i].clear(); scanf("%d", &n); for(int i=0; i<n; i++) { scanf("%d %d", &u,&v); graph[u].push_back(v); } int ans=INT_MIN,aa; memset(vis,0,sizeof(vis)); for(int i=1; i<=n; i++) { if(!vis[i]){ dis[i]=0; max_=INT_MIN; int temp=dfs(i);//cout<<i<<" "<<ans<<" "<<max_<<endl; //for(int i=1;i<=n; i++) cout<<vis2[i]<<" "; cout<<endl; if(max_>ans) {//cout<<i<<" "<<max_<<endl; ans=max_; aa=i; } } } printf("Case %d: %d\n",tt,aa); } return 0; }
bff926c7f3ffeca93813b9f2d87a14cb4980c251
6d51efbb264ef5920a99c54e2e436bc2f0a4ec40
/C++-Practise/TRIE.cpp
1395f60e98c29484ce5cb1a792412f418e90a55b
[]
no_license
Sarvesh1990/Coding-Practise
db3adc0d4fca25ddee6ea5c99ad6a26baac917de
6c64219f058d89c3fb76cc86ece4ec14dffd286e
refs/heads/master
2021-01-10T15:33:56.291896
2016-01-09T11:37:01
2016-01-09T11:37:01
47,115,152
0
0
null
null
null
null
UTF-8
C++
false
false
1,513
cpp
TRIE.cpp
#include <iostream> #include <string> #define DIFF(c) ((int)c - (int)'a') using namespace std; struct Node { int value; Node * children [26]; }; Node * newNode() { Node * myNode = new Node(); myNode->value=0; for(int i=0; i<26; i++) myNode->children[i]=NULL; return myNode; } /* int DIFF(char c) { return ((int)c - (int)'a'); } */ void Insert(Node * root, char * key, int myValue) { int length = strlen(key); for(int i=0; i<length; i++) { if(!root->children[DIFF(key[i])]) root->children[DIFF(key[i])]=newNode(); root=root->children[DIFF(key[i])]; } root->value=myValue; } void Search (Node * root, char * key) { int length = strlen(key); bool flag=true; for(int i=0; i<length; i++) { if(!root->children[DIFF(key[i])]) { flag=false; break; } else { root=root->children[DIFF(key[i])]; } } if(!flag) { cout<<"Word not present"<<endl; return; } if(root->value > 0) cout<<"Word is there with value "<<root->value<<endl; else cout<<"Word not present"<<endl; } int main() { char keys[][9] = {"the", "a", "there", "answer", "any", "by", "anything", "bye", "their"}; Node * root = newNode(); for(int i=0; i<9; i++) { Insert(root, keys[i], i); } Search(root, "answer"); Search(root, "an"); Search(root,"any"); Search(root,"anything"); }
8810141f0190b0311f55ddceefb3405266df54fd
0f7bdf7a3c719f2437f79ec0605e66de4ec33859
/src/swizzles/uci/go.cpp
1e981237c635e623feab0444ac4733823e287656
[ "MIT" ]
permissive
kz04px/swizzles
0646fe1b6ffec80bfabe6f30cdc5d09694afb28f
d77585055922e64ed4f5ff3acd1a9a28c80ae399
refs/heads/master
2022-05-31T06:30:41.553468
2022-05-07T20:17:58
2022-05-07T20:17:58
356,985,339
1
13
MIT
2022-04-12T20:42:30
2021-04-11T21:39:32
C++
UTF-8
C++
false
false
3,264
cpp
go.cpp
#include <cstdint> #include <iostream> #include <thread> #include "../search/pv.hpp" #include "../search/root.hpp" #include "../search/settings.hpp" #include "../settings.hpp" #include "uci.hpp" namespace swizzles::uci { std::thread search_thread; std::atomic<bool> search_stop = false; auto uci_info_printer = [](const int depth, const int seldepth, const int eval, const std::uint64_t ms, const std::uint64_t nodes, const std::uint64_t nps, const int tbhits, const int hashfull, const search::PV &pv) { std::cout << "info"; std::cout << " depth " << depth; std::cout << " seldepth " << seldepth; std::cout << " score cp " << eval; std::cout << " time " << ms; std::cout << " nodes " << nodes; std::cout << " nps " << nps; std::cout << " tbhits " << tbhits; std::cout << " hashfull " << hashfull; if (!pv.empty()) { std::cout << " pv"; for (const auto move : pv) { std::cout << " " << move; } } std::cout << std::endl; }; auto stop() noexcept -> void { search_stop = true; if (search_thread.joinable()) { search_thread.join(); } search_stop = false; } auto go(std::stringstream &ss, const UCIState &state) noexcept -> void { stop(); // Search settings auto settings = search::SearchSettings(); settings.info_printer = uci_info_printer; while (!ss.eof()) { std::string word; ss >> word; if (word == "wtime") { ss >> word; settings.type = search::SearchType::Time; settings.wtime = std::stoi(word); } else if (word == "btime") { ss >> word; settings.type = search::SearchType::Time; settings.btime = std::stoi(word); } else if (word == "winc") { ss >> word; settings.type = search::SearchType::Time; settings.winc = std::stoi(word); } else if (word == "binc") { ss >> word; settings.type = search::SearchType::Time; settings.binc = std::stoi(word); } else if (word == "depth") { ss >> word; settings.type = search::SearchType::Depth; settings.depth = std::stoi(word); } else if (word == "movetime") { ss >> word; settings.type = search::SearchType::Movetime; settings.movetime = std::stoi(word); } else if (word == "nodes") { // ss >> word; // settings.type = search::SearchType::Nodes; // settings.nodes = std::stoi(word); } else if (word == "movestogo") { ss >> word; settings.movestogo = std::stoi(word); } else if (word == "infinite") { settings.type = search::SearchType::Infinite; } } search_thread = std::thread([state, settings]() { const auto results = search::root(state, settings, search_stop); std::cout << "bestmove " << results.bestmove << std::endl; }); } } // namespace swizzles::uci
4bde0980b7744078058e5685f78c89d761de2383
a0798af89acaa5fb2959e2bba20e26d0b9e84da9
/Editor/src/gdeditor.h
974f149fdeee954a2bb5e378678e785d22e35e56
[ "Apache-2.0" ]
permissive
guilmont/GDManager
b562a114176d2a986e90d7e41a6b764ea8f61fa9
dedb0b6c5e1c55886def5360837cbce2485c0d78
refs/heads/master
2023-08-06T14:31:15.696019
2021-10-01T06:39:42
2021-10-01T06:39:42
397,579,554
0
0
null
null
null
null
UTF-8
C++
false
false
1,068
h
gdeditor.h
#include "GDManager.h" #include "GRender.h" class GDEditor : public GRender::Application { public: GDEditor(void); ~GDEditor(void); void onUserUpdate(float deltaTime) override; void ImGuiLayer(void) override; void ImGuiMenuLayer(void) override; void openFile(const fs::path& inPath); // So we can open files from the command line void saveFile(void); private: void recursiveTreeLoop(GDM::Group *group, ImGuiTreeNodeFlags nodeFlags); void treeViewWindow(void); void detailWindow(void); void releaseMemory(GDM::Group* group); void addObject(GDM::Group *group); private: bool view_imguidemo = false, view_implotdemo = false; private: GDM::Data* plotPointer = nullptr; void (GDEditor::* plotWindow)(void) = nullptr; void plotHeatmap(void); void plotLines(void); private: std::string close_file = ""; struct { GDM::Group *group = nullptr; bool view = false; } addObj; GDM::Object* currentObj = nullptr; GDM::File* currentFile = nullptr; std::map<fs::path, GDM::File> vFile; };
5691da0fa23ec95c3e2c4f69a1a31a246698f3ee
acbc41a1399241aaebbd8704a93fabae4d6f276d
/src/qt/myrestrictedassetrecord.cpp
fda030aa531d04f29ad38d4000c60f26e0d6b932
[ "MIT" ]
permissive
RavenProject/Ravencoin
208d9be7fcc833ff4e997aa5e47b28502062547b
e48d932ec70267a62ec3541bdaf4fe022c149f0e
refs/heads/master
2023-08-24T16:19:21.693091
2023-03-12T00:02:22
2023-03-12T00:02:22
96,713,114
1,218
871
MIT
2023-06-04T06:12:44
2017-07-09T21:42:06
C
UTF-8
C++
false
false
2,839
cpp
myrestrictedassetrecord.cpp
// Copyright (c) 2011-2016 The Bitcoin Core developers // Copyright (c) 2017-2019 The Raven Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "myrestrictedassetrecord.h" #include "assets/assets.h" #include "base58.h" #include "consensus/consensus.h" #include "validation.h" #include "timedata.h" #include "wallet/wallet.h" #include <stdint.h> #include <QDebug> /* Return positive answer if transaction should be shown in list. */ bool MyRestrictedAssetRecord::showTransaction(const CWalletTx &wtx) { // There are currently no cases where we hide transactions, but // we may want to use this in the future for things like RBF. return true; } /* * Decompose CWallet transaction to model transaction records. */ QList<MyRestrictedAssetRecord> MyRestrictedAssetRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx) { QList<MyRestrictedAssetRecord> parts; int64_t nTime = wtx.GetTxTime(); uint256 hash = wtx.GetHash(); std::map<std::string, std::string> mapValue = wtx.mapValue; for(unsigned int i = 0; i < wtx.tx->vout.size(); i++) { const CTxOut &txout = wtx.tx->vout[i]; isminetype mine = ISMINE_NO; if (txout.scriptPubKey.IsNullAssetTxDataScript()) { CNullAssetTxData data; std::string address; if (!AssetNullDataFromScript(txout.scriptPubKey, data, address)) { continue; } mine = IsMine(*wallet, DecodeDestination(address)); if (mine & ISMINE_ALL) { MyRestrictedAssetRecord sub(hash, nTime); sub.involvesWatchAddress = mine & ISMINE_SPENDABLE ? false : true; sub.assetName = data.asset_name; sub.address = address; if (IsAssetNameAQualifier(data.asset_name)) { if (data.flag == (int) QualifierType::ADD_QUALIFIER) { sub.type = MyRestrictedAssetRecord::Type::Tagged; } else { sub.type = MyRestrictedAssetRecord::Type::UnTagged; } } else if (IsAssetNameAnRestricted(data.asset_name)) { if (data.flag == (int) RestrictedType::FREEZE_ADDRESS) { sub.type = MyRestrictedAssetRecord::Type::Frozen; } else { sub.type = MyRestrictedAssetRecord::Type::UnFrozen; } } parts.append(sub); } } } return parts; } QString MyRestrictedAssetRecord::getTxID() const { return QString::fromStdString(hash.ToString()); } int MyRestrictedAssetRecord::getOutputIndex() const { return idx; }
546da843dcc32caea226c4368c7856c8edebb65f
13d7dd2ec7e94721edce66e01075e3024c6ece28
/M2TWEOP/Params.h
bf1d543ae3686f0c7d5a340ce63ac76ae153c2bb
[]
no_license
youneuoy/M2TWEOP
7918717e0621c0d053f464a77edd65bc053aa7c9
8e4d9697d447322f478448e1dbcf335ed8720b28
refs/heads/master
2023-03-02T12:40:56.377072
2021-02-08T07:17:11
2021-02-08T07:17:11
302,403,597
1
0
null
null
null
null
UTF-8
C++
false
false
493
h
Params.h
#pragma once #include <string> #include <vector> #include <windows.h> using namespace std; class Params { public: static void readStringInQuotes(string* arg, string s, string param); static void findOWParam(char* arg, string s, string param); static string getParrentDir(string patch); static string getFileName(string file); static void findAnyParam(bool* arg, string s, string param); private: static void replaceAll(string& s, const string& search, const string& replace); };
3a1b0a3c4ce4942b3bea639bbcb9adccb6d72688
19555fc7ebb58e6d915b78a22b9b8a29de4fabe0
/inc/platform/application.h
380780c55745974bd321c77eabf5328c7f30b770
[ "Unlicense" ]
permissive
wyrover/freeimage-PhotoViewer
1713a79d0f4a98b0b0ee7cca31aadc6e88c476a6
9d8fa6024e81e50904bab941501c639716cf26e0
refs/heads/master
2021-05-27T18:05:11.281823
2013-09-03T03:20:54
2013-09-03T03:20:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,354
h
application.h
#ifndef _PLATFORM_APPLICATION_H_INCLUDED_ #define _PLATFORM_APPLICATION_H_INCLUDED_ #include <string> #include "platform/registrysettings.h" #include "platform/eventhandler.h" namespace Platform { class Application : public Platform::EventHandler { public: Application(const std::wstring &name, const std::wstring &cmdLine); virtual ~Application(); virtual bool run() = 0; protected: /** * Returns an accessor to our application registry settings */ RegistrySettings &getRegistrySettings() { return _registrySettings; } /** * Process events until there are none left. * Returns false if there was a problem getting messages */ bool processEvents(); /** * Process events for the given number of milliseconds then return. * Returns false if there was a problem getting messages. */ bool processEvents(int sleepTimeMilliseconds); /** * Processes any pending events and return. * Returns false if the app is quiting otherwise returns true */ bool processPendingEvents(); protected: std::wstring _name; std::wstring _cmdLine; RegistrySettings _registrySettings; }; }; #endif
508f979f6782120f174cef875a426fa76c5d8965
59b8ea5e919fe9761fe5799e9f591850d71383c0
/codechef/long/jan_2020/BreakingBricks.cpp
227681abecbff4c7f3403302f469bd99bf6ac1f1
[]
no_license
utsavkuchhal/Competitive-Programming
a25db05aaf16009910497c1b1127815fece332aa
fd16601f223dbd168c4a3efda7d78af799ac4602
refs/heads/master
2023-04-18T00:33:31.738464
2021-04-24T03:07:50
2021-04-24T03:07:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
604
cpp
BreakingBricks.cpp
#include<bits/stdc++.h> using namespace std; int main(){ int t; cin>>t; while(t--){ int s,w1,w2,w3; cin>>s>>w1>>w2>>w3; int count=0; if(w1+w2+w3<=s){ count++; cout<<count<<endl; } else{ if(w1+w2<=s){ count+=2; } else{ count++; if(w2+w3<=s){ count++; } else{ count+=2; } } cout<<count<<endl; } } return 0; }
6f6af2641c4ba695c7cca2bf9d23262a359c2b56
749f3d84569bf9de824d9b5d941a1c3030c6fb8a
/Ch3_Oscillation/oscillatorObjects/src/oscillatorObjectsApp.cpp
27fb620de5197be44925e526a2d19970ac07b377
[]
no_license
jefarrell/NatureOfCode_Cinder
1da74b6d1f3680f2fcd0883e3fa68c0d673225f0
54f096c0ab94663e6611b7b37acfa42822b1c864
refs/heads/master
2021-01-10T08:57:47.102139
2016-03-25T17:45:41
2016-03-25T17:45:41
50,674,906
0
0
null
null
null
null
UTF-8
C++
false
false
954
cpp
oscillatorObjectsApp.cpp
#include "cinder/app/App.h" #include "cinder/app/RendererGl.h" #include "cinder/gl/gl.h" #include "Oscillator.hpp" using namespace ci; using namespace ci::app; using namespace std; class oscillatorObjectsApp : public App { public: void setup() override; void mouseDown( MouseEvent event ) override; void update() override; void draw() override; int NUM_OSC = 15; OscillatorRef oscillator; vector <OscillatorRef> oscillators_; }; void oscillatorObjectsApp::setup() { for (int i = 0; i < NUM_OSC; i++) { oscillator = Oscillator::create(); oscillators_.push_back(oscillator); } } void oscillatorObjectsApp::mouseDown( MouseEvent event ) { } void oscillatorObjectsApp::update() { for (auto o : oscillators_) o->update(); } void oscillatorObjectsApp::draw() { gl::clear( Color( 1, 1, 1 ) ); for (auto o : oscillators_) o->draw(); } CINDER_APP( oscillatorObjectsApp, RendererGl )
4f8116da202e3a3ac0da18212583cbae75203cb9
2d8e60c31515daf8865642304c6fedf228399707
/Game2D/Renderer.cpp
093ba9a191ddf05cf793c4c2e279f5a5fb8d2bd1
[]
no_license
Bargestt/Game2D-ShootingDuel
fd3ad3c2e57cfdc63536ac068f976e41e00dee24
2ed3ef053bef7869e1ae11ca9fd5b1904a814ef6
refs/heads/master
2020-03-15T12:40:53.721554
2018-05-06T08:14:35
2018-05-06T08:14:35
132,149,478
0
0
null
null
null
null
UTF-8
C++
false
false
674
cpp
Renderer.cpp
#include "stdafx.h" #include "Renderer.h" using namespace std; using namespace sf; Renderer::Renderer(const GameContext& context) : pWindow(context.window) { } Renderer::~Renderer() { } void Renderer::finishRender() { pWindow->clear(); for (auto shape : drawables) { pWindow->draw(*shape); } drawables.clear(); pWindow->display(); } void Renderer::draw(const sf::Drawable& drawable) { drawables.push_back(&drawable); } bool Renderer::isInside(sf::Vector2f point, float leeway) { auto rect = sf::FloatRect( 0 - leeway, 0 - leeway, pWindow->getSize().x + leeway * 2, pWindow->getSize().y + leeway * 2); return rect.contains(point); }
82880709041df153a5b6b0edba53c05945ebdf7c
bdbdeda733fb1f44ec3f08dc071136f6e0347439
/reportvalidator.h
f3c49b1caff92945235b81a13cafd8f6ffbaa7eb
[]
no_license
theunusingname/filingCheck
54c220b29fe30f5e977d4dfdb76aca084e7451d1
31529427144cfa2cf12d407eab11800a95ed807d
refs/heads/master
2021-01-10T02:31:01.935980
2016-01-29T19:30:39
2016-01-29T19:30:39
50,236,090
0
0
null
null
null
null
UTF-8
C++
false
false
381
h
reportvalidator.h
#ifndef REPORTVALIDATO_H #define REPORTVALIDATO_H #include <QFile> #include <QTextStream> #include <qfiledialog.h> #include <QString> class ReportValidator { private: QStringList filesList; QStringList watingList; int schema; public: enum{V2,V3,XML}; ReportValidator(); ReportValidator(int schema, QStringList fileList); }; #endif // REPORTVALIDATO_H
afc9c5566d2417a113bfee97298a0e49d9f4f5b2
9a33566bdd5fd8a1a7f40b27f69ad8d1118f8f18
/epoch/ayla/include/ayla/serialization/vertex_serializer.hpp
a134b9d2bebec059ef4ba10fcc833198f2424461
[ "MIT" ]
permissive
nwalablessing/vize
d0968f6208d608d9b158f0b21b0d063a12a45c81
042c16f96d8790303563be6787200558e1ec00b2
refs/heads/master
2023-05-31T15:39:02.877681
2019-12-22T14:09:02
2019-12-22T14:09:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
297
hpp
vertex_serializer.hpp
#ifndef AYLA_VERTEX_SERIALIZER_HPP #define AYLA_VERTEX_SERIALIZER_HPP namespace ayla { class Vertex; } namespace boost { namespace serialization { template <class Archive> void serialize(Archive& ar, ayla::Vertex& vertex, const unsigned int version); } } #endif // AYLA_VERTEX_SERIALIZER_HPP
a91a261fad56ac2c8f646346431f16b87fac537e
a5a99f646e371b45974a6fb6ccc06b0a674818f2
/Alignment/OfflineValidation/plugins/MuonAlignmentAnalyzer.cc
38cb8d0adaf394d06c8f52633c3f078fcfe1b783
[ "Apache-2.0" ]
permissive
cms-sw/cmssw
4ecd2c1105d59c66d385551230542c6615b9ab58
19c178740257eb48367778593da55dcad08b7a4f
refs/heads/master
2023-08-23T21:57:42.491143
2023-08-22T20:22:40
2023-08-22T20:22:40
10,969,551
1,006
3,696
Apache-2.0
2023-09-14T19:14:28
2013-06-26T14:09:07
C++
UTF-8
C++
false
false
135,953
cc
MuonAlignmentAnalyzer.cc
/** \class MuonAlignmentAnalyzer * MuonAlignment offline Monitor Analyzer * Makes histograms of high level Muon objects/quantities * for Alignment Scenarios/DB comparison * * $Date: 2011/09/04 17:40:58 $ * $Revision: 1.13 $ * \author J. Fernandez - Univ. Oviedo <Javier.Fernandez@cern.ch> */ #include "Alignment/OfflineValidation/plugins/MuonAlignmentAnalyzer.h" #include "TrackingTools/TrajectoryState/interface/FreeTrajectoryState.h" // Collaborating Class Header #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/Event.h" #include "Geometry/CommonDetUnit/interface/GeomDet.h" #include "DataFormats/Math/interface/deltaR.h" #include "TrackingTools/TransientTrack/interface/TransientTrack.h" #include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" #include "DataFormats/TrackingRecHit/interface/RecSegment.h" #include "TrackPropagation/SteppingHelixPropagator/interface/SteppingHelixPropagator.h" #include "DataFormats/GeometryVector/interface/GlobalVector.h" #include "DataFormats/GeometrySurface/interface/Cylinder.h" #include "DataFormats/GeometrySurface/interface/Plane.h" #include "DataFormats/GeometrySurface/interface/Cone.h" #include "TH2F.h" #include "TLorentzVector.h" /// Constructor MuonAlignmentAnalyzer::MuonAlignmentAnalyzer(const edm::ParameterSet &pset) : magFieldToken_(esConsumes()), trackingGeometryToken_(esConsumes()), theSTAMuonTag(pset.getParameter<edm::InputTag>("StandAloneTrackCollectionTag")), theGLBMuonTag(pset.getParameter<edm::InputTag>("GlobalMuonTrackCollectionTag")), theRecHits4DTagDT(pset.getParameter<edm::InputTag>("RecHits4DDTCollectionTag")), theRecHits4DTagCSC(pset.getParameter<edm::InputTag>("RecHits4DCSCCollectionTag")), theDataType(pset.getUntrackedParameter<std::string>("DataType")), doSAplots(pset.getUntrackedParameter<bool>("doSAplots")), doGBplots(pset.getUntrackedParameter<bool>("doGBplots")), doResplots(pset.getUntrackedParameter<bool>("doResplots")), ptRangeMin(pset.getUntrackedParameter<double>("ptRangeMin")), ptRangeMax(pset.getUntrackedParameter<double>("ptRangeMax")), invMassRangeMin(pset.getUntrackedParameter<double>("invMassRangeMin")), invMassRangeMax(pset.getUntrackedParameter<double>("invMassRangeMax")), resLocalXRangeStation1(pset.getUntrackedParameter<double>("resLocalXRangeStation1")), resLocalXRangeStation2(pset.getUntrackedParameter<double>("resLocalXRangeStation2")), resLocalXRangeStation3(pset.getUntrackedParameter<double>("resLocalXRangeStation3")), resLocalXRangeStation4(pset.getUntrackedParameter<double>("resLocalXRangeStation4")), resLocalYRangeStation1(pset.getUntrackedParameter<double>("resLocalYRangeStation1")), resLocalYRangeStation2(pset.getUntrackedParameter<double>("resLocalYRangeStation2")), resLocalYRangeStation3(pset.getUntrackedParameter<double>("resLocalYRangeStation3")), resLocalYRangeStation4(pset.getUntrackedParameter<double>("resLocalYRangeStation4")), resPhiRange(pset.getUntrackedParameter<double>("resPhiRange")), resThetaRange(pset.getUntrackedParameter<double>("resThetaRange")), nbins(pset.getUntrackedParameter<unsigned int>("nbins")), min1DTrackRecHitSize(pset.getUntrackedParameter<unsigned int>("min1DTrackRecHitSize")), min4DTrackSegmentSize(pset.getUntrackedParameter<unsigned int>("min4DTrackSegmentSize")), simTrackToken_(consumes<edm::SimTrackContainer>(edm::InputTag("g4SimHits"))), staTrackToken_(consumes<reco::TrackCollection>(theSTAMuonTag)), glbTrackToken_(consumes<reco::TrackCollection>(theGLBMuonTag)), allDTSegmentToken_(consumes<DTRecSegment4DCollection>(theRecHits4DTagDT)), allCSCSegmentToken_(consumes<CSCSegmentCollection>(theRecHits4DTagCSC)), hGBNmuons(nullptr), hSANmuons(nullptr), hSimNmuons(nullptr), hGBNmuons_Barrel(nullptr), hSANmuons_Barrel(nullptr), hSimNmuons_Barrel(nullptr), hGBNmuons_Endcap(nullptr), hSANmuons_Endcap(nullptr), hSimNmuons_Endcap(nullptr), hGBNhits(nullptr), hGBNhits_Barrel(nullptr), hGBNhits_Endcap(nullptr), hSANhits(nullptr), hSANhits_Barrel(nullptr), hSANhits_Endcap(nullptr), hGBChi2(nullptr), hSAChi2(nullptr), hGBChi2_Barrel(nullptr), hSAChi2_Barrel(nullptr), hGBChi2_Endcap(nullptr), hSAChi2_Endcap(nullptr), hGBInvM(nullptr), hSAInvM(nullptr), hSimInvM(nullptr), hGBInvM_Barrel(nullptr), hSAInvM_Barrel(nullptr), hSimInvM_Barrel(nullptr), hGBInvM_Endcap(nullptr), hSAInvM_Endcap(nullptr), hSimInvM_Endcap(nullptr), hGBInvM_Overlap(nullptr), hSAInvM_Overlap(nullptr), hSimInvM_Overlap(nullptr), hSAPTRec(nullptr), hGBPTRec(nullptr), hSimPT(nullptr), hSAPTRec_Barrel(nullptr), hGBPTRec_Barrel(nullptr), hSimPT_Barrel(nullptr), hSAPTRec_Endcap(nullptr), hGBPTRec_Endcap(nullptr), hSimPT_Endcap(nullptr), hGBPTvsEta(nullptr), hGBPTvsPhi(nullptr), hSAPTvsEta(nullptr), hSAPTvsPhi(nullptr), hSimPTvsEta(nullptr), hSimPTvsPhi(nullptr), hSimPhivsEta(nullptr), hSAPhivsEta(nullptr), hGBPhivsEta(nullptr), hSAPTres(nullptr), hSAinvPTres(nullptr), hGBPTres(nullptr), hGBinvPTres(nullptr), hSAPTres_Barrel(nullptr), hSAPTres_Endcap(nullptr), hGBPTres_Barrel(nullptr), hGBPTres_Endcap(nullptr), hSAPTDiff(nullptr), hGBPTDiff(nullptr), hSAPTDiffvsEta(nullptr), hSAPTDiffvsPhi(nullptr), hGBPTDiffvsEta(nullptr), hGBPTDiffvsPhi(nullptr), hGBinvPTvsEta(nullptr), hGBinvPTvsPhi(nullptr), hSAinvPTvsEta(nullptr), hSAinvPTvsPhi(nullptr), hSAinvPTvsNhits(nullptr), hGBinvPTvsNhits(nullptr), hResidualLocalXDT(nullptr), hResidualLocalPhiDT(nullptr), hResidualLocalThetaDT(nullptr), hResidualLocalYDT(nullptr), hResidualLocalXCSC(nullptr), hResidualLocalPhiCSC(nullptr), hResidualLocalThetaCSC(nullptr), hResidualLocalYCSC(nullptr), hResidualLocalXDT_W(5), hResidualLocalPhiDT_W(5), hResidualLocalThetaDT_W(5), hResidualLocalYDT_W(5), hResidualLocalXCSC_ME(18), hResidualLocalPhiCSC_ME(18), hResidualLocalThetaCSC_ME(18), hResidualLocalYCSC_ME(18), hResidualLocalXDT_MB(20), hResidualLocalPhiDT_MB(20), hResidualLocalThetaDT_MB(20), hResidualLocalYDT_MB(20), hResidualGlobalRPhiDT(nullptr), hResidualGlobalPhiDT(nullptr), hResidualGlobalThetaDT(nullptr), hResidualGlobalZDT(nullptr), hResidualGlobalRPhiCSC(nullptr), hResidualGlobalPhiCSC(nullptr), hResidualGlobalThetaCSC(nullptr), hResidualGlobalRCSC(nullptr), hResidualGlobalRPhiDT_W(5), hResidualGlobalPhiDT_W(5), hResidualGlobalThetaDT_W(5), hResidualGlobalZDT_W(5), hResidualGlobalRPhiCSC_ME(18), hResidualGlobalPhiCSC_ME(18), hResidualGlobalThetaCSC_ME(18), hResidualGlobalRCSC_ME(18), hResidualGlobalRPhiDT_MB(20), hResidualGlobalPhiDT_MB(20), hResidualGlobalThetaDT_MB(20), hResidualGlobalZDT_MB(20), hprofLocalPositionCSC(nullptr), hprofLocalAngleCSC(nullptr), hprofLocalPositionRmsCSC(nullptr), hprofLocalAngleRmsCSC(nullptr), hprofGlobalPositionCSC(nullptr), hprofGlobalAngleCSC(nullptr), hprofGlobalPositionRmsCSC(nullptr), hprofGlobalAngleRmsCSC(nullptr), hprofLocalPositionDT(nullptr), hprofLocalAngleDT(nullptr), hprofLocalPositionRmsDT(nullptr), hprofLocalAngleRmsDT(nullptr), hprofGlobalPositionDT(nullptr), hprofGlobalAngleDT(nullptr), hprofGlobalPositionRmsDT(nullptr), hprofGlobalAngleRmsDT(nullptr), hprofLocalXDT(nullptr), hprofLocalPhiDT(nullptr), hprofLocalThetaDT(nullptr), hprofLocalYDT(nullptr), hprofLocalXCSC(nullptr), hprofLocalPhiCSC(nullptr), hprofLocalThetaCSC(nullptr), hprofLocalYCSC(nullptr), hprofGlobalRPhiDT(nullptr), hprofGlobalPhiDT(nullptr), hprofGlobalThetaDT(nullptr), hprofGlobalZDT(nullptr), hprofGlobalRPhiCSC(nullptr), hprofGlobalPhiCSC(nullptr), hprofGlobalThetaCSC(nullptr), hprofGlobalRCSC(nullptr) { usesResource(TFileService::kSharedResource); if (theDataType != "RealData" && theDataType != "SimData") edm::LogError("MuonAlignmentAnalyzer") << "Error in Data Type!!" << std::endl; numberOfSimTracks = 0; numberOfSARecTracks = 0; numberOfGBRecTracks = 0; numberOfHits = 0; } void MuonAlignmentAnalyzer::fillDescriptions(edm::ConfigurationDescriptions &descriptions) { edm::ParameterSetDescription desc; desc.add<edm::InputTag>("StandAloneTrackCollectionTag", edm::InputTag("globalMuons")); desc.add<edm::InputTag>("GlobalMuonTrackCollectionTag", edm::InputTag("standAloneMuons", "UpdatedAtVtx")); desc.add<edm::InputTag>("RecHits4DDTCollectionTag", edm::InputTag("dt4DSegments")); desc.add<edm::InputTag>("RecHits4DCSCCollectionTag", edm::InputTag("cscSegments")); desc.addUntracked<std::string>("DataType", "RealData"); desc.addUntracked<double>("ptRangeMin", 0.0); desc.addUntracked<double>("ptRangeMax", 300.0); desc.addUntracked<double>("invMassRangeMin", 0.0); desc.addUntracked<double>("invMassRangeMax", 200.0); desc.addUntracked<bool>("doSAplots", true); desc.addUntracked<bool>("doGBplots", true); desc.addUntracked<bool>("doResplots", true); desc.addUntracked<double>("resLocalXRangeStation1", 0.1); desc.addUntracked<double>("resLocalXRangeStation2", 0.3); desc.addUntracked<double>("resLocalXRangeStation3", 3.0); desc.addUntracked<double>("resLocalXRangeStation4", 3.0); desc.addUntracked<double>("resLocalYRangeStation1", 0.7); desc.addUntracked<double>("resLocalYRangeStation2", 0.7); desc.addUntracked<double>("resLocalYRangeStation3", 5.0); desc.addUntracked<double>("resLocalYRangeStation4", 5.0); desc.addUntracked<double>("resThetaRange", 0.1); desc.addUntracked<double>("resPhiRange", 0.1); desc.addUntracked<int>("nbins", 500); desc.addUntracked<int>("min1DTrackRecHitSize", 1); desc.addUntracked<int>("min4DTrackSegmentSize", 1); descriptions.add("muonAlignmentAnalyzer", desc); } void MuonAlignmentAnalyzer::beginJob() { // eventSetup.get<IdealMagneticFieldRecord>().get(theMGField); //Create the propagator // if(doResplots) thePropagator = new SteppingHelixPropagator(&*theMGField, alongMomentum); int nBinsPt = (int)fabs(ptRangeMax - ptRangeMin); int nBinsMass = (int)fabs(invMassRangeMax - invMassRangeMin); // Define and book histograms for SA and GB muon quantities/objects if (doGBplots) { hGBNmuons = fs->make<TH1F>("GBNmuons", "Nmuons", 10, 0, 10); hGBNmuons_Barrel = fs->make<TH1F>("GBNmuons_Barrel", "Nmuons", 10, 0, 10); hGBNmuons_Endcap = fs->make<TH1F>("GBNmuons_Endcap", "Nmuons", 10, 0, 10); hGBNhits = fs->make<TH1F>("GBNhits", "Nhits", 100, 0, 100); hGBNhits_Barrel = fs->make<TH1F>("GBNhits_Barrel", "Nhits", 100, 0, 100); hGBNhits_Endcap = fs->make<TH1F>("GBNhits_Endcap", "Nhits", 100, 0, 100); hGBPTRec = fs->make<TH1F>("GBpTRec", "p_{T}^{rec}", nBinsPt, ptRangeMin, ptRangeMax); hGBPTRec_Barrel = fs->make<TH1F>("GBpTRec_Barrel", "p_{T}^{rec}", nBinsPt, ptRangeMin, ptRangeMax); hGBPTRec_Endcap = fs->make<TH1F>("GBpTRec_Endcap", "p_{T}^{rec}", nBinsPt, ptRangeMin, ptRangeMax); hGBPTvsEta = fs->make<TH2F>("GBPTvsEta", "p_{T}^{rec} VS #eta", 100, -2.5, 2.5, nBinsPt, ptRangeMin, ptRangeMax); hGBPTvsPhi = fs->make<TH2F>("GBPTvsPhi", "p_{T}^{rec} VS #phi", 100, -3.1416, 3.1416, nBinsPt, ptRangeMin, ptRangeMax); hGBPhivsEta = fs->make<TH2F>("GBPhivsEta", "#phi VS #eta", 100, -2.5, 2.5, 100, -3.1416, 3.1416); if (theDataType == "SimData") { hGBPTDiff = fs->make<TH1F>("GBpTDiff", "p_{T}^{rec} - p_{T}^{gen} ", 250, -120, 120); hGBPTDiffvsEta = fs->make<TH2F>("GBPTDiffvsEta", "p_{T}^{rec} - p_{T}^{gen} VS #eta", 100, -2.5, 2.5, 250, -120, 120); hGBPTDiffvsPhi = fs->make<TH2F>("GBPTDiffvsPhi", "p_{T}^{rec} - p_{T}^{gen} VS #phi", 100, -3.1416, 3.1416, 250, -120, 120); hGBPTres = fs->make<TH1F>("GBpTRes", "pT Resolution", 100, -2, 2); hGBPTres_Barrel = fs->make<TH1F>("GBpTRes_Barrel", "pT Resolution", 100, -2, 2); hGBPTres_Endcap = fs->make<TH1F>("GBpTRes_Endcap", "pT Resolution", 100, -2, 2); hGBinvPTres = fs->make<TH1F>("GBinvPTRes", "#sigma (q/p_{T}) Resolution", 100, -2, 2); hGBinvPTvsEta = fs->make<TH2F>("GBinvPTvsEta", "#sigma (q/p_{T}) VS #eta", 100, -2.5, 2.5, 100, -2, 2); hGBinvPTvsPhi = fs->make<TH2F>("GBinvPTvsPhi", "#sigma (q/p_{T}) VS #phi", 100, -3.1416, 3.1416, 100, -2, 2); hGBinvPTvsNhits = fs->make<TH2F>("GBinvPTvsNhits", "#sigma (q/p_{T}) VS Nhits", 100, 0, 100, 100, -2, 2); } hGBChi2 = fs->make<TH1F>("GBChi2", "Chi2", 200, 0, 200); hGBChi2_Barrel = fs->make<TH1F>("GBChi2_Barrel", "Chi2", 200, 0, 200); hGBChi2_Endcap = fs->make<TH1F>("GBChi2_Endcap ", "Chi2", 200, 0, 200); hGBInvM = fs->make<TH1F>("GBInvM", "M_{inv}^{rec}", nBinsMass, invMassRangeMin, invMassRangeMax); hGBInvM_Barrel = fs->make<TH1F>("GBInvM_Barrel", "M_{inv}^{rec}", nBinsMass, invMassRangeMin, invMassRangeMax); hGBInvM_Endcap = fs->make<TH1F>("GBInvM_Endcap ", "M_{inv}^{rec}", nBinsMass, invMassRangeMin, invMassRangeMax); hGBInvM_Overlap = fs->make<TH1F>("GBInvM_Overlap", "M_{inv}^{rec}", nBinsMass, invMassRangeMin, invMassRangeMax); } if (doSAplots) { hSANmuons = fs->make<TH1F>("SANmuons", "Nmuons", 10, 0, 10); hSANmuons_Barrel = fs->make<TH1F>("SANmuons_Barrel", "Nmuons", 10, 0, 10); hSANmuons_Endcap = fs->make<TH1F>("SANmuons_Endcap", "Nmuons", 10, 0, 10); hSANhits = fs->make<TH1F>("SANhits", "Nhits", 100, 0, 100); hSANhits_Barrel = fs->make<TH1F>("SANhits_Barrel", "Nhits", 100, 0, 100); hSANhits_Endcap = fs->make<TH1F>("SANhits_Endcap", "Nhits", 100, 0, 100); hSAPTRec = fs->make<TH1F>("SApTRec", "p_{T}^{rec}", nBinsPt, ptRangeMin, ptRangeMax); hSAPTRec_Barrel = fs->make<TH1F>("SApTRec_Barrel", "p_{T}^{rec}", nBinsPt, ptRangeMin, ptRangeMax); hSAPTRec_Endcap = fs->make<TH1F>("SApTRec_Endcap", "p_{T}^{rec}", nBinsPt, ptRangeMin, ptRangeMax); hSAPTvsEta = fs->make<TH2F>("SAPTvsEta", "p_{T}^{rec} VS #eta", 100, -2.5, 2.5, nBinsPt, ptRangeMin, ptRangeMax); hSAPTvsPhi = fs->make<TH2F>("SAPTvsPhi", "p_{T}^{rec} VS #phi", 100, -3.1416, 3.1416, nBinsPt, ptRangeMin, ptRangeMax); hSAPhivsEta = fs->make<TH2F>("SAPhivsEta", "#phi VS #eta", 100, -2.5, 2.5, 100, -3.1416, 3.1416); if (theDataType == "SimData") { hSAPTDiff = fs->make<TH1F>("SApTDiff", "p_{T}^{rec} - p_{T}^{gen} ", 250, -120, 120); hSAPTDiffvsEta = fs->make<TH2F>("SAPTDiffvsEta", "p_{T}^{rec} - p_{T}^{gen} VS #eta", 100, -2.5, 2.5, 250, -120, 120); hSAPTDiffvsPhi = fs->make<TH2F>("SAPTDiffvsPhi", "p_{T}^{rec} - p_{T}^{gen} VS #phi", 100, -3.1416, 3.1416, 250, -120, 120); hSAPTres = fs->make<TH1F>("SApTRes", "pT Resolution", 100, -2, 2); hSAPTres_Barrel = fs->make<TH1F>("SApTRes_Barrel", "pT Resolution", 100, -2, 2); hSAPTres_Endcap = fs->make<TH1F>("SApTRes_Endcap", "pT Resolution", 100, -2, 2); hSAinvPTres = fs->make<TH1F>("SAinvPTRes", "1/pT Resolution", 100, -2, 2); hSAinvPTvsEta = fs->make<TH2F>("SAinvPTvsEta", "#sigma (q/p_{T}) VS #eta", 100, -2.5, 2.5, 100, -2, 2); hSAinvPTvsPhi = fs->make<TH2F>("SAinvPTvsPhi", "#sigma (q/p_{T}) VS #phi", 100, -3.1416, 3.1416, 100, -2, 2); hSAinvPTvsNhits = fs->make<TH2F>("SAinvPTvsNhits", "#sigma (q/p_{T}) VS Nhits", 100, 0, 100, 100, -2, 2); } hSAInvM = fs->make<TH1F>("SAInvM", "M_{inv}^{rec}", nBinsMass, invMassRangeMin, invMassRangeMax); hSAInvM_Barrel = fs->make<TH1F>("SAInvM_Barrel", "M_{inv}^{rec}", nBinsMass, invMassRangeMin, invMassRangeMax); hSAInvM_Endcap = fs->make<TH1F>("SAInvM_Endcap", "M_{inv}^{rec}", nBinsMass, invMassRangeMin, invMassRangeMax); hSAInvM_Overlap = fs->make<TH1F>("SAInvM_Overlap", "M_{inv}^{rec}", nBinsMass, invMassRangeMin, invMassRangeMax); hSAChi2 = fs->make<TH1F>("SAChi2", "Chi2", 200, 0, 200); hSAChi2_Barrel = fs->make<TH1F>("SAChi2_Barrel", "Chi2", 200, 0, 200); hSAChi2_Endcap = fs->make<TH1F>("SAChi2_Endcap", "Chi2", 200, 0, 200); } if (theDataType == "SimData") { hSimNmuons = fs->make<TH1F>("SimNmuons", "Nmuons", 10, 0, 10); hSimNmuons_Barrel = fs->make<TH1F>("SimNmuons_Barrel", "Nmuons", 10, 0, 10); hSimNmuons_Endcap = fs->make<TH1F>("SimNmuons_Endcap", "Nmuons", 10, 0, 10); hSimPT = fs->make<TH1F>("SimPT", "p_{T}^{gen} ", nBinsPt, ptRangeMin, ptRangeMax); hSimPT_Barrel = fs->make<TH1F>("SimPT_Barrel", "p_{T}^{gen} ", nBinsPt, ptRangeMin, ptRangeMax); hSimPT_Endcap = fs->make<TH1F>("SimPT_Endcap", "p_{T}^{gen} ", nBinsPt, ptRangeMin, ptRangeMax); hSimPTvsEta = fs->make<TH2F>("SimPTvsEta", "p_{T}^{gen} VS #eta", 100, -2.5, 2.5, nBinsPt, ptRangeMin, ptRangeMax); hSimPTvsPhi = fs->make<TH2F>("SimPTvsPhi", "p_{T}^{gen} VS #phi", 100, -3.1416, 3.1416, nBinsPt, ptRangeMin, ptRangeMax); hSimPhivsEta = fs->make<TH2F>("SimPhivsEta", "#phi VS #eta", 100, -2.5, 2.5, 100, -3.1416, 3.1416); hSimInvM = fs->make<TH1F>("SimInvM", "M_{inv}^{gen} ", nBinsMass, invMassRangeMin, invMassRangeMax); hSimInvM_Barrel = fs->make<TH1F>("SimInvM_Barrel", "M_{inv}^{rec}", nBinsMass, invMassRangeMin, invMassRangeMax); hSimInvM_Endcap = fs->make<TH1F>("SimInvM_Endcap", "M_{inv}^{gen} ", nBinsMass, invMassRangeMin, invMassRangeMax); hSimInvM_Overlap = fs->make<TH1F>("SimInvM_Overlap", "M_{inv}^{gen} ", nBinsMass, invMassRangeMin, invMassRangeMax); } if (doResplots) { // All DT and CSC chambers hResidualLocalXDT = fs->make<TH1F>("hResidualLocalXDT", "hResidualLocalXDT", 200, -10, 10); hResidualLocalPhiDT = fs->make<TH1F>("hResidualLocalPhiDT", "hResidualLocalPhiDT", 100, -1, 1); hResidualLocalThetaDT = fs->make<TH1F>("hResidualLocalThetaDT", "hResidualLocalThetaDT", 100, -1, 1); hResidualLocalYDT = fs->make<TH1F>("hResidualLocalYDT", "hResidualLocalYDT", 200, -10, 10); hResidualLocalXCSC = fs->make<TH1F>("hResidualLocalXCSC", "hResidualLocalXCSC", 200, -10, 10); hResidualLocalPhiCSC = fs->make<TH1F>("hResidualLocalPhiCSC", "hResidualLocalPhiCSC", 100, -1, 1); hResidualLocalThetaCSC = fs->make<TH1F>("hResidualLocalThetaCSC", "hResidualLocalThetaCSC", 100, -1, 1); hResidualLocalYCSC = fs->make<TH1F>("hResidualLocalYCSC", "hResidualLocalYCSC", 200, -10, 10); hResidualGlobalRPhiDT = fs->make<TH1F>("hResidualGlobalRPhiDT", "hResidualGlobalRPhiDT", 200, -10, 10); hResidualGlobalPhiDT = fs->make<TH1F>("hResidualGlobalPhiDT", "hResidualGlobalPhiDT", 100, -1, 1); hResidualGlobalThetaDT = fs->make<TH1F>("hResidualGlobalThetaDT", "hResidualGlobalThetaDT", 100, -1, 1); hResidualGlobalZDT = fs->make<TH1F>("hResidualGlobalZDT", "hResidualGlobalZDT", 200, -10, 10); hResidualGlobalRPhiCSC = fs->make<TH1F>("hResidualGlobalRPhiCSC", "hResidualGlobalRPhiCSC", 200, -10, 10); hResidualGlobalPhiCSC = fs->make<TH1F>("hResidualGlobalPhiCSC", "hResidualGlobalPhiCSC", 100, -1, 1); hResidualGlobalThetaCSC = fs->make<TH1F>("hResidualGlobalThetaCSC", "hResidualGlobalThetaCSC", 100, -1, 1); hResidualGlobalRCSC = fs->make<TH1F>("hResidualGlobalRCSC", "hResidualGlobalRCSC", 200, -10, 10); // DT Wheels hResidualLocalXDT_W[0] = fs->make<TH1F>("hResidualLocalXDT_W-2", "hResidualLocalXDT_W-2", 200, -10, 10); hResidualLocalPhiDT_W[0] = fs->make<TH1F>("hResidualLocalPhiDT_W-2", "hResidualLocalPhiDT_W-2", 200, -1, 1); hResidualLocalThetaDT_W[0] = fs->make<TH1F>("hResidualLocalThetaDT_W-2", "hResidualLocalThetaDT_W-2", 200, -1, 1); hResidualLocalYDT_W[0] = fs->make<TH1F>("hResidualLocalYDT_W-2", "hResidualLocalYDT_W-2", 200, -10, 10); hResidualLocalXDT_W[1] = fs->make<TH1F>("hResidualLocalXDT_W-1", "hResidualLocalXDT_W-1", 200, -10, 10); hResidualLocalPhiDT_W[1] = fs->make<TH1F>("hResidualLocalPhiDT_W-1", "hResidualLocalPhiDT_W-1", 200, -1, 1); hResidualLocalThetaDT_W[1] = fs->make<TH1F>("hResidualLocalThetaDT_W-1", "hResidualLocalThetaDT_W-1", 200, -1, 1); hResidualLocalYDT_W[1] = fs->make<TH1F>("hResidualLocalYDT_W-1", "hResidualLocalYDT_W-1", 200, -10, 10); hResidualLocalXDT_W[2] = fs->make<TH1F>("hResidualLocalXDT_W0", "hResidualLocalXDT_W0", 200, -10, 10); hResidualLocalPhiDT_W[2] = fs->make<TH1F>("hResidualLocalPhiDT_W0", "hResidualLocalPhiDT_W0", 200, -1, 1); hResidualLocalThetaDT_W[2] = fs->make<TH1F>("hResidualLocalThetaDT_W0", "hResidualLocalThetaDT_W0", 200, -1, 1); hResidualLocalYDT_W[2] = fs->make<TH1F>("hResidualLocalYDT_W0", "hResidualLocalYDT_W0", 200, -10, 10); hResidualLocalXDT_W[3] = fs->make<TH1F>("hResidualLocalXDT_W1", "hResidualLocalXDT_W1", 200, -10, 10); hResidualLocalPhiDT_W[3] = fs->make<TH1F>("hResidualLocalPhiDT_W1", "hResidualLocalPhiDT_W1", 200, -1, 1); hResidualLocalThetaDT_W[3] = fs->make<TH1F>("hResidualLocalThetaDT_W1", "hResidualLocalThetaDT_W1", 200, -1, 1); hResidualLocalYDT_W[3] = fs->make<TH1F>("hResidualLocalYDT_W1", "hResidualLocalYDT_W1", 200, -10, 10); hResidualLocalXDT_W[4] = fs->make<TH1F>("hResidualLocalXDT_W2", "hResidualLocalXDT_W2", 200, -10, 10); hResidualLocalPhiDT_W[4] = fs->make<TH1F>("hResidualLocalPhiDT_W2", "hResidualLocalPhiDT_W2", 200, -1, 1); hResidualLocalThetaDT_W[4] = fs->make<TH1F>("hResidualLocalThetaDT_W2", "hResidualLocalThetaDT_W2", 200, -1, 1); hResidualLocalYDT_W[4] = fs->make<TH1F>("hResidualLocalYDT_W2", "hResidualLocalYDT_W2", 200, -10, 10); hResidualGlobalRPhiDT_W[0] = fs->make<TH1F>("hResidualGlobalRPhiDT_W-2", "hResidualGlobalRPhiDT_W-2", 200, -10, 10); hResidualGlobalPhiDT_W[0] = fs->make<TH1F>("hResidualGlobalPhiDT_W-2", "hResidualGlobalPhiDT_W-2", 200, -1, 1); hResidualGlobalThetaDT_W[0] = fs->make<TH1F>("hResidualGlobalThetaDT_W-2", "hResidualGlobalThetaDT_W-2", 200, -1, 1); hResidualGlobalZDT_W[0] = fs->make<TH1F>("hResidualGlobalZDT_W-2", "hResidualGlobalZDT_W-2", 200, -10, 10); hResidualGlobalRPhiDT_W[1] = fs->make<TH1F>("hResidualGlobalRPhiDT_W-1", "hResidualGlobalRPhiDT_W-1", 200, -10, 10); hResidualGlobalPhiDT_W[1] = fs->make<TH1F>("hResidualGlobalPhiDT_W-1", "hResidualGlobalPhiDT_W-1", 200, -1, 1); hResidualGlobalThetaDT_W[1] = fs->make<TH1F>("hResidualGlobalThetaDT_W-1", "hResidualGlobalThetaDT_W-1", 200, -1, 1); hResidualGlobalZDT_W[1] = fs->make<TH1F>("hResidualGlobalZDT_W-1", "hResidualGlobalZDT_W-1", 200, -10, 10); hResidualGlobalRPhiDT_W[2] = fs->make<TH1F>("hResidualGlobalRPhiDT_W0", "hResidualGlobalRPhiDT_W0", 200, -10, 10); hResidualGlobalPhiDT_W[2] = fs->make<TH1F>("hResidualGlobalPhiDT_W0", "hResidualGlobalPhiDT_W0", 200, -1, 1); hResidualGlobalThetaDT_W[2] = fs->make<TH1F>("hResidualGlobalThetaDT_W0", "hResidualGlobalThetaDT_W0", 200, -1, 1); hResidualGlobalZDT_W[2] = fs->make<TH1F>("hResidualGlobalZDT_W0", "hResidualGlobalZDT_W0", 200, -10, 10); hResidualGlobalRPhiDT_W[3] = fs->make<TH1F>("hResidualGlobalRPhiDT_W1", "hResidualGlobalRPhiDT_W1", 200, -10, 10); hResidualGlobalPhiDT_W[3] = fs->make<TH1F>("hResidualGlobalPhiDT_W1", "hResidualGlobalPhiDT_W1", 200, -1, 1); hResidualGlobalThetaDT_W[3] = fs->make<TH1F>("hResidualGlobalThetaDT_W1", "hResidualGlobalThetaDT_W1", 200, -1, 1); hResidualGlobalZDT_W[3] = fs->make<TH1F>("hResidualGlobalZDT_W1", "hResidualGlobalZDT_W1", 200, -10, 10); hResidualGlobalRPhiDT_W[4] = fs->make<TH1F>("hResidualGlobalRPhiDT_W2", "hResidualGlobalRPhiDT_W2", 200, -10, 10); hResidualGlobalPhiDT_W[4] = fs->make<TH1F>("hResidualGlobalPhiDT_W2", "hResidualGlobalPhiDT_W2", 200, -1, 1); hResidualGlobalThetaDT_W[4] = fs->make<TH1F>("hResidualGlobalThetaDT_W2", "hResidualGlobalThetaDT_W2", 200, -1, 1); hResidualGlobalZDT_W[4] = fs->make<TH1F>("hResidualGlobalZDT_W2", "hResidualGlobalZDT_W2", 200, -10, 10); // DT Stations hResidualLocalXDT_MB[0] = fs->make<TH1F>("hResidualLocalXDT_MB-2/1", "hResidualLocalXDT_MB-2/1", 200, -10, 10); hResidualLocalPhiDT_MB[0] = fs->make<TH1F>("hResidualLocalPhiDT_MB-2/1", "hResidualLocalPhiDT_MB-2/1", 200, -1, 1); hResidualLocalThetaDT_MB[0] = fs->make<TH1F>("hResidualLocalThetaDT_MB-2/1", "hResidualLocalThetaDT_MB-2/1", 200, -1, 1); hResidualLocalYDT_MB[0] = fs->make<TH1F>("hResidualLocalYDT_MB-2/1", "hResidualLocalYDT_MB-2/1", 200, -10, 10); hResidualLocalXDT_MB[1] = fs->make<TH1F>("hResidualLocalXDT_MB-2/2", "hResidualLocalXDT_MB-2/2", 200, -10, 10); hResidualLocalPhiDT_MB[1] = fs->make<TH1F>("hResidualLocalPhiDT_MB-2/2", "hResidualLocalPhiDT_MB-2/2", 200, -1, 1); hResidualLocalThetaDT_MB[1] = fs->make<TH1F>("hResidualLocalThetaDT_MB-2/2", "hResidualLocalThetaDT_MB-2/2", 200, -1, 1); hResidualLocalYDT_MB[1] = fs->make<TH1F>("hResidualLocalYDT_MB-2/2", "hResidualLocalYDT_MB-2/2", 200, -10, 10); hResidualLocalXDT_MB[2] = fs->make<TH1F>("hResidualLocalXDT_MB-2/3", "hResidualLocalXDT_MB-2/3", 200, -10, 10); hResidualLocalPhiDT_MB[2] = fs->make<TH1F>("hResidualLocalPhiDT_MB-2/3", "hResidualLocalPhiDT_MB-2/3", 200, -1, 1); hResidualLocalThetaDT_MB[2] = fs->make<TH1F>("hResidualLocalThetaDT_MB-2/3", "hResidualLocalThetaDT_MB-2/3", 200, -1, 1); hResidualLocalYDT_MB[2] = fs->make<TH1F>("hResidualLocalYDT_MB-2/3", "hResidualLocalYDT_MB-2/3", 200, -10, 10); hResidualLocalXDT_MB[3] = fs->make<TH1F>("hResidualLocalXDT_MB-2/4", "hResidualLocalXDT_MB-2/4", 200, -10, 10); hResidualLocalPhiDT_MB[3] = fs->make<TH1F>("hResidualLocalPhiDT_MB-2/4", "hResidualLocalPhiDT_MB-2/4", 200, -1, 1); hResidualLocalThetaDT_MB[3] = fs->make<TH1F>("hResidualLocalThetaDT_MB-2/4", "hResidualLocalThetaDT_MB-2/4", 200, -1, 1); hResidualLocalYDT_MB[3] = fs->make<TH1F>("hResidualLocalYDT_MB-2/4", "hResidualLocalYDT_MB-2/4", 200, -10, 10); hResidualLocalXDT_MB[4] = fs->make<TH1F>("hResidualLocalXDT_MB-1/1", "hResidualLocalXDT_MB-1/1", 200, -10, 10); hResidualLocalPhiDT_MB[4] = fs->make<TH1F>("hResidualLocalPhiDT_MB-1/1", "hResidualLocalPhiDT_MB-1/1", 200, -1, 1); hResidualLocalThetaDT_MB[4] = fs->make<TH1F>("hResidualLocalThetaDT_MB-1/1", "hResidualLocalThetaDT_MB-1/1", 200, -1, 1); hResidualLocalYDT_MB[4] = fs->make<TH1F>("hResidualLocalYDT_MB-1/1", "hResidualLocalYDT_MB-1/1", 200, -10, 10); hResidualLocalXDT_MB[5] = fs->make<TH1F>("hResidualLocalXDT_MB-1/2", "hResidualLocalXDT_MB-1/2", 200, -10, 10); hResidualLocalPhiDT_MB[5] = fs->make<TH1F>("hResidualLocalPhiDT_MB-1/2", "hResidualLocalPhiDT_MB-1/2", 200, -1, 1); hResidualLocalThetaDT_MB[5] = fs->make<TH1F>("hResidualLocalThetaDT_MB-1/2", "hResidualLocalThetaDT_MB-1/2", 200, -1, 1); hResidualLocalYDT_MB[5] = fs->make<TH1F>("hResidualLocalYDT_MB-1/2", "hResidualLocalYDT_MB-1/2", 200, -10, 10); hResidualLocalXDT_MB[6] = fs->make<TH1F>("hResidualLocalXDT_MB-1/3", "hResidualLocalXDT_MB-1/3", 200, -10, 10); hResidualLocalPhiDT_MB[6] = fs->make<TH1F>("hResidualLocalPhiDT_MB-1/3", "hResidualLocalPhiDT_MB-1/3", 200, -1, 1); hResidualLocalThetaDT_MB[6] = fs->make<TH1F>("hResidualLocalThetaDT_MB-1/3", "hResidualLocalThetaDT_MB-1/3", 200, -1, 1); hResidualLocalYDT_MB[6] = fs->make<TH1F>("hResidualLocalYDT_MB-1/3", "hResidualLocalYDT_MB-1/3", 200, -10, 10); hResidualLocalXDT_MB[7] = fs->make<TH1F>("hResidualLocalXDT_MB-1/4", "hResidualLocalXDT_MB-1/4", 200, -10, 10); hResidualLocalPhiDT_MB[7] = fs->make<TH1F>("hResidualLocalPhiDT_MB-1/4", "hResidualLocalPhiDT_MB-1/4", 200, -1, 1); hResidualLocalThetaDT_MB[7] = fs->make<TH1F>("hResidualLocalThetaDT_MB-1/4", "hResidualLocalThetaDT_MB-1/4", 200, -1, 1); hResidualLocalYDT_MB[7] = fs->make<TH1F>("hResidualLocalYDT_MB-1/4", "hResidualLocalYDT_MB-1/4", 200, -10, 10); hResidualLocalXDT_MB[8] = fs->make<TH1F>("hResidualLocalXDT_MB0/1", "hResidualLocalXDT_MB0/1", 200, -10, 10); hResidualLocalPhiDT_MB[8] = fs->make<TH1F>("hResidualLocalPhiDT_MB0/1", "hResidualLocalPhiDT_MB0/1", 200, -1, 1); hResidualLocalThetaDT_MB[8] = fs->make<TH1F>("hResidualLocalThetaDT_MB0/1", "hResidualLocalThetaDT_MB0/1", 200, -1, 1); hResidualLocalYDT_MB[8] = fs->make<TH1F>("hResidualLocalYDT_MB0/1", "hResidualLocalYDT_MB0/1", 200, -10, 10); hResidualLocalXDT_MB[9] = fs->make<TH1F>("hResidualLocalXDT_MB0/2", "hResidualLocalXDT_MB0/2", 200, -10, 10); hResidualLocalPhiDT_MB[9] = fs->make<TH1F>("hResidualLocalPhiDT_MB0/2", "hResidualLocalPhiDT_MB0/2", 200, -1, 1); hResidualLocalThetaDT_MB[9] = fs->make<TH1F>("hResidualLocalThetaDT_MB0/2", "hResidualLocalThetaDT_MB0/2", 200, -1, 1); hResidualLocalYDT_MB[9] = fs->make<TH1F>("hResidualLocalYDT_MB0/2", "hResidualLocalYDT_MB0/2", 200, -10, 10); hResidualLocalXDT_MB[10] = fs->make<TH1F>("hResidualLocalXDT_MB0/3", "hResidualLocalXDT_MB0/3", 200, -10, 10); hResidualLocalThetaDT_MB[10] = fs->make<TH1F>("hResidualLocalThetaDT_MB0/3", "hResidualLocalThetaDT_MB0/3", 200, -1, 1); hResidualLocalPhiDT_MB[10] = fs->make<TH1F>("hResidualLocalPhiDT_MB0/3", "hResidualLocalPhiDT_MB0/3", 200, -1, 1); hResidualLocalYDT_MB[10] = fs->make<TH1F>("hResidualLocalYDT_MB0/3", "hResidualLocalYDT_MB0/3", 200, -10, 10); hResidualLocalXDT_MB[11] = fs->make<TH1F>("hResidualLocalXDT_MB0/4", "hResidualLocalXDT_MB0/4", 200, -10, 10); hResidualLocalPhiDT_MB[11] = fs->make<TH1F>("hResidualLocalPhiDT_MB0/4", "hResidualLocalPhiDT_MB0/4", 200, -1, 1); hResidualLocalThetaDT_MB[11] = fs->make<TH1F>("hResidualLocalThetaDT_MB0/4", "hResidualLocalThetaDT_MB0/4", 200, -1, 1); hResidualLocalYDT_MB[11] = fs->make<TH1F>("hResidualLocalYDT_MB0/4", "hResidualLocalYDT_MB0/4", 200, -10, 10); hResidualLocalXDT_MB[12] = fs->make<TH1F>("hResidualLocalXDT_MB1/1", "hResidualLocalXDT_MB1/1", 200, -10, 10); hResidualLocalPhiDT_MB[12] = fs->make<TH1F>("hResidualLocalPhiDT_MB1/1", "hResidualLocalPhiDT_MB1/1", 200, -1, 1); hResidualLocalThetaDT_MB[12] = fs->make<TH1F>("hResidualLocalThetaDT_MB1/1", "hResidualLocalThetaDT_MB1/1", 200, -1, 1); hResidualLocalYDT_MB[12] = fs->make<TH1F>("hResidualLocalYDT_MB1/1", "hResidualLocalYDT_MB1/1", 200, -10, 10); hResidualLocalXDT_MB[13] = fs->make<TH1F>("hResidualLocalXDT_MB1/2", "hResidualLocalXDT_MB1/2", 200, -10, 10); hResidualLocalPhiDT_MB[13] = fs->make<TH1F>("hResidualLocalPhiDT_MB1/2", "hResidualLocalPhiDT_MB1/2", 200, -1, 1); hResidualLocalThetaDT_MB[13] = fs->make<TH1F>("hResidualLocalThetaDT_MB1/2", "hResidualLocalThetaDT_MB1/2", 200, -1, 1); hResidualLocalYDT_MB[13] = fs->make<TH1F>("hResidualLocalYDT_MB1/2", "hResidualLocalYDT_MB1/2", 200, -10, 10); hResidualLocalXDT_MB[14] = fs->make<TH1F>("hResidualLocalXDT_MB1/3", "hResidualLocalXDT_MB1/3", 200, -10, 10); hResidualLocalPhiDT_MB[14] = fs->make<TH1F>("hResidualLocalPhiDT_MB1/3", "hResidualLocalPhiDT_MB1/3", 200, -1, 1); hResidualLocalThetaDT_MB[14] = fs->make<TH1F>("hResidualLocalThetaDT_MB1/3", "hResidualLocalThetaDT_MB1/3", 200, -1, 1); hResidualLocalYDT_MB[14] = fs->make<TH1F>("hResidualLocalYDT_MB1/3", "hResidualLocalYDT_MB1/3", 200, -10, 10); hResidualLocalXDT_MB[15] = fs->make<TH1F>("hResidualLocalXDT_MB1/4", "hResidualLocalXDT_MB1/4", 200, -10, 10); hResidualLocalPhiDT_MB[15] = fs->make<TH1F>("hResidualLocalPhiDT_MB1/4", "hResidualLocalPhiDT_MB1/4", 200, -1, 1); hResidualLocalThetaDT_MB[15] = fs->make<TH1F>("hResidualLocalThetaDT_MB1/4", "hResidualLocalThetaDT_MB1/4", 200, -1, 1); hResidualLocalYDT_MB[15] = fs->make<TH1F>("hResidualLocalYDT_MB1/4", "hResidualLocalYDT_MB1/4", 200, -10, 10); hResidualLocalXDT_MB[16] = fs->make<TH1F>("hResidualLocalXDT_MB2/1", "hResidualLocalXDT_MB2/1", 200, -10, 10); hResidualLocalPhiDT_MB[16] = fs->make<TH1F>("hResidualLocalPhiDT_MB2/1", "hResidualLocalPhiDT_MB2/1", 200, -1, 1); hResidualLocalThetaDT_MB[16] = fs->make<TH1F>("hResidualLocalThetaDT_MB2/1", "hResidualLocalThetaDT_MB2/1", 200, -1, 1); hResidualLocalYDT_MB[16] = fs->make<TH1F>("hResidualLocalYDT_MB2/1", "hResidualLocalYDT_MB2/1", 200, -10, 10); hResidualLocalXDT_MB[17] = fs->make<TH1F>("hResidualLocalXDT_MB2/2", "hResidualLocalXDT_MB2/2", 200, -10, 10); hResidualLocalPhiDT_MB[17] = fs->make<TH1F>("hResidualLocalPhiDT_MB2/2", "hResidualLocalPhiDT_MB2/2", 200, -1, 1); hResidualLocalThetaDT_MB[17] = fs->make<TH1F>("hResidualLocalThetaDT_MB2/2", "hResidualLocalThetaDT_MB2/2", 200, -1, 1); hResidualLocalYDT_MB[17] = fs->make<TH1F>("hResidualLocalYDT_MB2/2", "hResidualLocalYDT_MB2/2", 200, -10, 10); hResidualLocalXDT_MB[18] = fs->make<TH1F>("hResidualLocalXDT_MB2/3", "hResidualLocalXDT_MB2/3", 200, -10, 10); hResidualLocalPhiDT_MB[18] = fs->make<TH1F>("hResidualLocalPhiDT_MB2/3", "hResidualLocalPhiDT_MB2/3", 200, -1, 1); hResidualLocalThetaDT_MB[18] = fs->make<TH1F>("hResidualLocalThetaDT_MB2/3", "hResidualLocalThetaDT_MB2/3", 200, -1, 1); hResidualLocalYDT_MB[18] = fs->make<TH1F>("hResidualLocalYDT_MB2/3", "hResidualLocalYDT_MB2/3", 200, -10, 10); hResidualLocalXDT_MB[19] = fs->make<TH1F>("hResidualLocalXDT_MB2/4", "hResidualLocalXDT_MB2/4", 200, -10, 10); hResidualLocalPhiDT_MB[19] = fs->make<TH1F>("hResidualLocalPhiDT_MB2/4", "hResidualLocalPhiDT_MB2/4", 200, -1, 1); hResidualLocalThetaDT_MB[19] = fs->make<TH1F>("hResidualLocalThetaDT_MB2/4", "hResidualLocalThetaDT_MB2/4", 200, -1, 1); hResidualLocalYDT_MB[19] = fs->make<TH1F>("hResidualLocalYDT_MB2/4", "hResidualLocalYDT_MB2/4", 200, -10, 10); hResidualGlobalRPhiDT_MB[0] = fs->make<TH1F>("hResidualGlobalRPhiDT_MB-2/1", "hResidualGlobalRPhiDT_MB-2/1", 200, -10, 10); hResidualGlobalPhiDT_MB[0] = fs->make<TH1F>("hResidualGlobalPhiDT_MB-2/1", "hResidualGlobalPhiDT_MB-2/1", 200, -1, 1); hResidualGlobalThetaDT_MB[0] = fs->make<TH1F>("hResidualGlobalThetaDT_MB-2/1", "hResidualGlobalThetaDT_MB-2/1", 200, -1, 1); hResidualGlobalZDT_MB[0] = fs->make<TH1F>("hResidualGlobalZDT_MB-2/1", "hResidualGlobalZDT_MB-2/1", 200, -10, 10); hResidualGlobalRPhiDT_MB[1] = fs->make<TH1F>("hResidualGlobalRPhiDT_MB-2/2", "hResidualGlobalRPhiDT_MB-2/2", 200, -10, 10); hResidualGlobalPhiDT_MB[1] = fs->make<TH1F>("hResidualGlobalPhiDT_MB-2/2", "hResidualGlobalPhiDT_MB-2/2", 200, -1, 1); hResidualGlobalThetaDT_MB[1] = fs->make<TH1F>("hResidualGlobalThetaDT_MB-2/2", "hResidualGlobalThetaDT_MB-2/2", 200, -1, 1); hResidualGlobalZDT_MB[1] = fs->make<TH1F>("hResidualGlobalZDT_MB-2/2", "hResidualGlobalZDT_MB-2/2", 200, -10, 10); hResidualGlobalRPhiDT_MB[2] = fs->make<TH1F>("hResidualGlobalRPhiDT_MB-2/3", "hResidualGlobalRPhiDT_MB-2/3", 200, -10, 10); hResidualGlobalPhiDT_MB[2] = fs->make<TH1F>("hResidualGlobalPhiDT_MB-2/3", "hResidualGlobalPhiDT_MB-2/3", 200, -1, 1); hResidualGlobalThetaDT_MB[2] = fs->make<TH1F>("hResidualGlobalThetaDT_MB-2/3", "hResidualGlobalThetaDT_MB-2/3", 200, -1, 1); hResidualGlobalZDT_MB[2] = fs->make<TH1F>("hResidualGlobalZDT_MB-2/3", "hResidualGlobalZDT_MB-2/3", 200, -10, 10); hResidualGlobalRPhiDT_MB[3] = fs->make<TH1F>("hResidualGlobalRPhiDT_MB-2/4", "hResidualGlobalRPhiDT_MB-2/4", 200, -10, 10); hResidualGlobalPhiDT_MB[3] = fs->make<TH1F>("hResidualGlobalPhiDT_MB-2/4", "hResidualGlobalPhiDT_MB-2/4", 200, -1, 1); hResidualGlobalThetaDT_MB[3] = fs->make<TH1F>("hResidualGlobalThetaDT_MB-2/4", "hResidualGlobalThetaDT_MB-2/4", 200, -1, 1); hResidualGlobalZDT_MB[3] = fs->make<TH1F>("hResidualGlobalZDT_MB-2/4", "hResidualGlobalZDT_MB-2/4", 200, -10, 10); hResidualGlobalRPhiDT_MB[4] = fs->make<TH1F>("hResidualGlobalRPhiDT_MB-1/1", "hResidualGlobalRPhiDT_MB-1/1", 200, -10, 10); hResidualGlobalPhiDT_MB[4] = fs->make<TH1F>("hResidualGlobalPhiDT_MB-1/1", "hResidualGlobalPhiDT_MB-1/1", 200, -1, 1); hResidualGlobalThetaDT_MB[4] = fs->make<TH1F>("hResidualGlobalThetaDT_MB-1/1", "hResidualGlobalThetaDT_MB-1/1", 200, -1, 1); hResidualGlobalZDT_MB[4] = fs->make<TH1F>("hResidualGlobalZDT_MB-1/1", "hResidualGlobalZDT_MB-1/1", 200, -10, 10); hResidualGlobalRPhiDT_MB[5] = fs->make<TH1F>("hResidualGlobalRPhiDT_MB-1/2", "hResidualGlobalRPhiDT_MB-1/2", 200, -10, 10); hResidualGlobalPhiDT_MB[5] = fs->make<TH1F>("hResidualGlobalPhiDT_MB-1/2", "hResidualGlobalPhiDT_MB-1/2", 200, -1, 1); hResidualGlobalThetaDT_MB[5] = fs->make<TH1F>("hResidualGlobalThetaDT_MB-1/2", "hResidualGlobalThetaDT_MB-1/2", 200, -1, 1); hResidualGlobalZDT_MB[5] = fs->make<TH1F>("hResidualGlobalZDT_MB-1/2", "hResidualGlobalZDT_MB-1/2", 200, -10, 10); hResidualGlobalRPhiDT_MB[6] = fs->make<TH1F>("hResidualGlobalRPhiDT_MB-1/3", "hResidualGlobalRPhiDT_MB-1/3", 200, -10, 10); hResidualGlobalPhiDT_MB[6] = fs->make<TH1F>("hResidualGlobalPhiDT_MB-1/3", "hResidualGlobalPhiDT_MB-1/3", 200, -1, 1); hResidualGlobalThetaDT_MB[6] = fs->make<TH1F>("hResidualGlobalThetaDT_MB-1/3", "hResidualGlobalThetaDT_MB-1/3", 200, -1, 1); hResidualGlobalZDT_MB[6] = fs->make<TH1F>("hResidualGlobalZDT_MB-1/3", "hResidualGlobalZDT_MB-1/3", 200, -10, 10); hResidualGlobalRPhiDT_MB[7] = fs->make<TH1F>("hResidualGlobalRPhiDT_MB-1/4", "hResidualGlobalRPhiDT_MB-1/4", 200, -10, 10); hResidualGlobalPhiDT_MB[7] = fs->make<TH1F>("hResidualGlobalPhiDT_MB-1/4", "hResidualGlobalPhiDT_MB-1/4", 200, -1, 1); hResidualGlobalThetaDT_MB[7] = fs->make<TH1F>("hResidualGlobalThetaDT_MB-1/4", "hResidualGlobalThetaDT_MB-1/4", 200, -1, 1); hResidualGlobalZDT_MB[7] = fs->make<TH1F>("hResidualGlobalZDT_MB-1/4", "hResidualGlobalZDT_MB-1/4", 200, -10, 10); hResidualGlobalRPhiDT_MB[8] = fs->make<TH1F>("hResidualGlobalRPhiDT_MB0/1", "hResidualGlobalRPhiDT_MB0/1", 200, -10, 10); hResidualGlobalPhiDT_MB[8] = fs->make<TH1F>("hResidualGlobalPhiDT_MB0/1", "hResidualGlobalPhiDT_MB0/1", 200, -1, 1); hResidualGlobalThetaDT_MB[8] = fs->make<TH1F>("hResidualGlobalThetaDT_MB0/1", "hResidualGlobalThetaDT_MB0/1", 200, -1, 1); hResidualGlobalZDT_MB[8] = fs->make<TH1F>("hResidualGlobalZDT_MB0/1", "hResidualGlobalZDT_MB0/1", 200, -10, 10); hResidualGlobalRPhiDT_MB[9] = fs->make<TH1F>("hResidualGlobalRPhiDT_MB0/2", "hResidualGlobalRPhiDT_MB0/2", 200, -10, 10); hResidualGlobalPhiDT_MB[9] = fs->make<TH1F>("hResidualGlobalPhiDT_MB0/2", "hResidualGlobalPhiDT_MB0/2", 200, -1, 1); hResidualGlobalThetaDT_MB[9] = fs->make<TH1F>("hResidualGlobalThetaDT_MB0/2", "hResidualGlobalThetaDT_MB0/2", 200, -1, 1); hResidualGlobalZDT_MB[9] = fs->make<TH1F>("hResidualGlobalZDT_MB0/2", "hResidualGlobalZDT_MB0/2", 200, -10, 10); hResidualGlobalRPhiDT_MB[10] = fs->make<TH1F>("hResidualGlobalRPhiDT_MB0/3", "hResidualGlobalRPhiDT_MB0/3", 200, -10, 10); hResidualGlobalThetaDT_MB[10] = fs->make<TH1F>("hResidualGlobalThetaDT_MB0/3", "hResidualGlobalThetaDT_MB0/3", 200, -1, 1); hResidualGlobalPhiDT_MB[10] = fs->make<TH1F>("hResidualGlobalPhiDT_MB0/3", "hResidualGlobalPhiDT_MB0/3", 200, -1, 1); hResidualGlobalZDT_MB[10] = fs->make<TH1F>("hResidualGlobalZDT_MB0/3", "hResidualGlobalZDT_MB0/3", 200, -10, 10); hResidualGlobalRPhiDT_MB[11] = fs->make<TH1F>("hResidualGlobalRPhiDT_MB0/4", "hResidualGlobalRPhiDT_MB0/4", 200, -10, 10); hResidualGlobalPhiDT_MB[11] = fs->make<TH1F>("hResidualGlobalPhiDT_MB0/4", "hResidualGlobalPhiDT_MB0/4", 200, -1, 1); hResidualGlobalThetaDT_MB[11] = fs->make<TH1F>("hResidualGlobalThetaDT_MB0/4", "hResidualGlobalThetaDT_MB0/4", 200, -1, 1); hResidualGlobalZDT_MB[11] = fs->make<TH1F>("hResidualGlobalZDT_MB0/4", "hResidualGlobalZDT_MB0/4", 200, -10, 10); hResidualGlobalRPhiDT_MB[12] = fs->make<TH1F>("hResidualGlobalRPhiDT_MB1/1", "hResidualGlobalRPhiDT_MB1/1", 200, -10, 10); hResidualGlobalPhiDT_MB[12] = fs->make<TH1F>("hResidualGlobalPhiDT_MB1/1", "hResidualGlobalPhiDT_MB1/1", 200, -1, 1); hResidualGlobalThetaDT_MB[12] = fs->make<TH1F>("hResidualGlobalThetaDT_MB1/1", "hResidualGlobalThetaDT_MB1/1", 200, -1, 1); hResidualGlobalZDT_MB[12] = fs->make<TH1F>("hResidualGlobalZDT_MB1/1", "hResidualGlobalZDT_MB1/1", 200, -10, 10); hResidualGlobalRPhiDT_MB[13] = fs->make<TH1F>("hResidualGlobalRPhiDT_MB1/2", "hResidualGlobalRPhiDT_MB1/2", 200, -10, 10); hResidualGlobalPhiDT_MB[13] = fs->make<TH1F>("hResidualGlobalPhiDT_MB1/2", "hResidualGlobalPhiDT_MB1/2", 200, -1, 1); hResidualGlobalThetaDT_MB[13] = fs->make<TH1F>("hResidualGlobalThetaDT_MB1/2", "hResidualGlobalThetaDT_MB1/2", 200, -1, 1); hResidualGlobalZDT_MB[13] = fs->make<TH1F>("hResidualGlobalZDT_MB1/2", "hResidualGlobalZDT_MB1/2", 200, -10, 10); hResidualGlobalRPhiDT_MB[14] = fs->make<TH1F>("hResidualGlobalRPhiDT_MB1/3", "hResidualGlobalRPhiDT_MB1/3", 200, -10, 10); hResidualGlobalPhiDT_MB[14] = fs->make<TH1F>("hResidualGlobalPhiDT_MB1/3", "hResidualGlobalPhiDT_MB1/3", 200, -1, 1); hResidualGlobalThetaDT_MB[14] = fs->make<TH1F>("hResidualGlobalThetaDT_MB1/3", "hResidualGlobalThetaDT_MB1/3", 200, -1, 1); hResidualGlobalZDT_MB[14] = fs->make<TH1F>("hResidualGlobalZDT_MB1/3", "hResidualGlobalZDT_MB1/3", 200, -10, 10); hResidualGlobalRPhiDT_MB[15] = fs->make<TH1F>("hResidualGlobalRPhiDT_MB1/4", "hResidualGlobalRPhiDT_MB1/4", 200, -10, 10); hResidualGlobalPhiDT_MB[15] = fs->make<TH1F>("hResidualGlobalPhiDT_MB1/4", "hResidualGlobalPhiDT_MB1/4", 200, -1, 1); hResidualGlobalThetaDT_MB[15] = fs->make<TH1F>("hResidualGlobalThetaDT_MB1/4", "hResidualGlobalThetaDT_MB1/4", 200, -1, 1); hResidualGlobalZDT_MB[15] = fs->make<TH1F>("hResidualGlobalZDT_MB1/4", "hResidualGlobalZDT_MB1/4", 200, -10, 10); hResidualGlobalRPhiDT_MB[16] = fs->make<TH1F>("hResidualGlobalRPhiDT_MB2/1", "hResidualGlobalRPhiDT_MB2/1", 200, -10, 10); hResidualGlobalPhiDT_MB[16] = fs->make<TH1F>("hResidualGlobalPhiDT_MB2/1", "hResidualGlobalPhiDT_MB2/1", 200, -1, 1); hResidualGlobalThetaDT_MB[16] = fs->make<TH1F>("hResidualGlobalThetaDT_MB2/1", "hResidualGlobalThetaDT_MB2/1", 200, -1, 1); hResidualGlobalZDT_MB[16] = fs->make<TH1F>("hResidualGlobalZDT_MB2/1", "hResidualGlobalZDT_MB2/1", 200, -10, 10); hResidualGlobalRPhiDT_MB[17] = fs->make<TH1F>("hResidualGlobalRPhiDT_MB2/2", "hResidualGlobalRPhiDT_MB2/2", 200, -10, 10); hResidualGlobalPhiDT_MB[17] = fs->make<TH1F>("hResidualGlobalPhiDT_MB2/2", "hResidualGlobalPhiDT_MB2/2", 200, -1, 1); hResidualGlobalThetaDT_MB[17] = fs->make<TH1F>("hResidualGlobalThetaDT_MB2/2", "hResidualGlobalThetaDT_MB2/2", 200, -1, 1); hResidualGlobalZDT_MB[17] = fs->make<TH1F>("hResidualGlobalZDT_MB2/2", "hResidualGlobalZDT_MB2/2", 200, -10, 10); hResidualGlobalRPhiDT_MB[18] = fs->make<TH1F>("hResidualGlobalRPhiDT_MB2/3", "hResidualGlobalRPhiDT_MB2/3", 200, -10, 10); hResidualGlobalPhiDT_MB[18] = fs->make<TH1F>("hResidualGlobalPhiDT_MB2/3", "hResidualGlobalPhiDT_MB2/3", 200, -1, 1); hResidualGlobalThetaDT_MB[18] = fs->make<TH1F>("hResidualGlobalThetaDT_MB2/3", "hResidualGlobalThetaDT_MB2/3", 200, -1, 1); hResidualGlobalZDT_MB[18] = fs->make<TH1F>("hResidualGlobalZDT_MB2/3", "hResidualGlobalZDT_MB2/3", 200, -10, 10); hResidualGlobalRPhiDT_MB[19] = fs->make<TH1F>("hResidualGlobalRPhiDT_MB2/4", "hResidualGlobalRPhiDT_MB2/4", 200, -10, 10); hResidualGlobalPhiDT_MB[19] = fs->make<TH1F>("hResidualGlobalPhiDT_MB2/4", "hResidualGlobalPhiDT_MB2/4", 200, -1, 1); hResidualGlobalThetaDT_MB[19] = fs->make<TH1F>("hResidualGlobalThetaDT_MB2/4", "hResidualGlobalThetaDT_MB2/4", 200, -1, 1); hResidualGlobalZDT_MB[19] = fs->make<TH1F>("hResidualGlobalZDT_MB2/4", "hResidualGlobalZDT_MB2/4", 200, -10, 10); // CSC Stations hResidualLocalXCSC_ME[0] = fs->make<TH1F>("hResidualLocalXCSC_ME-4/1", "hResidualLocalXCSC_ME-4/1", 200, -10, 10); hResidualLocalPhiCSC_ME[0] = fs->make<TH1F>("hResidualLocalPhiCSC_ME-4/1", "hResidualLocalPhiCSC_ME-4/1", 200, -1, 1); hResidualLocalThetaCSC_ME[0] = fs->make<TH1F>("hResidualLocalThetaCSC_ME-4/1", "hResidualLocalThetaCSC_ME-4/1", 200, -1, 1); hResidualLocalYCSC_ME[0] = fs->make<TH1F>("hResidualLocalYCSC_ME-4/1", "hResidualLocalYCSC_ME-4/1", 200, -10, 10); hResidualLocalXCSC_ME[1] = fs->make<TH1F>("hResidualLocalXCSC_ME-4/2", "hResidualLocalXCSC_ME-4/2", 200, -10, 10); hResidualLocalPhiCSC_ME[1] = fs->make<TH1F>("hResidualLocalPhiCSC_ME-4/2", "hResidualLocalPhiCSC_ME-4/2", 200, -1, 1); hResidualLocalThetaCSC_ME[1] = fs->make<TH1F>("hResidualLocalThetaCSC_ME-4/2", "hResidualLocalThetaCSC_ME-4/2", 200, -1, 1); hResidualLocalYCSC_ME[1] = fs->make<TH1F>("hResidualLocalYCSC_ME-4/2", "hResidualLocalYCSC_ME-4/2", 200, -10, 10); hResidualLocalXCSC_ME[2] = fs->make<TH1F>("hResidualLocalXCSC_ME-3/1", "hResidualLocalXCSC_ME-3/1", 200, -10, 10); hResidualLocalPhiCSC_ME[2] = fs->make<TH1F>("hResidualLocalPhiCSC_ME-3/1", "hResidualLocalPhiCSC_ME-3/1", 200, -1, 1); hResidualLocalThetaCSC_ME[2] = fs->make<TH1F>("hResidualLocalThetaCSC_ME-3/1", "hResidualLocalThetaCSC_ME-3/1", 200, -1, 1); hResidualLocalYCSC_ME[2] = fs->make<TH1F>("hResidualLocalYCSC_ME-3/1", "hResidualLocalYCSC_ME-3/1", 200, -10, 10); hResidualLocalXCSC_ME[3] = fs->make<TH1F>("hResidualLocalXCSC_ME-3/2", "hResidualLocalXCSC_ME-3/2", 200, -10, 10); hResidualLocalPhiCSC_ME[3] = fs->make<TH1F>("hResidualLocalPhiCSC_ME-3/2", "hResidualLocalPhiCSC_ME-3/2", 200, -1, 1); hResidualLocalThetaCSC_ME[3] = fs->make<TH1F>("hResidualLocalThetaCSC_ME-3/2", "hResidualLocalThetaCSC_ME-3/2", 200, -1, 1); hResidualLocalYCSC_ME[3] = fs->make<TH1F>("hResidualLocalYCSC_ME-3/2", "hResidualLocalYCSC_ME-3/2", 200, -10, 10); hResidualLocalXCSC_ME[4] = fs->make<TH1F>("hResidualLocalXCSC_ME-2/1", "hResidualLocalXCSC_ME-2/1", 200, -10, 10); hResidualLocalPhiCSC_ME[4] = fs->make<TH1F>("hResidualLocalPhiCSC_ME-2/1", "hResidualLocalPhiCSC_ME-2/1", 200, -1, 1); hResidualLocalThetaCSC_ME[4] = fs->make<TH1F>("hResidualLocalThetaCSC_ME-2/1", "hResidualLocalThetaCSC_ME-2/1", 200, -1, 1); hResidualLocalYCSC_ME[4] = fs->make<TH1F>("hResidualLocalYCSC_ME-2/1", "hResidualLocalYCSC_ME-2/1", 200, -10, 10); hResidualLocalXCSC_ME[5] = fs->make<TH1F>("hResidualLocalXCSC_ME-2/2", "hResidualLocalXCSC_ME-2/2", 200, -10, 10); hResidualLocalPhiCSC_ME[5] = fs->make<TH1F>("hResidualLocalPhiCSC_ME-2/2", "hResidualLocalPhiCSC_ME-2/2", 200, -1, 1); hResidualLocalThetaCSC_ME[5] = fs->make<TH1F>("hResidualLocalThetaCSC_ME-2/2", "hResidualLocalThetaCSC_ME-2/2", 200, -1, 1); hResidualLocalYCSC_ME[5] = fs->make<TH1F>("hResidualLocalYCSC_ME-2/2", "hResidualLocalYCSC_ME-2/2", 200, -10, 10); hResidualLocalXCSC_ME[6] = fs->make<TH1F>("hResidualLocalXCSC_ME-1/1", "hResidualLocalXCSC_ME-1/1", 200, -10, 10); hResidualLocalPhiCSC_ME[6] = fs->make<TH1F>("hResidualLocalPhiCSC_ME-1/1", "hResidualLocalPhiCSC_ME-1/1", 200, -1, 1); hResidualLocalThetaCSC_ME[6] = fs->make<TH1F>("hResidualLocalThetaCSC_ME-1/1", "hResidualLocalThetaCSC_ME-1/1", 200, -1, 1); hResidualLocalYCSC_ME[6] = fs->make<TH1F>("hResidualLocalYCSC_ME-1/1", "hResidualLocalYCSC_ME-1/1", 200, -10, 10); hResidualLocalXCSC_ME[7] = fs->make<TH1F>("hResidualLocalXCSC_ME-1/2", "hResidualLocalXCSC_ME-1/2", 200, -10, 10); hResidualLocalPhiCSC_ME[7] = fs->make<TH1F>("hResidualLocalPhiCSC_ME-1/2", "hResidualLocalPhiCSC_ME-1/2", 200, -1, 1); hResidualLocalThetaCSC_ME[7] = fs->make<TH1F>("hResidualLocalThetaCSC_ME-1/2", "hResidualLocalThetaCSC_ME-1/2", 200, -1, 1); hResidualLocalYCSC_ME[7] = fs->make<TH1F>("hResidualLocalYCSC_ME-1/2", "hResidualLocalYCSC_ME-1/2", 200, -10, 10); hResidualLocalXCSC_ME[8] = fs->make<TH1F>("hResidualLocalXCSC_ME-1/3", "hResidualLocalXCSC_ME-1/3", 200, -10, 10); hResidualLocalPhiCSC_ME[8] = fs->make<TH1F>("hResidualLocalPhiCSC_ME-1/3", "hResidualLocalPhiCSC_ME-1/3", 200, -1, 1); hResidualLocalThetaCSC_ME[8] = fs->make<TH1F>("hResidualLocalThetaCSC_ME-1/3", "hResidualLocalThetaCSC_ME-1/3", 200, -1, 1); hResidualLocalYCSC_ME[8] = fs->make<TH1F>("hResidualLocalYCSC_ME-1/3", "hResidualLocalYCSC_ME-1/3", 200, -10, 10); hResidualLocalXCSC_ME[9] = fs->make<TH1F>("hResidualLocalXCSC_ME1/1", "hResidualLocalXCSC_ME1/1", 200, -10, 10); hResidualLocalPhiCSC_ME[9] = fs->make<TH1F>("hResidualLocalPhiCSC_ME1/1", "hResidualLocalPhiCSC_ME1/1", 100, -1, 1); hResidualLocalThetaCSC_ME[9] = fs->make<TH1F>("hResidualLocalThetaCSC_ME1/1", "hResidualLocalThetaCSC_ME1/1", 200, -1, 1); hResidualLocalYCSC_ME[9] = fs->make<TH1F>("hResidualLocalYCSC_ME1/1", "hResidualLocalYCSC_ME1/1", 200, -10, 10); hResidualLocalXCSC_ME[10] = fs->make<TH1F>("hResidualLocalXCSC_ME1/2", "hResidualLocalXCSC_ME1/2", 200, -10, 10); hResidualLocalPhiCSC_ME[10] = fs->make<TH1F>("hResidualLocalPhiCSC_ME1/2", "hResidualLocalPhiCSC_ME1/2", 200, -1, 1); hResidualLocalThetaCSC_ME[10] = fs->make<TH1F>("hResidualLocalThetaCSC_ME1/2", "hResidualLocalThetaCSC_ME1/2", 200, -1, 1); hResidualLocalYCSC_ME[10] = fs->make<TH1F>("hResidualLocalYCSC_ME1/2", "hResidualLocalYCSC_ME1/2", 200, -10, 10); hResidualLocalXCSC_ME[11] = fs->make<TH1F>("hResidualLocalXCSC_ME1/3", "hResidualLocalXCSC_ME1/3", 200, -10, 10); hResidualLocalPhiCSC_ME[11] = fs->make<TH1F>("hResidualLocalPhiCSC_ME1/3", "hResidualLocalPhiCSC_ME1/3", 200, -1, 1); hResidualLocalThetaCSC_ME[11] = fs->make<TH1F>("hResidualLocalThetaCSC_ME1/3", "hResidualLocalThetaCSC_ME1/3", 200, -1, 1); hResidualLocalYCSC_ME[11] = fs->make<TH1F>("hResidualLocalYCSC_ME1/3", "hResidualLocalYCSC_ME1/3", 200, -10, 10); hResidualLocalXCSC_ME[12] = fs->make<TH1F>("hResidualLocalXCSC_ME2/1", "hResidualLocalXCSC_ME2/1", 200, -10, 10); hResidualLocalPhiCSC_ME[12] = fs->make<TH1F>("hResidualLocalPhiCSC_ME2/1", "hResidualLocalPhiCSC_ME2/1", 200, -1, 1); hResidualLocalThetaCSC_ME[12] = fs->make<TH1F>("hResidualLocalThetaCSC_ME2/1", "hResidualLocalThetaCSC_ME2/1", 200, -1, 1); hResidualLocalYCSC_ME[12] = fs->make<TH1F>("hResidualLocalYCSC_ME2/1", "hResidualLocalYCSC_ME2/1", 200, -10, 10); hResidualLocalXCSC_ME[13] = fs->make<TH1F>("hResidualLocalXCSC_ME2/2", "hResidualLocalXCSC_ME2/2", 200, -10, 10); hResidualLocalPhiCSC_ME[13] = fs->make<TH1F>("hResidualLocalPhiCSC_ME2/2", "hResidualLocalPhiCSC_ME2/2", 200, -1, 1); hResidualLocalThetaCSC_ME[13] = fs->make<TH1F>("hResidualLocalThetaCSC_ME2/2", "hResidualLocalThetaCSC_ME2/2", 200, -1, 1); hResidualLocalYCSC_ME[13] = fs->make<TH1F>("hResidualLocalYCSC_ME2/2", "hResidualLocalYCSC_ME2/2", 200, -10, 10); hResidualLocalXCSC_ME[14] = fs->make<TH1F>("hResidualLocalXCSC_ME3/1", "hResidualLocalXCSC_ME3/1", 200, -10, 10); hResidualLocalPhiCSC_ME[14] = fs->make<TH1F>("hResidualLocalPhiCSC_ME3/1", "hResidualLocalPhiCSC_ME3/1", 200, -1, 1); hResidualLocalThetaCSC_ME[14] = fs->make<TH1F>("hResidualLocalThetaCSC_ME3/1", "hResidualLocalThetaCSC_ME3/1", 200, -1, 1); hResidualLocalYCSC_ME[14] = fs->make<TH1F>("hResidualLocalYCSC_ME3/1", "hResidualLocalYCSC_ME3/1", 200, -10, 10); hResidualLocalXCSC_ME[15] = fs->make<TH1F>("hResidualLocalXCSC_ME3/2", "hResidualLocalXCSC_ME3/2", 200, -10, 10); hResidualLocalPhiCSC_ME[15] = fs->make<TH1F>("hResidualLocalPhiCSC_ME3/2", "hResidualLocalPhiCSC_ME3/2", 200, -1, 1); hResidualLocalThetaCSC_ME[15] = fs->make<TH1F>("hResidualLocalThetaCSC_ME3/2", "hResidualLocalThetaCSC_ME3/2", 200, -1, 1); hResidualLocalYCSC_ME[15] = fs->make<TH1F>("hResidualLocalYCSC_ME3/2", "hResidualLocalYCSC_ME3/2", 200, -10, 10); hResidualLocalXCSC_ME[16] = fs->make<TH1F>("hResidualLocalXCSC_ME4/1", "hResidualLocalXCSC_ME4/1", 200, -10, 10); hResidualLocalPhiCSC_ME[16] = fs->make<TH1F>("hResidualLocalPhiCSC_ME4/1", "hResidualLocalPhiCSC_ME4/1", 200, -1, 1); hResidualLocalThetaCSC_ME[16] = fs->make<TH1F>("hResidualLocalThetaCSC_ME4/1", "hResidualLocalThetaCSC_ME4/1", 200, -1, 1); hResidualLocalYCSC_ME[16] = fs->make<TH1F>("hResidualLocalYCSC_ME4/1", "hResidualLocalYCSC_ME4/1", 200, -10, 10); hResidualLocalXCSC_ME[17] = fs->make<TH1F>("hResidualLocalXCSC_ME4/2", "hResidualLocalXCSC_ME4/2", 200, -10, 10); hResidualLocalPhiCSC_ME[17] = fs->make<TH1F>("hResidualLocalPhiCSC_ME4/2", "hResidualLocalPhiCSC_ME4/2", 200, -1, 1); hResidualLocalThetaCSC_ME[17] = fs->make<TH1F>("hResidualLocalThetaCSC_ME4/2", "hResidualLocalThetaCSC_ME4/2", 200, -1, 1); hResidualLocalYCSC_ME[17] = fs->make<TH1F>("hResidualLocalYCSC_ME4/2", "hResidualLocalYCSC_ME4/2", 200, -10, 10); hResidualGlobalRPhiCSC_ME[0] = fs->make<TH1F>("hResidualGlobalRPhiCSC_ME-4/1", "hResidualGlobalRPhiCSC_ME-4/1", 200, -10, 10); hResidualGlobalPhiCSC_ME[0] = fs->make<TH1F>("hResidualGlobalPhiCSC_ME-4/1", "hResidualGlobalPhiCSC_ME-4/1", 200, -1, 1); hResidualGlobalThetaCSC_ME[0] = fs->make<TH1F>("hResidualGlobalThetaCSC_ME-4/1", "hResidualGlobalThetaCSC_ME-4/1", 200, -1, 1); hResidualGlobalRCSC_ME[0] = fs->make<TH1F>("hResidualGlobalRCSC_ME-4/1", "hResidualGlobalRCSC_ME-4/1", 200, -10, 10); hResidualGlobalRPhiCSC_ME[1] = fs->make<TH1F>("hResidualGlobalRPhiCSC_ME-4/2", "hResidualGlobalRPhiCSC_ME-4/2", 200, -10, 10); hResidualGlobalPhiCSC_ME[1] = fs->make<TH1F>("hResidualGlobalPhiCSC_ME-4/2", "hResidualGlobalPhiCSC_ME-4/2", 200, -1, 1); hResidualGlobalThetaCSC_ME[1] = fs->make<TH1F>("hResidualGlobalThetaCSC_ME-4/2", "hResidualGlobalThetaCSC_ME-4/2", 200, -1, 1); hResidualGlobalRCSC_ME[1] = fs->make<TH1F>("hResidualGlobalRCSC_ME-4/2", "hResidualGlobalRCSC_ME-4/2", 200, -10, 10); hResidualGlobalRPhiCSC_ME[2] = fs->make<TH1F>("hResidualGlobalRPhiCSC_ME-3/1", "hResidualGlobalRPhiCSC_ME-3/1", 200, -10, 10); hResidualGlobalPhiCSC_ME[2] = fs->make<TH1F>("hResidualGlobalPhiCSC_ME-3/1", "hResidualGlobalPhiCSC_ME-3/1", 200, -1, 1); hResidualGlobalThetaCSC_ME[2] = fs->make<TH1F>("hResidualGlobalThetaCSC_ME-3/1", "hResidualGlobalThetaCSC_ME-3/1", 200, -1, 1); hResidualGlobalRCSC_ME[2] = fs->make<TH1F>("hResidualGlobalRCSC_ME-3/1", "hResidualGlobalRCSC_ME-3/1", 200, -10, 10); hResidualGlobalRPhiCSC_ME[3] = fs->make<TH1F>("hResidualGlobalRPhiCSC_ME-3/2", "hResidualGlobalRPhiCSC_ME-3/2", 200, -10, 10); hResidualGlobalPhiCSC_ME[3] = fs->make<TH1F>("hResidualGlobalPhiCSC_ME-3/2", "hResidualGlobalPhiCSC_ME-3/2", 200, -1, 1); hResidualGlobalThetaCSC_ME[3] = fs->make<TH1F>("hResidualGlobalThetaCSC_ME-3/2", "hResidualGlobalThetaCSC_ME-3/2", 200, -1, 1); hResidualGlobalRCSC_ME[3] = fs->make<TH1F>("hResidualGlobalRCSC_ME-3/2", "hResidualGlobalRCSC_ME-3/2", 200, -10, 10); hResidualGlobalRPhiCSC_ME[4] = fs->make<TH1F>("hResidualGlobalRPhiCSC_ME-2/1", "hResidualGlobalRPhiCSC_ME-2/1", 200, -10, 10); hResidualGlobalPhiCSC_ME[4] = fs->make<TH1F>("hResidualGlobalPhiCSC_ME-2/1", "hResidualGlobalPhiCSC_ME-2/1", 200, -1, 1); hResidualGlobalThetaCSC_ME[4] = fs->make<TH1F>("hResidualGlobalThetaCSC_ME-2/1", "hResidualGlobalThetaCSC_ME-2/1", 200, -1, 1); hResidualGlobalRCSC_ME[4] = fs->make<TH1F>("hResidualGlobalRCSC_ME-2/1", "hResidualGlobalRCSC_ME-2/1", 200, -10, 10); hResidualGlobalRPhiCSC_ME[5] = fs->make<TH1F>("hResidualGlobalRPhiCSC_ME-2/2", "hResidualGlobalRPhiCSC_ME-2/2", 200, -10, 10); hResidualGlobalPhiCSC_ME[5] = fs->make<TH1F>("hResidualGlobalPhiCSC_ME-2/2", "hResidualGlobalPhiCSC_ME-2/2", 200, -1, 1); hResidualGlobalThetaCSC_ME[5] = fs->make<TH1F>("hResidualGlobalThetaCSC_ME-2/2", "hResidualGlobalThetaCSC_ME-2/2", 200, -1, 1); hResidualGlobalRCSC_ME[5] = fs->make<TH1F>("hResidualGlobalRCSC_ME-2/2", "hResidualGlobalRCSC_ME-2/2", 200, -10, 10); hResidualGlobalRPhiCSC_ME[6] = fs->make<TH1F>("hResidualGlobalRPhiCSC_ME-1/1", "hResidualGlobalRPhiCSC_ME-1/1", 200, -10, 10); hResidualGlobalPhiCSC_ME[6] = fs->make<TH1F>("hResidualGlobalPhiCSC_ME-1/1", "hResidualGlobalPhiCSC_ME-1/1", 200, -1, 1); hResidualGlobalThetaCSC_ME[6] = fs->make<TH1F>("hResidualGlobalThetaCSC_ME-1/1", "hResidualGlobalThetaCSC_ME-1/1", 200, -1, 1); hResidualGlobalRCSC_ME[6] = fs->make<TH1F>("hResidualGlobalRCSC_ME-1/1", "hResidualGlobalRCSC_ME-1/1", 200, -10, 10); hResidualGlobalRPhiCSC_ME[7] = fs->make<TH1F>("hResidualGlobalRPhiCSC_ME-1/2", "hResidualGlobalRPhiCSC_ME-1/2", 200, -10, 10); hResidualGlobalPhiCSC_ME[7] = fs->make<TH1F>("hResidualGlobalPhiCSC_ME-1/2", "hResidualGlobalPhiCSC_ME-1/2", 200, -1, 1); hResidualGlobalThetaCSC_ME[7] = fs->make<TH1F>("hResidualGlobalThetaCSC_ME-1/2", "hResidualGlobalThetaCSC_ME-1/2", 200, -1, 1); hResidualGlobalRCSC_ME[7] = fs->make<TH1F>("hResidualGlobalRCSC_ME-1/2", "hResidualGlobalRCSC_ME-1/2", 200, -10, 10); hResidualGlobalRPhiCSC_ME[8] = fs->make<TH1F>("hResidualGlobalRPhiCSC_ME-1/3", "hResidualGlobalRPhiCSC_ME-1/3", 200, -10, 10); hResidualGlobalPhiCSC_ME[8] = fs->make<TH1F>("hResidualGlobalPhiCSC_ME-1/3", "hResidualGlobalPhiCSC_ME-1/3", 200, -1, 1); hResidualGlobalThetaCSC_ME[8] = fs->make<TH1F>("hResidualGlobalThetaCSC_ME-1/3", "hResidualGlobalThetaCSC_ME-1/3", 200, -1, 1); hResidualGlobalRCSC_ME[8] = fs->make<TH1F>("hResidualGlobalRCSC_ME-1/3", "hResidualGlobalRCSC_ME-1/3", 200, -10, 10); hResidualGlobalRPhiCSC_ME[9] = fs->make<TH1F>("hResidualGlobalRPhiCSC_ME1/1", "hResidualGlobalRPhiCSC_ME1/1", 200, -10, 10); hResidualGlobalPhiCSC_ME[9] = fs->make<TH1F>("hResidualGlobalPhiCSC_ME1/1", "hResidualGlobalPhiCSC_ME1/1", 100, -1, 1); hResidualGlobalThetaCSC_ME[9] = fs->make<TH1F>("hResidualGlobalThetaCSC_ME1/1", "hResidualGlobalThetaCSC_ME1/1", 200, -1, 1); hResidualGlobalRCSC_ME[9] = fs->make<TH1F>("hResidualGlobalRCSC_ME1/1", "hResidualGlobalRCSC_ME1/1", 200, -10, 10); hResidualGlobalRPhiCSC_ME[10] = fs->make<TH1F>("hResidualGlobalRPhiCSC_ME1/2", "hResidualGlobalRPhiCSC_ME1/2", 200, -10, 10); hResidualGlobalPhiCSC_ME[10] = fs->make<TH1F>("hResidualGlobalPhiCSC_ME1/2", "hResidualGlobalPhiCSC_ME1/2", 200, -1, 1); hResidualGlobalThetaCSC_ME[10] = fs->make<TH1F>("hResidualGlobalThetaCSC_ME1/2", "hResidualGlobalThetaCSC_ME1/2", 200, -1, 1); hResidualGlobalRCSC_ME[10] = fs->make<TH1F>("hResidualGlobalRCSC_ME1/2", "hResidualGlobalRCSC_ME1/2", 200, -10, 10); hResidualGlobalRPhiCSC_ME[11] = fs->make<TH1F>("hResidualGlobalRPhiCSC_ME1/3", "hResidualGlobalRPhiCSC_ME1/3", 200, -10, 10); hResidualGlobalPhiCSC_ME[11] = fs->make<TH1F>("hResidualGlobalPhiCSC_ME1/3", "hResidualGlobalPhiCSC_ME1/3", 200, -1, 1); hResidualGlobalThetaCSC_ME[11] = fs->make<TH1F>("hResidualGlobalThetaCSC_ME1/3", "hResidualGlobalThetaCSC_ME1/3", 200, -1, 1); hResidualGlobalRCSC_ME[11] = fs->make<TH1F>("hResidualGlobalRCSC_ME1/3", "hResidualGlobalRCSC_ME1/3", 200, -10, 10); hResidualGlobalRPhiCSC_ME[12] = fs->make<TH1F>("hResidualGlobalRPhiCSC_ME2/1", "hResidualGlobalRPhiCSC_ME2/1", 200, -10, 10); hResidualGlobalPhiCSC_ME[12] = fs->make<TH1F>("hResidualGlobalPhiCSC_ME2/1", "hResidualGlobalPhiCSC_ME2/1", 200, -1, 1); hResidualGlobalThetaCSC_ME[12] = fs->make<TH1F>("hResidualGlobalThetaCSC_ME2/1", "hResidualGlobalThetaCSC_ME2/1", 200, -1, 1); hResidualGlobalRCSC_ME[12] = fs->make<TH1F>("hResidualGlobalRCSC_ME2/1", "hResidualGlobalRCSC_ME2/1", 200, -10, 10); hResidualGlobalRPhiCSC_ME[13] = fs->make<TH1F>("hResidualGlobalRPhiCSC_ME2/2", "hResidualGlobalRPhiCSC_ME2/2", 200, -10, 10); hResidualGlobalPhiCSC_ME[13] = fs->make<TH1F>("hResidualGlobalPhiCSC_ME2/2", "hResidualGlobalPhiCSC_ME2/2", 200, -1, 1); hResidualGlobalThetaCSC_ME[13] = fs->make<TH1F>("hResidualGlobalThetaCSC_ME2/2", "hResidualGlobalThetaCSC_ME2/2", 200, -1, 1); hResidualGlobalRCSC_ME[13] = fs->make<TH1F>("hResidualGlobalRCSC_ME2/2", "hResidualGlobalRCSC_ME2/2", 200, -10, 10); hResidualGlobalRPhiCSC_ME[14] = fs->make<TH1F>("hResidualGlobalRPhiCSC_ME3/1", "hResidualGlobalRPhiCSC_ME3/1", 200, -10, 10); hResidualGlobalPhiCSC_ME[14] = fs->make<TH1F>("hResidualGlobalPhiCSC_ME3/1", "hResidualGlobalPhiCSC_ME3/1", 200, -1, 1); hResidualGlobalThetaCSC_ME[14] = fs->make<TH1F>("hResidualGlobalThetaCSC_ME3/1", "hResidualGlobalThetaCSC_ME3/1", 200, -1, 1); hResidualGlobalRCSC_ME[14] = fs->make<TH1F>("hResidualGlobalRCSC_ME3/1", "hResidualGlobalRCSC_ME3/1", 200, -10, 10); hResidualGlobalRPhiCSC_ME[15] = fs->make<TH1F>("hResidualGlobalRPhiCSC_ME3/2", "hResidualGlobalRPhiCSC_ME3/2", 200, -10, 10); hResidualGlobalPhiCSC_ME[15] = fs->make<TH1F>("hResidualGlobalPhiCSC_ME3/2", "hResidualGlobalPhiCSC_ME3/2", 200, -1, 1); hResidualGlobalThetaCSC_ME[15] = fs->make<TH1F>("hResidualGlobalThetaCSC_ME3/2", "hResidualGlobalThetaCSC_ME3/2", 200, -1, 1); hResidualGlobalRCSC_ME[15] = fs->make<TH1F>("hResidualGlobalRCSC_ME3/2", "hResidualGlobalRCSC_ME3/2", 200, -10, 10); hResidualGlobalRPhiCSC_ME[16] = fs->make<TH1F>("hResidualGlobalRPhiCSC_ME4/1", "hResidualGlobalRPhiCSC_ME4/1", 200, -10, 10); hResidualGlobalPhiCSC_ME[16] = fs->make<TH1F>("hResidualGlobalPhiCSC_ME4/1", "hResidualGlobalPhiCSC_ME4/1", 200, -1, 1); hResidualGlobalThetaCSC_ME[16] = fs->make<TH1F>("hResidualGlobalThetaCSC_ME4/1", "hResidualGlobalThetaCSC_ME4/1", 200, -1, 1); hResidualGlobalRCSC_ME[16] = fs->make<TH1F>("hResidualGlobalRCSC_ME4/1", "hResidualGlobalRCSC_ME4/1", 200, -10, 10); hResidualGlobalRPhiCSC_ME[17] = fs->make<TH1F>("hResidualGlobalRPhiCSC_ME4/2", "hResidualGlobalRPhiCSC_ME4/2", 200, -10, 10); hResidualGlobalPhiCSC_ME[17] = fs->make<TH1F>("hResidualGlobalPhiCSC_ME4/2", "hResidualGlobalPhiCSC_ME4/2", 200, -1, 1); hResidualGlobalThetaCSC_ME[17] = fs->make<TH1F>("hResidualGlobalThetaCSC_ME4/2", "hResidualGlobalThetaCSC_ME4/2", 200, -1, 1); hResidualGlobalRCSC_ME[17] = fs->make<TH1F>("hResidualGlobalRCSC_ME4/2", "hResidualGlobalRCSC_ME4/2", 200, -10, 10); //DQM plots: mean residual with RMS as error hprofLocalXDT = fs->make<TH1F>("hprofLocalXDT", "Local X DT;;X (cm)", 280, 0, 280); hprofLocalPhiDT = fs->make<TH1F>("hprofLocalPhiDT", "Local Phi DT;;Phi (rad)", 280, 0, 280); hprofLocalThetaDT = fs->make<TH1F>("hprofLocalThetaDT", "Local Theta DT;;Theta (rad)", 280, 0, 280); hprofLocalYDT = fs->make<TH1F>("hprofLocalYDT", "Local Y DT;;Y (cm)", 280, 0, 280); hprofLocalXCSC = fs->make<TH1F>("hprofLocalXCSC", "Local X CSC;;X (cm)", 540, 0, 540); hprofLocalPhiCSC = fs->make<TH1F>("hprofLocalPhiCSC", "Local Phi CSC;;Phi (rad)", 540, 0, 540); hprofLocalThetaCSC = fs->make<TH1F>("hprofLocalThetaCSC", "Local Theta CSC;;Theta (rad)", 540, 0, 540); hprofLocalYCSC = fs->make<TH1F>("hprofLocalYCSC", "Local Y CSC;;Y (cm)", 540, 0, 540); hprofGlobalRPhiDT = fs->make<TH1F>("hprofGlobalRPhiDT", "Global RPhi DT;;RPhi (cm)", 280, 0, 280); hprofGlobalPhiDT = fs->make<TH1F>("hprofGlobalPhiDT", "Global Phi DT;;Phi (rad)", 280, 0, 280); hprofGlobalThetaDT = fs->make<TH1F>("hprofGlobalThetaDT", "Global Theta DT;;Theta (rad)", 280, 0, 280); hprofGlobalZDT = fs->make<TH1F>("hprofGlobalZDT", "Global Z DT;;Z (cm)", 280, 0, 280); hprofGlobalRPhiCSC = fs->make<TH1F>("hprofGlobalRPhiCSC", "Global RPhi CSC;;RPhi (cm)", 540, 0, 540); hprofGlobalPhiCSC = fs->make<TH1F>("hprofGlobalPhiCSC", "Global Phi CSC;;Phi (cm)", 540, 0, 540); hprofGlobalThetaCSC = fs->make<TH1F>("hprofGlobalThetaCSC", "Global Theta CSC;;Theta (rad)", 540, 0, 540); hprofGlobalRCSC = fs->make<TH1F>("hprofGlobalRCSC", "Global R CSC;;R (cm)", 540, 0, 540); // TH1F options hprofLocalXDT->GetXaxis()->SetLabelSize(0.025); hprofLocalPhiDT->GetXaxis()->SetLabelSize(0.025); hprofLocalThetaDT->GetXaxis()->SetLabelSize(0.025); hprofLocalYDT->GetXaxis()->SetLabelSize(0.025); hprofLocalXCSC->GetXaxis()->SetLabelSize(0.025); hprofLocalPhiCSC->GetXaxis()->SetLabelSize(0.025); hprofLocalThetaCSC->GetXaxis()->SetLabelSize(0.025); hprofLocalYCSC->GetXaxis()->SetLabelSize(0.025); hprofGlobalRPhiDT->GetXaxis()->SetLabelSize(0.025); hprofGlobalPhiDT->GetXaxis()->SetLabelSize(0.025); hprofGlobalThetaDT->GetXaxis()->SetLabelSize(0.025); hprofGlobalZDT->GetXaxis()->SetLabelSize(0.025); hprofGlobalRPhiCSC->GetXaxis()->SetLabelSize(0.025); hprofGlobalPhiCSC->GetXaxis()->SetLabelSize(0.025); hprofGlobalThetaCSC->GetXaxis()->SetLabelSize(0.025); hprofGlobalRCSC->GetXaxis()->SetLabelSize(0.025); // TH2F histos definition hprofGlobalPositionDT = fs->make<TH2F>( "hprofGlobalPositionDT", "Global DT position (cm) absolute MEAN residuals;Sector;;cm", 14, 0, 14, 40, 0, 40); hprofGlobalAngleDT = fs->make<TH2F>( "hprofGlobalAngleDT", "Global DT angle (rad) absolute MEAN residuals;Sector;;rad", 14, 0, 14, 40, 0, 40); hprofGlobalPositionRmsDT = fs->make<TH2F>( "hprofGlobalPositionRmsDT", "Global DT position (cm) RMS residuals;Sector;;rad", 14, 0, 14, 40, 0, 40); hprofGlobalAngleRmsDT = fs->make<TH2F>( "hprofGlobalAngleRmsDT", "Global DT angle (rad) RMS residuals;Sector;;rad", 14, 0, 14, 40, 0, 40); hprofLocalPositionDT = fs->make<TH2F>( "hprofLocalPositionDT", "Local DT position (cm) absolute MEAN residuals;Sector;;cm", 14, 0, 14, 40, 0, 40); hprofLocalAngleDT = fs->make<TH2F>( "hprofLocalAngleDT", "Local DT angle (rad) absolute MEAN residuals;Sector;;rad", 14, 0, 14, 40, 0, 40); hprofLocalPositionRmsDT = fs->make<TH2F>( "hprofLocalPositionRmsDT", "Local DT position (cm) RMS residuals;Sector;;rad", 14, 0, 14, 40, 0, 40); hprofLocalAngleRmsDT = fs->make<TH2F>("hprofLocalAngleRmsDT", "Local DT angle (rad) RMS residuals;Sector;;rad", 14, 0, 14, 40, 0, 40); hprofGlobalPositionCSC = fs->make<TH2F>( "hprofGlobalPositionCSC", "Global CSC position (cm) absolute MEAN residuals;Sector;;cm", 36, 0, 36, 36, 0, 36); hprofGlobalAngleCSC = fs->make<TH2F>( "hprofGlobalAngleCSC", "Global CSC angle (rad) absolute MEAN residuals;Sector;;rad", 36, 0, 36, 36, 0, 36); hprofGlobalPositionRmsCSC = fs->make<TH2F>( "hprofGlobalPositionRmsCSC", "Global CSC position (cm) RMS residuals;Sector;;rad", 36, 0, 36, 36, 0, 36); hprofGlobalAngleRmsCSC = fs->make<TH2F>( "hprofGlobalAngleRmsCSC", "Global CSC angle (rad) RMS residuals;Sector;;rad", 36, 0, 36, 36, 0, 36); hprofLocalPositionCSC = fs->make<TH2F>( "hprofLocalPositionCSC", "Local CSC position (cm) absolute MEAN residuals;Sector;;cm", 36, 0, 36, 36, 0, 36); hprofLocalAngleCSC = fs->make<TH2F>( "hprofLocalAngleCSC", "Local CSC angle (rad) absolute MEAN residuals;Sector;;rad", 36, 0, 36, 36, 0, 36); hprofLocalPositionRmsCSC = fs->make<TH2F>( "hprofLocalPositionRmsCSC", "Local CSC position (cm) RMS residuals;Sector;;rad", 36, 0, 36, 36, 0, 36); hprofLocalAngleRmsCSC = fs->make<TH2F>( "hprofLocalAngleRmsCSC", "Local CSC angle (rad) RMS residuals;Sector;;rad", 36, 0, 36, 36, 0, 36); // histos options Float_t labelSize = 0.025; hprofGlobalPositionDT->GetYaxis()->SetLabelSize(labelSize); hprofGlobalAngleDT->GetYaxis()->SetLabelSize(labelSize); hprofGlobalPositionRmsDT->GetYaxis()->SetLabelSize(labelSize); hprofGlobalAngleRmsDT->GetYaxis()->SetLabelSize(labelSize); hprofLocalPositionDT->GetYaxis()->SetLabelSize(labelSize); hprofLocalAngleDT->GetYaxis()->SetLabelSize(labelSize); hprofLocalPositionRmsDT->GetYaxis()->SetLabelSize(labelSize); hprofLocalAngleRmsDT->GetYaxis()->SetLabelSize(labelSize); hprofGlobalPositionCSC->GetYaxis()->SetLabelSize(labelSize); hprofGlobalAngleCSC->GetYaxis()->SetLabelSize(labelSize); hprofGlobalPositionRmsCSC->GetYaxis()->SetLabelSize(labelSize); hprofGlobalAngleRmsCSC->GetYaxis()->SetLabelSize(labelSize); hprofLocalPositionCSC->GetYaxis()->SetLabelSize(labelSize); hprofLocalAngleCSC->GetYaxis()->SetLabelSize(labelSize); hprofLocalPositionRmsCSC->GetYaxis()->SetLabelSize(labelSize); hprofLocalAngleRmsCSC->GetYaxis()->SetLabelSize(labelSize); char binLabel[32]; for (int i = 1; i < 15; i++) { snprintf(binLabel, sizeof(binLabel), "Sec-%d", i); hprofGlobalPositionDT->GetXaxis()->SetBinLabel(i, binLabel); hprofGlobalAngleDT->GetXaxis()->SetBinLabel(i, binLabel); hprofGlobalPositionRmsDT->GetXaxis()->SetBinLabel(i, binLabel); hprofGlobalAngleRmsDT->GetXaxis()->SetBinLabel(i, binLabel); hprofLocalPositionDT->GetXaxis()->SetBinLabel(i, binLabel); hprofLocalAngleDT->GetXaxis()->SetBinLabel(i, binLabel); hprofLocalPositionRmsDT->GetXaxis()->SetBinLabel(i, binLabel); hprofLocalAngleRmsDT->GetXaxis()->SetBinLabel(i, binLabel); } for (int i = 1; i < 37; i++) { snprintf(binLabel, sizeof(binLabel), "Ch-%d", i); hprofGlobalPositionCSC->GetXaxis()->SetBinLabel(i, binLabel); hprofGlobalAngleCSC->GetXaxis()->SetBinLabel(i, binLabel); hprofGlobalPositionRmsCSC->GetXaxis()->SetBinLabel(i, binLabel); hprofGlobalAngleRmsCSC->GetXaxis()->SetBinLabel(i, binLabel); hprofLocalPositionCSC->GetXaxis()->SetBinLabel(i, binLabel); hprofLocalAngleCSC->GetXaxis()->SetBinLabel(i, binLabel); hprofLocalPositionRmsCSC->GetXaxis()->SetBinLabel(i, binLabel); hprofLocalAngleRmsCSC->GetXaxis()->SetBinLabel(i, binLabel); } } } void MuonAlignmentAnalyzer::endJob() { edm::LogInfo("MuonAlignmentAnalyzer") << "----------------- " << std::endl << std::endl; if (theDataType == "SimData") edm::LogInfo("MuonAlignmentAnalyzer") << "Number of Sim tracks: " << numberOfSimTracks << std::endl << std::endl; if (doSAplots) edm::LogInfo("MuonAlignmentAnalyzer") << "Number of SA Reco tracks: " << numberOfSARecTracks << std::endl << std::endl; if (doGBplots) edm::LogInfo("MuonAlignmentAnalyzer") << "Number of GB Reco tracks: " << numberOfGBRecTracks << std::endl << std::endl; if (doResplots) { // delete thePropagator; edm::LogInfo("MuonAlignmentAnalyzer") << "Number of Hits considered for residuals: " << numberOfHits << std::endl << std::endl; char binLabel[40]; for (unsigned int i = 0; i < unitsLocalX.size(); i++) { TString nameHistoLocalX = unitsLocalX[i]->GetName(); TString nameHistoLocalPhi = unitsLocalPhi[i]->GetName(); TString nameHistoLocalTheta = unitsLocalTheta[i]->GetName(); TString nameHistoLocalY = unitsLocalY[i]->GetName(); TString nameHistoGlobalRPhi = unitsGlobalRPhi[i]->GetName(); TString nameHistoGlobalPhi = unitsGlobalPhi[i]->GetName(); TString nameHistoGlobalTheta = unitsGlobalTheta[i]->GetName(); TString nameHistoGlobalRZ = unitsGlobalRZ[i]->GetName(); if (nameHistoLocalX.Contains("MB")) // HistoLocalX DT { int wheel, station, sector; sscanf(nameHistoLocalX, "ResidualLocalX_W%dMB%1dS%d", &wheel, &station, &sector); Int_t nstation = station - 1; Int_t nwheel = wheel + 2; Double_t MeanRPhi = unitsLocalX[i]->GetMean(); Double_t ErrorRPhi = unitsLocalX[i]->GetMeanError(); Int_t xbin = sector + 14 * nstation + 14 * 4 * nwheel; snprintf(binLabel, sizeof(binLabel), "MB%d/%dS%d", wheel, station, sector); hprofLocalXDT->SetMarkerStyle(21); hprofLocalXDT->SetMarkerColor(kRed); hprofLocalXDT->SetBinContent(xbin, MeanRPhi); hprofLocalXDT->SetBinError(xbin, ErrorRPhi); hprofLocalXDT->GetXaxis()->SetBinLabel(xbin, binLabel); Int_t ybin = 1 + nwheel * 8 + nstation * 2; hprofLocalPositionDT->SetBinContent(sector, ybin, fabs(MeanRPhi)); snprintf(binLabel, sizeof(binLabel), "MB%d/%d_LocalX", wheel, station); hprofLocalPositionDT->GetYaxis()->SetBinLabel(ybin, binLabel); hprofLocalPositionRmsDT->SetBinContent(sector, ybin, ErrorRPhi); hprofLocalPositionRmsDT->GetYaxis()->SetBinLabel(ybin, binLabel); } if (nameHistoLocalX.Contains("ME")) // HistoLocalX CSC { int station, ring, chamber; sscanf(nameHistoLocalX, "ResidualLocalX_ME%dR%1dC%d", &station, &ring, &chamber); Double_t MeanRPhi = unitsLocalX[i]->GetMean(); Double_t ErrorRPhi = unitsLocalX[i]->GetMeanError(); Int_t xbin = abs(station) * 2 + ring; if (abs(station) == 1) xbin = ring; if (station > 0) xbin = xbin + 9; else xbin = 10 - xbin; // To avoid holes in xAxis, I can't imagine right now a simpler way... if (xbin < 5) xbin = 18 * (((Int_t)(xbin / 3)) * 2 + (Int_t)(xbin / 2)) + chamber; else if (xbin < 6) xbin = 108 + chamber; else if (xbin < 14) xbin = 126 + (xbin - 6) * 36 + chamber; else if (xbin < 18) xbin = 414 + 18 * (((Int_t)(xbin - 13) / 3) * 2 + ((Int_t)(xbin - 13) / 2)) + chamber; else xbin = 522 + chamber; snprintf(binLabel, sizeof(binLabel), "ME%d/%dC%d", station, ring, chamber); hprofLocalXCSC->SetMarkerStyle(21); hprofLocalXCSC->SetMarkerColor(kRed); hprofLocalXCSC->SetBinContent(xbin, MeanRPhi); hprofLocalXCSC->SetBinError(xbin, ErrorRPhi); hprofLocalXCSC->GetXaxis()->SetBinLabel(xbin, binLabel); Int_t ybin = abs(station) * 2 + ring; if (abs(station) == 1) ybin = ring; if (station > 0) ybin = ybin + 9; else ybin = 10 - ybin; ybin = 2 * ybin - 1; hprofLocalPositionCSC->SetBinContent(chamber, ybin, fabs(MeanRPhi)); snprintf(binLabel, sizeof(binLabel), "ME%d/%d_LocalX", station, ring); hprofLocalPositionCSC->GetYaxis()->SetBinLabel(ybin, binLabel); hprofLocalPositionRmsCSC->SetBinContent(chamber, ybin, ErrorRPhi); hprofLocalPositionRmsCSC->GetYaxis()->SetBinLabel(ybin, binLabel); } if (nameHistoLocalTheta.Contains("MB")) // HistoLocalTheta DT { int wheel, station, sector; sscanf(nameHistoLocalTheta, "ResidualLocalTheta_W%dMB%1dS%d", &wheel, &station, &sector); if (station != 4) { Int_t nstation = station - 1; Int_t nwheel = wheel + 2; Double_t MeanTheta = unitsLocalTheta[i]->GetMean(); Double_t ErrorTheta = unitsLocalTheta[i]->GetMeanError(); Int_t xbin = sector + 14 * nstation + 14 * 4 * nwheel; snprintf(binLabel, sizeof(binLabel), "MB%d/%dS%d", wheel, station, sector); hprofLocalThetaDT->SetBinContent(xbin, MeanTheta); hprofLocalThetaDT->SetBinError(xbin, ErrorTheta); hprofLocalThetaDT->SetMarkerStyle(21); hprofLocalThetaDT->SetMarkerColor(kRed); hprofLocalThetaDT->GetXaxis()->SetBinLabel(xbin, binLabel); Int_t ybin = 2 + nwheel * 8 + nstation * 2; hprofLocalAngleDT->SetBinContent(sector, ybin, fabs(MeanTheta)); snprintf(binLabel, sizeof(binLabel), "MB%d/%d_LocalTheta", wheel, station); hprofLocalAngleDT->GetYaxis()->SetBinLabel(ybin, binLabel); hprofLocalAngleRmsDT->SetBinContent(sector, ybin, ErrorTheta); hprofLocalAngleRmsDT->GetYaxis()->SetBinLabel(ybin, binLabel); } } if (nameHistoLocalPhi.Contains("MB")) // HistoLocalPhi DT { int wheel, station, sector; sscanf(nameHistoLocalPhi, "ResidualLocalPhi_W%dMB%1dS%d", &wheel, &station, &sector); Int_t nstation = station - 1; Int_t nwheel = wheel + 2; Double_t MeanPhi = unitsLocalPhi[i]->GetMean(); Double_t ErrorPhi = unitsLocalPhi[i]->GetMeanError(); Int_t xbin = sector + 14 * nstation + 14 * 4 * nwheel; snprintf(binLabel, sizeof(binLabel), "MB%d/%dS%d", wheel, station, sector); hprofLocalPhiDT->SetBinContent(xbin, MeanPhi); hprofLocalPhiDT->SetBinError(xbin, ErrorPhi); hprofLocalPhiDT->SetMarkerStyle(21); hprofLocalPhiDT->SetMarkerColor(kRed); hprofLocalPhiDT->GetXaxis()->SetBinLabel(xbin, binLabel); Int_t ybin = 1 + nwheel * 8 + nstation * 2; hprofLocalAngleDT->SetBinContent(sector, ybin, fabs(MeanPhi)); snprintf(binLabel, sizeof(binLabel), "MB%d/%d_LocalPhi", wheel, station); hprofLocalAngleDT->GetYaxis()->SetBinLabel(ybin, binLabel); hprofLocalAngleRmsDT->SetBinContent(sector, ybin, ErrorPhi); hprofLocalAngleRmsDT->GetYaxis()->SetBinLabel(ybin, binLabel); } if (nameHistoLocalPhi.Contains("ME")) // HistoLocalPhi CSC { int station, ring, chamber; sscanf(nameHistoLocalPhi, "ResidualLocalPhi_ME%dR%1dC%d", &station, &ring, &chamber); Double_t MeanPhi = unitsLocalPhi[i]->GetMean(); Double_t ErrorPhi = unitsLocalPhi[i]->GetMeanError(); Int_t xbin = abs(station) * 2 + ring; if (abs(station) == 1) xbin = ring; if (station > 0) xbin = xbin + 9; else xbin = 10 - xbin; // To avoid holes in xAxis, I can't imagine right now a simpler way... if (xbin < 5) xbin = 18 * (((Int_t)(xbin / 3)) * 2 + (Int_t)(xbin / 2)) + chamber; else if (xbin < 6) xbin = 108 + chamber; else if (xbin < 14) xbin = 126 + (xbin - 6) * 36 + chamber; else if (xbin < 18) xbin = 414 + 18 * (((Int_t)(xbin - 13) / 3) * 2 + ((Int_t)(xbin - 13) / 2)) + chamber; else xbin = 522 + chamber; snprintf(binLabel, sizeof(binLabel), "ME%d/%dC%d", station, ring, chamber); hprofLocalPhiCSC->SetMarkerStyle(21); hprofLocalPhiCSC->SetMarkerColor(kRed); hprofLocalPhiCSC->SetBinContent(xbin, MeanPhi); hprofLocalPhiCSC->SetBinError(xbin, ErrorPhi); hprofLocalPhiCSC->GetXaxis()->SetBinLabel(xbin, binLabel); Int_t ybin = abs(station) * 2 + ring; if (abs(station) == 1) ybin = ring; if (station > 0) ybin = ybin + 9; else ybin = 10 - ybin; ybin = 2 * ybin - 1; hprofLocalAngleCSC->SetBinContent(chamber, ybin, fabs(MeanPhi)); snprintf(binLabel, sizeof(binLabel), "ME%d/%d_LocalPhi", station, ring); hprofLocalAngleCSC->GetYaxis()->SetBinLabel(ybin, binLabel); hprofLocalAngleRmsCSC->SetBinContent(chamber, ybin, ErrorPhi); hprofLocalAngleRmsCSC->GetYaxis()->SetBinLabel(ybin, binLabel); } if (nameHistoLocalTheta.Contains("ME")) // HistoLocalTheta CSC { int station, ring, chamber; sscanf(nameHistoLocalTheta, "ResidualLocalTheta_ME%dR%1dC%d", &station, &ring, &chamber); Double_t MeanTheta = unitsLocalTheta[i]->GetMean(); Double_t ErrorTheta = unitsLocalTheta[i]->GetMeanError(); Int_t xbin = abs(station) * 2 + ring; if (abs(station) == 1) xbin = ring; if (station > 0) xbin = xbin + 9; else xbin = 10 - xbin; // To avoid holes in xAxis, I can't imagine right now a simpler way... if (xbin < 5) xbin = 18 * (((Int_t)(xbin / 3)) * 2 + (Int_t)(xbin / 2)) + chamber; else if (xbin < 6) xbin = 108 + chamber; else if (xbin < 14) xbin = 126 + (xbin - 6) * 36 + chamber; else if (xbin < 18) xbin = 414 + 18 * (((Int_t)(xbin - 13) / 3) * 2 + ((Int_t)(xbin - 13) / 2)) + chamber; else xbin = 522 + chamber; snprintf(binLabel, sizeof(binLabel), "ME%d/%dC%d", station, ring, chamber); hprofLocalThetaCSC->SetMarkerStyle(21); hprofLocalThetaCSC->SetMarkerColor(kRed); hprofLocalThetaCSC->SetBinContent(xbin, MeanTheta); hprofLocalThetaCSC->SetBinError(xbin, ErrorTheta); hprofLocalThetaCSC->GetXaxis()->SetBinLabel(xbin, binLabel); Int_t ybin = abs(station) * 2 + ring; if (abs(station) == 1) ybin = ring; if (station > 0) ybin = ybin + 9; else ybin = 10 - ybin; ybin = 2 * ybin; hprofLocalAngleCSC->SetBinContent(chamber, ybin, fabs(MeanTheta)); snprintf(binLabel, sizeof(binLabel), "ME%d/%d_LocalTheta", station, ring); hprofLocalAngleCSC->GetYaxis()->SetBinLabel(ybin, binLabel); hprofLocalAngleRmsCSC->SetBinContent(chamber, ybin, ErrorTheta); hprofLocalAngleRmsCSC->GetYaxis()->SetBinLabel(ybin, binLabel); } if (nameHistoLocalY.Contains("MB")) // HistoLocalY DT { int wheel, station, sector; sscanf(nameHistoLocalY, "ResidualLocalY_W%dMB%1dS%d", &wheel, &station, &sector); if (station != 4) { Int_t nstation = station - 1; Int_t nwheel = wheel + 2; Double_t MeanZ = unitsLocalY[i]->GetMean(); Double_t ErrorZ = unitsLocalY[i]->GetMeanError(); Int_t xbin = sector + 14 * nstation + 14 * 4 * nwheel; snprintf(binLabel, sizeof(binLabel), "MB%d/%dS%d", wheel, station, sector); hprofLocalYDT->SetMarkerStyle(21); hprofLocalYDT->SetMarkerColor(kRed); hprofLocalYDT->SetBinContent(xbin, MeanZ); hprofLocalYDT->SetBinError(xbin, ErrorZ); hprofLocalYDT->GetXaxis()->SetBinLabel(xbin, binLabel); Int_t ybin = 2 + nwheel * 8 + nstation * 2; hprofLocalPositionDT->SetBinContent(sector, ybin, fabs(MeanZ)); snprintf(binLabel, sizeof(binLabel), "MB%d/%d_LocalY", wheel, station); hprofLocalPositionDT->GetYaxis()->SetBinLabel(ybin, binLabel); hprofLocalPositionRmsDT->SetBinContent(sector, ybin, ErrorZ); hprofLocalPositionRmsDT->GetYaxis()->SetBinLabel(ybin, binLabel); } } if (nameHistoLocalY.Contains("ME")) // HistoLocalY CSC { int station, ring, chamber; sscanf(nameHistoLocalY, "ResidualLocalY_ME%dR%1dC%d", &station, &ring, &chamber); Double_t MeanR = unitsLocalY[i]->GetMean(); Double_t ErrorR = unitsLocalY[i]->GetMeanError(); Int_t xbin = abs(station) * 2 + ring; if (abs(station) == 1) xbin = ring; if (station > 0) xbin = xbin + 9; else xbin = 10 - xbin; // To avoid holes in xAxis, I can't imagine right now a simpler way... if (xbin < 5) xbin = 18 * (((Int_t)(xbin / 3)) * 2 + (Int_t)(xbin / 2)) + chamber; else if (xbin < 6) xbin = 108 + chamber; else if (xbin < 14) xbin = 126 + (xbin - 6) * 36 + chamber; else if (xbin < 18) xbin = 414 + 18 * (((Int_t)(xbin - 13) / 3) * 2 + ((Int_t)(xbin - 13) / 2)) + chamber; else xbin = 522 + chamber; snprintf(binLabel, sizeof(binLabel), "ME%d/%dC%d", station, ring, chamber); hprofLocalYCSC->SetMarkerStyle(21); hprofLocalYCSC->SetMarkerColor(kRed); hprofLocalYCSC->SetBinContent(xbin, MeanR); hprofLocalYCSC->SetBinError(xbin, ErrorR); hprofLocalYCSC->GetXaxis()->SetBinLabel(xbin, binLabel); Int_t ybin = abs(station) * 2 + ring; if (abs(station) == 1) ybin = ring; if (station > 0) ybin = ybin + 9; else ybin = 10 - ybin; ybin = 2 * ybin; hprofLocalPositionCSC->SetBinContent(chamber, ybin, fabs(MeanR)); snprintf(binLabel, sizeof(binLabel), "ME%d/%d_LocalY", station, ring); hprofLocalPositionCSC->GetYaxis()->SetBinLabel(ybin, binLabel); hprofLocalPositionRmsCSC->SetBinContent(chamber, ybin, ErrorR); hprofLocalPositionRmsCSC->GetYaxis()->SetBinLabel(ybin, binLabel); } if (nameHistoGlobalRPhi.Contains("MB")) // HistoGlobalRPhi DT { int wheel, station, sector; sscanf(nameHistoGlobalRPhi, "ResidualGlobalRPhi_W%dMB%1dS%d", &wheel, &station, &sector); Int_t nstation = station - 1; Int_t nwheel = wheel + 2; Double_t MeanRPhi = unitsGlobalRPhi[i]->GetMean(); Double_t ErrorRPhi = unitsGlobalRPhi[i]->GetMeanError(); Int_t xbin = sector + 14 * nstation + 14 * 4 * nwheel; snprintf(binLabel, sizeof(binLabel), "MB%d/%dS%d", wheel, station, sector); hprofGlobalRPhiDT->SetMarkerStyle(21); hprofGlobalRPhiDT->SetMarkerColor(kRed); hprofGlobalRPhiDT->SetBinContent(xbin, MeanRPhi); hprofGlobalRPhiDT->SetBinError(xbin, ErrorRPhi); hprofGlobalRPhiDT->GetXaxis()->SetBinLabel(xbin, binLabel); Int_t ybin = 1 + nwheel * 8 + nstation * 2; hprofGlobalPositionDT->SetBinContent(sector, ybin, fabs(MeanRPhi)); snprintf(binLabel, sizeof(binLabel), "MB%d/%d_GlobalRPhi", wheel, station); hprofGlobalPositionDT->GetYaxis()->SetBinLabel(ybin, binLabel); hprofGlobalPositionRmsDT->SetBinContent(sector, ybin, ErrorRPhi); hprofGlobalPositionRmsDT->GetYaxis()->SetBinLabel(ybin, binLabel); } if (nameHistoGlobalRPhi.Contains("ME")) // HistoGlobalRPhi CSC { int station, ring, chamber; sscanf(nameHistoGlobalRPhi, "ResidualGlobalRPhi_ME%dR%1dC%d", &station, &ring, &chamber); Double_t MeanRPhi = unitsGlobalRPhi[i]->GetMean(); Double_t ErrorRPhi = unitsGlobalRPhi[i]->GetMeanError(); Int_t xbin = abs(station) * 2 + ring; if (abs(station) == 1) xbin = ring; if (station > 0) xbin = xbin + 9; else xbin = 10 - xbin; // To avoid holes in xAxis, I can't imagine right now a simpler way... if (xbin < 5) xbin = 18 * (((Int_t)(xbin / 3)) * 2 + (Int_t)(xbin / 2)) + chamber; else if (xbin < 6) xbin = 108 + chamber; else if (xbin < 14) xbin = 126 + (xbin - 6) * 36 + chamber; else if (xbin < 18) xbin = 414 + 18 * (((Int_t)(xbin - 13) / 3) * 2 + ((Int_t)(xbin - 13) / 2)) + chamber; else xbin = 522 + chamber; snprintf(binLabel, sizeof(binLabel), "ME%d/%dC%d", station, ring, chamber); hprofGlobalRPhiCSC->SetMarkerStyle(21); hprofGlobalRPhiCSC->SetMarkerColor(kRed); hprofGlobalRPhiCSC->SetBinContent(xbin, MeanRPhi); hprofGlobalRPhiCSC->SetBinError(xbin, ErrorRPhi); hprofGlobalRPhiCSC->GetXaxis()->SetBinLabel(xbin, binLabel); Int_t ybin = abs(station) * 2 + ring; if (abs(station) == 1) ybin = ring; if (station > 0) ybin = ybin + 9; else ybin = 10 - ybin; ybin = 2 * ybin - 1; hprofGlobalPositionCSC->SetBinContent(chamber, ybin, fabs(MeanRPhi)); snprintf(binLabel, sizeof(binLabel), "ME%d/%d_GlobalRPhi", station, ring); hprofGlobalPositionCSC->GetYaxis()->SetBinLabel(ybin, binLabel); hprofGlobalPositionRmsCSC->SetBinContent(chamber, ybin, ErrorRPhi); hprofGlobalPositionRmsCSC->GetYaxis()->SetBinLabel(ybin, binLabel); } if (nameHistoGlobalTheta.Contains("MB")) // HistoGlobalRTheta DT { int wheel, station, sector; sscanf(nameHistoGlobalTheta, "ResidualGlobalTheta_W%dMB%1dS%d", &wheel, &station, &sector); if (station != 4) { Int_t nstation = station - 1; Int_t nwheel = wheel + 2; Double_t MeanTheta = unitsGlobalTheta[i]->GetMean(); Double_t ErrorTheta = unitsGlobalTheta[i]->GetMeanError(); Int_t xbin = sector + 14 * nstation + 14 * 4 * nwheel; snprintf(binLabel, sizeof(binLabel), "MB%d/%dS%d", wheel, station, sector); hprofGlobalThetaDT->SetBinContent(xbin, MeanTheta); hprofGlobalThetaDT->SetBinError(xbin, ErrorTheta); hprofGlobalThetaDT->SetMarkerStyle(21); hprofGlobalThetaDT->SetMarkerColor(kRed); hprofGlobalThetaDT->GetXaxis()->SetBinLabel(xbin, binLabel); Int_t ybin = 2 + nwheel * 8 + nstation * 2; hprofGlobalAngleDT->SetBinContent(sector, ybin, fabs(MeanTheta)); snprintf(binLabel, sizeof(binLabel), "MB%d/%d_GlobalTheta", wheel, station); hprofGlobalAngleDT->GetYaxis()->SetBinLabel(ybin, binLabel); hprofGlobalAngleRmsDT->SetBinContent(sector, ybin, ErrorTheta); hprofGlobalAngleRmsDT->GetYaxis()->SetBinLabel(ybin, binLabel); } } if (nameHistoGlobalPhi.Contains("MB")) // HistoGlobalPhi DT { int wheel, station, sector; sscanf(nameHistoGlobalPhi, "ResidualGlobalPhi_W%dMB%1dS%d", &wheel, &station, &sector); Int_t nstation = station - 1; Int_t nwheel = wheel + 2; Double_t MeanPhi = unitsGlobalPhi[i]->GetMean(); Double_t ErrorPhi = unitsGlobalPhi[i]->GetMeanError(); Int_t xbin = sector + 14 * nstation + 14 * 4 * nwheel; snprintf(binLabel, sizeof(binLabel), "MB%d/%dS%d", wheel, station, sector); hprofGlobalPhiDT->SetBinContent(xbin, MeanPhi); hprofGlobalPhiDT->SetBinError(xbin, ErrorPhi); hprofGlobalPhiDT->SetMarkerStyle(21); hprofGlobalPhiDT->SetMarkerColor(kRed); hprofGlobalPhiDT->GetXaxis()->SetBinLabel(xbin, binLabel); Int_t ybin = 1 + nwheel * 8 + nstation * 2; hprofGlobalAngleDT->SetBinContent(sector, ybin, fabs(MeanPhi)); snprintf(binLabel, sizeof(binLabel), "MB%d/%d_GlobalPhi", wheel, station); hprofGlobalAngleDT->GetYaxis()->SetBinLabel(ybin, binLabel); hprofGlobalAngleRmsDT->SetBinContent(sector, ybin, ErrorPhi); hprofGlobalAngleRmsDT->GetYaxis()->SetBinLabel(ybin, binLabel); } if (nameHistoGlobalPhi.Contains("ME")) // HistoGlobalPhi CSC { int station, ring, chamber; sscanf(nameHistoGlobalPhi, "ResidualGlobalPhi_ME%dR%1dC%d", &station, &ring, &chamber); Double_t MeanPhi = unitsGlobalPhi[i]->GetMean(); Double_t ErrorPhi = unitsGlobalPhi[i]->GetMeanError(); Int_t xbin = abs(station) * 2 + ring; if (abs(station) == 1) xbin = ring; if (station > 0) xbin = xbin + 9; else xbin = 10 - xbin; // To avoid holes in xAxis, I can't imagine right now a simpler way... if (xbin < 5) xbin = 18 * (((Int_t)(xbin / 3)) * 2 + (Int_t)(xbin / 2)) + chamber; else if (xbin < 6) xbin = 108 + chamber; else if (xbin < 14) xbin = 126 + (xbin - 6) * 36 + chamber; else if (xbin < 18) xbin = 414 + 18 * (((Int_t)(xbin - 13) / 3) * 2 + ((Int_t)(xbin - 13) / 2)) + chamber; else xbin = 522 + chamber; snprintf(binLabel, sizeof(binLabel), "ME%d/%dC%d", station, ring, chamber); hprofGlobalPhiCSC->SetMarkerStyle(21); hprofGlobalPhiCSC->SetMarkerColor(kRed); hprofGlobalPhiCSC->SetBinContent(xbin, MeanPhi); hprofGlobalPhiCSC->SetBinError(xbin, ErrorPhi); hprofGlobalPhiCSC->GetXaxis()->SetBinLabel(xbin, binLabel); Int_t ybin = abs(station) * 2 + ring; if (abs(station) == 1) ybin = ring; if (station > 0) ybin = ybin + 9; else ybin = 10 - ybin; ybin = 2 * ybin - 1; hprofGlobalAngleCSC->SetBinContent(chamber, ybin, fabs(MeanPhi)); snprintf(binLabel, sizeof(binLabel), "ME%d/%d_GlobalPhi", station, ring); hprofGlobalAngleCSC->GetYaxis()->SetBinLabel(ybin, binLabel); hprofGlobalAngleRmsCSC->SetBinContent(chamber, ybin, ErrorPhi); hprofGlobalAngleRmsCSC->GetYaxis()->SetBinLabel(ybin, binLabel); } if (nameHistoGlobalTheta.Contains("ME")) // HistoGlobalTheta CSC { int station, ring, chamber; sscanf(nameHistoGlobalTheta, "ResidualGlobalTheta_ME%dR%1dC%d", &station, &ring, &chamber); Double_t MeanTheta = unitsGlobalTheta[i]->GetMean(); Double_t ErrorTheta = unitsGlobalTheta[i]->GetMeanError(); Int_t xbin = abs(station) * 2 + ring; if (abs(station) == 1) xbin = ring; if (station > 0) xbin = xbin + 9; else xbin = 10 - xbin; // To avoid holes in xAxis, I can't imagine right now a simpler way... if (xbin < 5) xbin = 18 * (((Int_t)(xbin / 3)) * 2 + (Int_t)(xbin / 2)) + chamber; else if (xbin < 6) xbin = 108 + chamber; else if (xbin < 14) xbin = 126 + (xbin - 6) * 36 + chamber; else if (xbin < 18) xbin = 414 + 18 * (((Int_t)(xbin - 13) / 3) * 2 + ((Int_t)(xbin - 13) / 2)) + chamber; else xbin = 522 + chamber; snprintf(binLabel, sizeof(binLabel), "ME%d/%dC%d", station, ring, chamber); hprofGlobalThetaCSC->SetMarkerStyle(21); hprofGlobalThetaCSC->SetMarkerColor(kRed); hprofGlobalThetaCSC->SetBinContent(xbin, MeanTheta); hprofGlobalThetaCSC->SetBinError(xbin, ErrorTheta); hprofGlobalThetaCSC->GetXaxis()->SetBinLabel(xbin, binLabel); Int_t ybin = abs(station) * 2 + ring; if (abs(station) == 1) ybin = ring; if (station > 0) ybin = ybin + 9; else ybin = 10 - ybin; ybin = 2 * ybin; hprofGlobalAngleCSC->SetBinContent(chamber, ybin, fabs(MeanTheta)); snprintf(binLabel, sizeof(binLabel), "ME%d/%d_GlobalTheta", station, ring); hprofGlobalAngleCSC->GetYaxis()->SetBinLabel(ybin, binLabel); hprofGlobalAngleRmsCSC->SetBinContent(chamber, ybin, ErrorTheta); hprofGlobalAngleRmsCSC->GetYaxis()->SetBinLabel(ybin, binLabel); } if (nameHistoGlobalRZ.Contains("MB")) // HistoGlobalZ DT { int wheel, station, sector; sscanf(nameHistoGlobalRZ, "ResidualGlobalZ_W%dMB%1dS%d", &wheel, &station, &sector); if (station != 4) { Int_t nstation = station - 1; Int_t nwheel = wheel + 2; Double_t MeanZ = unitsGlobalRZ[i]->GetMean(); Double_t ErrorZ = unitsGlobalRZ[i]->GetMeanError(); Int_t xbin = sector + 14 * nstation + 14 * 4 * nwheel; snprintf(binLabel, sizeof(binLabel), "MB%d/%dS%d", wheel, station, sector); hprofGlobalZDT->SetMarkerStyle(21); hprofGlobalZDT->SetMarkerColor(kRed); hprofGlobalZDT->SetBinContent(xbin, MeanZ); hprofGlobalZDT->SetBinError(xbin, ErrorZ); hprofGlobalZDT->GetXaxis()->SetBinLabel(xbin, binLabel); Int_t ybin = 2 + nwheel * 8 + nstation * 2; hprofGlobalPositionDT->SetBinContent(sector, ybin, fabs(MeanZ)); snprintf(binLabel, sizeof(binLabel), "MB%d/%d_GlobalZ", wheel, station); hprofGlobalPositionDT->GetYaxis()->SetBinLabel(ybin, binLabel); hprofGlobalPositionRmsDT->SetBinContent(sector, ybin, ErrorZ); hprofGlobalPositionRmsDT->GetYaxis()->SetBinLabel(ybin, binLabel); } } if (nameHistoGlobalRZ.Contains("ME")) // HistoGlobalR CSC { int station, ring, chamber; sscanf(nameHistoGlobalRZ, "ResidualGlobalR_ME%dR%1dC%d", &station, &ring, &chamber); Double_t MeanR = unitsGlobalRZ[i]->GetMean(); Double_t ErrorR = unitsGlobalRZ[i]->GetMeanError(); Int_t xbin = abs(station) * 2 + ring; if (abs(station) == 1) xbin = ring; if (station > 0) xbin = xbin + 9; else xbin = 10 - xbin; // To avoid holes in xAxis, I can't imagine right now a simpler way... if (xbin < 5) xbin = 18 * (((Int_t)(xbin / 3)) * 2 + (Int_t)(xbin / 2)) + chamber; else if (xbin < 6) xbin = 108 + chamber; else if (xbin < 14) xbin = 126 + (xbin - 6) * 36 + chamber; else if (xbin < 18) xbin = 414 + 18 * (((Int_t)(xbin - 13) / 3) * 2 + ((Int_t)(xbin - 13) / 2)) + chamber; else xbin = 522 + chamber; snprintf(binLabel, sizeof(binLabel), "ME%d/%dC%d", station, ring, chamber); hprofGlobalRCSC->SetMarkerStyle(21); hprofGlobalRCSC->SetMarkerColor(kRed); hprofGlobalRCSC->SetBinContent(xbin, MeanR); hprofGlobalRCSC->SetBinError(xbin, ErrorR); hprofGlobalRCSC->GetXaxis()->SetBinLabel(xbin, binLabel); Int_t ybin = abs(station) * 2 + ring; if (abs(station) == 1) ybin = ring; if (station > 0) ybin = ybin + 9; else ybin = 10 - ybin; ybin = 2 * ybin; hprofGlobalPositionCSC->SetBinContent(chamber, ybin, fabs(MeanR)); snprintf(binLabel, sizeof(binLabel), "ME%d/%d_GlobalR", station, ring); hprofGlobalPositionCSC->GetYaxis()->SetBinLabel(ybin, binLabel); hprofGlobalPositionRmsCSC->SetBinContent(chamber, ybin, ErrorR); hprofGlobalPositionRmsCSC->GetYaxis()->SetBinLabel(ybin, binLabel); } } // for in histos } // doResPlots } void MuonAlignmentAnalyzer::analyze(const edm::Event &event, const edm::EventSetup &eventSetup) { GlobalVector p1, p2; std::vector<double> simPar[4]; //pt,eta,phi,charge // ######### if data= MC, do Simulation Plots##### if (theDataType == "SimData") { double simEta = 0; double simPt = 0; double simPhi = 0; int i = 0, ie = 0, ib = 0; // Get the SimTrack collection from the event const edm::Handle<edm::SimTrackContainer> &simTracks = event.getHandle(simTrackToken_); edm::SimTrackContainer::const_iterator simTrack; for (simTrack = simTracks->begin(); simTrack != simTracks->end(); ++simTrack) { if (abs((*simTrack).type()) == 13) { i++; simPt = (*simTrack).momentum().Pt(); simEta = (*simTrack).momentum().eta(); simPhi = (*simTrack).momentum().phi(); numberOfSimTracks++; hSimPT->Fill(simPt); if (fabs(simEta) < 1.04) { hSimPT_Barrel->Fill(simPt); ib++; } else { hSimPT_Endcap->Fill(simPt); ie++; } hSimPTvsEta->Fill(simEta, simPt); hSimPTvsPhi->Fill(simPhi, simPt); hSimPhivsEta->Fill(simEta, simPhi); simPar[0].push_back(simPt); simPar[1].push_back(simEta); simPar[2].push_back(simPhi); simPar[3].push_back((*simTrack).charge()); // Save the muon pair if (i == 1) p1 = GlobalVector((*simTrack).momentum().x(), (*simTrack).momentum().y(), (*simTrack).momentum().z()); if (i == 2) p2 = GlobalVector((*simTrack).momentum().x(), (*simTrack).momentum().y(), (*simTrack).momentum().z()); } } hSimNmuons->Fill(i); hSimNmuons_Barrel->Fill(ib); hSimNmuons_Endcap->Fill(ie); if (i > 1) { // Take 2 first muons :-( TLorentzVector mu1(p1.x(), p1.y(), p1.z(), p1.mag()); TLorentzVector mu2(p2.x(), p2.y(), p2.z(), p2.mag()); TLorentzVector pair = mu1 + mu2; double Minv = pair.M(); hSimInvM->Fill(Minv); if (fabs(p1.eta()) < 1.04 && fabs(p2.eta()) < 1.04) hSimInvM_Barrel->Fill(Minv); else if (fabs(p1.eta()) >= 1.04 && fabs(p2.eta()) >= 1.04) hSimInvM_Endcap->Fill(Minv); else hSimInvM_Overlap->Fill(Minv); } } //simData // ############ Stand Alone Muon plots ############### if (doSAplots) { double SArecPt = 0.; double SAeta = 0.; double SAphi = 0.; int i = 0, ie = 0, ib = 0; double ich = 0; // Get the RecTrack collection from the event const edm::Handle<reco::TrackCollection> &staTracks = event.getHandle(staTrackToken_); numberOfSARecTracks += staTracks->size(); reco::TrackCollection::const_iterator staTrack; for (staTrack = staTracks->begin(); staTrack != staTracks->end(); ++staTrack) { i++; SArecPt = (*staTrack).pt(); SAeta = (*staTrack).eta(); SAphi = (*staTrack).phi(); ich = (*staTrack).charge(); hSAPTRec->Fill(SArecPt); hSAPhivsEta->Fill(SAeta, SAphi); hSAChi2->Fill((*staTrack).chi2()); hSANhits->Fill((*staTrack).numberOfValidHits()); if (fabs(SAeta) < 1.04) { hSAPTRec_Barrel->Fill(SArecPt); hSAChi2_Barrel->Fill((*staTrack).chi2()); hSANhits_Barrel->Fill((*staTrack).numberOfValidHits()); ib++; } else { hSAPTRec_Endcap->Fill(SArecPt); hSAChi2_Endcap->Fill((*staTrack).chi2()); hSANhits_Endcap->Fill((*staTrack).numberOfValidHits()); ie++; } // save the muon pair if (i == 1) p1 = GlobalVector((*staTrack).momentum().x(), (*staTrack).momentum().y(), (*staTrack).momentum().z()); if (i == 2) p2 = GlobalVector((*staTrack).momentum().x(), (*staTrack).momentum().y(), (*staTrack).momentum().z()); if (SArecPt && theDataType == "SimData") { double candDeltaR = -999.0, dR; int iCand = 0; if (!simPar[0].empty()) { for (unsigned int iSim = 0; iSim < simPar[0].size(); iSim++) { dR = deltaR(SAeta, SAphi, simPar[1][iSim], simPar[2][iSim]); if (candDeltaR < 0 || dR < candDeltaR) { candDeltaR = dR; iCand = iSim; } } } double simPt = simPar[0][iCand]; hSAPTres->Fill((SArecPt - simPt) / simPt); if (fabs(SAeta) < 1.04) hSAPTres_Barrel->Fill((SArecPt - simPt) / simPt); else hSAPTres_Endcap->Fill((SArecPt - simPt) / simPt); hSAPTDiff->Fill(SArecPt - simPt); hSAPTDiffvsEta->Fill(SAeta, SArecPt - simPt); hSAPTDiffvsPhi->Fill(SAphi, SArecPt - simPt); double ptInvRes = (ich / SArecPt - simPar[3][iCand] / simPt) / (simPar[3][iCand] / simPt); hSAinvPTres->Fill(ptInvRes); hSAinvPTvsEta->Fill(SAeta, ptInvRes); hSAinvPTvsPhi->Fill(SAphi, ptInvRes); hSAinvPTvsNhits->Fill((*staTrack).numberOfValidHits(), ptInvRes); } hSAPTvsEta->Fill(SAeta, SArecPt); hSAPTvsPhi->Fill(SAphi, SArecPt); } hSANmuons->Fill(i); hSANmuons_Barrel->Fill(ib); hSANmuons_Endcap->Fill(ie); if (i > 1) { // Take 2 first muons :-( TLorentzVector mu1(p1.x(), p1.y(), p1.z(), p1.mag()); TLorentzVector mu2(p2.x(), p2.y(), p2.z(), p2.mag()); TLorentzVector pair = mu1 + mu2; double Minv = pair.M(); hSAInvM->Fill(Minv); if (fabs(p1.eta()) < 1.04 && fabs(p2.eta()) < 1.04) hSAInvM_Barrel->Fill(Minv); else if (fabs(p1.eta()) >= 1.04 && fabs(p2.eta()) >= 1.04) hSAInvM_Endcap->Fill(Minv); else hSAInvM_Overlap->Fill(Minv); } // 2 first muons } //end doSAplots // ############### Global Muons plots ########## if (doGBplots) { // Get the RecTrack collection from the event const edm::Handle<reco::TrackCollection> &glbTracks = event.getHandle(glbTrackToken_); numberOfGBRecTracks += glbTracks->size(); double GBrecPt = 0; double GBeta = 0; double GBphi = 0; double ich = 0; int i = 0, ie = 0, ib = 0; reco::TrackCollection::const_iterator glbTrack; for (glbTrack = glbTracks->begin(); glbTrack != glbTracks->end(); ++glbTrack) { i++; GBrecPt = (*glbTrack).pt(); GBeta = (*glbTrack).eta(); GBphi = (*glbTrack).phi(); ich = (*glbTrack).charge(); hGBPTRec->Fill(GBrecPt); hGBPhivsEta->Fill(GBeta, GBphi); hGBChi2->Fill((*glbTrack).chi2()); hGBNhits->Fill((*glbTrack).numberOfValidHits()); if (fabs(GBeta) < 1.04) { hGBPTRec_Barrel->Fill(GBrecPt); hGBChi2_Barrel->Fill((*glbTrack).chi2()); hGBNhits_Barrel->Fill((*glbTrack).numberOfValidHits()); ib++; } else { hGBPTRec_Endcap->Fill(GBrecPt); hGBChi2_Endcap->Fill((*glbTrack).chi2()); hGBNhits_Endcap->Fill((*glbTrack).numberOfValidHits()); ie++; } // save the muon pair if (i == 1) p1 = GlobalVector((*glbTrack).momentum().x(), (*glbTrack).momentum().y(), (*glbTrack).momentum().z()); if (i == 2) p2 = GlobalVector((*glbTrack).momentum().x(), (*glbTrack).momentum().y(), (*glbTrack).momentum().z()); if (GBrecPt && theDataType == "SimData") { double candDeltaR = -999.0, dR; int iCand = 0; if (!simPar[0].empty()) { for (unsigned int iSim = 0; iSim < simPar[0].size(); iSim++) { dR = deltaR(GBeta, GBphi, simPar[1][iSim], simPar[2][iSim]); if (candDeltaR < 0 || dR < candDeltaR) { candDeltaR = dR; iCand = iSim; } } } double simPt = simPar[0][iCand]; hGBPTres->Fill((GBrecPt - simPt) / simPt); if (fabs(GBeta) < 1.04) hGBPTres_Barrel->Fill((GBrecPt - simPt) / simPt); else hGBPTres_Endcap->Fill((GBrecPt - simPt) / simPt); hGBPTDiff->Fill(GBrecPt - simPt); hGBPTDiffvsEta->Fill(GBeta, GBrecPt - simPt); hGBPTDiffvsPhi->Fill(GBphi, GBrecPt - simPt); double ptInvRes = (ich / GBrecPt - simPar[3][iCand] / simPt) / (simPar[3][iCand] / simPt); hGBinvPTres->Fill(ptInvRes); hGBinvPTvsEta->Fill(GBeta, ptInvRes); hGBinvPTvsPhi->Fill(GBphi, ptInvRes); hGBinvPTvsNhits->Fill((*glbTrack).numberOfValidHits(), ptInvRes); } hGBPTvsEta->Fill(GBeta, GBrecPt); hGBPTvsPhi->Fill(GBphi, GBrecPt); } hGBNmuons->Fill(i); hGBNmuons_Barrel->Fill(ib); hGBNmuons_Endcap->Fill(ie); if (i > 1) { // Take 2 first muons :-( TLorentzVector mu1(p1.x(), p1.y(), p1.z(), p1.mag()); TLorentzVector mu2(p2.x(), p2.y(), p2.z(), p2.mag()); TLorentzVector pair = mu1 + mu2; double Minv = pair.M(); hGBInvM->Fill(Minv); if (fabs(p1.eta()) < 1.04 && fabs(p2.eta()) < 1.04) hGBInvM_Barrel->Fill(Minv); else if (fabs(p1.eta()) >= 1.04 && fabs(p2.eta()) >= 1.04) hGBInvM_Endcap->Fill(Minv); else hGBInvM_Overlap->Fill(Minv); } } //end doGBplots // ############ Residual plots ################### if (doResplots) { const MagneticField *theMGField = &eventSetup.getData(magFieldToken_); const edm::ESHandle<GlobalTrackingGeometry> &theTrackingGeometry = eventSetup.getHandle(trackingGeometryToken_); // Get the RecTrack collection from the event const edm::Handle<reco::TrackCollection> &staTracks = event.getHandle(staTrackToken_); // Get the 4D DTSegments const edm::Handle<DTRecSegment4DCollection> &all4DSegmentsDT = event.getHandle(allDTSegmentToken_); DTRecSegment4DCollection::const_iterator segmentDT; // Get the 4D CSCSegments const edm::Handle<CSCSegmentCollection> &all4DSegmentsCSC = event.getHandle(allCSCSegmentToken_); CSCSegmentCollection::const_iterator segmentCSC; //Vectors used to perform the matching between Segments and hits from Track intDVector indexCollectionDT; intDVector indexCollectionCSC; /* std::cout << "<MuonAlignmentAnalyzer> List of DTSegments found in Local Reconstruction" << std::endl; std::cout << "Number: " << all4DSegmentsDT->size() << std::endl; for (segmentDT = all4DSegmentsDT->begin(); segmentDT != all4DSegmentsDT->end(); ++segmentDT){ const GeomDet* geomDet = theTrackingGeometry->idToDet((*segmentDT).geographicalId()); std::cout << "<MuonAlignmentAnalyzer> " << geomDet->toGlobal((*segmentDT).localPosition()) << std::endl; std::cout << "<MuonAlignmentAnalyzer> Local " << (*segmentDT).localPosition() << std::endl; } std::cout << "<MuonAlignmentAnalyzer> List of CSCSegments found in Local Reconstruction" << std::endl; for (segmentCSC = all4DSegmentsCSC->begin(); segmentCSC != all4DSegmentsCSC->end(); ++segmentCSC){ const GeomDet* geomDet = theTrackingGeometry->idToDet((*segmentCSC).geographicalId()); std::cout << "<MuonAlignmentAnalyzer>" << geomDet->toGlobal((*segmentCSC).localPosition()) << std::endl; } */ thePropagator = new SteppingHelixPropagator(theMGField, alongMomentum); reco::TrackCollection::const_iterator staTrack; for (staTrack = staTracks->begin(); staTrack != staTracks->end(); ++staTrack) { int countPoints = 0; reco::TransientTrack track(*staTrack, theMGField, theTrackingGeometry); if (staTrack->numberOfValidHits() > (min1DTrackRecHitSize - 1)) { RecHitVector my4DTrack = this->doMatching( *staTrack, all4DSegmentsDT, all4DSegmentsCSC, &indexCollectionDT, &indexCollectionCSC, theTrackingGeometry); //cut in number of segments if (my4DTrack.size() > (min4DTrackSegmentSize - 1)) { // start propagation // TrajectoryStateOnSurface innerTSOS = track.impactPointState(); TrajectoryStateOnSurface innerTSOS = track.innermostMeasurementState(); //If the state is valid if (innerTSOS.isValid()) { //Loop over Associated segments for (RecHitVector::iterator rechit = my4DTrack.begin(); rechit != my4DTrack.end(); ++rechit) { const GeomDet *geomDet = theTrackingGeometry->idToDet((*rechit)->geographicalId()); //Otherwise the propagator could throw an exception const Plane *pDest = dynamic_cast<const Plane *>(&geomDet->surface()); const Cylinder *cDest = dynamic_cast<const Cylinder *>(&geomDet->surface()); if (pDest != nullptr || cDest != nullptr) { //Donde antes iba el try TrajectoryStateOnSurface destiny = thePropagator->propagate(*(innerTSOS.freeState()), geomDet->surface()); if (!destiny.isValid() || !destiny.hasError()) continue; /* std::cout << "<MuonAlignmentAnalyzer> Segment: " << geomDet->toGlobal((*rechit)->localPosition()) << std::endl; std::cout << "<MuonAlignmentAnalyzer> Segment local: " << (*rechit)->localPosition() << std::endl; std::cout << "<MuonAlignmentAnalyzer> Predicted: " << destiny.freeState()->position() << std::endl; std::cout << "<MuonAlignmentAnalyzer> Predicted local: " << destiny.localPosition() << std::endl; */ const long rawId = (*rechit)->geographicalId().rawId(); int position = -1; bool newDetector = true; //Loop over the DetectorCollection to see if the detector is new and requires a new entry for (std::vector<long>::iterator myIds = detectorCollection.begin(); myIds != detectorCollection.end(); myIds++) { ++position; //If matches newDetector = false if (*myIds == rawId) { newDetector = false; break; } } DetId myDet(rawId); int det = myDet.subdetId(); int wheel = 0, station = 0, sector = 0; int endcap = 0, ring = 0, chamber = 0; double residualGlobalRPhi = 0, residualGlobalPhi = 0, residualGlobalR = 0, residualGlobalTheta = 0, residualGlobalZ = 0; double residualLocalX = 0, residualLocalPhi = 0, residualLocalY = 0, residualLocalTheta = 0; // Fill generic histograms //If it's a DT if (det == 1) { DTChamberId myChamber(rawId); wheel = myChamber.wheel(); station = myChamber.station(); sector = myChamber.sector(); //global residualGlobalRPhi = geomDet->toGlobal((*rechit)->localPosition()).perp() * geomDet->toGlobal((*rechit)->localPosition()).barePhi() - destiny.freeState()->position().perp() * destiny.freeState()->position().barePhi(); //local residualLocalX = (*rechit)->localPosition().x() - destiny.localPosition().x(); //global residualGlobalPhi = geomDet->toGlobal(((RecSegment *)(*rechit))->localDirection()).barePhi() - destiny.globalDirection().barePhi(); //local residualLocalPhi = atan2(((RecSegment *)(*rechit))->localDirection().z(), ((RecSegment *)(*rechit))->localDirection().x()) - atan2(destiny.localDirection().z(), destiny.localDirection().x()); hResidualGlobalRPhiDT->Fill(residualGlobalRPhi); hResidualGlobalPhiDT->Fill(residualGlobalPhi); hResidualLocalXDT->Fill(residualLocalX); hResidualLocalPhiDT->Fill(residualLocalPhi); if (station != 4) { //global residualGlobalZ = geomDet->toGlobal((*rechit)->localPosition()).z() - destiny.freeState()->position().z(); //local residualLocalY = (*rechit)->localPosition().y() - destiny.localPosition().y(); //global residualGlobalTheta = geomDet->toGlobal(((RecSegment *)(*rechit))->localDirection()).bareTheta() - destiny.globalDirection().bareTheta(); //local residualLocalTheta = atan2(((RecSegment *)(*rechit))->localDirection().z(), ((RecSegment *)(*rechit))->localDirection().y()) - atan2(destiny.localDirection().z(), destiny.localDirection().y()); hResidualGlobalThetaDT->Fill(residualGlobalTheta); hResidualGlobalZDT->Fill(residualGlobalZ); hResidualLocalThetaDT->Fill(residualLocalTheta); hResidualLocalYDT->Fill(residualLocalY); } int index = wheel + 2; hResidualGlobalRPhiDT_W[index]->Fill(residualGlobalRPhi); hResidualGlobalPhiDT_W[index]->Fill(residualGlobalPhi); hResidualLocalXDT_W[index]->Fill(residualLocalX); hResidualLocalPhiDT_W[index]->Fill(residualLocalPhi); if (station != 4) { hResidualGlobalThetaDT_W[index]->Fill(residualGlobalTheta); hResidualGlobalZDT_W[index]->Fill(residualGlobalZ); hResidualLocalThetaDT_W[index]->Fill(residualLocalTheta); hResidualLocalYDT_W[index]->Fill(residualLocalY); } index = wheel * 4 + station + 7; hResidualGlobalRPhiDT_MB[index]->Fill(residualGlobalRPhi); hResidualGlobalPhiDT_MB[index]->Fill(residualGlobalPhi); hResidualLocalXDT_MB[index]->Fill(residualLocalX); hResidualLocalPhiDT_MB[index]->Fill(residualLocalPhi); if (station != 4) { hResidualGlobalThetaDT_MB[index]->Fill(residualGlobalTheta); hResidualGlobalZDT_MB[index]->Fill(residualGlobalZ); hResidualLocalThetaDT_MB[index]->Fill(residualLocalTheta); hResidualLocalYDT_MB[index]->Fill(residualLocalY); } } else if (det == 2) { CSCDetId myChamber(rawId); endcap = myChamber.endcap(); station = myChamber.station(); if (endcap == 2) station = -station; ring = myChamber.ring(); chamber = myChamber.chamber(); //global residualGlobalRPhi = geomDet->toGlobal((*rechit)->localPosition()).perp() * geomDet->toGlobal((*rechit)->localPosition()).barePhi() - destiny.freeState()->position().perp() * destiny.freeState()->position().barePhi(); //local residualLocalX = (*rechit)->localPosition().x() - destiny.localPosition().x(); //global residualGlobalR = geomDet->toGlobal((*rechit)->localPosition()).perp() - destiny.freeState()->position().perp(); //local residualLocalY = (*rechit)->localPosition().y() - destiny.localPosition().y(); //global residualGlobalPhi = geomDet->toGlobal(((RecSegment *)(*rechit))->localDirection()).barePhi() - destiny.globalDirection().barePhi(); //local residualLocalPhi = atan2(((RecSegment *)(*rechit))->localDirection().y(), ((RecSegment *)(*rechit))->localDirection().x()) - atan2(destiny.localDirection().y(), destiny.localDirection().x()); //global residualGlobalTheta = geomDet->toGlobal(((RecSegment *)(*rechit))->localDirection()).bareTheta() - destiny.globalDirection().bareTheta(); //local residualLocalTheta = atan2(((RecSegment *)(*rechit))->localDirection().y(), ((RecSegment *)(*rechit))->localDirection().z()) - atan2(destiny.localDirection().y(), destiny.localDirection().z()); hResidualGlobalRPhiCSC->Fill(residualGlobalRPhi); hResidualGlobalPhiCSC->Fill(residualGlobalPhi); hResidualGlobalThetaCSC->Fill(residualGlobalTheta); hResidualGlobalRCSC->Fill(residualGlobalR); hResidualLocalXCSC->Fill(residualLocalX); hResidualLocalPhiCSC->Fill(residualLocalPhi); hResidualLocalThetaCSC->Fill(residualLocalTheta); hResidualLocalYCSC->Fill(residualLocalY); int index = 2 * station + ring + 7; if (station == -1) { index = 5 + ring; if (ring == 4) index = 6; } if (station == 1) { index = 8 + ring; if (ring == 4) index = 9; } hResidualGlobalRPhiCSC_ME[index]->Fill(residualGlobalRPhi); hResidualGlobalPhiCSC_ME[index]->Fill(residualGlobalPhi); hResidualGlobalThetaCSC_ME[index]->Fill(residualGlobalTheta); hResidualGlobalRCSC_ME[index]->Fill(residualGlobalR); hResidualLocalXCSC_ME[index]->Fill(residualLocalX); hResidualLocalPhiCSC_ME[index]->Fill(residualLocalPhi); hResidualLocalThetaCSC_ME[index]->Fill(residualLocalTheta); hResidualLocalYCSC_ME[index]->Fill(residualLocalY); } else { residualGlobalRPhi = 0, residualGlobalPhi = 0, residualGlobalR = 0, residualGlobalTheta = 0, residualGlobalZ = 0; residualLocalX = 0, residualLocalPhi = 0, residualLocalY = 0, residualLocalTheta = 0; } // Fill individual chamber histograms if (newDetector) { //Create an RawIdDetector, fill it and push it into the collection detectorCollection.push_back(rawId); //This piece of code calculates the range of the residuals double rangeX = 3.0, rangeY = 5.; switch (abs(station)) { case 1: { rangeX = resLocalXRangeStation1; rangeY = resLocalYRangeStation1; } break; case 2: { rangeX = resLocalXRangeStation2; rangeY = resLocalYRangeStation2; } break; case 3: { rangeX = resLocalXRangeStation3; rangeY = resLocalYRangeStation3; } break; case 4: { rangeX = resLocalXRangeStation4; rangeY = resLocalYRangeStation4; } break; default: break; } //create new histograms char nameOfHistoLocalX[50]; char nameOfHistoLocalTheta[50]; char nameOfHistoLocalY[50]; char nameOfHistoLocalPhi[50]; char nameOfHistoGlobalRPhi[50]; char nameOfHistoGlobalTheta[50]; char nameOfHistoGlobalR[50]; char nameOfHistoGlobalPhi[50]; char nameOfHistoGlobalZ[50]; if (det == 1) { // DT snprintf(nameOfHistoLocalX, sizeof(nameOfHistoLocalX), "ResidualLocalX_W%dMB%1dS%1d", wheel, station, sector); snprintf(nameOfHistoLocalPhi, sizeof(nameOfHistoLocalPhi), "ResidualLocalPhi_W%dMB%1dS%1d", wheel, station, sector); snprintf(nameOfHistoGlobalRPhi, sizeof(nameOfHistoGlobalRPhi), "ResidualGlobalRPhi_W%dMB%1dS%1d", wheel, station, sector); snprintf(nameOfHistoGlobalPhi, sizeof(nameOfHistoGlobalPhi), "ResidualGlobalPhi_W%dMB%1dS%1d", wheel, station, sector); snprintf(nameOfHistoLocalTheta, sizeof(nameOfHistoLocalTheta), "ResidualLocalTheta_W%dMB%1dS%1d", wheel, station, sector); snprintf(nameOfHistoLocalY, sizeof(nameOfHistoLocalY), "ResidualLocalY_W%dMB%1dS%1d", wheel, station, sector); TH1F *histoLocalY = fs->make<TH1F>(nameOfHistoLocalY, nameOfHistoLocalY, nbins, -rangeY, rangeY); unitsLocalY.push_back(histoLocalY); snprintf(nameOfHistoGlobalTheta, sizeof(nameOfHistoGlobalTheta), "ResidualGlobalTheta_W%dMB%1dS%1d", wheel, station, sector); snprintf(nameOfHistoGlobalZ, sizeof(nameOfHistoGlobalZ), "ResidualGlobalZ_W%dMB%1dS%1d", wheel, station, sector); TH1F *histoGlobalZ = fs->make<TH1F>(nameOfHistoGlobalZ, nameOfHistoGlobalZ, nbins, -rangeY, rangeY); unitsGlobalRZ.push_back(histoGlobalZ); } else if (det == 2) { //CSC snprintf(nameOfHistoLocalX, sizeof(nameOfHistoLocalX), "ResidualLocalX_ME%dR%1dC%1d", station, ring, chamber); snprintf(nameOfHistoLocalPhi, sizeof(nameOfHistoLocalPhi), "ResidualLocalPhi_ME%dR%1dC%1d", station, ring, chamber); snprintf(nameOfHistoLocalTheta, sizeof(nameOfHistoLocalTheta), "ResidualLocalTheta_ME%dR%1dC%1d", station, ring, chamber); snprintf(nameOfHistoLocalY, sizeof(nameOfHistoLocalY), "ResidualLocalY_ME%dR%1dC%1d", station, ring, chamber); TH1F *histoLocalY = fs->make<TH1F>(nameOfHistoLocalY, nameOfHistoLocalY, nbins, -rangeY, rangeY); unitsLocalY.push_back(histoLocalY); snprintf(nameOfHistoGlobalRPhi, sizeof(nameOfHistoGlobalRPhi), "ResidualGlobalRPhi_ME%dR%1dC%1d", station, ring, chamber); snprintf(nameOfHistoGlobalPhi, sizeof(nameOfHistoGlobalPhi), "ResidualGlobalPhi_ME%dR%1dC%1d", station, ring, chamber); snprintf(nameOfHistoGlobalTheta, sizeof(nameOfHistoGlobalTheta), "ResidualGlobalTheta_ME%dR%1dC%1d", station, ring, chamber); snprintf(nameOfHistoGlobalR, sizeof(nameOfHistoGlobalR), "ResidualGlobalR_ME%dR%1dC%1d", station, ring, chamber); TH1F *histoGlobalR = fs->make<TH1F>(nameOfHistoGlobalR, nameOfHistoGlobalR, nbins, -rangeY, rangeY); unitsGlobalRZ.push_back(histoGlobalR); } // Common histos to DT and CSC TH1F *histoLocalX = fs->make<TH1F>(nameOfHistoLocalX, nameOfHistoLocalX, nbins, -rangeX, rangeX); TH1F *histoGlobalRPhi = fs->make<TH1F>(nameOfHistoGlobalRPhi, nameOfHistoGlobalRPhi, nbins, -rangeX, rangeX); TH1F *histoLocalPhi = fs->make<TH1F>(nameOfHistoLocalPhi, nameOfHistoLocalPhi, nbins, -resPhiRange, resPhiRange); TH1F *histoGlobalPhi = fs->make<TH1F>(nameOfHistoGlobalPhi, nameOfHistoGlobalPhi, nbins, -resPhiRange, resPhiRange); TH1F *histoGlobalTheta = fs->make<TH1F>( nameOfHistoGlobalTheta, nameOfHistoGlobalTheta, nbins, -resThetaRange, resThetaRange); TH1F *histoLocalTheta = fs->make<TH1F>( nameOfHistoLocalTheta, nameOfHistoLocalTheta, nbins, -resThetaRange, resThetaRange); histoLocalX->Fill(residualLocalX); histoLocalPhi->Fill(residualLocalPhi); histoLocalTheta->Fill(residualLocalTheta); histoGlobalRPhi->Fill(residualGlobalRPhi); histoGlobalPhi->Fill(residualGlobalPhi); histoGlobalTheta->Fill(residualGlobalTheta); //Push them into their respective vectors unitsLocalX.push_back(histoLocalX); unitsLocalPhi.push_back(histoLocalPhi); unitsLocalTheta.push_back(histoLocalTheta); unitsGlobalRPhi.push_back(histoGlobalRPhi); unitsGlobalPhi.push_back(histoGlobalPhi); unitsGlobalTheta.push_back(histoGlobalTheta); } // new detector else { //If the detector was not new, just fill the histogram unitsLocalX.at(position)->Fill(residualLocalX); unitsLocalPhi.at(position)->Fill(residualLocalPhi); unitsLocalTheta.at(position)->Fill(residualLocalTheta); unitsGlobalRPhi.at(position)->Fill(residualGlobalRPhi); unitsGlobalPhi.at(position)->Fill(residualGlobalPhi); unitsGlobalTheta.at(position)->Fill(residualGlobalTheta); if (det == 1) { unitsLocalY.at(position)->Fill(residualLocalY); unitsGlobalRZ.at(position)->Fill(residualGlobalZ); } else if (det == 2) { unitsLocalY.at(position)->Fill(residualLocalY); unitsGlobalRZ.at(position)->Fill(residualGlobalR); } } countPoints++; innerTSOS = destiny; } else { edm::LogError("MuonAlignmentAnalyzer") << " Error!! Exception in propagator catched" << std::endl; continue; } } //loop over my4DTrack } //TSOS was valid } // cut in at least 4 segments } //end cut in RecHitsSize>36 numberOfHits = numberOfHits + countPoints; } //loop over STAtracks delete thePropagator; } //end doResplots } RecHitVector MuonAlignmentAnalyzer::doMatching(const reco::Track &staTrack, const edm::Handle<DTRecSegment4DCollection> &all4DSegmentsDT, const edm::Handle<CSCSegmentCollection> &all4DSegmentsCSC, intDVector *indexCollectionDT, intDVector *indexCollectionCSC, const edm::ESHandle<GlobalTrackingGeometry> &theTrackingGeometry) { DTRecSegment4DCollection::const_iterator segmentDT; CSCSegmentCollection::const_iterator segmentCSC; std::vector<int> positionDT; std::vector<int> positionCSC; RecHitVector my4DTrack; //Loop over the hits of the track for (int counter = 0; counter != staTrack.numberOfValidHits() - 1; counter++) { TrackingRecHitRef myRef = staTrack.recHit(counter); const TrackingRecHit *rechit = myRef.get(); const GeomDet *geomDet = theTrackingGeometry->idToDet(rechit->geographicalId()); //It's a DT Hit if (geomDet->subDetector() == GeomDetEnumerators::DT) { //Take the layer associated to this hit DTLayerId myLayer(rechit->geographicalId().rawId()); int NumberOfDTSegment = 0; //Loop over segments for (segmentDT = all4DSegmentsDT->begin(); segmentDT != all4DSegmentsDT->end(); ++segmentDT) { //By default the chamber associated to this Segment is new bool isNewChamber = true; //Loop over segments already included in the vector of segments in the actual track for (std::vector<int>::iterator positionIt = positionDT.begin(); positionIt != positionDT.end(); positionIt++) { //If this segment has been used before isNewChamber = false if (NumberOfDTSegment == *positionIt) isNewChamber = false; } //Loop over vectors of segments associated to previous tracks for (std::vector<std::vector<int> >::iterator collect = indexCollectionDT->begin(); collect != indexCollectionDT->end(); ++collect) { //Loop over segments associated to a track for (std::vector<int>::iterator positionIt = (*collect).begin(); positionIt != (*collect).end(); positionIt++) { //If this segment was used in a previos track then isNewChamber = false if (NumberOfDTSegment == *positionIt) isNewChamber = false; } } //If the chamber is new if (isNewChamber) { DTChamberId myChamber((*segmentDT).geographicalId().rawId()); //If the layer of the hit belongs to the chamber of the 4D Segment if (myLayer.wheel() == myChamber.wheel() && myLayer.station() == myChamber.station() && myLayer.sector() == myChamber.sector()) { //push position of the segment and tracking rechit positionDT.push_back(NumberOfDTSegment); my4DTrack.push_back((TrackingRecHit *)&(*segmentDT)); } } NumberOfDTSegment++; } //In case is a CSC } else if (geomDet->subDetector() == GeomDetEnumerators::CSC) { //Take the layer associated to this hit CSCDetId myLayer(rechit->geographicalId().rawId()); int NumberOfCSCSegment = 0; //Loop over 4Dsegments for (segmentCSC = all4DSegmentsCSC->begin(); segmentCSC != all4DSegmentsCSC->end(); segmentCSC++) { //By default the chamber associated to the segment is new bool isNewChamber = true; //Loop over segments in the current track for (std::vector<int>::iterator positionIt = positionCSC.begin(); positionIt != positionCSC.end(); positionIt++) { //If this segment has been used then newchamber = false if (NumberOfCSCSegment == *positionIt) isNewChamber = false; } //Loop over vectors of segments in previous tracks for (std::vector<std::vector<int> >::iterator collect = indexCollectionCSC->begin(); collect != indexCollectionCSC->end(); ++collect) { //Loop over segments in a track for (std::vector<int>::iterator positionIt = (*collect).begin(); positionIt != (*collect).end(); positionIt++) { //If the segment was used in a previous track isNewChamber = false if (NumberOfCSCSegment == *positionIt) isNewChamber = false; } } //If the chamber is new if (isNewChamber) { CSCDetId myChamber((*segmentCSC).geographicalId().rawId()); //If the chambers are the same if (myLayer.chamberId() == myChamber.chamberId()) { //push positionCSC.push_back(NumberOfCSCSegment); my4DTrack.push_back((TrackingRecHit *)&(*segmentCSC)); } } NumberOfCSCSegment++; } } } indexCollectionDT->push_back(positionDT); indexCollectionCSC->push_back(positionCSC); return my4DTrack; } DEFINE_FWK_MODULE(MuonAlignmentAnalyzer);
2735a931ea47bc46a55b5a6db36702aa0dc4885a
b47a67b1293864730ec4d8dc231c01e408c200fa
/lessons/02-branches/src/exercise_01_sol.cpp
b3dd2ecc20369f53eee591a39bdaf87e15fdb040
[ "BSD-3-Clause" ]
permissive
alvarovm/LearnCPP11
4f04b20fcc767f95692c39aecb8d696a907c6ccd
025a6e043c6eadb61324c261168bbd0478d9690b
refs/heads/master
2021-09-16T11:05:35.555785
2018-06-20T00:17:17
2018-06-20T00:17:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,520
cpp
exercise_01_sol.cpp
#include <iostream> int main(int argc, char** argv) { // Usage printing if less than two arguments if (argc < 3) { std::cout << "Usage: " << argv[0] << " <char1> <char2>\n"; return 0; } // Assigning the characters to c1 and c2 char c1 = *argv[1]; char c2 = *argv[2]; // Checking if they are capital or lower case bool isLower1 = false; bool isLower2 = false; bool isCapital1 = false; bool isCapital2 = false; if (c1 >= 'A' && c1 <= 'Z') { isCapital1 = true; } if (c1 >= 'a' && c1 <= 'z') { isLower1 = true; } if (c2 >= 'A' && c2 <= 'Z') { isCapital2 = true; } if (c2 >= 'a' && c2 <= 'z') { isLower2 = true; } // Checking if they are letters bool isLetter1 = false; bool isLetter2 = false; if (isCapital1 || isLower1) { isLetter1 = true; } if (isCapital2 || isLower2) { isLetter2 = true; } // Printing in case one of them is not a letter if (!isLetter1) { std::cout << "ERROR: " << c1 << " is not a letter\n"; return 0; } else if (!isLetter2) { std::cout << "ERROR: " << c2 << " is not a letter\n"; return 0; } // Checking if they are both lower case or upper case if (isLower1 && isLower2) { std::cout << "The two letters " << c1 << " and " << c2 << " are lowercase\n"; } else if (isCapital1 && isCapital2) { std::cout << "The two letters " << c1 << " and " << c2 << " are capital\n"; } return 0; }
e4a08f2324c7034cce33d9d3dc164335a7c17aa4
d1ffdefc460487f97c937df25f10c40cf150797a
/leNet.h
bdf1822c49be35566da7ef20018ba54bd3ef5c1a
[]
no_license
saurav2000/Image-Processing-TrainedCNN
cdbe7ff9b4071bcf6fc2f844f0529400592e8462
43a620c70a385fe9a83b17b87ec1c0fc009a92c1
refs/heads/master
2020-04-15T18:43:48.106615
2019-10-20T16:53:50
2019-10-20T16:53:50
164,922,483
0
0
null
null
null
null
UTF-8
C++
false
false
148
h
leNet.h
#include <vector> int leNetArchitecture(std::vector<std::vector<float> > &img, char* c1, char* c2, char* fc1, char* fc2, std::vector<float> &prob);
f7c07c5eb32f96aa8fa8f0a6f4c57bde818656db
20164225b26f3d07893496ecf1b33d294b2d10ff
/entregable/backend-multi/RWLock_sem_librito.h
a9fe61d42bfef1e4fdee16f69a91cc27f9b71f71
[]
no_license
mnsantos/sistemas-tp2
07b0c8cf630fb8b2369f7708238027b852c870ac
0a13d94f5b8c93726f1f55a215ae87899b4a0570
refs/heads/master
2020-05-20T09:39:08.685149
2013-12-09T00:50:01
2013-12-09T00:50:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
348
h
RWLock_sem_librito.h
#ifndef RWLock_h #define RWLock_h #include <iostream> #include <semaphore.h> #include <assert.h> class RWLock { public: RWLock(); ~RWLock(); void rlock(); void wlock(); void runlock(); void wunlock(); private: sem_t turnstile; sem_t roomEmpty; sem_t mutex; int readers; }; #endif
703e1641dc5283507dac9d9623ff955ceda9dc40
8f267f2f54ac5d58f9715eb57e1d279cb5e31e80
/src/core/unittype.hpp
6b469e8780b00f8b588aba21cfb0ff413c8b7c8f
[]
no_license
LodePublishing/Evolution-Forge-2
d455293b1736abcbacc5277b77aad1e4699b0671
bca5dcd7c652d3b4525a8159bc58d24d5b9b4c4e
refs/heads/master
2021-03-27T10:56:03.473667
2016-12-01T10:38:12
2016-12-01T10:38:12
67,313,513
0
0
null
null
null
null
UTF-8
C++
false
false
3,015
hpp
unittype.hpp
#ifndef _CORE_UNITTYPE_HPP #define _CORE_UNITTYPE_HPP #include <string> #include <list> #include <vector> #pragma warning(push, 0) #include <boost/shared_ptr.hpp> #include <boost/assign/list_of.hpp> #pragma warning(pop) #include <misc/uuid.hpp> #include "unitresourcetype.hpp" #include "race.hpp" #include "enums/unitmovementtype.hpp" class UnitType : public UUID<UnitType> { public: UnitType(const boost::uuids::uuid id, const std::string& name, const boost::shared_ptr<const Race> race, // TODO relevant? const std::list<UnitResourceType>& resources = boost::assign::list_of(UnitResourceType::NOT_BUILDABLE_TYPE), const bool corporeal = false, const unsigned int maxCount = 0, const unsigned int buildTime = 0, const eUnitMovementType movementType = NO_MOVEMENT_TYPE, const unsigned int speed = 0, const unsigned int upgradedSpeed = 0); UnitType(const std::string& name, const boost::shared_ptr<const Race> race, const std::list<UnitResourceType>& resources = boost::assign::list_of(UnitResourceType::NOT_BUILDABLE_TYPE), const bool corporeal = false, const unsigned int maxCount = 0, const unsigned int buildTime = 0, const eUnitMovementType movementType = NO_MOVEMENT_TYPE, const unsigned int speed = 0, const unsigned int upgradedSpeed = 0); ~UnitType(); const std::string& getName() const; const boost::shared_ptr<const Race> getRace() const; const boost::uuids::uuid getRaceId() const; const std::list<UnitResourceType>& getResources() const; // TODO evtl Map machen bool isCorporeal() const; unsigned int getMaxCount() const; unsigned int getBuildTime() const; eUnitMovementType getMovementType() const; unsigned int getSpeed() const; unsigned int getUpgradedSpeed() const; private: // mandatory fields const std::string name; const boost::shared_ptr<const Race> race; const boost::uuids::uuid raceId; const std::list<UnitResourceType> resources; // maximal number of units of this type a player can have const bool corporeal; const unsigned int maxCount; const unsigned int buildTime; const eUnitMovementType movementType; const unsigned int speed; const unsigned int upgradedSpeed; UnitType& operator=(const UnitType& other); }; inline unsigned int UnitType::getBuildTime() const { return buildTime; } inline unsigned int UnitType::getMaxCount() const { return maxCount; } inline const std::string& UnitType::getName() const { return name; } inline const std::list<UnitResourceType>& UnitType::getResources() const { return resources; } inline const boost::shared_ptr<const Race> UnitType::getRace() const { return race; } inline const boost::uuids::uuid UnitType::getRaceId() const { return raceId; } inline bool UnitType::isCorporeal() const { return corporeal; } inline unsigned int UnitType::getSpeed() const { return speed; } inline unsigned int UnitType::getUpgradedSpeed() const { return upgradedSpeed; } inline eUnitMovementType UnitType::getMovementType() const { return movementType; } #endif
236acf9c405b177c4193bf0d717dbef2db0b4b34
06bed8ad5fd60e5bba6297e9870a264bfa91a71d
/JavaQt/imageicon.cpp
277c27b48a6f46e9e31c2aec5df38fedbfc71af1
[]
no_license
allenck/DecoderPro_app
43aeb9561fe3fe9753684f7d6d76146097d78e88
226c7f245aeb6951528d970f773776d50ae2c1dc
refs/heads/master
2023-05-12T07:36:18.153909
2023-05-10T21:17:40
2023-05-10T21:17:40
61,044,197
4
3
null
null
null
null
UTF-8
C++
false
false
20,280
cpp
imageicon.cpp
#include "imageicon.h" ImageIcon::ImageIcon(QObject *parent) : QObject(parent) { init(); } /** * An implementation of the Icon interface that paints Icons * from Images. Images that are created from a URL, filename or byte array * are preloaded using MediaTracker to monitor the loaded state * of the image. * * <p> * For further information and examples of using image icons, see * <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/icon.html">How to Use Icons</a> * in <em>The Java Tutorial.</em> * * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @author Jeff Dinkins * @author Lynn Monsanto */ //public class ImageIcon implements Icon, Serializable, Accessible { /* Keep references to the filename and location so that * alternate persistence schemes have the option to archive * images symbolically rather than including the image data * in the archive. */ // static { // component = AccessController.doPrivileged(new PrivilegedAction<Component>() { // public Component run() { // try { // final Component component = createNoPermsComponent(); // // 6482575 - clear the appContext field so as not to leak it // Field appContextField = // Component.class.getDeclaredField("appContext"); // appContextField.setAccessible(true); // appContextField.set(component, null); // return component; // } catch (Throwable e) { // // We don't care about component. // // So don't prevent class initialisation. // e.printStackTrace(); // return null; // } // } // }); // tracker = new MediaTracker(component); // } // private static Component createNoPermsComponent() { // // 7020198 - set acc field to no permissions and no subject // // Note, will have appContext set. // return AccessController.doPrivileged( // new PrivilegedAction<Component>() { // public Component run() { // return new Component() { // }; // } // }, // new AccessControlContext(new ProtectionDomain[]{ // new ProtectionDomain(null, null) // }) // ); // } void ImageIcon::init() { width = -1; height = -1; loadStatus = 0; } /** * Creates an ImageIcon from the specified file. The image will * be preloaded by using MediaTracker to monitor the loading state * of the image. * @param filename the name of the file containing the image * @param description a brief textual description of the image * @see #ImageIcon(QString) */ /*public*/ ImageIcon::ImageIcon(QString filename, QString description, QObject* parent) : QObject(parent) { init(); //image = Toolkit.getDefaultToolkit().getImage(filename); if(description == "") description = filename; image = QImage(filename); if (image.isNull()) { return; } height = image.height(); width = image.width(); this->filename = filename; if(description.isEmpty()) this->_description = filename; this->_description = description; //loadImage(image); } /** * Creates an ImageIcon from the specified file. The image will * be preloaded by using MediaTracker to monitor the loading state * of the image. The specified QString can be a file name or a * file path. When specifying a path, use the Internet-standard * forward-slash ("/") as a separator. * (The string is converted to an URL, so the forward-slash works * on all systems.) * For example, specify: * <pre> * new ImageIcon("images/myImage.gif") </pre> * The description is initialized to the <code>filename</code> string. * * @param filename a QString specifying a filename or path * @see #getDescription */ //@ConstructorProperties({"description"}) ///*public*/ ImageIcon (QString filename) { // this(filename, filename); //} /** * Creates an ImageIcon from the specified URL. The image will * be preloaded by using MediaTracker to monitor the loaded state * of the image. * @param location the URL for the image * @param description a brief textual description of the image * @see #ImageIcon(QString) */ /*public*/ ImageIcon::ImageIcon(QUrl *location, QString description, QObject* parent) : QObject(parent) { if(description == "") description = filename; init(); //image = Toolkit.getDefaultToolkit().getImage(location); image = QImage(location->toString()); if (image.isNull()) { image = QImage(location->toString(), "GIF"); if(image.isNull()) { image = QImage(location->toString(), "PNG"); if(image.isNull()) return; } } height = image.height(); width = image.width(); this->_location = location; this->_description = description; //loadImage(image); } QString ImageIcon::location() { return _location->toString();} QString ImageIcon::description() { return _description;} ///** // * Creates an ImageIcon from the specified URL. The image will // * be preloaded by using MediaTracker to monitor the loaded state // * of the image. // * The icon's description is initialized to be // * a string representation of the URL. // * @param location the URL for the image // * @see #getDescription // */ ///*public*/ ImageIcon (QUrl location) { // this(location, location.toExternalForm()); //} /** * Creates an ImageIcon from the image. * @param image the image * @param description a brief textual description of the image */ /*public*/ ImageIcon::ImageIcon(QImage image, QString description, QObject *parent) : QObject(parent) { if(description == "") description = filename; init(); //this(image); this->image = image; this->_description = description; height = image.height(); width = image.width(); } /** * Creates an ImageIcon from an image object. * If the image has a "comment" property that is a string, * then the string is used as the description of this icon. * @param image the image * @see #getDescription * @see java.awt.Image#getProperty */ /*public*/ ImageIcon::ImageIcon(QImage image, QObject *parent) : QObject(parent) { init(); this->image = image; height = image.height(); width = image.width(); // Object o = image.getProperty("comment", imageObserver); // if (o instanceof QString) { // description = (QString) o; // } _description = image.text("comment"); // loadImage(image); } #if 0 /** * Creates an ImageIcon from an array of bytes which were * read from an image file containing a supported image format, * such as GIF, JPEG, or (as of 1.3) PNG. * Normally this array is created * by reading an image using Class.getResourceAsStream(), but * the byte array may also be statically stored in a class. * * @param imageData an array of pixels in an image format supported * by the AWT Toolkit, such as GIF, JPEG, or (as of 1.3) PNG * @param description a brief textual description of the image * @see java.awt.Toolkit#createImage */ public ImageIcon (byte[] imageData, QString description) { this.image = Toolkit.getDefaultToolkit().createImage(imageData); if (image == null) { return; } this.description = description; loadImage(image); } /** * Creates an ImageIcon from an array of bytes which were * read from an image file containing a supported image format, * such as GIF, JPEG, or (as of 1.3) PNG. * Normally this array is created * by reading an image using Class.getResourceAsStream(), but * the byte array may also be statically stored in a class. * If the resulting image has a "comment" property that is a string, * then the string is used as the description of this icon. * * @param imageData an array of pixels in an image format supported by * the AWT Toolkit, such as GIF, JPEG, or (as of 1.3) PNG * @see java.awt.Toolkit#createImage * @see #getDescription * @see java.awt.Image#getProperty */ public ImageIcon (byte[] imageData) { this.image = Toolkit.getDefaultToolkit().createImage(imageData); if (image == null) { return; } Object o = image.getProperty("comment", imageObserver); if (o instanceof QString) { description = (QString) o; } loadImage(image); } /** * Creates an uninitialized image icon. */ public ImageIcon() { } /** * Loads the image, returning only when the image is loaded. * @param image the image */ protected void loadImage(Image image) { MediaTracker mTracker = getTracker(); synchronized(mTracker) { int id = getNextID(); mTracker.addImage(image, id); try { mTracker.waitForID(id, 0); } catch (InterruptedException e) { System.out.println("INTERRUPTED while loading Image"); } loadStatus = mTracker.statusID(id, false); mTracker.removeImage(image, id); width = image.getWidth(imageObserver); height = image.getHeight(imageObserver); } } /** * Returns an ID to use with the MediaTracker in loading an image. */ private int getNextID() { synchronized(getTracker()) { return ++mediaTrackerID; } } /** * Returns the MediaTracker for the current AppContext, creating a new * MediaTracker if necessary. */ private MediaTracker getTracker() { Object trackerObj; AppContext ac = AppContext.getAppContext(); // Opt: Only synchronize if trackerObj comes back null? // If null, synchronize, re-check for null, and put new tracker synchronized(ac) { trackerObj = ac.get(TRACKER_KEY); if (trackerObj == null) { Component comp = new Component() {}; trackerObj = new MediaTracker(comp); ac.put(TRACKER_KEY, trackerObj); } } return (MediaTracker) trackerObj; } /** * Returns the status of the image loading operation. * @return the loading status as defined by java.awt.MediaTracker * @see java.awt.MediaTracker#ABORTED * @see java.awt.MediaTracker#ERRORED * @see java.awt.MediaTracker#COMPLETE */ public int getImageLoadStatus() { return loadStatus; } #endif /** * Returns this icon's <code>Image</code>. * @return the <code>Image</code> object for this <code>ImageIcon</code> */ //@Transient /*public*/ QImage ImageIcon::getImage() { return image; } /** * Sets the image displayed by this icon. * @param image the image */ /*public*/ void ImageIcon::setImage(QImage image) { this->image = image; height = image.height(); width = image.width(); // loadImage(image); } /** * Gets the description of the image. This is meant to be a brief * textual description of the object. For example, it might be * presented to a blind user to give an indication of the purpose * of the image. * The description may be null. * * @return a brief textual description of the image */ /*public*/ QString ImageIcon::getDescription() { return _description; } /** * Sets the description of the image. This is meant to be a brief * textual description of the object. For example, it might be * presented to a blind user to give an indication of the purpose * of the image. * @param description a brief textual description of the image */ /*public*/ void ImageIcon::setDescription(QString description) { this->_description = description; } #if 0 /** * Paints the icon. * The top-left corner of the icon is drawn at * the point (<code>x</code>, <code>y</code>) * in the coordinate space of the graphics context <code>g</code>. * If this icon has no image observer, * this method uses the <code>c</code> component * as the observer. * * @param c the component to be used as the observer * if this icon has no image observer * @param g the graphics context * @param x the X coordinate of the icon's top-left corner * @param y the Y coordinate of the icon's top-left corner */ public synchronized void paintIcon(Component c, Graphics g, int x, int y) { if(imageObserver == null) { g.drawImage(image, x, y, c); } else { g.drawImage(image, x, y, imageObserver); } } #endif /** * Gets the width of the icon. * * @return the width in pixels of this icon */ /*public*/ int ImageIcon::getIconWidth() { return width; } /** * Gets the height of the icon. * * @return the height in pixels of this icon */ /*public*/ int ImageIcon::getIconHeight() { return height; } #if 0 /** * Sets the image observer for the image. Set this * property if the ImageIcon contains an animated GIF, so * the observer is notified to update its display. * For example: * <pre> * icon = new ImageIcon(...) * button.setIcon(icon); * icon.setImageObserver(button); * </pre> * * @param observer the image observer */ public void setImageObserver(ImageObserver observer) { imageObserver = observer; } /** * Returns the image observer for the image. * * @return the image observer, which may be null */ @Transient public ImageObserver getImageObserver() { return imageObserver; } #endif /** * Returns a string representation of this image. * * @return a string representing this image */ /*public*/ QString ImageIcon::toString() { if (_description != "") { return _description; } //return super.toString(); return ""; } #if 0 private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException { s.defaultReadObject(); int w = s.readInt(); int h = s.readInt(); int[] pixels = (int[])(s.readObject()); if (pixels != null) { Toolkit tk = Toolkit.getDefaultToolkit(); ColorModel cm = ColorModel.getRGBdefault(); image = tk.createImage(new MemoryImageSource(w, h, cm, pixels, 0, w)); loadImage(image); } } private void writeObject(ObjectOutputStream s) throws IOException { s.defaultWriteObject(); int w = getIconWidth(); int h = getIconHeight(); int[] pixels = image != null? new int[w * h] : null; if (image != null) { try { PixelGrabber pg = new PixelGrabber(image, 0, 0, w, h, pixels, 0, w); pg.grabPixels(); if ((pg.getStatus() & ImageObserver.ABORT) != 0) { throw new IOException("failed to load image contents"); } } catch (InterruptedException e) { throw new IOException("image load interrupted"); } } s.writeInt(w); s.writeInt(h); s.writeObject(pixels); } /** * --- Accessibility Support --- */ private AccessibleImageIcon accessibleContext = null; /** * Gets the AccessibleContext associated with this ImageIcon. * For image icons, the AccessibleContext takes the form of an * AccessibleImageIcon. * A new AccessibleImageIcon instance is created if necessary. * * @return an AccessibleImageIcon that serves as the * AccessibleContext of this ImageIcon * @beaninfo * expert: true * description: The AccessibleContext associated with this ImageIcon. * @since 1.3 */ public AccessibleContext getAccessibleContext() { if (accessibleContext == null) { accessibleContext = new AccessibleImageIcon(); } return accessibleContext; } /** * This class implements accessibility support for the * <code>ImageIcon</code> class. It provides an implementation of the * Java Accessibility API appropriate to image icon user-interface * elements. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * @since 1.3 */ protected class AccessibleImageIcon extends AccessibleContext implements AccessibleIcon, Serializable { /* * AccessibleContest implementation ----------------- */ /** * Gets the role of this object. * * @return an instance of AccessibleRole describing the role of the * object * @see AccessibleRole */ public AccessibleRole getAccessibleRole() { return AccessibleRole.ICON; } /** * Gets the state of this object. * * @return an instance of AccessibleStateSet containing the current * state set of the object * @see AccessibleState */ public AccessibleStateSet getAccessibleStateSet() { return null; } /** * Gets the Accessible parent of this object. If the parent of this * object implements Accessible, this method should simply return * getParent(). * * @return the Accessible parent of this object -- can be null if this * object does not have an Accessible parent */ public Accessible getAccessibleParent() { return null; } /** * Gets the index of this object in its accessible parent. * * @return the index of this object in its parent; -1 if this * object does not have an accessible parent. * @see #getAccessibleParent */ public int getAccessibleIndexInParent() { return -1; } /** * Returns the number of accessible children in the object. If all * of the children of this object implement Accessible, than this * method should return the number of children of this object. * * @return the number of accessible children in the object. */ public int getAccessibleChildrenCount() { return 0; } /** * Returns the nth Accessible child of the object. * * @param i zero-based index of child * @return the nth Accessible child of the object */ public Accessible getAccessibleChild(int i) { return null; } /** * Returns the locale of this object. * * @return the locale of this object */ public Locale getLocale() throws IllegalComponentStateException { return null; } /* * AccessibleIcon implementation ----------------- */ /** * Gets the description of the icon. This is meant to be a brief * textual description of the object. For example, it might be * presented to a blind user to give an indication of the purpose * of the icon. * * @return the description of the icon */ public QString getAccessibleIconDescription() { return ImageIcon.this.getDescription(); } /** * Sets the description of the icon. This is meant to be a brief * textual description of the object. For example, it might be * presented to a blind user to give an indication of the purpose * of the icon. * * @param description the description of the icon */ public void setAccessibleIconDescription(QString description) { ImageIcon.this.setDescription(description); } /** * Gets the height of the icon. * * @return the height of the icon */ public int getAccessibleIconHeight() { return ImageIcon.this.height; } /** * Gets the width of the icon. * * @return the width of the icon */ public int getAccessibleIconWidth() { return ImageIcon.this.width; } private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException { s.defaultReadObject(); } private void writeObject(ObjectOutputStream s) throws IOException { s.defaultWriteObject(); } }; #endif
4de7d216844e52bc9c6b95e2241918295ac5303d
107a54b3709a8b4f20ff1ab110187652d6438395
/Server/Frame/login.h
4b7b52b5789729831edcf92232ace22bcf09c661
[]
no_license
liugang-kv7/GraduationDesign-github
82ed5a98eed704c3717e481930f6e1552db15223
496f355bf727a6191add4435afafd20d566e9cbc
refs/heads/master
2021-01-20T19:39:11.455923
2016-06-05T15:35:42
2016-06-05T15:35:42
60,467,119
0
0
null
null
null
null
UTF-8
C++
false
false
660
h
login.h
#ifndef _LOGIN_H__ #define _LOGIN_H__ #include "../Include/server_base.h" #include "mysql.h" namespace IslandSurvival{ #define dbconfig "./config/database.txt" enum { db_error = 0, login_succeed = 1, login_failed = 2, regist_succeed = 3, regist_used = 4 }; class Login { public: static Login* Instance(); int32_t Init(); int32_t LoginRequest(std::string name, std::string passwd, int32_t& user_id); int32_t NewUserRegist(std::string name, std::string passwd, int32_t& user_id); private: Login(); ~Login(); static Login* m_pInstance; MYSQL* m_connection; MYSQL_RES* m_result; MYSQL_ROW m_row; }; #define LOGIN Login::Instance() } #endif
2a922dbd4ddd1305afa6b57b096071d628bcb528
95a254c8eaa6fae336e918111a039c8ec027793b
/sum-of-substrings-easy.cpp
823e24f382252ae255ec0053aa19ad80a069bee7
[]
no_license
kpratik2015/Interview-Code-Practice
9d17b042a1c991215e40cd2cb6e30cafa02b1e9a
6242c681a19617e410a30300e0d21dae103b56ae
refs/heads/master
2020-12-03T00:04:02.779405
2018-02-05T03:25:43
2018-02-05T03:25:43
95,981,167
0
0
null
null
null
null
UTF-8
C++
false
false
760
cpp
sum-of-substrings-easy.cpp
/* SIMPLER SOLUTION: Input : num = “1234” Output : 1670 Sum = 1 + 2 + 3 + 4 + 12 + 23 + 34 + 123 + 234 + 1234 = 1670 */ #include <iostream> #include <string> using namespace std; int main() { string num = "1234"; int length = num.length(); // cout << "String length: " << length << endl; int sum = 0; // Adding individual digits for (int i = 0 ; i < length ; i++) { sum += num[i] - '0'; } // Adding sub string of lengths 2 to length - 1 int iteration = length - 1; for (int i = 2 ; i < length ; i++) { for (int j = 0 ; j < iteration ; j++ ) { string substr = num.substr(j, i); sum += stoi(substr); } iteration -= 1; } // Adding whole of string num sum += stoi(num); cout << sum << endl; return 0; }
9e6c2e461d28baa1280da498884c04f5af99fb2c
2a8a290eb1d0703a7c7b21429b07870c5ffa868e
/Include/ecrD3D11Renderer/D3D11Include.h
6e21c5e278c0575591fdbd6fbe85cb93561e6b38
[]
no_license
sigmaco/gamebryo-v32
b935d737b773497bf9e663887e326db4eca81885
0709c2570e21f6bb06a9382f9e1aa524070f3751
refs/heads/master
2023-03-31T13:56:37.844472
2021-04-17T02:30:46
2021-04-17T02:30:46
198,067,949
4
4
null
2021-04-17T02:30:47
2019-07-21T14:39:54
C++
UTF-8
C++
false
false
1,580
h
D3D11Include.h
// EMERGENT GAME TECHNOLOGIES PROPRIETARY INFORMATION // // This software is supplied under the terms of a license agreement or // nondisclosure agreement with Emergent Game Technologies and may not // be copied or disclosed except in accordance with the terms of that // agreement. // // Copyright (c) 1996-2009 Emergent Game Technologies. // All Rights Reserved. // // Emergent Game Technologies, Calabasas, CA 91302 // http://www.emergent.net #pragma once #ifndef EE_D3D11INCLUDE_H #define EE_D3D11INCLUDE_H #include <ecrD3D11Renderer/ecrD3D11RendererLibType.h> #include <ecrD3D11Renderer/D3D11Headers.h> namespace ecr { /** A Gamebryo-specific implementation of ID3DInclude that allows applications to provide search paths for files included by shaders. */ class EE_ECRD3D11RENDERER_ENTRY D3D11Include : public ID3DInclude { public: /// Sets the path that will be searched for an include file. void SetBasePath(const efd::Char* pBasePath); /// @cond EMERGENT_INTERNAL /// Override of ID3DInclude::Open, which searches the provided base path for include files. virtual HRESULT STDMETHODCALLTYPE Open( D3D_INCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes); /// Override of ID3DInclude::Close. virtual HRESULT STDMETHODCALLTYPE Close(LPCVOID pData); /// @endcond protected: efd::Char m_basePath[efd::EE_MAX_PATH]; }; } // End namespace ecr. #endif // EE_D3D11INCLUDE_H
26983ffdea40e792a42bd313d4b8a40e399aa44a
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/chrome/test/base/ash_test_environment_chrome.h
06708c85e85f5763f4d042723d23e4bf9eab3f48
[ "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
782
h
ash_test_environment_chrome.h
// Copyright 2016 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. #ifndef CHROME_TEST_BASE_ASH_TEST_ENVIRONMENT_CHROME_H_ #define CHROME_TEST_BASE_ASH_TEST_ENVIRONMENT_CHROME_H_ #include "ash/test/ash_test_environment.h" #include "base/macros.h" class AshTestEnvironmentChrome : public ash::test::AshTestEnvironment { public: AshTestEnvironmentChrome(); ~AshTestEnvironmentChrome() override; // AshTestEnvironment: base::SequencedWorkerPool* GetBlockingPool() override; std::unique_ptr<views::ViewsDelegate> CreateViewsDelegate() override; private: DISALLOW_COPY_AND_ASSIGN(AshTestEnvironmentChrome); }; #endif // CHROME_TEST_BASE_ASH_TEST_ENVIRONMENT_CHROME_H_
5ffa45c729ca68ca9ebee095d0dfec10ff54ee17
75db20d51489f9cce049474945850cfd38f71096
/Orderfile.h
ed6e680ea6db5be8481f87c14073c0ff385cc02f
[]
no_license
Dark-Patrick/text
d7b4546557ff76d71e2fa9cdabc33593cde10c79
a37a9209eaccae93c868a2327532ba3cf700dcf7
refs/heads/main
2023-02-17T14:34:30.520770
2020-12-28T13:10:11
2020-12-28T13:10:11
324,261,186
2
0
null
null
null
null
GB18030
C++
false
false
315
h
Orderfile.h
#pragma once #include<iostream> #include<map> #include"globalFile.h" using namespace std; class Orderfile { public: Orderfile(); void updateOrder(); map<int, map<string, string>>m_orderData; //!!key:int 代表机录的条数 key:string 代表date interval 等属性 int order_size; };
b4a12d733c05c5bc617a1dbc28fb6ff320623e81
755a05dbf86eedc8ee02c999bc867e5acf4c94b4
/dcp_cpp/test/TestDay304.cpp
c82e226351876e569f56355ee1273b2284342e85
[ "MIT" ]
permissive
sraaphorst/daily-coding-problem
b667b9dcd5c60756806101905047a50e25fdd51f
5981e97106376186241f0fad81ee0e3a9b0270b5
refs/heads/master
2022-12-11T23:56:43.533967
2022-12-04T09:28:53
2022-12-04T09:28:53
182,330,159
0
0
null
null
null
null
UTF-8
C++
false
false
722
cpp
TestDay304.cpp
/** * TestDay304.cpp * * By Sebastian Raaphorst, 2020. */ #include <catch.hpp> #include <cmath> #include <day304/day304.h> using namespace dcp::day304; TEST_CASE("Day 304: Make sure all positions in [0,3]x[0,3] match for five steps") { for (size_t x = 0; x < 3; ++x) for (size_t y = 0; y < 3; ++y) for (size_t s = 1; s < 6; ++ s) REQUIRE(fabs(knight_survival_probability_dp(x, y, s) - knight_survival_probability_markov(x, y, s)) < 1e-6); } TEST_CASE("Day 304: Make sure both functions are constexpr") { constexpr auto dp = knight_survival_probability_dp(0, 0, 3); constexpr auto mk = knight_survival_probability_markov(0, 0, 3); REQUIRE(fabs(dp - mk) < 1e-6); }
cf8cb9d8a0c261a3e8f1a054496afd40a9919d41
f08ebf4a9a4019239c8eedf1d8e7249828b47dd2
/MSVC/Common_utilities/PantheiosLogHelper.h
8e190399f6ea824b23e4b9e81a2277e5ba1e4178
[]
no_license
baniuk/A2F
473e30fbc95b3c7f4dbc9439263d78876b321970
79298f1348d01e17dc7da45ea3847e768bb69de4
refs/heads/master
2020-04-28T23:21:58.557787
2014-04-11T18:41:59
2014-04-11T18:41:59
175,651,776
0
0
null
null
null
null
UTF-8
C++
false
false
933
h
PantheiosLogHelper.h
/** * \file PantheiosLogHelper.h * \brief Helps in logging * \author PB * \date 2014/01/20 * \version 0.5 * \remarks Requires "Pantheios_header.h" and <comutil.h> */ #ifndef PantheiosLogHelper_h__ #define PantheiosLogHelper_h__ // user includes #include "Pantheios_header.h" #include <comutil.h> #include <atlsafe.h> /** * \class PantheiosHelper * \brief Class contains helper functions for laooging. * \details all functions are static. This is only conatainer for methods * \author PB * \date 2014/01/31 */ class PantheiosHelper { public: /// Dumps VARIANT data to log file static void dumpVariant( const VARIANT* data, const TCHAR* desc); /// Dumps double array static void dumpCComSafeArray( const ATL::CComSafeArray<double>& data, const TCHAR* desc); /// Dumps BSTR array static void dumpCComSafeArray( const ATL::CComSafeArray<BSTR>& data, const TCHAR* desc); }; #endif // PantheiosLogHelper_h__
294a2d58deec97c18eb428b161a603c869ec6a3f
21ef516c20961b9a29148258552cf1072c93715c
/lib/Galois/libgalois/include/galois/runtime/Iterable.h
c41bef9b06353c4b1952bfb79b8cc99a6a6357ad
[ "MIT", "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
rovinski/LSOracle
b6426c3e45129faa4c41e0f569c323d9d78a9643
0a3f08fb9925e45fa912799d0ee96513c02005e1
refs/heads/master
2023-06-08T05:35:28.164760
2021-07-02T00:46:41
2021-07-02T00:46:41
382,189,413
0
0
MIT
2021-07-02T00:33:59
2021-07-02T00:33:59
null
UTF-8
C++
false
false
2,045
h
Iterable.h
/* * This file belongs to the Galois project, a C++ library for exploiting parallelism. * The code is being released under the terms of the 3-Clause BSD License (a * copy is located in LICENSE.txt at the top-level directory). * * Copyright (C) 2018, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. */ #ifndef GALOIS_RUNTIME_ITERABLE_H #define GALOIS_RUNTIME_ITERABLE_H namespace galois { namespace runtime { // iterable and make_iterable specific // From: // https://github.com/CppCon/CppCon2014/tree/master/Presentations/C%2B%2B11%20in%20the%20Wild%20-%20Techniques%20from%20a%20Real%20Codebase // Author: Arthur O'Dwyer // License: The C++ code in this directory is placed in the public domain and // may be reused or modified for any purpose, commercial or non-commercial. template <class It> class iterable { It m_first, m_last; public: iterable() = default; iterable(It first, It last) : m_first(first), m_last(last) {} It begin() const { return m_first; } It end() const { return m_last; } }; template <class It> static inline iterable<It> make_iterable(It a, It b) { return iterable<It>(a, b); } } // end namespace runtime } // end namespace galois #endif // GALOIS_RUNTIME_ITERABLE_H
77b7552b59cc81ed8c59004ccd138d86ea94e772
9a49a034538934bb733af731de0b6be527ea4f23
/leetcode_c++/54.spiral-matrix.cpp
40b8976d541543fbdcb9fc79f2419467df4533af
[]
no_license
bjut-hz/basics
a34b793d279adf5d1d2dcd7cdd92a865e036116a
0d355e2b47bb8de5c7c7fd79363d279eda8f1243
refs/heads/master
2021-07-23T13:18:25.902620
2021-07-04T08:15:11
2021-07-04T08:15:11
144,576,914
2
0
null
null
null
null
UTF-8
C++
false
false
1,322
cpp
54.spiral-matrix.cpp
/* * @lc app=leetcode id=54 lang=cpp * * [54] Spiral Matrix */ // @lc code=start class Solution { public: /* 在展开数组时,我们可以看到,我们按照的顺序是: 向右->向下->向左->向上 假如说一个矩阵是m*n的,那么,首先向右走m步,然后向下走n-1步;接着向左走m-1步,之后向上走n-2步。。。 当我们发现需要走的步数为0时,自然就结束了。 */ vector<int> spiralOrder(vector<vector<int>>& matrix) { int n = matrix.size(); if(0 == n) return {}; int m = matrix[0].size(); if(0 == m) return {}; vector<int> res; vector<int> steps{m, n - 1}; // 四个方向,分别为:右下左上 vector<vector<int>> dirs{{0,1},{1,0},{0,-1},{-1,0}}; int dir = 0; int i_row = 0; int i_col = -1; // 第一步的左侧一个元素 while(steps[dir%2]) { for(int i = 0; i < steps[dir%2]; ++i) { i_col += dirs[dir][1]; i_row += dirs[dir][0]; res.push_back(matrix[i_row][i_col]); } steps[dir%2]--; dir = (dir + 1) % 4; } return res; } }; // @lc code=end
0028c4f9fb0bb6292500cd706989087207fa925f
95c669a8f5732cd9efe831eaae3e50fdc7261297
/qinteractivemaptool.h
05108d50a9b155a7196468fbbe1b81f8a1154615
[]
no_license
xin0111/QMapInteractiveHelp
44b953d0b9407a4a5cec93443448327b5167b05c
e00ee7005ef3fddf0deb2ad9100157e88c753fb2
refs/heads/master
2020-05-24T05:54:16.059860
2019-05-17T02:43:37
2019-05-17T02:43:37
187,128,616
0
0
null
null
null
null
UTF-8
C++
false
false
4,581
h
qinteractivemaptool.h
#ifndef QGSMAPTOOL_H #define QGSMAPTOOL_H #include <QCursor> #include <QString> #include <QObject> #include "qmapinteractive_global.h" class QWidget; class QKeyEvent; class QMouseEvent; class QWheelEvent; class QPoint; class QAction; class QAbstractButton; class QInteractiveManager; /** * \ingroup gui * Abstract base class for all map tools. * Map tools are user interactive tools for manipulating the * map canvas. For example map pan and zoom features are * implemented as map tools. */ class QMAPINTERACTIVE_EXPORT QInteractiveMapTool : public QObject { Q_OBJECT public: /** * Enumeration of flags that adjust the way the map tool operates */ enum Flag { Transient = 1 << 1, /*!< Indicates that this map tool performs a transient (one-off) operation. If it does, the tool can be operated once and then a previous map tool automatically restored. */ EditTool = 1 << 2, //!< Map tool is an edit tool, which can only be used when layer is editable AllowZoomRect = 1 << 3, //!< Allow zooming by rectangle (by holding shift and dragging) while the tool is active }; Q_DECLARE_FLAGS( Flags, Flag ) /** * Returns the flags for the map tool. */ virtual Flags flags() const { return Flags(); } ~QInteractiveMapTool() ; //! Mouse move event for overriding. Default implementation does nothing. virtual void canvasMoveEvent( QMouseEvent *e ); //! Mouse double-click event for overriding. Default implementation does nothing. virtual void canvasDoubleClickEvent( QMouseEvent *e ); //! Mouse press event for overriding. Default implementation does nothing. virtual void canvasPressEvent( QMouseEvent *e ); //! Mouse release event for overriding. Default implementation does nothing. virtual void canvasReleaseEvent( QMouseEvent *e ); //! Mouse wheel event for overriding. Default implementation does nothing. virtual void wheelEvent( QWheelEvent *e ); //! Key event for overriding. Default implementation does nothing. virtual void keyPressEvent( QKeyEvent *e ); //! Key event for overriding. Default implementation does nothing. virtual void keyReleaseEvent( QKeyEvent *e ); /** * Use this to associate a QAction to this maptool. Then when the setMapTool * method of mapcanvas is called the action state will be set to on. * Usually this will cause e.g. a toolbutton to appear pressed in and * the previously used toolbutton to pop out. */ void setAction( QAction *action ); //! Returns associated action with map tool or NULL if no action is associated QAction *action(); /** * Returns if the current map tool active on the map canvas */ bool isActive() const; /** * Use this to associate a button to this maptool. It has the same meaning * as setAction() function except it works with a button instead of an QAction. */ void setButton( QAbstractButton *button ); //! Returns associated button with map tool or NULL if no button is associated QAbstractButton *button(); //! Sets a user defined cursor virtual void setCursor( const QCursor &cursor ); //! make action and/or button active virtual void activate(); //! make action and/or button active deactivated(使无效) virtual void deactivate(); //! convenient method to clean members virtual void clean(); /** * Emit map tool changed with the old tool */ QString toolName() { return mToolName; } signals: //! emit signal to clear previous message void messageDiscarded(); //! signal emitted once the map tool is activated void activated(); //! signal emitted once the map tool is deactivated void deactivated(); private slots: //! clear pointer when action is destroyed void actionDestroyed(); protected: QInteractiveMapTool(QWidget* viewport, QInteractiveManager *iManager ); QWidget* mViewport; QInteractiveManager* mIManager; //! cursor used in map tool QCursor mCursor; /** * optionally map tool can have pointer to action * which will be used to set that action as active */ QAction *mAction; /** * optionally map tool can have pointer to a button * which will be used to set that action as active */ QAbstractButton *mButton; //! translated name of the map tool QString mToolName; }; Q_DECLARE_OPERATORS_FOR_FLAGS( QInteractiveMapTool::Flags ) #endif
35009c51f9010958a9ca95bc8f378301c8d88ce8
7e1107c4995489a26c4007e41b53ea8d00ab2134
/game/code/main/gcplatform.h
ddab488e7ff625bc43dd0dc7bac3b270dfd8be96
[]
no_license
Svxy/The-Simpsons-Hit-and-Run
83837eb2bfb79d5ddb008346313aad42cd39f10d
eb4b3404aa00220d659e532151dab13d642c17a3
refs/heads/main
2023-07-14T07:19:13.324803
2023-05-31T21:31:32
2023-05-31T21:31:32
647,840,572
591
45
null
null
null
null
UTF-8
C++
false
false
5,284
h
gcplatform.h
//============================================================================= // Copyright (C) 2002 Radical Entertainment Ltd. All rights reserved. // // File: gcplatform.h // // Description: Abstracts the differences for setting up and shutting down // the different platforms. // // History: + Stolen and cleaned up from Svxy -- Darwin Chau // //============================================================================= #ifndef GCPLATFORM_H #define GCPLATFORM_H //======================================== // Nested Includes //======================================== #include <main/platform.h> // base class #include <p3d/platform.hpp> //======================================== // Forward References //======================================== struct IRadMemoryHeap; //class tPlatform; class tContext; // // This value define the resolution of the rendering area. // Based on the width, Pure3D figures out the approriate height. // const int WindowSizeX = 640; #ifdef PAL const int WindowSizeY = 524; #else const int WindowSizeY = 480; #endif // // The depth of the rendering area. This value only has an effect // when Pure3D has taken over the entire display. When running in // a window on the desktop, Pure3D uses the same bit depth as the // desktop. Pure3D only supports 16, and 32 rendering depths. // static const int WindowBPP = 16; //Turn this on to disable ARAM use. Use this to test leaks in the ARAM heap. //#define NO_ARAM #ifdef NO_ARAM const int VMM_MAIN_RAM = 0; const int VMM_ARAM = 0; #else const int VMM_MAIN_RAM = ( 1 * 1024 * 1024 ) + ( 500 * 1024 ); const int VMM_ARAM = 6 * 1024 * 1024; #endif //============================================================================= // // Synopsis: Provides abstraction for setting up and closing down the GC. // //============================================================================= class GCPlatform : public Platform { public: // Static Methods for accessing this singleton. static GCPlatform* CreateInstance(); static GCPlatform* GetInstance(); static void DestroyInstance(); // Had to workaround our nice clean design cause FTech must be init'ed // before anything else is done. static void InitializeFoundation(); static void InitializeMemory(); // Implement Platform interface. virtual void InitializePlatform(); virtual void ShutdownPlatform(); virtual void InitializeFoundation(); virtual void LaunchDashboard(); virtual void ResetMachine(); virtual void DisplaySplashScreen( SplashScreen screenID, const char* overlayText = NULL, float fontScale = 1.0f, float textPosX = 0.0f, float textPosY = 0.0f, tColour textColour = tColour( 255,255,255 ), int fadeFrames = 3 ); virtual void DisplaySplashScreen( const char* textureName, const char* overlayText = NULL, float fontScale = 1.0f, float textPosX = 0.0f, float textPosY = 0.0f, tColour textColour = tColour( 255,255,255 ), int fadeFrames = 3 ); bool DisplayYesNo( float fontScale = 1.0f, float yesPosX = 0.0f, float yesPosY = 0.0f, float noPosX = 0.0f, float noPosY = 0.0f, int fadeFrames = 3 ); tContextInitData* GetInitData(); virtual bool OnDriveError( radFileError error, const char* pDriveName, void* pUserData ); virtual void OnControllerError(const char *msg); protected: virtual void InitializeFoundationDrive(); virtual void ShutdownFoundation(); virtual void InitializePure3D(); virtual void ShutdownPure3D(); private: // Constructors, Destructors, and Operators GCPlatform(); virtual ~GCPlatform(); // Unused Constructors, Destructors, and Operators GCPlatform( const GCPlatform& aPlatform ); GCPlatform& operator=( const GCPlatform& aPlatform ); // Pointer to the one and only instance of this singleton. static GCPlatform* spInstance; // Pure 3D attributes tPlatform* mpPlatform; tContext* mpContext; tContextInitData mInitData; }; //============================================================================= // GCPlatform::GetInitData //============================================================================= // Description: Comment // // Parameters: () // // Return: tContextInitData // //============================================================================= inline tContextInitData* GCPlatform::GetInitData() { return &mInitData; } #endif // GCPLATFORM_H
59c6d924f7c1e426940cb4105b959b896abb6be0
ba69594df5b20968f64346c28a98eba34513d449
/OOP-Task-1c_Skelington-master/CurrentAccount.h
e0941cdf005bb0970f5af96a08c3b1308bacc414
[ "Apache-2.0" ]
permissive
rooleyzee123/C-Example-work
164a9e1edcb5a7bf0b16af974da03bc1ce3a3fa8
cdadd902e5cb9a071b72f3456a6e7bccfd113780
refs/heads/master
2020-03-24T05:58:41.240408
2018-07-27T01:17:12
2018-07-27T01:17:12
142,511,403
0
0
null
null
null
null
UTF-8
C++
false
false
747
h
CurrentAccount.h
//Pascale Vacher - February 18 //OOP Assignment Task 1c - Semester 2 //Group Number: 16 //Team: Dion Perez-France, Daniel Rose, Zak Bond, Zak Rooley #ifndef CurrentAccountH #define CurrentAccountH //--------------------------------------------------------------------------- //CurrentAccount: class declaration //--------------------------------------------------------------------------- #include "BankAccount.h" class CurrentAccount : public BankAccount { public: //constructors & destructor CurrentAccount(); ~CurrentAccount(); void abstract() {}; double getOverdraftLimit() const; virtual double maxBorrowable() const; virtual bool canWithdraw(double amount) const; private: //data items double overdraftLimit_; }; #endif
427c3efdefaea3b52cc0db41c9fe80a744d05ecf
1b90be9561c10508eea59cb36c1f1665d0ef947f
/test/unit/math/prim/prob/discrete_range_ccdf_log_test.cpp
e4e8d900aba456528c363ad31199beecb2d6ee55
[ "BSD-3-Clause", "GPL-2.0-only", "Apache-2.0" ]
permissive
stan-dev/math
473e7c1eaf11f84eaf2032c2455e12ba65feef39
bdf281f4e7f8034f47974d14dea7f09e600ac02a
refs/heads/develop
2023-08-31T09:02:59.224115
2023-08-29T15:17:01
2023-08-29T15:17:01
38,388,440
732
240
BSD-3-Clause
2023-09-14T19:44:20
2015-07-01T18:40:54
C++
UTF-8
C++
false
false
1,248
cpp
discrete_range_ccdf_log_test.cpp
#include <stan/math/prim.hpp> #include <gtest/gtest.h> TEST(ProbDiscreteRange, cdf_log_matches_lccdf) { using stan::math::discrete_range_ccdf_log; using stan::math::discrete_range_lccdf; for (int lower = 0; lower < 5; ++lower) { for (int upper = lower; upper < 5; ++upper) { for (int y = lower; y <= upper; ++y) { EXPECT_FLOAT_EQ((discrete_range_lccdf(y, lower, upper)), (discrete_range_ccdf_log(y, lower, upper))); EXPECT_FLOAT_EQ((discrete_range_lccdf<double>(y, lower, upper)), (discrete_range_ccdf_log<double>(y, lower, upper))); } } } } TEST(ProbDiscreteRange, lccdf_boundaries) { using stan::math::discrete_range_lccdf; int lower = 1; int upper = 5; EXPECT_FLOAT_EQ(std::log(4.0 / 5), discrete_range_lccdf(lower, lower, upper)); EXPECT_FLOAT_EQ(stan::math::LOG_ZERO, discrete_range_lccdf(upper, lower, upper)); } TEST(ProbDiscreteRange, lccdf_out_of_support) { using stan::math::discrete_range_lccdf; int lower = 1; int upper = 5; EXPECT_FLOAT_EQ(0.0, discrete_range_lccdf(lower - 1, lower, upper)); EXPECT_FLOAT_EQ(stan::math::LOG_ZERO, discrete_range_lccdf(upper + 1, lower, upper)); }
28b26c2a25fa533a376d98484f4bc034f3293091
80a945c29335f6a9ad6de57392b8563952b3feda
/LinkedList/DoubleLinkedList/DoubleLinkedList.cpp
1f412c8216f9337ef1f6baab9c1320c6ee7aadfb
[]
no_license
NTZemp/LinkedList_M411
edbd5bb16431166cb0be4e903ad8b2694a1fac8b
4e885729a4a6e17f1b2d985aaee787aa6ba3a8dd
refs/heads/master
2020-04-10T05:09:09.124404
2019-01-11T12:49:23
2019-01-11T12:49:23
160,818,957
0
0
null
null
null
null
ISO-8859-1
C++
false
false
13,531
cpp
DoubleLinkedList.cpp
#include "stdio.h" #include "stdlib.h" #include "string.h" #include "time.h" #include "chrono" typedef struct Person { char firstname[40]; char lastname[40]; int year; struct Person* pNext; struct Person* pPrev; } struPerson; /* Autor: Lino Meyer Gibt einen zufälligen Grossbuchstaben zurück */ char randomName() { return rand() % 26 + 'A'; } /* Autor: Lino Meyer Gibt ein zufälliges Jahr zwischen 1900 und 2018 zurück */ int randomYear() { return 1900 + (rand() % 119); } /* Autor: Lino Meyer Erstellt eine doppelt verkettete Liste mit einer bestimmten Anzahl Elementen */ struPerson* create(int amount) { struPerson* pStart = NULL; struPerson* pLast = NULL; for (int i = 0; i < amount; i++) { struPerson* pNew = (struPerson*)malloc(sizeof(struPerson)); pNew->pNext = NULL; pNew->pPrev = NULL; pNew->firstname[0] = randomName(); pNew->firstname[1] = '\0'; pNew->lastname[0] = randomName(); pNew->lastname[1] = '\0'; pNew->year = randomYear(); if (pStart == NULL) { pStart = pNew; pStart->pPrev = NULL; pLast = pStart; } else { pLast->pNext = pNew; pNew->pPrev = pLast; pLast = pNew; } } return pStart; } /* Autor: Noah Zemp Löscht die Ganze Liste */ void deleteList(struPerson* pStart) { struPerson* pCurrentPerson = pStart; struPerson* pNextPerson; while (pCurrentPerson != NULL) { // pNextPerson zeigt auf nächstes Personenelement pNextPerson = pCurrentPerson->pNext; // momentanes Elements löschen free(pCurrentPerson); pCurrentPerson = pNextPerson; } } /* Autor: Lino Meyer Löscht alle Personen mit dem angegebenen Vor- und Nachnamen */ struPerson* deletePerson(struPerson* pStart, const char* firstname, const char* lastname) { struPerson* pCurrent = pStart; while (pCurrent != NULL) { struPerson* pNext = pCurrent->pNext; if (strcmp(firstname, pCurrent->firstname) == 0 && strcmp(lastname, pCurrent->lastname) == 0) { if (pCurrent->pPrev == NULL) { pCurrent->pNext->pPrev = NULL; pStart = pCurrent->pNext; free(pCurrent); } else if (pCurrent->pNext == NULL) { pCurrent->pPrev->pNext = NULL; free(pCurrent); } else { pCurrent->pPrev->pNext = pCurrent->pNext; pCurrent->pNext->pPrev = pCurrent->pPrev; free(pCurrent); } } pCurrent = pNext; } return pStart; } /* Autor: Noah Zemp */ int GetNumberOfElements(struPerson* pStart) { struPerson* pCurrent = pStart; int counter = 1; while (pCurrent->pNext != NULL) { counter++; pCurrent = pCurrent->pNext; } free(pCurrent); free(pStart); return counter; } /* Autor: Noah Zemp */ struPerson* GetElementAt(int index, struPerson* pStart) { struPerson* pCurrent = pStart; int counter = 0; while (counter != index) { counter++; pCurrent = pCurrent->pNext; } return pCurrent; } /* Autor: Noah Zemp */ [[deprecated]] void SetElementToStart(struPerson* pStart, struPerson* pElementToStart) { pElementToStart->pPrev = NULL; pElementToStart->pNext = pStart; pStart->pPrev = pElementToStart; } /* Autor: Noah Zemp */ void swapElements(struPerson* pElement1, struPerson* pElement2) { struPerson* pTemp = (struPerson*)malloc(sizeof(struPerson)); //Copy Element1 into Temp pTemp->pNext = pElement1->pNext; pTemp->pPrev = pElement1->pPrev; //Put Element1 to the same Position as Element2 pElement1->pNext = pElement2->pNext; pElement1->pPrev = pElement2->pPrev; //Put Element2 to the Position were Element1 was pElement2->pNext = pTemp->pNext; pElement2->pPrev = pTemp->pPrev; if (pElement1->pPrev != NULL) pElement1->pPrev->pNext = pElement1; pElement2->pNext->pPrev = pElement2; } /* Autor: Lino Meyer Tauscht die Position eines Elements mit dem nächsten */ struPerson* swapWithNextElement(struPerson* pStart, struPerson* pCurrent) { struPerson* pBefore = pCurrent->pPrev; struPerson* pAfter = pCurrent->pNext; struPerson* pAfterAfter = pAfter->pNext; if (pCurrent == pStart) { pStart = pAfter; } // vorherigen Node neu verknüpfen if (pBefore != NULL) { pBefore->pNext = pAfter; } // jetzigen Node neu verknüpfen pCurrent->pNext = pAfter->pNext; pCurrent->pPrev = pAfter; // nächsten Node neu verknüpfen pAfter->pNext = pCurrent; pAfter->pPrev = pBefore; // übernächsten Node neu verknüpfen if (pAfterAfter != NULL) pAfterAfter->pPrev = pCurrent; return pStart; } struPerson* swap(struPerson* pStart, struPerson* pCurrent) { struPerson* pBefore = pCurrent->pPrev; struPerson* pAfter = pCurrent->pNext; if (pCurrent == pStart) { pStart = pAfter; } struPerson* pTemp = (struPerson*)malloc(sizeof(struPerson)); //Copy Element1 into Temp pTemp->pNext = pCurrent->pNext; pTemp->pPrev = pCurrent->pPrev; //Put Element1 to the same Position as Element2 pCurrent->pNext = pAfter->pNext; pCurrent->pPrev = pAfter->pPrev; //Put Element2 to the Position were Element1 was pAfter->pNext = pTemp->pNext; pAfter->pPrev = pTemp->pPrev; return pStart; } /* Autor: Lino Meyer Sortiert die Liste nach Bubblesort vorgehen. Der Benutzer kann wählen nach welchen Kriterien */ struPerson* bubbleSort(struPerson* pStart, const char* sortingCriteria) { bool isSorting; struPerson* pCurrent; do { isSorting = false; pCurrent = pStart; while (pCurrent != NULL && pCurrent->pNext != NULL) { struPerson* pNext = pCurrent->pNext; if (sortingCriteria[0] == 'l') { //Nach Nachnamen sortieren if (strcmp(pCurrent->lastname, pNext->lastname) > 0) { pStart = swapWithNextElement(pStart, pCurrent); /* da pCurrent jetzt den an dem Ort ist an dem pNext zuvor war, wird pCurrent auf diesen Wert gesetzt damit kein Element übersprungen wird. */ pCurrent = pNext; isSorting = true; } if (sortingCriteria[1] == 'f') { // Nach Vor- und Nachnamen sortieren if (strcmp(pCurrent->lastname, pNext->lastname) == 0 && strcmp(pCurrent->firstname, pNext->firstname) > 0) { pStart = swapWithNextElement(pStart, pCurrent); pCurrent = pNext; isSorting = true; } if (sortingCriteria[2] == 'y') { // Nach Vor- Nachnamen und Jahr sortieren if (strcmp(pCurrent->lastname, pNext->lastname) == 0 && strcmp(pCurrent->firstname, pNext->firstname) == 0 && pCurrent->year > pNext->year) { pStart = swapWithNextElement(pStart, pCurrent); pCurrent = pNext; isSorting = true; } } } else if (sortingCriteria[1] == 'y') { // Nach Nachnamen und Jahr sortieren if (strcmp(pCurrent->lastname, pNext->lastname) == 0 && pCurrent->year > pNext->year) { pStart = swapWithNextElement(pStart, pCurrent); pCurrent = pNext; isSorting = true; } } } else if (sortingCriteria[0] == 'f') { // Nach Vornamen sortieren if (strcmp(pCurrent->firstname, pNext->firstname) > 0) { pStart = swapWithNextElement(pStart, pCurrent); pCurrent = pNext; isSorting = true; } if (sortingCriteria[1] == 'y') { // Nach Vornamen und Jahr sortieren if (strcmp(pCurrent->firstname, pNext->firstname) == 0 && pCurrent->year > pNext->year) { pStart = swapWithNextElement(pStart, pCurrent); pCurrent = pNext; isSorting = true; } } } else if (sortingCriteria[0] == 'y') { // Nach Jahr sortieren if (pCurrent->year > pNext->year) { pStart = swapWithNextElement(pStart, pCurrent); pCurrent = pNext; isSorting = true; } } pCurrent = pCurrent->pNext; } } while (isSorting); return pStart; } struPerson* insertionSort(struPerson* pStart) { struPerson* pCurrent = NULL; bool isSorting = false; // Schleife durch Ganze Liste, beginnt beim ersten Element nach pStart for (pCurrent = pStart->pNext; pCurrent != NULL;) { struPerson* pPrev = pCurrent->pPrev; // Schleife geht zurück zum Start solange der Nachname des vorherigen Elements grösser ist while (pPrev != NULL && strcmp(pPrev->lastname, pCurrent->lastname) > 0) { pStart = swapElements(pCurrent, pPrev); isSorting = true; //pStart = swapWithNextElement(pStart, pPrev); } if (isSorting) { pCurrent = pPrev; } else { pCurrent = pCurrent->pNext; } isSorting = false; } return pStart; } /* Autor: Noah Zemp */ void PrintElement(struPerson* pElement) { printf("Vorname: %s\nNachname: %s\nJahrgang: %d\n", pElement->firstname, pElement->lastname, pElement->year); } /* Autor: Lino Meyer Gibt die Ganze Liste in der Konsole aus */ void printList(struPerson* pStart) { for (struPerson* pOutput = pStart; pOutput != NULL; pOutput = pOutput->pNext) { PrintElement(pOutput); } } /* Autor: Lino Meyer Gibt eine festgelegte Anzahl Elemente aus */ /* Autor: Noah Zemp, Lino Meyer */ void printElements(struPerson* pStart, int numberOfElements) { struPerson* pCurrent = pStart; if (numberOfElements == 0) { printList(pStart); } while (numberOfElements > 0) { PrintElement(pCurrent); numberOfElements--; pCurrent = pCurrent->pNext; } } // User Interaktion void main() { srand((unsigned)time(NULL)); printf("******************\nVerkettete Liste\n******************\n\n"); printf("Wie viele Personen soll die Liste haben? "); int numberOfElements = 0; scanf_s("%i", &numberOfElements); struPerson* pStart = create(numberOfElements); char input[40]; while (true) { // diese Zeile wird zu oft ausgegeben printf("Wie viele Elemente wollen Sie ausgeben? [0 = alle]: "); scanf_s("%i", &numberOfElements); printElements(pStart, numberOfElements); printf("\nWas wollen Sie tun?\n\n"); printf("Liste löschen [\"dl\"]\n"); printf("Personen löschen [\"dp\"]\n"); printf("Liste mit BubbleSort sortieren [\"bs\"]\n"); printf("Liste mit InsertionSort sortieren [\"is\"]"); printf("Programm beenden [\"quit\"]\n"); printf("Eingabe:"); // Das Enter nach einer scanf_s Eingabe bleibt im Buffer hängen getchar(); gets_s(input); // Liste löschen if (strcmp(input, "dl") == 0) { deleteList(pStart); return; } // Person löschen else if (strcmp(input, "dp") == 0) { printf("\nWie heisst die Person die Sie löschen wollen?"); printf("\nVorname: "); char firstname[40]; gets_s(firstname); printf("Nachname: "); char lastname[40]; gets_s(lastname); pStart = deletePerson(pStart, firstname, lastname); } // Bubblesort mit Sortierkriterien else if (strcmp(input, "bs") == 0) { /*Die Priorität beim sortieren ist festgelegt, zuerst Nachname dann Vorname, dann Jahr Es kann also nicht nach Jahr und dann nach Nachname sortiert werden, umgekehrt aber schon. Ansonsten kann nach einzelnen Variablen oder auch nach mehreren sortiert werden.*/ printf("\nNach welchen Variablen möchten Sie sortieren? [l = Nachname, f = Vorname, y = Jahr] z.B. \"lf\": "); char sortingCriteria[4]; gets_s(sortingCriteria); // Zeitmessung Start auto start = std::chrono::high_resolution_clock::now(); pStart = bubbleSort(pStart, sortingCriteria); //Zeitmessung Ende auto finish = std::chrono::high_resolution_clock::now(); //Messzeit std::chrono::duration<double> timeElapsed = finish - start; printf("%f\n", (double)timeElapsed.count()); } else if (strcmp(input, "quit") == 0) { return; } else if (strcmp(input, "is") == 0){ pStart = insertionSort(pStart); } else { printf("\nFalsche Eingabe\n"); } } system("pause"); }
a763d9e2408528adae878c2f215bf125aa1118b8
2168abb68394404d9402cc3be9e4a6c186866197
/WiiRemote.cpp
7cae018212deb9f2e80c73dd8209d03c868120cf
[]
no_license
ZalophusDokdo/WiiRemote-2WS-Control
737235a05f365dac7be7fe67736bec2c6329a63e
4ebe1d5a13815b699f53ba4002d31f6d5b249ef4
refs/heads/master
2021-01-18T01:41:06.700845
2019-02-24T18:41:33
2019-02-24T18:41:33
62,112,717
4
3
null
null
null
null
UTF-8
C++
false
false
36,405
cpp
WiiRemote.cpp
/* WiiRemote.cpp - WiiRemote Bluetooth stack on Arduino with USB Host Shield Copyright (C) 2010 Tomo Tanaka This program is based on <wiiblue.pde> which is developed by Richard Ibbotson. This program also needs MAX3421E and USB libraries for Arduino written by Oleg Mazurov. The source codes can be grabbed from <https://github.com/felis/USB_Host_Shield>. 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/>. */ /* #include "WProgram.h" */ #include <Arduino.h> #include <avr/pgmspace.h> #include "WiiRemote.h" #include "Max3421e.h" #include "Usb.h" #define ARRAY_LENGTH(array) (sizeof(array)/sizeof(*array)) #define WIIREMOTE_DEBUG 0 // {{{ #if WIIREMOTE_DEBUG void Serial_print_P(const prog_char *str) { char c; if (!str) return; while ((c = pgm_read_byte(str++)) != 0) { Serial.print(c, BYTE); } } void Serial_println_P(const prog_char *str) { Serial_print_P(str); Serial.println(""); } #define DEBUG_PRINT(c, f) Serial.print(c, f) #define DEBUG_PRINTLN(c, f) Serial.println(c, f) #define DEBUG_PRINT_P(c) Serial_print_P(c) #define DEBUG_PRINTLN_P(c) Serial_println_P(c) #else #define DEBUG_PRINT(c, f) #define DEBUG_PRINTLN(c, f) #define DEBUG_PRINT_P(c) #define DEBUG_PRINTLN_P(c) #endif // }}} MAX3421E Max; USB Usb; WiiRemote::WiiRemote(void) { l2cap_state_ = L2CAP_DOWN_STATE; l2cap_txid_ = 0; command_scid_ = 0x0040; // L2CAP local CID for HID_Control interrupt_scid_ = 0x0041; // L2CAP local CID for HID_Interrupt hid_flags_ = 0; hid_buttons_ = 0; old_hid_buttons_ = 0; hid_buttons_click_ = 0; bdaddr_acquisition_mode_ = BD_ADDR_INQUIRY; wiiremote_status_ = 0; } WiiRemote::~WiiRemote(void) { } void WiiRemote::init(void) { Max.powerOn(); delay(200); } void WiiRemote::task(void (*pFunc)(void)) { Max.Task(); Usb.Task(); delay(1); // re-initialize if (Usb.getUsbTaskState() == USB_DETACHED_SUBSTATE_INITIALIZE) { /* TODO */ wiiremote_status_ = 0; } // wait for addressing state if (Usb.getUsbTaskState() == USB_STATE_CONFIGURING) { initBTController(); if (wiiremote_status_ & WIIREMOTE_STATE_USB_CONFIGURED) { hci_state_ = HCI_INIT_STATE; hci_counter_ = 10; l2cap_state_ = L2CAP_DOWN_STATE; Usb.setUsbTaskState(USB_STATE_RUNNING); } } if (Usb.getUsbTaskState() == USB_STATE_RUNNING) { HCI_task(); // poll the HCI event pipe L2CAP_task(); // start polling the ACL input pipe too, though discard // data until connected } //if (l2cap_state_ == L2CAP_READY_STATE) { if (wiiremote_status_ & WIIREMOTE_STATE_RUNNING) { if (pFunc) { pFunc(); } } } // task uint8_t WiiRemote::getStatus(void) { return wiiremote_status_; } void WiiRemote::setBDAddress(uint8_t *bdaddr, int size) { int array_length = ARRAY_LENGTH(wiiremote_bdaddr_); for (int i = 0; i < size && i < array_length; i++) { wiiremote_bdaddr_[i] = bdaddr[i]; } } void WiiRemote::setBDAddressMode(eBDAddressMode mode) { bdaddr_acquisition_mode_ = mode; } void WiiRemote::getBDAddress(uint8_t *bdaddr, int size) { int array_length = ARRAY_LENGTH(wiiremote_bdaddr_); for (int i = 0; i < size && i < array_length; i++) { bdaddr[i] = wiiremote_bdaddr_[i]; } } /************************************************************/ /* Initialize Bluetooth USB Controller (CSR) */ /************************************************************/ void WiiRemote::initBTController(void) { uint8_t rcode = 0; // return code uint8_t buf[MAX_BUFFER_SIZE] = {0}; USB_DEVICE_DESCRIPTOR *device_descriptor; /* initialize data structures for endpoints of device 1 */ // copy endpoint 0 parameters ep_record_[ CONTROL_PIPE ] = *( Usb.getDevTableEntry(0,0) ); // Bluetooth event endpoint ep_record_[ EVENT_PIPE ].epAddr = 0x01; ep_record_[ EVENT_PIPE ].Attr = EP_INTERRUPT; ep_record_[ EVENT_PIPE ].MaxPktSize = INT_MAXPKTSIZE; ep_record_[ EVENT_PIPE ].Interval = EP_POLL; ep_record_[ EVENT_PIPE ].sndToggle = bmSNDTOG0; ep_record_[ EVENT_PIPE ].rcvToggle = bmRCVTOG0; // Bluetoth data endpoint ep_record_[ DATAIN_PIPE ].epAddr = 0x02; ep_record_[ DATAIN_PIPE ].Attr = EP_BULK; ep_record_[ DATAIN_PIPE ].MaxPktSize = BULK_MAXPKTSIZE; ep_record_[ DATAIN_PIPE ].Interval = 0; ep_record_[ DATAIN_PIPE ].sndToggle = bmSNDTOG0; ep_record_[ DATAIN_PIPE ].rcvToggle = bmRCVTOG0; // Bluetooth data endpoint ep_record_[ DATAOUT_PIPE ].epAddr = 0x02; ep_record_[ DATAOUT_PIPE ].Attr = EP_BULK; ep_record_[ DATAOUT_PIPE ].MaxPktSize = BULK_MAXPKTSIZE; ep_record_[ DATAOUT_PIPE ].Interval = 0; ep_record_[ DATAOUT_PIPE ].sndToggle = bmSNDTOG0; ep_record_[ DATAOUT_PIPE ].rcvToggle = bmRCVTOG0; // plug kbd.endpoint parameters to devtable Usb.setDevTableEntry(BT_ADDR, ep_record_); // read the device descriptor and check VID and PID rcode = Usb.getDevDescr(BT_ADDR, ep_record_[ CONTROL_PIPE ].epAddr, DEV_DESCR_LEN, (char *) buf); if (rcode) { DEBUG_PRINT_P( PSTR("\r\nDevice Descriptor Error: ") ); DEBUG_PRINT(rcode, HEX); return; } device_descriptor = (USB_DEVICE_DESCRIPTOR *) &buf; if ((device_descriptor->idVendor != CSR_VID) || (device_descriptor->idProduct != CSR_PID)) { DEBUG_PRINT_P( PSTR("\r\nWrong USB Device ID: ") ); DEBUG_PRINT_P( PSTR("\r\n\t Vendor ID = ") ); DEBUG_PRINT(device_descriptor->idVendor, HEX); DEBUG_PRINT_P( PSTR("\r\n\tProduct ID = ") ); DEBUG_PRINT(device_descriptor->idProduct, HEX); return; } wiiremote_status_ |= WIIREMOTE_STATE_USB_AUTHORIZED; // configure device rcode = Usb.setConf(BT_ADDR, ep_record_[ CONTROL_PIPE ].epAddr, BT_CONFIGURATION); if (rcode) { DEBUG_PRINT_P( PSTR("\r\nDevice Configuration Error: ") ); DEBUG_PRINT(rcode, HEX); return; } wiiremote_status_ |= WIIREMOTE_STATE_USB_CONFIGURED; //LCD.clear(); DEBUG_PRINT_P( PSTR("\r\nCSR Initialized") ); //delay(200); } // initBTController /************************************************************/ /* HCI Flow Control */ /************************************************************/ void WiiRemote::HCI_task(void) { HCI_event_task(); switch (hci_state_) { case HCI_INIT_STATE: // wait until we have looped 10 times to clear any old events if (hci_timeout) { hci_reset(); hci_state_ = HCI_RESET_STATE; hci_counter_ = 1000; } break; case HCI_RESET_STATE: if (hci_command_complete) { DEBUG_PRINT_P( PSTR("\r\nHCI Reset complete") ); switch (bdaddr_acquisition_mode_) { case BD_ADDR_FIXED: hci_state_ = HCI_READY_CONNECT_STATE; hci_counter_ = 10000; break; case BD_ADDR_INQUIRY: hci_inquiry(); hci_state_ = HCI_INQUIRY_STATE; hci_counter_ = 10000; break; default: break; } } if (hci_timeout) { DEBUG_PRINT_P( PSTR("\r\nNo response to HCI Reset") ); hci_state_ = HCI_INIT_STATE; hci_counter_ = 10; } break; case HCI_INQUIRY_STATE: if (hci_inquiry_result) { DEBUG_PRINT_P( PSTR("\r\nHCI Inquiry responded") ); hci_inquiry_cancel(); hci_state_ = HCI_READY_CONNECT_STATE; hci_counter_ = 10000; } break; case HCI_READY_CONNECT_STATE: if (hci_command_complete) { if (hci_inquiry_result) { DEBUG_PRINT_P( PSTR("\r\nHCI Inquiry complete") ); } hci_connect(wiiremote_bdaddr_); // connect to Wiimote hci_state_ = HCI_CONNECT_OUT_STATE; hci_counter_ = 10000; } break; case HCI_CONNECT_OUT_STATE: if (hci_connect_complete) { if(hci_connect_ok) { DEBUG_PRINT_P( PSTR("\r\nConnected to Wiimote") ); hci_state_ = HCI_CONNECTED_STATE; l2cap_state_ = L2CAP_INIT_STATE; wiiremote_status_ |= WIIREMOTE_STATE_CONNECTED; } else { hci_connect(wiiremote_bdaddr_); // try again to connect to Wiimote hci_counter_ = 10000; } } if (hci_timeout) { hci_connect(wiiremote_bdaddr_); // try again to connect to Wiimote hci_counter_ = 10000; } break; case HCI_CONNECTED_STATE: if (hci_disconn_complete) { DEBUG_PRINT_P( PSTR("\r\nWiimote Disconnected") ); hci_state_ = HCI_INIT_STATE; hci_counter_ = 10; l2cap_state_ = L2CAP_DOWN_STATE; wiiremote_status_ &= ~WIIREMOTE_STATE_CONNECTED; } break; default: break; } // switch (hci_state_) return; } // HCI_task void WiiRemote::HCI_event_task(void) { uint8_t rcode = 0; // return code uint8_t buf[MAX_BUFFER_SIZE] = {0}; // check input on the event pipe (endpoint 1) rcode = Usb.inTransfer(BT_ADDR, ep_record_[ EVENT_PIPE ].epAddr, MAX_BUFFER_SIZE, (char *) buf, USB_NAK_NOWAIT); /* DEBUG_PRINT_P( PSTR("\r\nHCI_event_task: rcode = 0x") ); DEBUG_PRINT(rcode, HEX); */ if (!rcode) { /* buf[0] = Event Code */ /* buf[1] = Parameter Total Length */ /* buf[n] = Event Parameters based on each event */ DEBUG_PRINT_P( PSTR("\r\nHCI event = 0x") ); DEBUG_PRINT(buf[0], HEX); switch (buf[0]) { // switch on event type case HCI_EVENT_COMMAND_COMPLETE: hci_event_flag_ |= HCI_FLAG_COMMAND_COMPLETE; break; case HCI_EVENT_INQUIRY_RESULT: hci_event_flag_ |= HCI_FLAG_INQUIRY_RESULT; /* assume that Num_Responses is 1 */ DEBUG_PRINT_P( PSTR("\r\nFound WiiRemote BD_ADDR:\t") ); for (uint8_t i = 0; i < 6; i++) { wiiremote_bdaddr_[5-i] = (uint8_t) buf[3+i]; DEBUG_PRINT(wiiremote_bdaddr_[5-i], HEX); } break; case HCI_EVENT_INQUIRY_COMPLETE: hci_event_flag_ |= HCI_FLAG_INQUIRY_COMPLETE; break; case HCI_EVENT_COMMAND_STATUS: hci_event_flag_ |= HCI_FLAG_COMMAND_STATUS; #if WIIREMOTE_DEBUG if (buf[2]) { // show status on serial if not OK DEBUG_PRINT_P( PSTR("\r\nHCI Command Failed: ") ); DEBUG_PRINT_P( PSTR("\r\n\t Status = ") ); DEBUG_PRINT(buf[2], HEX); DEBUG_PRINT_P( PSTR("\r\n\tCommand_OpCode(OGF) = ") ); DEBUG_PRINT( ((buf[5] & 0xFC) >> 2), HEX); DEBUG_PRINT_P( PSTR("\r\n\tCommand_OpCode(OCF) = ") ); DEBUG_PRINT( (buf[5] & 0x03), HEX); DEBUG_PRINT(buf[4], HEX); } #endif break; case HCI_EVENT_CONNECT_COMPLETE: hci_event_flag_ |= HCI_FLAG_CONNECT_COMPLETE; if (!buf[2]) { // check if connected OK // store the handle for the ACL connection hci_handle_ = buf[3] | ((buf[4] & 0x0F) << 8); hci_event_flag_ |= HCI_FLAG_CONNECT_OK; } break; case HCI_EVENT_NUM_COMPLETED_PKT: #if WIIREMOTE_DEBUG DEBUG_PRINT_P( PSTR("\r\nHCI Number Of Completed Packets Event: ") ); DEBUG_PRINT_P( PSTR("\r\n\tNumber_of_Handles = 0x") ); DEBUG_PRINT(buf[2], HEX); for (uint8_t i = 0; i < buf[2]; i++) { DEBUG_PRINT_P( PSTR("\r\n\tConnection_Handle = 0x") ); DEBUG_PRINT((buf[3+i] | ((buf[4+i] & 0x0F) << 8)), HEX); } #endif break; case HCI_EVENT_QOS_SETUP_COMPLETE: break; case HCI_EVENT_DISCONN_COMPLETE: hci_event_flag_ |= HCI_FLAG_DISCONN_COMPLETE; DEBUG_PRINT_P( PSTR("\r\nHCI Disconnection Complete Event: ") ); DEBUG_PRINT_P( PSTR("\r\n\t Status = 0x") ); DEBUG_PRINT(buf[2], HEX); DEBUG_PRINT_P( PSTR("\r\n\tConnection_Handle = 0x") ); DEBUG_PRINT((buf[3] | ((buf[4] & 0x0F) << 8)), HEX); DEBUG_PRINT_P( PSTR("\r\n\t Reason = 0x") ); DEBUG_PRINT(buf[5], HEX); break; default: DEBUG_PRINT_P( PSTR("\r\nUnmanaged Event: 0x") ); DEBUG_PRINT(buf[0], HEX); break; } // switch (buf[0]) } return; } // HCI_event_task /************************************************************/ /* HCI Commands */ /************************************************************/ uint8_t WiiRemote::hci_reset(void) { uint8_t buf[3] = {0}; hci_event_flag_ = 0; // clear all the flags buf[0] = HCI_OCF_RESET; buf[1] = HCI_OGF_CTRL_BBAND; buf[2] = 0x00; // Parameter Total Length = 0 return HCI_Command(3, buf); } #if 0 uint8_t hci_read_bd_addr(void) { uint8_t buf[3] = {0}; hci_event_flag_ &= ~HCI_FLAG_COMMAND_COMPLETE; buf[0] = HCI_OCF_READ_BD_ADDR; buf[1] = HCI_OGF_INFO_PARAM; buf[2] = 0x00; // Parameter Total Length = 0 return HCI_Command(3, buf); } #endif uint8_t WiiRemote::hci_inquiry(void) { uint8_t buf[8] = {0}; hci_event_flag_ &= ~(HCI_FLAG_INQUIRY_RESULT | HCI_FLAG_INQUIRY_COMPLETE); buf[0] = HCI_OCF_INQUIRY; buf[1] = HCI_OGF_LINK_CNTRL; buf[2] = 0x05; // Parameter Total Length = 5 buf[3] = 0x33; // LAP: Genera/Unlimited Inquiry Access Code (GIAC = 0x9E8B33) buf[4] = 0x8B; buf[5] = 0x9E; buf[6] = 0x0A; // Inquiry time buf[7] = 0x03; // Max 1 response return HCI_Command(8, buf); } uint8_t WiiRemote::hci_inquiry_cancel(void) { uint8_t buf[3] = {0}; hci_event_flag_ &= ~HCI_FLAG_COMMAND_COMPLETE; buf[0] = HCI_OCF_INQUIRY_CANCEL; buf[1] = HCI_OGF_LINK_CNTRL; buf[2] = 0x0; // Parameter Total Length = 0 return HCI_Command(3, buf); } uint8_t WiiRemote::hci_connect(uint8_t *bdaddr) { uint8_t buf[16] = {0}; hci_event_flag_ &= ~(HCI_FLAG_CONNECT_COMPLETE | HCI_FLAG_CONNECT_OK); buf[0] = HCI_OCF_CREATE_CONNECTION; buf[1] = HCI_OGF_LINK_CNTRL; buf[2] = 0x0D; // Parameter Total Length = 13 buf[3] = *(bdaddr + 5); // 6 octet bluetooth address buf[4] = *(bdaddr + 4); buf[5] = *(bdaddr + 3); buf[6] = *(bdaddr + 2); buf[7] = *(bdaddr + 1); buf[8] = *bdaddr; buf[ 9] = 0x18; // DM1 or DH1 may be used buf[10] = 0xCC; // DM3, DH3, DM5, DH5 may be used buf[11] = 0x01; // page repetition mode R1 buf[12] = 0x00; // always 0 buf[13] = 0x00; // clock offset buf[14] = 0x00; // invalid clock offset buf[15] = 0x00; // do not allow role switch return HCI_Command(16, buf); } /* perform HCI Command */ uint8_t WiiRemote::HCI_Command(uint16_t nbytes, uint8_t *dataptr) { //hci_event_flag_ &= ~HCI_FLAG_COMMAND_COMPLETE; return Usb.ctrlReq(BT_ADDR, ep_record_[ CONTROL_PIPE ].epAddr, bmREQ_HCI_OUT, HCI_COMMAND_REQ, 0x00, 0x00, 0, nbytes, (char *) dataptr); } /************************************************************/ /* L2CAP Flow Control */ /************************************************************/ void WiiRemote::L2CAP_task(void) { L2CAP_event_task(); switch (l2cap_state_) { case L2CAP_DOWN_STATE: break; case L2CAP_INIT_STATE: l2cap_event_status_ = 0; l2cap_connect(command_scid_, L2CAP_PSM_WRITE); l2cap_state_ = L2CAP_CONTROL_CONNECTING_STATE; break; case L2CAP_CONTROL_CONNECTING_STATE: if (l2cap_command_connected) { l2cap_event_status_ &= ~L2CAP_EV_COMMAND_CONFIGURED; l2cap_configure(command_dcid_); l2cap_state_ = L2CAP_CONTROL_CONFIGURING_STATE; } break; case L2CAP_CONTROL_CONFIGURING_STATE: if (l2cap_command_configured) { l2cap_event_status_ &= ~L2CAP_EV_INTERRUPT_CONNECTED; l2cap_connect(interrupt_scid_, L2CAP_PSM_READ); l2cap_state_ = L2CAP_INTERRUPT_CONNECTING_STATE; } break; case L2CAP_INTERRUPT_CONNECTING_STATE: if (l2cap_interrupt_connected) { l2cap_event_status_ &= ~L2CAP_EV_INTERRUPT_CONFIGURED; l2cap_configure(interrupt_dcid_); l2cap_state_ = L2CAP_INTERRUPT_CONFIGURING_STATE; } break; case L2CAP_INTERRUPT_CONFIGURING_STATE: if (l2cap_interrupt_configured) { l2cap_state_ = L2CAP_CONNECTED_STATE; } break; /* Established L2CAP */ case L2CAP_CONNECTED_STATE: hid_flags_ = 0; setLED(WIIREMOTE_LED1); //delay(500); l2cap_state_ = L2CAP_WIIREMOTE_LED_STATE; break; case L2CAP_WIIREMOTE_LED_STATE: if (hid_command_success) { readWiiRemoteCalibration(); l2cap_state_ = L2CAP_WIIREMOTE_CAL_STATE; } break; /* case L2CAP_CALIBRATION_STATE: if (hid_read_calibration) { setLED(WIIREMOTE_LED2); delay(600); l2cap_state_ = L2CAP_LED2_STATE; } break; case L2CAP_LED2_STATE: if (hid_command_success) { setLED(WIIREMOTE_LED3); delay(600); l2cap_state_ = L2CAP_LED3_STATE; } break; */ case L2CAP_WIIREMOTE_CAL_STATE: if (hid_command_success) { setReportMode(INPUT_REPORT_IR_EXT_ACCEL); l2cap_state_ = L2CAP_READY_STATE; wiiremote_status_ |= WIIREMOTE_STATE_RUNNING; } break; /* case L2CAP_REPORT_MODE_STATE: if (hid_command_success) { setLED(WIIREMOTE_LED4); l2cap_state_ = L2CAP_READY_STATE; } break; case L2CAP_LED4_STATE: if (hid_command_success) { l2cap_state_ = L2CAP_READY_STATE; } break; */ case L2CAP_READY_STATE: // a status report will require reporting to be restarted if (hid_status_reported) { setReportMode(INPUT_REPORT_IR_EXT_ACCEL); } if (l2cap_interrupt_disconnected || l2cap_command_disconnected) { l2cap_state_ = L2CAP_DISCONNECT_STATE; wiiremote_status_ &= ~WIIREMOTE_STATE_RUNNING; } break; case L2CAP_DISCONNECT_STATE: break; default: break; } return; } // L2CAP_task void WiiRemote::L2CAP_event_task(void) { uint8_t rcode = 0; // return code uint8_t buf[MAX_BUFFER_SIZE] = {0}; static uint8_t prev_rcode = 0; // check input on the event pipe (endpoint 2) rcode = Usb.inTransfer(BT_ADDR, ep_record_[ DATAIN_PIPE ].epAddr, MAX_BUFFER_SIZE, (char *) buf, USB_NAK_NOWAIT); /* DEBUG_PRINT_P( PSTR("\r\nL2CAP_event_task: rcode = 0x") ); DEBUG_PRINT(rcode, HEX); */ if (!rcode) { if (acl_handle_ok) { if (l2cap_control) { DEBUG_PRINT_P( PSTR("\r\nL2CAP Signaling Command = 0x") ); DEBUG_PRINT(buf[8], HEX); if (l2cap_connection_response) { if (l2cap_connection_success) { if ((buf[14] | (buf[15] << 8)) == command_scid_) { command_dcid_ = buf[12] | (buf[13] << 8); l2cap_event_status_ |= L2CAP_EV_COMMAND_CONNECTED; } else if ((buf[14] | (buf[15] << 8)) == interrupt_scid_) { interrupt_dcid_ = buf[12] | ( buf[13] << 8); l2cap_event_status_ |= L2CAP_EV_INTERRUPT_CONNECTED; } } // l2cap_connection_success } // l2cap_connection_response else if (l2cap_configuration_response) { /* TODO l2cap_configuration_success */ if ((buf[12] | (buf[13] << 8)) == command_scid_) { l2cap_event_status_ |= L2CAP_EV_COMMAND_CONFIGURED; } else if ((buf[12] | (buf[13] << 8)) == interrupt_scid_) { l2cap_event_status_ |= L2CAP_EV_INTERRUPT_CONFIGURED; } } else if (l2cap_configuration_request) { if ((buf[12] | (buf[13] << 8)) == command_scid_) { l2cap_event_status_ |= L2CAP_EV_COMMAND_CONFIG_REQ; l2cap_config_response(buf[9], command_dcid_); } else if ((buf[12] | (buf[13] << 8)) == interrupt_scid_) { l2cap_event_status_ |= L2CAP_EV_INTERRUPT_CONFIG_REQ; l2cap_config_response(buf[9], interrupt_dcid_); } } else if (l2cap_disconnect_request) { if ((buf[12] | (buf[13] << 8)) == command_scid_) { l2cap_event_status_ |= L2CAP_EV_COMMAND_DISCONNECT_REQ; l2cap_disconnect_response(buf[9], command_scid_, command_dcid_); } else if ((buf[12] | (buf[13] << 8)) == interrupt_scid_) { l2cap_event_status_ |= L2CAP_EV_INTERRUPT_DISCONNECT_REQ; l2cap_disconnect_response(buf[9], command_scid_, command_dcid_); } } } // l2cap_control else if (l2cap_interrupt) { readReport(buf); wiiremote_status_ |= WIIREMOTE_STATE_RUNNING; } // l2cap_interrupt else if (l2cap_command){ if (hid_handshake_success) { hid_flags_ |= HID_FLAG_COMMAND_SUCCESS; } } // l2cap_command } // acl_handle_ok } // !rcode // check whether NAK is occured if ((prev_rcode == hrSUCCESS) && (rcode == hrNAK)) { wiiremote_status_ &= ~WIIREMOTE_STATE_RUNNING; } prev_rcode = rcode; return; } // L2CAP_event_task /************************************************************/ /* L2CAP Commands */ /************************************************************/ uint8_t WiiRemote::l2cap_connect(uint16_t scid, uint16_t psm) { uint8_t cmd_buf[8]; cmd_buf[0] = L2CAP_CMD_CONNECTION_REQUEST; // Code cmd_buf[1] = (uint8_t) (l2cap_txid_++); // Identifier cmd_buf[2] = 0x04; // Length cmd_buf[3] = 0x00; cmd_buf[4] = (uint8_t) (psm & 0xff); // PSM cmd_buf[5] = (uint8_t) (psm >> 8); cmd_buf[6] = (uint8_t) (scid & 0xff); // Source CID cmd_buf[7] = (uint8_t) (scid >> 8); return L2CAP_Command((uint8_t *) cmd_buf, 8); } uint8_t WiiRemote::l2cap_configure(uint16_t dcid) { uint8_t cmd_buf[12]; cmd_buf[0] = L2CAP_CMD_CONFIG_REQUEST; // Code cmd_buf[1] = (uint8_t) (l2cap_txid_++); // Identifier cmd_buf[2] = 0x08; // Length cmd_buf[3] = 0x00; cmd_buf[4] = (uint8_t) (dcid & 0xff); // Destination CID cmd_buf[5] = (uint8_t) (dcid >> 8); cmd_buf[6] = 0x00; // Flags cmd_buf[7] = 0x00; cmd_buf[8] = 0x01; // Config Opt: type = MTU (Maximum Transmission Unit) cmd_buf[9] = 0x02; // Config Opt: length cmd_buf[10] = 0xa0; // Config Opt: data = masimum SDU size is 672 octets cmd_buf[11] = 0x02; return L2CAP_Command((uint8_t *) cmd_buf, 12); } uint8_t WiiRemote::l2cap_config_response( uint8_t rxid, uint16_t dcid) { uint8_t resp_buf[10]; resp_buf[0] = L2CAP_CMD_CONFIG_RESPONSE; // Code resp_buf[1] = rxid; // Identifier resp_buf[2] = 0x06; // Length resp_buf[3] = 0x00; resp_buf[4] = (uint8_t) (dcid & 0xff); // Source CID resp_buf[5] = (uint8_t) (dcid >> 8); resp_buf[6] = 0x00; // Result resp_buf[7] = 0x00; resp_buf[8] = 0x00; // Config resp_buf[9] = 0x00; return L2CAP_Command((uint8_t *) resp_buf, 10); } uint8_t WiiRemote::l2cap_disconnect_response( uint8_t rxid, uint16_t scid, uint16_t dcid) { uint8_t resp_buf[8]; resp_buf[0] = L2CAP_CMD_DISCONNECT_RESPONSE; // Code resp_buf[1] = rxid; // Identifier resp_buf[2] = 0x04; // Length resp_buf[3] = 0x00; resp_buf[4] = (uint8_t) (dcid & 0xff); // Destination CID resp_buf[5] = (uint8_t) (dcid >> 8); resp_buf[6] = (uint8_t) (scid & 0xff); // Source CID resp_buf[7] = (uint8_t) (scid >> 8); return L2CAP_Command((uint8_t *) resp_buf, 8); } uint8_t WiiRemote::L2CAP_Command(uint8_t *data, uint8_t length) { uint8_t buf[MAX_BUFFER_SIZE] = {0}; buf[0] = (uint8_t) (hci_handle_ & 0xff); // HCI handle with PB,BC flag buf[1] = (uint8_t) (((hci_handle_ >> 8) & 0x0f) | 0x20); buf[2] = (uint8_t) ((4 + length) & 0xff); // HCI ACL total data length buf[3] = (uint8_t) ((4 + length) >> 8); buf[4] = (uint8_t) (length & 0xff); // L2CAP header: Length buf[5] = (uint8_t) (length >> 8); buf[6] = 0x01; // L2CAP header: Channel ID buf[7] = 0x00; // L2CAP Signalling channel over ACL-U logical link for (uint8_t i = 0; i < length; i++) { // L2CAP C-frame buf[8+i] = *data; data++; } // output on endpoint 2 return Usb.outTransfer(BT_ADDR, ep_record_[ DATAOUT_PIPE ].epAddr, (8 + length), (char *) buf); } /************************************************************/ /* HID Report (HCI ACL Packet) */ /************************************************************/ void WiiRemote::readReport(uint8_t *data) { if (data[8] == HID_THDR_DATA_INPUT) { switch (data[9]) { case INPUT_REPORT_STATUS: hid_flags_ |= HID_FLAG_STATUS_REPORTED; break; case INPUT_REPORT_READ_DATA: /* (a1) 21 BB BB SE FF FF DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD */ /* BB BB is the state of the buttons on the Wiimote */ /* E (low nybble of SE) is the error flag. Error value 0 for no error. */ /* S (high nybble of SE) is the size in bytes, minus one. */ /* FF FF is the offset expressed in abs. memory address of 1st byte. */ if ((data[12] & 0x0f) == 0) { if ((data[13] == 0x00) && (data[14] == 0x16)) { hid_flags_ |= HID_FLAG_READ_CALIBRATION; parseCalData(data); } } break; case INPUT_REPORT_IR_EXT_ACCEL: /* (a1) 37 BB BB AA AA AA II II II II II II II II II II EE EE EE EE EE EE */ old_hid_buttons_ = hid_buttons_; hid_buttons_ = (data[10] & 0x9f) | (data[11] & 0x9f) << 8; if (hid_buttons_ != old_hid_buttons_) { hid_flags_ |= HID_FLAG_BUTTONS_CHANGED; } else { hid_flags_ &= ~HID_FLAG_BUTTONS_CHANGED; } hid_buttons_click_ = ~hid_buttons_ & old_hid_buttons_; parseAccel(data); //parseButtons(data); /* buttonPressed() can be used */ break; default: DEBUG_PRINT_P( PSTR("\r\nUnmanaged Input Report: ") ); DEBUG_PRINT(data[9], HEX); break; } } } // readReport uint8_t WiiRemote::writeReport(uint8_t *data, uint8_t length) { uint8_t buf[MAX_BUFFER_SIZE] = {0}; buf[0] = (uint8_t) (hci_handle_ & 0xff); // HCI handle with PB,BC flag buf[1] = (uint8_t) (((hci_handle_ >> 8) & 0x0f) | 0x20); buf[2] = (uint8_t) ((5 + length) & 0xff); // HCI ACL total data length buf[3] = (uint8_t) ((5 + length) >> 8); buf[4] = (uint8_t) ((1 + length) & 0xff); // L2CAP header: Length buf[5] = (uint8_t) ((1 + length) >> 8); buf[6] = (uint8_t) (command_dcid_ & 0xff); // L2CAP header: Channel ID buf[7] = (uint8_t) (command_dcid_ >> 8); buf[8] = HID_THDR_SET_REPORT_OUTPUT; // L2CAP B-frame for (uint8_t i = 0; i < length; i++) { buf[9+i] = *data; data++; } hid_flags_ &= ~HID_FLAG_COMMAND_SUCCESS; // output on endpoint 2 return Usb.outTransfer(BT_ADDR, ep_record_[ DATAOUT_PIPE ].epAddr, (9 + length), (char *) buf); } // writeReport void WiiRemote::parseCalData(uint8_t *data) { //uint8_t nbytes = ((data[12] & 0xf0) >> 4) + 1; Accel_Cal_.offset.X = (data[15] << 2) | (data[18] & 0x30) >> 4; Accel_Cal_.offset.Y = (data[16] << 2) | (data[18] & 0x0c) >> 2; Accel_Cal_.offset.Z = (data[17] << 2) | (data[18] & 0x03); Accel_Cal_.gravity.X = (data[19] << 2) | (data[22] & 0x30) >> 4; Accel_Cal_.gravity.Y = (data[20] << 2) | (data[22] & 0x0c) >> 2; Accel_Cal_.gravity.Z = (data[21] << 2) | (data[22] & 0x03); DEBUG_PRINT_P( PSTR("\r\nCalibration Data") ); DEBUG_PRINT_P( PSTR("\r\n\tX0 = ") ); DEBUG_PRINT(Accel_Cal_.offset.X, HEX); DEBUG_PRINT_P( PSTR("\r\n\tY0 = ") ); DEBUG_PRINT(Accel_Cal_.offset.Y, HEX); DEBUG_PRINT_P( PSTR("\r\n\tZ0 = ") ); DEBUG_PRINT(Accel_Cal_.offset.Z, HEX); DEBUG_PRINT_P( PSTR("\r\n\tXG = ") ); DEBUG_PRINT(Accel_Cal_.gravity.X, HEX); DEBUG_PRINT_P( PSTR("\r\n\tYG = ") ); DEBUG_PRINT(Accel_Cal_.gravity.Y, HEX); DEBUG_PRINT_P( PSTR("\r\n\tZG = ") ); DEBUG_PRINT(Accel_Cal_.gravity.Z, HEX); } // parseCalData void WiiRemote::parseAccel(uint8_t *data) { static uint8_t accel_cnt; uint8_t i = accel_cnt++ % ACCEL_AVERAGE_SIZE; Point3f_t accel_avg; /* In all Data Reporting Modes which include Accelerometer data except */ /* for mode 0x3e/0x3f, the accelerometer data is reported as three */ /* consecutive bytes XX, YY and ZZ: */ /* (a1) RR BB BB XX YY ZZ [...] */ Accel_Raw_[i].X = (data[12] << 2) | ((data[10] & 0x60) >> 5); Accel_Raw_[i].Y = (data[13] << 2) | ((data[11] & 0x20) >> 4); Accel_Raw_[i].Z = (data[14] << 2) | ((data[11] & 0x40) >> 5); if (accel_cnt >= ACCEL_AVERAGE_SIZE) { accel_avg = averagePoint3(Accel_Raw_, ACCEL_AVERAGE_SIZE); } else { accel_avg.X = (float) Accel_Cal_.offset.X; accel_avg.Y = (float) Accel_Cal_.offset.Y; accel_avg.Z = (float) Accel_Cal_.offset.Z; } Report.Accel.X = (accel_avg.X - (float) Accel_Cal_.offset.X) / (float) (Accel_Cal_.gravity.X - Accel_Cal_.offset.X); Report.Accel.Y = (accel_avg.Y - (float) Accel_Cal_.offset.Y) / (float) (Accel_Cal_.gravity.Y - Accel_Cal_.offset.Y); Report.Accel.Z = (accel_avg.Z - (float) Accel_Cal_.offset.Z) / (float) (Accel_Cal_.gravity.Z - Accel_Cal_.offset.Z); #if 0 DEBUG_PRINT_P( PSTR("\r\nparseAccel X=") ); DEBUG_PRINT(Report.Accel.X, 2); DEBUG_PRINT_P( PSTR(" Y=") ); DEBUG_PRINT(Report.Accel.Y, 2); DEBUG_PRINT_P( PSTR(" Z=") ); DEBUG_PRINT(Report.Accel.Z, 2); #endif } // parseAccel void WiiRemote::parseButtons(uint8_t *data) { uint16_t buttons = (data[10] & 0x9f) | (data[11] & 0x9f) << 8; Report.Button.Left = ((buttons & WIIREMOTE_LEFT) != 0); Report.Button.Right = ((buttons & WIIREMOTE_RIGHT) != 0); Report.Button.Down = ((buttons & WIIREMOTE_DOWN) != 0); Report.Button.Up = ((buttons & WIIREMOTE_UP) != 0); Report.Button.Plus = ((buttons & WIIREMOTE_PLUS) != 0); Report.Button.Two = ((buttons & WIIREMOTE_TWO) != 0); Report.Button.One = ((buttons & WIIREMOTE_ONE) != 0); Report.Button.B = ((buttons & WIIREMOTE_B) != 0); Report.Button.A = ((buttons & WIIREMOTE_A) != 0); Report.Button.Minus = ((buttons & WIIREMOTE_MINUS) != 0); Report.Button.Home = ((buttons & WIIREMOTE_HOME) != 0); } // parseButtons /************************************************************/ /* WiiRemote HID Command (primitive) */ /************************************************************/ uint8_t WiiRemote::setLED(uint8_t led) { uint8_t hid_buf[2]; hid_buf[0] = OUTPUT_REPORT_LED; hid_buf[1] = led; //hid_flags_ &= ~HID_FLAG_COMMAND_SUCCESS; return writeReport((uint8_t *) hid_buf, 2); } uint8_t WiiRemote::setReportMode(uint8_t mode) { uint8_t hid_buf[3]; hid_buf[0] = OUTPUT_REPORT_MODE; hid_buf[1] = 0x00; // Wiimote will only send an report when the data has changed hid_buf[2] = mode; //hid_flags_ &= ~HID_FLAG_COMMAND_SUCCESS; hid_flags_ &= ~HID_FLAG_STATUS_REPORTED; return writeReport((uint8_t *) hid_buf, 3); } uint8_t WiiRemote::readData(uint32_t offset, uint16_t size) { uint8_t hid_buf[7]; hid_buf[0] = OUTPUT_REPORT_READ_DATA; hid_buf[1] = (uint8_t) ((offset & 0xff000000) >> 24); /* TODO involve Rumble flag */ hid_buf[2] = (uint8_t) ((offset & 0x00ff0000) >> 16); hid_buf[3] = (uint8_t) ((offset & 0x0000ff00) >> 8); hid_buf[4] = (uint8_t) ((offset & 0x000000ff)); hid_buf[5] = (uint8_t) ((size & 0xff00) >> 8); hid_buf[6] = (uint8_t) ((size & 0x00ff)); //hid_flags_ &= ~HID_FLAG_COMMAND_SUCCESS; hid_flags_ &= ~HID_FLAG_READ_CALIBRATION; return writeReport((uint8_t *) hid_buf, 7); } /************************************************************/ /* WiiRemote Command */ /************************************************************/ uint8_t WiiRemote::readWiiRemoteCalibration(void) { return readData(0x0016, 8); } bool WiiRemote::buttonPressed(uint16_t button) { /* true while a button is pressed */ return ((hid_buttons_ & button) != 0); } bool WiiRemote::buttonClicked(uint16_t button) { /* true when a button is clicked */ bool click = ((hid_buttons_click_ & button) != 0); hid_buttons_click_ &= ~button; // clear "click" event return click; } /************************************************************/ /* etc */ /************************************************************/ Point3f_t WiiRemote::averagePoint3(Point3i_t *data, uint8_t size) { Point3f_t sum = {0.0, 0.0, 0.0}; for (uint8_t i = 0; i < size; i++) { sum.X += (float) data->X; sum.Y += (float) data->Y; sum.Z += (float) data->Z; data++; } sum.X /= size; sum.Y /= size; sum.Z /= size; return sum; } // vim: sts=4 sw=4 ts=4 et cin fdm=marker cms=//%s syntax=arduino
c4c7429d9a795a093fac4f2330d2e6544a0d5b5c
857d865574bb4eabd9dfdd12c39fa8038c1317a0
/Source/Runtime/D3D11RHI/DX11/Bindable/Topology.h
a9a31e7db153ebd2097a24246a3766e1b45b97f7
[]
no_license
WssIDs/SimpleGameEngine
ee112af1e4910a891888121628e621566ecb2e07
92b310a90858d4b8301308d00de4dd40584e73ff
refs/heads/master
2021-12-27T13:42:29.027676
2021-12-21T00:15:10
2021-12-21T00:15:10
222,161,333
1
0
null
null
null
null
UTF-8
C++
false
false
469
h
Topology.h
#pragma once #include <Runtime/D3D11RHI/DX11/Bindable/Bindable.h> namespace Bind { class Topology : public Bindable { public: Topology(DX11RHI& gfx, D3D_PRIMITIVE_TOPOLOGY type); virtual void Bind(DX11RHI& gfx) override; static std::shared_ptr<Topology> Resolve(DX11RHI& gfx, D3D_PRIMITIVE_TOPOLOGY type); static std::string GenerateUID(D3D_PRIMITIVE_TOPOLOGY type); std::string GetUID() const override; protected: D3D_PRIMITIVE_TOPOLOGY type; }; }
33cfc1d4ea236897e1384555c84e06aebc47e278
27595b0aa0ab23e6307adb1e22aebc6b11619c36
/LP_Lab14/Automat.h
6edb6a5bad5c4d4a97e2e1addaf4a2a608d3bc38
[]
no_license
Harwex213/Prog_Langs_3sem
16f888ed1dee46cacb8a8fe5132301dd9a176aad
aa070c7061d3d62f2f7cdde180c1bbad5a123e6b
refs/heads/master
2023-02-01T04:37:34.690024
2020-12-15T23:51:52
2020-12-15T23:51:52
293,024,483
0
2
null
2020-09-11T07:15:34
2020-09-05T07:17:34
C++
UTF-8
C++
false
false
249
h
Automat.h
#pragma once #include "FST.h" #include "IT.h" #include "Graph.h" namespace Automat { struct AUTOMAT { FST::FST* KeyWord = NULL; char* nothing = NULL; FST::FST selectGraph = { GRAPH_SELECT }; FST::FST& operator[] (const char index); }; }