blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
5ebe70a76592a6d67dc25b9584c9e79f26ec82bd
888ff1ff4f76c61e0a2cff281f3fae2c9a4dcb7b
/jianzhioffer/52.cpp
cf4e321d66bff39ad26a6da20895e4a0cbb78500
[]
no_license
sanjusss/leetcode-cpp
59e243fa41cd5a1e59fc1f0c6ec13161fae9a85b
8bdf45a26f343b221caaf5be9d052c9819f29258
refs/heads/master
2023-08-18T01:02:47.798498
2023-08-15T00:30:51
2023-08-15T00:30:51
179,413,256
0
0
null
null
null
null
UTF-8
C++
false
false
679
cpp
/* * @Author: sanjusss * @Date: 2021-07-21 08:19:55 * @LastEditors: sanjusss * @LastEditTime: 2021-07-21 08:23:40 * @FilePath: \jianzhioffer\52.cpp */ #include "leetcode.h" class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { ListNode* pA = headA; ListNode* pB = headB; while (pA != pB) { if (pA == nullptr) { pA = headB; } else { pA = pA->next; } if (pB == nullptr) { pB = headA; } else { pB = pB->next; } } return pA; } };
[ "sanjusss@qq.com" ]
sanjusss@qq.com
a78dc583c752aa2cbe56ceeccc91496506cfce42
aabf2d9eacfc7bdafce823920507c073b94d24f5
/RaccoonBranch/SharedFiles/QLib/ParamsDialog/ParamsLevelExposure.cpp
2965eaaaa0eafff512699fcc0db7a34699203cab
[]
no_license
SlavaC1/ControlSW
90a5cf3709ea3d49db5126f0091c89428f5e1f49
6c8af513233a5d3d7c7f0d8b4d89c0ee69a661cb
refs/heads/master
2021-01-10T15:47:23.183784
2016-03-04T13:33:26
2016-03-04T13:33:26
53,054,100
0
0
null
null
null
null
UTF-8
C++
false
false
3,050
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "MainUnit.h" #include "ParamsLevelExposure.h" #include "AppParams.h" #include "QThreadUtils.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TParametersExposureLevelForm *ParametersExposureLevelForm; //--------------------------------------------------------------------------- __fastcall TParametersExposureLevelForm::TParametersExposureLevelForm(TComponent* Owner) : TForm(Owner) {} //--------------------------------------------------------------------------- void __fastcall TParametersExposureLevelForm::CancelButtonClick(TObject *Sender) { PasswordMaskEdit->Clear(); Close(); } //--------------------------------------------------------------------------- void __fastcall TParametersExposureLevelForm::OkButtonClick(TObject *Sender) { time_t rawtime; struct tm * timeinfo; time ( &rawtime ); timeinfo = localtime ( &rawtime ); int res = timeinfo->tm_mday*timeinfo->tm_mday+(timeinfo->tm_mon+1)*(timeinfo->tm_mon+1)+timeinfo->tm_year; QString str = "EMPM" + QIntToStr(res); if(strcmp(str.c_str(),PasswordMaskEdit->Text.c_str())==0) { PasswordMaskEdit->Clear(); IncorrectPass->Visible = false; MainForm->SetCurrentParamLevel(SUPER_USER_LEVEL); MainForm->SetValidPassword(true); Close(); MainForm->OpenParamsDialogActionExecute(Sender); } else { IncorrectPass->Visible = true; MainForm->SetCurrentParamLevel(SERVICE_LEVEL); MainForm->SetValidPassword(false); } } //--------------------------------------------------------------------------- void __fastcall TParametersExposureLevelForm::FormShow(TObject *Sender) { TRadioButton *MyRadio; int CurrentLevel = -1; CurrentLevel = MainForm->GetCurrentParamLevel(); for (int i = 0; i < ChooseUserGroupBox->ControlCount; i++) { MyRadio = dynamic_cast<TRadioButton *>(ChooseUserGroupBox->Controls[i]); if (MyRadio != NULL) if(MyRadio->Tag == CurrentLevel) { MyRadio->Checked = true; break; } } Timer1->Enabled = true; IncorrectPass->Visible = false; } //--------------------------------------------------------------------------- void __fastcall TParametersExposureLevelForm::Timer1Timer(TObject *Sender) { while( GetTopWindow(NULL) != this->Handle ) { Timer1->Enabled = false; SetWindowPos(this->Handle,HWND_TOPMOST,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_SHOWWINDOW); } } //--------------------------------------------------------------------------- void __fastcall TParametersExposureLevelForm::FormClose(TObject *Sender, TCloseAction &Action) { Timer1->Enabled = false; } //--------------------------------------------------------------------------- void __fastcall TParametersExposureLevelForm::FormPaint(TObject *Sender) { Timer1->Enabled = false; } //---------------------------------------------------------------------------
[ "wastelanders@gmail.com" ]
wastelanders@gmail.com
b31be5a92613a0e8d0a4221d580590c0162ae5e6
3c09d1c279c8578791dae535852c06e09efad4a1
/EclipseCpp/11.Calendar/src/11.Calendar.cpp
77bea8ca43b837c6a471bc8990e0f382357689f2
[]
no_license
rosen90/GitHub
f00653f8a65cdffc479b70d2d7ca8f9e103d3eeb
851d210f2f6073d818e0984fa9daab96e833b066
refs/heads/master
2016-09-12T23:57:19.530896
2016-05-04T22:09:03
2016-05-04T22:09:03
58,085,509
0
0
null
null
null
null
UTF-8
C++
false
false
725
cpp
#include <iostream> using namespace std; int main() { int day, mounth, year; int period; cout << "Enter a year (XXXX): "; cin >> year; cout << "Enter Month (0-12):"; cin >> mounth; cout << "Enter day: (0-30): "; cin >> day; cout << "Enter the period in days: "; cin >> period; int temp; int temp2 = period; temp = ((period % 365) % 30); day += temp; if(day > 30) { mounth++; day %= 30; } temp = period % 365; period = temp; temp = period / 30; mounth += temp; if(mounth > 12) { year++; mounth %= 12; } period = temp2; temp = period / 365; year += temp; if(year % 4 == 0) { day +=1; } cout << "Future date: " << year <<", " << mounth << ", " << day; return 0; }
[ "karadinev@gmail.com" ]
karadinev@gmail.com
3680a6bedf2d234e89d41975a06704c0e619736c
13be382f6162250767c976bb0336b7d334e61956
/c20200625/Paly844/Paly844.h
452fe24a695e0610eab3c7999b2d1eb01c0a85ea
[]
no_license
liupengzhouyi/LeetCode
8cfa79041b31fd7b1742892656f2918e006ea31f
19cffe0aad21c099abdfd80e03d961035be4e332
refs/heads/master
2021-07-10T01:06:31.490053
2021-03-24T07:56:43
2021-03-24T07:56:43
229,280,974
0
0
null
null
null
null
UTF-8
C++
false
false
271
h
// // Created by 刘鹏 on 2020/6/25. // #ifndef LEETCODE_PALY844_H #define LEETCODE_PALY844_H #include <iostream> #include <vector> #include <stack> class Paly844 { public: bool backspaceCompare(::std::string S, ::std::string T); }; #endif //LEETCODE_PALY844_H
[ "liupeng.0@outlook.com" ]
liupeng.0@outlook.com
737e3fd0c1ec0ed5b3e0493fca31e32ec852cf6a
387abaa47af408b66e071802468e49663668a891
/Graphs/10. Cycle Detection in Undirected graph using BFS.cpp
1aa7c8da6c820150849e09fffad5ba457e42f644
[]
no_license
gargVader/CPP-Data-Structures-Algorithms-Launchpad
22eac05476f6d2d3a9ecdff90c5e6235b3895d7b
af2647a343d6d7b27c0313a745dfcf470639cad8
refs/heads/master
2023-07-27T09:26:21.125449
2021-09-09T04:42:19
2021-09-09T04:42:19
289,625,432
61
36
null
2020-12-10T06:25:20
2020-08-23T05:54:40
C++
UTF-8
C++
false
false
1,644
cpp
/* Cycle detection in undirected graph using BFS ============================================== Run BFS. If we come across a node that has not been visited yet, push it into queue. Otherwise, the node is contributing to a potential cycle. Catch here is that the node (nbr) should not be parent of the current node. If cycle is not present then it is Tree Check if we are visiting a node by more than one path */ #include <iostream> #include<map> #include <queue> #include<list> using namespace std; template<typename T> class Graph { map<T, list<T>> l; public: void addEdge(T x, T y) { l[x].push_back(y); l[y].push_back(x); } bool isTree() { map<T, bool> isVisited; map<T, T> parentOf; for (auto p : l) { T node = p.first; isVisited[node] = 0; parentOf[node] = node; } T src = 1; queue<T> q; q.push(src); isVisited[src] = 1; // BFS // Pop out one node and visit its nbrs while (!q.empty()) { T curr = q.front(); q.pop(); cout << curr << endl; // Push all nbrs of curr for (auto nbr : l[curr]) { if (!isVisited[nbr]) { q.push(nbr); isVisited[nbr] = 1; parentOf[nbr] = curr; } else if (isVisited[nbr] && parentOf[curr] != nbr) { return 0; } } } // for (auto p : parentOf) { // cout << p.first << " " << p.second << endl; // } return 1; } }; int main() { Graph<int> g; // g.addEdge(0, 1); // g.addEdge(0, 3); // g.addEdge(2, 1); // g.addEdge(2, 3); // g.addEdge(3, 4); // g.addEdge(4, 5); g.addEdge(0, 1); g.addEdge(1, 2); g.addEdge(2, 3); g.addEdge(3, 4); g.addEdge(4, 5); cout << g.isTree() << endl; }
[ "girishgargcool@gmail.com" ]
girishgargcool@gmail.com
2eda796082f27dbb1781d0d82fa6926e12b8e3d0
9fdf3aa251c041fbdf35cb43f99ccd3d7b909fbd
/src/lda.cc
bf99b3d4bd03ed186835a1141d807ccb9fbe8d0b
[]
no_license
BurnedRobot/ldacc
5588b06f6e9dd8ad9c31fad5c99e1cf07078d26a
44fb1c464d5891ecb10864c583f43a7a8bf3049b
refs/heads/master
2021-01-19T14:57:18.905782
2015-01-01T07:54:25
2015-01-01T07:54:25
12,204,472
1
0
null
null
null
null
UTF-8
C++
false
false
5,866
cc
#include "../include/lda.h" #include "../include/preprocess.h" #include "../include/multi_sampler.h" #include "../include/utils.h" #include <cstdlib> #include <algorithm> #include <ctime> #include <numeric> void LDA::Init(const char* inputfile) { docs_num = ReadData("../data/document.dat", words_matrix, words_bag); if(0 == docs_num && docs_num != words_matrix.size()) { std::fprintf(stderr,"Numbers of Documents Error!\n"); std::exit(0); } InitCountVariables(); InitTopicIndex(); for(int index_doc = 0; index_doc < docs_num; index_doc++) for(int index_word = 0; index_word < words_matrix[index_doc].size(); index_word++) IncreCountVariables(index_doc, index_word); b_ready = true; } void LDA::InitCountVariables() { NKm_count.resize(docs_num); for_each(NKm_count.begin(), NKm_count.end(), [&](std::vector<int>& vt){ vt.resize(topics_num); }); NKm_sum.resize(docs_num); NTk_count.resize(topics_num); NTk_sum.resize(topics_num); } void LDA::InitTopicIndex() { Zmn.resize(docs_num); int count = 0; for_each(Zmn.begin(), Zmn.end(), [&](std::vector<int>& vt){ vt.resize(words_matrix[count++].size()); }); srand((unsigned)time(0)); std::vector<double> pro_vt(topics_num); std::fill(pro_vt.begin(), pro_vt.end(), (double)(1.0)/topics_num); for_each(Zmn.begin(), Zmn.end(), [&](std::vector<int>& vt) { generate(vt.begin(), vt.end(), [&]{ return GenerateMultiSample(topics_num, pro_vt); }); }); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void LDA::IncreCountVariables(std::size_t index_doc, std::size_t index_word) { int i = Zmn[index_doc][index_word]; (NKm_count)[index_doc][i]++ ; (NKm_sum)[index_doc]++; std::string term = words_matrix[index_doc][index_word]; (NTk_count)[i][term]++; (NTk_sum)[i]++; } void LDA::DecreCountVariables(std::size_t index_doc, std::size_t index_word) { int i = Zmn[index_doc][index_word]; (NKm_count)[index_doc][i]-- ; (NKm_sum)[index_doc]--; std::string term = words_matrix[index_doc][index_word]; (NTk_count)[i][term]--; (NTk_sum)[i]--; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// void LDA::Training() { if(!b_ready) std::fprintf(stderr, "Init Error!\n"); //PrintZmn(); GibbsSampling(); EstimateTheta(); EstimatePhi(); } void LDA::GibbsSampling() { int count = 0; while(count < iter_num) { count++; for(std::size_t index_doc = 0; index_doc < words_matrix.size(); ++index_doc) { for(std::size_t index_word = 0; index_word < words_matrix[index_doc].size(); ++index_word) { //std::cout << "word: " << words_matrix[index_doc][index_word] << std::endl; DecreCountVariables(index_doc, index_word); Zmn[index_doc][index_word] = UpdateTopic(index_doc, index_word); IncreCountVariables(index_doc, index_word); //break; } //break; } } } int LDA::UpdateTopic(std::size_t index_doc, std::size_t index_word) { int k = Zmn[index_doc][index_word]; std::string term = words_matrix[index_doc][index_word]; //std::cout << "Change Topic is " << k << std::endl; std::vector<double> temp_vt; for(k = 0; k < topics_num; k++) { double denominator = 0.0; denominator = ((NTk_sum)[k] + words_num * beta) * ((NKm_sum)[index_doc] + topics_num * alpha); double numerator = 0.0; numerator = ((NTk_count)[k][term] + beta)*((NKm_count)[index_doc][k] + alpha); double probability = numerator / denominator; temp_vt.push_back(probability); } double sum = std::accumulate(temp_vt.begin(), temp_vt.end(), 0.0); //std::cout << sum << std::endl; std::vector<double> pro_vt; for_each(temp_vt.begin(), temp_vt.end(), [&](double temp) { pro_vt.push_back(temp/sum); }); //copy(pro_vt.begin(), pro_vt.end(), std::ostream_iterator<double>(std::cout, " ")); return GenerateMultiSample(topics_num, pro_vt); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// void LDA::EstimateTheta() { theta_matrix.resize(docs_num); for(int i = 0; i < docs_num; i++) { (theta_matrix)[i].resize(topics_num); for(int j = 0; j < topics_num; j++) { (theta_matrix)[i][j] = ((NKm_count)[i][j] + alpha) / ((NKm_sum)[i] + alpha * topics_num); } } } void LDA::EstimatePhi() { phi_matrix.resize(topics_num); std::map<std::string, int>::const_iterator iter; for(int i = 0; i < topics_num; i++) { for(iter = (NTk_count)[i].begin(); iter != (NTk_count)[i].end(); ++iter) { double phi_value = (static_cast<double>(iter->second) + beta) / ((NTk_sum)[i] + beta * words_num); (phi_matrix)[i].push_back(make_pair(iter->first, phi_value)); } std::sort((phi_matrix)[i].begin(), (phi_matrix)[i].end(), [&](const std::pair<std::string, double>& x, const std::pair<std::string, double>& y) -> bool { return !(x.second <= y.second); }); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////// const THETA_MATRIX& LDA::GetTheta() { return theta_matrix; } const PHI_MATRIX& LDA::GetPhi() { return phi_matrix; }
[ "robotflying777@gmail.com" ]
robotflying777@gmail.com
eb8a504a1f043b0290af4e29a8d60e1e2628f5c3
58457842abd6ac0073ce969eccb1ed22caef9ea2
/lulib/network/protocol/http/authorize/_policy.hpp
109e70b2333e7632ff0317446163773a05693b92
[]
no_license
luluci/lulib
abbf7cf09765bd1a76ed1acf30b289b111b8f431
235378b85cb07169ffc627021cd01094affd5c99
refs/heads/master
2021-03-12T23:01:26.865103
2012-01-02T15:19:33
2012-01-02T15:19:33
1,025,943
0
0
null
null
null
null
UTF-8
C++
false
false
250
hpp
#pragma once namespace lulib { namespace network { namespace http { namespace authorize_detail { template<typename Policy> class basic_autorizer { }; }// namespace lulib::network::http::autorize_detail }}}// namespace lulib::network::http
[ "lucis.cis@gmail.com" ]
lucis.cis@gmail.com
c0d973a38b69df4e8a39ffaa0030ab472373bc7b
45e0fbd9a9dbcdd4fbe6aaa2fdb2aed296f81e33
/FindSecret/Classes/Native/UnityEngine_UI_UnityEngine_EventSystems_MoveDirect1216237838.h
c55f693a3eac183a3829d342cdc950d92ee4c5a1
[ "MIT" ]
permissive
GodIsWord/NewFindSecret
d4a5d2d810ee1f9d6b3bc91168895cc808bac817
4f98f316d29936380f9665d6a6d89962d9ee5478
refs/heads/master
2020-03-24T09:54:50.239014
2018-10-27T05:22:11
2018-10-27T05:22:11
142,641,511
0
0
null
null
null
null
UTF-8
C++
false
false
1,020
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_Enum4135868527.h" #include "UnityEngine_UI_UnityEngine_EventSystems_MoveDirect1216237838.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.EventSystems.MoveDirection struct MoveDirection_t1216237838 { public: // System.Int32 UnityEngine.EventSystems.MoveDirection::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(MoveDirection_t1216237838, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "zhangyide@9fbank.cc" ]
zhangyide@9fbank.cc
f672acb9291ab512f4d33ca061786611eb364c6a
778968fa32b556d865e977f635d5ff815ebe4dc6
/Object Oriented Programming/Lab9/Agentie de turism/Agentie de turism/Repository.h
6974a468e27dc6ee440422f98205f2e55ca3a67d
[]
no_license
katybucsa/faculty
cf29148329e8630c096de4aa53ef2b7cc271a53e
a7172e4e8433caca86021c74ce4961df477a535f
refs/heads/master
2023-02-12T01:58:17.841213
2021-01-07T15:27:08
2021-01-07T15:47:28
327,284,764
0
0
null
null
null
null
UTF-8
C++
false
false
2,167
h
#pragma once #include <vector> #include <fstream> #include <algorithm> #include "Domain.h" class Repository { protected: std::vector<Oferta> offers; public: /* default constructor for Repository class */ Repository() = default; /* do not allow to make copy for an object of type Repository */ Repository(const Repository& otrep) = delete; /* store an offer throw an exception if the offer already exists */ virtual void add(const Oferta&); /* modify an offer throw an exception if the offer does not exist */ virtual void modify(const Oferta&); /* verify if an offer already exists returning it's position in the list or throwing an exception otherwise */ virtual size_t getOPoz(const Oferta&); /* removes an offer throw an exception if the offer does not exist */ virtual void remove(const Oferta&); /* return all the offers which were saved */ virtual const std::vector<Oferta>& getAll() noexcept; virtual const Oferta& getOferta(const std::string&); /* return the number of offers */ virtual size_t sizeElems() noexcept; }; class FileRepository :public Repository { private: std::string fName; void loadFromFile(); void writeToFile(); public: FileRepository(std::string fName) :Repository{}, fName{ fName } { loadFromFile(); } void add(const Oferta& o) override { loadFromFile(); Repository::add(o); writeToFile(); } void modify(const Oferta& o) override { loadFromFile(); Repository::modify(o); writeToFile(); } void remove(const Oferta& o) override { loadFromFile(); Repository::remove(o); writeToFile(); } const std::vector<Oferta>& getAll() noexcept override{ loadFromFile(); return Repository::getAll(); } const Oferta& getOferta(const std::string& name) override{ loadFromFile(); return Repository::getOferta(name); } size_t sizeElems() noexcept override{ loadFromFile(); return Repository::sizeElems(); } }; /* used to report the errors occured in repo */ class RepositoryException { private: std::string message; public: RepositoryException(std::string msg) :message{ msg } {} const std::string& getMessage() const noexcept { return message; } };
[ "katybucsa@github.com" ]
katybucsa@github.com
34dd4e3af6f734950b24ecc5dda9c2106c609c5d
9ada6ca9bd5e669eb3e903f900bae306bf7fd75e
/case3/ddtFoam_Tutorial/0.001500000/uniform/time
655a63dd24956b0ddafc58bb704b9da0fa70ef4d
[]
no_license
ptroyen/DDT
a6c8747f3a924a7039b71c96ee7d4a1618ad4197
6e6ddc7937324b04b22fbfcf974f9c9ea24e48bf
refs/heads/master
2020-05-24T15:04:39.786689
2018-01-28T21:36:40
2018-01-28T21:36:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,006
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 2.1.1 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "0.001500000/uniform"; object time; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // value 0.0015; name "0.001500000"; index 5584; deltaT 2.5908e-07; deltaT0 2.5908e-07; // ************************************************************************* //
[ "ubuntu@ip-172-31-45-175.eu-west-1.compute.internal" ]
ubuntu@ip-172-31-45-175.eu-west-1.compute.internal
575fc939565455f1ee600df078e5798ef705d7a1
a33aac97878b2cb15677be26e308cbc46e2862d2
/program_data/PKU_raw/70/166.c
bcac12b9392a4dbfd225409137c0f9ecdfffd191
[]
no_license
GabeOchieng/ggnn.tensorflow
f5d7d0bca52258336fc12c9de6ae38223f28f786
7c62c0e8427bea6c8bec2cebf157b6f1ea70a213
refs/heads/master
2022-05-30T11:17:42.278048
2020-05-02T11:33:31
2020-05-02T11:33:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
444
c
int main(int argc, char* argv[]) { int num,i,a,b,na=1; double x[50],y[50],z[400]; double dis=0; scanf("%d",&num); for (i=1;i<=num;i++) { scanf("%lf",&x[i]); scanf("%lf",&y[i]); } for (a=1;a<=num;a++){ for(b=a+1;b<=num;b++){ z[na]=(x[a]-x[b])*(x[a]-x[b])+(y[a]-y[b])*(y[a]-y[b]); if (z[na]>dis) { dis=z[na];} na++; } } printf("%.4lf\n",sqrt(dis)); return 0; }
[ "bdqnghi@gmail.com" ]
bdqnghi@gmail.com
29c8786fe4a68c0936c542669e20a679ee97e9ad
342d01d22f453ef7cb6fea382da0071d71c418e4
/moped-modeling-py/src/imundistort.cpp
6a2207fc9a075d6115bfd4327bfc414acb1cbcd0
[]
no_license
kanster/moped
1ddf78cb2aa939e788fe0c0b5974797f58f46b87
f8d74b6680915eca73265be656d72e7d346e1aa0
refs/heads/master
2021-01-19T04:25:16.861856
2016-08-01T02:08:29
2016-08-01T02:08:29
64,627,677
13
1
null
null
null
null
UTF-8
C++
false
false
1,797
cpp
/********************************************************************* * imundistort * Non-linear image undistortion, code taken from old version of OpenCV * * Written by Alvaro Collet acollet@cs.cmu.edu * Copyright: Carnegie Mellon University * * DEPENDENCIES: This library requires boost.python and pyUblas. * *********************************************************************/ #include <Python.h> #include <boost/python.hpp> #include <pyublas/numpy.hpp> #include <opencv/cv.h> #include "cvundistort.h" using namespace pyublas; pyublas::numpy_vector<unsigned int> undistort( pyublas::numpy_vector<unsigned int> pydata, pyublas::numpy_vector<double> pyKK, pyublas::numpy_vector<double> pydist ) { const npy_intp *dims = pydata.dims(); const numpy_array<unsigned int> py_img(pydata.to_python()); const numpy_array<double> dist(pydist.to_python()); int channels = pydata.ndim() == 3 ? dims[2] : 1; IplImage *cv_img = cvCreateImageHeader(cvSize(dims[1], dims[0]), IPL_DEPTH_8U, channels); IplImage *cv_out_img = cvCreateImageHeader(cvSize(dims[1], dims[0]), IPL_DEPTH_8U, channels); numpy_vector<unsigned int> out_img; out_img.resize(py_img.size()); out_img.reshape(pydata.ndim(), dims); cvSetData(cv_img, (unsigned int *) &pydata[0], dims[1]); cvSetData(cv_out_img, (unsigned int *) &out_img[0], dims[1]); double KK[9] = {pyKK[0], 0, pyKK[2], 0, pyKK[1], pyKK[3], 0, 0, 1}; CvMat FullKK = cvMat(3, 3, CV_64FC1, KK); CvMat dist_coeffs = cvMat(4, 1, CV_64FC1, (double *)&dist[0]); cvUndistort(cv_img, cv_out_img, &FullKK, &dist_coeffs); cvReleaseImageHeader(&cv_img); cvReleaseImageHeader(&cv_out_img); return out_img; } BOOST_PYTHON_MODULE(libimundistort) { boost::python::def("undistort", undistort); }
[ "vandeweg@users.noreply.github.com" ]
vandeweg@users.noreply.github.com
8a3f19982f5084d19ca49a10930848a76f148de1
2780081bb046866b1449519cbe4dd78fbbf0719e
/XUL.framework/Versions/2.0/include/nsIDOMSVGAnimateTransformElement.h
4d6df978eed9a2315bcffd9eef42d4e4e43a1399
[]
no_license
edisonlee55/gluezilla-mac
d8b6535d2b36fc900eff837009372f033484a63f
45d559edad7b5191430e139629d2aee918aa6654
refs/heads/master
2022-09-23T19:57:18.853517
2020-06-03T03:57:37
2020-06-03T03:57:37
267,499,676
1
0
null
null
null
null
UTF-8
C++
false
false
2,416
h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM /builds/slave/rel-2.0-xr-osx64-bld/build/dom/interfaces/svg/nsIDOMSVGAnimateTransformElement.idl */ #ifndef __gen_nsIDOMSVGAnimateTransformElement_h__ #define __gen_nsIDOMSVGAnimateTransformElement_h__ #ifndef __gen_nsIDOMSVGAnimationElement_h__ #include "nsIDOMSVGAnimationElement.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif /* starting interface: nsIDOMSVGAnimateTransformElement */ #define NS_IDOMSVGANIMATETRANSFORMELEMENT_IID_STR "735e0f75-c6aa-4aee-bcd2-46426d6ac90c" #define NS_IDOMSVGANIMATETRANSFORMELEMENT_IID \ {0x735e0f75, 0xc6aa, 0x4aee, \ { 0xbc, 0xd2, 0x46, 0x42, 0x6d, 0x6a, 0xc9, 0x0c }} class NS_NO_VTABLE NS_SCRIPTABLE nsIDOMSVGAnimateTransformElement : public nsIDOMSVGAnimationElement { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMSVGANIMATETRANSFORMELEMENT_IID) }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMSVGAnimateTransformElement, NS_IDOMSVGANIMATETRANSFORMELEMENT_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIDOMSVGANIMATETRANSFORMELEMENT \ /* no methods! */ /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIDOMSVGANIMATETRANSFORMELEMENT(_to) \ /* no methods! */ /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIDOMSVGANIMATETRANSFORMELEMENT(_to) \ /* no methods! */ #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsDOMSVGAnimateTransformElement : public nsIDOMSVGAnimateTransformElement { public: NS_DECL_ISUPPORTS NS_DECL_NSIDOMSVGANIMATETRANSFORMELEMENT nsDOMSVGAnimateTransformElement(); private: ~nsDOMSVGAnimateTransformElement(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsDOMSVGAnimateTransformElement, nsIDOMSVGAnimateTransformElement) nsDOMSVGAnimateTransformElement::nsDOMSVGAnimateTransformElement() { /* member initializers and constructor code */ } nsDOMSVGAnimateTransformElement::~nsDOMSVGAnimateTransformElement() { /* destructor code */ } /* End of implementation class template. */ #endif #endif /* __gen_nsIDOMSVGAnimateTransformElement_h__ */
[ "edisonlee@edisonlee55.com" ]
edisonlee@edisonlee55.com
0302f5bc028370bb3cc03cd253be8e87c0ec5bf7
63ffcd2798915ea9b9199cfd1d6ee6de319cff84
/LeedCodeChallenge/2020/August2020/Week 1/Design HashSet.cpp
8230ab9c60addf080ecdf4f7470e39ee6bb28c67
[]
no_license
numenoreon/LeetCode
b8069990d30bda73809e21d304703eec0c979ed6
912fcc4c5f6a2eb8e95db48096d3d8f5e3eb8cf0
refs/heads/master
2021-09-01T16:26:26.190661
2021-08-24T19:49:29
2021-08-24T19:49:29
231,564,913
0
0
null
null
null
null
UTF-8
C++
false
false
1,135
cpp
class MyHashSet { public: vector<list<int>> vec; MyHashSet() { vec = vector<list<int>> (128); } inline int GetHash(int key) { int h = hash<int>{}(key); int hash_mod = h % vec.size(); return hash_mod; } void add(int key) { int hash = GetHash(key); if (contains(key, hash)) return ; auto &l = vec[hash]; l.push_back(key); return ; } inline void remove(int key, int hash) { auto &l = vec[hash]; auto it = l.begin(); while (it != l.end()) { if (*it != key) { ++it; continue; } l.erase(it); return ; } return ; } void remove(int key) { remove(key, GetHash(key)); return ; } inline bool contains(int key, int hash) { const auto &l = vec[hash]; for (int n : l) { if (n == key) return true; } return false; } bool contains(int key) { return contains(key, GetHash(key)); } };
[ "numenoreon@gmail.com" ]
numenoreon@gmail.com
13c8ae8a08f2ac1b4aa9fbaa5f2ac0dedc47dab1
2f6d39c2daf70ebaae90e72ca503f8b275d3572a
/test/instr/BundleReachVerify.cpp
1cea068949838371374b8a1d4271ea2d15d1fbf8
[ "MIT" ]
permissive
facebook/redex
5a39c5b733e729ecb52101dd3f941a63f9fa32f0
36c6607be749ba2009210aae404d68cd57e747eb
refs/heads/main
2023-09-01T18:21:21.839608
2023-09-01T02:01:59
2023-09-01T02:01:59
54,664,770
6,459
775
MIT
2023-08-25T00:06:04
2016-03-24T18:26:35
C++
UTF-8
C++
false
false
852
cpp
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <gtest/gtest.h> #include "VerifyUtil.h" TEST_F(PreVerify, BundleReachTest) { EXPECT_NE(nullptr, find_class_named(classes, "Lcom/fb/bundles/MainActivity;")); EXPECT_NE(nullptr, find_class_named(classes, "Lcom/fb/bundles/MyApplication;")); EXPECT_NE(nullptr, find_class_named(classes, "Lcom/fb/bundles/Unused;")); } TEST_F(PostVerify, BundleReachTest) { EXPECT_NE(nullptr, find_class_named(classes, "Lcom/fb/bundles/MainActivity;")); EXPECT_NE(nullptr, find_class_named(classes, "Lcom/fb/bundles/MyApplication;")); EXPECT_EQ(nullptr, find_class_named(classes, "Lcom/fb/bundles/Unused;")); }
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
902403dc3026d99d23e7385e62dc96b1aac0a562
49a0586dcba95aa09833b76bcd0800af628c80ee
/BMWCars/tests/test_model.cpp
af025fbc2abed55035a899a5cb9c81fb145a6ce2
[]
no_license
kvpz/Dealer
4de29c392575671d34a24442881683c6732a1ff8
7e25da5dfa46af77a4ac157d8c7e4c21518f8d7f
refs/heads/master
2021-06-24T12:01:20.828719
2017-07-30T19:15:13
2017-07-30T19:15:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
117
cpp
/* Test class Model */ #include <iostream> #include <model.hpp> int main() { Model model; return 0; }
[ "unknotted26@gmail.com" ]
unknotted26@gmail.com
534cf464c9107b394243d6d6315a879b5a608a94
698a11c977d074f3ab3f7d59883ba5e2e6f41002
/src/language/stringdata.cpp
dcda38ce066a669fa6311d6842652fbeb910bf1e
[]
no_license
jeffmeese/tiberius
d0d92ebb69cd761baf2d79b75290e55cf21c70ec
5a058cea86126d0b04b324830d757e7ece0fb497
refs/heads/master
2023-02-25T19:01:27.095207
2021-01-29T20:08:17
2021-01-29T20:08:17
306,618,752
0
0
null
null
null
null
UTF-8
C++
false
false
3,380
cpp
#include "stringdata.h" #include "stringdatagroup.h" #include <QDebug> #include <QDir> #include <QFile> #include <sstream> #include <stdexcept> StringData::StringData() { } StringData::~StringData() { } void StringData::addGroup(std::unique_ptr<StringDataGroup> textGroup) { mGroups.push_back(std::move(textGroup)); } QString StringData::getString(uint32_t groupId, uint32_t number) const { const StringDataGroup * textGoup = mGroups.at(groupId-1).get(); if (textGoup->totalStrings() <= number) { return QString(); } return mGroups.at(groupId-1)->stringAt(number); } void StringData::loadFromDataStream(QDataStream &dataStream) { mGroups.clear(); dataStream.setByteOrder(QDataStream::LittleEndian); // Read the header data Header header; dataStream.readRawData(header.description, 16); dataStream >> header.totalGroups; dataStream >> header.totalStrings; dataStream >> header.totalWords; // Read index data Index indexData[MAX_INDEX]; for (int32_t i = 0; i < MAX_INDEX; i++) { dataStream >> indexData[i].offset; dataStream >> indexData[i].numStrings; } // Read the string data // Older versions only specified where the group was used // while newer versions specified how many strings were in // each group. The following assumes the old format and // converts to the new format. For new format files this // is unnecessary but it's only done once so the performance // impact is minimal. for (int32_t i = 0; i < MAX_INDEX-1; i++) { uint32_t offset = indexData[i].offset; uint32_t numStrings = indexData[i].numStrings; if (numStrings > 0) { StringDataGroupPtr group(new StringDataGroup(i+1)); // Read new strings until we hit the offset for the next group uint32_t nextOffset = indexData[i+1].offset; // What if the next one isn't used? QString currentString; while (offset < nextOffset && !dataStream.atEnd()) { offset++; // Read characters until we find a null char c; dataStream.readRawData(&c, 1); if (c == '\0') { group->addString(currentString); currentString.clear(); } else { currentString += c; } } addGroup(std::move(group)); } } } void StringData::loadFromFile(const QString &fileName) { QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { std::ostringstream oss; oss << "Could not open language file " << fileName.toStdString(); throw std::invalid_argument(oss.str()); } QDataStream dataStream(&file); loadFromDataStream(dataStream); } void StringData::saveToDataStream(QDataStream & dataStream) const { // TODO: Implement } void StringData::saveToFile(const QString & fileName) const { QFile file(fileName); if (!file.open(QIODevice::WriteOnly)) { std::ostringstream oss; oss << "Could not open language file " << fileName.toStdString(); throw std::invalid_argument(oss.str()); } } std::size_t StringData::totalGroups() const { return mGroups.size(); } std::size_t StringData::totalStrings() const { std::size_t total = 0; for (std::size_t i = 0; i < mGroups.size(); i++) { total += mGroups.at(i)->totalStrings(); } return total; }
[ "jmeese@DESKTOP-8IUC6VI.attlocal.net" ]
jmeese@DESKTOP-8IUC6VI.attlocal.net
6f6231bcef9d9a8625b6cfa08c6c93839612281b
8101a9dcde73f28dc59ab58244c3722e5c30d593
/v3/SingleRelay.cpp
39c44d20bb7aecb741b6ce4b9c767ea278efd289
[]
no_license
winkste/esp8266_template
8c8583c2321781ddc55a9b0ea38356aeb5b4370b
d324ed60753a4b2fcfc2fca38b2f842eec791df8
refs/heads/master
2021-08-26T05:34:56.133840
2017-11-21T20:05:13
2017-11-21T20:05:13
109,651,723
0
0
null
null
null
null
UTF-8
C++
false
false
11,871
cpp
/***************************************************************************************** * FILENAME : SingleRelay.cpp * * DESCRIPTION : * Implementation of the single relay shield. * * PUBLIC FUNCTIONS : * * * NOTES : * * * Copyright (c) [2017] [Stephan Wink] * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE vAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * AUTHOR : Stephan Wink START DATE : 01.10.2017 * *****************************************************************************************/ /****************************************************************************************/ /* Include Interfaces */ #include "SingleRelay.h" #include "MqttDevice.h" #include "Trace.h" #include "PubSubClient.h" /****************************************************************************************/ /* Local constant defines */ #define RELAY_PIN 5 #define MQTT_SUB_TOGGLE "/relay/toggle" // command message for toggle command #define MQTT_SUB_BUTTON "/relay/switch" // command message for button commands #define MQTT_PUB_LIGHT_STATE "/relay/status" //state of relay #define MQTT_PAYLOAD_CMD_ON "ON" #define MQTT_PAYLOAD_CMD_OFF "OFF" /****************************************************************************************/ /* Local function like makros */ /****************************************************************************************/ /* Local type definitions (enum, struct, union) */ /****************************************************************************************/ /* Public functions (unlimited visibility) */ /**--------------------------------------------------------------------------------------- * @brief Constructor for the single relay shield * @author winkste * @date 20 Okt. 2017 * @param p_trace trace object for info and error messages * @return n/a *//*-----------------------------------------------------------------------------------*/ SingleRelay::SingleRelay(Trace *p_trace) : MqttDevice(p_trace) { this->prevTime_u32 = 0; this->publications_u16 = 0; this->relayState_bol = false; this->publishState_bol = true; } /**--------------------------------------------------------------------------------------- * @brief Default destructor * @author winkste * @date 20 Okt. 2017 * @return n/a *//*-----------------------------------------------------------------------------------*/ SingleRelay::~SingleRelay() { // TODO Auto-generated destructor stub } /**--------------------------------------------------------------------------------------- * @brief Initialization of the single relay object * @author winkste * @date 20 Okt. 2017 * @return n/a *//*-----------------------------------------------------------------------------------*/ void SingleRelay::Initialize() { p_trace->println(trace_INFO_MSG, "Single relay initialized"); pinMode(RELAY_PIN, OUTPUT); this->setRelay(); this->isInitialized_bol = true; } /**--------------------------------------------------------------------------------------- * @brief Function call to initialize the MQTT interface for this module * @author winkste * @date 20 Okt. 2017 * @param client mqtt client object * @param dev_p client device id for building the mqtt topics * @return n/a *//*-----------------------------------------------------------------------------------*/ void SingleRelay::Reconnect(PubSubClient *client_p, const char *dev_p) { if(NULL != client_p) { this->dev_p = dev_p; this->isConnected_bol = true; p_trace->println(trace_INFO_MSG, "Single relay reconnected"); // ... and resubscribe // toggle relay client_p->subscribe(build_topic(MQTT_SUB_TOGGLE)); client_p->loop(); p_trace->print(trace_INFO_MSG, "[mqtt] subscribed 1: "); p_trace->println(trace_PURE_MSG, MQTT_SUB_TOGGLE); // change relay state with payload client_p->subscribe(build_topic(MQTT_SUB_BUTTON)); client_p->loop(); p_trace->print(trace_INFO_MSG, "[mqtt] subscribed 2: "); p_trace->println(trace_PURE_MSG, MQTT_SUB_BUTTON); client_p->loop(); } else { // failure, not connected p_trace->println(trace_ERROR_MSG, "uninizialized MQTT client in single relay detected"); this->isConnected_bol = false; } } /**--------------------------------------------------------------------------------------- * @brief Callback function to process subscribed MQTT publication * @author winkste * @date 20 Okt. 2017 * @param client mqtt client object * @param p_topic received topic * @param p_payload attached payload message * @return n/a *//*-----------------------------------------------------------------------------------*/ void SingleRelay::CallbackMqtt(PubSubClient *client, char* p_topic, String p_payload) { if(true == this->isConnected_bol) { // received toggle relay mqtt topic if (String(build_topic(MQTT_SUB_TOGGLE)).equals(p_topic)) { p_trace->println(trace_INFO_MSG, "Single relay mqtt callback"); p_trace->println(trace_INFO_MSG, p_topic); p_trace->println(trace_INFO_MSG, p_payload); this->ToggleRelay(); } // execute command to switch on/off the relay else if (String(build_topic(MQTT_SUB_BUTTON)).equals(p_topic)) { p_trace->println(trace_INFO_MSG, "Single relay mqtt callback"); p_trace->println(trace_INFO_MSG, p_topic); p_trace->println(trace_INFO_MSG, p_payload); // test if the payload is equal to "ON" or "OFF" if(0 == p_payload.indexOf(String(MQTT_PAYLOAD_CMD_ON))) { this->relayState_bol = true; this->setRelay(); } else if(0 == p_payload.indexOf(String(MQTT_PAYLOAD_CMD_OFF))) { this->relayState_bol = false; this->setRelay(); } else { p_trace->print(trace_ERROR_MSG, "[mqtt] unexpected payload: "); p_trace->println(trace_PURE_MSG, p_payload); } } } else { p_trace->println(trace_ERROR_MSG, "connection failure in sonoff CallbackMqtt "); } } /**--------------------------------------------------------------------------------------- * @brief Sending generated publications * @author winkste * @date 20 Okt. 2017 * @param client mqtt client object * @return n/a *//*-----------------------------------------------------------------------------------*/ bool SingleRelay::ProcessPublishRequests(PubSubClient *client) { String tPayload; boolean ret = false; if(true == this->isConnected_bol) { // check if state has changed, than publish this state if(true == publishState_bol) { p_trace->print(trace_INFO_MSG, "[mqtt] publish requested state: "); p_trace->print(trace_PURE_MSG, MQTT_PUB_LIGHT_STATE); p_trace->print(trace_PURE_MSG, " : "); if(true == this->relayState_bol) { ret = client->publish(build_topic(MQTT_PUB_LIGHT_STATE), MQTT_PAYLOAD_CMD_ON, true); p_trace->println(trace_PURE_MSG, MQTT_PAYLOAD_CMD_ON); } else { ret = client->publish(build_topic(MQTT_PUB_LIGHT_STATE), MQTT_PAYLOAD_CMD_OFF, true); p_trace->println(trace_PURE_MSG, MQTT_PAYLOAD_CMD_OFF); } if(ret) { publishState_bol = false; } } } else { p_trace->println(trace_ERROR_MSG, "connection failure in sonoff ProcessPublishRequests "); } return ret; }; /**--------------------------------------------------------------------------------------- * @brief This function toggles the relay * @author winkste * @date 20 Okt. 2017 * @return void *//*-----------------------------------------------------------------------------------*/ void SingleRelay::ToggleRelay(void) { if(true == this->relayState_bol) { this->TurnRelayOff(); } else { this->TurnRelayOn(); } } /****************************************************************************************/ /* Private functions: */ /**--------------------------------------------------------------------------------------- * @brief This function turns the relay off * @author winkste * @date 20 Okt. 2017 * @return void *//*-----------------------------------------------------------------------------------*/ void SingleRelay::TurnRelayOff(void) { if(true == this->isInitialized_bol) { this->relayState_bol = false; digitalWrite(RELAY_PIN, LOW); p_trace->println(trace_INFO_MSG, "relay turned off"); this->publishState_bol = true; } } /**--------------------------------------------------------------------------------------- * @brief This function turns the relay on * @author winkste * @date 20 Okt. 2017 * @return void *//*-----------------------------------------------------------------------------------*/ void SingleRelay::TurnRelayOn(void) { if(true == this->isInitialized_bol) { this->relayState_bol = true; digitalWrite(RELAY_PIN, HIGH); p_trace->println(trace_INFO_MSG, "relay turned on"); this->publishState_bol = true; } } /**--------------------------------------------------------------------------------------- * @brief This function sets the relay based on the state of the relayState_bol * attribute * @author winkste * @date 20 Okt. 2017 * @return n/a *//*-----------------------------------------------------------------------------------*/ void SingleRelay::setRelay(void) { if(true == this->relayState_bol) { TurnRelayOn(); } else { TurnRelayOff(); } } /**--------------------------------------------------------------------------------------- * @brief This function helps to build the complete topic including the * custom device. * @author winkste * @date 20 Okt. 2017 * @param topic pointer to topic string * @return combined topic as char pointer, it uses buffer_stca to store the topic *//*-----------------------------------------------------------------------------------*/ char* SingleRelay::build_topic(const char *topic) { sprintf(buffer_ca, "%s%s", this->dev_p, topic); return buffer_ca; }
[ "stephan_wink@winkste-MBP.fritz.box" ]
stephan_wink@winkste-MBP.fritz.box
b82a422506998aa858411bb7c6ef4de642ae32f6
282fa8dd9fd2e26b5ebf448c85121ed1bf873148
/src/Common.h
fc2ccae7db358b3dd540ac093bb6215433e4d1ef
[]
no_license
fjgarciao/hustle_castle_bot_pack
ec8e71a1ea175a6790b187c64b0116f24b61d587
0ae16429e5da7d5bd69afdf1d28e15eaaa70e4d3
refs/heads/master
2020-04-20T17:15:36.817536
2019-02-03T21:32:10
2019-02-03T21:32:10
168,983,796
0
0
null
null
null
null
UTF-8
C++
false
false
432
h
#pragma once #include "pch.h" cv::Point MatchingMethod(const cv::Mat &src, const cv::Mat &templ); void GenerateDataForTrain(); int TestWinApi(); double Compare(const cv::Mat &a, const cv::Mat &b); bool CompareFromTemplate(const cv::Mat &src, const cv::Mat &sample, const cv::Mat &tmpl); bool MaskToRect(const cv::Mat &img, cv::Rect &rect); std::string type2str(int type); void show_two(const cv::Mat &a, const cv::Mat &b);
[ "denesic@gmail.com" ]
denesic@gmail.com
5cc36906183916dab3372702e0245fa1d6caef42
4966b2e0985f0fc99214e4fb5442402efe8d1731
/main.cpp
5253067e89e9d7fa6bd8d89ea74c6fa3805615e6
[]
no_license
tschmit/mbtpdfasm
8bee6aada6bb12351639f38755c12abf4a702465
d192725b91f042a89a664ffb8fada0d40965b756
refs/heads/master
2021-01-20T09:46:35.142361
2015-02-25T14:57:07
2015-02-25T14:57:07
90,286,479
2
0
null
null
null
null
ISO-8859-1
C++
false
false
35,443
cpp
#ifdef WIN32 #pragma warning(disable : 4201) #include <crtdbg.h> // #include <windows.h> #pragma warning(default: 4201) #define snprintf _snprintf #else #include <string.h> #include <unistd.h> #define _snprintf snprintf #define stricmp strcasecmp #endif #define DLL_EXPORTS #define RES_BUF_GROWTH 5000 #ifdef MBTPDFASM_DLL # include "mbtPdfAsmDll.h" #endif #include "mbtPdfAsmError.h" #include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include <string.h> #include "mpaMain.hpp" #include "string.hpp" #include "listeFichiers.hpp" #include "pdfFile.hpp" #define GET_NUMBER_OF_PAGES 0x0001 #define GET_FILE_NAME 0x0002 #define GET_CYPHER_INFOS 0x0004 #define GET_HEADER_LINE 0x0008 #define GET_META_AUTHOR 0x0010 #define GET_META_KW 0x0020 #define GET_META_SUBJECT 0x0040 #define GET_META_TITLE 0x0080 #define GET_OUTLINES 0x0100 #define MODE_DISPLAY_USE -1 #define MODE_ASSEMBLAGE 1 #define MODE_GET_INFOS 2 #define MODE_UPDATE 4 #define MODE_SPLIT 8 #define MODE_VERSION 16 int displayUse(FILE *output) { FILE * org; char tc[1000]; int i; fprintf(output, "mbtPdfAsm %s\r\nusing PCRE 4.4 (http://www.pcre.org)\r\nsee at %s", strVersion, strMPAURL); return 0; } /* ************************************************************************************* retourne le nombre de page insérées, -1 en cas d'erreur */ #define NOT_NEXT_ATOME *pc && ((*pc < '0') || (*pc > '9')) && (*pc != '*') && (*pc != '-') && (*pc != 'L') int insertPageListToFrom(char *pl, C_pdfFile *to, C_pdfFile *from, int startPage, int nbPages, FILE *output) { char *pc; int max, min, i, res, vres; pc = pl; res = 0; vres = 0; if ( nbPages <= 0 ) { nbPages = 100000; } while ( NOT_NEXT_ATOME ) ++pc; // on se positionne sur la première page à insérer while ( *pc ) { switch ( *pc ) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'L': if ( *pc == 'L' ) { min = from->getNbPages(); ++pc; } else { min = atoi(pc); //fixed by Stephen C. Morgana while ( *pc && (*pc >= '0') && (*pc <= '9') ) ++pc; } max = min; while ( NOT_NEXT_ATOME ) ++pc; if ( *pc == '-' ) { max = 0; ++pc; } if ( *pc && !max ) { while ( NOT_NEXT_ATOME ) ++pc; switch ( *pc ) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': max = atoi(pc); while ( *pc && (*pc >= '0') && (*pc <= '9') ) ++pc; break; case '*': while ( *pc != '-' ) --pc; max = min; break; case 'L': ++pc; max = from->getNbPages(); break; default: max = min; break; } } break; case '*': ++pc; min = 1; max = from->getNbPages(); //min = max = -1; option incompatible avec la gestion de l'option -lP break; case '-': ++pc; while ( *pc && ((*pc < '0') || (*pc > '9')) && (*pc != '*') ) ++pc; if ( *pc == '*' ) { min = from->getNbPages(); max = 1; ++pc; } else min = 0; break; } while ( NOT_NEXT_ATOME ) { ++pc; } if ( min ) { if ( min == -1 ) { } else { if ( min <= max ) { for (i=min; (i <= max) && (res < nbPages); ++i) { ++vres; if ( vres < startPage ) continue; if ( !to->insertPage(from, i, to->getRootPagesObjNum()) ) { if ( output != 0 ) { fprintf(output, strPageInserted, i, from->getFileName()); } ++res; } else { if ( output != 0 ) fprintf(output, strCantInsertPage, i, from->getFileName()); } } } else { for (i=min; (i >= max) && (res < nbPages); --i) { if ( ! to->insertPage(from, i, to->getRootPagesObjNum()) ) { ++res; if ( output != 0 ) fprintf(output, strPageInserted, i, from->getFileName()); } else { if ( output != 0 ) fprintf(output, strCantInsertPage, i, from->getFileName()); } } } } } } return res; } //************************************************************************************* //************************************************************************************* //************************************************************************************* #define SET_PDF_FILE_INSERTION_OPTION \ if ( bdpOrientation != 0 ) \ pPdfFile->setBdpOrientation((float)atof(bdpOrientation)); \ if ( bdpX != 0 ) \ pPdfFile->setBdpX(bdpX); \ if ( bdpY != 0 ) \ pPdfFile->setBdpY(bdpY); \ if ( bdpSize != 0 ) \ pPdfFile->setBdpSize(bdpSize); \ if ( bdpColors != 0 ) \ pPdfFile->setBdpRGB(bdpColors); \ if ( bdpFontName != -1 ) \ pPdfFile->setBdpFontName(bdpFontName); \ if ( bdpStr != 0 ) \ pPdfFile->setBdpStr(bdpStr); \ if ( pnX != 0 ) \ pPdfFile->setPageNumberX(pnX); \ if ( pnY != 0 ) \ pPdfFile->setPageNumberY(pnY); \ if ( pnSize != 0 ) \ pPdfFile->setPageNumberSize(pnSize); \ if ( pnColors != 0 ) \ pPdfFile->setPageNumberRGB(pnColors); \ if ( pnFontName != -1 ) \ pPdfFile->setPageNumberFontName(pnFontName); \ if ( insertPageNumber) \ pPdfFile->insertPageNumberInPage(true); \ if ( pnFirstNum != 0 ) \ pPdfFile->setPageNumberFirstNum(pnFirstNum); \ if ( pnOrientation != 0 ) \ pPdfFile->setPageNumberOrientation((float)atof(pnOrientation)); \ if ( pageRotation != 0 ) \ pPdfFile->setPageRotation(pageRotation); #define MAKE_PDF_FILE_FROM_PAGES_LIST \ for (;;) { \ i = insertPageListToFrom(p, pPdfFile, pdfOrg, startPage, pageLimitNumber - nbInsertedPages, output); \ totalPage += i; \ nbInsertedPages += i; \ currentPageNumber += i; \ if ( (nbInsertedPages == pageLimitNumber) && (pageLimitNumber != 0) ) { \ nbInsertedPages = 0; \ pPdfFile->close(); \ delete pPdfFile; \ ++resultFileCpt; \ snprintf(tBuf, LG_TBUF - 1, "%s_%03i.pdf", d, resultFileCpt); \ pPdfFile = new C_pdfFile(tBuf, write); \ pPdfFile->setOptions(mdpU, mdpO, masterModeNoEncrypt, restrict, lgEncryptKey, pMetadataStr, metadataStr); \ SET_PDF_FILE_INSERTION_OPTION \ startPage += i; \ pdfOrg->getXrefTable()->resetInserted(); \ } \ else { \ startPage = 1; \ break; \ } \ if ( currentPageNumber == pdfOrg->getNbPages() ) { \ startPage = 1; \ break; \ } \ } //************************************************************************************* #ifdef MBTPDFASM_DLL # define ERROR_FLAGS(x) this->errorFlags |= x; # define RES_BUF this->resBuf # define RES_BUF_SIZE this->resBufSize int CSmbtPdfAsm::mbtPdfAsm(int argc, char *argv[]) { //************************************************************************************* #else # define ERROR_FLAGS(x) # define RES_BUF resBuf # define RES_BUF_SIZE resBufSize int main(int argc, char *argv[]) { char *resBuf = 0; int resBufSize = 0; #endif //************************************************************************************* C_listeFichiers *lFile; C_pdfFile *pPdfFile, *pdfOrg; int mode; char tBuf[LG_TBUF], *pc; int res, i, totalPage, j; int optFL; // options pour file list char *m, *d, *o, *s; // m = mask, d = destination, o = outlines def, s = fichier de script char *p; // une liste de pages à insérer char *b; // répertoire de base char *bdpStr; char *bdpOrientation, *bdpColors; int bdpX, bdpY, bdpSize, bdpFontName; bool insertPageNumber; int pnX, pnY, pnSize, pnFontName; char *pnOrientation, *pnColors; int pnFirstNum; char *restrict, *mdpU, *mdpO; bool masterModeNoEncrypt; FILE *script; int sizeof_fBuf; char *fBuf; char *MBuf; MBuf = 0; int infoFlags; int lgEncryptKey; FILE *output; output = stdout; #ifdef DEBUG_MEM_LEAK #ifdef WIN32 _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG)|_CRTDBG_LEAK_CHECK_DF); #define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__) #define new DEBUG_NEW #endif #endif #ifdef WIN32 _fmode = _O_BINARY; #endif /* ************************* */ char **metadataStr; int pMetadataStr; bool preserveExistingMetadata; bool keepBakFile; const char **pcc; bool keepOutlines; pMetadataStr = 0; metadataStr = 0; preserveExistingMetadata = true; keepBakFile = true; i = C_pdfFile::getNumberOfMetadata(); if ( i != 0 ) metadataStr = (char **)calloc((i + 1) * 2, sizeof(void *)); //************************************ // gestion des limitations d'assemblage int pageLimitNumber; int sizeLimitValue; int resultFileCpt; //compteur de fichier résultat pour le mode SPLIT int nbInsertedPages; int startPage; int currentPageNumber; pageLimitNumber = 0; sizeLimitValue = 0; resultFileCpt = 1; //nbInsertedPages = 0; //startPage = 0; mode = MODE_ASSEMBLAGE; infoFlags = 0; masterModeNoEncrypt = false; lgEncryptKey = 0; optFL = OPTION_LISTEFICHIERS_CASELESS | OPTION_LISTEFICHIERS_SPLIT_MASK; m = d = o = s = p = b = restrict = mdpU = mdpO = bdpStr = bdpOrientation = bdpColors = pnOrientation = pnColors= (char *)0; pnFirstNum = 0; bdpFontName = -1; pnFontName = -1; bdpX = bdpY = bdpSize = pnX = pnY = pnSize = 0; insertPageNumber = false; keepOutlines = false; lFile = (C_listeFichiers *)0; fBuf = (char *)0; //******************************* //rotation des pages int pageRotation = 0; //analyse de la ligne de commande optFL |= OPTION_LISTEFICHIERS_ORDER_AZ; for (i = 1; i < argc; i++) { if ( (argv[i][0] == '-') || (argv[i][0] == '/') ) { switch ( argv[i][1] ) { case 'a': // traitement des masques dans l'ordre de leur apparition optFL = optFL & ((OPTION_LISTEFICHIERS_ORDER_AZ | OPTION_LISTEFICHIERS_ORDER_ZA) ^ 0xffffffff); if ( argv[i][2] == 's' ) { optFL |= OPTION_LISTEFICHIERS_ORDER_MASK; } break; case 'b': //spécifier un répertoire de base b = &argv[i][2]; break; case 'c': //cryptage du fichier résultat switch ( argv[i][2] ) { case 'L': //mot de passe utilisateur lgEncryptKey = atoi(&argv[i][3]); if ((lgEncryptKey < 5) || (lgEncryptKey > 16)) lgEncryptKey = 5; break; case 'R': //restrictions: m pour modif, p pour impression, s select, a annotations/formulaires restrict = &argv[i][3]; break; case 'U': //mot de passe utilisateur mdpU = &argv[i][3]; break; case 'O': //mot de passe propriétaire mdpO = &argv[i][3]; break; } break; case 'd': //fichier résultat d = &argv[i][2]; break; case 'g': //obtenir une information sur les fichiers du masques j = 2; while ( argv[i][j] != 0 ) { switch ( argv[i][j] ) { case 'A': infoFlags |= GET_META_AUTHOR; break; case 'C': infoFlags |= GET_CYPHER_INFOS; break; case 'F': infoFlags |= GET_FILE_NAME; break; case 'H': infoFlags |= GET_HEADER_LINE; break; case 'K': infoFlags |= GET_META_KW; break; case 'N': infoFlags |= GET_NUMBER_OF_PAGES; break; case 'O': //keepOutlines = true; infoFlags |= GET_OUTLINES; break; case 'S': infoFlags |= GET_META_SUBJECT; break; case 'T': infoFlags |= GET_META_TITLE; break; } ++j; } break; case 'h': mode = MODE_DISPLAY_USE; i = argc; break; case 'l': // mode limitation de taille mode = MODE_SPLIT; switch ( argv[i][2] ) { case 'P': pageLimitNumber = atoi(&argv[i][3]); break; case 'S': sizeLimitValue = atoi(&argv[i][3]); break; default: mode = MODE_DISPLAY_USE; i = argc; } break; case 'm': // masque m = &argv[i][2]; break; case 'M': //on dégrade les regexp if (MBuf == 0) { MBuf = new char[LG_FBUF]; pc = &argv[i][2]; j = 1; MBuf[0] = '^'; while ( *pc ) { switch ( *pc ) { case '.': MBuf[j++] = '\\'; MBuf[j++] = '.'; break; case '*': MBuf[j++] = '.'; MBuf[j++] = '*'; break; case '?': MBuf[j++] = '.'; break; case ';': case ',': MBuf[j++] = '$'; MBuf[j++] = ';'; MBuf[j++] = '^'; break; default : MBuf[j++] = *pc; } ++pc; if ( j > LG_FBUF - 3 ) break; } MBuf[j++] = '$'; MBuf[j] = 0; //if ( output != 0 ) // fprintf(output, "regexp = %s\r\n", MBuf); m = MBuf; } break; case 'n': insertPageNumber = true; break; case 'N': switch ( argv[i][2] ) { case '0': pnFirstNum = atoi(argv[i] + 3); break; case 'c': pnColors = argv[i] + 3; break; case 'f': pnFontName = atoi(argv[i] + 3); break; case 'o': pnOrientation = argv[i] + 3; break; case 's': pnSize = atoi(argv[i] + 3); break; case 'x': pnX = atoi(argv[i] + 3); break; case 'y': pnY = atoi(argv[i] + 3); break; } break; case 'o': // outlines switch ( argv[i][2] ) { case 'O': keepOutlines = true; break; default: o = &argv[i][2]; break; } break; case 'p': // listes de pages à extraire du fichier p = &argv[i][2]; pc = p; while ( *pc ) { if ( (*pc == ';') || (*pc == ',') ) { *pc = ' '; } ++pc; } break; case 'r': optFL |= OPTION_LISTEFICHIERS_RECURSE_SUBDIR; break; case 'R': pageRotation = atoi(argv[i] + 2); if ( (pageRotation != 90) && (pageRotation != 180) && (pageRotation != 270) ) { pageRotation = 0; } break; case 's': // script ou mise à jour des metadatas. if ( (argv[i][2] == 'A') || (argv[i][2] == 'K') || (argv[i][2] == 'S') || (argv[i][2] == 'T') ) { switch ( argv[i][2] ) { case 'A': metadataStr[pMetadataStr ++] = "/Author"; break; case 'K': metadataStr[pMetadataStr ++] = "/Keywords"; break; case 'S': metadataStr[pMetadataStr ++] = "/Subject"; break; case 'T': metadataStr[pMetadataStr ++] = "/Title"; break; } metadataStr[pMetadataStr ++] = &argv[i][3]; pc = &argv[i][3]; while ( *pc ) { if ( *pc == '_' ) { *pc = ' '; } ++pc; } } else { s = &argv[i][2]; break; } break; case 'S': output = 0; break; case 't': bdpStr = &argv[i][2]; break; case 'T': switch ( argv[i][2] ) { case 'c': bdpColors = argv[i] + 3; break; case 'f': bdpFontName = atoi(argv[i] + 3); break; case 'o': bdpOrientation = argv[i] + 3; break; case 's': bdpSize = atoi(argv[i] + 3); break; case 'x': bdpX = atoi(argv[i] + 3); break; case 'y': bdpY = atoi(argv[i] + 3); break; } break; case 'u': mode = MODE_UPDATE; pc = &argv[i][2]; while ( *pc ) { switch ( *pc ) { case 'K': keepBakFile = false; break; case 'P': preserveExistingMetadata = false; break; } ++pc; } break; case 'v': // affichage de la version i = argc; mode = MODE_VERSION; break; case 'x': masterModeNoEncrypt = true; break; case 'z': // ordre inverse des fichiers optFL |= OPTION_LISTEFICHIERS_ORDER_ZA; optFL = optFL & ((OPTION_LISTEFICHIERS_ORDER_AZ | OPTION_LISTEFICHIERS_ORDER_MASK) ^ 0xffffffff); break; default: mode = MODE_DISPLAY_USE; i = argc; } } else { // le commutateur de la ligne de commande n'est pas valide mode = MODE_DISPLAY_USE; i = argc; } } //test de la ligne de commande if ( argc < 2 ) { if ( output != 0 ) displayUse(output); ERROR_FLAGS(ERROR_ARGC_LESS_THAN_2) return RETURN_ARGC_LESS_THAN_2; } if ( infoFlags != 0 ) mode = MODE_GET_INFOS; C_listeFichiers::setPath(".\\"); totalPage = 0; switch ( mode ) { case MODE_DISPLAY_USE: ERROR_FLAGS(ERROR_DISPLAY_USE) if ( output != 0 ) displayUse(output); break; //********************************************************************************************** case MODE_ASSEMBLAGE: case MODE_SPLIT: if ( !((d && m) || (d && s)) ) { if ( output != 0 ) displayUse(output); break; } if ( output != 0 ) fprintf(output, "mbtPdfAsm version %s\r\n", strVersion); //initialisation du fichier résultat if ( pageLimitNumber != 0 ) { i = strlen(d); //corrigé par Bernard Dautrevaux if ( i > 4 && stricmp(d+(i - 4), ".pdf") == 0 ) d[i - 4] = 0; snprintf(tBuf, LG_TBUF - 1, "%s_%03i.pdf", d, 1); if ( p == 0 ) p = "*"; } else { snprintf(tBuf, LG_TBUF - 1, "%s", d); } pPdfFile = new C_pdfFile(tBuf, write); if ( keepOutlines ) { pPdfFile->setKeepOutlines(true); } if ( pPdfFile && (pPdfFile->getStatus()) ) { pPdfFile->setOptions(mdpU, mdpO, masterModeNoEncrypt, restrict, lgEncryptKey, pMetadataStr, metadataStr); SET_PDF_FILE_INSERTION_OPTION startPage = 1; nbInsertedPages = 0; } else { if ( output != 0 ) fprintf(output, strResImp, d); m = 0; s = 0; o = 0; } if ( m ) { // recherche des fichiers selon le mask lFile = new C_listeFichiers(b, m, d, optFL); if ( lFile->getNbFichiers() > 0 ) { if ( p ) { //********** traitement en lot d'une liste de pages lFile->firstFile(tBuf, LG_TBUF - 1); do { currentPageNumber = 0; if ( output != 0 ) fprintf(output, strDebTrait, tBuf); pdfOrg = new C_pdfFile(tBuf, read); if ( !pdfOrg || !pdfOrg->getStatus() ) { //on peut pas ouvrir le fichier pdf ERROR_FLAGS(ERROR_UNABLE_TO_OPEN_ORG_PDF_FILE) if ( output != 0 ) fprintf(output, strErrFile, tBuf); } else { //fichier pdf d'origine ouvert if ( pdfOrg->getXrefTable()->getEncryptObj() != 0 ) { if ( !pdfOrg->encrypt->isDecryptPossible() ) { ERROR_FLAGS(ERROR_UNABLE_TO_DECRYPT_PDF_FILE) if ( output != 0 ) fprintf(output, "impossible de déchiffrer le fichier %s\r\n", fBuf); delete pdfOrg; pdfOrg = 0; continue; } } MAKE_PDF_FILE_FROM_PAGES_LIST } if ( pdfOrg ) { delete pdfOrg; pdfOrg = 0; } } while (lFile->nextFile(tBuf, LG_TBUF - 1)); } else { lFile->firstFile(tBuf, LG_TBUF - 1); do { if ( (res = pPdfFile->merge(tBuf)) != -1 ) { totalPage += res; if ( output != 0 ) fprintf(output, strAjout, tBuf, res); } else { res = pPdfFile->getMergeError(); switch ( res ) { case PDF_MERGE_CANT_MERGE_READ_ONLY_FILE: pc = "impossible de merger un fichier non vide\r\n"; break; case PDF_MERGE_CANT_OPEN_ORG_FILE: pc = (char *)strErrFile; break; case PDF_MERGE_CANT_MERGE_ENCRYPTED_FILE: pc = (char *)strErrEncrypt; break; case PDF_MERGE_CANT_HANDLE_ENCRYPT_VERSION: pc = (char *)strErrEncryptVer; break; default: pc = (char *)strErrFile; break; } if ( output != 0 ) fprintf(output, pc, tBuf); } } while (lFile->nextFile(tBuf, LG_TBUF - 1)); } lFile->closeListe(); } else { ERROR_FLAGS(ERROR_NO_MATCHING_FILE) if ( output != 0 ) fprintf(output, strNoMFile); } } if ( s ) { // interpretation du script char *startFileName; script = fopen(s, "rb"); if ( !script ) { ERROR_FLAGS(ERROR_UNABLE_TO_OPEN_SCRIPT) if ( output != 0 ) fprintf(output, strCantOpenScript, s); } else { sizeof_fBuf = 4 * LGMAX_FILE_NAME; fBuf = new char[sizeof_fBuf]; while ( fgets(fBuf, sizeof_fBuf, script) ) { pc = fBuf; startFileName = fBuf; if ( *pc < ' ') continue; char end; if ( (*pc == '"') || (*pc == '\'') ) { end = *pc++; ++startFileName; } else { end = ' '; } while ( (*pc != end) && ((pc - fBuf) < sizeof_fBuf) && ((unsigned char)(*pc) >= ' ') ) { ++pc; } *pc++ = 0; //il faut avancer pc pour lire la liste des pages à a assembler. pdfOrg = new C_pdfFile(startFileName, read); if ( !pdfOrg || !pdfOrg->getStatus() ) { //on peut pas ouvrir le fichier pdf ERROR_FLAGS(ERROR_UNABLE_TO_OPEN_ORG_PDF_FILE_SCRIPT) if ( output != 0 ) fprintf(output, strErrFile, fBuf); if ( pdfOrg ) { delete pdfOrg; } } else { //fichier pdf d'origine ouvert char *lpc; lpc = pc; while ( *lpc >= ' ' ) ++lpc; *lpc = 0; lpc = pc; while ( *lpc >= ' ' ) { if ( *lpc == '-' ) { if ( (*(lpc + 1) == 'c') && (*(lpc + 2) == 'U') ) { pdfOrg->encrypt->setMdpU(lpc + 3); *(lpc - 1) = 0; break; } } ++lpc; } if ( pdfOrg->getXrefTable()->getEncryptObj() != 0 ) { if ( pdfOrg->encrypt->isDecryptPossible() ) { pPdfFile->setEncryptStandardP(mostRestrictive(pPdfFile->getEncryptStandardP(), pdfOrg->getEncryptStandardP())); } else { ERROR_FLAGS(ERROR_UNABLE_TO_DECRYPT_PDF_FILE_SCRIPT) if ( output != 0 ) fprintf(output, "impossible de déchiffrer le fichier %s\r\n", fBuf); delete pdfOrg; continue; } } p = pc; MAKE_PDF_FILE_FROM_PAGES_LIST pdfOrg->close(); delete pdfOrg; } } fclose(script); } } if ( (pageLimitNumber != 0) && (nbInsertedPages == 0) ) { pPdfFile->close(); remove(pPdfFile->getFileName()); delete pPdfFile; pPdfFile = 0; //--resultFileCpt; } //traitement du fichier de définition des outlines if ( (o != 0) && (mode != MODE_SPLIT) ) { if ( pPdfFile->loadOutlines(o) ) { if ( pPdfFile->flushOutlines() ) { if ( output != 0 ) fprintf(output, "signets integres\r\n"); } else { ERROR_FLAGS(ERROR_UNABLE_TO_FLUSH_OUTLINES) if ( output != 0 ) fprintf(output, strErrSignet); } } else { ERROR_FLAGS(ERROR_UNABLE_TO_LOAD_OUTLINES) if ( output != 0 ) fprintf(output, "impossible de charger %s\r\n", o); } } // fin de la création du fichier PDF if ( pPdfFile ) { pPdfFile->close(); delete pPdfFile; } if ( output != 0 ) fprintf(output, strFinAsm, totalPage); break; /* ********************************************************************** */ case MODE_GET_INFOS: FILE *infOutput; if ( !(m && (infoFlags != 0)) ) { if ( output != 0 ) displayUse(output); break; } infOutput = output; if ( infOutput == 0 ) infOutput = stdout; if ( RES_BUF == 0 ) { RES_BUF_SIZE = RES_BUF_GROWTH; RES_BUF = new char[RES_BUF_SIZE]; RES_BUF[0] = 0; } i = 0; if ( infoFlags & GET_HEADER_LINE ) { if ( infoFlags & GET_FILE_NAME ) i += snprintf(RES_BUF + i, RES_BUF_SIZE - i, "%s;", strHLFileName); if ( infoFlags & GET_NUMBER_OF_PAGES ) i += snprintf(RES_BUF + i, RES_BUF_SIZE - i, "%s;", strHLNumberOfPages); if ( infoFlags & GET_META_AUTHOR ) i += snprintf(RES_BUF + i, RES_BUF_SIZE - i, "%s;", strHLAuthor); if ( infoFlags & GET_META_KW ) i += snprintf(RES_BUF + i, RES_BUF_SIZE - i, "%s;", strHLKW); if ( infoFlags & GET_META_SUBJECT ) i += snprintf(RES_BUF + i, RES_BUF_SIZE - i, "%s;", strHLSubject); if ( infoFlags & GET_META_TITLE ) i += snprintf(RES_BUF + i, RES_BUF_SIZE - i, "%s;", strHLTitle); if ( infoFlags & GET_CYPHER_INFOS ) i += snprintf(RES_BUF + i, RES_BUF_SIZE - i, "%s;%s;%s;", strHLEFilter, strHLEKeyLength, strHLUserMdp); fprintf(infOutput, "%s\r\n", RES_BUF); i = 0; } lFile = new C_listeFichiers(b, m, 0, optFL); if ( lFile->getNbFichiers() > 0 ) { lFile->firstFile(tBuf, LG_TBUF - 1); do { if (infoFlags & GET_FILE_NAME) i += snprintf(RES_BUF + i, RES_BUF_SIZE - i, "%s;", tBuf); pdfOrg = new C_pdfFile(tBuf, read); if ( pdfOrg != 0 ) { if (infoFlags & GET_NUMBER_OF_PAGES) i += snprintf(RES_BUF + i, RES_BUF_SIZE - i, "%i;", pdfOrg->getNbPages()); if (infoFlags & GET_META_AUTHOR ) { pdfOrg->getMetadataStr(tBuf, LG_TBUF - 1, "/Author"); i += snprintf(RES_BUF + i, RES_BUF_SIZE - i, "%s;", tBuf); } if (infoFlags & GET_META_KW ) { pdfOrg->getMetadataStr(tBuf, LG_TBUF - 1, "/Keywords"); i += snprintf(RES_BUF + i, RES_BUF_SIZE - i, "%s;", tBuf); } if (infoFlags & GET_META_SUBJECT ) { pdfOrg->getMetadataStr(tBuf, LG_TBUF - 1, "/Subject"); i += snprintf(RES_BUF + i, RES_BUF_SIZE - i, "%s;", tBuf); } if (infoFlags & GET_META_TITLE ) { pdfOrg->getMetadataStr(tBuf, LG_TBUF - 1, "/Title"); i += snprintf(RES_BUF + i, RES_BUF_SIZE - i, "%s;", tBuf); } if (infoFlags & GET_CYPHER_INFOS) { i += snprintf(RES_BUF + i, RES_BUF_SIZE - i, "%s;%i;%i;%i;", pdfOrg->encrypt->getEncryptFilter(tBuf, LG_TBUF - 1), pdfOrg->encrypt->getEncryptLength(), pdfOrg->encrypt->userProtect()); } fprintf(infOutput, "%s", RES_BUF); if (infoFlags & GET_OUTLINES) { pdfOrg->flushFormatedOutlinesToDest(OUTLINES_FLUSH_FORMAT_MBT, infOutput); fprintf(infOutput, ";"); } delete pdfOrg; } fprintf(infOutput, "\r\n"); i = 0; } while (lFile->nextFile(tBuf, LG_TBUF - 1)); lFile->closeListe(); } else { //i += snprintf(RES_BUF + i, RES_BUF_SIZE - i, "0"); snprintf(RES_BUF + i, RES_BUF_SIZE - i, "0"); fprintf(infOutput, "0"); } break; //***************************************************************************** case MODE_UPDATE: if ( !m ) { if ( output != 0 ) displayUse(output); break; } lFile = new C_listeFichiers(b, m, "pdfbak", optFL); if ( lFile->getNbFichiers() > 0 ) { char tBuf2[LG_TBUF]; lFile->firstFile(tBuf, LG_TBUF - 1); do { _snprintf(tBuf2, LG_TBUF - 1, "%s.pdfbak", tBuf); i = 1; if ( rename(tBuf, tBuf2) != 0 ) { i = 0; remove(tBuf2); if ( rename(tBuf, tBuf2) == 0 ) { i = 1; } } if ( i ) { pPdfFile = new C_pdfFile(tBuf, write); pPdfFile->setOptions(mdpU, mdpO, masterModeNoEncrypt, restrict, lgEncryptKey, pMetadataStr, metadataStr); if ( preserveExistingMetadata ) { #define LG_METADATA_BUF 500 pdfOrg = new C_pdfFile(tBuf2, read); pcc = C_pdfFile::pdfMetadataStrName; if ( fBuf == 0 ) { sizeof_fBuf = LG_METADATA_BUF * 2; fBuf = new char[sizeof_fBuf]; } while ( *pcc != 0 ) { if ( (i = pdfOrg->getMetadataStr(fBuf, LG_METADATA_BUF - 1, *pcc)) != 0 ) { if ( pPdfFile->getMetadataStr(fBuf + LG_METADATA_BUF, LG_METADATA_BUF - 1, *pcc) == 0 ) { pPdfFile->setMetadataStr(*pcc, fBuf, i); } } ++pcc; } delete pdfOrg; } //pPdfFile->merge(tBuf2); pPdfFile->fullMerge(tBuf2); //pPdfFile->close(); delete pPdfFile; if ( !keepBakFile ) { remove(tBuf2); } if ( output != 0 ) fprintf(output, strUpdateRes, tBuf); } else { ERROR_FLAGS(ERROR_DURING_UPDATE) if ( output != 0 ) fprintf(output, strUpdateResErr, tBuf); } } while (lFile->nextFile(tBuf, LG_TBUF - 1)); lFile->closeListe(); } else { ERROR_FLAGS(ERROR_NO_MATCHING_FILE_UPDATE) if ( output != 0 ) fprintf(output, strNoMFile); } break; //*********************************************************************************************** case MODE_VERSION: if ( RES_BUF == 0 ) { RES_BUF_SIZE = RES_BUF_GROWTH; RES_BUF = new char[RES_BUF_SIZE]; } snprintf(RES_BUF, RES_BUF_SIZE, "%s", strVersion); if ( output != 0 ) fprintf(output, "%s\r\n", RES_BUF); break; } if ( lFile ) { delete lFile; } if ( fBuf ) { delete fBuf; } if ( metadataStr ) free(metadataStr); if ( MBuf ) delete MBuf; #ifndef MBTPDFASM_DLL if ( RES_BUF ) delete RES_BUF; #endif return totalPage; }
[ "thierry.schmit@gmail.com" ]
thierry.schmit@gmail.com
7b9a21a80339d2a270bd8a7bf52cd8b8990e4887
3ea863d76752b3aa8a28a9a4c2eb25b664329536
/bluetooth/bt.cpp
b6f8bf5ea79090037cdcce161029c91178600751
[ "ICU" ]
permissive
yuht/CSR8811-Keil
e0289ffafbaa0be1cbd07a79bb53095ce3d6a91e
7637fe443f8ede65082b249b9b61eb3e703d2a8f
refs/heads/master
2021-01-18T18:41:52.419670
2019-04-04T02:12:11
2019-04-04T02:12:11
62,788,271
0
3
null
null
null
null
WINDOWS-1252
C++
false
false
5,262
cpp
#include "bt.h" //#include "../../fc/conf.h" //#include "pan1322.h" #include "CSR8811.h" //#define DEBUG_BT_ENABLED //¿ªÆôµ÷ÊÔ #ifdef DEBUG_BT_ENABLED #define DEBUG_BT(...) DEBUG(__VA_ARGS__) #else #define DEBUG_BT(...) #endif bool bt_autodetect = false; uint8_t bt_module_type = BT_PAN1322; pan1026 bt_pan1026; //pan1322 bt_pan1322; Usart bt_uart; uint32_t bt_reset_counter = 0; uint8_t bt_reset_counter_step = 0; volatile bool bt_device_connected = false; volatile uint8_t bt_module_state = BT_MOD_STATE_OFF; ISR(BT_CTS_PIN_INT) { DEBUG_BT("BT CTS\r\n"); // if (bt_module_type == BT_PAN1322) // bt_pan1322.TxResume(); // if (bt_module_type == BT_PAN1026) bt_pan1026.TxResume(); } //void bt_pan1322_init() //{ // DEBUG_BT("bt_pan1322_init\r\n"); // bt_pan1322.Init(&bt_uart); //} void bt_pan1026_init() { DEBUG_BT("bt_pan1026_init\r\n"); bt_pan1026.Init(&bt_uart); } void bt_module_deinit() { GpioWrite(BT_EN, LOW); GpioWrite(BT_RESET, LOW); bt_irqh(BT_IRQ_DEINIT, 0); bt_uart.Stop(); BT_UART_PWR_OFF; } void bt_module_reset() { GpioWrite(BT_EN, LOW); GpioWrite(BT_RESET, LOW); bt_uart.Stop(); BT_UART_PWR_OFF; bt_reset_counter = task_get_ms_tick() + 500; bt_reset_counter_step = 0; } void bt_module_init() { //module specific code // switch (bt_module_type) // { // case(BT_PAN1322): // bt_pan1322_init(); // break; // case(BT_PAN1026): bt_pan1026_init(); // break; // default: //UNKNOWN module // bt_autodetect = true; // bt_module_type = BT_PAN1322; // bt_pan1322_init(); // break; // } } void bt_init() { DEBUG_BT("bt_init\r\n"); //get module type eeprom_busy_wait(); bt_module_type = eeprom_read_byte(&config_ro.bt_module_type); //init bt_uart bt_uart.InitBuffers(BUFFER_SIZE * 2, BUFFER_SIZE); //pin init GpioSetDirection(BT_EN, OUTPUT); GpioSetDirection(BT_RESET, OUTPUT); GpioSetDirection(BT_RTS, OUTPUT); //power is off GpioWrite(BT_RTS, LOW); GpioWrite(BT_EN, LOW); GpioWrite(BT_RESET, LOW); //IRQ init GpioSetDirection(BT_CTS, INPUT); GpioSetPull(BT_CTS, gpio_pull_down); GpioSetInterrupt(BT_CTS, gpio_interrupt1, gpio_rising); } void bt_stop() { bt_module_deinit(); GpioSetPull(BT_CTS, gpio_totem); } bool bt_device_active() { return bt_device_connected; } void bt_unknown_parser() { while (!bt_uart.isRxBufferEmpty()) { uint8_t c = bt_uart.Read(); DEBUG_BT(">> %02X %c ??\r\n", c, c); } } void bt_step() { if (bt_module_state == BT_MOD_STATE_OFF) return; if (bt_reset_counter) { if (bt_reset_counter > task_get_ms_tick()) return; DEBUG_BT("BT RESET STEP: %d\r\n", bt_reset_counter_step); switch(bt_reset_counter_step) { case(0): GpioWrite(BT_EN, HIGH); bt_reset_counter = task_get_ms_tick() + 500; bt_reset_counter_step = 1; break; case(1): //enable bt uart BT_UART_PWR_ON; bt_uart.Init(BT_UART, 115200); bt_uart.SetInterruptPriority(MEDIUM); bt_reset_counter = task_get_ms_tick() + 10; bt_reset_counter_step = 2; break; case(2): GpioWrite(BT_RESET, HIGH); bt_reset_counter_step = 0; bt_reset_counter = 0; break; } return; } // if (bt_module_type == BT_PAN1322) // bt_pan1322.Step(); // if (bt_module_type == BT_PAN1026) bt_pan1026.Step(); // if (bt_module_type == BT_UNKNOWN) // bt_unknown_parser(); } void bt_send(char * str,uint16_t len) { if (!bt_device_connected) return; // if (bt_module_type == BT_PAN1322) // bt_pan1322.SendString(str); // if (bt_module_type == BT_PAN1026) bt_pan1026.SendString(str,len); } //void bt_sendBinary(char * str,uint16_t len) //{ // if (!bt_device_connected) // return; // //// bt_pan1026.SendBinary(str,len); //} void bt_irqh(uint8_t type, uint8_t * buf) { // uint8_t old_type; switch(type) { case(BT_IRQ_INIT): DEBUG_BT("BT_MOD_STATE_INIT\r\n"); bt_module_state = BT_MOD_STATE_INIT; break; case(BT_IRQ_INIT_OK): DEBUG_BT("BT_MOD_STATE_OK\r\n"); _delay_ms(10); bt_module_state = BT_MOD_STATE_OK; bt_autodetect = false; break; case(BT_IRQ_DEINIT): DEBUG_BT("BT_MOD_STATE_OFF\r\n"); bt_module_state = BT_MOD_STATE_OFF; bt_device_connected = false; break; case(BT_IRQ_CONNECTED): DEBUG_BT("BT_IRQ_CONNECTED\r\n"); gui_showmessage_P(PSTR("Bluetooth connected\r\n")); bt_device_connected = true; break; case(BT_IRQ_DISCONNECTED): DEBUG_BT("BT_IRQ_DISCONNECTED\r\n"); gui_showmessage_P(PSTR("Bluetooth disconnected\r\n")); bt_device_connected = false; break; case(BT_IRQ_RESET): DEBUG_BT("BT_IRQ_RESET\r\n"); bt_device_connected = false; break; case(BT_IRQ_INIT_FAIL): DEBUG_BT("BT_IRQ_INIT_FAIL!\r\n"); if (bt_autodetect) { // old_type = bt_module_type; bt_module_deinit(); bt_module_type = BT_UNKNOWN; _delay_ms(500); BT_UART_PWR_ON; // if (old_type == BT_PAN1322) // { bt_module_type = BT_PAN1026; bt_pan1026_init(); // } // if (old_type == BT_PAN1026) // { // bt_module_type = BT_PAN1322; // bt_pan1322_init(); // } } else { // gui_showmessage_P(PSTR("Bluetooth\r\nInit failed!")); } break; } } bool bt_selftest() { return (bt_module_state == BT_MOD_STATE_OK); } uint8_t bt_get_module_type() { return bt_module_type; }
[ "yuht@qq.com" ]
yuht@qq.com
273e75b669669937d9d3796ba75c6ce892c19874
94dcc118f9492896d6781e5a3f59867eddfbc78a
/llvm/include/llvm/DebugInfo/PDB/Raw/StreamReader.h
1897dfe147452edf0c3e147cf920cb8e752b67d5
[ "NCSA", "Apache-2.0" ]
permissive
vusec/safeinit
43fd500b5a832cce2bd87696988b64a718a5d764
8425bc49497684fe16e0063190dec8c3c58dc81a
refs/heads/master
2021-07-07T11:46:25.138899
2021-05-05T10:40:52
2021-05-05T10:40:52
76,794,423
22
5
null
null
null
null
UTF-8
C++
false
false
1,649
h
//===- StreamReader.h - Reads bytes and objects from a stream ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_DEBUGINFO_PDB_RAW_STREAMREADER_H #define LLVM_DEBUGINFO_PDB_RAW_STREAMREADER_H #include "llvm/ADT/ArrayRef.h" #include "llvm/DebugInfo/PDB/Raw/StreamInterface.h" #include "llvm/Support/Endian.h" #include "llvm/Support/Error.h" #include <string> namespace llvm { namespace pdb { class StreamInterface; class StreamReader { public: StreamReader(const StreamInterface &S); Error readBytes(MutableArrayRef<uint8_t> Buffer); Error readInteger(uint32_t &Dest); Error readZeroString(std::string &Dest); template <typename T> Error readObject(T *Dest) { MutableArrayRef<uint8_t> Buffer(reinterpret_cast<uint8_t *>(Dest), sizeof(T)); return readBytes(Buffer); } template <typename T> Error readArray(MutableArrayRef<T> Array) { MutableArrayRef<uint8_t> Casted(reinterpret_cast<uint8_t*>(Array.data()), Array.size() * sizeof(T)); return readBytes(Casted); } Error getArrayRef(ArrayRef<uint8_t> &Array, uint32_t Length); void setOffset(uint32_t Off) { Offset = Off; } uint32_t getOffset() const { return Offset; } uint32_t getLength() const { return Stream.getLength(); } uint32_t bytesRemaining() const { return getLength() - getOffset(); } private: const StreamInterface &Stream; uint32_t Offset; }; } } #endif
[ "fuzzie@fuzzie.org" ]
fuzzie@fuzzie.org
7ee4cab57405bc4449d9bc11632eebef531e2125
52174bb20c8bb0edd671a780df84e989d5427fb2
/src/irc.cpp
4e6c19c5c042576a3f1b8631de18521fe2a6944a
[ "MIT" ]
permissive
sevenminer7/7coin
44914548a63afa7ba28035ba97a376b33fa504ad
c8132d9980da7765348bfdf73c01c35fe9b4b3ce
refs/heads/master
2020-06-03T06:40:55.397014
2014-01-23T22:35:12
2014-01-23T22:35:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,584
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2012 Litecoin Developers // Copyright (c) 2013 42 Developers // Copyright (c) 2014 The 7 Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "irc.h" #include "net.h" #include "strlcpy.h" #include "base58.h" using namespace std; using namespace boost; int nGotIRCAddresses = 0; void ThreadIRCSeed2(void* parg); #pragma pack(push, 1) struct ircaddr { struct in_addr ip; short port; }; #pragma pack(pop) string EncodeAddress(const CService& addr) { struct ircaddr tmp; if (addr.GetInAddr(&tmp.ip)) { tmp.port = htons(addr.GetPort()); vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp)); return string("u") + EncodeBase58Check(vch); } return ""; } bool DecodeAddress(string str, CService& addr) { vector<unsigned char> vch; if (!DecodeBase58Check(str.substr(1), vch)) return false; struct ircaddr tmp; if (vch.size() != sizeof(tmp)) return false; memcpy(&tmp, &vch[0], sizeof(tmp)); addr = CService(tmp.ip, ntohs(tmp.port)); return true; } static bool Send(SOCKET hSocket, const char* pszSend) { if (strstr(pszSend, "PONG") != pszSend) printf("IRC SENDING: %s\n", pszSend); const char* psz = pszSend; const char* pszEnd = psz + strlen(psz); while (psz < pszEnd) { int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL); if (ret < 0) return false; psz += ret; } return true; } bool RecvLineIRC(SOCKET hSocket, string& strLine) { loop { bool fRet = RecvLine(hSocket, strLine); if (fRet) { if (fShutdown) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() >= 1 && vWords[0] == "PING") { strLine[1] = 'O'; strLine += '\r'; Send(hSocket, strLine.c_str()); continue; } } return fRet; } } int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL) { loop { string strLine; strLine.reserve(10000); if (!RecvLineIRC(hSocket, strLine)) return 0; printf("IRC %s\n", strLine.c_str()); if (psz1 && strLine.find(psz1) != string::npos) return 1; if (psz2 && strLine.find(psz2) != string::npos) return 2; if (psz3 && strLine.find(psz3) != string::npos) return 3; if (psz4 && strLine.find(psz4) != string::npos) return 4; } } bool Wait(int nSeconds) { if (fShutdown) return false; printf("IRC waiting %d seconds to reconnect\n", nSeconds); for (int i = 0; i < nSeconds; i++) { if (fShutdown) return false; Sleep(1000); } return true; } bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet) { strRet.clear(); loop { string strLine; if (!RecvLineIRC(hSocket, strLine)) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 2) continue; if (vWords[1] == psz1) { printf("IRC %s\n", strLine.c_str()); strRet = strLine; return true; } } } bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet) { Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str()); string strLine; if (!RecvCodeLine(hSocket, "302", strLine)) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 4) return false; string str = vWords[3]; if (str.rfind("@") == string::npos) return false; string strHost = str.substr(str.rfind("@")+1); // Hybrid IRC used by lfnet always returns IP when you userhost yourself, // but in case another IRC is ever used this should work. printf("GetIPFromIRC() got userhost %s\n", strHost.c_str()); CNetAddr addr(strHost, true); if (!addr.IsValid()) return false; ipRet = addr; return true; } void ThreadIRCSeed(void* parg) { IMPLEMENT_RANDOMIZE_STACK(ThreadIRCSeed(parg)); // Make this thread recognisable as the IRC seeding thread RenameThread("bitcoin-ircseed"); try { ThreadIRCSeed2(parg); } catch (std::exception& e) { PrintExceptionContinue(&e, "ThreadIRCSeed()"); } catch (...) { PrintExceptionContinue(NULL, "ThreadIRCSeed()"); } printf("ThreadIRCSeed exited\n"); } void ThreadIRCSeed2(void* parg) { /* Dont advertise on IRC if we don't allow incoming connections */ if (mapArgs.count("-connect") || fNoListen) return; if (!GetBoolArg("-irc", false)) return; printf("ThreadIRCSeed started\n"); int nErrorWait = 10; int nRetryWait = 10; while (!fShutdown) { CService addrConnect("92.243.23.21", 6667); // irc.lfnet.org CService addrIRC("irc.lfnet.org", 6667, true); if (addrIRC.IsValid()) addrConnect = addrIRC; SOCKET hSocket; if (!ConnectSocket(addrConnect, hSocket)) { printf("IRC connect failed\n"); nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname")) { closesocket(hSocket); hSocket = INVALID_SOCKET; nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } CNetAddr addrIPv4("1.2.3.4"); // arbitrary IPv4 address to make GetLocal prefer IPv4 addresses CService addrLocal; string strMyName; if (GetLocal(addrLocal, &addrIPv4)) strMyName = EncodeAddress(GetLocalAddress(&addrConnect)); if (strMyName == "") strMyName = strprintf("x%u", GetRand(1000000000)); Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str()); Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str()); int nRet = RecvUntil(hSocket, " 004 ", " 433 "); if (nRet != 1) { closesocket(hSocket); hSocket = INVALID_SOCKET; if (nRet == 2) { printf("IRC name already in use\n"); Wait(10); continue; } nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } Sleep(500); // Get our external IP from the IRC server and re-nick before joining the channel CNetAddr addrFromIRC; if (GetIPFromIRC(hSocket, strMyName, addrFromIRC)) { printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToString().c_str()); if (addrFromIRC.IsRoutable()) { // IRC lets you to re-nick AddLocal(addrFromIRC, LOCAL_IRC); strMyName = EncodeAddress(GetLocalAddress(&addrConnect)); Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str()); } } if (fTestNet) { Send(hSocket, "JOIN #worldcoinTEST3\r"); Send(hSocket, "WHO #worldcoinTEST3\r"); } else { // randomly join #worldcoin00-#worldcoin99 int channel_number = GetRandInt(100); channel_number = 0; // 7: for now, just use one channel Send(hSocket, strprintf("JOIN #7%02d\r", channel_number).c_str()); Send(hSocket, strprintf("WHO #7%02d\r", channel_number).c_str()); } int64 nStart = GetTime(); string strLine; strLine.reserve(10000); while (!fShutdown && RecvLineIRC(hSocket, strLine)) { if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':') continue; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 2) continue; char pszName[10000]; pszName[0] = '\0'; if (vWords[1] == "352" && vWords.size() >= 8) { // index 7 is limited to 16 characters // could get full length name at index 10, but would be different from join messages strlcpy(pszName, vWords[7].c_str(), sizeof(pszName)); printf("IRC got who\n"); } if (vWords[1] == "JOIN" && vWords[0].size() > 1) { // :username!username@50000007.F000000B.90000002.IP JOIN :#channelname strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName)); if (strchr(pszName, '!')) *strchr(pszName, '!') = '\0'; printf("IRC got join\n"); } if (pszName[0] == 'u') { CAddress addr; if (DecodeAddress(pszName, addr)) { addr.nTime = GetAdjustedTime(); if (addrman.Add(addr, addrConnect, 51 * 60)) printf("IRC got new address: %s\n", addr.ToString().c_str()); nGotIRCAddresses++; } else { printf("IRC decode failed\n"); } } } closesocket(hSocket); hSocket = INVALID_SOCKET; if (GetTime() - nStart > 20 * 60) { nErrorWait /= 3; nRetryWait /= 3; } nRetryWait = nRetryWait * 11 / 10; if (!Wait(nRetryWait += 60)) return; } } #ifdef TEST int main(int argc, char *argv[]) { WSADATA wsadata; if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR) { printf("Error at WSAStartup()\n"); return false; } ThreadIRCSeed(NULL); WSACleanup(); return 0; } #endif
[ "sevenminer7@gmail.com" ]
sevenminer7@gmail.com
38c633311279d17d9570a58320027f2ba58c23eb
b71a7dde138885229d78b958c085872f35cdd218
/Applications/SpaceInvaders/BlocAliens.h
3d7c1513274708d3654e178039804d3a29c66af2
[]
no_license
Kporal/SuperCasseBriques
c2df7513f2f88c6d5bf500e01b05ff4a1388ca66
bc48b15719f7e7d106681b525c323e4f6e1dec29
refs/heads/master
2016-09-06T01:29:04.629721
2013-10-31T22:43:49
2013-10-31T22:43:49
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
2,442
h
/* * BlocAliens.h * * Created on: 27 oct. 2008 * Author: Aurélien */ #ifndef BLOCALIENS_H_ #define BLOCALIENS_H_ #include "TimerSpaceInvaders.h" #include <sextant/Activite/Threads.h> #include "ConfigSpaceInvader.h" #include "Entites/EntiteFactory.h" #include "Random.h" class Espace; /* * Bloc d'aliens. * Si le sémaphore deplacementAliens du timer est dispo, le bloc se déplace. */ class BlocAliens: public Threads { private: /* * Le timer sert à gérer le mouvement suivant les tic d'horloges et interruption. */ TimerSpaceInvaders *timer; Espace *espace; /* * Tableau d'aliens. * Largeur et Hauteur sont les dimensions actuelles du tableau, pouvant varier * suivant la destruction des aliens. EcartGauche et EcartHaut interviennent * lorsque le bloc est diminué à gauche ou à droite. */ int hauteur, largeur, ecartGauche; Alien *blocAliens[LARGEUR_BLOC_ALIEN_MAX * HAUTEUR_BLOC_ALIEN_MAX]; //Linéarisation du tableau. /* * Direction de déplacement du bloc, ainsi que sa vitesse. * Position du bloc dans l'espace. Repéré par son entité en haut à gauche. * Nombre d'aliens présents dans le bloc. */ int direction, vitesseBlocInitiale, positionLigne, positionColonne, nombreAliens, nombreAliensInitial; /* * Générateur de nombres aléatoires. */ Random random; public: BlocAliens(TimerSpaceInvaders *timer, Espace *espace, int vitesse, int positionLigne = 2, int positionColonne = 15); ~BlocAliens(); /* * Accesseurs simples. */ int getPositionLigne(); int getPositionColonne(); int getEcartGauche(); int getHauteur(); int getLargeur(); int getDirection(); void run(); /* * Retourne l'entité depuis les coordonnées intra-bloc. * Retourne le nombre d'aliens restants sauvegardé (rapide) ou le recalcule (lent). */ Alien *getAlien(int ligne, int colonne); int getNombreAliensRestants(); int calculerNombreAliensRestants(); /* * Retourne les positions intrabloc de l'alien. */ int getPositionLigne(Alien *alien); int getPositionColonne(Alien *alien); void creerBloc1(); void ajouterAlien(int ligne, int colonne, Alien *alien); void retirerAlien(Alien *alien); void deplacer(); void effacer(); void dessiner(); void ajusterDimensionsBloc(); void ajusterDimensionAGauche(); void ajusterDimensionADroite(); void ajusterDimensionEnBas(); void ajusterVitesse(); void tirerMissile(); }; #endif /* BLOCALIENS_H_ */
[ "Guillaume@Samsung-Leloup" ]
Guillaume@Samsung-Leloup
82e03e9a6b39875f4c811c3a64be83218993d023
bb4d0899650ec41875a93ce053b9854221283bba
/contests/paiza_s/002.cpp
2b8f43b64fa141e5441ac49376abc5ccfd6390e3
[]
no_license
moosan63/my_competitive_programmings
9c41a9ac9a95c5f404b1e697c75650b4a0076a0f
e507b15659e9c629839165f0f265eb624df8bda2
refs/heads/master
2020-05-19T17:04:27.378309
2020-01-27T10:15:32
2020-01-27T10:15:32
185,125,043
0
0
null
null
null
null
UTF-8
C++
false
false
2,241
cpp
#include <algorithm> #include <bitset> #include <cstdio> #include <cstdlib> #include <iomanip> #include <iostream> #include <map> #include <numeric> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> #define REP(i, b, n) for (Int i = b; i < Int(n); i++) #define rep(i, n) REP(i, 0, n) using namespace std; using Int = long long; Int inf = 1000000000000000001LL; using vi = vector<Int>; using vvi = vector<vi>; int start_i, start_j; int goal_i, goal_j; int N,M; vvi done_a; vvi done_b; vvi done_c; vvi done_d; vector<vector<char>> nm; Int GCD(Int a, Int b){ if(b==0) return a; if(a < b) return GCD(b, a); unsigned r; while ((r=a%b)) { a = b; b = r; } return b; } int dfs(int source_i, int source_j, int i, int j,Int cost){ if(i == goal_i && j == goal_j){ return cost; } if(nm[i][j]=='1'){ return 99999999; } int a=999999999,b=999999999,c=999999999,d=999999999; if(i+1 != source_i && i<M-1 && done_a[i+1][j] != 1){ done_a[i+1][j] = 1; a = dfs(i,j,i+1,j,cost+1); } if(i-1 != source_i && i>0 && done_b[i-1][j] != 1){ done_b[i-1][j] = 1; b = dfs(i,j,i-1,j,cost+1); } if(j+1 != source_j && j<N-1 && done_c[i][j+1] != 1){ done_c[i][j+1] = 1; c = dfs(i,j,i,j+1,cost+1); } if(j-1 != source_j && j>0 && done_d[i][j-1] != 1){ done_d[i][j-1] = 1; d = dfs(i,j,i,j-1,cost+1); } return min(a,(min(b,min(c,d)))); } int main() { Int ans; cin >> N >> M; nm = vector<vector<char>>(M,vector<char>(N,'0')); done_a = vvi(M,vi(N,0)); done_b = vvi(M,vi(N,0)); done_c = vvi(M,vi(N,0)); done_d = vvi(M,vi(N,0)); rep(i,M){ rep(j,N){ cin >> nm[i][j]; if(nm[i][j] == 's'){ start_i = i; start_j = j; } if(nm[i][j] == 'g'){ goal_i = i; goal_j = j; } } } ans = dfs(start_i,start_j,start_i,start_j,0); if(ans != 99999999){ cout << ans; }else{ cout << "Fail"; } return 0; }
[ "moosan63@gmail.com" ]
moosan63@gmail.com
38ab5016f5a605ea7d7245f14ae0eeebd65862c6
b38ab36ce6710bda9c495301d1d7b8769cfd454b
/projects/GoldMiner/Classes/SelectRoleAndPropMenu.cpp
835bc0496f2f8f5738f24c7e297b4ebd29abfeaf
[]
no_license
wjf1616/TheMiners
604fa141dbbe614a87ea88a1d9d9a4bc60678070
afdb2eab217ad90434736d9580e942d5622bf929
refs/heads/master
2021-01-10T02:21:26.861908
2016-01-06T10:18:58
2016-01-06T10:18:58
48,987,660
2
0
null
null
null
null
GB18030
C++
false
false
83,442
cpp
#include "SelectRoleAndPropMenu.h" #include "Global.h" #include "GoldenMinerScene.h" #include "RoleInformation.h" #include "Player.h" #include "CartoonLayer.h" #include "GameControl.h" #include "LoadingLayer.h" #include "PromptLayer.h" USING_NS_CC; USING_NS_CC_EXT; #define SELECTROLEANDPROPMENU_YUN_ASIDE 11 #define SELECTROLEANDPROPMENU_FRAME_ASIDE 111 #define SELECTROLEANDPROPMENU_BUTTON_ASIDE 11 #define SELECTROLEANDPROPMENU_YUN_MIDDLE 21 #define SELECTROLEANDPROPMENU_FRAME_MIDDLE 121 #define SELECTROLEANDPROPMENU_BUTTON_MIDDLE 21 #define SELECTROLEANDPROPMENU_BUTTON_SELECTED_UP 102 #define SELECTROLEANDPROPMENU_BUTTON_UNSELECTED_DOWN 101 #define SELECTROLEANDPROPMENU_POINT_Y 40 #define SELECTROLEANDPROPMENU_POINT_X 30 static const ccColor3B myGrey={60,60,60}; static const ccColor4B myGrey4 = {0,0,0,200}; SelectRoleAndPropMenu::SelectRoleAndPropMenu(void) : mAnimationManager(NULL) ,greyLayer(NULL) ,isBackGround(false) ,loadingLayer(NULL) { } SelectRoleAndPropMenu::~SelectRoleAndPropMenu(void) { CC_SAFE_RELEASE_NULL(mAnimationManager); CC_SAFE_RELEASE_NULL(rolePageButton);// 人物选择按钮 CC_SAFE_RELEASE_NULL(propPageButton);// 道具选择按钮 CC_SAFE_RELEASE_NULL(ingotNum);// 道具选择按钮 CC_SAFE_RELEASE_NULL(coupletSelect);// 道具选择按钮 CC_SAFE_RELEASE_NULL(coupletAbout);// 道具选择按钮 CC_SAFE_DELETE(propControl); CCObject * p; CC_SAFE_RELEASE(pointIndexSprite); CCARRAY_FOREACH(selectPropId, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(selectRoleSpritesName, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(pointRoleSprites, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(pointPropSprites, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(currSelectPropPrice, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(currSelectPropName, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(currSelectSpritesIntroduce, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(currSelectRoleSpeedBackground, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(currSelectRolePowerBackground, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(currSelectRoleSpeed, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(currSelectRolePower, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(selectRoleSpritesSpeed, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(selectRoleSpritesPower, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(selectRoleSpritesIntroduce, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(selectPropIntroduce, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(selectPropPrice, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(selectPropName, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(selectRoleSprites, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(selectRoleSpritesIsHaving, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(selectRoleSpritesIsOpen, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(selectPropSprites, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(currSelectSprites, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(currSelectRoleSpritesIsHaving, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(currSelectRoleSpritesIsOpen, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(currSelectYunSprites, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(currSelectButtonSelectSprites, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(currSelectPropFrameSprites, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(currSelectGetSelectSprites, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(currSelectAboutSelectSprites, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(currSelectFrameSprites, p) { CC_SAFE_RELEASE_NULL(p); } CCARRAY_FOREACH(currSelectButtonBuySprites, p) { CC_SAFE_RELEASE_NULL(p); } CCLOG("SelectRoleAndPropMenu::~SelectRoleAndPropMenu"); } void SelectRoleAndPropMenu::onEnter(void) { CCLayer::onEnter(); setVisible(false); isBackGround = true; Player::getInstance()->getMusicControl()->playOtherBackGround(); isFristRolePage = true; isFristPropPage = true; currRoleIndex = 0; currPropIndex = 0; isRolePage = false; rolePageButton = CCSprite::create("xuanren/renwu.png"); CC_SAFE_RETAIN(rolePageButton); addChild(rolePageButton); propPageButton = CCSprite::create("xuanren/daoju.png"); CC_SAFE_RETAIN(propPageButton); addChild(propPageButton); char _s[32]; sprintf(_s, "%d",Player::getInstance()->getPropNum(PROP_TYPE_INGOT)); ingotNum = CCLabelAtlas::create(_s, "xuanren/yuanbaoshuzi.png", 18, 26, '0'); CC_SAFE_RETAIN(ingotNum); addChild(ingotNum, 998); coupletSelect = CCSprite::create("xuanren/yishangzhen.png");// 已上阵 coupletSelect->setPosition(ccp(280, 320)); CC_SAFE_RETAIN(coupletSelect); addChild(coupletSelect); coupletAbout = CCSprite::create("xuanren/weijiesuo.png");// 未解锁 coupletAbout->setPosition(ccp(280, 320)); CC_SAFE_RETAIN(coupletAbout); addChild(coupletAbout); currSelectSprites = new CCArray(); currSelectRoleSpritesIsHaving = new cocos2d::CCArray(); selectRoleSpritesIsOpen = new cocos2d::CCArray(); selectPropSprites = new CCArray(); selectRoleSprites = new CCArray(); selectRoleSpritesIsHaving = new cocos2d::CCArray(); currSelectRoleSpritesIsOpen = new cocos2d::CCArray(); // 人物界面 selectRoleSpritesName = new CCArray(); currSelectRoleSpeedBackground = new CCArray(); currSelectRolePowerBackground = new CCArray(); currSelectRoleSpeed = new CCArray(); currSelectRolePower = new CCArray(); currSelectYunSprites = new CCArray(); currSelectButtonSelectSprites = new CCArray(); currSelectAboutSelectSprites = new CCArray(); currSelectGetSelectSprites = new CCArray(); currSelectFrameSprites = new CCArray(); currSelectSpritesIntroduce = new cocos2d::CCArray(); selectRoleSpritesSpeed = new CCArray(); selectRoleSpritesPower = new CCArray(); selectRoleSpritesIntroduce = new CCArray(); currSelectPropPrice = new cocos2d::CCArray(); currSelectPropName = new cocos2d::CCArray(); pointRoleSprites = new cocos2d::CCArray(); // 道具界面 currSelectButtonBuySprites = new CCArray(); currSelectPropFrameSprites = new cocos2d::CCArray(); selectPropIntroduce = new CCArray(); selectPropPrice = new CCArray(); selectPropName = new CCArray(); pointPropSprites = new cocos2d::CCArray(); selectPropId = new cocos2d::CCArray(); initSprites(); setPageButton(isRolePage); Global::getInstance()->setSelectRoleId(Player::getInstance()->getLastRoleSelect()); ((CCSprite *)selectRoleSpritesName->objectAtIndex((currRoleIndex + 1)%selectRoleSpritesName->count()))->setVisible(false); schedule(schedule_selector(SelectRoleAndPropMenu::doAction), 0); setTouchEnabled(true); setKeypadEnabled(true); } void SelectRoleAndPropMenu::onEnterTransitionDidFinish(void) { CCLayer::onEnterTransitionDidFinish(); if (loadingLayer != NULL) { ((LoadingLayer *)loadingLayer)->appendFinishLayerNum(1); } else { startSelf(); } } void SelectRoleAndPropMenu::startSelf(void) { setVisible(true); isBackGround = false; mAnimationManager->runAnimationsForSequenceNamed("daojuchuxian"); } void SelectRoleAndPropMenu::setLoadingLayer(cocos2d::CCLayer * _layer) { loadingLayer = _layer; if (loadingLayer == NULL) { setVisible(true); } } void SelectRoleAndPropMenu::keyBackClicked(void) { onMenuItemBackClicked(NULL); } void SelectRoleAndPropMenu::onExit(void) { mAnimationManager->setAnimationCompletedCallback(NULL, NULL); CCLayer::onExit(); } SEL_MenuHandler SelectRoleAndPropMenu::onResolveCCBCCMenuItemSelector(CCObject * pTarget, const char * pSelectorName) { CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnBack", SelectRoleAndPropMenu::onMenuItemBackClicked); CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnPlay", SelectRoleAndPropMenu::onMenuItemPlayClicked); CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnPlus", SelectRoleAndPropMenu::onMenuItemPlusClicked); CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnShop", SelectRoleAndPropMenu::onMenuItemShopClicked); // 解锁信息 CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnUnlock1", SelectRoleAndPropMenu::menuAbout1Callback); CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnUnlock2", SelectRoleAndPropMenu::menuAbout2Callback); CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnUnlock3", SelectRoleAndPropMenu::menuAbout3Callback); CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnUnlock4", SelectRoleAndPropMenu::menuAbout4Callback); // 购买道具 CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnBuy1", SelectRoleAndPropMenu::menuBuy1Callback); CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnBuy2", SelectRoleAndPropMenu::menuBuy2Callback); CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnBuy3", SelectRoleAndPropMenu::menuBuy3Callback); CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnBuy4", SelectRoleAndPropMenu::menuBuy4Callback); // 招募 CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnRecruit1", SelectRoleAndPropMenu::menuGet1Callback); CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnRecruit2", SelectRoleAndPropMenu::menuGet2Callback); CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnRecruit3", SelectRoleAndPropMenu::menuGet3Callback); CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnRecruit4", SelectRoleAndPropMenu::menuGet4Callback); // 上阵 CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnBattle1", SelectRoleAndPropMenu::menuSelect1Callback); CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnBattle2", SelectRoleAndPropMenu::menuSelect2Callback); CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnBattle3", SelectRoleAndPropMenu::menuSelect3Callback); CCB_SELECTORRESOLVER_CCMENUITEM_GLUE(this, "OnBattle4", SelectRoleAndPropMenu::menuSelect4Callback); return NULL; } SEL_CCControlHandler SelectRoleAndPropMenu::onResolveCCBCCControlSelector(CCObject * pTarget, const char * pSelectorName) { return NULL; } bool SelectRoleAndPropMenu::onAssignCCBMemberVariable(CCObject * pTarget, const char * pMemberVariableName, CCNode * pNode) { CCB_MEMBERVARIABLEASSIGNER_GLUE(this, "mAnimationManager", CCBAnimationManager *, this->mAnimationManager); return false; } void SelectRoleAndPropMenu::setAnimationManager(cocos2d::extension::CCBAnimationManager *pAnimationManager) { CC_SAFE_RELEASE_NULL(mAnimationManager); mAnimationManager = pAnimationManager; //mAnimationManager->runAnimationsForSequenceNamed("daojuchuxian"); mAnimationManager->setAnimationCompletedCallback(this, callfunc_selector(SelectRoleAndPropMenu::doAnimationCompleted)); CC_SAFE_RETAIN(mAnimationManager); } void SelectRoleAndPropMenu::setBackGround(bool _b) { if (_b == true) { if (greyLayer == NULL) { greyLayer = CCLayerColor::create(myGrey4); } Global::getInstance()->s->addLayerToRunningScene(greyLayer); } else { if (greyLayer != NULL) { Global::getInstance()->s->removeLayerToRunningScene(greyLayer); greyLayer = NULL; } } isBackGround = _b; } void SelectRoleAndPropMenu::onMenuItemShopClicked(cocos2d::CCObject * pSender) { Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON); } void SelectRoleAndPropMenu::onMenuItemBackClicked(cocos2d::CCObject * pSender) { //Global::getInstance()->s->replaceScene(Global::getInstance()->s->getShopLayer(NULL)); //if (Global::getInstance()->getChallengeLevel() != 0) //{ // LoadingLayer * _tmp; // CCLayer * _tmp1; // _tmp = (LoadingLayer *)Global::getInstance()->s->getLoadingLayer(); // _tmp1 = Global::getInstance()->s->getMainLayer(_tmp); // _tmp->setNextLayer(LAYER_ID_MAIN, _tmp1); // _tmp->addLoadingLayer(0,_tmp1); // Global::getInstance()->s->replaceScene(_tmp); // //Global::getInstance()->s->replaceScene(Global::getInstance()->s->getMainLayer()); //} //else //{ // // 有loading // Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON); // LoadingLayer * _tmp; // CCLayer * _tmp1; // _tmp = (LoadingLayer *)Global::getInstance()->s->getLoadingLayer(); // _tmp1 = Global::getInstance()->s->getSimleGateMenu(_tmp); // _tmp->setNextLayer(LAYER_ID_SMILE_GATE_SCENCE, _tmp1); // _tmp->addLoadingLayer(0,_tmp1); // Global::getInstance()->s->replaceScene(_tmp); // //Global::getInstance()->s->replaceScene(Global::getInstance()->s->getSimleGateMenu()); // // // 没有loading // //Global::getInstance()->s->replaceScene(Global::getInstance()->s->getSimleGateMenu(NULL)); //} } void SelectRoleAndPropMenu::onMenuItemPlayClicked(cocos2d::CCObject * pSender) { Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON); Player::getInstance()->setLastRoleSelect(Global::getInstance()->getSelectRoleId()); if (Global::getInstance()->getChallengeLevel() != 0) { //// 开始游戏loading的页面 //LoadingLayer * p = (LoadingLayer *)Global::getInstance()->s->getLoadingLayer(); //CCLayer * p1 = Global::getInstance()->s->getChallengeLayer(Global::getInstance()->getNextChallengeGateId(), Global::getInstance()->getSelectRoleId(), p); ////((GameControl *)p1)->setLoadingLayer(p); ////p->appendLoadingLayerNum(1); //p->addLoadingLayer(0,p1); //p->setNextLayer(LAYER_ID_GAMING, p1); //Global::getInstance()->s->replaceScene(p); ////Global::getInstance()->s->addLayerToRunningScene(p1); //开始游戏没有loading的页面 Global::getInstance()->s->replaceScene(Global::getInstance()->s->getChallengeLayer(Global::getInstance()->getNextChallengeGateId(), Global::getInstance()->getSelectRoleId(), NULL)); //Global::getInstance()->s->replaceScene(Global::getInstance()->s->getChallengeLayer(Global::getInstance()->getNextChallengeGateId(), Global::getInstance()->getSelectRoleId())); } else { Player::getInstance()->setLastMapId(Global::getInstance()->getMapIdByGateId(Global::getInstance()->getSelectGateId())); // 播放漫画 Global::getInstance()->setCartoonId(0); Global::getInstance()->setCartoonId(Global::getInstance()->getSelectGateId()); //// 开始游戏loading的页面 //LoadingLayer * p = NULL; //CCLayer * p1 = NULL; //CCLayer * p2 = NULL; //CCLayer * p3 = NULL; //switch(Global::getInstance()->getCartoonId()) //{ //case 0: // p = (LoadingLayer *)Global::getInstance()->s->getLoadingLayer(); // p1 = Global::getInstance()->s->getGameLayer(Global::getInstance()->getSelectGateId(), Global::getInstance()->getSelectRoleId(),p); // p->setNextLayer(LAYER_ID_GAMING, p1); // //((GameControl *)p1)->setLoadingLayer(p); // //p->appendLoadingLayerNum(1); // p->addLoadingLayer(0,p1); // Global::getInstance()->s->replaceScene(p); // //Global::getInstance()->s->addLayerToRunningScene(p1); // break; //case CARTOON_BAOXIANGGUO: // p = (LoadingLayer *)Global::getInstance()->s->getLoadingLayer(); // p1 = Global::getInstance()->s->getCartoonLayer(CARTOON_START, p); // p2 = Global::getInstance()->s->getCartoonLayer(CARTOON_BAOXIANGGUO, p); // p3 = Global::getInstance()->s->getGameLayer(Global::getInstance()->getSelectGateId(), Global::getInstance()->getSelectRoleId(),p); // p->setNextLayer(LAYER_ID_CARTOON, p1); // ((CartoonLayer *)p1)->setNextLayer(LAYER_ID_CARTOON, p2); // ((CartoonLayer *)p2)->setNextLayer(LAYER_ID_GAMING, p3); // //((CartoonLayer *)p1)->setLoadingLayer(p); // //((CartoonLayer *)p2)->setLoadingLayer(p); // //((GameControl *)p3)->setLoadingLayer(p); // //p->appendLoadingLayerNum(1); // p->addLoadingLayer(0,p1); // p->addLoadingLayer(0,p2); // p->addLoadingLayer(0,p3); // Global::getInstance()->s->replaceScene(p); // //Global::getInstance()->s->addLayerToRunningScene(p1); // //Global::getInstance()->s->addLayerToRunningScene(p2); // //Global::getInstance()->s->addLayerToRunningScene(p3); // break; //case CARTOON_TONGYIANHE: // p = (LoadingLayer *)Global::getInstance()->s->getLoadingLayer(); // p1 = Global::getInstance()->s->getCartoonLayer(CARTOON_TONGYIANHE,p); // p2 = Global::getInstance()->s->getGameLayer(Global::getInstance()->getSelectGateId(), Global::getInstance()->getSelectRoleId(),p); // p->setNextLayer(LAYER_ID_CARTOON, p1); // ((CartoonLayer *)p1)->setNextLayer(LAYER_ID_GAMING, p2); // //((CartoonLayer *)p1)->setLoadingLayer(p); // //((GameControl *)p2)->setLoadingLayer(p); // //p->appendLoadingLayerNum(1); // p->addLoadingLayer(0,p1); // p->addLoadingLayer(0,p2); // Global::getInstance()->s->replaceScene(p); // //Global::getInstance()->s->addLayerToRunningScene(p1); // //Global::getInstance()->s->addLayerToRunningScene(p2); // break; //case CARTOON_NVERGUO: // p = (LoadingLayer *)Global::getInstance()->s->getLoadingLayer(); // p1 = Global::getInstance()->s->getCartoonLayer(CARTOON_NVERGUO,p); // p2 = Global::getInstance()->s->getGameLayer(Global::getInstance()->getSelectGateId(), Global::getInstance()->getSelectRoleId(),p); // p->setNextLayer(LAYER_ID_CARTOON, p1); // ((CartoonLayer *)p1)->setNextLayer(LAYER_ID_GAMING, p2); // //((CartoonLayer *)p1)->setLoadingLayer(p); // //((GameControl *)p2)->setLoadingLayer(p); // //p->appendLoadingLayerNum(1); // p->addLoadingLayer(0,p1); // p->addLoadingLayer(0,p2); // Global::getInstance()->s->replaceScene(p); // //Global::getInstance()->s->addLayerToRunningScene(p1); // //Global::getInstance()->s->addLayerToRunningScene(p2); // break; //case CARTOON_HUOYANSHAN: // p = (LoadingLayer *)Global::getInstance()->s->getLoadingLayer(); // p1 = Global::getInstance()->s->getCartoonLayer(CARTOON_HUOYANSHAN,p); // p2 = Global::getInstance()->s->getGameLayer(Global::getInstance()->getSelectGateId(), Global::getInstance()->getSelectRoleId(),p); // p->setNextLayer(LAYER_ID_CARTOON, p1); // ((CartoonLayer *)p1)->setNextLayer(LAYER_ID_GAMING, p2); // //((CartoonLayer *)p1)->setLoadingLayer(p); // //((GameControl *)p2)->setLoadingLayer(p); // //p->appendLoadingLayerNum(1); // p->addLoadingLayer(0,p1); // p->addLoadingLayer(0,p2); // Global::getInstance()->s->replaceScene(p); // //Global::getInstance()->s->addLayerToRunningScene(p1); // //Global::getInstance()->s->addLayerToRunningScene(p2); // break; //case CARTOON_LINGSHAN: // p = (LoadingLayer *)Global::getInstance()->s->getLoadingLayer(); // p1 = Global::getInstance()->s->getCartoonLayer(CARTOON_LINGSHAN,p); // p2 = Global::getInstance()->s->getGameLayer(Global::getInstance()->getSelectGateId(), Global::getInstance()->getSelectRoleId(),p); // p->setNextLayer(LAYER_ID_CARTOON, p1); // ((CartoonLayer *)p1)->setNextLayer(LAYER_ID_GAMING, p2); // //((CartoonLayer *)p1)->setLoadingLayer(p); // //((GameControl *)p2)->setLoadingLayer(p); // //p->appendLoadingLayerNum(1); // p->addLoadingLayer(0,p1); // p->addLoadingLayer(0,p2); // Global::getInstance()->s->replaceScene(p); // //Global::getInstance()->s->addLayerToRunningScene(p1); // //Global::getInstance()->s->addLayerToRunningScene(p2); // break; //default: // break; //} // 开始游戏loading的页面 if (Global::getInstance()->getCartoonId() != 0) { if (Global::getInstance()->getCartoonId() == CARTOON_BAOXIANGGUO) { Global::getInstance()->s->replaceScene(Global::getInstance()->s->getCartoonLayer(CARTOON_START, NULL)); } else { Global::getInstance()->s->replaceScene(Global::getInstance()->s->getCartoonLayer(Global::getInstance()->getCartoonId(), NULL)); } } else { Global::getInstance()->s->replaceScene(Global::getInstance()->s->getGameLayer(Global::getInstance()->getSelectGateId(), Global::getInstance()->getSelectRoleId(), NULL)); } //// 播放漫画 //Global::getInstance()->setCartoonId(Global::getInstance()->getSelectGateId()); //if (Global::getInstance()->getCartoonId() != 0) //{ // Global::getInstance()->s->replaceScene(Global::getInstance()->s->getCartoonLayer(Global::getInstance()->getCartoonId())); //} //else //{ // Player::getInstance()->setLastMapId(Global::getInstance()->getSelectGateId()); // Global::getInstance()->s->replaceScene(Global::getInstance()->s->getGameLayer(Global::getInstance()->getSelectGateId(), Global::getInstance()->getSelectRoleId())); //} } } void SelectRoleAndPropMenu::onMenuItemPlusClicked(cocos2d::CCObject * pSender) { Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON); } void SelectRoleAndPropMenu::ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent) { if (isBackGround) { return; } //此方法是cocos2d-x的标准操作,取touch集合第一个touch,将其位置转成opengl坐标,没办法,这些坐标太乱了,touch默认坐标是屏幕坐标,左上角为远点,cocos默认坐标是opengl坐标,左下角是原点。 CCSetIterator it = pTouches->begin(); CCTouch* touch = (CCTouch*)(*it); m_touchBeginPos = touch->getLocation (); m_touchBeginPos = CCDirector::sharedDirector()->convertToGL( m_touchBeginPos ); if (isRolePage) { isCheckButtonIsSelected = Global::getInstance()->isInRect( new CCRect(rolePageButton->getPositionX() + rolePageButton->getContentSize().width/2, propPageButton->getPositionY() - propPageButton->getContentSize().height*0.7/2, propPageButton->getContentSize().width*0.7, propPageButton->getContentSize().height*0.7 ), m_touchBeginPos.x, 480 - m_touchBeginPos.y); } else { isCheckButtonIsSelected = Global::getInstance()->isInRect( new CCRect(rolePageButton->getPositionX() - rolePageButton->getContentSize().width*0.7/2, rolePageButton->getPositionY() - rolePageButton->getContentSize().height*0.7/2, propPageButton->getPositionX() - (rolePageButton->getPositionX() - rolePageButton->getContentSize().width*0.7/2), rolePageButton->getContentSize().height*0.7 ), m_touchBeginPos.x, 480 - m_touchBeginPos.y); } m_touchMove = false; } void SelectRoleAndPropMenu::ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent) { if (isBackGround) { return; } m_touchMove = true; } void SelectRoleAndPropMenu::ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent) { if (isBackGround) { return; } CCSetIterator it = pTouches->begin(); CCTouch* touch = (CCTouch*)(*it); m_touchEndPos = touch->getLocation (); m_touchEndPos = CCDirector::sharedDirector()->convertToGL( m_touchEndPos ); if(m_touchMove) { //如果move了,那么看手指是否上下滑动超过50像素,这个纠正值得有,否则太灵敏了 if ((m_touchBeginPos.x - m_touchEndPos.x) > 50) { if(isRolePage) { setCurrRole(true); } else { setCurrProp(true); } } else if ((m_touchEndPos.x - m_touchBeginPos.x) > 50) { if(isRolePage) { setCurrRole(false); } else { setCurrProp(false); } } else { checkButtonEvent(); } } else { checkButtonEvent(); } m_touchMove = false; } void SelectRoleAndPropMenu::changeCurrPage(void) { for (int i = 0; i < selectRoleSpritesName->count(); i++) { ((CCSprite *)selectRoleSpritesName->objectAtIndex(i))->setVisible(false); } if(isRolePage) { mAnimationManager->runAnimationsForSequenceNamed("rwxiaoshi"); // 换button的显示 } else { mAnimationManager->runAnimationsForSequenceNamed("daojuxiaoshi"); // 换button的显示 } } void SelectRoleAndPropMenu::setCurrRole(bool _isXiangZuo) { if (_isXiangZuo) { setNodeBySelectIndex(_isXiangZuo); currRoleIndex++; currRoleIndex = currRoleIndex % selectRoleSprites->count(); mAnimationManager->runAnimationsForSequenceNamed("xiangzuo"); for (int i = 0; i < 4; i++) { if (i == 2) { currButtonIndex = 3; ((CCSprite *)currSelectYunSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_YUN_MIDDLE); ((CCSprite *)currSelectFrameSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE); ((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE); ((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE); ((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE); ((CCSprite *)currSelectRoleSpeed->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE); ((CCSprite *)currSelectRolePower->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE); ((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_MIDDLE); ((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_MIDDLE); ((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_MIDDLE); } else { ((CCSprite *)currSelectYunSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_YUN_ASIDE); ((CCSprite *)currSelectFrameSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE); ((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE); ((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE); ((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE); ((CCSprite *)currSelectRoleSpeed->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE); ((CCSprite *)currSelectRolePower->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE); ((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_ASIDE); ((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_ASIDE); ((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_ASIDE); } } } else { setNodeBySelectIndex(_isXiangZuo); currRoleIndex--; currRoleIndex = (currRoleIndex + selectRoleSprites->count()) % selectRoleSprites->count(); mAnimationManager->runAnimationsForSequenceNamed("xiangyou"); for (int i = 0; i < 4; i++) { if (i == 0) { currButtonIndex = 1; ((CCSprite *)currSelectYunSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_YUN_MIDDLE); ((CCSprite *)currSelectFrameSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE); ((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE); ((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE); ((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE); ((CCSprite *)currSelectRoleSpeed->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE); ((CCSprite *)currSelectRolePower->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE); ((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_MIDDLE); ((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_MIDDLE); ((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_MIDDLE); } else { ((CCSprite *)currSelectYunSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_YUN_ASIDE); ((CCSprite *)currSelectFrameSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE); ((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE); ((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE); ((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE); ((CCSprite *)currSelectRoleSpeed->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE); ((CCSprite *)currSelectRolePower->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE); ((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_ASIDE); ((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_ASIDE); ((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_ASIDE); } } } ((CCSprite *)selectRoleSpritesName->objectAtIndex((currRoleIndex + 1)%selectRoleSpritesName->count()))->setVisible(true); } void SelectRoleAndPropMenu::setCurrProp(bool _isXiangZuo) { if (_isXiangZuo) { currButtonIndex = 3; setNodeBySelectIndex(_isXiangZuo); currPropIndex++; currPropIndex = currPropIndex % selectPropSprites->count(); mAnimationManager->runAnimationsForSequenceNamed("djxiangzuo"); } else { currButtonIndex = 1; setNodeBySelectIndex(_isXiangZuo); currPropIndex--; currPropIndex = (currPropIndex + selectPropSprites->count()) % selectPropSprites->count(); mAnimationManager->runAnimationsForSequenceNamed("djxiangyou"); } } void SelectRoleAndPropMenu::checkButtonEvent(void) { if (isCheckButtonIsSelected) { if (isRolePage) { if (Global::getInstance()->isInRect( new CCRect(rolePageButton->getPositionX() + rolePageButton->getContentSize().width/2, propPageButton->getPositionY() - propPageButton->getContentSize().height*0.7/2, propPageButton->getContentSize().width*0.7, propPageButton->getContentSize().height*0.7 ), m_touchEndPos.x, 480 - m_touchEndPos.y)) { Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON); changeCurrPage(); //setPageButton(false); } } else { if (isCheckButtonIsSelected = Global::getInstance()->isInRect( new CCRect(rolePageButton->getPositionX() - rolePageButton->getContentSize().width*0.7/2, rolePageButton->getPositionY() - rolePageButton->getContentSize().height*0.7/2, propPageButton->getPositionX() - (rolePageButton->getPositionX() - rolePageButton->getContentSize().width*0.7/2), rolePageButton->getContentSize().height*0.7 ), m_touchEndPos.x, 480 - m_touchEndPos.y)) { Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON); changeCurrPage(); //setPageButton(true); } } } } void SelectRoleAndPropMenu::setPageButton(bool _isRolePage) { isRolePage = _isRolePage; if (_isRolePage) { rolePageButton->setPosition(ccp(97,41)); rolePageButton->setScale(1); rolePageButton->setZOrder(SELECTROLEANDPROPMENU_BUTTON_SELECTED_UP); propPageButton->setPosition(ccp(204,28)); propPageButton->setScale(0.7); propPageButton->setZOrder(SELECTROLEANDPROPMENU_BUTTON_UNSELECTED_DOWN); for (int i = 0 ; i < 4; i++) { ((CCSprite *)currSelectYunSprites->objectAtIndex(i))->setVisible(true); ((CCSprite *)currSelectFrameSprites->objectAtIndex(i))->setVisible(true); ((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i))->setVisible(true); ((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i))->setVisible(true); ((CCSprite *)currSelectRoleSpeed->objectAtIndex(i))->setVisible(true); ((CCSprite *)currSelectRolePower->objectAtIndex(i))->setVisible(true); ((CCSprite *)currSelectPropName->objectAtIndex(i))->setVisible(false); ((CCLabelAtlas *)currSelectPropPrice->objectAtIndex(i))->setVisible(false); ((CCSprite *)currSelectPropFrameSprites->objectAtIndex(i))->setVisible(false); ((CCMenuItemImage *)currSelectButtonBuySprites->objectAtIndex(i))->setVisible(false); } for (int i =0; i < pointRoleSprites->count(); i++) { ((CCSprite *)pointRoleSprites->objectAtIndex(i))->setVisible(true); } for (int i =0; i < pointPropSprites->count(); i++) { ((CCSprite *)pointPropSprites->objectAtIndex(i))->setVisible(false); } coupletAbout->setVisible(false); coupletSelect->setVisible(false); isFristRolePage = true; setNodeBySelectIndex(true); } else { rolePageButton->setPosition(ccp(71,28)); rolePageButton->setScale(0.7); rolePageButton->setZOrder(SELECTROLEANDPROPMENU_BUTTON_UNSELECTED_DOWN); propPageButton->setPosition(ccp(182,41)); propPageButton->setScale(1); propPageButton->setZOrder(SELECTROLEANDPROPMENU_BUTTON_SELECTED_UP); for (int i = 0 ; i < 4; i++) { ((CCSprite *)currSelectYunSprites->objectAtIndex(i))->setVisible(false); ((CCSprite *)currSelectFrameSprites->objectAtIndex(i))->setVisible(false); ((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i))->setVisible(false); ((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i))->setVisible(false); ((CCSprite *)currSelectRoleSpeed->objectAtIndex(i))->setVisible(false); ((CCSprite *)currSelectRolePower->objectAtIndex(i))->setVisible(false); ((CCSprite *)currSelectPropName->objectAtIndex(i))->setVisible(true); ((CCLabelAtlas *)currSelectPropPrice->objectAtIndex(i))->setVisible(true); ((CCSprite *)currSelectPropFrameSprites->objectAtIndex(i))->setVisible(true); ((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setVisible(false); ((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setVisible(false); ((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setVisible(false); ((CCMenuItemImage *)currSelectButtonBuySprites->objectAtIndex(i))->setVisible(true); } for (int i =0; i < pointRoleSprites->count(); i++) { ((CCSprite *)pointRoleSprites->objectAtIndex(i))->setVisible(false); } for (int i =0; i < pointPropSprites->count(); i++) { ((CCSprite *)pointPropSprites->objectAtIndex(i))->setVisible(true); } isFristPropPage = true; coupletAbout->setVisible(false); coupletSelect->setVisible(false); setNodeBySelectIndex(true); } getChildByTag(999)->setZOrder(100); } void SelectRoleAndPropMenu::doAnimationCompleted(void) { if (strcmp(mAnimationManager->getLastCompletedSequenceName().c_str(),"rwxiaoshi") == 0) { setPageButton(false); mAnimationManager->runAnimationsForSequenceNamed("daojuchuxian"); } else if (strcmp(mAnimationManager->getLastCompletedSequenceName().c_str(),"daojuxiaoshi") == 0) { setPageButton(true); mAnimationManager->runAnimationsForSequenceNamed("renwuchuxian2"); ((CCSprite *)selectRoleSpritesName->objectAtIndex((currRoleIndex + 1)%selectRoleSpritesName->count()))->setVisible(true); } } void SelectRoleAndPropMenu::reBack(int _type, bool _b) { setBackGround(false); // type是值回来前调用界面的类型 这里没必要区分 只是购买才需要处理 if(_b) { int index = currSelectSprites->indexOfObject(selectRoleSprites->objectAtIndex((currRoleIndex + 1) % selectRoleSprites->count())); if(CC_INVALID_INDEX != index) { ((CCSprite *)currSelectGetSelectSprites->objectAtIndex(index))->setVisible(false); ((CCSprite *)currSelectButtonSelectSprites->objectAtIndex(index))->setVisible(true); } index = (currRoleIndex + 1) % selectRoleSprites->count(); CCInteger * p = CCInteger::create(1); selectRoleSpritesIsHaving->addObject(p); selectRoleSpritesIsHaving->exchangeObjectAtIndex(selectRoleSpritesIsHaving->count()-1, index); selectRoleSpritesIsHaving->removeLastObject(); char _s[32]; sprintf(_s, "%d",Player::getInstance()->getPropNum(PROP_TYPE_INGOT)); removeChild(ingotNum); ingotNum = CCLabelAtlas::create(_s, "xuanren/yuanbaoshuzi.png", 18, 26, '0'); CC_SAFE_RETAIN(ingotNum); addChild(ingotNum, 998); } } void SelectRoleAndPropMenu::initSprites(void) { // 人物界面 // 龙女 if (Player::getInstance()->getRoleHavingStatusByRoleId(ROLE_TYPE_XIAOLONGNV)) { selectRoleSpritesIsHaving->addObject(CCInteger::create(1)); selectRoleSpritesIsOpen->addObject(CCInteger::create(1)); selectRoleSprites->addObject(CCSprite::create("xuanren/longnv1.png")); } else { selectRoleSpritesIsHaving->addObject(CCInteger::create(0)); if (Player::getInstance()->getRoleOpenStatusByRoleId(ROLE_TYPE_XIAOLONGNV)) { selectRoleSpritesIsOpen->addObject(CCInteger::create(1)); selectRoleSprites->addObject(CCSprite::create("xuanren/longnv1.png")); } else { selectRoleSpritesIsOpen->addObject(CCInteger::create(0)); selectRoleSprites->addObject(CCSprite::create("xuanren/longnv1.png")); //selectRoleSprites->addObject(CCSprite::create("xuanren/longnvhui.png")); } } selectRoleSpritesName->addObject(CCSprite::create("xuanren/longnv.png")); ((CCSprite *)selectRoleSpritesName->lastObject())->setPosition(ccp(405, 425)); ((CCSprite *)selectRoleSpritesName->lastObject())->setVisible(false); addChild((CCSprite *)selectRoleSpritesName->lastObject(), 998); // 还要初始化是否拥有对象(假的现在)是否已经开启对象 selectRoleSpritesSpeed->addObject(CCInteger::create(1)); selectRoleSpritesPower->addObject(CCInteger::create(1)); selectRoleSpritesIntroduce->addObject(CCSprite::create("xuanren/hxsh.png")); // 唐僧 selectRoleSpritesIsHaving->addObject(CCInteger::create(1)); selectRoleSpritesIsOpen->addObject(CCInteger::create(1)); selectRoleSprites->addObject(CCSprite::create("xuanren/tangseng1.png")); selectRoleSpritesName->addObject(CCSprite::create("xuanren/tangseng.png")); ((CCSprite *)selectRoleSpritesName->lastObject())->setPosition(ccp(405, 425)); ((CCSprite *)selectRoleSpritesName->lastObject())->setVisible(false); addChild((CCSprite *)selectRoleSpritesName->lastObject(), 998); // 还要初始化是否拥有对象(假的现在)是否已经开启对象 selectRoleSpritesSpeed->addObject(CCInteger::create(1)); selectRoleSpritesPower->addObject(CCInteger::create(1)); selectRoleSpritesIntroduce->addObject(CCSprite::create("xuanren/dscj.png")); // 八戒 if (Player::getInstance()->getRoleHavingStatusByRoleId(ROLE_TYPE_ZHUBAJIE)) { selectRoleSpritesIsHaving->addObject(CCInteger::create(1)); selectRoleSpritesIsOpen->addObject(CCInteger::create(1)); selectRoleSprites->addObject(CCSprite::create("xuanren/bajie1.png")); } else { selectRoleSpritesIsHaving->addObject(CCInteger::create(0)); if (Player::getInstance()->getRoleOpenStatusByRoleId(ROLE_TYPE_ZHUBAJIE)) { selectRoleSpritesIsOpen->addObject(CCInteger::create(1)); selectRoleSprites->addObject(CCSprite::create("xuanren/bajie1.png")); } else { selectRoleSpritesIsOpen->addObject(CCInteger::create(0)); selectRoleSprites->addObject(CCSprite::create("xuanren/bajie1.png")); //selectRoleSprites->addObject(CCSprite::create("xuanren/bajiehui.png")); } } selectRoleSpritesName->addObject(CCSprite::create("xuanren/bajie.png")); ((CCSprite *)selectRoleSpritesName->lastObject())->setPosition(ccp(405, 425)); ((CCSprite *)selectRoleSpritesName->lastObject())->setVisible(false); addChild((CCSprite *)selectRoleSpritesName->lastObject(), 998); // 还要初始化是否拥有对象(假的现在)是否已经开启对象 selectRoleSpritesSpeed->addObject(CCInteger::create(1)); selectRoleSpritesPower->addObject(CCInteger::create(1)); selectRoleSpritesIntroduce->addObject(CCSprite::create("xuanren/dahailaoz.png")); // 沙僧 if (Player::getInstance()->getRoleHavingStatusByRoleId(ROLE_TYPE_SHAHESHANG)) { selectRoleSpritesIsHaving->addObject(CCInteger::create(1)); selectRoleSpritesIsOpen->addObject(CCInteger::create(1)); selectRoleSprites->addObject(CCSprite::create("xuanren/shaseng1.png")); } else { selectRoleSpritesIsHaving->addObject(CCInteger::create(0)); if (Player::getInstance()->getRoleOpenStatusByRoleId(ROLE_TYPE_SHAHESHANG)) { selectRoleSpritesIsOpen->addObject(CCInteger::create(1)); selectRoleSprites->addObject(CCSprite::create("xuanren/shaseng1.png")); } else { selectRoleSpritesIsOpen->addObject(CCInteger::create(0)); selectRoleSprites->addObject(CCSprite::create("xuanren/shaseng1.png")); //selectRoleSprites->addObject(CCSprite::create("xuanren/shasenghui.png")); } } selectRoleSpritesName->addObject(CCSprite::create("xuanren/shaseng.png")); ((CCSprite *)selectRoleSpritesName->lastObject())->setPosition(ccp(405, 425)); ((CCSprite *)selectRoleSpritesName->lastObject())->setVisible(false); addChild((CCSprite *)selectRoleSpritesName->lastObject(), 998); // 还要初始化是否拥有对象(假的现在)是否已经开启对象 selectRoleSpritesSpeed->addObject(CCInteger::create(1)); selectRoleSpritesPower->addObject(CCInteger::create(1)); selectRoleSpritesIntroduce->addObject(CCSprite::create("xuanren/jjdj.png")); // 悟空 if (Player::getInstance()->getRoleHavingStatusByRoleId(ROLE_TYPE_SUNWUKONG)) { selectRoleSpritesIsHaving->addObject(CCInteger::create(1)); selectRoleSpritesIsOpen->addObject(CCInteger::create(1)); selectRoleSprites->addObject(CCSprite::create("xuanren/wukong1.png")); } else { selectRoleSpritesIsHaving->addObject(CCInteger::create(0)); if (Player::getInstance()->getRoleOpenStatusByRoleId(ROLE_TYPE_SUNWUKONG)) { selectRoleSpritesIsOpen->addObject(CCInteger::create(1)); selectRoleSprites->addObject(CCSprite::create("xuanren/wukong1.png")); } else { selectRoleSpritesIsOpen->addObject(CCInteger::create(0)); selectRoleSprites->addObject(CCSprite::create("xuanren/wukong1.png")); //selectRoleSprites->addObject(CCSprite::create("xuanren/wukonghui.png")); } } selectRoleSpritesName->addObject(CCSprite::create("xuanren/wukong.png")); ((CCSprite *)selectRoleSpritesName->lastObject())->setPosition(ccp(405, 425)); ((CCSprite *)selectRoleSpritesName->lastObject())->setVisible(false); addChild((CCSprite *)selectRoleSpritesName->lastObject(), 998); // 还要初始化是否拥有对象(假的现在)是否已经开启对象 selectRoleSpritesSpeed->addObject(CCInteger::create(1)); selectRoleSpritesPower->addObject(CCInteger::create(1)); selectRoleSpritesIntroduce->addObject(CCSprite::create("xuanren/sjjz.png")); // 添加任务点点 for (int i = 0; i < 5; i++) { pointRoleSprites->addObject(CCSprite::create("xuandaguan/dian2.png")); ((CCSprite *)pointRoleSprites->lastObject())->setPosition(ccp(400 - 5*SELECTROLEANDPROPMENU_POINT_X/2 + i*SELECTROLEANDPROPMENU_POINT_X + SELECTROLEANDPROPMENU_POINT_X/2, SELECTROLEANDPROPMENU_POINT_Y)); addChild((CCSprite *)pointRoleSprites->lastObject()); } // 道具界面 当界面选项不足所需的4个时候 要添加一个循环 char _s[32]; propControl = new Prop(); selectPropSprites->addObject(CCSprite::create("xuanren/sl.png")); selectPropName->addObject(CCSprite::create("xuanren/sl1.png")); sprintf(_s, "%d",propControl->getPrice(PROP_TYPE_MOONLIGHT)); selectPropPrice->addObject(CCLabelAtlas::create(_s, "xuanren/yuanbaoshuzi.png", 18, 26, '0')); selectPropId->addObject(CCInteger::create(PROP_TYPE_MOONLIGHT)); selectPropIntroduce->addObject(CCSprite::create("xuanren/sl2.png")); selectPropSprites->addObject(CCSprite::create("xuanren/zd.png")); selectPropName->addObject(CCSprite::create("xuanren/zhadan.png")); sprintf(_s, "%d",propControl->getPrice(PROP_TYPE_GRENADE)); selectPropPrice->addObject(CCLabelAtlas::create(_s, "xuanren/yuanbaoshuzi.png", 18, 26, '0')); selectPropId->addObject(CCInteger::create(PROP_TYPE_GRENADE)); selectPropIntroduce->addObject(CCSprite::create("xuanren/zd1.png")); selectPropSprites->addObject(CCSprite::create("xuanren/llys.png")); selectPropName->addObject(CCSprite::create("xuanren/llys1.png")); sprintf(_s, "%d",propControl->getPrice(PROP_TYPE_VIGOROUSLY_PILL)); selectPropPrice->addObject(CCLabelAtlas::create(_s, "xuanren/yuanbaoshuzi.png", 18, 26, '0')); selectPropId->addObject(CCInteger::create(PROP_TYPE_VIGOROUSLY_PILL)); selectPropIntroduce->addObject(CCSprite::create("xuanren/dlys2.png")); selectPropSprites->addObject(CCSprite::create("xuanren/miaozhunjing.png")); selectPropName->addObject(CCSprite::create("xuanren/miaozhunjing2.png")); sprintf(_s, "%d",propControl->getPrice(PROP_TYPE_ALIGNMENT)); selectPropPrice->addObject(CCLabelAtlas::create(_s, "xuanren/yuanbaoshuzi.png", 18, 26, '0')); selectPropId->addObject(CCInteger::create(PROP_TYPE_ALIGNMENT)); selectPropIntroduce->addObject(CCSprite::create("xuanren/miaozhunjing1.png")); //selectPropSprites->addObject(CCSprite::create("xuanren/sl.png")); //selectPropName->addObject(CCSprite::create("xuanren/sl1.png")); //sprintf(_s, "%d",propControl->getPrice(PROP_TYPE_MOONLIGHT)); //selectPropPrice->addObject(CCLabelAtlas::create(_s, "xuanren/yuanbaoshuzi.png", 18, 26, '0')); //selectPropId->addObject(CCInteger::create(PROP_TYPE_MOONLIGHT)); //selectPropIntroduce->addObject(CCSprite::create("xuanren/sl2.png")); //selectPropSprites->addObject(CCSprite::create("xuanren/zd.png")); //selectPropName->addObject(CCSprite::create("xuanren/zhadan.png")); //sprintf(_s, "%d",propControl->getPrice(PROP_TYPE_GRENADE)); //selectPropPrice->addObject(CCLabelAtlas::create(_s, "xuanren/yuanbaoshuzi.png", 18, 26, '0')); //selectPropId->addObject(CCInteger::create(PROP_TYPE_GRENADE)); //selectPropIntroduce->addObject(CCSprite::create("xuanren/zd1.png")); //selectPropSprites->addObject(CCSprite::create("xuanren/llys.png")); //selectPropName->addObject(CCSprite::create("xuanren/llys1.png")); //sprintf(_s, "%d",propControl->getPrice(PROP_TYPE_VIGOROUSLY_PILL)); //selectPropPrice->addObject(CCLabelAtlas::create(_s, "xuanren/yuanbaoshuzi.png", 18, 26, '0')); //selectPropId->addObject(CCInteger::create(PROP_TYPE_VIGOROUSLY_PILL)); //selectPropIntroduce->addObject(CCSprite::create("xuanren/sl2.png")); // 添加道具点点 for (int i = 0; i < 4; i++) { pointPropSprites->addObject(CCSprite::create("xuandaguan/dian2.png")); ((CCSprite *)pointPropSprites->lastObject())->setPosition(ccp(400 - 3*SELECTROLEANDPROPMENU_POINT_X/2 + i*SELECTROLEANDPROPMENU_POINT_X + SELECTROLEANDPROPMENU_POINT_X/2, SELECTROLEANDPROPMENU_POINT_Y)); addChild((CCSprite *)pointPropSprites->lastObject()); } // 亮点点 pointIndexSprite = CCSprite::create("xuandaguan/dian1.png"); pointIndexSprite->retain(); addChild(pointIndexSprite,998); currSelectButtonSelectSprites->addObject(getChildByTag(999)->getChildByTag(41)); currSelectButtonSelectSprites->addObject(getChildByTag(999)->getChildByTag(42)); currSelectButtonSelectSprites->addObject(getChildByTag(999)->getChildByTag(43)); currSelectButtonSelectSprites->addObject(getChildByTag(999)->getChildByTag(44)); currSelectAboutSelectSprites->addObject(getChildByTag(999)->getChildByTag(11)); currSelectAboutSelectSprites->addObject(getChildByTag(999)->getChildByTag(12)); currSelectAboutSelectSprites->addObject(getChildByTag(999)->getChildByTag(13)); currSelectAboutSelectSprites->addObject(getChildByTag(999)->getChildByTag(14)); currSelectGetSelectSprites->addObject(getChildByTag(999)->getChildByTag(31)); currSelectGetSelectSprites->addObject(getChildByTag(999)->getChildByTag(32)); currSelectGetSelectSprites->addObject(getChildByTag(999)->getChildByTag(33)); currSelectGetSelectSprites->addObject(getChildByTag(999)->getChildByTag(34)); currSelectButtonBuySprites->addObject(getChildByTag(999)->getChildByTag(21)); currSelectButtonBuySprites->addObject(getChildByTag(999)->getChildByTag(22)); currSelectButtonBuySprites->addObject(getChildByTag(999)->getChildByTag(23)); currSelectButtonBuySprites->addObject(getChildByTag(999)->getChildByTag(24)); for (int i = 0; i< 4; i++) { currSelectYunSprites->addObject(CCSprite::create("xuanren/yun.png")); addChild((CCSprite *)currSelectYunSprites->objectAtIndex(i)); currSelectFrameSprites->addObject(CCSprite::create("xuanren/jieshao.png")); addChild((CCSprite *)currSelectFrameSprites->objectAtIndex(i)); currSelectRoleSpeedBackground->addObject(CCSprite::create("xuanren/hui.png")); addChild((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i)); currSelectRolePowerBackground->addObject(CCSprite::create("xuanren/hui.png")); addChild((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i)); currSelectRoleSpeed->addObject(CCSprite::create("xuanren/lan.png")); addChild((CCSprite *)currSelectRoleSpeed->objectAtIndex(i)); currSelectRolePower->addObject(CCSprite::create("xuanren/hong.png")); addChild((CCSprite *)currSelectRolePower->objectAtIndex(i)); //addChild((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i)); //addChild((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i)); //addChild((CCMenuItemImage *)currSelectButtonBuySprites->objectAtIndex(i)); currSelectPropName->addObject((CCSprite *)selectPropName->objectAtIndex(i)); currSelectPropPrice->addObject((CCSprite *)selectPropPrice->objectAtIndex(i)); currSelectSprites->addObject(selectRoleSprites->objectAtIndex((i + currRoleIndex) % selectRoleSprites->count())); currSelectSpritesIntroduce->addObject(selectRoleSpritesIntroduce->objectAtIndex((i + currRoleIndex) % selectRoleSprites->count())); currSelectPropFrameSprites->addObject(CCSprite::create("xuanren/daojukuang.png")); getChildByTag(i+1)->addChild((CCSprite *)currSelectSprites->objectAtIndex(i)); addChild((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i)); addChild((CCSprite *)currSelectPropPrice->objectAtIndex(i)); addChild((CCSprite *)currSelectPropName->objectAtIndex(i)); ((CCSprite *)currSelectPropName->objectAtIndex(i))->setVisible(false); getChildByTag(i+1)->addChild((CCSprite *)currSelectPropFrameSprites->objectAtIndex(i)); //if (i % 2 == 0) //{ // ((CCSprite *)currSelectSprites->objectAtIndex(i))->setColor(myGrey); //} } } void SelectRoleAndPropMenu::setNodeBySelectIndex(bool _isXiangZuo) { if (isRolePage) { for (int i = 4; i > 0; i--) {// 移除node中的ccSprite getChildByTag(i)->removeChild((CCSprite *)currSelectSprites->lastObject()); removeChild((CCSprite *)currSelectSpritesIntroduce->lastObject(),true); currSelectSprites->removeLastObject(); currSelectSpritesIntroduce->removeLastObject(); } for (int i = 0; i< 4; i++) { // 按钮显示相关 if (((CCInteger *)selectRoleSpritesIsHaving->objectAtIndex((i + currRoleIndex) % selectRoleSprites->count()))->getValue() == 1) { // 拥有人物 ((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setVisible(true); ((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setVisible(false); ((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setVisible(false); } else { // 没有拥有人物 if (((CCInteger *)selectRoleSpritesIsOpen->objectAtIndex((i + currRoleIndex) % selectRoleSprites->count()))->getValue() == 1) {// 可以购买人物 ((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setVisible(false); ((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setVisible(true); ((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setVisible(false); } else {// 不能购买人物 只能看介绍 ((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setVisible(false); ((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setVisible(false); ((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setVisible(true); } } // 属性显示相关 if (_isXiangZuo) { currSelectSprites->addObject(selectRoleSprites->objectAtIndex((i + currRoleIndex) % selectRoleSprites->count())); currSelectSpritesIntroduce->addObject(selectRoleSpritesIntroduce->objectAtIndex((i + currRoleIndex) % selectRoleSprites->count())); } else { if (i == 3) { currSelectSprites->addObject(selectRoleSprites->objectAtIndex((selectRoleSprites->count() - 1 + currRoleIndex) % selectRoleSprites->count())); currSelectSpritesIntroduce->addObject(selectRoleSpritesIntroduce->objectAtIndex((selectRoleSprites->count() - 1 + currRoleIndex) % selectRoleSprites->count())); } else { currSelectSprites->addObject(selectRoleSprites->objectAtIndex((i + currRoleIndex) % selectRoleSprites->count())); currSelectSpritesIntroduce->addObject(selectRoleSpritesIntroduce->objectAtIndex((i + currRoleIndex) % selectRoleSprites->count())); } } getChildByTag(i+1)->addChild((CCSprite *)currSelectSprites->objectAtIndex(i)); addChild((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i)); if (isFristRolePage) { if (i % 2 == 0) { ((CCSprite *)currSelectSprites->objectAtIndex(i))->setColor(myGrey); ((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setColor(myGrey); ((CCSprite *)currSelectYunSprites->objectAtIndex(i))->setColor(myGrey); ((CCSprite *)currSelectFrameSprites->objectAtIndex(i))->setColor(myGrey); ((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setColor(myGrey); ((CCSprite *)currSelectRoleSpeed->objectAtIndex(i))->setColor(myGrey); ((CCSprite *)currSelectRolePower->objectAtIndex(i))->setColor(myGrey); ((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i))->setColor(myGrey); ((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i))->setColor(myGrey); ((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setColor(myGrey); ((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setColor(myGrey); ((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setColor(myGrey); } else { ((CCSprite *)currSelectSprites->objectAtIndex(i))->setColor(ccWHITE); ((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setColor(ccWHITE); ((CCSprite *)currSelectYunSprites->objectAtIndex(i))->setColor(ccWHITE); ((CCSprite *)currSelectFrameSprites->objectAtIndex(i))->setColor(ccWHITE); ((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setColor(ccWHITE); ((CCSprite *)currSelectRoleSpeed->objectAtIndex(i))->setColor(ccWHITE); ((CCSprite *)currSelectRolePower->objectAtIndex(i))->setColor(ccWHITE); ((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i))->setColor(ccWHITE); ((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i))->setColor(ccWHITE); ((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setColor(ccWHITE); ((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setColor(ccWHITE); ((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setColor(ccWHITE); } if (i == 1) { currButtonIndex = 2; ((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_YUN_MIDDLE); ((CCSprite *)currSelectYunSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_YUN_MIDDLE); ((CCSprite *)currSelectFrameSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE); ((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE); ((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE); ((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE); ((CCSprite *)currSelectRoleSpeed->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE); ((CCSprite *)currSelectRolePower->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_MIDDLE); ((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_MIDDLE); ((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_MIDDLE); ((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_MIDDLE); } else { ((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_YUN_ASIDE); ((CCSprite *)currSelectYunSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_YUN_ASIDE); ((CCSprite *)currSelectFrameSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE); ((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE); ((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE); ((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE); ((CCSprite *)currSelectRoleSpeed->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE); ((CCSprite *)currSelectRolePower->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_FRAME_ASIDE); ((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_ASIDE); ((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_ASIDE); ((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setZOrder(SELECTROLEANDPROPMENU_BUTTON_ASIDE); } } else { if (i % 2 == 1) { ((CCSprite *)currSelectSprites->objectAtIndex(i))->setColor(myGrey); ((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setColor(myGrey); ((CCSprite *)currSelectYunSprites->objectAtIndex(i))->setColor(myGrey); ((CCSprite *)currSelectFrameSprites->objectAtIndex(i))->setColor(myGrey); ((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setColor(myGrey); ((CCSprite *)currSelectRoleSpeed->objectAtIndex(i))->setColor(myGrey); ((CCSprite *)currSelectRolePower->objectAtIndex(i))->setColor(myGrey); ((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i))->setColor(myGrey); ((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i))->setColor(myGrey); ((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setColor(myGrey); ((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setColor(myGrey); ((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setColor(myGrey); } else { ((CCSprite *)currSelectSprites->objectAtIndex(i))->setColor(ccWHITE); ((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setColor(ccWHITE); ((CCSprite *)currSelectYunSprites->objectAtIndex(i))->setColor(ccWHITE); ((CCSprite *)currSelectFrameSprites->objectAtIndex(i))->setColor(ccWHITE); ((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setColor(ccWHITE); ((CCSprite *)currSelectRoleSpeed->objectAtIndex(i))->setColor(ccWHITE); ((CCSprite *)currSelectRolePower->objectAtIndex(i))->setColor(ccWHITE); ((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i))->setColor(ccWHITE); ((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i))->setColor(ccWHITE); ((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setColor(ccWHITE); ((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setColor(ccWHITE); ((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setColor(ccWHITE); } } } if (isFristRolePage) { isFristRolePage = false; } for (int i = 0; i < selectRoleSpritesName->count(); i++) { ((CCSprite *)selectRoleSpritesName->objectAtIndex(i))->setVisible(false); } getChildByTag(999)->setZOrder(100); } else { for (int i = 4; i > 0; i--) {// 移除node中的ccSprite getChildByTag(i)->removeChild((CCSprite *)currSelectSprites->lastObject()); currSelectSprites->removeLastObject(); removeChild((CCSprite *)currSelectSpritesIntroduce->lastObject(),true); currSelectSpritesIntroduce->removeLastObject(); removeChild((CCLabelAtlas *)currSelectPropPrice->lastObject(),true); currSelectPropPrice->removeLastObject(); removeChild((CCSprite *)currSelectPropName->lastObject(),true); currSelectPropName->removeLastObject(); } for (int i = 0; i< 4; i++) { if (_isXiangZuo) { currSelectSprites->addObject(selectPropSprites->objectAtIndex((i + currPropIndex) % selectPropSprites->count())); currSelectSpritesIntroduce->addObject(selectPropIntroduce->objectAtIndex((i + currPropIndex) % selectPropSprites->count())); currSelectPropPrice->addObject(selectPropPrice->objectAtIndex((i + currPropIndex) % selectPropSprites->count())); currSelectPropName->addObject(selectPropName->objectAtIndex((i + currPropIndex) % selectPropSprites->count())); } else { if (i == 3) { currSelectSprites->addObject(selectPropSprites->objectAtIndex((selectPropSprites->count() - 1 + currPropIndex) % selectPropSprites->count())); currSelectSpritesIntroduce->addObject(selectPropIntroduce->objectAtIndex((selectPropSprites->count() - 1 + currPropIndex) % selectPropSprites->count())); currSelectPropPrice->addObject(selectPropPrice->objectAtIndex((selectPropSprites->count() - 1 + currPropIndex) % selectPropSprites->count())); currSelectPropName->addObject(selectPropName->objectAtIndex((selectPropSprites->count() - 1 + currPropIndex) % selectPropSprites->count())); } else { currSelectSprites->addObject(selectPropSprites->objectAtIndex((i + currPropIndex) % selectPropSprites->count())); currSelectSpritesIntroduce->addObject(selectPropIntroduce->objectAtIndex((i + currPropIndex) % selectPropSprites->count())); currSelectPropPrice->addObject(selectPropPrice->objectAtIndex((i + currPropIndex) % selectPropSprites->count())); currSelectPropName->addObject(selectPropName->objectAtIndex((i + currPropIndex) % selectPropSprites->count())); } } getChildByTag(i+1)->addChild((CCSprite *)currSelectSprites->objectAtIndex(i)); addChild((CCLabelAtlas *)currSelectPropPrice->objectAtIndex(i)); addChild((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i)); addChild((CCSprite *)currSelectPropName->objectAtIndex(i)); if (isFristPropPage) { currButtonIndex = 2; if (i % 2 == 0) { ((CCSprite *)currSelectSprites->objectAtIndex(i))->setColor(myGrey); ((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setColor(myGrey); ((CCLabelAtlas *)currSelectPropPrice->objectAtIndex(i))->setColor(myGrey); ((CCSprite *)currSelectPropName->objectAtIndex(i))->setColor(myGrey); ((CCSprite *)currSelectPropFrameSprites->objectAtIndex(i))->setColor(myGrey); ((CCMenuItemImage *)currSelectButtonBuySprites->objectAtIndex(i))->setColor(myGrey); } else { ((CCSprite *)currSelectSprites->objectAtIndex(i))->setColor(ccWHITE); ((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setColor(ccWHITE); ((CCLabelAtlas *)currSelectPropPrice->objectAtIndex(i))->setColor(ccWHITE); ((CCSprite *)currSelectPropName->objectAtIndex(i))->setColor(ccWHITE); ((CCSprite *)currSelectPropFrameSprites->objectAtIndex(i))->setColor(ccWHITE); ((CCMenuItemImage *)currSelectButtonBuySprites->objectAtIndex(i))->setColor(ccWHITE); } } else { if (i % 2 == 1) { ((CCSprite *)currSelectSprites->objectAtIndex(i))->setColor(myGrey); ((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setColor(myGrey); ((CCLabelAtlas *)currSelectPropPrice->objectAtIndex(i))->setColor(myGrey); ((CCSprite *)currSelectPropName->objectAtIndex(i))->setColor(myGrey); ((CCSprite *)currSelectPropFrameSprites->objectAtIndex(i))->setColor(myGrey); ((CCMenuItemImage *)currSelectButtonBuySprites->objectAtIndex(i))->setColor(myGrey); } else { ((CCSprite *)currSelectSprites->objectAtIndex(i))->setColor(ccWHITE); ((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setColor(ccWHITE); ((CCLabelAtlas *)currSelectPropPrice->objectAtIndex(i))->setColor(ccWHITE); ((CCSprite *)currSelectPropName->objectAtIndex(i))->setColor(ccWHITE); ((CCSprite *)currSelectPropFrameSprites->objectAtIndex(i))->setColor(ccWHITE); ((CCMenuItemImage *)currSelectButtonBuySprites->objectAtIndex(i))->setColor(ccWHITE); } } } if (isFristPropPage) { isFristPropPage = false; } getChildByTag(999)->setZOrder(100); } } void SelectRoleAndPropMenu::menuSelect1Callback(CCObject* pSender) { if (isBackGround) { return; } Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON); if (currButtonIndex == 1) { int _tmpIndex = currSelectSprites->indexOfObject(selectRoleSprites->objectAtIndex(Global::getInstance()->getSelectRoleId())); if (_tmpIndex != CC_INVALID_INDEX) { ((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(_tmpIndex))->setVisible(true); } Global::getInstance()->setSelectRoleId((currRoleIndex + 1) % selectRoleSprites->count()); } } void SelectRoleAndPropMenu::menuSelect2Callback(CCObject* pSender) { if (isBackGround) { return; } Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON); if (currButtonIndex == 2) { int _tmpIndex = currSelectSprites->indexOfObject(selectRoleSprites->objectAtIndex(Global::getInstance()->getSelectRoleId())); if (_tmpIndex != CC_INVALID_INDEX) { ((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(_tmpIndex))->setVisible(true); } Global::getInstance()->setSelectRoleId((currRoleIndex + 1) % selectRoleSprites->count()); } } void SelectRoleAndPropMenu::menuSelect3Callback(CCObject* pSender) { if (isBackGround) { return; } Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON); if (currButtonIndex == 3) { int _tmpIndex = currSelectSprites->indexOfObject(selectRoleSprites->objectAtIndex(Global::getInstance()->getSelectRoleId())); if (_tmpIndex != CC_INVALID_INDEX) { ((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(_tmpIndex))->setVisible(true); } Global::getInstance()->setSelectRoleId((currRoleIndex + 1) % selectRoleSprites->count()); } } void SelectRoleAndPropMenu::menuSelect4Callback(CCObject* pSender) { if (isBackGround) { return; } Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON); if (currButtonIndex == 4) { int _tmpIndex = currSelectSprites->indexOfObject(selectRoleSprites->objectAtIndex(Global::getInstance()->getSelectRoleId())); if (_tmpIndex != CC_INVALID_INDEX) { ((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(_tmpIndex))->setVisible(true); } Global::getInstance()->setSelectRoleId((currRoleIndex + 1) % selectRoleSprites->count()); } } void SelectRoleAndPropMenu::menuGet1Callback(CCObject* pSender) { if (isBackGround) { return; } Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON); if (currButtonIndex == 1) { // 购买人物 RoleInformation * information = (RoleInformation *)Global::getInstance()->s->getRoleInformation(this); setBackGround(true); Global::getInstance()->s->addLayerToRunningScene(information); information->getRoleGetInfromationByRoleId((currRoleIndex + 1) % selectRoleSprites->count()); } } void SelectRoleAndPropMenu::menuGet2Callback(CCObject* pSender) { if (isBackGround) { return; } Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON); if (currButtonIndex == 2) { // 购买人物 RoleInformation * information = (RoleInformation *)Global::getInstance()->s->getRoleInformation(this); setBackGround(true); Global::getInstance()->s->addLayerToRunningScene(information); information->getRoleGetInfromationByRoleId((currRoleIndex + 1) % selectRoleSprites->count()); } } void SelectRoleAndPropMenu::menuGet3Callback(CCObject* pSender) { if (isBackGround) { return; } Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON); if (currButtonIndex == 3) { // 购买人物 RoleInformation * information = (RoleInformation *)Global::getInstance()->s->getRoleInformation(this); setBackGround(true); Global::getInstance()->s->addLayerToRunningScene(information); information->getRoleGetInfromationByRoleId((currRoleIndex + 1) % selectRoleSprites->count()); } } void SelectRoleAndPropMenu::menuGet4Callback(CCObject* pSender) { if (isBackGround) { return; } Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON); if (currButtonIndex == 4) { // 购买人物 RoleInformation * information = (RoleInformation *)Global::getInstance()->s->getRoleInformation(this); setBackGround(true); Global::getInstance()->s->addLayerToRunningScene(information); information->getRoleGetInfromationByRoleId((currRoleIndex + 1) % selectRoleSprites->count()); } } void SelectRoleAndPropMenu::menuAbout1Callback(CCObject* pSender) { if (isBackGround) { return; } Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON); if (currButtonIndex == 1) { // 介绍 RoleInformation * information = (RoleInformation *)Global::getInstance()->s->getRoleInformation(this); setBackGround(true); Global::getInstance()->s->addLayerToRunningScene(information); information->getRoleAboutInfromationByRoleId((currRoleIndex + 1) % selectRoleSprites->count()); } } void SelectRoleAndPropMenu::menuAbout2Callback(CCObject* pSender) { if (isBackGround) { return; } Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON); if (currButtonIndex == 2) { // 介绍 RoleInformation * information = (RoleInformation *)Global::getInstance()->s->getRoleInformation(this); setBackGround(true); Global::getInstance()->s->addLayerToRunningScene(information); information->getRoleAboutInfromationByRoleId((currRoleIndex + 1) % selectRoleSprites->count()); } } void SelectRoleAndPropMenu::menuAbout3Callback(CCObject* pSender) { if (isBackGround) { return; } Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON); if (currButtonIndex == 3) { // 介绍 RoleInformation * information = (RoleInformation *)Global::getInstance()->s->getRoleInformation(this); setBackGround(true); Global::getInstance()->s->addLayerToRunningScene(information); information->getRoleAboutInfromationByRoleId((currRoleIndex + 1) % selectRoleSprites->count()); } } void SelectRoleAndPropMenu::menuAbout4Callback(CCObject* pSender) { if (isBackGround) { return; } Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON); if (currButtonIndex == 4) { // 介绍 RoleInformation * information = (RoleInformation *)Global::getInstance()->s->getRoleInformation(this); setBackGround(true); Global::getInstance()->s->addLayerToRunningScene(information); information->getRoleAboutInfromationByRoleId((currRoleIndex + 1) % selectRoleSprites->count()); } } void SelectRoleAndPropMenu::menuBuy1Callback(CCObject* pSender) { if (isBackGround) { return; } Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON); if (currButtonIndex == 1) { // 购买道具 int id = ((CCInteger *)selectPropId->objectAtIndex((currPropIndex + 1) % selectPropSprites->count()))->getValue(); if (id == PROP_TYPE_ALIGNMENT && (Player::getInstance()->getPropNum(PROP_TYPE_ALIGNMENT) > 0)) { // 提示已经购买了瞄准线了 (瞄准线最多1个) PromptLayer * promptLayer = (PromptLayer *)Global::getInstance()->s->getPromptLayer(this, LAYER_ID_PROP_ROLE); setBackGround(true); //promptLayer->setForwardLayer(this); Global::getInstance()->s->addLayerToRunningScene(promptLayer); promptLayer->miaoZhunXianInformation(); } else { if (Player::getInstance()->getPropNum(PROP_TYPE_INGOT) >= propControl->getPrice(id)) { Player::getInstance()->appendPropNum(PROP_TYPE_INGOT ,-propControl->getPrice(id)); Player::getInstance()->savePropNum(PROP_TYPE_INGOT ,-propControl->getPrice(id)); Player::getInstance()->appendPropNum(id ,1); Player::getInstance()->savePropNum(id ,1); char _s[32]; sprintf(_s, "%d",Player::getInstance()->getPropNum(PROP_TYPE_INGOT)); removeChild(ingotNum); ingotNum = CCLabelAtlas::create(_s, "xuanren/yuanbaoshuzi.png", 18, 26, '0'); CC_SAFE_RETAIN(ingotNum); addChild(ingotNum, 998); Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUY_FINISH); } else { // 钱不够购买 Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUY_FAILED); } } } } void SelectRoleAndPropMenu::menuBuy2Callback(CCObject* pSender) { if (isBackGround) { return; } Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON); if (currButtonIndex == 2) { // 购买道具 int id = ((CCInteger *)selectPropId->objectAtIndex((currPropIndex + 1) % selectPropSprites->count()))->getValue(); if (id == PROP_TYPE_ALIGNMENT && (Player::getInstance()->getPropNum(PROP_TYPE_ALIGNMENT) > 0)) { // 提示已经购买了瞄准线了 (瞄准线最多1个) } else { if (Player::getInstance()->getPropNum(PROP_TYPE_INGOT) >= propControl->getPrice(id)) { Player::getInstance()->appendPropNum(PROP_TYPE_INGOT ,-propControl->getPrice(id)); Player::getInstance()->savePropNum(PROP_TYPE_INGOT ,-propControl->getPrice(id)); Player::getInstance()->appendPropNum(id ,1); Player::getInstance()->savePropNum(id ,1); char _s[32]; sprintf(_s, "%d",Player::getInstance()->getPropNum(PROP_TYPE_INGOT)); removeChild(ingotNum); ingotNum = CCLabelAtlas::create(_s, "xuanren/yuanbaoshuzi.png", 18, 26, '0'); CC_SAFE_RETAIN(ingotNum); addChild(ingotNum, 998); Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUY_FINISH); } else { // 钱不够购买 Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUY_FAILED); } } } } void SelectRoleAndPropMenu::menuBuy3Callback(CCObject* pSender) { if (isBackGround) { return; } Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON); if (currButtonIndex == 3) { // 购买道具 int id = ((CCInteger *)selectPropId->objectAtIndex((currPropIndex + 1) % selectPropSprites->count()))->getValue(); if (id == PROP_TYPE_ALIGNMENT && (Player::getInstance()->getPropNum(PROP_TYPE_ALIGNMENT) > 0)) { // 提示已经购买了瞄准线了 (瞄准线最多1个) } else { if (Player::getInstance()->getPropNum(PROP_TYPE_INGOT) >= propControl->getPrice(id)) { Player::getInstance()->appendPropNum(PROP_TYPE_INGOT ,-propControl->getPrice(id)); Player::getInstance()->savePropNum(PROP_TYPE_INGOT ,-propControl->getPrice(id)); Player::getInstance()->appendPropNum(id ,1); Player::getInstance()->savePropNum(id ,1); char _s[32]; sprintf(_s, "%d",Player::getInstance()->getPropNum(PROP_TYPE_INGOT)); removeChild(ingotNum); ingotNum = CCLabelAtlas::create(_s, "xuanren/yuanbaoshuzi.png", 18, 26, '0'); CC_SAFE_RETAIN(ingotNum); addChild(ingotNum, 998); Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUY_FINISH); } else { // 钱不够购买 Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUY_FAILED); } } } } void SelectRoleAndPropMenu::menuBuy4Callback(CCObject* pSender) { if (isBackGround) { return; } Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUTTON); if (currButtonIndex == 4) { // 购买道具 int id = ((CCInteger *)selectPropId->objectAtIndex((currPropIndex + 1) % selectPropSprites->count()))->getValue(); if (id == PROP_TYPE_ALIGNMENT && (Player::getInstance()->getPropNum(PROP_TYPE_ALIGNMENT) > 0)) { // 提示已经购买了瞄准线了 (瞄准线最多1个) } else { if (Player::getInstance()->getPropNum(PROP_TYPE_INGOT) >= propControl->getPrice(id)) { Player::getInstance()->appendPropNum(PROP_TYPE_INGOT ,-propControl->getPrice(id)); Player::getInstance()->savePropNum(PROP_TYPE_INGOT ,-propControl->getPrice(id)); Player::getInstance()->appendPropNum(id ,1); Player::getInstance()->savePropNum(id ,1); char _s[32]; sprintf(_s, "%d",Player::getInstance()->getPropNum(PROP_TYPE_INGOT)); removeChild(ingotNum); ingotNum = CCLabelAtlas::create(_s, "xuanren/yuanbaoshuzi.png", 18, 26, '0'); CC_SAFE_RETAIN(ingotNum); addChild(ingotNum, 998); Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUY_FINISH); } else { // 钱不够购买 Player::getInstance()->getMusicControl()->playEffect(MUSICCONTROL_EFFECT_ID_BUY_FAILED); } } } } void SelectRoleAndPropMenu::doAction(float _f) { if (isRolePage) { for (int i = 0; i < 4; i++) { double _positionX = ((CCNode *)getChildByTag(i+1))->getPositionX(); double _positionY = ((CCNode *)getChildByTag(i+1))->getPositionY(); double _scale = ((CCNode *)getChildByTag(i+1))->getScale(); ((CCSprite *)currSelectYunSprites->objectAtIndex(i))->setPosition(ccp(_positionX+7*_scale, _positionY-124*_scale)); ((CCSprite *)currSelectFrameSprites->objectAtIndex(i))->setPosition(ccp(_positionX+237*_scale, _positionY-111*_scale)); ((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setPosition(ccp(_positionX+1*_scale, _positionY-139*_scale)); ((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setPosition(ccp(_positionX+1*_scale, _positionY-139*_scale)); ((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setPosition(ccp(_positionX+1*_scale, _positionY-139*_scale)); ((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setPosition(ccp(_positionX+233.5*_scale, _positionY-137.5*_scale)); ((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i))->setPosition(ccp(_positionX+226*_scale, _positionY-87.5*_scale)); ((CCSprite *)currSelectRoleSpeed->objectAtIndex(i))->setPosition(ccp(_positionX+226*_scale, _positionY-87.5*_scale)); ((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i))->setPosition(ccp(_positionX+233.5*_scale, _positionY-112.5*_scale)); ((CCSprite *)currSelectRolePower->objectAtIndex(i))->setPosition(ccp(_positionX+233.5*_scale, _positionY-112.5*_scale)); ((CCSprite *)currSelectYunSprites->objectAtIndex(i))->setScale(_scale); ((CCSprite *)currSelectFrameSprites->objectAtIndex(i))->setScale(_scale); ((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(i))->setScale(_scale); ((CCMenuItemImage *)currSelectGetSelectSprites->objectAtIndex(i))->setScale(_scale); ((CCMenuItemImage *)currSelectAboutSelectSprites->objectAtIndex(i))->setScale(_scale); ((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setScale(_scale); ((CCSprite *)currSelectRoleSpeedBackground->objectAtIndex(i))->setScale(_scale); ((CCSprite *)currSelectRoleSpeed->objectAtIndex(i))->setScale(_scale); ((CCSprite *)currSelectRolePowerBackground->objectAtIndex(i))->setScale(_scale); ((CCSprite *)currSelectRolePower->objectAtIndex(i))->setScale(_scale); } int _tmpIndex = currSelectSprites->indexOfObject(selectRoleSprites->objectAtIndex(Global::getInstance()->getSelectRoleId())); if (_tmpIndex != CC_INVALID_INDEX) { ((CCMenuItemImage *)currSelectButtonSelectSprites->objectAtIndex(_tmpIndex))->setVisible(false); } if (0 == ((CCInteger *)selectRoleSpritesIsOpen->objectAtIndex((currRoleIndex + 1) % selectRoleSprites->count()))->getValue()) { coupletAbout->setVisible(true); coupletSelect->setVisible(false); } else { if ((currRoleIndex + 1) % selectRoleSprites->count() == Global::getInstance()->getSelectRoleId()) { coupletAbout->setVisible(false); coupletSelect->setVisible(true); } else { coupletAbout->setVisible(false); coupletSelect->setVisible(false); } } pointIndexSprite->setPosition(((CCSprite *)pointRoleSprites->objectAtIndex(currRoleIndex%pointRoleSprites->count()))->getPosition()); } else { for (int i = 0; i < 4; i++) { double _positionX = ((CCNode *)getChildByTag(i+1))->getPositionX(); double _positionY = ((CCNode *)getChildByTag(i+1))->getPositionY(); double _scale = ((CCNode *)getChildByTag(i+1))->getScale(); ((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setPosition(ccp(_positionX-2.5*_scale, _positionY-96.5*_scale)); ((CCLabelAtlas *)currSelectPropPrice->objectAtIndex(i))->setPosition(ccp(_positionX-43.5*_scale, _positionY-38*_scale)); ((CCSprite *)currSelectPropName->objectAtIndex(i))->setPosition(ccp(_positionX+2*_scale, _positionY+30.5*_scale)); ((CCSprite *)currSelectSprites->objectAtIndex(i))->setPosition(ccp(0, 100+40*_scale)); ((CCMenuItemImage *)currSelectButtonBuySprites->objectAtIndex(i))->setPosition(ccp(_positionX-2*_scale, _positionY+ 35+ 35*_scale)); ((CCMenuItemImage *)currSelectButtonBuySprites->objectAtIndex(i))->setScale(_scale); ((CCSprite *)currSelectSpritesIntroduce->objectAtIndex(i))->setScale(_scale); ((CCLabelAtlas *)currSelectPropPrice->objectAtIndex(i))->setScale(_scale); ((CCSprite *)currSelectPropName->objectAtIndex(i))->setScale(_scale); ((CCSprite *)currSelectSprites->objectAtIndex(i))->setScale(_scale); } pointIndexSprite->setPosition(((CCSprite *)pointPropSprites->objectAtIndex(currPropIndex%pointPropSprites->count()))->getPosition()); } double _positionX = ((CCNode *)getChildByTag(10))->getPositionX(); double _positionY = ((CCNode *)getChildByTag(10))->getPositionY(); int i = 0; int length = Player::getInstance()->getPropNum(PROP_TYPE_INGOT); while(1) { length = length / 10; if (length > 0) { i++; } else { break; } } ingotNum->setPosition(ccp(_positionX - i*8, _positionY - 13)); }
[ "wjf1616@163.com" ]
wjf1616@163.com
8c01e1827671e8f5b39071e4785552c7bfa695e0
c0caed81b5b3e1498cbca4c1627513c456908e38
/src/core/scoring/methods/PoissonBoltzmannEnergy.cc
15662387c08a9b217a5d3ed6d2f661418a2dbc8c
[]
no_license
malaifa/source
5b34ac0a4e7777265b291fc824da8837ecc3ee84
fc0af245885de0fb82e0a1144422796a6674aeae
refs/heads/master
2021-01-19T22:10:22.942155
2017-04-19T14:13:07
2017-04-19T14:13:07
88,761,668
0
2
null
null
null
null
UTF-8
C++
false
false
14,744
cc
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington UW TechTransfer, email: license@u.washington.edu. /// @file core/scoring/methods/PoissonBoltzmannEnergy.cc /// @brief Ramachandran energy method class implementation /// @author Phil Bradley /// @author Andrew Leaver-Fay (aleaverfay@gmail.com) // Unit Headers #include <core/scoring/methods/PoissonBoltzmannEnergy.hh> #include <core/scoring/methods/PoissonBoltzmannEnergyCreator.hh> // Package Headers #include <core/scoring/PoissonBoltzmannPotential.hh> #include <core/scoring/EnergyMap.hh> #include <core/scoring/OneToAllEnergyContainer.hh> #include <core/scoring/Energies.hh> #include <core/scoring/methods/Methods.hh> #include <core/scoring/ScoreFunction.hh> #include <core/scoring/methods/EnergyMethodOptions.hh> // Project headers #include <core/pose/Pose.hh> #include <core/pose/PDBInfo.hh> #include <core/conformation/Residue.hh> // Utility headers #include <basic/Tracer.hh> #include <basic/datacache/CacheableData.hh> #include <basic/datacache/DataCache.hh> #include <core/pose/datacache/CacheableDataType.hh> // option #include <basic/options/option.hh> #include <basic/options/keys/pb_potential.OptionKeys.gen.hh> // numeric #include <numeric/xyzVector.hh> #include <utility/vector1.hh> static THREAD_LOCAL basic::Tracer TR( "core.scoring.methods.PoissonBoltzmannEnergy" ); namespace core { namespace scoring { namespace methods { //***************************************************************** // // PBLifetimeCache: carries cache for the entire runtime cycle. // //***************************************************************** PBLifetimeCache::PBLifetimeCache() {} PBLifetimeCache::~PBLifetimeCache() {} basic::datacache::CacheableDataOP PBLifetimeCache::clone() const { return basic::datacache::CacheableDataOP( new PBLifetimeCache(*this) ); } void PBLifetimeCache::set_charged_residues_map( const std::map<std::string, bool> & charged_residues_map ) { charged_residues_map_ = charged_residues_map; } void PBLifetimeCache::set_energy_state( const std::string& energy_state ) { energy_state_ = energy_state; } void PBLifetimeCache::set_conformational_data( const std::string& energy_state, const core::pose::Pose & pose, PoissonBoltzmannPotentialOP pbp ) { pose_by_state_[energy_state] = core::pose::PoseOP( new core::pose::Pose(pose) ); pb_by_state_[energy_state] = pbp; } std::map<std::string, bool> & PBLifetimeCache::get_charged_residues_map() { return charged_residues_map_; } const std::string & PBLifetimeCache::get_energy_state() const { return energy_state_; } core::pose::PoseCOP PBLifetimeCache::get_pose( const std::string& energy_state ) { //TR << "Looking for cached pose for state \"" << energy_state << "\" in PBLifetimeCache " << "{ "; //std::map<std::string, pose::PoseCOP>::const_iterator itr = poses_by_state_.begin(); //for(; itr != poses_by_state_.end(); ++itr ){ // TR << "(key=" << itr->first << ": val=" << itr->second->pdb_info()->name() << "), "; //} //TR << " }" << std::endl; return pose_by_state_[energy_state]; } PoissonBoltzmannPotentialOP PBLifetimeCache::get_pbp( const std::string& energy_state ) { return pb_by_state_[energy_state]; } bool PBLifetimeCache::has_cache( const std::string& energy_state ) const { return pb_by_state_.count(energy_state) && pose_by_state_.count( energy_state); } //***************************************************************** // // PoissonBoltzmannEnergyCreator // //***************************************************************** /// @details This must return a fresh instance of the PoissonBoltzmannEnergy class, /// never an instance already in use methods::EnergyMethodOP PoissonBoltzmannEnergyCreator::create_energy_method( methods::EnergyMethodOptions const & ) const { return methods::EnergyMethodOP( new PoissonBoltzmannEnergy ); } ScoreTypes PoissonBoltzmannEnergyCreator::score_types_for_method() const { ScoreTypes sts; sts.push_back( PB_elec ); return sts; } //***************************************************************** // // PoissonBoltzmannEnergy // //***************************************************************** /// ctor PoissonBoltzmannEnergy::PoissonBoltzmannEnergy() : parent( methods::EnergyMethodCreatorOP( new PoissonBoltzmannEnergyCreator ) ), fixed_residue_(1), epsilon_(2.0) //, //poisson_boltzmann_potential_( new scoring::PoissonBoltzmannPotential ) { if ( basic::options::option[basic::options::OptionKeys::pb_potential::epsilon].user() ) { epsilon_ = basic::options::option[basic::options::OptionKeys::pb_potential::epsilon]; } } /// clone EnergyMethodOP PoissonBoltzmannEnergy::clone() const { return EnergyMethodOP( new PoissonBoltzmannEnergy( *this ) ); } methods::LongRangeEnergyType PoissonBoltzmannEnergy::long_range_type() const { return methods::PB_elec_lr; } void PoissonBoltzmannEnergy::setup_for_scoring( pose::Pose & pose, ScoreFunction const & scorefxn ) const { using namespace methods; // If the cached object is not in the pose data-cache, it suggests that the setup protocol has not // been called in prior. Warn and get out! if ( ! pose.data().has( pose::datacache::CacheableDataType::PB_LIFETIME_CACHE ) ) { TR << "PB_LIFETIME_CACHE object is not initialized. Did you call SetupPoissonBoltzmannPotential mover? Terminaing the program..." << std::endl; TR.flush(); // Register the empty cache holder if not done so yet. PoissonBoltzmannEnergy::PBLifetimeCacheOP new_cache( new PoissonBoltzmannEnergy::PBLifetimeCache() ); pose.data().set( pose::datacache::CacheableDataType::PB_LIFETIME_CACHE, new_cache ); //runtime_assert(false); } PBLifetimeCacheOP cached_data = static_cast< PBLifetimeCacheOP > (pose.data().get_ptr< PBLifetimeCache >(pose::datacache::CacheableDataType::PB_LIFETIME_CACHE )); // Do we have the map of charged residues by name? charged_residues_ = cached_data->get_charged_residues_map(); if ( charged_residues_.size() == 0 ) { utility::vector1<int> charged_chains = basic::options::option[basic::options::OptionKeys::pb_potential::charged_chains]; TR << "Charged residues: [ "; for ( Size i=1; i<= pose.total_residue(); ++i ) { core::conformation::Residue const & rsd( pose.residue(i) ); bool residue_charged = false; if ( std::find(charged_chains.begin(), charged_chains.end(), (int)rsd.chain()) != charged_chains.end() ) { residue_charged = true; TR << rsd.type().name() << ","; } charged_residues_[rsd.type().name()] = residue_charged; } cached_data->set_charged_residues_map( charged_residues_ ); TR << "]" << std::endl; } core::scoring::methods::EnergyMethodOptions emoptions = scorefxn.energy_method_options(); std::string energy_state = cached_data->get_energy_state(); if ( energy_state == "" ) { energy_state = "stateless"; } TR << "Energy state: \"" << energy_state << "\" for scorefxn: " << scorefxn.get_name() << std::endl; const Size atom_index = 2; // alpha carbon // Solve PB // // use cached data if the bound comformation hasn't changed. if ( cached_data->has_cache( energy_state ) ) { core::pose::PoseCOP prev_pose = cached_data->get_pose( energy_state ); // switch to the state's pb poisson_boltzmann_potential_ = cached_data->get_pbp(energy_state); debug_assert(poisson_boltzmann_potential_ != 0); TR << "Found cached pose for state: " << energy_state << std::endl; // re-evaluate only for bound-state. if ( energy_state == emoptions.pb_bound_tag() ) { if ( !protein_position_equal_within( pose, *prev_pose, atom_index, epsilon_ ) ) { TR << "Atoms (" << atom_index << ") in charged chains moved more than " ; TR << epsilon_ << "A" << std::endl; poisson_boltzmann_potential_->solve_pb(pose, energy_state, charged_residues_); } } } else { TR << "No cached pose for state: " << energy_state << std::endl; poisson_boltzmann_potential_ = scoring::PoissonBoltzmannPotentialOP( new PoissonBoltzmannPotential() ); poisson_boltzmann_potential_->solve_pb(pose, energy_state, charged_residues_); } // Update the cache cached_data->set_conformational_data( energy_state, pose, poisson_boltzmann_potential_ ); // create LR energy container LongRangeEnergyType const & lr_type( long_range_type() ); Energies & energies( pose.energies() ); bool create_new_lre_container( false ); if ( energies.long_range_container( lr_type ) == 0 ) { create_new_lre_container = true; } else { LREnergyContainerOP lrc = energies.nonconst_long_range_container( lr_type ); OneToAllEnergyContainerOP dec( utility::pointer::static_pointer_cast< core::scoring::OneToAllEnergyContainer > ( lrc ) ); // make sure size or root did not change if ( dec->size() != pose.total_residue() ) { create_new_lre_container = true; } } if ( create_new_lre_container ) { TR << "Creating new one-to-all energy container (" << pose.total_residue() << ")" << std::endl; LREnergyContainerOP new_dec( new OneToAllEnergyContainer( fixed_residue_, pose.total_residue(), PB_elec ) ); energies.set_long_range_container( lr_type, new_dec ); } } ///////////////////////////////////////////////////////////////////////////// // methods ///////////////////////////////////////////////////////////////////////////// bool PoissonBoltzmannEnergy::defines_residue_pair_energy( pose::Pose const &, Size res1, Size res2 ) const { return ( res1 == fixed_residue_ || res2 == fixed_residue_ ); } void PoissonBoltzmannEnergy::eval_intrares_energy( conformation::Residue const &, pose::Pose const &, ScoreFunction const &, EnergyMap & ) const { return; } bool PoissonBoltzmannEnergy::residue_in_chains( conformation::Residue const & rsd, utility::vector1 <Size> chains ) const { for ( Size ichain=1; ichain<=chains.size(); ++ichain ) { if ( rsd.chain() == chains[ichain] ) return true; } return false; } Real PoissonBoltzmannEnergy::revamp_weight_by_burial( conformation::Residue const & rsd, pose::Pose const & pose ) const { utility::vector1 <Size> chains = basic::options::option[basic::options::OptionKeys::pb_potential::revamp_near_chain](); Real weight = 1.; Real neighbor_count = 0.; Real threshold = 4.; for ( Size j_res = 1; j_res <= pose.total_residue(); ++j_res ) { if ( pose.residue(j_res).is_virtual_residue() ) continue; if ( !residue_in_chains(pose.residue(j_res), chains) ) continue; bool found_neighbor = false; for ( Size i_atom = rsd.last_backbone_atom() + 1; i_atom <= rsd.nheavyatoms(); ++i_atom ) { for ( Size j_atom = 1; j_atom <= rsd.nheavyatoms(); ++j_atom ) { if ( pose.residue(j_res).is_virtual(j_atom) ) continue; Real distance = rsd.xyz(i_atom).distance(pose.residue(j_res).xyz(j_atom)); if ( distance < threshold ) { neighbor_count += 1.; found_neighbor = true; break; } } if ( found_neighbor ) break; } } if ( neighbor_count > 0 ) weight = 1./neighbor_count; //using namespace ObjexxFCL::format; //TR << "PB_weight:" << I(4,rsd.seqpos()) << F(8, 3, weight) << std::endl; return weight; } void PoissonBoltzmannEnergy::residue_pair_energy( conformation::Residue const & rsd1, conformation::Residue const & rsd2, pose::Pose const & pose, ScoreFunction const &, EnergyMap & emap ) const { //check fixed_residue_ conformation::Residue const &rsd (rsd1.seqpos() == fixed_residue_? rsd2 : rsd1 ); // If it is part of charged chain, skip. if ( const_cast<std::map<std::string, bool>&>(charged_residues_)[rsd.type().name()] ) { return; } Real PB_score_residue, PB_score_backbone, PB_score_sidechain; Real PB_burial_weight(1.0); if ( basic::options::option[basic::options::OptionKeys::pb_potential::revamp_near_chain].user() ) { PB_burial_weight = revamp_weight_by_burial(rsd, pose); } poisson_boltzmann_potential_->eval_PB_energy_residue( rsd, PB_score_residue, PB_score_backbone, PB_score_sidechain, PB_burial_weight ); if ( basic::options::option[basic::options::OptionKeys::pb_potential::sidechain_only]() ) { emap[ PB_elec ] += PB_score_sidechain; } else { emap[ PB_elec ] += PB_score_residue; } } /// @brief Energy is context independent and thus indicates that no context graphs need to /// be maintained by class Energies void PoissonBoltzmannEnergy::indicate_required_context_graphs( utility::vector1< bool > & /*context_graphs_required*/ ) const {} /// Compare if two poses are close in fold within tolerance. /// /// To be specific, it returns True if for all a in A and b in B, /// sqrt( (a.x-b.x)^2 + (a.y-b.y)^2 + (a.z-b.z)^2 ) <= tol, /// for A and B are sets of all atoms in protein 1 and protein 2, respectively. /// /// @param pose1 A protein's pose /// @param pose2 Another protein's pose /// @param atom_num The atom number /// @param tol Tolerable distance in Angstrom, >= 0.A /// bool PoissonBoltzmannEnergy::protein_position_equal_within( pose::Pose const & pose1, pose::Pose const & pose2, Size atom_num, Real tol) const { // error: reference cannot be bound to dereferenced null pointer in well-defined C++ code; comparison may be assumed to always evaluate to false [-Werror,-Wtautological-undefined-compare] //if( &pose1 == NULL || &pose2 == NULL ) { // return false; //} //if( &pose1 == NULL && &pose2 == NULL ) { // return true; //} if ( pose1.total_residue() != pose2.total_residue() ) { return false; } for ( Size i=1; i<=pose1.total_residue(); ++i ) { // Skip nonprotein pose 1. if ( !pose1.residue(i).is_protein() ) continue; // If a protein residue from pose 1 matches seqpos of a nonprotein // residue from pose 2, must be false. if ( !pose2.residue(i).is_protein() ) return false; // Nonmatching by definition. if ( pose1.residue_type(i).natoms() != pose2.residue(i).natoms() || pose1.residue_type(i).aa() != pose2.residue_type(i).aa() ) { return false; } const core::conformation::Atom atom1 = pose1.residue(i).atom(atom_num); const core::conformation::Atom atom2 = pose2.residue(i).atom(atom_num); const numeric::xyzVector<Real> xyz1 = atom1.xyz(); const numeric::xyzVector<Real> xyz2 = atom2.xyz(); const Real delta = xyz1.distance(xyz2); if ( delta > tol ) { // exceed tolerance return false; } } return true; } core::Size PoissonBoltzmannEnergy::version() const { return 1; // Initial versioning } } // methods } // scoring } // core
[ "malaifa@yahoo.com" ]
malaifa@yahoo.com
e846e6d07b6a7d776186246dccaac4c9bca34dba
cce1863b204ae1ed76f0e2b54ec8a121ee83e4dc
/VimbaCPP/Examples/AsynchronousGrab/Qt/Source/CameraObserver.h
25a9683cdf2e9535e742e52e2270af73d9830a62
[]
no_license
quminhdo/vimba
0c54366f00cd8df3139bcd7887dd6771bbdc25b4
1203f1809e00d9deab8705c5867b8425a22f6355
refs/heads/master
2023-05-08T04:46:46.626769
2021-06-01T15:54:52
2021-06-01T15:54:52
367,311,686
0
0
null
null
null
null
UTF-8
C++
false
false
2,441
h
/*============================================================================= Copyright (C) 2012 - 2016 Allied Vision Technologies. All Rights Reserved. Redistribution of this file, in original or modified form, without prior written consent of Allied Vision Technologies is prohibited. ------------------------------------------------------------------------------- File: CameraObserver.h Description: The camera observer that is used for notifications from VimbaCPP regarding a change in the camera list. ------------------------------------------------------------------------------- THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =============================================================================*/ #ifndef AVT_VMBAPI_EXAMPLES_CAMERAOBSERVER #define AVT_VMBAPI_EXAMPLES_CAMERAOBSERVER #include <QObject> #include <VimbaCPP/Include/VimbaCPP.h> namespace AVT { namespace VmbAPI { namespace Examples { class CameraObserver : public QObject, public ICameraListObserver { Q_OBJECT public: // // This is our callback routine that will be executed every time a camera was plugged in or out // // Parameters: // [in] pCam The camera that triggered the callback // [in] reason The reason why the callback was triggered // virtual void CameraListChanged( CameraPtr pCamera, UpdateTriggerType reason ); signals: // // The camera list changed event (Qt signal) that notifies about a camera change and its reason // // Parameters: // [out] reason The reason why this event was fired // void CameraListChangedSignal( int reason ); }; }}} // namespace AVT::VmbAPI::Examples #endif
[ "quminh.do@gmail.com" ]
quminh.do@gmail.com
a296999c64bf652921262eb489da31bc1af5b18d
ce98a778117849e0c177c5c4e1dba55d83c01d43
/src/OpenGL.h
0c644175ce17cba7488b1212157f8fcbe42bfac7
[]
no_license
swarzzy/sokoban
a965027a5362eed27fcdeabf9c55664a9d1c0dca
f61ef59d364e7565db0749e04aed1ff3cbd33d00
refs/heads/master
2020-07-01T03:35:16.188329
2020-02-15T15:33:38
2020-02-15T15:33:38
201,034,169
0
0
null
null
null
null
UTF-8
C++
false
false
67,597
h
#pragma once #if defined(__gl_h_) #error gl/gl.h included somewhere #endif #include "soko_glcorearb.h" #include "Platform.h" // NOTE: Extensions // ARB_texture_filter_anisotropic #define GL_TEXTURE_MAX_ANISOTROPY_ARB 0x84FE #define GL_MAX_TEXTURE_MAX_ANISOTROPY_ARB 0x84FF // ARB_gl_spirv #define GL_SHADER_BINARY_FORMAT_SPIR_V_ARB 0x9551 #define GL_SPIR_V_BINARY_ARB 0x9552 extern "C" { typedef void(APIENTRY* PFNGLSPECIALIZESHADERARBPROC)(GLuint shader, const GLchar* pEntryPoint, GLuint numSpecializationConstants, const GLuint* pConstantIndex, const GLuint* pConstantValue); } // ARB_spirv_extensions #define GL_SPIR_V_EXTENSIONS_ARB 0x9553 #define GL_NUM_SPIR_V_EXTENSIONS_ARB 0x9554 // NOTE: It was defined in soko_glcorearb.h #if defined(APIENTRY_DEFINED) #undef APIENTRY #endif namespace soko { struct OpenGL { union Functions { struct _Functions { // 1.0 PFNGLCULLFACEPROC glCullFace; PFNGLFRONTFACEPROC glFrontFace; PFNGLHINTPROC glHint; PFNGLLINEWIDTHPROC glLineWidth; PFNGLPOINTSIZEPROC glPointSize; PFNGLPOLYGONMODEPROC glPolygonMode; PFNGLSCISSORPROC glScissor; PFNGLTEXPARAMETERFPROC glTexParameterf; PFNGLTEXPARAMETERFVPROC glTexParameterfv; PFNGLTEXPARAMETERIPROC glTexParameteri; PFNGLTEXPARAMETERIVPROC glTexParameteriv; PFNGLTEXIMAGE1DPROC glTexImage1D; PFNGLTEXIMAGE2DPROC glTexImage2D; PFNGLDRAWBUFFERPROC glDrawBuffer; PFNGLCLEARPROC glClear; PFNGLCLEARCOLORPROC glClearColor; PFNGLCLEARSTENCILPROC glClearStencil; PFNGLCLEARDEPTHPROC glClearDepth; PFNGLSTENCILMASKPROC glStencilMask; PFNGLCOLORMASKPROC glColorMask; PFNGLDEPTHMASKPROC glDepthMask; PFNGLDISABLEPROC glDisable; PFNGLENABLEPROC glEnable; PFNGLFINISHPROC glFinish; PFNGLFLUSHPROC glFlush; PFNGLBLENDFUNCPROC glBlendFunc; PFNGLLOGICOPPROC glLogicOp; PFNGLSTENCILFUNCPROC glStencilFunc; PFNGLSTENCILOPPROC glStencilOp; PFNGLDEPTHFUNCPROC glDepthFunc; PFNGLPIXELSTOREFPROC glPixelStoref; PFNGLPIXELSTOREIPROC glPixelStorei; PFNGLREADBUFFERPROC glReadBuffer; PFNGLREADPIXELSPROC glReadPixels; PFNGLGETBOOLEANVPROC glGetBooleanv; PFNGLGETDOUBLEVPROC glGetDoublev; PFNGLGETERRORPROC glGetError; PFNGLGETFLOATVPROC glGetFloatv; PFNGLGETINTEGERVPROC glGetIntegerv; PFNGLGETSTRINGPROC glGetString; PFNGLGETTEXIMAGEPROC glGetTexImage; PFNGLGETTEXPARAMETERFVPROC glGetTexParameterfv; PFNGLGETTEXPARAMETERIVPROC glGetTexParameteriv; PFNGLGETTEXLEVELPARAMETERFVPROC glGetTexLevelParameterfv; PFNGLGETTEXLEVELPARAMETERIVPROC glGetTexLevelParameteriv; PFNGLISENABLEDPROC glIsEnabled; PFNGLDEPTHRANGEPROC glDepthRange; PFNGLVIEWPORTPROC glViewport; // 11 PFNGLDRAWARRAYSPROC glDrawArrays; PFNGLDRAWELEMENTSPROC glDrawElements; PFNGLGETPOINTERVPROC glGetPointerv; PFNGLPOLYGONOFFSETPROC glPolygonOffset; PFNGLCOPYTEXIMAGE1DPROC glCopyTexImage1D; PFNGLCOPYTEXIMAGE2DPROC glCopyTexImage2D; PFNGLCOPYTEXSUBIMAGE1DPROC glCopyTexSubImage1D; PFNGLCOPYTEXSUBIMAGE2DPROC glCopyTexSubImage2D; PFNGLTEXSUBIMAGE1DPROC glTexSubImage1D; PFNGLTEXSUBIMAGE2DPROC glTexSubImage2D; PFNGLBINDTEXTUREPROC glBindTexture; PFNGLDELETETEXTURESPROC glDeleteTextures; PFNGLGENTEXTURESPROC glGenTextures; PFNGLISTEXTUREPROC glIsTexture; // 12 PFNGLDRAWRANGEELEMENTSPROC glDrawRangeElements; PFNGLTEXIMAGE3DPROC glTexImage3D; PFNGLTEXSUBIMAGE3DPROC glTexSubImage3D; PFNGLCOPYTEXSUBIMAGE3DPROC glCopyTexSubImage3D; // 13 PFNGLACTIVETEXTUREPROC glActiveTexture; PFNGLSAMPLECOVERAGEPROC glSampleCoverage; PFNGLCOMPRESSEDTEXIMAGE3DPROC glCompressedTexImage3D; PFNGLCOMPRESSEDTEXIMAGE2DPROC glCompressedTexImage2D; PFNGLCOMPRESSEDTEXIMAGE1DPROC glCompressedTexImage1D; PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC glCompressedTexSubImage3D; PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glCompressedTexSubImage2D; PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC glCompressedTexSubImage1D; PFNGLGETCOMPRESSEDTEXIMAGEPROC glGetCompressedTexImage; // 14 PFNGLBLENDFUNCSEPARATEPROC glBlendFuncSeparate; PFNGLMULTIDRAWARRAYSPROC glMultiDrawArrays; PFNGLMULTIDRAWELEMENTSPROC glMultiDrawElements; PFNGLPOINTPARAMETERFPROC glPointParameterf; PFNGLPOINTPARAMETERFVPROC glPointParameterfv; PFNGLPOINTPARAMETERIPROC glPointParameteri; PFNGLPOINTPARAMETERIVPROC glPointParameteriv; PFNGLBLENDCOLORPROC glBlendColor; PFNGLBLENDEQUATIONPROC glBlendEquation; // 15 PFNGLGENQUERIESPROC glGenQueries; PFNGLDELETEQUERIESPROC glDeleteQueries; PFNGLISQUERYPROC glIsQuery; PFNGLBEGINQUERYPROC glBeginQuery; PFNGLENDQUERYPROC glEndQuery; PFNGLGETQUERYIVPROC glGetQueryiv; PFNGLGETQUERYOBJECTIVPROC glGetQueryObjectiv; PFNGLGETQUERYOBJECTUIVPROC glGetQueryObjectuiv; PFNGLBINDBUFFERPROC glBindBuffer; PFNGLDELETEBUFFERSPROC glDeleteBuffers; PFNGLGENBUFFERSPROC glGenBuffers; PFNGLISBUFFERPROC glIsBuffer; PFNGLBUFFERDATAPROC glBufferData; PFNGLBUFFERSUBDATAPROC glBufferSubData; PFNGLGETBUFFERSUBDATAPROC glGetBufferSubData; PFNGLMAPBUFFERPROC glMapBuffer; PFNGLUNMAPBUFFERPROC glUnmapBuffer; PFNGLGETBUFFERPARAMETERIVPROC glGetBufferParameteriv; PFNGLGETBUFFERPOINTERVPROC glGetBufferPointerv; // 20 PFNGLBLENDEQUATIONSEPARATEPROC glBlendEquationSeparate; PFNGLDRAWBUFFERSPROC glDrawBuffers; PFNGLSTENCILOPSEPARATEPROC glStencilOpSeparate; PFNGLSTENCILFUNCSEPARATEPROC glStencilFuncSeparate; PFNGLSTENCILMASKSEPARATEPROC glStencilMaskSeparate; PFNGLATTACHSHADERPROC glAttachShader; PFNGLBINDATTRIBLOCATIONPROC glBindAttribLocation; PFNGLCOMPILESHADERPROC glCompileShader; PFNGLCREATEPROGRAMPROC glCreateProgram; PFNGLCREATESHADERPROC glCreateShader; PFNGLDELETEPROGRAMPROC glDeleteProgram; PFNGLDELETESHADERPROC glDeleteShader; PFNGLDETACHSHADERPROC glDetachShader; PFNGLDISABLEVERTEXATTRIBARRAYPROC glDisableVertexAttribArray; PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray; PFNGLGETACTIVEATTRIBPROC glGetActiveAttrib; PFNGLGETACTIVEUNIFORMPROC glGetActiveUniform; PFNGLGETATTACHEDSHADERSPROC glGetAttachedShaders; PFNGLGETATTRIBLOCATIONPROC glGetAttribLocation; PFNGLGETPROGRAMIVPROC glGetProgramiv; PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog; PFNGLGETSHADERIVPROC glGetShaderiv; PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog; PFNGLGETSHADERSOURCEPROC glGetShaderSource; PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation; PFNGLGETUNIFORMFVPROC glGetUniformfv; PFNGLGETUNIFORMIVPROC glGetUniformiv; PFNGLGETVERTEXATTRIBDVPROC glGetVertexAttribdv; PFNGLGETVERTEXATTRIBFVPROC glGetVertexAttribfv; PFNGLGETVERTEXATTRIBIVPROC glGetVertexAttribiv; PFNGLGETVERTEXATTRIBPOINTERVPROC glGetVertexAttribPointerv; PFNGLISPROGRAMPROC glIsProgram; PFNGLISSHADERPROC glIsShader; PFNGLLINKPROGRAMPROC glLinkProgram; PFNGLSHADERSOURCEPROC glShaderSource; PFNGLUSEPROGRAMPROC glUseProgram; PFNGLUNIFORM1FPROC glUniform1f; PFNGLUNIFORM2FPROC glUniform2f; PFNGLUNIFORM3FPROC glUniform3f; PFNGLUNIFORM4FPROC glUniform4f; PFNGLUNIFORM1IPROC glUniform1i; PFNGLUNIFORM2IPROC glUniform2i; PFNGLUNIFORM3IPROC glUniform3i; PFNGLUNIFORM4IPROC glUniform4i; PFNGLUNIFORM1FVPROC glUniform1fv; PFNGLUNIFORM2FVPROC glUniform2fv; PFNGLUNIFORM3FVPROC glUniform3fv; PFNGLUNIFORM4FVPROC glUniform4fv; PFNGLUNIFORM1IVPROC glUniform1iv; PFNGLUNIFORM2IVPROC glUniform2iv; PFNGLUNIFORM3IVPROC glUniform3iv; PFNGLUNIFORM4IVPROC glUniform4iv; PFNGLUNIFORMMATRIX2FVPROC glUniformMatrix2fv; PFNGLUNIFORMMATRIX3FVPROC glUniformMatrix3fv; PFNGLUNIFORMMATRIX4FVPROC glUniformMatrix4fv; PFNGLVALIDATEPROGRAMPROC glValidateProgram; PFNGLVERTEXATTRIB1DPROC glVertexAttrib1d; PFNGLVERTEXATTRIB1DVPROC glVertexAttrib1dv; PFNGLVERTEXATTRIB1FPROC glVertexAttrib1f; PFNGLVERTEXATTRIB1FVPROC glVertexAttrib1fv; PFNGLVERTEXATTRIB1SPROC glVertexAttrib1s; PFNGLVERTEXATTRIB1SVPROC glVertexAttrib1sv; PFNGLVERTEXATTRIB2DPROC glVertexAttrib2d; PFNGLVERTEXATTRIB2DVPROC glVertexAttrib2dv; PFNGLVERTEXATTRIB2FPROC glVertexAttrib2f; PFNGLVERTEXATTRIB2FVPROC glVertexAttrib2fv; PFNGLVERTEXATTRIB2SPROC glVertexAttrib2s; PFNGLVERTEXATTRIB2SVPROC glVertexAttrib2sv; PFNGLVERTEXATTRIB3DPROC glVertexAttrib3d; PFNGLVERTEXATTRIB3DVPROC glVertexAttrib3dv; PFNGLVERTEXATTRIB3FPROC glVertexAttrib3f; PFNGLVERTEXATTRIB3FVPROC glVertexAttrib3fv; PFNGLVERTEXATTRIB3SPROC glVertexAttrib3s; PFNGLVERTEXATTRIB3SVPROC glVertexAttrib3sv; PFNGLVERTEXATTRIB4NBVPROC glVertexAttrib4Nbv; PFNGLVERTEXATTRIB4NIVPROC glVertexAttrib4Niv; PFNGLVERTEXATTRIB4NSVPROC glVertexAttrib4Nsv; PFNGLVERTEXATTRIB4NUBPROC glVertexAttrib4Nub; PFNGLVERTEXATTRIB4NUBVPROC glVertexAttrib4Nubv; PFNGLVERTEXATTRIB4NUIVPROC glVertexAttrib4Nuiv; PFNGLVERTEXATTRIB4NUSVPROC glVertexAttrib4Nusv; PFNGLVERTEXATTRIB4BVPROC glVertexAttrib4bv; PFNGLVERTEXATTRIB4DPROC glVertexAttrib4d; PFNGLVERTEXATTRIB4DVPROC glVertexAttrib4dv; PFNGLVERTEXATTRIB4FPROC glVertexAttrib4f; PFNGLVERTEXATTRIB4FVPROC glVertexAttrib4fv; PFNGLVERTEXATTRIB4IVPROC glVertexAttrib4iv; PFNGLVERTEXATTRIB4SPROC glVertexAttrib4s; PFNGLVERTEXATTRIB4SVPROC glVertexAttrib4sv; PFNGLVERTEXATTRIB4UBVPROC glVertexAttrib4ubv; PFNGLVERTEXATTRIB4UIVPROC glVertexAttrib4uiv; PFNGLVERTEXATTRIB4USVPROC glVertexAttrib4usv; PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer; // 21 PFNGLUNIFORMMATRIX2X3FVPROC glUniformMatrix2x3fv; PFNGLUNIFORMMATRIX3X2FVPROC glUniformMatrix3x2fv; PFNGLUNIFORMMATRIX2X4FVPROC glUniformMatrix2x4fv; PFNGLUNIFORMMATRIX4X2FVPROC glUniformMatrix4x2fv; PFNGLUNIFORMMATRIX3X4FVPROC glUniformMatrix3x4fv; PFNGLUNIFORMMATRIX4X3FVPROC glUniformMatrix4x3fv; // 30 PFNGLCOLORMASKIPROC glColorMaski; PFNGLGETBOOLEANI_VPROC glGetBooleani_v; PFNGLGETINTEGERI_VPROC glGetIntegeri_v; PFNGLENABLEIPROC glEnablei; PFNGLDISABLEIPROC glDisablei; PFNGLISENABLEDIPROC glIsEnabledi; PFNGLBEGINTRANSFORMFEEDBACKPROC glBeginTransformFeedback; PFNGLENDTRANSFORMFEEDBACKPROC glEndTransformFeedback; PFNGLBINDBUFFERRANGEPROC glBindBufferRange; PFNGLBINDBUFFERBASEPROC glBindBufferBase; PFNGLTRANSFORMFEEDBACKVARYINGSPROC glTransformFeedbackVaryings; PFNGLGETTRANSFORMFEEDBACKVARYINGPROC glGetTransformFeedbackVarying; PFNGLCLAMPCOLORPROC glClampColor; PFNGLBEGINCONDITIONALRENDERPROC glBeginConditionalRender; PFNGLENDCONDITIONALRENDERPROC glEndConditionalRender; PFNGLVERTEXATTRIBIPOINTERPROC glVertexAttribIPointer; PFNGLGETVERTEXATTRIBIIVPROC glGetVertexAttribIiv; PFNGLGETVERTEXATTRIBIUIVPROC glGetVertexAttribIuiv; PFNGLVERTEXATTRIBI1IPROC glVertexAttribI1i; PFNGLVERTEXATTRIBI2IPROC glVertexAttribI2i; PFNGLVERTEXATTRIBI3IPROC glVertexAttribI3i; PFNGLVERTEXATTRIBI4IPROC glVertexAttribI4i; PFNGLVERTEXATTRIBI1UIPROC glVertexAttribI1ui; PFNGLVERTEXATTRIBI2UIPROC glVertexAttribI2ui; PFNGLVERTEXATTRIBI3UIPROC glVertexAttribI3ui; PFNGLVERTEXATTRIBI4UIPROC glVertexAttribI4ui; PFNGLVERTEXATTRIBI1IVPROC glVertexAttribI1iv; PFNGLVERTEXATTRIBI2IVPROC glVertexAttribI2iv; PFNGLVERTEXATTRIBI3IVPROC glVertexAttribI3iv; PFNGLVERTEXATTRIBI4IVPROC glVertexAttribI4iv; PFNGLVERTEXATTRIBI1UIVPROC glVertexAttribI1uiv; PFNGLVERTEXATTRIBI2UIVPROC glVertexAttribI2uiv; PFNGLVERTEXATTRIBI3UIVPROC glVertexAttribI3uiv; PFNGLVERTEXATTRIBI4UIVPROC glVertexAttribI4uiv; PFNGLVERTEXATTRIBI4BVPROC glVertexAttribI4bv; PFNGLVERTEXATTRIBI4SVPROC glVertexAttribI4sv; PFNGLVERTEXATTRIBI4UBVPROC glVertexAttribI4ubv; PFNGLVERTEXATTRIBI4USVPROC glVertexAttribI4usv; PFNGLGETUNIFORMUIVPROC glGetUniformuiv; PFNGLBINDFRAGDATALOCATIONPROC glBindFragDataLocation; PFNGLGETFRAGDATALOCATIONPROC glGetFragDataLocation; PFNGLUNIFORM1UIPROC glUniform1ui; PFNGLUNIFORM2UIPROC glUniform2ui; PFNGLUNIFORM3UIPROC glUniform3ui; PFNGLUNIFORM4UIPROC glUniform4ui; PFNGLUNIFORM1UIVPROC glUniform1uiv; PFNGLUNIFORM2UIVPROC glUniform2uiv; PFNGLUNIFORM3UIVPROC glUniform3uiv; PFNGLUNIFORM4UIVPROC glUniform4uiv; PFNGLTEXPARAMETERIIVPROC glTexParameterIiv; PFNGLTEXPARAMETERIUIVPROC glTexParameterIuiv; PFNGLGETTEXPARAMETERIIVPROC glGetTexParameterIiv; PFNGLGETTEXPARAMETERIUIVPROC glGetTexParameterIuiv; PFNGLCLEARBUFFERIVPROC glClearBufferiv; PFNGLCLEARBUFFERUIVPROC glClearBufferuiv; PFNGLCLEARBUFFERFVPROC glClearBufferfv; PFNGLCLEARBUFFERFIPROC glClearBufferfi; PFNGLGETSTRINGIPROC glGetStringi; PFNGLISRENDERBUFFERPROC glIsRenderbuffer; PFNGLBINDRENDERBUFFERPROC glBindRenderbuffer; PFNGLDELETERENDERBUFFERSPROC glDeleteRenderbuffers; PFNGLGENRENDERBUFFERSPROC glGenRenderbuffers; PFNGLRENDERBUFFERSTORAGEPROC glRenderbufferStorage; PFNGLGETRENDERBUFFERPARAMETERIVPROC glGetRenderbufferParameteriv; PFNGLISFRAMEBUFFERPROC glIsFramebuffer; PFNGLBINDFRAMEBUFFERPROC glBindFramebuffer; PFNGLDELETEFRAMEBUFFERSPROC glDeleteFramebuffers; PFNGLGENFRAMEBUFFERSPROC glGenFramebuffers; PFNGLCHECKFRAMEBUFFERSTATUSPROC glCheckFramebufferStatus; PFNGLFRAMEBUFFERTEXTURE1DPROC glFramebufferTexture1D; PFNGLFRAMEBUFFERTEXTURE2DPROC glFramebufferTexture2D; PFNGLFRAMEBUFFERTEXTURE3DPROC glFramebufferTexture3D; PFNGLFRAMEBUFFERRENDERBUFFERPROC glFramebufferRenderbuffer; PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC glGetFramebufferAttachmentParameteriv; PFNGLGENERATEMIPMAPPROC glGenerateMipmap; PFNGLBLITFRAMEBUFFERPROC glBlitFramebuffer; PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC glRenderbufferStorageMultisample; PFNGLFRAMEBUFFERTEXTURELAYERPROC glFramebufferTextureLayer; PFNGLMAPBUFFERRANGEPROC glMapBufferRange; PFNGLFLUSHMAPPEDBUFFERRANGEPROC glFlushMappedBufferRange; PFNGLBINDVERTEXARRAYPROC glBindVertexArray; PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArrays; PFNGLGENVERTEXARRAYSPROC glGenVertexArrays; PFNGLISVERTEXARRAYPROC glIsVertexArray; // 31 PFNGLDRAWARRAYSINSTANCEDPROC glDrawArraysInstanced; PFNGLDRAWELEMENTSINSTANCEDPROC glDrawElementsInstanced; PFNGLTEXBUFFERPROC glTexBuffer; PFNGLPRIMITIVERESTARTINDEXPROC glPrimitiveRestartIndex; PFNGLCOPYBUFFERSUBDATAPROC glCopyBufferSubData; PFNGLGETUNIFORMINDICESPROC glGetUniformIndices; PFNGLGETACTIVEUNIFORMSIVPROC glGetActiveUniformsiv; PFNGLGETACTIVEUNIFORMNAMEPROC glGetActiveUniformName; PFNGLGETUNIFORMBLOCKINDEXPROC glGetUniformBlockIndex; PFNGLGETACTIVEUNIFORMBLOCKIVPROC glGetActiveUniformBlockiv; PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC glGetActiveUniformBlockName; PFNGLUNIFORMBLOCKBINDINGPROC glUniformBlockBinding; // 32 PFNGLDRAWELEMENTSBASEVERTEXPROC glDrawElementsBaseVertex; PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC glDrawRangeElementsBaseVertex; PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC glDrawElementsInstancedBaseVertex; PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC glMultiDrawElementsBaseVertex; PFNGLPROVOKINGVERTEXPROC glProvokingVertex; PFNGLFENCESYNCPROC glFenceSync; PFNGLISSYNCPROC glIsSync; PFNGLDELETESYNCPROC glDeleteSync; PFNGLCLIENTWAITSYNCPROC glClientWaitSync; PFNGLWAITSYNCPROC glWaitSync; PFNGLGETINTEGER64VPROC glGetInteger64v; PFNGLGETSYNCIVPROC glGetSynciv; PFNGLGETINTEGER64I_VPROC glGetInteger64i_v; PFNGLGETBUFFERPARAMETERI64VPROC glGetBufferParameteri64v; PFNGLFRAMEBUFFERTEXTUREPROC glFramebufferTexture; PFNGLTEXIMAGE2DMULTISAMPLEPROC glTexImage2DMultisample; PFNGLTEXIMAGE3DMULTISAMPLEPROC glTexImage3DMultisample; PFNGLGETMULTISAMPLEFVPROC glGetMultisamplefv; PFNGLSAMPLEMASKIPROC glSampleMaski; // 33 PFNGLBINDFRAGDATALOCATIONINDEXEDPROC glBindFragDataLocationIndexed; PFNGLGETFRAGDATAINDEXPROC glGetFragDataIndex; PFNGLGENSAMPLERSPROC glGenSamplers; PFNGLDELETESAMPLERSPROC glDeleteSamplers; PFNGLISSAMPLERPROC glIsSampler; PFNGLBINDSAMPLERPROC glBindSampler; PFNGLSAMPLERPARAMETERIPROC glSamplerParameteri; PFNGLSAMPLERPARAMETERIVPROC glSamplerParameteriv; PFNGLSAMPLERPARAMETERFPROC glSamplerParameterf; PFNGLSAMPLERPARAMETERFVPROC glSamplerParameterfv; PFNGLSAMPLERPARAMETERIIVPROC glSamplerParameterIiv; PFNGLSAMPLERPARAMETERIUIVPROC glSamplerParameterIuiv; PFNGLGETSAMPLERPARAMETERIVPROC glGetSamplerParameteriv; PFNGLGETSAMPLERPARAMETERIIVPROC glGetSamplerParameterIiv; PFNGLGETSAMPLERPARAMETERFVPROC glGetSamplerParameterfv; PFNGLGETSAMPLERPARAMETERIUIVPROC glGetSamplerParameterIuiv; PFNGLQUERYCOUNTERPROC glQueryCounter; PFNGLGETQUERYOBJECTI64VPROC glGetQueryObjecti64v; PFNGLGETQUERYOBJECTUI64VPROC glGetQueryObjectui64v; PFNGLVERTEXATTRIBDIVISORPROC glVertexAttribDivisor; PFNGLVERTEXATTRIBP1UIPROC glVertexAttribP1ui; PFNGLVERTEXATTRIBP1UIVPROC glVertexAttribP1uiv; PFNGLVERTEXATTRIBP2UIPROC glVertexAttribP2ui; PFNGLVERTEXATTRIBP2UIVPROC glVertexAttribP2uiv; PFNGLVERTEXATTRIBP3UIPROC glVertexAttribP3ui; PFNGLVERTEXATTRIBP3UIVPROC glVertexAttribP3uiv; PFNGLVERTEXATTRIBP4UIPROC glVertexAttribP4ui; PFNGLVERTEXATTRIBP4UIVPROC glVertexAttribP4uiv; // 4.0 PFNGLMINSAMPLESHADINGPROC glMinSampleShading; PFNGLBLENDEQUATIONIPROC glBlendEquationi; PFNGLBLENDEQUATIONSEPARATEIPROC glBlendEquationSeparatei; PFNGLBLENDFUNCIPROC glBlendFunci; PFNGLBLENDFUNCSEPARATEIPROC glBlendFuncSeparatei; PFNGLDRAWARRAYSINDIRECTPROC glDrawArraysIndirect; PFNGLDRAWELEMENTSINDIRECTPROC glDrawElementsIndirect; PFNGLUNIFORM1DPROC glUniform1d; PFNGLUNIFORM2DPROC glUniform2d; PFNGLUNIFORM3DPROC glUniform3d; PFNGLUNIFORM4DPROC glUniform4d; PFNGLUNIFORM1DVPROC glUniform1dv; PFNGLUNIFORM2DVPROC glUniform2dv; PFNGLUNIFORM3DVPROC glUniform3dv; PFNGLUNIFORM4DVPROC glUniform4dv; PFNGLUNIFORMMATRIX2DVPROC glUniformMatrix2dv; PFNGLUNIFORMMATRIX3DVPROC glUniformMatrix3dv; PFNGLUNIFORMMATRIX4DVPROC glUniformMatrix4dv; PFNGLUNIFORMMATRIX2X3DVPROC glUniformMatrix2x3dv; PFNGLUNIFORMMATRIX2X4DVPROC glUniformMatrix2x4dv; PFNGLUNIFORMMATRIX3X2DVPROC glUniformMatrix3x2dv; PFNGLUNIFORMMATRIX3X4DVPROC glUniformMatrix3x4dv; PFNGLUNIFORMMATRIX4X2DVPROC glUniformMatrix4x2dv; PFNGLUNIFORMMATRIX4X3DVPROC glUniformMatrix4x3dv; PFNGLGETUNIFORMDVPROC glGetUniformdv; PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC glGetSubroutineUniformLocation; PFNGLGETSUBROUTINEINDEXPROC glGetSubroutineIndex; PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC glGetActiveSubroutineUniformiv; PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC glGetActiveSubroutineUniformName; PFNGLGETACTIVESUBROUTINENAMEPROC glGetActiveSubroutineName; PFNGLUNIFORMSUBROUTINESUIVPROC glUniformSubroutinesuiv; PFNGLGETUNIFORMSUBROUTINEUIVPROC glGetUniformSubroutineuiv; PFNGLGETPROGRAMSTAGEIVPROC glGetProgramStageiv; PFNGLPATCHPARAMETERIPROC glPatchParameteri; PFNGLPATCHPARAMETERFVPROC glPatchParameterfv; PFNGLBINDTRANSFORMFEEDBACKPROC glBindTransformFeedback; PFNGLDELETETRANSFORMFEEDBACKSPROC glDeleteTransformFeedbacks; PFNGLGENTRANSFORMFEEDBACKSPROC glGenTransformFeedbacks; PFNGLISTRANSFORMFEEDBACKPROC glIsTransformFeedback; PFNGLPAUSETRANSFORMFEEDBACKPROC glPauseTransformFeedback; PFNGLRESUMETRANSFORMFEEDBACKPROC glResumeTransformFeedback; PFNGLDRAWTRANSFORMFEEDBACKPROC glDrawTransformFeedback; PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC glDrawTransformFeedbackStream; PFNGLBEGINQUERYINDEXEDPROC glBeginQueryIndexed; PFNGLENDQUERYINDEXEDPROC glEndQueryIndexed; PFNGLGETQUERYINDEXEDIVPROC glGetQueryIndexediv; // 4.1 PFNGLRELEASESHADERCOMPILERPROC glReleaseShaderCompiler; PFNGLSHADERBINARYPROC glShaderBinary; PFNGLGETSHADERPRECISIONFORMATPROC glGetShaderPrecisionFormat; PFNGLDEPTHRANGEFPROC glDepthRangef; PFNGLCLEARDEPTHFPROC glClearDepthf; PFNGLGETPROGRAMBINARYPROC glGetProgramBinary; PFNGLPROGRAMBINARYPROC glProgramBinary; PFNGLPROGRAMPARAMETERIPROC glProgramParameteri; PFNGLUSEPROGRAMSTAGESPROC glUseProgramStages; PFNGLACTIVESHADERPROGRAMPROC glActiveShaderProgram; PFNGLCREATESHADERPROGRAMVPROC glCreateShaderProgramv; PFNGLBINDPROGRAMPIPELINEPROC glBindProgramPipeline; PFNGLDELETEPROGRAMPIPELINESPROC glDeleteProgramPipelines; PFNGLGENPROGRAMPIPELINESPROC glGenProgramPipelines; PFNGLISPROGRAMPIPELINEPROC glIsProgramPipeline; PFNGLGETPROGRAMPIPELINEIVPROC glGetProgramPipelineiv; PFNGLPROGRAMUNIFORM1IPROC glProgramUniform1i; PFNGLPROGRAMUNIFORM1IVPROC glProgramUniform1iv; PFNGLPROGRAMUNIFORM1FPROC glProgramUniform1f; PFNGLPROGRAMUNIFORM1FVPROC glProgramUniform1fv; PFNGLPROGRAMUNIFORM1DPROC glProgramUniform1d; PFNGLPROGRAMUNIFORM1DVPROC glProgramUniform1dv; PFNGLPROGRAMUNIFORM1UIPROC glProgramUniform1ui; PFNGLPROGRAMUNIFORM1UIVPROC glProgramUniform1uiv; PFNGLPROGRAMUNIFORM2IPROC glProgramUniform2i; PFNGLPROGRAMUNIFORM2IVPROC glProgramUniform2iv; PFNGLPROGRAMUNIFORM2FPROC glProgramUniform2f; PFNGLPROGRAMUNIFORM2FVPROC glProgramUniform2fv; PFNGLPROGRAMUNIFORM2DPROC glProgramUniform2d; PFNGLPROGRAMUNIFORM2DVPROC glProgramUniform2dv; PFNGLPROGRAMUNIFORM2UIPROC glProgramUniform2ui; PFNGLPROGRAMUNIFORM2UIVPROC glProgramUniform2uiv; PFNGLPROGRAMUNIFORM3IPROC glProgramUniform3i; PFNGLPROGRAMUNIFORM3IVPROC glProgramUniform3iv; PFNGLPROGRAMUNIFORM3FPROC glProgramUniform3f; PFNGLPROGRAMUNIFORM3FVPROC glProgramUniform3fv; PFNGLPROGRAMUNIFORM3DPROC glProgramUniform3d; PFNGLPROGRAMUNIFORM3DVPROC glProgramUniform3dv; PFNGLPROGRAMUNIFORM3UIPROC glProgramUniform3ui; PFNGLPROGRAMUNIFORM3UIVPROC glProgramUniform3uiv; PFNGLPROGRAMUNIFORM4IPROC glProgramUniform4i; PFNGLPROGRAMUNIFORM4IVPROC glProgramUniform4iv; PFNGLPROGRAMUNIFORM4FPROC glProgramUniform4f; PFNGLPROGRAMUNIFORM4FVPROC glProgramUniform4fv; PFNGLPROGRAMUNIFORM4DPROC glProgramUniform4d; PFNGLPROGRAMUNIFORM4DVPROC glProgramUniform4dv; PFNGLPROGRAMUNIFORM4UIPROC glProgramUniform4ui; PFNGLPROGRAMUNIFORM4UIVPROC glProgramUniform4uiv; PFNGLPROGRAMUNIFORMMATRIX2FVPROC glProgramUniformMatrix2fv; PFNGLPROGRAMUNIFORMMATRIX3FVPROC glProgramUniformMatrix3fv; PFNGLPROGRAMUNIFORMMATRIX4FVPROC glProgramUniformMatrix4fv; PFNGLPROGRAMUNIFORMMATRIX2DVPROC glProgramUniformMatrix2dv; PFNGLPROGRAMUNIFORMMATRIX3DVPROC glProgramUniformMatrix3dv; PFNGLPROGRAMUNIFORMMATRIX4DVPROC glProgramUniformMatrix4dv; PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC glProgramUniformMatrix2x3fv; PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC glProgramUniformMatrix3x2fv; PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC glProgramUniformMatrix2x4fv; PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC glProgramUniformMatrix4x2fv; PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC glProgramUniformMatrix3x4fv; PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC glProgramUniformMatrix4x3fv; PFNGLPROGRAMUNIFORMMATRIX2X3DVPROC glProgramUniformMatrix2x3dv; PFNGLPROGRAMUNIFORMMATRIX3X2DVPROC glProgramUniformMatrix3x2dv; PFNGLPROGRAMUNIFORMMATRIX2X4DVPROC glProgramUniformMatrix2x4dv; PFNGLPROGRAMUNIFORMMATRIX4X2DVPROC glProgramUniformMatrix4x2dv; PFNGLPROGRAMUNIFORMMATRIX3X4DVPROC glProgramUniformMatrix3x4dv; PFNGLPROGRAMUNIFORMMATRIX4X3DVPROC glProgramUniformMatrix4x3dv; PFNGLVALIDATEPROGRAMPIPELINEPROC glValidateProgramPipeline; PFNGLGETPROGRAMPIPELINEINFOLOGPROC glGetProgramPipelineInfoLog; PFNGLVERTEXATTRIBL1DPROC glVertexAttribL1d; PFNGLVERTEXATTRIBL2DPROC glVertexAttribL2d; PFNGLVERTEXATTRIBL3DPROC glVertexAttribL3d; PFNGLVERTEXATTRIBL4DPROC glVertexAttribL4d; PFNGLVERTEXATTRIBL1DVPROC glVertexAttribL1dv; PFNGLVERTEXATTRIBL2DVPROC glVertexAttribL2dv; PFNGLVERTEXATTRIBL3DVPROC glVertexAttribL3dv; PFNGLVERTEXATTRIBL4DVPROC glVertexAttribL4dv; PFNGLVERTEXATTRIBLPOINTERPROC glVertexAttribLPointer; PFNGLGETVERTEXATTRIBLDVPROC glGetVertexAttribLdv; PFNGLVIEWPORTARRAYVPROC glViewportArrayv; PFNGLVIEWPORTINDEXEDFPROC glViewportIndexedf; PFNGLVIEWPORTINDEXEDFVPROC glViewportIndexedfv; PFNGLSCISSORARRAYVPROC glScissorArrayv; PFNGLSCISSORINDEXEDPROC glScissorIndexed; PFNGLSCISSORINDEXEDVPROC glScissorIndexedv; PFNGLDEPTHRANGEARRAYVPROC glDepthRangeArrayv; PFNGLDEPTHRANGEINDEXEDPROC glDepthRangeIndexed; PFNGLGETFLOATI_VPROC glGetFloati_v; PFNGLGETDOUBLEI_VPROC glGetDoublei_v; // 4.2 PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC glDrawArraysInstancedBaseInstance; PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC glDrawElementsInstancedBaseInstance; PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC glDrawElementsInstancedBaseVertexBaseInstance; PFNGLGETINTERNALFORMATIVPROC glGetInternalformativ; PFNGLGETACTIVEATOMICCOUNTERBUFFERIVPROC glGetActiveAtomicCounterBufferiv; PFNGLBINDIMAGETEXTUREPROC glBindImageTexture; PFNGLMEMORYBARRIERPROC glMemoryBarrier; PFNGLTEXSTORAGE1DPROC glTexStorage1D; PFNGLTEXSTORAGE2DPROC glTexStorage2D; PFNGLTEXSTORAGE3DPROC glTexStorage3D; PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDPROC glDrawTransformFeedbackInstanced; PFNGLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC glDrawTransformFeedbackStreamInstanced; // 4.3 PFNGLCLEARBUFFERDATAPROC glClearBufferData; PFNGLCLEARBUFFERSUBDATAPROC glClearBufferSubData; PFNGLDISPATCHCOMPUTEPROC glDispatchCompute; PFNGLDISPATCHCOMPUTEINDIRECTPROC glDispatchComputeIndirect; PFNGLCOPYIMAGESUBDATAPROC glCopyImageSubData; PFNGLFRAMEBUFFERPARAMETERIPROC glFramebufferParameteri; PFNGLGETFRAMEBUFFERPARAMETERIVPROC glGetFramebufferParameteriv; PFNGLGETINTERNALFORMATI64VPROC glGetInternalformati64v; PFNGLINVALIDATETEXSUBIMAGEPROC glInvalidateTexSubImage; PFNGLINVALIDATETEXIMAGEPROC glInvalidateTexImage; PFNGLINVALIDATEBUFFERSUBDATAPROC glInvalidateBufferSubData; PFNGLINVALIDATEBUFFERDATAPROC glInvalidateBufferData; PFNGLINVALIDATEFRAMEBUFFERPROC glInvalidateFramebuffer; PFNGLINVALIDATESUBFRAMEBUFFERPROC glInvalidateSubFramebuffer; PFNGLMULTIDRAWARRAYSINDIRECTPROC glMultiDrawArraysIndirect; PFNGLMULTIDRAWELEMENTSINDIRECTPROC glMultiDrawElementsIndirect; PFNGLGETPROGRAMINTERFACEIVPROC glGetProgramInterfaceiv; PFNGLGETPROGRAMRESOURCEINDEXPROC glGetProgramResourceIndex; PFNGLGETPROGRAMRESOURCENAMEPROC glGetProgramResourceName; PFNGLGETPROGRAMRESOURCEIVPROC glGetProgramResourceiv; PFNGLGETPROGRAMRESOURCELOCATIONPROC glGetProgramResourceLocation; PFNGLGETPROGRAMRESOURCELOCATIONINDEXPROC glGetProgramResourceLocationIndex; PFNGLSHADERSTORAGEBLOCKBINDINGPROC glShaderStorageBlockBinding; PFNGLTEXBUFFERRANGEPROC glTexBufferRange; PFNGLTEXSTORAGE2DMULTISAMPLEPROC glTexStorage2DMultisample; PFNGLTEXSTORAGE3DMULTISAMPLEPROC glTexStorage3DMultisample; PFNGLTEXTUREVIEWPROC glTextureView; PFNGLBINDVERTEXBUFFERPROC glBindVertexBuffer; PFNGLVERTEXATTRIBFORMATPROC glVertexAttribFormat; PFNGLVERTEXATTRIBIFORMATPROC glVertexAttribIFormat; PFNGLVERTEXATTRIBLFORMATPROC glVertexAttribLFormat; PFNGLVERTEXATTRIBBINDINGPROC glVertexAttribBinding; PFNGLVERTEXBINDINGDIVISORPROC glVertexBindingDivisor; PFNGLDEBUGMESSAGECONTROLPROC glDebugMessageControl; PFNGLDEBUGMESSAGEINSERTPROC glDebugMessageInsert; PFNGLDEBUGMESSAGECALLBACKPROC glDebugMessageCallback; PFNGLGETDEBUGMESSAGELOGPROC glGetDebugMessageLog; PFNGLPUSHDEBUGGROUPPROC glPushDebugGroup; PFNGLPOPDEBUGGROUPPROC glPopDebugGroup; PFNGLOBJECTLABELPROC glObjectLabel; PFNGLGETOBJECTLABELPROC glGetObjectLabel; PFNGLOBJECTPTRLABELPROC glObjectPtrLabel; PFNGLGETOBJECTPTRLABELPROC glGetObjectPtrLabel; // 4.4 PFNGLBUFFERSTORAGEPROC glBufferStorage; PFNGLCLEARTEXIMAGEPROC glClearTexImage; PFNGLCLEARTEXSUBIMAGEPROC glClearTexSubImage; PFNGLBINDBUFFERSBASEPROC glBindBuffersBase; PFNGLBINDBUFFERSRANGEPROC glBindBuffersRange; PFNGLBINDTEXTURESPROC glBindTextures; PFNGLBINDSAMPLERSPROC glBindSamplers; PFNGLBINDIMAGETEXTURESPROC glBindImageTextures; PFNGLBINDVERTEXBUFFERSPROC glBindVertexBuffers; // 4.5 PFNGLCLIPCONTROLPROC glClipControl; PFNGLCREATETRANSFORMFEEDBACKSPROC glCreateTransformFeedbacks; PFNGLTRANSFORMFEEDBACKBUFFERBASEPROC glTransformFeedbackBufferBase; PFNGLTRANSFORMFEEDBACKBUFFERRANGEPROC glTransformFeedbackBufferRange; PFNGLGETTRANSFORMFEEDBACKIVPROC glGetTransformFeedbackiv; PFNGLGETTRANSFORMFEEDBACKI_VPROC glGetTransformFeedbacki_v; PFNGLGETTRANSFORMFEEDBACKI64_VPROC glGetTransformFeedbacki64_v; PFNGLCREATEBUFFERSPROC glCreateBuffers; PFNGLNAMEDBUFFERSTORAGEPROC glNamedBufferStorage; PFNGLNAMEDBUFFERDATAPROC glNamedBufferData; PFNGLNAMEDBUFFERSUBDATAPROC glNamedBufferSubData; PFNGLCOPYNAMEDBUFFERSUBDATAPROC glCopyNamedBufferSubData; PFNGLCLEARNAMEDBUFFERDATAPROC glClearNamedBufferData; PFNGLCLEARNAMEDBUFFERSUBDATAPROC glClearNamedBufferSubData; PFNGLMAPNAMEDBUFFERPROC glMapNamedBuffer; PFNGLMAPNAMEDBUFFERRANGEPROC glMapNamedBufferRange; PFNGLUNMAPNAMEDBUFFERPROC glUnmapNamedBuffer; PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEPROC glFlushMappedNamedBufferRange; PFNGLGETNAMEDBUFFERPARAMETERIVPROC glGetNamedBufferParameteriv; PFNGLGETNAMEDBUFFERPARAMETERI64VPROC glGetNamedBufferParameteri64v; PFNGLGETNAMEDBUFFERPOINTERVPROC glGetNamedBufferPointerv; PFNGLGETNAMEDBUFFERSUBDATAPROC glGetNamedBufferSubData; PFNGLCREATEFRAMEBUFFERSPROC glCreateFramebuffers; PFNGLNAMEDFRAMEBUFFERRENDERBUFFERPROC glNamedFramebufferRenderbuffer; PFNGLNAMEDFRAMEBUFFERPARAMETERIPROC glNamedFramebufferParameteri; PFNGLNAMEDFRAMEBUFFERTEXTUREPROC glNamedFramebufferTexture; PFNGLNAMEDFRAMEBUFFERTEXTURELAYERPROC glNamedFramebufferTextureLayer; PFNGLNAMEDFRAMEBUFFERDRAWBUFFERPROC glNamedFramebufferDrawBuffer; PFNGLNAMEDFRAMEBUFFERDRAWBUFFERSPROC glNamedFramebufferDrawBuffers; PFNGLNAMEDFRAMEBUFFERREADBUFFERPROC glNamedFramebufferReadBuffer; PFNGLINVALIDATENAMEDFRAMEBUFFERDATAPROC glInvalidateNamedFramebufferData; PFNGLINVALIDATENAMEDFRAMEBUFFERSUBDATAPROC glInvalidateNamedFramebufferSubData; PFNGLCLEARNAMEDFRAMEBUFFERIVPROC glClearNamedFramebufferiv; PFNGLCLEARNAMEDFRAMEBUFFERUIVPROC glClearNamedFramebufferuiv; PFNGLCLEARNAMEDFRAMEBUFFERFVPROC glClearNamedFramebufferfv; PFNGLCLEARNAMEDFRAMEBUFFERFIPROC glClearNamedFramebufferfi; PFNGLBLITNAMEDFRAMEBUFFERPROC glBlitNamedFramebuffer; PFNGLCHECKNAMEDFRAMEBUFFERSTATUSPROC glCheckNamedFramebufferStatus; PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVPROC glGetNamedFramebufferParameteriv; PFNGLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVPROC glGetNamedFramebufferAttachmentParameteriv; PFNGLCREATERENDERBUFFERSPROC glCreateRenderbuffers; PFNGLNAMEDRENDERBUFFERSTORAGEPROC glNamedRenderbufferStorage; PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEPROC glNamedRenderbufferStorageMultisample; PFNGLGETNAMEDRENDERBUFFERPARAMETERIVPROC glGetNamedRenderbufferParameteriv; PFNGLCREATETEXTURESPROC glCreateTextures; PFNGLTEXTUREBUFFERPROC glTextureBuffer; PFNGLTEXTUREBUFFERRANGEPROC glTextureBufferRange; PFNGLTEXTURESTORAGE1DPROC glTextureStorage1D; PFNGLTEXTURESTORAGE2DPROC glTextureStorage2D; PFNGLTEXTURESTORAGE3DPROC glTextureStorage3D; PFNGLTEXTURESTORAGE2DMULTISAMPLEPROC glTextureStorage2DMultisample; PFNGLTEXTURESTORAGE3DMULTISAMPLEPROC glTextureStorage3DMultisample; PFNGLTEXTURESUBIMAGE1DPROC glTextureSubImage1D; PFNGLTEXTURESUBIMAGE2DPROC glTextureSubImage2D; PFNGLTEXTURESUBIMAGE3DPROC glTextureSubImage3D; PFNGLCOMPRESSEDTEXTURESUBIMAGE1DPROC glCompressedTextureSubImage1D; PFNGLCOMPRESSEDTEXTURESUBIMAGE2DPROC glCompressedTextureSubImage2D; PFNGLCOMPRESSEDTEXTURESUBIMAGE3DPROC glCompressedTextureSubImage3D; PFNGLCOPYTEXTURESUBIMAGE1DPROC glCopyTextureSubImage1D; PFNGLCOPYTEXTURESUBIMAGE2DPROC glCopyTextureSubImage2D; PFNGLCOPYTEXTURESUBIMAGE3DPROC glCopyTextureSubImage3D; PFNGLTEXTUREPARAMETERFPROC glTextureParameterf; PFNGLTEXTUREPARAMETERFVPROC glTextureParameterfv; PFNGLTEXTUREPARAMETERIPROC glTextureParameteri; PFNGLTEXTUREPARAMETERIIVPROC glTextureParameterIiv; PFNGLTEXTUREPARAMETERIUIVPROC glTextureParameterIuiv; PFNGLTEXTUREPARAMETERIVPROC glTextureParameteriv; PFNGLGENERATETEXTUREMIPMAPPROC glGenerateTextureMipmap; PFNGLBINDTEXTUREUNITPROC glBindTextureUnit; PFNGLGETTEXTUREIMAGEPROC glGetTextureImage; PFNGLGETCOMPRESSEDTEXTUREIMAGEPROC glGetCompressedTextureImage; PFNGLGETTEXTURELEVELPARAMETERFVPROC glGetTextureLevelParameterfv; PFNGLGETTEXTURELEVELPARAMETERIVPROC glGetTextureLevelParameteriv; PFNGLGETTEXTUREPARAMETERFVPROC glGetTextureParameterfv; PFNGLGETTEXTUREPARAMETERIIVPROC glGetTextureParameterIiv; PFNGLGETTEXTUREPARAMETERIUIVPROC glGetTextureParameterIuiv; PFNGLGETTEXTUREPARAMETERIVPROC glGetTextureParameteriv; PFNGLCREATEVERTEXARRAYSPROC glCreateVertexArrays; PFNGLDISABLEVERTEXARRAYATTRIBPROC glDisableVertexArrayAttrib; PFNGLENABLEVERTEXARRAYATTRIBPROC glEnableVertexArrayAttrib; PFNGLVERTEXARRAYELEMENTBUFFERPROC glVertexArrayElementBuffer; PFNGLVERTEXARRAYVERTEXBUFFERPROC glVertexArrayVertexBuffer; PFNGLVERTEXARRAYVERTEXBUFFERSPROC glVertexArrayVertexBuffers; PFNGLVERTEXARRAYATTRIBBINDINGPROC glVertexArrayAttribBinding; PFNGLVERTEXARRAYATTRIBFORMATPROC glVertexArrayAttribFormat; PFNGLVERTEXARRAYATTRIBIFORMATPROC glVertexArrayAttribIFormat; PFNGLVERTEXARRAYATTRIBLFORMATPROC glVertexArrayAttribLFormat; PFNGLVERTEXARRAYBINDINGDIVISORPROC glVertexArrayBindingDivisor; PFNGLGETVERTEXARRAYIVPROC glGetVertexArrayiv; PFNGLGETVERTEXARRAYINDEXEDIVPROC glGetVertexArrayIndexediv; PFNGLGETVERTEXARRAYINDEXED64IVPROC glGetVertexArrayIndexed64iv; PFNGLCREATESAMPLERSPROC glCreateSamplers; PFNGLCREATEPROGRAMPIPELINESPROC glCreateProgramPipelines; PFNGLCREATEQUERIESPROC glCreateQueries; PFNGLGETQUERYBUFFEROBJECTI64VPROC glGetQueryBufferObjecti64v; PFNGLGETQUERYBUFFEROBJECTIVPROC glGetQueryBufferObjectiv; PFNGLGETQUERYBUFFEROBJECTUI64VPROC glGetQueryBufferObjectui64v; PFNGLGETQUERYBUFFEROBJECTUIVPROC glGetQueryBufferObjectuiv; PFNGLMEMORYBARRIERBYREGIONPROC glMemoryBarrierByRegion; PFNGLGETTEXTURESUBIMAGEPROC glGetTextureSubImage; PFNGLGETCOMPRESSEDTEXTURESUBIMAGEPROC glGetCompressedTextureSubImage; PFNGLGETGRAPHICSRESETSTATUSPROC glGetGraphicsResetStatus; PFNGLGETNCOMPRESSEDTEXIMAGEPROC glGetnCompressedTexImage; PFNGLGETNTEXIMAGEPROC glGetnTexImage; PFNGLGETNUNIFORMDVPROC glGetnUniformdv; PFNGLGETNUNIFORMFVPROC glGetnUniformfv; PFNGLGETNUNIFORMIVPROC glGetnUniformiv; PFNGLGETNUNIFORMUIVPROC glGetnUniformuiv; PFNGLREADNPIXELSPROC glReadnPixels; PFNGLTEXTUREBARRIERPROC glTextureBarrier; // 4.6 #if 0 PFNGLSPECIALIZESHADERPROC glSpecializeShader; PFNGLMULTIDRAWARRAYSINDIRECTCOUNTPROC glMultiDrawArraysIndirectCount; PFNGLMULTIDRAWELEMENTSINDIRECTCOUNTPROC glMultiDrawElementsIndirectCount; PFNGLPOLYGONOFFSETCLAMPPROC glPolygonOffsetClamp; #endif } fn; void* raw[sizeof(Functions::_Functions) / sizeof(void*)]; } functions; struct { bool EXT_texture_filter_anisotropic; bool ARB_texture_filter_anisotropic; bool ARB_spirv_extensions; struct _ARB_gl_spirv { bool supported; PFNGLSPECIALIZESHADERARBPROC glSpecializeShaderARB; } ARB_gl_spirv; } extensions; static const uint32_t FunctionCount = sizeof(Functions::_Functions) / sizeof(void*); static const inline char* FunctionNames[] = { "glCullFace", "glFrontFace", "glHint", "glLineWidth", "glPointSize", "glPolygonMode", "glScissor", "glTexParameterf", "glTexParameterfv", "glTexParameteri", "glTexParameteriv", "glTexImage1D", "glTexImage2D", "glDrawBuffer", "glClear", "glClearColor", "glClearStencil", "glClearDepth", "glStencilMask", "glColorMask", "glDepthMask", "glDisable", "glEnable", "glFinish", "glFlush", "glBlendFunc", "glLogicOp", "glStencilFunc", "glStencilOp", "glDepthFunc", "glPixelStoref", "glPixelStorei", "glReadBuffer", "glReadPixels", "glGetBooleanv", "glGetDoublev", "glGetError", "glGetFloatv", "glGetIntegerv", "glGetString", "glGetTexImage", "glGetTexParameterfv", "glGetTexParameteriv", "glGetTexLevelParameterfv", "glGetTexLevelParameteriv", "glIsEnabled", "glDepthRange", "glViewport", // 11 "glDrawArrays", "glDrawElements", "glGetPointerv", "glPolygonOffset", "glCopyTexImage1D", "glCopyTexImage2D", "glCopyTexSubImage1D", "glCopyTexSubImage2D", "glTexSubImage1D", "glTexSubImage2D", "glBindTexture", "glDeleteTextures", "glGenTextures", "glIsTexture", // 12 "glDrawRangeElements", "glTexImage3D", "glTexSubImage3D", "glCopyTexSubImage3D", // 13 "glActiveTexture", "glSampleCoverage", "glCompressedTexImage3D", "glCompressedTexImage2D", "glCompressedTexImage1D", "glCompressedTexSubImage3D", "glCompressedTexSubImage2D", "glCompressedTexSubImage1D", "glGetCompressedTexImage", // 14 "glBlendFuncSeparate", "glMultiDrawArrays", "glMultiDrawElements", "glPointParameterf", "glPointParameterfv", "glPointParameteri", "glPointParameteriv", "glBlendColor", "glBlendEquation", // 15 "glGenQueries", "glDeleteQueries", "glIsQuery", "glBeginQuery", "glEndQuery", "glGetQueryiv", "glGetQueryObjectiv", "glGetQueryObjectuiv", "glBindBuffer", "glDeleteBuffers", "glGenBuffers", "glIsBuffer", "glBufferData", "glBufferSubData", "glGetBufferSubData", "glMapBuffer", "glUnmapBuffer", "glGetBufferParameteriv", "glGetBufferPointerv", // 20 "glBlendEquationSeparate", "glDrawBuffers", "glStencilOpSeparate", "glStencilFuncSeparate", "glStencilMaskSeparate", "glAttachShader", "glBindAttribLocation", "glCompileShader", "glCreateProgram", "glCreateShader", "glDeleteProgram", "glDeleteShader", "glDetachShader", "glDisableVertexAttribArray", "glEnableVertexAttribArray", "glGetActiveAttrib", "glGetActiveUniform", "glGetAttachedShaders", "glGetAttribLocation", "glGetProgramiv", "glGetProgramInfoLog", "glGetShaderiv", "glGetShaderInfoLog", "glGetShaderSource", "glGetUniformLocation", "glGetUniformfv", "glGetUniformiv", "glGetVertexAttribdv", "glGetVertexAttribfv", "glGetVertexAttribiv", "glGetVertexAttribPointerv", "glIsProgram", "glIsShader", "glLinkProgram", "glShaderSource", "glUseProgram", "glUniform1f", "glUniform2f", "glUniform3f", "glUniform4f", "glUniform1i", "glUniform2i", "glUniform3i", "glUniform4i", "glUniform1fv", "glUniform2fv", "glUniform3fv", "glUniform4fv", "glUniform1iv", "glUniform2iv", "glUniform3iv", "glUniform4iv", "glUniformMatrix2fv", "glUniformMatrix3fv", "glUniformMatrix4fv", "glValidateProgram", "glVertexAttrib1d", "glVertexAttrib1dv", "glVertexAttrib1f", "glVertexAttrib1fv", "glVertexAttrib1s", "glVertexAttrib1sv", "glVertexAttrib2d", "glVertexAttrib2dv", "glVertexAttrib2f", "glVertexAttrib2fv", "glVertexAttrib2s", "glVertexAttrib2sv", "glVertexAttrib3d", "glVertexAttrib3dv", "glVertexAttrib3f", "glVertexAttrib3fv", "glVertexAttrib3s", "glVertexAttrib3sv", "glVertexAttrib4Nbv", "glVertexAttrib4Niv", "glVertexAttrib4Nsv", "glVertexAttrib4Nub", "glVertexAttrib4Nubv", "glVertexAttrib4Nuiv", "glVertexAttrib4Nusv", "glVertexAttrib4bv", "glVertexAttrib4d", "glVertexAttrib4dv", "glVertexAttrib4f", "glVertexAttrib4fv", "glVertexAttrib4iv", "glVertexAttrib4s", "glVertexAttrib4sv", "glVertexAttrib4ubv", "glVertexAttrib4uiv", "glVertexAttrib4usv", "glVertexAttribPointer", // 21 "glUniformMatrix2x3fv", "glUniformMatrix3x2fv", "glUniformMatrix2x4fv", "glUniformMatrix4x2fv", "glUniformMatrix3x4fv", "glUniformMatrix4x3fv", // 30 "glColorMaski", "VPROC glGetBooleani_v", "VPROC glGetIntegeri_v", "glEnablei", "glDisablei", "glIsEnabledi", "glBeginTransformFeedback", "glEndTransformFeedback", "glBindBufferRange", "glBindBufferBase", "glTransformFeedbackVaryings", "glGetTransformFeedbackVarying", "glClampColor", "glBeginConditionalRender", "glEndConditionalRender", "glVertexAttribIPointer", "glGetVertexAttribIiv", "glGetVertexAttribIuiv", "glVertexAttribI1i", "glVertexAttribI2i", "glVertexAttribI3i", "glVertexAttribI4i", "glVertexAttribI1ui", "glVertexAttribI2ui", "glVertexAttribI3ui", "glVertexAttribI4ui", "glVertexAttribI1iv", "glVertexAttribI2iv", "glVertexAttribI3iv", "glVertexAttribI4iv", "glVertexAttribI1uiv", "glVertexAttribI2uiv", "glVertexAttribI3uiv", "glVertexAttribI4uiv", "glVertexAttribI4bv", "glVertexAttribI4sv", "glVertexAttribI4ubv", "glVertexAttribI4usv", "glGetUniformuiv", "glBindFragDataLocation", "glGetFragDataLocation", "glUniform1ui", "glUniform2ui", "glUniform3ui", "glUniform4ui", "glUniform1uiv", "glUniform2uiv", "glUniform3uiv", "glUniform4uiv", "glTexParameterIiv", "glTexParameterIuiv", "glGetTexParameterIiv", "glGetTexParameterIuiv", "glClearBufferiv", "glClearBufferuiv", "glClearBufferfv", "glClearBufferfi", "glGetStringi", "glIsRenderbuffer", "glBindRenderbuffer", "glDeleteRenderbuffers", "glGenRenderbuffers", "glRenderbufferStorage", "glGetRenderbufferParameteriv", "glIsFramebuffer", "glBindFramebuffer", "glDeleteFramebuffers", "glGenFramebuffers", "glCheckFramebufferStatus", "glFramebufferTexture1D", "glFramebufferTexture2D", "glFramebufferTexture3D", "glFramebufferRenderbuffer", "glGetFramebufferAttachmentParameteriv", "glGenerateMipmap", "glBlitFramebuffer", "glRenderbufferStorageMultisample", "glFramebufferTextureLayer", "glMapBufferRange", "glFlushMappedBufferRange", "glBindVertexArray", "glDeleteVertexArrays", "glGenVertexArrays", "glIsVertexArray", // 31 "glDrawArraysInstanced", "glDrawElementsInstanced", "glTexBuffer", "glPrimitiveRestartIndex", "glCopyBufferSubData", "glGetUniformIndices", "glGetActiveUniformsiv", "glGetActiveUniformName", "glGetUniformBlockIndex", "glGetActiveUniformBlockiv", "glGetActiveUniformBlockName", "glUniformBlockBinding", // 32 "glDrawElementsBaseVertex", "glDrawRangeElementsBaseVertex", "glDrawElementsInstancedBaseVertex", "glMultiDrawElementsBaseVertex", "glProvokingVertex", "glFenceSync", "glIsSync", "glDeleteSync", "glClientWaitSync", "glWaitSync", "glGetInteger64v", "glGetSynciv", "glGetInteger64i_v", "glGetBufferParameteri64v", "glFramebufferTexture", "glTexImage2DMultisample", "glTexImage3DMultisample", "glGetMultisamplefv", "glSampleMaski", // 33 "glBindFragDataLocationIndexed", "glGetFragDataIndex", "glGenSamplers", "glDeleteSamplers", "glIsSampler", "glBindSampler", "glSamplerParameteri", "glSamplerParameteriv", "glSamplerParameterf", "glSamplerParameterfv", "glSamplerParameterIiv", "glSamplerParameterIuiv", "glGetSamplerParameteriv", "glGetSamplerParameterIiv", "glGetSamplerParameterfv", "glGetSamplerParameterIuiv", "glQueryCounter", "glGetQueryObjecti64v", "glGetQueryObjectui64v", "glVertexAttribDivisor", "glVertexAttribP1ui", "glVertexAttribP1uiv", "glVertexAttribP2ui", "glVertexAttribP2uiv", "glVertexAttribP3ui", "glVertexAttribP3uiv", "glVertexAttribP4ui", "glVertexAttribP4uiv", // 4.0 "glMinSampleShading", "glBlendEquationi", "glBlendEquationSeparatei", "glBlendFunci", "glBlendFuncSeparatei", "glDrawArraysIndirect", "glDrawElementsIndirect", "glUniform1d", "glUniform2d", "glUniform3d", "glUniform4d", "glUniform1dv", "glUniform2dv", "glUniform3dv", "glUniform4dv", "glUniformMatrix2dv", "glUniformMatrix3dv", "glUniformMatrix4dv", "glUniformMatrix2x3dv", "glUniformMatrix2x4dv", "glUniformMatrix3x2dv", "glUniformMatrix3x4dv", "glUniformMatrix4x2dv", "glUniformMatrix4x3dv", "glGetUniformdv", "glGetSubroutineUniformLocation", "glGetSubroutineIndex", "glGetActiveSubroutineUniformiv", "glGetActiveSubroutineUniformName", "glGetActiveSubroutineName", "glUniformSubroutinesuiv", "glGetUniformSubroutineuiv", "glGetProgramStageiv", "glPatchParameteri", "glPatchParameterfv", "glBindTransformFeedback", "glDeleteTransformFeedbacks", "glGenTransformFeedbacks", "glIsTransformFeedback", "glPauseTransformFeedback", "glResumeTransformFeedback", "glDrawTransformFeedback", "glDrawTransformFeedbackStream", "glBeginQueryIndexed", "glEndQueryIndexed", "glGetQueryIndexediv", // 4.1 "glReleaseShaderCompiler", "glShaderBinary", "glGetShaderPrecisionFormat", "glDepthRangef", "glClearDepthf", "glGetProgramBinary", "glProgramBinary", "glProgramParameteri", "glUseProgramStages", "glActiveShaderProgram", "glCreateShaderProgramv", "glBindProgramPipeline", "glDeleteProgramPipelines", "glGenProgramPipelines", "glIsProgramPipeline", "glGetProgramPipelineiv", "glProgramUniform1i", "glProgramUniform1iv", "glProgramUniform1f", "glProgramUniform1fv", "glProgramUniform1d", "glProgramUniform1dv", "glProgramUniform1ui", "glProgramUniform1uiv", "glProgramUniform2i", "glProgramUniform2iv", "glProgramUniform2f", "glProgramUniform2fv", "glProgramUniform2d", "glProgramUniform2dv", "glProgramUniform2ui", "glProgramUniform2uiv", "glProgramUniform3i", "glProgramUniform3iv", "glProgramUniform3f", "glProgramUniform3fv", "glProgramUniform3d", "glProgramUniform3dv", "glProgramUniform3ui", "glProgramUniform3uiv", "glProgramUniform4i", "glProgramUniform4iv", "glProgramUniform4f", "glProgramUniform4fv", "glProgramUniform4d", "glProgramUniform4dv", "glProgramUniform4ui", "glProgramUniform4uiv", "glProgramUniformMatrix2fv", "glProgramUniformMatrix3fv", "glProgramUniformMatrix4fv", "glProgramUniformMatrix2dv", "glProgramUniformMatrix3dv", "glProgramUniformMatrix4dv", "glProgramUniformMatrix2x3fv", "glProgramUniformMatrix3x2fv", "glProgramUniformMatrix2x4fv", "glProgramUniformMatrix4x2fv", "glProgramUniformMatrix3x4fv", "glProgramUniformMatrix4x3fv", "glProgramUniformMatrix2x3dv", "glProgramUniformMatrix3x2dv", "glProgramUniformMatrix2x4dv", "glProgramUniformMatrix4x2dv", "glProgramUniformMatrix3x4dv", "glProgramUniformMatrix4x3dv", "glValidateProgramPipeline", "glGetProgramPipelineInfoLog", "glVertexAttribL1d", "glVertexAttribL2d", "glVertexAttribL3d", "glVertexAttribL4d", "glVertexAttribL1dv", "glVertexAttribL2dv", "glVertexAttribL3dv", "glVertexAttribL4dv", "glVertexAttribLPointer", "glGetVertexAttribLdv", "glViewportArrayv", "glViewportIndexedf", "glViewportIndexedfv", "glScissorArrayv", "glScissorIndexed", "glScissorIndexedv", "glDepthRangeArrayv", "glDepthRangeIndexed", "glGetFloati_v", "glGetDoublei_v", // 4.2 "glDrawArraysInstancedBaseInstance", "glDrawElementsInstancedBaseInstance", "glDrawElementsInstancedBaseVertexBaseInstance", "glGetInternalformativ", "glGetActiveAtomicCounterBufferiv", "glBindImageTexture", "glMemoryBarrier", "glTexStorage1D", "glTexStorage2D", "glTexStorage3D", "glDrawTransformFeedbackInstanced", "glDrawTransformFeedbackStreamInstanced", // 4.3 "glClearBufferData", "glClearBufferSubData", "glDispatchCompute", "glDispatchComputeIndirect", "glCopyImageSubData", "glFramebufferParameteri", "glGetFramebufferParameteriv", "glGetInternalformati64v", "glInvalidateTexSubImage", "glInvalidateTexImage", "glInvalidateBufferSubData", "glInvalidateBufferData", "glInvalidateFramebuffer", "glInvalidateSubFramebuffer", "glMultiDrawArraysIndirect", "glMultiDrawElementsIndirect", "glGetProgramInterfaceiv", "glGetProgramResourceIndex", "glGetProgramResourceName", "glGetProgramResourceiv", "glGetProgramResourceLocation", "glGetProgramResourceLocationIndex", "glShaderStorageBlockBinding", "glTexBufferRange", "glTexStorage2DMultisample", "glTexStorage3DMultisample", "glTextureView", "glBindVertexBuffer", "glVertexAttribFormat", "glVertexAttribIFormat", "glVertexAttribLFormat", "glVertexAttribBinding", "glVertexBindingDivisor", "glDebugMessageControl", "glDebugMessageInsert", "glDebugMessageCallback", "glGetDebugMessageLog", "glPushDebugGroup", "glPopDebugGroup", "glObjectLabel", "glGetObjectLabel", "glObjectPtrLabel", "glGetObjectPtrLabel", // 4.4 "glBufferStorage", "glClearTexImage", "glClearTexSubImage", "glBindBuffersBase", "glBindBuffersRange", "glBindTextures", "glBindSamplers", "glBindImageTextures", "glBindVertexBuffers", // 4.5 "glClipControl", "glCreateTransformFeedbacks", "glTransformFeedbackBufferBase", "glTransformFeedbackBufferRange", "glGetTransformFeedbackiv", "glGetTransformFeedbacki_v", "glGetTransformFeedbacki64_v", "glCreateBuffers", "glNamedBufferStorage", "glNamedBufferData", "glNamedBufferSubData", "glCopyNamedBufferSubData", "glClearNamedBufferData", "glClearNamedBufferSubData", "glMapNamedBuffer", "glMapNamedBufferRange", "glUnmapNamedBuffer", "glFlushMappedNamedBufferRange", "glGetNamedBufferParameteriv", "glGetNamedBufferParameteri64v", "glGetNamedBufferPointerv", "glGetNamedBufferSubData", "glCreateFramebuffers", "glNamedFramebufferRenderbuffer", "glNamedFramebufferParameteri", "glNamedFramebufferTexture", "glNamedFramebufferTextureLayer", "glNamedFramebufferDrawBuffer", "glNamedFramebufferDrawBuffers", "glNamedFramebufferReadBuffer", "glInvalidateNamedFramebufferData", "glInvalidateNamedFramebufferSubData", "glClearNamedFramebufferiv", "glClearNamedFramebufferuiv", "glClearNamedFramebufferfv", "glClearNamedFramebufferfi", "glBlitNamedFramebuffer", "glCheckNamedFramebufferStatus", "glGetNamedFramebufferParameteriv", "glGetNamedFramebufferAttachmentParameteriv", "glCreateRenderbuffers", "glNamedRenderbufferStorage", "glNamedRenderbufferStorageMultisample", "glGetNamedRenderbufferParameteriv", "glCreateTextures", "glTextureBuffer", "glTextureBufferRange", "glTextureStorage1D", "glTextureStorage2D", "glTextureStorage3D", "glTextureStorage2DMultisample", "glTextureStorage3DMultisample", "glTextureSubImage1D", "glTextureSubImage2D", "glTextureSubImage3D", "glCompressedTextureSubImage1D", "glCompressedTextureSubImage2D", "glCompressedTextureSubImage3D", "glCopyTextureSubImage1D", "glCopyTextureSubImage2D", "glCopyTextureSubImage3D", "glTextureParameterf", "glTextureParameterfv", "glTextureParameteri", "glTextureParameterIiv", "glTextureParameterIuiv", "glTextureParameteriv", "glGenerateTextureMipmap", "glBindTextureUnit", "glGetTextureImage", "glGetCompressedTextureImage", "glGetTextureLevelParameterfv", "glGetTextureLevelParameteriv", "glGetTextureParameterfv", "glGetTextureParameterIiv", "glGetTextureParameterIuiv", "glGetTextureParameteriv", "glCreateVertexArrays", "glDisableVertexArrayAttrib", "glEnableVertexArrayAttrib", "glVertexArrayElementBuffer", "glVertexArrayVertexBuffer", "glVertexArrayVertexBuffers", "glVertexArrayAttribBinding", "glVertexArrayAttribFormat", "glVertexArrayAttribIFormat", "glVertexArrayAttribLFormat", "glVertexArrayBindingDivisor", "glGetVertexArrayiv", "glGetVertexArrayIndexediv", "glGetVertexArrayIndexed64iv", "glCreateSamplers", "glCreateProgramPipelines", "glCreateQueries", "glGetQueryBufferObjecti64v", "glGetQueryBufferObjectiv", "glGetQueryBufferObjectui64v", "glGetQueryBufferObjectuiv", "glMemoryBarrierByRegion", "glGetTextureSubImage", "glGetCompressedTextureSubImage", "glGetGraphicsResetStatus", "glGetnCompressedTexImage", "glGetnTexImage", "glGetnUniformdv", "glGetnUniformfv", "glGetnUniformiv", "glGetnUniformuiv", "glReadnPixels", "glTextureBarrier" // 4.6 #if 0 "glSpecializeShader", "glMultiDrawArraysIndirectCount", "glMultiDrawElementsIndirectCount", "glPolygonOffsetClamp" #endif }; }; }
[ "hbr.tzuf@yandex.ru" ]
hbr.tzuf@yandex.ru
289ff4bd56770331322c3c04f4a1277d50d88e46
c8958958e5802f3e04ce88bd4064eacb98ce2f97
/森林中的兔子.cpp
f2ee5e95986e8944691d1c9096b268d5d495463c
[]
no_license
Kiids/OJ_Practice
08e5ea99066421bfaf5b71e59eea24e282e39a24
e7d36ddb1664635d27db3c37bec952970b77dcb0
refs/heads/master
2023-09-01T11:38:28.834187
2023-06-30T17:12:18
2023-06-30T17:12:18
217,068,695
0
0
null
null
null
null
GB18030
C++
false
false
1,641
cpp
/* 森林中,每个兔子都有颜色。其中一些兔子(可能是全部)告诉你还有多少其他的兔子和自己有相同的颜色。我们将这些回答放在 answers 数组里。 返回森林中兔子的最少数量。 示例: 输入: answers = [1, 1, 2] 输出: 5 解释: 两只回答了 "1" 的兔子可能有相同的颜色,设为红色。 之后回答了 "2" 的兔子不会是红色,否则他们的回答会相互矛盾。 设回答了 "2" 的兔子为蓝色。 此外,森林中还应有另外 2 只蓝色兔子的回答没有包含在数组中。 因此森林中兔子的最少数量是 5: 3 只回答的和 2 只没有回答的。 输入: answers = [10, 10, 10] 输出: 11 输入: answers = [] 输出: 0 说明: answers 的长度最大为1000。 answers[i] 是在 [0, 999] 范围内的整数。 */ class Solution { public: int numRabbits(vector<int>& answers) { if (answers.empty()) return 0; int ret = 0; unordered_map<int, int> m; // <数字, 说了这个数字的兔子数量> for (int e : answers) { if (!m.count(e) || m[e] == 0) // 没有记录或当前数字的兔子数量为0时 { ret += e + 1; m[e]++ ; } else if (m.count(e)) m[e] ++ ; if (m[e] == e + 1) // 当兔子数量等于数字时,表示达到该种颜色所能代表的数量上限 m[e] = 0; // 重置兔子数量为零,若再遇到相同数字,需要开另一种颜色来存 } return ret; } };
[ "1980774293@qq.com" ]
1980774293@qq.com
364cca4f7c1a1bf798424fb91eddfee3d9d81739
d7db098f4b1d1cd7d32952ebde8106e1f297252e
/CodeChef/d.cpp
d8ed0927c34b9bc5693171121c0ab3eecdc372e8
[]
no_license
monman53/online_judge
d1d3ce50f5a8a3364a259a78bb89980ce05b9419
dec972d2b2b3922227d9eecaad607f1d9cc94434
refs/heads/master
2021-01-16T18:36:27.455888
2019-05-26T14:03:14
2019-05-26T14:03:14
25,679,069
0
0
null
null
null
null
UTF-8
C++
false
false
3,607
cpp
// header {{{ #include <bits/stdc++.h> using namespace std; // {U}{INT,LONG,LLONG}_{MAX,MIN} #define INF INT_MAX/3 #define LLINF LLONG_MAX/3 #define MOD (1000000007LL) #define MODA(a, b) a=((a)+(b))%MOD #define MODP(a, b) a=((a)*(b))%MOD #define inc(i, l, r) for(int i=(l);i<(r);i++) #define dec(i, l, r) for(int i=(r)-1;i>=(l);i--) #define pb push_back #define se second #define fi first #define mset(a, b) memset(a, b, sizeof(a)) using LL = long long; using G = vector<vector<int>>; int di[] = {0, -1, 0, 1}; int dj[] = {1, 0, -1, 0}; // }}} struct Hoge { int l, r; vector<int> seq; Hoge(char c, int l, int r){ this->l = l; this->r = r; int cnt = 0; inc(i, 0, r-l){ seq.push_back(cnt); if(c == 'I'){ cnt++; }else{ cnt--; } } } int add(char c, int l, int r){ set<int> st; int cnt = 0; inc(i, l-this->l, this->r-this->l){ st.insert(seq[i]-cnt); if(c == 'I'){ cnt++; }else{ cnt--; } } if(st.size() != 1){ return 1; }else{ inc(i, this->r-this->l, r-this->l){ if(c == 'I'){ seq.push_back(seq[i-1]+1); }else{ seq.push_back(seq[i-1]-1); } } this->r = r; return 0; } } }; int solve() { int n, m, k; vector<int> a; vector<pair<pair<int, int>, char>> lr; vector<int> imos; stack<Hoge> st; LL ans = 1; cin >> n >> m >> k; a.resize(n); lr.resize(m); imos.resize(n+5, 0); inc(i, 0, n) cin >> a[i]; inc(i, 0, m){ char c; int l, r; cin >> c >> l >> r; l--; imos[l]++; imos[r]--; lr[i] = {{l, r}, c}; } inc(i, 1, n+4){ imos[i] = imos[i-1] + imos[i]; } sort(lr.begin(), lr.end()); inc(i, 0, m){ char c = lr[i].se; int l = lr[i].fi.fi; int r = lr[i].fi.se; if(st.size() == 0){ st.push(Hoge(c, l, r)); }else{ auto now = st.top(); st.pop(); if(now.r-l > 0){ if(now.add(c, l, r)){ return 1; } st.push(now); }else{ st.push(now); st.push(Hoge(c, l, r)); } } } while(!st.empty()){ auto now = st.top(); st.pop(); int l = now.l; int r = now.r; set<int> ss; int mmax = -INF; int mmin = INF; inc(i, l, r){ if(a[i] != -1){ ss.insert(now.seq[i-l]-a[i]); } mmax = max(now.seq[i-l], mmax); mmin = min(now.seq[i-l], mmin); } //cout << "ss" << ss.size() << endl; //cout << "a" << ans << endl; if(ss.size() == 0){ if(k-(mmax-mmin) < 1){ return 1; } MODP(ans, k-(mmax-mmin)); }else{ if(ss.size() != 1) return 1; } } inc(i, 0, n+5){ if(imos[i] == 0 && a[i] == -1){ MODP(ans, k); } } cout << ans << endl; return 0; } int main() { cin.tie(0);ios::sync_with_stdio(false); int t;cin >> t; while(t--){ if(solve()){ cout << 0 << endl; } } return 0; }
[ "monman.cs@gmail.com" ]
monman.cs@gmail.com
037beb0fa5e70e5074fd6e92826630500efff0be
c766bece263e5149d0dbab04ea20308bf1191ab8
/AdobeInDesignCCProductsSDK.2020/source/public/interfaces/architecture/IRecoveryList.h
04aff3c384e8c02c0d6e757cd306adb8b8f673e5
[]
no_license
stevenstong/adobe-tools
37a36868619db90984d5303187305c9da1e024f7
c74d61d882363a91da4938fd525b97f83084cb2e
refs/heads/master
2022-04-08T17:31:35.516938
2020-03-18T20:57:40
2020-03-18T20:57:40
248,061,036
0
0
null
null
null
null
UTF-8
C++
false
false
1,972
h
//======================================================================================== // // $File: //depot/devtech/15.0/plugin/source/public/interfaces/architecture/IRecoveryList.h $ // // Owner: Roey Horns // // $Author: pmbuilder $ // // $DateTime: 2019/10/11 10:48:01 $ // // $Revision: #2 $ // // $Change: 1061132 $ // // Copyright 1997-2010 Adobe Systems Incorporated. All rights reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file in accordance // with the terms of the Adobe license agreement accompanying it. If you have received // this file from a source other than Adobe, then your use, modification, or // distribution of it requires the prior written permission of Adobe. // //======================================================================================== #pragma once #ifndef __IRecoveryList__ #define __IRecoveryList__ #include "IPMUnknown.h" #include "PMString.h" #include "DocumentID.h" class IRecoveryList : public IPMUnknown { public: // Methods for Default Pub Recovery (accessed by CSession) virtual bool16 DefaultFileWasOpen() const = 0; virtual const IDFile *GetDefaultMiniSaveFile() const = 0; virtual void SetDefaultMiniSaveFile(const IDFile *file) = 0; virtual void StartDefaultFileRecovery() = 0; virtual void EndDefaultFileRecovery() = 0; virtual bool16 InDefaultFileRecovery() = 0; // Recovery Control virtual void DoRecovery() = 0; virtual bool16 InRecovery() const = 0; // Recovery List Maintainance // The doc interface could be a regular InDesign document or // book file or some other special files we may support later. //virtual void AddDocument(IPMUnknown *doc, ClassID commandID = kRecoverDocumentCmdBoss) = 0; virtual void AddDocument(IPMUnknown *doc, ClassID commandID = kInvalidClass) = 0; virtual void UpdateDocument(IPMUnknown *doc) = 0; virtual void RemoveDocument(IPMUnknown *doc) = 0; }; #endif // __IRecoveryList__
[ "steven.tong@hcl.com" ]
steven.tong@hcl.com
a8efe39ed49af6aa38ecee392c58bb3865fc8421
44bf3ced806bcd72fc2476cd15c7143b6fc81dcc
/src/blend2d/bitarray.h
28fe9f966ec98e58f63176514f14eb536fe8c6d2
[ "Zlib" ]
permissive
blend2d/blend2d
9bc48e614a0f1cda65cb0ceaafda709d4453ad85
99fc3aa9a1d113e913df67166d40d2a81bef1dcb
refs/heads/master
2023-08-30T03:10:19.645400
2023-08-28T11:40:00
2023-08-28T11:40:00
16,447,163
1,305
112
Zlib
2023-05-01T08:16:41
2014-02-02T02:01:04
C++
UTF-8
C++
false
false
18,771
h
// This file is part of Blend2D project <https://blend2d.com> // // See blend2d.h or LICENSE.md for license and copyright information // SPDX-License-Identifier: Zlib #ifndef BLEND2D_BITARRAY_H #define BLEND2D_BITARRAY_H #include "object.h" //! \addtogroup blend2d_api_globals //! \{ //! \name BLBitArray - C API //! \{ BL_BEGIN_C_DECLS BL_API BLResult BL_CDECL blBitArrayInit(BLBitArrayCore* self) BL_NOEXCEPT_C; BL_API BLResult BL_CDECL blBitArrayInitMove(BLBitArrayCore* self, BLBitArrayCore* other) BL_NOEXCEPT_C; BL_API BLResult BL_CDECL blBitArrayInitWeak(BLBitArrayCore* self, const BLBitArrayCore* other) BL_NOEXCEPT_C; BL_API BLResult BL_CDECL blBitArrayDestroy(BLBitArrayCore* self) BL_NOEXCEPT_C; BL_API BLResult BL_CDECL blBitArrayReset(BLBitArrayCore* self) BL_NOEXCEPT_C; BL_API BLResult BL_CDECL blBitArrayAssignMove(BLBitArrayCore* self, BLBitArrayCore* other) BL_NOEXCEPT_C; BL_API BLResult BL_CDECL blBitArrayAssignWeak(BLBitArrayCore* self, const BLBitArrayCore* other) BL_NOEXCEPT_C; BL_API BLResult BL_CDECL blBitArrayAssignWords(BLBitArrayCore* self, const uint32_t* wordData, uint32_t wordCount) BL_NOEXCEPT_C; BL_API bool BL_CDECL blBitArrayIsEmpty(const BLBitArrayCore* self) BL_NOEXCEPT_C; BL_API uint32_t BL_CDECL blBitArrayGetSize(const BLBitArrayCore* self) BL_NOEXCEPT_C; BL_API uint32_t BL_CDECL blBitArrayGetWordCount(const BLBitArrayCore* self) BL_NOEXCEPT_C; BL_API uint32_t BL_CDECL blBitArrayGetCapacity(const BLBitArrayCore* self) BL_NOEXCEPT_C; BL_API const uint32_t* BL_CDECL blBitArrayGetData(const BLBitArrayCore* self) BL_NOEXCEPT_C; BL_API uint32_t BL_CDECL blBitArrayGetCardinality(const BLBitArrayCore* self) BL_NOEXCEPT_C; BL_API uint32_t BL_CDECL blBitArrayGetCardinalityInRange(const BLBitArrayCore* self, uint32_t startBit, uint32_t endBit) BL_NOEXCEPT_C; BL_API bool BL_CDECL blBitArrayHasBit(const BLBitArrayCore* self, uint32_t bitIndex) BL_NOEXCEPT_C; BL_API bool BL_CDECL blBitArrayHasBitsInRange(const BLBitArrayCore* self, uint32_t startBit, uint32_t endBit) BL_NOEXCEPT_C; BL_API bool BL_CDECL blBitArraySubsumes(const BLBitArrayCore* a, const BLBitArrayCore* b) BL_NOEXCEPT_C; BL_API bool BL_CDECL blBitArrayIntersects(const BLBitArrayCore* a, const BLBitArrayCore* b) BL_NOEXCEPT_C; BL_API bool BL_CDECL blBitArrayGetRange(const BLBitArrayCore* self, uint32_t* startOut, uint32_t* endOut) BL_NOEXCEPT_C; BL_API bool BL_CDECL blBitArrayEquals(const BLBitArrayCore* a, const BLBitArrayCore* b) BL_NOEXCEPT_C; BL_API int BL_CDECL blBitArrayCompare(const BLBitArrayCore* a, const BLBitArrayCore* b) BL_NOEXCEPT_C; BL_API BLResult BL_CDECL blBitArrayClear(BLBitArrayCore* self) BL_NOEXCEPT_C; BL_API BLResult BL_CDECL blBitArrayResize(BLBitArrayCore* self, uint32_t nBits) BL_NOEXCEPT_C; BL_API BLResult BL_CDECL blBitArrayReserve(BLBitArrayCore* self, uint32_t nBits) BL_NOEXCEPT_C; BL_API BLResult BL_CDECL blBitArrayShrink(BLBitArrayCore* self) BL_NOEXCEPT_C; BL_API BLResult BL_CDECL blBitArraySetBit(BLBitArrayCore* self, uint32_t bitIndex) BL_NOEXCEPT_C; BL_API BLResult BL_CDECL blBitArrayFillRange(BLBitArrayCore* self, uint32_t startBit, uint32_t endBit) BL_NOEXCEPT_C; BL_API BLResult BL_CDECL blBitArrayFillWords(BLBitArrayCore* self, uint32_t bitIndex, const uint32_t* wordData, uint32_t wordCount) BL_NOEXCEPT_C; BL_API BLResult BL_CDECL blBitArrayClearBit(BLBitArrayCore* self, uint32_t bitIndex) BL_NOEXCEPT_C; BL_API BLResult BL_CDECL blBitArrayClearRange(BLBitArrayCore* self, uint32_t startBit, uint32_t endBit) BL_NOEXCEPT_C; BL_API BLResult BL_CDECL blBitArrayClearWord(BLBitArrayCore* self, uint32_t bitIndex, uint32_t wordValue) BL_NOEXCEPT_C; BL_API BLResult BL_CDECL blBitArrayClearWords(BLBitArrayCore* self, uint32_t bitIndex, const uint32_t* wordData, uint32_t wordCount) BL_NOEXCEPT_C; BL_API BLResult BL_CDECL blBitArrayReplaceOp(BLBitArrayCore* self, uint32_t nBits, uint32_t** dataOut) BL_NOEXCEPT_C; BL_API BLResult BL_CDECL blBitArrayReplaceBit(BLBitArrayCore* self, uint32_t bitIndex, bool bitValue) BL_NOEXCEPT_C; BL_API BLResult BL_CDECL blBitArrayReplaceWord(BLBitArrayCore* self, uint32_t bitIndex, uint32_t wordValue) BL_NOEXCEPT_C; BL_API BLResult BL_CDECL blBitArrayReplaceWords(BLBitArrayCore* self, uint32_t bitIndex, const uint32_t* wordData, uint32_t wordCount) BL_NOEXCEPT_C; BL_API BLResult BL_CDECL blBitArrayAppendBit(BLBitArrayCore* self, bool bitValue) BL_NOEXCEPT_C; BL_API BLResult BL_CDECL blBitArrayAppendWord(BLBitArrayCore* self, uint32_t wordValue) BL_NOEXCEPT_C; BL_API BLResult BL_CDECL blBitArrayAppendWords(BLBitArrayCore* self, const uint32_t* wordData, uint32_t wordCount) BL_NOEXCEPT_C; // TODO: Future API (BitArray). /* BL_API BLResult BL_CDECL blBitArrayCombine(BLBitArrayCore* dst, const BLBitArrayCore* a, const BLBitArrayCore* b, BLBooleanOp booleanOp) BL_NOEXCEPT_C; */ BL_END_C_DECLS //! BitArray container [C API]. struct BLBitArrayCore BL_CLASS_INHERITS(BLObjectCore) { BL_DEFINE_OBJECT_DETAIL BL_DEFINE_OBJECT_DCAST(BLBitArray) }; //! \} //! \cond INTERNAL //! \name BLBitArray - Internals //! \{ //! BitArray container [Impl]. struct BLBitArrayImpl BL_CLASS_INHERITS(BLObjectImpl) { //! Size in bit units. uint32_t size; //! Capacity in bit-word units. uint32_t capacity; #ifdef __cplusplus //! Pointer to array data. BL_INLINE_NODEBUG uint32_t* data() noexcept { return reinterpret_cast<uint32_t*>(this + 1); } //! Pointer to array data (const). BL_INLINE_NODEBUG const uint32_t* data() const noexcept { return reinterpret_cast<const uint32_t*>(this + 1); } #endif }; //! \} //! \endcond //! \name BLBitArray - C++ API //! \{ #ifdef __cplusplus //! BitArray container [C++ API]. class BLBitArray final : public BLBitArrayCore { public: //! \cond INTERNAL //! \name Internals //! \{ enum : uint32_t { //! Number of words that can be used by SSO representation. kSSOWordCount = 3, //! Signature of SSO representation of an empty BitArray. kSSOEmptySignature = BLObjectInfo::packTypeWithMarker(BL_OBJECT_TYPE_BIT_ARRAY) }; BL_INLINE_NODEBUG BLBitArrayImpl* _impl() const noexcept { return static_cast<BLBitArrayImpl*>(_d.impl); } //! \} //! \endcond //! \name Construction & Destruction //! \{ BL_INLINE_NODEBUG BLBitArray() noexcept { _d.initStatic(BLObjectInfo{kSSOEmptySignature}); } BL_INLINE_NODEBUG BLBitArray(BLBitArray&& other) noexcept { _d = other._d; other._d.initStatic(BLObjectInfo{kSSOEmptySignature}); } BL_INLINE_NODEBUG BLBitArray(const BLBitArray& other) noexcept { blBitArrayInitWeak(this, &other); } //! Destroys the BitArray. BL_INLINE_NODEBUG ~BLBitArray() noexcept { if (BLInternal::objectNeedsCleanup(_d.info.bits)) blBitArrayDestroy(this); } //! \} //! \name Overloaded Operators //! \{ //! Tests whether the BitArray has a content. //! //! \note This is essentially the opposite of `empty()`. BL_INLINE_NODEBUG explicit operator bool() const noexcept { return !empty(); } //! Move assignment. //! //! \note The `other` BitArray is reset by move assignment, so its state after the move operation is the same as //! a default constructed BitArray. BL_INLINE_NODEBUG BLBitArray& operator=(BLBitArray&& other) noexcept { blBitArrayAssignMove(this, &other); return *this; } //! Copy assignment, performs weak copy of the data held by the `other` BitArray. BL_INLINE_NODEBUG BLBitArray& operator=(const BLBitArray& other) noexcept { blBitArrayAssignWeak(this, &other); return *this; } BL_INLINE_NODEBUG bool operator==(const BLBitArray& other) const noexcept { return equals(other); } BL_INLINE_NODEBUG bool operator!=(const BLBitArray& other) const noexcept { return !equals(other); } BL_INLINE_NODEBUG bool operator<(const BLBitArray& other) const noexcept { return compare(other) < 0; } BL_INLINE_NODEBUG bool operator<=(const BLBitArray& other) const noexcept { return compare(other) <= 0; } BL_INLINE_NODEBUG bool operator>(const BLBitArray& other) const noexcept { return compare(other) > 0; } BL_INLINE_NODEBUG bool operator>=(const BLBitArray& other) const noexcept { return compare(other) >= 0; } //! \} //! \name Common Functionality //! \{ //! Clears the content of the BitArray and releases its data. //! //! After reset the BitArray content matches a default constructed instance. BL_INLINE_NODEBUG BLResult reset() noexcept { return blBitArrayReset(this); } //! Swaps the content of this string with the `other` string. BL_INLINE_NODEBUG void swap(BLBitArrayCore& other) noexcept { _d.swap(other._d); } //! \name Accessors //! \{ //! Tests whether the BitArray is empty (has no content). //! //! Returns `true` if the BitArray's size is zero. BL_INLINE_NODEBUG bool empty() const noexcept { return blBitArrayIsEmpty(this); } //! Returns the size of the BitArray in bits. BL_INLINE_NODEBUG uint32_t size() const noexcept { return _d.sso() ? uint32_t(_d.pField()) : _impl()->size; } //! Returns number of BitWords this BitArray uses. BL_INLINE_NODEBUG uint32_t wordCount() const noexcept { return sizeof(void*) >= 8 ? (uint32_t((uint64_t(size()) + 31u) / 32u)) : (size() / 32u + uint32_t((size() & 31u) != 0u)); } //! Returns the capacity of the BitArray in bits. BL_INLINE_NODEBUG uint32_t capacity() const noexcept { return _d.sso() ? uint32_t(kSSOWordCount * 32u) : _impl()->capacity; } //! Returns the number of bits set in the BitArray. BL_INLINE_NODEBUG uint32_t cardinality() const noexcept { return blBitArrayGetCardinality(this); } //! Returns the number of bits set in the given `[startBit, endBit)` range. BL_INLINE_NODEBUG uint32_t cardinalityInRange(uint32_t startBit, uint32_t endBit) const noexcept { return blBitArrayGetCardinalityInRange(this, startBit, endBit); } //! Returns bit data. BL_INLINE_NODEBUG const uint32_t* data() const noexcept { return _d.sso() ? _d.u32_data : _impl()->data(); } //! \} //! \name Test Operations //! \{ //! Returns a bit-value at the given `bitIndex`. BL_INLINE_NODEBUG bool hasBit(uint32_t bitIndex) const noexcept { return blBitArrayHasBit(this, bitIndex); } //! Returns whether the bit-set has at least on bit in the given `[startBit, endbit)` range. BL_INLINE_NODEBUG bool hasBitsInRange(uint32_t startBit, uint32_t endBit) const noexcept { return blBitArrayHasBitsInRange(this, startBit, endBit); } //! Returns whether this BitArray subsumes `other`. BL_INLINE_NODEBUG bool subsumes(const BLBitArrayCore& other) const noexcept { return blBitArraySubsumes(this, &other); } //! Returns whether this BitArray intersects with `other`. BL_INLINE_NODEBUG bool intersects(const BLBitArrayCore& other) const noexcept { return blBitArrayIntersects(this, &other); } //! \} //! \name Equality & Comparison //! \{ //! Returns whether this BitArray and `other` are bitwise equal. BL_INLINE_NODEBUG bool equals(const BLBitArrayCore& other) const noexcept { return blBitArrayEquals(this, &other); } //! Compares this BitArray with `other` and returns either `-1`, `0`, or `1`. BL_INLINE_NODEBUG int compare(const BLBitArrayCore& other) const noexcept { return blBitArrayCompare(this, &other); } //! \} //! \name Content Manipulation //! \{ //! Move assignment, the same as `operator=`, but returns a `BLResult` instead of `this`. BL_INLINE_NODEBUG BLResult assign(BLBitArrayCore&& other) noexcept { return blBitArrayAssignMove(this, &other); } //! Copy assignment, the same as `operator=`, but returns a `BLResult` instead of `this`. BL_INLINE_NODEBUG BLResult assign(const BLBitArrayCore& other) noexcept { return blBitArrayAssignWeak(this, &other); } //! Replaces the content of the BitArray by bits specified by `wordData` of size `wordCount` [the size is in uint32_t units]. BL_INLINE_NODEBUG BLResult assignWords(const uint32_t* wordData, uint32_t wordCount) noexcept { return blBitArrayAssignWords(this, wordData, wordCount); } //! Clears the content of the BitArray without releasing its dynamically allocated data, if possible. BL_INLINE_NODEBUG BLResult clear() noexcept { return blBitArrayClear(this); } //! Resizes the BitArray so its size matches `nBits`. BL_INLINE_NODEBUG BLResult resize(uint32_t nBits) noexcept { return blBitArrayResize(this, nBits); } //! Reserves `nBits` in the BitArray (capacity would match `nBits`) without changing its size. BL_INLINE_NODEBUG BLResult reserve(uint32_t nBits) noexcept { return blBitArrayResize(this, nBits); } //! Shrinks the capacity of the BitArray to match the actual content with the intention to save memory. BL_INLINE_NODEBUG BLResult shrink() noexcept { return blBitArrayShrink(this); } //! Sets a bit to true at the given `bitIndex`. BL_INLINE_NODEBUG BLResult setBit(uint32_t bitIndex) noexcept { return blBitArraySetBit(this, bitIndex); } //! Fills bits in `[startBit, endBit)` range to true. BL_INLINE_NODEBUG BLResult fillRange(uint32_t startBit, uint32_t endBit) noexcept { return blBitArrayFillRange(this, startBit, endBit); } //! Fills bits starting from `bitIndex` specified by `wordData` and `wordCount` to true (zeros in wordData are ignored). //! //! \note This operation uses an `OR` operator - bits in `wordData` are combined with OR operator with existing bits in BitArray. BL_INLINE_NODEBUG BLResult fillWords(uint32_t bitIndex, const uint32_t* wordData, uint32_t wordCount) noexcept { return blBitArrayFillWords(this, bitIndex, wordData, wordCount); } //! Sets a bit to false at the given `bitIndex`. BL_INLINE_NODEBUG BLResult clearBit(uint32_t bitIndex) noexcept { return blBitArrayClearBit(this, bitIndex); } //! Sets bits in `[startBit, endBit)` range to false. BL_INLINE_NODEBUG BLResult clearRange(uint32_t startBit, uint32_t endBit) noexcept { return blBitArrayClearRange(this, startBit, endBit); } //! Sets bits starting from `bitIndex` specified by `wordValue` to false (zeros in wordValue are ignored). //! //! \note This operation uses an `AND_NOT` operator - bits in `wordData` are negated and then combined with AND operator with existing bits in BitArray. BL_INLINE_NODEBUG BLResult clearWord(uint32_t bitIndex, uint32_t wordValue) noexcept { return blBitArrayClearWord(this, bitIndex, wordValue); } //! Sets bits starting from `bitIndex` specified by `wordData` and `wordCount` to false (zeros in wordData are ignored). //! //! \note This operation uses an `AND_NOT` operator - bits in `wordData` are negated and then combined with AND operator with existing bits in BitArray. BL_INLINE_NODEBUG BLResult clearWords(uint32_t bitIndex, const uint32_t* wordData, uint32_t wordCount) noexcept { return blBitArrayClearWords(this, bitIndex, wordData, wordCount); } //! Makes the BitArray mutable with the intention to replace all bits of it. //! //! \note All bits in the BitArray will be set to zero. BL_INLINE_NODEBUG BLResult replaceOp(uint32_t nBits, uint32_t** dataOut) noexcept { return blBitArrayReplaceOp(this, nBits, dataOut); } //! Replaces a bit in the BitArray at the given `bitIndex` to match `bitValue`. BL_INLINE_NODEBUG BLResult replaceBit(uint32_t bitIndex, bool bitValue) noexcept { return blBitArrayReplaceBit(this, bitIndex, bitValue); } //! Replaces bits starting from `bitIndex` to match the bits specified by `wordValue`. //! //! \note Replaced bits from BitArray are not combined by using any operator, `wordValue` is copied as is, thus //! replaces fully the existing bits. BL_INLINE_NODEBUG BLResult replaceWord(uint32_t bitIndex, uint32_t wordValue) noexcept { return blBitArrayReplaceWord(this, bitIndex, wordValue); } //! Replaces bits starting from `bitIndex` to match the bits specified by `wordData` and `wordCount`. //! //! \note Replaced bits from BitArray are not combined by using any operator, `wordData` is copied as is, thus //! replaces fully the existing bits. BL_INLINE_NODEBUG BLResult replaceWords(uint32_t bitIndex, const uint32_t* wordData, uint32_t wordCount) noexcept { return blBitArrayReplaceWords(this, bitIndex, wordData, wordCount); } //! Appends a bit `bitValue` to the BitArray. BL_INLINE_NODEBUG BLResult appendBit(bool bitValue) noexcept { return blBitArrayAppendBit(this, bitValue); } //! Appends a single word `wordValue` to the BitArray. BL_INLINE_NODEBUG BLResult appendWord(uint32_t wordValue) noexcept { return blBitArrayAppendWord(this, wordValue); } //! Appends whole words to the BitArray. BL_INLINE_NODEBUG BLResult appendWords(const uint32_t* wordData, uint32_t wordCount) noexcept { return blBitArrayAppendWords(this, wordData, wordCount); } /* // TODO: Future API (BitArray). BL_INLINE_NODEBUG BLResult and_(const BLBitArrayCore& other) noexcept { return blBitArrayCombine(this, this, &other, BL_BOOLEAN_OP_AND); } BL_INLINE_NODEBUG BLResult or_(const BLBitArrayCore& other) noexcept { return blBitArrayCombine(this, this, &other, BL_BOOLEAN_OP_OR); } BL_INLINE_NODEBUG BLResult xor_(const BLBitArrayCore& other) noexcept { return blBitArrayCombine(this, this, &other, BL_BOOLEAN_OP_XOR); } BL_INLINE_NODEBUG BLResult andNot(const BLBitArrayCore& other) noexcept { return blBitArrayCombine(this, this, &other, BL_BOOLEAN_OP_AND_NOT); } BL_INLINE_NODEBUG BLResult notAnd(const BLBitArrayCore& other) noexcept { return blBitArrayCombine(this, this, &other, BL_BOOLEAN_OP_NOT_AND); } BL_INLINE_NODEBUG BLResult combine(const BLBitArrayCore& other, BLBooleanOp booleanOp) noexcept { return blBitArrayCombine(this, this, &other, booleanOp); } static BL_INLINE_NODEBUG BLResult and_(BLBitArrayCore& dst, const BLBitArrayCore& a, const BLBitArrayCore& b) noexcept { return blBitArrayCombine(&dst, &a, &b, BL_BOOLEAN_OP_AND); } static BL_INLINE_NODEBUG BLResult or_(BLBitArrayCore& dst, const BLBitArrayCore& a, const BLBitArrayCore& b) noexcept { return blBitArrayCombine(&dst, &a, &b, BL_BOOLEAN_OP_OR); } static BL_INLINE_NODEBUG BLResult xor_(BLBitArrayCore& dst, const BLBitArrayCore& a, const BLBitArrayCore& b) noexcept { return blBitArrayCombine(&dst, &a, &b, BL_BOOLEAN_OP_XOR); } static BL_INLINE_NODEBUG BLResult andNot(BLBitArrayCore& dst, const BLBitArrayCore& a, const BLBitArrayCore& b) noexcept { return blBitArrayCombine(&dst, &a, &b, BL_BOOLEAN_OP_AND_NOT); } static BL_INLINE_NODEBUG BLResult notAnd(BLBitArrayCore& dst, const BLBitArrayCore& a, const BLBitArrayCore& b) noexcept { return blBitArrayCombine(&dst, &a, &b, BL_BOOLEAN_OP_NOT_AND); } static BL_INLINE_NODEBUG BLResult combine(BLBitArrayCore& dst, const BLBitArrayCore& a, const BLBitArrayCore& b, BLBooleanOp booleanOp) noexcept { return blBitArrayCombine(&dst, &a, &b, booleanOp); } */ //! \} }; #endif //! \} //! \} #endif // BLEND2D_BITARRAY_H
[ "kobalicek.petr@gmail.com" ]
kobalicek.petr@gmail.com
55ecc547b8fc58ad1b17429874cda8c64de397e6
3052e22574a9a8f36d3aa9ef8d7fcfd67808df31
/test/view/ints.cpp
cb4511ad75a14813ad7b7eec085218aa8f51241c
[ "NCSA", "MIT", "BSL-1.0", "LicenseRef-scancode-mit-old-style", "LicenseRef-scancode-other-permissive" ]
permissive
krzysztof-jusiak/range-v3
35bc90f6ede2cd03cf1896e121237a46a71cdd4e
565394cc0c067b8b0bdfe00e1bbe94edc8378314
refs/heads/master
2021-01-18T20:06:21.519869
2016-04-21T15:36:54
2016-04-21T15:36:54
56,779,437
0
0
null
2016-04-21T14:15:27
2016-04-21T14:15:27
null
UTF-8
C++
false
false
2,398
cpp
// Range v3 library // // Copyright Eric Niebler 2014 // // Use, modification and distribution is subject to the // Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Project home: https://github.com/ericniebler/range-v3 // #include <range/v3/core.hpp> #include <range/v3/view/ints.hpp> #include <range/v3/view/take.hpp> #include <range/v3/view/indirect.hpp> #include "../simple_test.hpp" #include "../test_utils.hpp" #include "../test_iterators.hpp" int main() { using namespace ranges; ::check_equal(view::ints | view::take(10), {0,1,2,3,4,5,6,7,8,9}); ::check_equal(view::ints(0) | view::take(10), {0,1,2,3,4,5,6,7,8,9}); ::check_equal(view::ints(0,9), {0,1,2,3,4,5,6,7,8}); ::check_equal(view::closed_ints(0,9), {0,1,2,3,4,5,6,7,8,9}); ::check_equal(view::ints(1,10), {1,2,3,4,5,6,7,8,9}); ::check_equal(view::closed_ints(1,10), {1,2,3,4,5,6,7,8,9,10}); auto chars = view::ints(std::numeric_limits<char>::min(), std::numeric_limits<char>::max()); static_assert(Same<int, range_difference_t<decltype(chars)>>(), ""); ::models<concepts::RandomAccessView>(chars); models<concepts::BoundedView>(chars); auto shorts = view::ints(std::numeric_limits<unsigned short>::min(), std::numeric_limits<unsigned short>::max()); models<concepts::BoundedView>(shorts); static_assert(Same<int, range_difference_t<decltype(shorts)>>(), ""); auto uints = view::closed_ints( std::numeric_limits<std::uint32_t>::min(), std::numeric_limits<std::uint32_t>::max()); models<concepts::BoundedView>(uints); static_assert(Same<std::int64_t, range_difference_t<decltype(uints)>>(), ""); static_assert(Same<std::uint64_t, range_size_t<decltype(uints)>>(), ""); CHECK(uints.size() == (static_cast<uint64_t>(std::numeric_limits<std::uint32_t>::max()) + 1)); auto ints = view::closed_ints( std::numeric_limits<std::int32_t>::min(), std::numeric_limits<std::int32_t>::max()); static_assert(Same<std::int64_t, range_difference_t<decltype(ints)>>(), ""); static_assert(Same<std::uint64_t, range_size_t<decltype(ints)>>(), ""); CHECK(ints.size() == (static_cast<uint64_t>(std::numeric_limits<std::uint32_t>::max()) + 1)); return ::test_result(); }
[ "krzysztof@jusiak.net" ]
krzysztof@jusiak.net
0f16cc5ea0c3a0319907371b6fe622320371203f
529a4f10d008553636fb36a087684297cebee88e
/algorithm/cgal/DilateXY.h
3f064033d0ff0393c2ac6d21387bbcdd705fbe3b
[ "MIT" ]
permissive
jsxcad/JSxCAD
fba3f55a5b442d078814fc727f01c5b18e03545e
962689c323d29b4ef97ec9fcc95218e6ec011a51
refs/heads/master
2023-08-09T17:58:35.062711
2023-08-03T14:41:52
2023-08-03T14:41:52
173,755,199
36
13
MIT
2023-09-11T15:07:13
2019-03-04T13:59:33
JavaScript
UTF-8
C++
false
false
1,441
h
#include <CGAL/Nef_polyhedron_3.h> #include <CGAL/minkowski_sum_3.h> int DilateXY(Geometry* geometry, double amount) { typedef CGAL::Nef_polyhedron_3<Kernel> Nef_polyhedron; size_t size = geometry->getSize(); geometry->copyInputMeshesToOutputMeshes(); geometry->transformToAbsoluteFrame(); Nef_polyhedron tool; // Build a rough circle in XY. { const double segments = 16; Points points; for (double a = 0; a < CGAL_PI * 2; a += CGAL_PI / segments) { points.push_back(Point(compute_approximate_point_value(sin(-a) * amount), compute_approximate_point_value(cos(-a) * amount), 0)); } typedef Points::iterator point_iterator; typedef std::pair<point_iterator, point_iterator> point_range; typedef std::list<point_range> polyline; polyline poly; poly.push_back(point_range(points.begin(), points.end())); tool = Nef_polyhedron(poly.begin(), poly.end(), Nef_polyhedron::Polylines_tag()); } for (size_t nth = 0; nth < size; nth++) { if (geometry->type(nth) != GEOMETRY_MESH) { continue; } Surface_mesh& mesh = geometry->mesh(nth); Nef_polyhedron nef(mesh); Nef_polyhedron result = CGAL::minkowski_sum_3(nef, tool); mesh.clear(); CGAL::convert_nef_polyhedron_to_polygon_mesh(result, mesh, true); } geometry->transformToLocalFrame(); return STATUS_OK; }
[ "brian.spilsbury@gmail.com" ]
brian.spilsbury@gmail.com
e550cc89d58fd577b9fef7ff1efb178850126569
f0ae9b02d6b471e2631e66c84e880be583c9ef97
/plugin/hook.h
caf59269d3e8961526b00b81d58fdcf1df9f5dd6
[ "BSD-2-Clause" ]
permissive
Bloodhacker/samp-plugin-crashdetect
a995386735d38ce29d42cce8699d549543f175aa
96a001f754ed90604e536af8b64cb36e20755667
refs/heads/master
2021-01-16T17:10:17.084452
2013-08-31T17:19:46
2013-08-31T17:19:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,801
h
// Copyright (c) 2011-2013 Zeex // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #ifndef HOOK_H #define HOOK_H #include <cstddef> #if !defined _M_IX86 && !defined __i386__ #error Unsupported architecture #endif class Hook { public: static const std::size_t kJmpInstrSize = 5; Hook(); Hook(void *src, void *dst); ~Hook(); bool Install(); bool Install(void *src, void *dst); bool IsInstalled() const; bool Remove(); static void *GetTargetAddress(void *jmp); // Temporary Remove() class ScopedRemove { public: ScopedRemove(Hook *jmp) : jmp_(jmp), removed_(jmp->Remove()) { // nothing } ~ScopedRemove() { if (removed_) { jmp_->Install(); } } private: ScopedRemove(const ScopedRemove &); void operator=(const ScopedRemove &); private: Hook *jmp_; bool removed_; }; // Temporary Install() class ScopedInstall { public: ScopedInstall(Hook *jmp) : jmp_(jmp), installed_(jmp->Install()) { // nothing } ~ScopedInstall() { if (installed_) { jmp_->Remove(); } } private: ScopedInstall(const ScopedInstall &); void operator=(const ScopedInstall &); private: Hook *jmp_; bool installed_; }; private: static void Unprotect(void *address, std::size_t size); private: Hook(const Hook &); void operator=(const Hook &); private: void *src_; void *dst_; unsigned char code_[5]; bool installed_; }; #endif
[ "zeex@rocketmail.com" ]
zeex@rocketmail.com
1187934589becdabe6e8787cef140290c7e1a622
563def4f397c5e130fb9282d72cbe9a942522f99
/outdir/nv_small/spec/manual/NVDLA_GEC_reg_c/ordt_pio_common.cpp
775d53d32f0ba515a915bc16636b5b7a7754e730
[]
no_license
Allahfan/nvdla_change
8311f581b6776cb531e504d6998ab8da583e36e2
cadd45ead29ff7a11970dc3f3b19b22e84d43fcb
refs/heads/master
2020-08-16T00:42:34.123345
2019-10-16T01:50:52
2019-10-16T01:50:52
215,432,413
0
0
null
null
null
null
UTF-8
C++
false
false
3,107
cpp
// Ordt 171103.01 autogenerated file // Input: NVDLA_GEC.rdl // Parms: opendla.parms // Date: Tue Jun 25 16:49:26 CST 2019 // #include "ordt_pio_common.hpp" // ------------------ ordt_data methods ------------------ ordt_data::ordt_data() : std::vector<uint32_t>() { } ordt_data::ordt_data(int _size, uint32_t _data) : std::vector<uint32_t>(_size, _data) { } ordt_data::ordt_data(const ordt_data& _data) : std::vector<uint32_t>(_data) { } void ordt_data::set_slice(int lobit, int size, const ordt_data& update) { int data_size = this->size() * 32; if ((lobit % 32) > 0) { std::cout << "ERROR set_slice: non 32b aligned slices are not supported" << "\n"; return; } int hibit = lobit + size - 1; int loword = lobit / 32; int hiword = hibit / 32; if (hibit > data_size - 1) { std::cout << "ERROR set_slice: specified slice is not contained in data" << "\n"; return; } int update_idx=0; for (int idx=loword; idx < hiword + 1; idx++) { if (idx == hiword) { int modsize = hibit - hiword*32 + 1; uint32_t mask = (modsize == 32)? 0xffffffff : (1 << modsize) - 1; this->at(idx) = (this->at(idx) & ~mask) ^ (update.at(update_idx) & mask); } else this->at(idx) = update.at(update_idx); update_idx++; } } void ordt_data::get_slice(int lobit, int size, ordt_data& slice_out) const { int data_size = this->size() * 32; if ((lobit % 32) > 0) { std::cout << "ERROR set_slice: non 32b aligned large fields are not supported" << "\n"; return; } slice_out.clear(); int hibit = lobit + size - 1; int loword = lobit / 32; int hiword = hibit / 32; if (hibit > data_size - 1) { std::cout << "ERROR set_slice: specified slice is not contained in data" << "\n"; return; } int out_idx=0; for (int idx=loword; idx < hiword + 1; idx++) { if (idx == hiword) { int modsize = hibit - hiword*32 + 1; uint32_t mask = (modsize == 32)? 0xffffffff : (1 << modsize) - 1; slice_out.at(out_idx) = (this->at(idx) & mask); } else slice_out.at(out_idx) = this->at(idx); out_idx++; } return; } std::string ordt_data::to_string() const { std::stringstream ss; ss << "{" << std::hex << std::showbase; for (int idx=this->size() - 1; idx >= 0; idx--) ss << " " << this->at(idx); ss << " }"; return ss.str(); } ordt_data& ordt_data::operator=(const uint32_t rhs) { this->assign(this->size(), rhs); return *this; } ordt_data ordt_data::operator~() { ordt_data temp; for (int idx=0; idx<this->size(); idx++) temp.at(idx) = ~ this->at(idx); return temp; } ordt_data ordt_data::operator&(const ordt_data& rhs) { ordt_data temp; for (int idx=0; idx<this->size(); idx++) if (idx < rhs.size()) temp.at(idx) = this->at(idx) & rhs.at(idx); else temp.at(idx) = 0; return temp; } ordt_data ordt_data::operator|(const ordt_data& rhs) { ordt_data temp; for (int idx=0; idx<this->size(); idx++) if (idx < rhs.size()) temp.at(idx) = this->at(idx) | rhs.at(idx); else temp.at(idx) = this->at(idx); return temp; }
[ "1978573841@qq.com" ]
1978573841@qq.com
d8d0cb1d0a4ac59feed63366c58a1270f7874b19
99f10345da76d84c1d4400e3798bde8ca72d6875
/src/methods.cpp
ade1ebcae7bab117d79246fc29f7bea6c8bd3694
[]
no_license
Drvanon/tinyweb
caee17ab6f09cdd94e6e7e7ef6dc8dc98e86186e
ec522028f9843ca7f93eef2537f0191dbbe1e95b
refs/heads/master
2020-08-04T16:18:19.874413
2020-06-15T14:38:20
2020-06-15T14:38:20
212,199,898
0
0
null
null
null
null
UTF-8
C++
false
false
1,313
cpp
#include "methods.h" namespace tinyweb { METHODS string_to_method (std::string str) { METHODS method; if (str == "GET") { method = METHODS::GET; } else if (str == "HEAD") { method = METHODS::HEAD; } else if (str == "POST") { method = METHODS::POST; } else if (str == "PUT") { method = METHODS::PUT; } else if (str == "DELETE") { method = METHODS::DELETE; } else if (str == "TRACE") { method = METHODS::TRACE; } else if (str == "CONNECT") { method = METHODS::CONNECT; } return method; } std::string method_to_string (METHODS method) { std::string str; if (method == METHODS::GET) { str == "GET"; } else if (method == METHODS::HEAD) { str == "HEAD"; } else if (method == METHODS::POST) { str == "POST"; } else if (method == METHODS::PUT) { str == "PUT"; } else if (method == METHODS::DELETE) { str == "DELETE"; } else if (method == METHODS::TRACE) { str == "TRACE"; } else if (method == METHODS::CONNECT) { str == "CONNECT"; } return str; } } // namespace tinyweb
[ "robin@gridt.org" ]
robin@gridt.org
582bb799285e8290274d2bfa819fc5cbbf134697
19048fa3c92b3a01209de30023afd9e82f19284d
/2018组队/2013-2014 ACM-ICPC Northeastern European Regional Contest (NEERC 13)/e.cpp
07dbe7f78f8785ad53515c9cce5b007dd6ede895
[]
no_license
fblogy/code
b73d1172f4e58f9ecbe1ffbcac925070cbd10881
ae8bded0caced69d0248bfcbd2396d6aa745820a
refs/heads/master
2020-03-25T16:53:03.864473
2019-07-01T07:57:31
2019-07-01T07:57:31
134,960,799
0
0
null
null
null
null
UTF-8
C++
false
false
2,920
cpp
#include<bits/stdc++.h> using namespace std; #define fi first #define se second #define mp make_pair #define pb push_back #define rep(i, a, b) for(int i=(a); i<(b); i++) #define per(i, a, b) for(int i=(b)-1; i>=(a); i--) #define sz(a) (int)a.size() #define de(a) cout << #a << " = " << a << endl #define dd(a) cout << #a << " = " << a << " " #define all(a) a.begin(), a.end() #define pw(x) (1ll<<(x)) #define endl "\n" typedef double db; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pii; typedef vector<int> vi; const int P = 1e9 + 7; int add(int a, int b) {if((a += b) >= P) a -= P; return a;} int sub(int a, int b) {if((a -= b) < 0) a += P; return a;} int mul(int a, int b) {return 1ll * a * b % P;} int kpow(int a, int b) {int r=1;for(;b;b>>=1,a=mul(a,a)) {if(b&1)r=mul(r,a);}return r;} //---- const int N = 100005; int n, x[N], y[N], p1, p2, p; vector<pair<db, db> > V[2]; db ansx, ansy1, ansy2, lo, ro, m1, m2, s1, s2; db Y (db x, int p, int o) { assert(p < sz(V[o])); if (p == 0) return V[o][0].se; if (V[o][p].fi != V[o][p-1].fi) { return V[o][p-1].se + (x - V[o][p-1].fi) * (V[o][p].se - V[o][p-1].se) / (V[o][p].fi - V[o][p-1].fi); }else return V[o][p].se; } db cal(db a, db b) { if (b >= x[p2]) return -pw(60); int t1 = lower_bound(all(V[0]), mp(a, 1.0 * pw(30))) - V[0].begin(); int t2 = lower_bound(all(V[0]), mp(b, 1.0 * pw(30))) - V[0].begin(); if (t1 == sz(V[0]) || t2 == sz(V[0])) return -pw(60); db ma = min(Y(a, t1, 0), Y(b, t2, 0)); t1 = lower_bound(all(V[1]), mp(a, 1.0 * pw(30))) - V[1].begin(); t2 = lower_bound(all(V[1]), mp(b, 1.0 * pw(30))) - V[1].begin(); if (t1 == sz(V[1]) || t2 == sz(V[1])) return -pw(60); db mi = max(Y(a, t1, 1), Y(b, t2, 1)); if (ma < mi) return -pw(60); ansy1 = mi; ansy2 = ma; return (b - a) * (ma - mi); } db solve(db w) { db lo = x[p1], ro = x[p2], s1, s2; rep(tim, 0, 100) { db m1 = (lo + lo + ro) / 3, m2 = (lo + ro + ro) / 3; s1 = cal(m1, m1 + w); s2 = cal(m2, m2 + w); //dd(m1);de(m2);dd(s1);de(s2); if (s1 < s2) lo = m1; else ro = m2; } ansx = lo; return s1; } int main() { freopen("easy.in","r",stdin); // freopen("easy.out","w",stdout); std::ios::sync_with_stdio(false); std::cin.tie(0); cout << setiosflags(ios::fixed); cout << setprecision(10); cin >> n; rep(i, 1, n+1) cin >> x[i] >> y[i]; p1 = min_element(x+1, x+n+1) - x; p2 = max_element(x+1, x+n+1) - x; p = p1; while (p != p2) { V[0].pb(mp(x[p], y[p])); p++; if (p > n) p = 1; } V[0].pb(mp(x[p], y[p])); while (p != p1) { V[1].pb(mp(x[p], y[p])); p++; if (p > n) p = 1; } V[1].pb(mp(x[p], y[p])); reverse(all(V[1])); //de(solve(2)); //return 0; lo = 0; ro = x[p2] - x[p1]; rep(tim, 0, 100) { m1 = (lo + lo + ro) / 3; m2 = (lo + ro + ro) / 3; s1 = solve(m1); s2 = solve(m2); if (s1 < s2) lo = m1; else ro = m2; } cout << ansx << " " << ansy1 << " " << ansx + lo << " " << ansy2; return 0; }
[ "39649744+fblogy@users.noreply.github.com" ]
39649744+fblogy@users.noreply.github.com
adae3f407367db6fc5eb491c20ea994749db384c
a0b5820634469419965dd6b2439f29f3603c4c8e
/Hobot_conf/driver/c++/src/driver_common.cc
7dec67ee45bdc27b45612572c4a524932a65c5dc
[ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ]
permissive
zhuzy-xys/conf_schedule
84ad343e36f2cadf030247962409ee3ac5f5206c
1d5ca0e7f8e6131141b075d370f0e186401bb377
refs/heads/master
2020-03-16T21:23:46.170662
2018-06-04T14:59:13
2018-06-04T14:59:13
132,997,396
0
0
null
null
null
null
UTF-8
C++
false
false
873
cc
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "hconf_errno.h" #include "driver_common.h" int init_hconf_batch_nodes(hconf_batch_nodes *bnodes) { if (NULL == bnodes) return HCONF_ERR_PARAM; memset((void*)bnodes, 0, sizeof(hconf_batch_nodes)); return HCONF_OK; } int destroy_hconf_batch_nodes(hconf_batch_nodes *bnodes) { if (NULL == bnodes) return HCONF_ERR_PARAM; free_hconf_batch_nodes(bnodes, bnodes->count); return HCONF_OK; } void free_hconf_batch_nodes(hconf_batch_nodes *bnodes, size_t free_size) { if (NULL == bnodes) return; for (size_t i = 0; i < free_size; ++i) { free(bnodes->nodes[i].key); free(bnodes->nodes[i].value); bnodes->nodes[i].key = NULL; bnodes->nodes[i].value = NULL; } free(bnodes->nodes); bnodes->nodes = NULL; bnodes->count = 0; }
[ "17702514160@163.com" ]
17702514160@163.com
2a27df84d68a1be1402d24d1f6ef7bf22d147f5b
b677894966f2ae2d0585a31f163a362e41a3eae0
/ns3/ns-3.26/src/lte/model/epc-enb-s1-sap.h
2d3224eb9bf808e04da6c80f787f2b7518c40345
[ "LicenseRef-scancode-free-unknown", "GPL-2.0-only", "Apache-2.0" ]
permissive
cyliustack/clusim
667a9eef2e1ea8dad1511fd405f3191d150a04a8
cbedcf671ba19fded26e4776c0e068f81f068dfd
refs/heads/master
2022-10-06T20:14:43.052930
2022-10-01T19:42:19
2022-10-01T19:42:19
99,692,344
7
3
Apache-2.0
2018-07-04T10:09:24
2017-08-08T12:51:33
Python
UTF-8
C++
false
false
6,292
h
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2012 Centre Tecnologic de Telecomunicacions de Catalunya (CTTC) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * 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 * * Author: Nicola Baldo <nbaldo@cttc.es> */ #ifndef EPC_ENB_S1_SAP_H #define EPC_ENB_S1_SAP_H #include <list> #include <stdint.h> #include <ns3/eps-bearer.h> #include <ns3/ipv4-address.h> namespace ns3 { /** * This class implements the Service Access Point (SAP) between the * LteEnbRrc and the EpcEnbApplication. In particular, this class implements the * Provider part of the SAP, i.e., the methods exported by the * EpcEnbApplication and called by the LteEnbRrc. * */ class EpcEnbS1SapProvider { public: virtual ~EpcEnbS1SapProvider (); /** * * * \param imsi * \param rnti */ virtual void InitialUeMessage (uint64_t imsi, uint16_t rnti) = 0; /** * \brief Triggers epc-enb-application to send ERAB Release Indication message towards MME * \param imsi the UE IMSI * \param rnti the UE RNTI * \param bearerId Bearer Identity which is to be de-activated */ virtual void DoSendReleaseIndication (uint64_t imsi, uint16_t rnti, uint8_t bearerId) = 0; struct BearerToBeSwitched { uint8_t epsBearerId; uint32_t teid; }; struct PathSwitchRequestParameters { uint16_t rnti; uint16_t cellId; uint32_t mmeUeS1Id; std::list<BearerToBeSwitched> bearersToBeSwitched; }; virtual void PathSwitchRequest (PathSwitchRequestParameters params) = 0; /** * release UE context at the S1 Application of the source eNB after * reception of the UE CONTEXT RELEASE X2 message from the target eNB * during X2-based handover * * \param rnti */ virtual void UeContextRelease (uint16_t rnti) = 0; }; /** * This class implements the Service Access Point (SAP) between the * LteEnbRrc and the EpcEnbApplication. In particular, this class implements the * User part of the SAP, i.e., the methods exported by the LteEnbRrc * and called by the EpcEnbApplication. * */ class EpcEnbS1SapUser { public: virtual ~EpcEnbS1SapUser (); /** * Parameters passed to DataRadioBearerSetupRequest () * */ struct DataRadioBearerSetupRequestParameters { uint16_t rnti; /**< the RNTI identifying the UE for which the DataRadioBearer is to be created */ EpsBearer bearer; /**< the characteristics of the bearer to be set up */ uint8_t bearerId; /**< the EPS Bearer Identifier */ uint32_t gtpTeid; /**< S1-bearer GTP tunnel endpoint identifier, see 36.423 9.2.1 */ Ipv4Address transportLayerAddress; /**< IP Address of the SGW, see 36.423 9.2.1 */ }; /** * request the setup of a DataRadioBearer * */ virtual void DataRadioBearerSetupRequest (DataRadioBearerSetupRequestParameters params) = 0; struct PathSwitchRequestAcknowledgeParameters { uint16_t rnti; }; virtual void PathSwitchRequestAcknowledge (PathSwitchRequestAcknowledgeParameters params) = 0; }; /** * Template for the implementation of the EpcEnbS1SapProvider as a member * of an owner class of type C to which all methods are forwarded * */ template <class C> class MemberEpcEnbS1SapProvider : public EpcEnbS1SapProvider { public: MemberEpcEnbS1SapProvider (C* owner); // inherited from EpcEnbS1SapProvider virtual void InitialUeMessage (uint64_t imsi, uint16_t rnti); virtual void DoSendReleaseIndication (uint64_t imsi, uint16_t rnti, uint8_t bearerId); virtual void PathSwitchRequest (PathSwitchRequestParameters params); virtual void UeContextRelease (uint16_t rnti); private: MemberEpcEnbS1SapProvider (); C* m_owner; }; template <class C> MemberEpcEnbS1SapProvider<C>::MemberEpcEnbS1SapProvider (C* owner) : m_owner (owner) { } template <class C> MemberEpcEnbS1SapProvider<C>::MemberEpcEnbS1SapProvider () { } template <class C> void MemberEpcEnbS1SapProvider<C>::InitialUeMessage (uint64_t imsi, uint16_t rnti) { m_owner->DoInitialUeMessage (imsi, rnti); } template <class C> void MemberEpcEnbS1SapProvider<C>::DoSendReleaseIndication (uint64_t imsi, uint16_t rnti, uint8_t bearerId) { m_owner->DoReleaseIndication (imsi, rnti, bearerId); } template <class C> void MemberEpcEnbS1SapProvider<C>::PathSwitchRequest (PathSwitchRequestParameters params) { m_owner->DoPathSwitchRequest (params); } template <class C> void MemberEpcEnbS1SapProvider<C>::UeContextRelease (uint16_t rnti) { m_owner->DoUeContextRelease (rnti); } /** * Template for the implementation of the EpcEnbS1SapUser as a member * of an owner class of type C to which all methods are forwarded * */ template <class C> class MemberEpcEnbS1SapUser : public EpcEnbS1SapUser { public: MemberEpcEnbS1SapUser (C* owner); // inherited from EpcEnbS1SapUser virtual void DataRadioBearerSetupRequest (DataRadioBearerSetupRequestParameters params); virtual void PathSwitchRequestAcknowledge (PathSwitchRequestAcknowledgeParameters params); private: MemberEpcEnbS1SapUser (); C* m_owner; }; template <class C> MemberEpcEnbS1SapUser<C>::MemberEpcEnbS1SapUser (C* owner) : m_owner (owner) { } template <class C> MemberEpcEnbS1SapUser<C>::MemberEpcEnbS1SapUser () { } template <class C> void MemberEpcEnbS1SapUser<C>::DataRadioBearerSetupRequest (DataRadioBearerSetupRequestParameters params) { m_owner->DoDataRadioBearerSetupRequest (params); } template <class C> void MemberEpcEnbS1SapUser<C>::PathSwitchRequestAcknowledge (PathSwitchRequestAcknowledgeParameters params) { m_owner->DoPathSwitchRequestAcknowledge (params); } } // namespace ns3 #endif // EPC_ENB_S1_SAP_H
[ "you@example.com" ]
you@example.com
2ca00c247f1b73dd8f8cdb6ad83ca7a4814de196
60d718b01b6c1adbab2ec072836e5826c3985f3a
/QxOrm/src/QxDao/QxSqlRelationParams.cpp
d3628a4371ec1027945ee1edb0f7154c3c9227cb
[]
no_license
jpush/jchat-windows
1084127d0ce39ad00a344661f265e5d65389c186
e782268c8d04ffad5d6e9a69308fad30b583603e
refs/heads/master
2022-01-14T06:35:47.571133
2019-05-14T05:32:42
2019-05-14T05:42:19
106,393,361
19
4
null
null
null
null
UTF-8
C++
false
false
2,955
cpp
/**************************************************************************** ** ** http://www.qxorm.com/ ** Copyright (C) 2013 Lionel Marty (contact@qxorm.com) ** ** This file is part of the QxOrm library ** ** This software is provided 'as-is', without any express or implied ** warranty. In no event will the authors be held liable for any ** damages arising from the use of this software ** ** Commercial Usage ** Licensees holding valid commercial QxOrm licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Lionel Marty ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file 'license.gpl3.txt' included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met : http://www.gnu.org/copyleft/gpl.html ** ** If you are unsure which license is appropriate for your use, or ** if you have questions regarding the use of this file, please contact : ** contact@qxorm.com ** ****************************************************************************/ #include <QxPrecompiled.h> #include <QxDao/QxSqlRelationParams.h> #include <QxDao/QxSqlRelationLinked.h> #include <QxDao/IxSqlQueryBuilder.h> #include <QxDao/IxSqlRelation.h> #include <QxMemLeak/mem_leak.h> namespace qx { QxSqlRelationParams::QxSqlRelationParams() : m_lIndex(0), m_lIndexOwner(0), m_lOffset(0), m_sql(NULL), m_builder(NULL), m_query(NULL), m_database(NULL), m_pOwner(NULL), m_eJoinType(qx::dao::sql_join::no_join), m_pRelationX(NULL), m_eSaveMode(qx::dao::save_mode::e_check_insert_or_update), m_bRecursiveMode(false), m_pColumns(NULL) { ; } QxSqlRelationParams::QxSqlRelationParams(long lIndex, long lOffset, QString * sql, IxSqlQueryBuilder * builder, QSqlQuery * query, void * pOwner) : m_lIndex(lIndex), m_lIndexOwner(0), m_lOffset(lOffset), m_sql(sql), m_builder(builder), m_query(query), m_database(NULL), m_pOwner(pOwner), m_eJoinType(qx::dao::sql_join::no_join), m_pRelationX(NULL), m_eSaveMode(qx::dao::save_mode::e_check_insert_or_update), m_bRecursiveMode(false), m_pColumns(NULL) { ; } QxSqlRelationParams::QxSqlRelationParams(long lIndex, long lOffset, QString * sql, IxSqlQueryBuilder * builder, QSqlQuery * query, void * pOwner, const QVariant & vId) : m_vId(vId), m_lIndex(lIndex), m_lIndexOwner(0), m_lOffset(lOffset), m_sql(sql), m_builder(builder), m_query(query), m_database(NULL), m_pOwner(pOwner), m_eJoinType(qx::dao::sql_join::no_join), m_pRelationX(NULL), m_eSaveMode(qx::dao::save_mode::e_check_insert_or_update), m_bRecursiveMode(false), m_pColumns(NULL) { ; } QxSqlRelationParams::~QxSqlRelationParams() { ; } } // namespace qx
[ "wangshun@jiguang.cn" ]
wangshun@jiguang.cn
ff5aea193b1ace4cf434caa5988825afce526de3
3a3b2ff8f104bc68a47408fb1fe43a14371222a1
/include/GLUtils.h
f440da9b44f793628b691c7860defd880f16f877
[]
no_license
easterbunny273/BambooEngine
33ef13ebd3be60ff3fffbf314a8a723ca448cee7
f2cef8a95f56091a872a03faa41be4e79a1c8b0a
refs/heads/master
2020-04-10T15:18:05.783569
2012-10-28T22:34:09
2012-10-28T22:34:09
2,694,222
0
0
null
null
null
null
UTF-8
C++
false
false
2,555
h
/* * header file for Logger class * written by: christian moellinger <ch.moellinger@gmail.com> * written by: florian spechtenhauser <florian.spechtenhauser@gmail.com> * 07/2011, Project Cube */ #ifndef __COMMON_OPENGL_HEADER #define __COMMON_OPENGL_HEADER //include extension wrapper - important: necessary to include BEFORE glfw to prevent compile errors #include <GL/glew.h> //include glfw //#define GLFW_NO_GLU //#include <GL/glfw.h> namespace GLUtils { //helper function for translating glerrors to char* inline const char *TranslateGLerror(GLenum error) { switch (error) { case GL_INVALID_ENUM: return "GL_INVALID_ENUM"; break; case GL_INVALID_VALUE: return "GL_INVALID_VALUE"; break; case GL_INVALID_OPERATION: return "GL_INVALID_OPERATION"; break; case GL_STACK_OVERFLOW: return "GL_STACK_OVERFLOW"; break; case GL_STACK_UNDERFLOW: return "GL_STACK_UNDERFLOW"; break; case GL_OUT_OF_MEMORY: return "GL_OUT_OF_MEMORY"; break; case GL_TABLE_TOO_LARGE: return "GL_TABLE_TOO_LARGE"; break; default: return "unknown GL error"; break; } } //helper function for translating glerrors to char* inline const char *TranslateFBOStatus(GLenum status) { switch (status) { case GL_FRAMEBUFFER_UNDEFINED: return "GL_FRAMEBUFFER_UNDEFINED"; break; case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: return "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT"; break; case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: return "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"; break; case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: return "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER"; break; case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: return "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER"; break; case GL_FRAMEBUFFER_UNSUPPORTED: return "GL_FRAMEBUFFER_UNSUPPORTED"; break; case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: return "GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE"; break; case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: return "GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS"; break; default: return "unknown fbo status"; break; } } } #endif
[ "ch.moellinger@gmail.com" ]
ch.moellinger@gmail.com
46f5fa8b6b7a6ca4293269043aca818aa3fa2ba0
9bf063f6c46777d15e82a1ab45d5a03449412fe4
/rewards/RewardRuleResolver.cpp
3aaa91fb9fd62c2f04783ef47cdf9bcc3fce120b
[]
no_license
arctgarg/rewards_calculator
7b68e4a9497ab3e4846f80eb7da64bb1c322cdd8
ebbb5e3292652f6385a7afacad54c6ca84e175cf
refs/heads/master
2021-01-07T21:59:48.187876
2020-02-24T18:00:29
2020-02-24T18:00:29
241,831,882
0
0
null
null
null
null
UTF-8
C++
false
false
1,828
cpp
// // Created by agarg145 on 2/16/20. // #include "RewardRuleResolver.h" #include "CSVReader.h" #include <math.h> #include <iostream> using std::vector; RewardRule RewardRuleResolver::findApplicableRule(const Transaction &transaction) { int matchingParamterCount = 0; RewardRule matchingRule; for(auto rule : this->rules) { int count = this->getMatchingParametersCount(rule, transaction); if(count > matchingParamterCount) { matchingRule = rule; matchingParamterCount = count; } } return matchingRule; } RewardRuleResolver::RewardRuleResolver(vector<RewardRule> rules) { this->rules = rules; } int RewardRuleResolver::getMatchingParametersCount(const RewardRule &rule, const Transaction transaction) { int matchingParameterCount = 0; if(rule.getTransactionType() != "NULL" ){ if(rule.getTransactionType() != transaction.getTransactionType()) return 0; else matchingParameterCount++; } if(rule.getMerchantType() != "NULL"){ if(rule.getMerchantType() != transaction.getMerchantType()) return 0; else matchingParameterCount++; } auto absoluteTransactionAmount = abs(transaction.getTransactionAmount()); if(rule.getUpperTransactionAmountLimit() >= absoluteTransactionAmount) matchingParameterCount++; if(rule.getLowerTransactionAmountLimit() <= absoluteTransactionAmount) matchingParameterCount++; return matchingParameterCount; } std::vector<RewardRule> RewardRuleCSVReader::readRules() { auto rows = getNextRecords(1000); vector<RewardRule> rules; for(auto& row : rows) { rules.push_back(RewardRule(row)); } return rules; } RewardRuleCSVReader::RewardRuleCSVReader(std::string filepath) : CSVReader(filepath) { }
[ "agarg145@bloomberg.net" ]
agarg145@bloomberg.net
35940afb25ad9c8bbbc75fe1ca9ecf895a17506d
ec68c973b7cd3821dd70ed6787497a0f808e18e1
/Cpp/SDK/Trait_ArmorPiercer_classes.h
fae08e15c3097cbc3204baef5d9c9c7ea025c330
[]
no_license
Hengle/zRemnant-SDK
05be5801567a8cf67e8b03c50010f590d4e2599d
be2d99fb54f44a09ca52abc5f898e665964a24cb
refs/heads/main
2023-07-16T04:44:43.113226
2021-08-27T14:26:40
2021-08-27T14:26:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
840
h
#pragma once // Name: Remnant, Version: 1.0 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Trait_ArmorPiercer.Trait_ArmorPiercer_C // 0x0000 class UTrait_ArmorPiercer_C : public UBP_RemnantTrait_C { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass Trait_ArmorPiercer.Trait_ArmorPiercer_C"); return ptr; } void ModifyInspectInfo(); void ModifyDamage(); void GetArmoredDamageMod(); void OnComputeStats(); void ExecuteUbergraph_Trait_ArmorPiercer(); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
2336d798a900927071cf8fc5764e3132b2fa311f
6afa2c437044c1f6015ccbb8bada7bb84d0bea53
/Catch Mind/Client Catch Mind/Client Catch Mind/Object.h
f2cd32d5783dbb93c710aa62e56c1f061dc44322
[]
no_license
nskogkatt/CatchMind
3642fd443a02d565051cbc801d4f1d3e3bd5644c
20cd6ea0c47b546fd51434b3a5cfd9d0179ba1dc
refs/heads/master
2020-04-15T18:44:37.852790
2019-01-27T06:21:55
2019-01-27T06:21:55
164,908,459
1
0
null
null
null
null
UTF-8
C++
false
false
378
h
#pragma once #include "ResManager.h" #include "../../Common/defineSize.h" class Bitmap; class Object { protected: RECT m_rcRect; bool m_bLive; public: virtual void Init(int iIndex, Bitmap** pBitmap, RECT rcRect); virtual void Draw() = 0; virtual bool InputMouseLButtonDown(POINT& ptMouse); virtual void SetLiveObject(bool bLive); Object(); virtual ~Object(); };
[ "43883216+nskogkatt@users.noreply.github.com" ]
43883216+nskogkatt@users.noreply.github.com
bc5facd964781422812694115e3a0b0b10b737e2
93edd9b5a7ae05fa6a16ffc86418b5de465490f6
/programmers/깊이너비우선탐색/단어변환/word_jiwon.cpp
5ee3bd4f9db8ac714e75f8152cc88e6eac3536b5
[]
no_license
Yellin36/LOGO-algorithm
dbc0590d5fdc22d74652aa009d988272ad98e281
2da7f99aeca36ec982c324e132e030e0dfe8e724
refs/heads/master
2023-05-07T01:34:21.883476
2021-05-25T17:04:57
2021-05-25T17:04:57
329,848,372
3
0
null
2021-05-25T17:04:57
2021-01-15T08:08:28
C++
UTF-8
C++
false
false
930
cpp
#include <string> #include <vector> using namespace std; bool visit[51]; int answer = 51; void DFS(string begin, string target, int cnt, vector<string> words){ if(begin == target){ if(answer>cnt) answer = cnt; return; } for(int i=0;i<words.size();i++){ if(!visit[i] && begin != words[i]){ int num = 0; for(int j=0;j<begin.length();j++){ if(begin[j] != words[i][j]) num++; if(num > 1) break; } if(num == 1){ visit[i] = true; DFS(words[i],target,cnt+1,words); visit[i] = false; } } } } int solution(string begin, string target, vector<string> words) { DFS(begin,target,0, words); //반환할 수 없는 경우 if(answer==51) answer = 0; return answer; }
[ "tjfdnjs0829@naver.com" ]
tjfdnjs0829@naver.com
3add123ba8aec226ee8ea688157cb92ba4755ff9
66684ef8257e424ae24af6a25379bbb64eec7436
/union/models/VertexBuffer.cpp
06a34b99b4af166abc7009f07d4e043c689fb6ea
[]
no_license
sergey-shambir/toAlexeyMalov
d39aa416649583f1a2c056fdb268ff0278908b83
f0bc5c9119e3954e97df9adeb4b05614d874773c
refs/heads/master
2020-05-29T12:03:33.817310
2015-10-15T22:59:34
2015-10-15T22:59:34
8,674,751
2
0
null
null
null
null
UTF-8
C++
false
false
2,730
cpp
#include "VertexBuffer.h" #include "../helpers/ResourceHeap.h" #include <GL/glew.h> #include <stdexcept> namespace GL { static unsigned bufferConstructor() { if (!GLEW_VERSION_1_5) { throw std::runtime_error("ERROR: hardware requirement missed - OpenGL >= 1.5," " update drivers or try run on another graphics card"); } unsigned bufferId(0); glGenBuffers(1, &bufferId); return bufferId; } static void bufferDestructor(unsigned bufferId) { glDeleteBuffers(1, &bufferId); } VertexBuffer::VertexBuffer() : m_id(0) , m_type(Type_Attributes) , m_usageHint(GL_STATIC_DRAW) , m_bytesCount(0) { } VertexBuffer::VertexBuffer(const VertexBuffer &other) : m_id(other.m_id) , m_type(other.m_type) , m_usageHint(other.m_usageHint) , m_bytesCount(0) { ResourceHeap::instance().retain(m_id, ResourceHeap::VertexBuffer); } VertexBuffer &VertexBuffer::operator =(const VertexBuffer &other) { ResourceHeap::instance().retain(m_id, ResourceHeap::VertexBuffer); m_id = other.m_id; m_type = other.m_type; m_usageHint = other.m_usageHint; m_bytesCount = other.m_bytesCount; return *this; } VertexBuffer::~VertexBuffer() { ResourceHeap::instance().release(m_id, ResourceHeap::VertexBuffer); } void VertexBuffer::ensureInitializated() { if (m_id == 0) { m_id = ResourceHeap::instance().create(bufferConstructor, bufferDestructor, ResourceHeap::VertexBuffer); } } void VertexBuffer::setType(VertexBuffer::Type type) { m_type = type; } void VertexBuffer::setUsageHint(int usageHint) { m_usageHint = usageHint; } void VertexBuffer::init(const void *data, unsigned bytesCount) { ensureInitializated(); m_bytesCount = bytesCount; GLenum target = (m_type == Type_Attributes) ? GL_ARRAY_BUFFER : GL_ELEMENT_ARRAY_BUFFER; glBindBuffer(target, m_id); glBufferData(target, bytesCount, data, m_usageHint); } void VertexBuffer::bind() const { GLenum target = (m_type == Type_Attributes) ? GL_ARRAY_BUFFER : GL_ELEMENT_ARRAY_BUFFER; glBindBuffer(target, m_id); } void VertexBuffer::unbind() const { GLenum target = (m_type == Type_Attributes) ? GL_ARRAY_BUFFER : GL_ELEMENT_ARRAY_BUFFER; glBindBuffer(target, 0); } void VertexBuffer::unbind(Type type) { GLenum target = (type == Type_Attributes) ? GL_ARRAY_BUFFER : GL_ELEMENT_ARRAY_BUFFER; glBindBuffer(target, 0); } unsigned VertexBuffer::bytesCount() const { return m_bytesCount; } } // namespace GL
[ "sergey.shambir.auto@gmail.com" ]
sergey.shambir.auto@gmail.com
a86dba580cfd434305edc5db4fce93f479c4d022
dfb7297f114bbff7a89fea86cb9b8e0e16243d01
/CCF-CSP/CCF-CSP/17-09-2.cpp
9a0a399969e39b888cfa22d8a46c7868b0e77282
[]
no_license
rainingapple/algorithm-competition-code
c06bd549d44e14c64e808d7026a0204d285f1fb3
809bff5cdf092568de47def7d24d36edef8d0c1e
refs/heads/main
2023-03-30T13:11:23.359366
2021-04-09T01:29:18
2021-04-09T01:29:18
343,407,072
0
0
null
null
null
null
UTF-8
C++
false
false
1,357
cpp
//#include<iostream> //#include<vector> //#include<queue> //#include<map> //#include<algorithm> //using namespace std; //struct node { // int no; // int flag; // int time; // node(int a, int b, int c) :no(a), flag(b), time(c) {} //}; //int n, k; //int key[1005]; //vector<node> action; //priority_queue<int,vector<int>,greater<int>> q; //map<int, int> pos; //bool cmp(node n1, node n2) { // if (n1.time != n2.time) // return n1.time < n2.time; // else if (n1.flag != n2.flag) { // return n1.flag > n2.flag; // } // else { // return n1.no < n2.no; // } //} //void fuc(node x) { // int no = x.no; // int flag = x.flag; // int time = x.time; // if (flag == 1) { // int top = q.top(); // q.pop(); // key[top] = no; // pos[no] = top; // } // else { // key[pos[no]] = 0; // q.push(pos[no]); // } //} //int main() { // cin >> n >> k; // for (int i = 1;i <= n;i++) { // key[i] = i; // pos[i] = i; // } // for (int i = 0;i < k;i++) { // int no, b_time, e_time; // cin >> no >> b_time >> e_time; // action.push_back(node(no, 0, b_time)); // action.push_back(node(no, 1, b_time+e_time)); // } // sort(action.begin(), action.end(), cmp); // for (auto i = action.begin();i < action.end();i++) { // fuc(*i); // } // for (int i = 1;i <= n;i++) { // cout << key[i] << " "; // } // return 0; //}
[ "825140645@qq.com" ]
825140645@qq.com
71e35f1a22ee8a004b8d5fb436e57ffa7b3c5373
e199dc22cf988d78b9290ce2757cdd5ad849f9c6
/PeisikInterpreter/Program.cpp
1a08e0a6c894db391dbfdf19430267f46ee01ef5
[ "MIT" ]
permissive
polsys/Peisik
9c42545339dc2e5d3d48045b06f72c2733e21f3a
5c55a41c4f4154b0ee2f23f9cbde576401c20832
refs/heads/master
2021-01-20T14:23:40.681288
2018-05-01T13:34:36
2018-05-01T13:34:36
90,603,083
0
0
null
2018-02-03T13:24:57
2017-05-08T08:15:27
C#
UTF-8
C++
false
false
5,416
cpp
#include "pch.h" #include "Bytecode.h" #include "PeisikException.h" #include "Program.h" using namespace Peisik; /* * Function */ const std::vector<BytecodeOp>& Function::GetBytecode() const { return m_bytecode; } short Peisik::Function::GetFunctionIndex() const { return m_functionIndex; } const std::vector<PrimitiveType>& Peisik::Function::GetLocalTypes() const { return m_localTypes; } short Peisik::Function::GetParameterCount() const { return m_parameterCount; } PrimitiveType Function::GetReturnType() const { return m_returnType; } /* * Program */ PObject Program::GetConstant(short index) const { if (index < 0 || index >= GetConstantCount()) { throw std::range_error("Constant index out of range."); } return m_constants[index]; } short Program::GetConstantCount() const { return static_cast<short>(m_constants.size()); } const Function& Program::GetFunction(short index) const { if (index < 0 || index >= GetFunctionCount()) { throw std::range_error("Function index out of range."); } return m_functions[index]; } short Program::GetFunctionCount() const { return static_cast<short>(m_functions.size()); } short Program::GetMainFunctionIndex() const { return m_mainFunctionIndex; } /* * Global namespace */ static void AssertValidType(short type) { if (type <= (short)PrimitiveType::NoType || type > (short)PrimitiveType::Bool) throw std::invalid_argument("Invalid constant type."); } template <typename T> static void Read(T* to, std::istream& stream) { stream.read(reinterpret_cast<char*>(to), sizeof(T)); } Program Peisik::DeserializeProgram(std::istream& stream) { // Make all errors throw stream.exceptions(std::istream::badbit | std::istream::eofbit | std::istream::failbit); Program result; // The header contains a magic number, bytecode version and the main function index uint32_t magic = 0; Read(&magic, stream); if (magic != 0x53494550 /* PEIS (notice the endianness) */) throw InterpreterException("Not a compiled Peisik file."); uint32_t bytecodeVersion = 0; Read(&bytecodeVersion, stream); if (bytecodeVersion != Program::BytecodeVersion) throw InterpreterException("Wrong bytecode version."); uint32_t mainIndex = 0; Read(&mainIndex, stream); result.m_mainFunctionIndex = static_cast<short>(mainIndex); // Then, the constants. // First, a 32-bit integer for their count and then each constant int32_t constCount = -1; Read(&constCount, stream); if (constCount < 0) throw InterpreterException("Constant count less than 0."); for (int i = 0; i < constCount; i++) { // Type code short type = 0; Read(&type, stream); AssertValidType(type); // 6 bytes of UTF-8 encoded name as padding - ignore char name[6]; stream.read(name, 6 * sizeof(char)); // Value int64_t value = -1; Read(&value, stream); // Add the constant result.m_constants.push_back(PObject(static_cast<PrimitiveType>(type), value)); } // Then the functions. // First, a 32-bit integer for their count. // Then for each function: // 1. The return type (2 bytes) // 2. Parameter count (2 bytes) // 3. Parameter types, 2 bytes each // (4. 2 bytes of padding if odd number of parameters) // 5. Bytecode size (4 bytes) // 6. Bytecode int32_t functionCount = -1; Read(&functionCount, stream); if (functionCount < 0) throw InterpreterException("Function count less than 0."); if (functionCount > 32768) throw std::range_error("Too many functions."); for (int i = 0; i < functionCount; i++) { Function func; func.m_functionIndex = static_cast<short>(i); // Return type short returnType; Read(&returnType, stream); AssertValidType(returnType); func.m_returnType = static_cast<PrimitiveType>(returnType); // Parameter count Read(&func.m_parameterCount, stream); if (func.m_parameterCount < 0) throw InterpreterException("Parameter count less than 0."); // Locals short localCount = -1; Read(&localCount, stream); if (localCount < 0) throw InterpreterException("Local count less than 0."); func.m_localTypes.reserve(localCount); for (int localIdx = 0; localIdx < localCount; localIdx++) { short type = 0; Read(&type, stream); AssertValidType(type); func.m_localTypes.push_back(static_cast<PrimitiveType>(type)); } if (localCount % 2 == 1) { short unused = 0; Read(&unused, stream); } // Bytecode int32_t codeSize = -1; Read(&codeSize, stream); if (codeSize < 0) throw InterpreterException("Code size less than 0."); func.m_bytecode.reserve(codeSize); for (int j = 0; j < codeSize; j++) { short op = -1; Read(&op, stream); short param = -1; Read(&param, stream); func.m_bytecode.push_back(BytecodeOp(static_cast<Opcode>(op), param)); } result.m_functions.push_back(func); } return result; }
[ "polsys@users.noreply.github.com" ]
polsys@users.noreply.github.com
2ccf0594afd4a3ea05ab188343450a75a6aebecf
3e5ae9b260b16fcc86bb0669c1bd4e56912b5433
/VCB600ENU1/MSDN_VCB/SAMPLES/VC98/MFC/GENERAL/CTRLTEST/PAREDIT.H
de5d922bbc77169d7ddba37f0e5be63a44adabd2
[]
no_license
briancpark/deitel-cpp
e8612c7011c9d9d748290419ae2708d2f3f11543
90cdae5661718e65ab945bcf45fe6adff30c1e10
refs/heads/main
2023-06-14T14:07:05.497253
2021-07-05T01:46:04
2021-07-05T01:46:04
382,984,213
0
0
null
null
null
null
UTF-8
C++
false
false
2,094
h
// paredit.h: C++ derived edit control for numbers/letters etc // // This is a part of the Microsoft Foundation Classes C++ library. // Copyright (C) 1992-1998 Microsoft Corporation // All rights reserved. // // This source code is only intended as a supplement to the // Microsoft Foundation Classes Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Microsoft Foundation Classes product. ///////////////////////////////////////////////////////////////////////////// // CParsedEdit is a specialized CEdit control that only allows characters // of a given type. // This class is used in 3 different ways in the samples class CParsedEdit : public CEdit { protected: WORD m_wParseStyle; // C++ member data public: // Construction CParsedEdit(); // explicit construction (see DERTEST.CPP) BOOL Create(DWORD dwStyle /* includes PES_ style*/, const RECT& rect, CWnd* pParentWnd, UINT nID); // subclassed construction (see SUBTEST.CPP) BOOL SubclassEdit(UINT nID, CWnd* pParent, WORD wParseStyle); // for WNDCLASS Registered window static BOOL RegisterControlClass(); // Overridables virtual void OnBadInput(); // Implementation protected: //{{AFX_MSG(CParsedEdit) afx_msg void OnChar(UINT, UINT, UINT); // for character validation afx_msg void OnVScroll(UINT, UINT, CScrollBar*); // for spin buttons //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////// // Parsed edit control sub-styles #define PES_NUMBERS 0x0001 #define PES_LETTERS 0x0002 #define PES_OTHERCHARS 0x0004 #define PES_ALL 0xFFFF ///////////////////////////////////////////////////////////////////////////// // Extra control notifications // above the range for normal EN_ messages #define PEN_ILLEGALCHAR 0x8000 // sent to parent when illegal character hit // return 0 if you want parsed edit to beep /////////////////////////////////////////////////////////////////////////////
[ "briancpark@berkeley.edu" ]
briancpark@berkeley.edu
7302ba3093297dcbc882a8a0177dee1b164535a1
f2f43c78369b0cf0ab522f0b0078098810b83504
/Project/Encrypted Storage/WebServerESP8266/TimeNtp.h
7ebaccad843cdc91fd2c0b0f203e9387de0ef70e
[ "MIT" ]
permissive
sebsalva/OpenThermostat-1
41bf8c0fac2a6e0b82e402461e22ef2ab2dd4318
8b3a85f92342c05687564ccd85e9777c446fa97c
refs/heads/master
2021-11-29T08:42:30.050250
2018-03-23T00:24:49
2018-03-23T00:24:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
911
h
#ifndef TimeNtp_h #define TimeNtp_h #include <TimeLib.h> #include <ESP8266WiFi.h> #include <WiFiUdp.h> #include "Application.h" class TimeNtp { private: static TimeNtp* getTimeObject; WiFiUDP Udp; // default NTP Servers: String ntpServerName = "fr.pool.ntp.org"; uint8_t timeZone = 2; // paris france unsigned int localPort = 8888; // local port to listen for UDP packets static const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets time_t getNtpTime(); void sendNTPpacket(IPAddress &address); static time_t globalGetNTPTime(); bool summertime(int year, byte month, byte day, byte hour, byte tzHours); unsigned int tempo = 20; public: bool gotTime = false; TimeNtp(); TimeNtp(String server, int zone); time_t getTime(void); void init(String server, int zone); }; #endif
[ "gryfenflash@gmail.com" ]
gryfenflash@gmail.com
f40b485776ab82587c3247d710f906465efc0e79
7c34490a04ec37a171398e098c68911ec93e57ae
/winvnc/winvnc/vncbuffer.h
aa6ad0c74e6863e0eca860fc77441763b77ad3e3
[]
no_license
larytet/UltraVNC-SC
20344b1e9ae0a7eb19138ec96a1bbc63aee62d8a
882b3c2be385ad536d24550f69cb129f094e3fbf
refs/heads/master
2020-07-04T06:32:33.131632
2016-09-12T09:51:59
2016-09-12T09:51:59
67,602,481
1
0
null
null
null
null
UTF-8
C++
false
false
4,237
h
// Copyright (C) 2002 Ultr@VNC Team Members. All Rights Reserved. // Copyright (C) 2002 RealVNC Ltd. All Rights Reserved. // Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved. // // This file is part of the VNC system. // // The VNC system 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. // // If the source code for the VNC system is not available from the place // whence you received this file, check http://www.uk.research.att.com/vnc or contact // the authors on vnc@uk.research.att.com for information on obtaining it. // vncBuffer object // The vncBuffer object provides a client-local copy of the screen // It can tell the client which bits have changed in a given region // It uses the specified vncDesktop to read screen data from class vncDesktop; class vncBuffer; #if !defined(_WINVNC_VNCBUFFER) #define _WINVNC_VNCBUFFER #pragma once // Includes #include "stdhdrs.h" #include "vncEncoder.h" #include "rfbRegion.h" #include "rfbRect.h" #include "rfb.h" #include "vncmemcpy.h" // Class definition class vncBuffer { // Methods public: // Create/Destroy methods vncBuffer(); ~vncBuffer(); void SetDesktop(vncDesktop *desktop); // BUFFER INFO rfb::Rect GetSize(); rfbPixelFormat GetLocalFormat(); // BUFFER MANIPULATION BOOL CheckBuffer(); // SCREEN SCANNING // void Clear(const rfb::Rect &rect); void CheckRegion(rfb::Region2D &dest,rfb::Region2D &cache, const rfb::Region2D &src); void CheckRect(rfb::Region2D &dest,rfb::Region2D &cache, const rfb::Rect &src); // SCREEN CAPTURE void CopyRect(const rfb::Rect &dest, const rfb::Point &delta); void GrabMouse(); void GrabRegion(rfb::Region2D &src,BOOL driver,bool capture); void GetMousePos(rfb::Rect &rect); // CACHE RDV void ClearCache(); void ClearCacheRect(const rfb::Rect &dest); void ClearBack(); void BlackBack(); void EnableCache(BOOL enable); BOOL IsCacheEnabled(); BOOL IsShapeCleared(); void Display(int number); int GetDisplay(); // sf@2005 - Grey Palette void EnableGreyPalette(BOOL enable); // Modif sf@2002 - Scaling void ScaleRect(rfb::Rect &rect); void GreyScaleRect(rfb::Rect &rect); rfb::Rect GetViewerSize(); UINT GetScale(); BOOL SetScale(int scale); // Modif sf@2002 - Optim BOOL SetAccuracy(int accuracy); // CURSOR HANDLING BOOL IsCursorUpdatePending(){return m_cursorpending;}; void SetCursorPending(BOOL enable){m_cursorpending=enable;}; bool ClipRect(int *x, int *y, int *w, int *h, int cx, int cy, int cw, int ch); // Implementation protected: // Routine to verify the mainbuff handle hasn't changed BOOL FastCheckMainbuffer(); // Fetch pixel data to the main buffer from the screen void GrabRect(const rfb::Rect &rect,BOOL driver,bool capture); BOOL m_freemainbuff; UINT m_bytesPerRow; // CACHE RDV BOOL m_use_cache; BOOL m_display_prim; BOOL m_display_sec; // Modif sf@2002 - Scaling UINT m_ScaledSize; UINT m_nScale; BYTE *m_ScaledBuff; int m_nAccuracyDiv; // Accuracy divider for changes detection in Rects int nRowIndex; // CURSOR HANDLING BOOL m_cursorpending; public: rfbServerInitMsg m_scrinfo; // vncEncodeMgr reads data from back buffer directly when encoding BYTE *m_backbuff; UINT m_backbuffsize; // CACHE RDV BYTE *m_cachebuff; BYTE *m_mainbuff; vncDesktop *m_desktop; BOOL m_cursor_shape_cleared; // sf@2005 - Grey palette BOOL m_fGreyPalette; }; #endif // _WINVNC_VNCBUFFER
[ "larytet@yahoo.com" ]
larytet@yahoo.com
fe44916d20c011139bee3e70175a6244a1318938
7ce390d147542a2cfaf198c66fb40494bb75e5ed
/project-files/dms/neurolib/KohonenNet.cpp
1da7b484a09f5a29f7a65a3ef18eac91e11995f5
[]
no_license
Nikita94/Data-Mining-Tool-System
2b51f6f7ff452264a9adc438a4560341477bb242
faf4f9d3d9abd5b2630267c6cb0d29e6ed8f0086
refs/heads/master
2020-01-23T21:40:35.842420
2018-03-11T11:58:11
2018-03-11T11:58:11
74,689,923
0
0
null
2016-11-24T16:36:29
2016-11-24T16:36:29
null
UTF-8
C++
false
false
10,856
cpp
#include "KohonenNet.h" #include "KohonenPretrain.h" #include <algorithm> #include "mkl_cblas.h" using namespace nnets_kohonen; int nnets_kohonen::getDistance(int neuron1, int neuron2, void* obj) { KohonenNet* kn = static_cast<KohonenNet*>(obj); NeuronIndex n1 = kn->neuron_index_map[neuron1]; NeuronIndex n2 = kn->neuron_index_map[neuron2]; return n1.distanceTo(n2); } size_t nnets_kohonen::getWeightsMatrixSize(void* obj) { KohonenNet* kn = static_cast<KohonenNet*>(obj); return kn->getWeightsMatrixSize(); } void nnets_kohonen::setWeights(const float* w, void* obj) { KohonenNet* kn = static_cast<KohonenNet*>(obj); kn->setWeights(w); } void nnets_kohonen::setUseNormalization(bool norm, void* obj) { KohonenNet* kn = static_cast<KohonenNet*>(obj); kn->setUseNormalization(norm); } size_t nnets_kohonen::getAllWeights(float * w, void * obj) { KohonenNet* kn = static_cast<KohonenNet*>(obj); return kn->getWeights(w); } void nnets_kohonen::disableNeurons(std::vector<int> neurons, void* obj) { KohonenNet* kn = static_cast<KohonenNet*>(obj); std::vector<NeuronIndex> new_neuron_map; std::vector<int> old_new_map; for (int j = 0; j < neurons.size(); j++) if ((neurons[j] < 0) || (neurons[j] > kn->neuron_index_map.size())) throw "Neuron index out of range"; for (int i = 0; i < kn->neuron_index_map.size(); i++) { bool is_disable = false; for (int j = 0; j < neurons.size(); j++) { if (i == neurons[j]) { is_disable = true; break; } } if (is_disable == false) { new_neuron_map.push_back(kn->neuron_index_map[i]); old_new_map.push_back(i); } } delete[] kn->kohonen_layer; kn->kohonen_layer = new float[new_neuron_map.size()]; float* new_weights = new float[new_neuron_map.size() * kn->x_size]; float** new_classes = new float*[new_neuron_map.size()]; for (int i = 0; i < new_neuron_map.size(); i++) { int old_index = old_new_map[i]; for (int j = 0; j < kn->x_size; j++) new_weights[i * kn->x_size + j] = kn->weights[old_index * kn->x_size + j]; new_classes[i] = new float[kn->y_size]; for (int j = 0; j < kn->y_size; j++) new_classes[i][j] = kn->classes[old_index][j]; delete[] kn->classes[old_index]; } delete[] kn->classes; delete[] kn->weights; kn->classes = new_classes; kn->weights = new_weights; kn->neuron_index_map = new_neuron_map; } void * nnets_kohonen::copyKohonen(void * obj) { KohonenNet* kn = static_cast<KohonenNet*>(obj); return new KohonenNet(*kn); } void nnets_kohonen::freeKohonen(void *& obj) { KohonenNet* kn = static_cast<KohonenNet*>(obj); delete kn; obj = nullptr; } const float* nnets_kohonen::getWeights(int neuron, void* obj) { KohonenNet* kn = static_cast<KohonenNet*>(obj); if (neuron == -1) throw "Invalid neuron index"; return kn->weights + neuron * kn->x_size; } int nnets_kohonen::getWinner(void* obj) { KohonenNet* kn = static_cast<KohonenNet*>(obj); return kn->getInternalIndex(kn->winner); } size_t nnets_kohonen::solve(const float* x, float* y, void* obj) { KohonenNet* kn = static_cast<KohonenNet*>(obj); return kn->solve(x, y); } int nnets_kohonen::getMaxNeuronIndex(void* obj) { KohonenNet* kn = static_cast<KohonenNet*>(obj); return kn->neuron_index_map.size(); } void nnets_kohonen::addmultWeights(int neuron, float alpha, float beta, const float* x, void* obj) { KohonenNet* kn = static_cast<KohonenNet*>(obj); if (neuron != -1) { float* w = kn->weights + neuron * kn->x_size; for (int i = 0; i < kn->x_size; i++) w[i] = alpha * w[i] + beta * x[i]; } else throw "Invalid neuron index"; } void nnets_kohonen::setY(int neuron, const float* y, void* obj) { KohonenNet* kn = static_cast<KohonenNet*>(obj); if (neuron != -1) kn->setClass(kn->neuron_index_map[neuron], y); else throw "Invalid neuron index"; } void KohonenNet::initByNeuronMap(std::vector<NeuronIndex> map) { kohonen_layer = new float[map.size()]; weights = new float[map.size() * x_size]; classes = new float*[map.size()]; for (int i = 0; i < map.size(); i++) { for (int j = 0; j < x_size; j++) weights[i * x_size + j] = 0.0f; classes[i] = new float[y_size]; for (int j = 0; j < y_size; j++) classes[i][j] = 0.0f; } neuron_index_map = map; } KohonenNet::KohonenNet(int inputs_count, int outputs_count, int koh_width, int koh_height, float classEps, ClassInitializer initializer, Metric metric) : winner({0,0}), neurons_width(koh_width), neurons_height(koh_height), x_size(inputs_count), y_size(outputs_count), initializer(initializer), metric(metric), class_eps(classEps) { use_norm_x = false; x_internal = new float[x_size]; std::vector<NeuronIndex> map; for (int y = 0; y < neurons_height; y++) for (int x = 0; x < neurons_width; x++) map.push_back(int2d{ x, y }); initByNeuronMap(map); } KohonenNet::KohonenNet(KohonenNet& kn) : winner({0,0}) { use_norm_x = kn.use_norm_x; neurons_width = kn.neurons_width; neurons_height = kn.neurons_height; x_size = kn.x_size; y_size = kn.y_size; metric = kn.metric; initializer = kn.initializer; class_eps = kn.class_eps; x_internal = new float[x_size]; initByNeuronMap(kn.neuron_index_map); for (int i = 0; i < neuron_index_map.size() * x_size; i++) weights[i] = kn.weights[i]; for (int i = 0; i < neuron_index_map.size(); i++) for (int j = 0; j < y_size; j++) classes[i][j] = kn.classes[i][j]; } size_t KohonenNet::getInputsCount() { return x_size; } size_t KohonenNet::getOutputsCount() { return y_size; } void KohonenNet::setWeights(const float* weights) { for (int i = 0; i < neuron_index_map.size() * x_size; i++) this->weights[i] = weights[i]; } void KohonenNet::setClasses(float ** classes) { for (int i = 0; i < neuron_index_map.size(); i++) for (int j = 0; j < y_size; j++) this->classes[i][j] = classes[i][j]; } void nnets_kohonen::KohonenNet::setClasses(float ** y, int rowsCount) { ClassExtracter extr { class_eps }; extr.fit(y, rowsCount, getOutputsCount()); auto distr = extr.getClassesDistributions(); int all_sizes = getMaxNeuronIndex(this); if ((initializer == Statistical) || (initializer == Revert)) { if (initializer == Revert) { std::sort(distr.begin(), distr.end(), [](std::pair<int, int> p1, std::pair<int, int> p2) { return p1.second < p2.second; }); auto first = distr.begin(); auto last = distr.end() - 1; while (first < last) { int temp = first->first; first->first = last->first; last->first = temp; first++; last--; } } int sum = 0; for (int i = 0; i < distr.size(); i++) { int temp = distr[i].second * all_sizes; distr[i].second = temp / rowsCount; sum += distr[i].second; } distr[distr.size() - 1].second += (all_sizes - sum); } else if (initializer == Evenly) { int sum = 0; for (int i = 0; i < distr.size(); i++) { distr[i].second = all_sizes / distr.size(); sum += distr[i].second; } distr[distr.size() - 1].second += (all_sizes - sum); } else throw "Unsupported class initializer"; int currentClassIndex = 0; for (int j = 0; j < all_sizes; j++) { if (distr[currentClassIndex].second <= 0) currentClassIndex++; setY(j, y[distr[currentClassIndex].first], this); distr[currentClassIndex].second--; } } void KohonenNet::setNeurons(std::vector<NeuronIndex>& neurons) { delete[] kohonen_layer; for (int i = 0; i < neurons_width * neurons_height; i++) delete[] classes[i]; delete[] classes; delete[] weights; initByNeuronMap(neurons); } int KohonenNet::getInternalIndex(NeuronIndex n) { int found_index = -1; for (int i = 0; i < neuron_index_map.size(); i++) if (neuron_index_map[i] == n) return i; return -1; } void KohonenNet::setClass(NeuronIndex n, const float* y) { int found_index = getInternalIndex(n); if (found_index != -1) { float* cur_class = classes[found_index]; for (int i = 0; i < y_size; i++) cur_class[i] = y[i]; } else throw "Invalid neuron index"; } void nnets_kohonen::KohonenNet::setClassEps(float eps) { class_eps = eps; } void KohonenNet::setUseNormalization(bool norm) { use_norm_x = norm; } size_t nnets_kohonen::KohonenNet::getClasses(float ** classes) { for (int i = 0; i < neuron_index_map.size(); i++) for (int j = 0; j < y_size; j++) classes[i][j] = this->classes[i][j]; return neuron_index_map.size() * y_size; } float nnets_kohonen::KohonenNet::getClassEps() { return class_eps; } size_t KohonenNet::getWeights(float* weights) { for (int i = 0; i < neuron_index_map.size() * x_size; i++) weights[i] = this->weights[i]; return neuron_index_map.size() * x_size; } std::vector<NeuronIndex> nnets_kohonen::KohonenNet::getNeurons() { return neuron_index_map; } size_t KohonenNet::getClass(NeuronIndex n, float* y) { int found_index = getInternalIndex(n); if (found_index != -1) { float* cur_class = classes[found_index]; for (int i = 0; i < y_size; i++) y[i] = cur_class[i]; return y_size; } return 0; } size_t KohonenNet::getWeightsMatrixSize() { return neuron_index_map.size() * x_size; } bool nnets_kohonen::KohonenNet::getUseNormalization() { return use_norm_x; } int nnets_kohonen::KohonenNet::getWinnerIndex() { return getInternalIndex(winner); } KohonenNet::~KohonenNet() { delete[] kohonen_layer; for (int i = 0; i < neurons_width * neurons_height; i++) delete[] classes[i]; delete[] classes; delete[] weights; delete[] x_internal; } NeuronIndex KohonenNet::calcWinner(const float* x) { const float* input = x; if (use_norm_x) { float norm = 0.0f; for (int i = 0; i < x_size; i++) norm += x[i] * x[i]; norm = std::sqrt(norm); for (int i = 0; i < x_size; i++) x_internal[i] = x[i] / norm; input = x_internal; } int winner_index = 0; if (metric == Metric::Default) { cblas_sgemv(CblasRowMajor, CblasNoTrans, neuron_index_map.size(), x_size, 1.0f, weights, x_size, input, 1, 0.0f, kohonen_layer, 1); float max_value = kohonen_layer[0]; for (int i = 1; i < neuron_index_map.size(); i++) { if (max_value < kohonen_layer[i]) { max_value = kohonen_layer[i]; winner_index = i; } } } else if (metric == Metric::Euclidean) { for (int i = 0; i < neuron_index_map.size(); i++) { kohonen_layer[i] = 0.0f; for (int j = 0; j < x_size; j++) { float temp = input[i] - weights[i * x_size + j]; kohonen_layer[i] += temp * temp; } } float min_value = kohonen_layer[0]; for (int i = 1; i < neuron_index_map.size(); i++) { if (min_value > kohonen_layer[i]) { min_value = kohonen_layer[i]; winner_index = i; } } } else throw "Undefined metric"; return neuron_index_map[winner_index]; } size_t KohonenNet::solve(const float* x, float* y) { winner = calcWinner(x); int found_index = getInternalIndex(winner); float* cur_class = classes[found_index]; for (int i = 0; i < y_size; i++) y[i] = cur_class[i]; return y_size; }
[ "michael_smirnov@me.com" ]
michael_smirnov@me.com
d378b8c6adef327b5745512eb5ce60410c5df4c5
59fbad8202b6e67777305bf9eef5fd9635735d7d
/Engine/Code/Engine/Math/MathUtil.cpp
90b8babdf2634f254058d8293ba533b881a2839a
[]
no_license
neesarg-yb/N-gene
da22a533112f8824ed3b3179adbd2acf08512f10
3f7f16683e0c543f566636e1576c9d663d6d5282
refs/heads/master
2020-03-19T08:58:57.927495
2019-05-07T07:33:04
2019-05-07T07:34:50
136,250,286
1
0
null
null
null
null
UTF-8
C++
false
false
12,717
cpp
#pragma once #include "MathUtil.hpp" #include "Engine/Math/Vector2.hpp" using namespace std; bool AreEqualFloats( float a, float b, uint ulp ) { float absDiff = std::fabsf( a - b ); float absSum = std::fabsf( a + b ); // the machine epsilon has to be scaled to the magnitude of the values used // and multiplied by the desired precision in ULPs (units in the last place) float scaledEpsilon = std::numeric_limits<float>::epsilon() * absSum * ulp; float epsilonForSubnormals = std::numeric_limits<float>::min(); // unless the result is subnormal return (absDiff <= scaledEpsilon) || (absDiff < epsilonForSubnormals); } bool SolveQuadraticEquation( Vector2& out, float a, float b, float c ) { // Quadratic Equation: // // root = ( -b +- (d)^(0.5) ) / ( 2a ) // d = ( b^2 ) - ( 4ac ) float bSquare = b * b; float ac = a * c; float d = bSquare - (4.f * ac); // Solution is imaginary or infinite if( d < 0 || a == 0 ) return false; float squareRootD = sqrt( d ); float root1 = ( -b + squareRootD ) / ( 2.f * a ); float root2 = ( -b - squareRootD ) / ( 2.f * a ); // Smaller root first & larger second if( root1 <= root2 ) { out.x = root1; out.y = root2; } else { out.x = root2; out.y = root1; } return true; } float AreaOfTriangle2D( Vector2 p1, Vector2 p2, Vector2 p3 ) { return abs( ((p1.x * (p2.y - p3.y)) + (p2.x * (p3.y - p1.y)) + (p3.x * (p1.y - p2.y))) * 0.5f ); } bool IsPointIsInsideTriangle2D( Vector2 point, Vector2 triangleCornerA, Vector2 triangleCornerB, Vector2 triangleCornerC ) { // Area of the triangle float A = AreaOfTriangle2D( triangleCornerA, triangleCornerB, triangleCornerC ); // Area of three sub-triangles made with the point & two corners float A1 = AreaOfTriangle2D( point, triangleCornerA, triangleCornerB ); float A2 = AreaOfTriangle2D( point, triangleCornerB, triangleCornerC ); float A3 = AreaOfTriangle2D( point, triangleCornerA, triangleCornerC ); // If sum of sub-area(s) == total area i.e. the point is inside return ( A == (A1 + A2 + A3) ); } void GetPointsOnCircle2D( Vector2 center, float radius, int numPoints, Vector2 *outArray ) { float stepInDegrees = 360.f / numPoints; for( int i = 0; i < numPoints; i++ ) { outArray[i].x = radius * CosDegree( stepInDegrees * i ); outArray[i].y = radius * SinDegree( stepInDegrees * i ); } } float DegreeToRadian(float degree) { return ( (degree * M_PI) / 180.f ); } float RadianToDegree(float radian) { return ( (radian * 180) / M_PI ); } float CosDegree(float degree) { return ( cosf(DegreeToRadian(degree)) ); } float SinDegree(float degree) { return ( sinf(DegreeToRadian(degree)) ); } float atan2fDegree(float y, float x) { return RadianToDegree(atan2f(y, x)); } float GetRandomFloatZeroToOne() { return ( (float) rand() / (float) RAND_MAX ); } float GetRandomFloatInRange(float minInclusive, float maxInclusive) { float range = (maxInclusive - minInclusive); return minInclusive + (GetRandomFloatZeroToOne() * range) ; } float GetRandomFloatAsPlusOrMinusOne() { return (rand() % 2 ? 1.f : -1.f); } int GetRandomNonNegativeIntLessThan(int maxNotInclusive) { return ( (int) rand() % maxNotInclusive ); } int GetRandomIntInRange(int minInclusive, int maxInclusive) { int range = (maxInclusive - minInclusive) + 1; return ( minInclusive + GetRandomNonNegativeIntLessThan(range) ); } bool CheckRandomChance( float chanceForSuccess ) { chanceForSuccess *= 100; int testInt = GetRandomIntInRange( 1, 100 ); if( testInt <= chanceForSuccess) { return true; } return false; } int ClampInt( int inValue, int min, int max ) { if(inValue < min) { inValue = min; } else if(inValue > max) { inValue = max; } return inValue; } float ClampFloat01(float number) { number = ClampFloat(number, 0.f, 1.f); return number; } float ClampFloat(float inValue, float minInclusive, float maxInclusive) { if(inValue < minInclusive) { inValue = minInclusive; } else if(inValue > maxInclusive) { inValue = maxInclusive; } return inValue; } float ClampFloatNegativeOneToOne( float inValue ) { if(inValue < -1.f) { inValue = -1.f; } else if(inValue > 1.f) { inValue = 1.f; } return inValue; } int RoundToNearestInt( float inValue ) { int sign = inValue >= 0 ? +1 : -1; float absInValue = abs(inValue); float fraction = absInValue - (int) absInValue; // Positive Number, do normal round if( sign == +1 ) { return (int)(inValue+0.5); } // Negative Number, so special round if(fraction > 0.5) { return (int)inValue - 1; // -1.6 -> -2 } else /* if(fraction <= 0.5) */ { return (int)inValue; // -1.5 -> -1 } } float GetSign( float number ) { if( number >= 0.f ) return +1.f; else return -1.f; } void NewSeedForRandom() { srand( (unsigned int) time(NULL) ); } float RangeMapFloat(float inValue, float inStart, float inEnd, float outStart, float outEnd) { // If inRange is zero, call of this function is not-appropriate, handle this situation.. if(inStart == inEnd) { return (outStart + outEnd) * 0.5f; } // Function call is appropriate, start calculation float inRange = inEnd - inStart; float outRange = outEnd - outStart; float inRelativeToStart = inValue - inStart; float fractionOfRange = inRelativeToStart / inRange; // inRange can't be ZERO float outRelativeToStart = fractionOfRange * outRange; return outRelativeToStart + outStart; } float GetFractionInRange( float inValue, float rangeStart, float rangeEnd ) { float relativePosition = inValue - rangeStart; float range = rangeEnd - rangeStart; // range can't be ZERO // Short-circuit if unsensible range if(range == 0) return 0.f; float fraction = relativePosition / range; return fraction; } float Interpolate( float start, float end, float fractionTowardEnd ) { float range = end - start; // range can't be ZERO // Short-circuit if unsensible range if(range == 0) return start; float relativePosition = fractionTowardEnd * range; float numberAtGivenFraction = relativePosition + start; return numberAtGivenFraction; } float GetAngularDisplacement( float startDegrees, float endDegrees ) { float angularDisp = endDegrees - startDegrees; while ( angularDisp > 180.f ) { angularDisp -= 360; } while ( angularDisp < -180.f ) { angularDisp += 360; } return angularDisp; } float TurnToward( float currentDegrees, float goalDegrees, float maxTurnDegrees ) { float difference = goalDegrees - currentDegrees; while (difference > 180.f) { difference -= 360; } while (difference < -180.f) { difference += 360; } if( difference != 0 ) { if( abs(difference) >= abs(maxTurnDegrees) ) { float diffSign = (difference < 0.f) ? -1.f : 1.f; // Since we compared abs(values), we need sign to determine: return currentDegrees + (maxTurnDegrees*diffSign); // whether add/subtract the maxTurnDegrees } else /* abs(diffrence) < maxTurnDegrees */ { return currentDegrees + difference; } } else /* difference == 0 */ { return currentDegrees; } } bool AreBitsSet( unsigned char bitFlags8, unsigned char flagsToCheck ) { if( (bitFlags8 & flagsToCheck) == flagsToCheck ) { return true; } return false; } bool AreBitsSet( unsigned int bitFlags32, unsigned int flagsToCheck ) { if( (bitFlags32 & flagsToCheck) == flagsToCheck ) { return true; } return false; } void SetBits( unsigned char& bitFlags8, unsigned char flagsToSet ) { bitFlags8 = bitFlags8 | flagsToSet; } void SetBits( unsigned int& bitFlags32, unsigned int flagsToSet ) { bitFlags32 = bitFlags32 | flagsToSet; } void ClearBits( unsigned char& bitFlags8, unsigned char flagToClear ) { unsigned char invertFlag = ~flagToClear; bitFlags8 = bitFlags8 & invertFlag; } void ClearBits( unsigned int& bitFlags32, unsigned int flagToClear ) { unsigned int invertFlag = ~flagToClear; bitFlags32 = bitFlags32 & invertFlag; } float SmoothStart2( float t ) { t = ClampFloat01(t); return t * t; } float SmoothStart3( float t ) { t = ClampFloat01(t); return t * t * t; } float SmoothStart4( float t ) { t = ClampFloat01(t); return t * t * t * t; } float SmoothStop2 ( float t ) { t = ClampFloat01(t); float flip = 1.f - t; float square = flip * flip; float result = 1.f - square; // flip again return result; } float SmoothStop3 ( float t ) { t = ClampFloat01(t); float flip = 1.f - t; float cube = flip * flip * flip; float result = 1.f - cube; // flip again return result; } float SmoothStop4 ( float t ) { t = ClampFloat01(t); float flip = 1.f - t; float pow4 = flip * flip * flip * flip; float result = 1.f - pow4; // flip again return result; } float SmoothStep3 ( float t ) { t = ClampFloat01(t); float smoothStart = SmoothStart3(t); float smoothStop = SmoothStop3(t); float smoothStep = ( ( 1.f - t ) * smoothStart ) + ( t * smoothStop ); // using t as a weight return smoothStep; } int Interpolate( int start, int end, float fractionTowardEnd ) { float range = (float)end - (float)start; // range can't be ZERO // Short-circuit if unsensible range if(range == 0) return start; float relativePosition = fractionTowardEnd * range; float floatAnswer = ( relativePosition ) + start; float roundIt = floatAnswer < 0 ? -0.5f : 0.5f; int numberAtGivenFraction = (int) (floatAnswer + roundIt); // Why (relativePosition + 0.5f) ? // Computer consider (int) 6.51 = 6, but we need (int) 6.51 = 7. return numberAtGivenFraction; } unsigned char Interpolate( unsigned char start, unsigned char end, float fractionTowardEnd ) { unsigned char resuleNumber = (unsigned char) Interpolate( (int)start , (int)end , fractionTowardEnd ); resuleNumber = (unsigned char) ClampInt( (int)resuleNumber , 0 , 255 ); return resuleNumber; } void SetFromText( int& setIt , const char* text ) { setIt = atoi(text); } void SetFromText( float& setIt , const char* text ) { setIt = (float) atof(text); } void SetFromText( bool& setIt , const char* text ) { setIt = false; // In case of malfunction, default value will be FALSE if( strcmp( text , "true" ) == 0 || strcmp( text , "1" ) == 0 ) setIt = true; } void SetFromText( std::vector<std::string>& setIt, const char* delimiter, const char* text ) { std::string inputText = text; size_t startPos = 0; for( size_t nextDelPos = inputText.find( delimiter, startPos); nextDelPos != std::string::npos; nextDelPos = inputText.find( delimiter, nextDelPos+1 ) ) { // delimiter found, push_back the string std::string strToPush( inputText, startPos, nextDelPos-startPos ); setIt.push_back( strToPush ); startPos = nextDelPos+1; } // push_back last part std::string strToPush( inputText, startPos ); setIt.push_back( strToPush ); } int GetIndexFromColumnRowNumberForMatrixOfWidth( int columnNum , int rowNum , int width ) { int index = ( width * rowNum ) + columnNum; return index; } std::vector<std::string> SplitIntoStringsByDelimiter( std::string passedString, char delimeter ) { std::string word = ""; passedString += delimeter; int stringTotalLength = (int) passedString.length(); // Traverse the string from left-to-right std::vector<std::string> subStringList; for( int i=0; i<stringTotalLength; i++ ) { if( passedString[i] != delimeter ) word += passedString[i]; else { if( (int) word.size() != 0 ) subStringList.push_back( word ); word = ""; } } return subStringList; } void ReplaceAllInString( std::string &stringToModify, std::string const &replaceFrom, std::string const &replaceTo ) { if( replaceFrom.empty() ) return; size_t startPos = 0; while( (startPos = stringToModify.find( replaceFrom, startPos )) != std::string::npos ) { stringToModify.replace( startPos, replaceFrom.length(), replaceTo ); startPos += replaceTo.length(); } } int ModuloNonNegative( int operatingOn, int moduloBy ) { // ( b + (a % b) ) % b int nnMod = ( moduloBy + ( operatingOn % moduloBy ) ) % moduloBy; return nnMod; } bool CycleLess( uint16_t a, uint16_t b ) { // Converting (Negative Number) -> (Unsigned Number) // -------------------------------------------------- // [ Way 1 ]: Taking 2's compliment // // Negative is calculated as 2's compliment for unsigned numbers // => 6 = 110'b // => -6 = 010'b // ---------- (addition results into ZERO) // 0 = 000'b // // 2's compliment is NOT( number-as-positive ), and then add 0001'b to it // => (-6) = NOT(110'b) + 001'b // = 001'b + 001'b // = 010'b = 2 // // [ Way 2 ]: MAX_NUM + 1 + (negative number) // // => -6 = (111'b) + (001'b) + (negative number) // = 7 + 1 - 6 // = 8 - 6 // = 2 = (010) uint16_t diff = b - a; return (diff != 0) && (diff < 0x8000); }
[ "neesarg.banglawala@gmail.com" ]
neesarg.banglawala@gmail.com
68d1a3aa3b6dda18a976ea83b9f827a1c55f3bf9
5d021944aea1c741592c00d274af013af51eda6d
/Code/libraries/utilities/include/datxio/utilities/key_conversion.hpp
f1dfdea20f829a55f764515cc1932de491b72526
[ "MIT" ]
permissive
railliu/DATx
4596865f0c9e5c0e56f787218b973f884c4ee7f0
f5f782c0101f8c4af65bcb892668e524bd37f836
refs/heads/master
2020-04-01T23:01:59.059667
2018-10-18T03:25:40
2018-10-18T03:25:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
476
hpp
/** * @file * @copyright defined in datx/LICENSE.txt */ #pragma once #include <string> #include <fc/crypto/elliptic.hpp> #include <fc/optional.hpp> namespace datxio { namespace utilities { std::string key_to_wif(const fc::sha256& private_secret ); std::string key_to_wif(const fc::ecc::private_key& key); fc::optional<fc::ecc::private_key> wif_to_key( const std::string& wif_key ); } } // end namespace datxio::utilities
[ "tsfdsong@163.com" ]
tsfdsong@163.com
adb2df9bf51608c419518c7331626e579a7b2fc4
16804ada1f93742f075f9a3c79201f514d1cd950
/Graph/1557. Minimum Number of Vertices to Reach All Nodes /MinimumNumberOfVerticesToReachAllNodes.cpp
68e4a29cca2b126c7327071ca707988bfb2e8ca1
[]
no_license
Jack--Ma/LeetCode
feff40b3aa880c62ff98e5812fb1a961f44caee9
86a10dc3adc6dc95e0bbd92be1ad7ac23e76f3b5
refs/heads/master
2023-06-13T01:14:37.706610
2023-06-05T15:09:43
2023-06-05T15:09:43
63,851,136
0
0
null
null
null
null
UTF-8
C++
false
false
1,996
cpp
// // MinimumNumberOfVerticesToReachAllNodes.cpp // LeetCode-main // // Created by jackma on 2022/3/28. // Copyright © 2022 JackMa. All rights reserved. // #include "MinimumNumberOfVerticesToReachAllNodes.hpp" /** Given a directed acyclic graph, with n vertices numbered from 0 to n-1, and an array edges where edges[i] = [fromi, toi] represents a directed edge from node fromi to node toi. Find the smallest set of vertices from which all nodes in the graph are reachable. It's guaranteed that a unique solution exists. Input: n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]] Output: [0,3] Explanation: It's not possible to reach all the nodes from a single vertex. From 0 we can reach [0,1,2,5]. From 3 we can reach [3,4,2,5]. So we output [0,3]. Input: n = 5, edges = [[0,1],[2,1],[3,1],[1,4],[2,4]] Output: [0,2,3] Explanation: Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4. */ void testFindSmallestSetOfVertices() { vector<vector<int>> edges = {{0,1},{2,1},{3,1},{1,4},{2,4}}; printVector(Solution().findSmallestSetOfVertices(5, edges)); } vector<int> Solution::findSmallestSetOfVertices(int n, vector<vector<int>>& edges) { // index mean number, value mean whether have node point to this number vector<int> reachNodes(n, 0); // set 1 mean there is a node point to second number for (vector<int> edge : edges) { int second = edge[1]; reachNodes[second] = 1; } /** Eg. default is 0, if has relationship set 1 0 1 2 3 4 0 1 1 1 2 1 1 3 1 4 reachNodes contain number 1/4, and the number 0/2/3 are not pointed by other nodes so we just need to filter this number */ vector<int> result = {}; for (int i = 0; i < n; i++) { if (reachNodes[i] == 0) { result.push_back(i); } } return result; }
[ "100858433@qq.com" ]
100858433@qq.com
09138c47f29e7679be97843d2c9a8a779e856be5
1d3496037ed70eab651a69ad607ce0a331b34f60
/algo/endterm/d.cpp
9e7b5b3d11bc01ffaf2c6cab12fd792a8dda92c6
[]
no_license
olzhas-b/algorithm-data-structure
90f00961585aef6796df9859d5554445bc8212c0
72803bbe9fbd772fd9233307051df21bfac16e95
refs/heads/master
2023-05-05T08:30:29.978262
2021-06-03T18:10:30
2021-06-03T18:10:30
373,599,853
0
0
null
null
null
null
UTF-8
C++
false
false
1,015
cpp
#include <bits/stdc++.h> using namespace std; int main(){ int n; cin >> n; vector<int> v(n); vector<long long> mx(3); for(int i = 0; i < n; i++) { cin >> v[i]; } for(int i = 0; i < min(3, n); i++) { mx[i] = v[i]; } for (int j = 0; j < 2; j++) for (int k = 0; k < 2; k++) if (mx[k] > mx[k+1]) swap(mx[k], mx[k+1]); for(int i = 0; i < n; i++) { if(i < 2) { cout << -1 << endl; } else { if(i == 2) { cout << mx[0] * mx[1] * mx[2] << endl; } else { if(v[i] >= mx[0]) { mx[0] = v[i]; for (int j = 0; j < 2; j++) for (int k = 0; k < 2; k++) if (mx[k] > mx[k+1]) swap(mx[k], mx[k+1]); } cout << mx[0] * mx[1] * mx[2] << endl; } } } return 0; }
[ "oljas.bazarbekov15@gmail.com" ]
oljas.bazarbekov15@gmail.com
237972b191730d218b4f91b296c6cfb027f81bcc
1482f91b80a80fac5a890d946f2256603adeba05
/FitTemplateWf.hxx
04fa07901207e4d649065679ea407acee9cf8fba
[]
no_license
kirbybri/FitTemplate
b4765c3c7c6142434cb0cf4c2da4aa2eae83a215
91d425261c9354641a63ab0bcf18aae80c2e2452
refs/heads/master
2020-09-01T17:51:18.207480
2019-11-24T01:30:34
2019-11-24T01:30:34
219,020,103
0
0
null
null
null
null
UTF-8
C++
false
false
6,539
hxx
#include <iostream> #include <stdlib.h> #include <math.h> #include "TMinuit.h" ///////////TEMPLATE DATA CLASS///////////////// class TemplateData { private: public: TemplateData(); ~TemplateData(); void addTemplate(const std::vector<double>& val, double period); void getSignalValue(double time, double offset, double pulseStartTime, double amp,double& simVal); std::vector<double> samp; double sampPeriod; }; TemplateData::TemplateData(){ sampPeriod = 0.01; //fractions of sample samp.clear(); } TemplateData::~TemplateData(){ } void TemplateData::addTemplate(const std::vector<double>& val, double period){ samp.clear(); samp = val; sampPeriod = period; return; } //get response function value quickly from vector interpolation void TemplateData::getSignalValue(double time, double offset, double templateStartTime, double amp,double& simVal){ simVal = offset; //simVal defaults to baseline if interpolation fails double sampTime = 0; if( time > templateStartTime ) sampTime = time - templateStartTime; //determine position of time value in signal vector double templateSampTime = sampTime/sampPeriod; //convert req time into sample # within template array unsigned int templateSampNum = floor(templateSampTime); //get actual template array element # if( templateSampNum >= samp.size() - 1 ) //if req time exceeds template array, simVal is just the baseline return; //do linear interpolation double sigVal = samp[templateSampNum] + ( samp[templateSampNum+1] - samp[templateSampNum] )*(templateSampTime - templateSampNum); //scale by amplitude factor, this assumes template is pedestal subtracted sigVal = amp*sigVal; simVal += sigVal; return; } //Stupid TMinuit global variables/functions static void ffer_fitFuncML(int& npar, double* gout, double& result, double par[], int flg); void ffer_calcLnL(double par[], double& result); double ffer_sampleErr; std::vector<double> *ffer_fitData_vals; std::vector<bool> *ffer_fitData_quality; TemplateData *ffer_tempData; class FitTemplateWf { private: public: FitTemplateWf(); ~FitTemplateWf(); void clearData(); void addTemplate(const std::vector<double>& val, double period); void addData(const std::vector<double>& val, const std::vector<bool>& valQuality); void doFit(); void setSampleError(double err); bool showOutput; double sampleErr; int status; TemplateData *tempData; std::vector<double> fitData_vals; std::vector<bool> fitData_quality; std::vector<double> initVals; std::vector<double> initErrs; std::vector<double> fitVals; std::vector<double> fitValErrs; std::vector<unsigned int> fixFitVars; }; using namespace std; FitTemplateWf::FitTemplateWf(){ //initial values showOutput = 0; sampleErr = 1.; status = -1; tempData = new TemplateData(); } FitTemplateWf::~FitTemplateWf(){ delete tempData; } void FitTemplateWf::clearData(){ fitData_vals.clear(); fitData_quality.clear(); tempData->samp.clear(); initVals.clear(); initErrs.clear(); fitVals.clear(); fitValErrs.clear(); fixFitVars.clear(); } void FitTemplateWf::setSampleError(double err){ sampleErr = 1.; if(err <= 0. ) return; sampleErr = err; return; } void FitTemplateWf::addTemplate(const std::vector<double>& val, double period){ tempData->addTemplate(val,period); return; } void FitTemplateWf::addData(const std::vector<double>& val, const std::vector<bool>& valQuality){ fitData_vals.clear(); fitData_quality.clear(); fitData_vals = val; fitData_quality = valQuality; return; } //wrapper function for TMinuit void FitTemplateWf::doFit(){ //sanity checks if( fitData_vals.size() == 0 || tempData->samp.size() == 0 || initVals.size() == 0 || initErrs.size() == 0 ){ std::cout << "Invalid # of data or template vectors" << std::endl; return; } //give the global variables to the class objects (very lame) ffer_sampleErr = sampleErr; ffer_fitData_vals = &fitData_vals; ffer_fitData_quality = &fitData_quality; ffer_tempData = tempData; //initialize variables status = -1; unsigned int numParameters = 3; TMinuit *minimizer = new TMinuit(numParameters); //Set print level , -1 = suppress, 0 = info minimizer->SetPrintLevel(-1); if( showOutput == 1 ) minimizer->SetPrintLevel(3); //define fit parameters minimizer->SetFCN(ffer_fitFuncML); minimizer->DefineParameter(0, "Offset", initVals[0], initErrs[0],0,0); minimizer->DefineParameter(1, "Time", initVals[1], initErrs[1],0,0); minimizer->DefineParameter(2, "Amp", initVals[2], initErrs[2],0,0); //optionally fix parameters for( unsigned int i = 0 ; i < fixFitVars.size() ; i++ ){ if( fixFitVars.at(i) < numParameters ) minimizer->FixParameter( fixFitVars.at(i) ); } //Set Minuit flags Double_t arglist[10]; arglist[0] = 0.5; //what is this Int_t ierflg = 0; minimizer->mnexcm("SET ERR", arglist ,1,ierflg); //command, arguments, # arguments, error flag //Do MIGRAD minimization Double_t tmp[1]; tmp[0] = 100000; Int_t err; minimizer->mnexcm("MIG", tmp ,1,err); //minimizer->mnexcm("HES", tmp ,1,err); status = err; fitVals.clear(); fitValErrs.clear(); for(unsigned int i = 0 ; i < numParameters ; i++ ){ double fitVal, fitValErr; minimizer->GetParameter(i, fitVal, fitValErr); fitVals.push_back( fitVal ); fitValErrs.push_back( fitValErr ); } delete minimizer; //memory leak? return; } //likelihood calc - note not included in class void calcLnL(double par[], double& result){ double diffSq = 0; double norm = 1./(ffer_sampleErr)/(ffer_sampleErr); //loop over data vector elements for(unsigned int num = 0 ; num < ffer_fitData_vals->size() ; num++ ){ //skip over invalid data elements if( ffer_fitData_quality->operator[](num) == 0 ) continue; //create fit hypothesis double simVal = 0; ffer_tempData->getSignalValue(num, par[0], par[1], par[2],simVal); //do lnL calc double dataVal = ffer_fitData_vals->operator[](num); diffSq = diffSq + (dataVal - simVal)*(dataVal - simVal)*norm; //gauss err assumed, noise is correlated but assume small }//end of element loop //calculate value to minimize result = -0.5*diffSq; return; } //Fit wrapper function - used by Minuit - has to be static void, annoying static void ffer_fitFuncML(int& npar, double* gout, double& result, double par[], int flg){ calcLnL(par, result); result = -1.*result;//Minuit is minimizing result ie maximizing LnL return; }
[ "kirbybri@gmail.com" ]
kirbybri@gmail.com
e6d4d7c71b2db0956ec6785eabe82e2372f7fbda
b451767f16cd2b9501285ba3dc57cbd163944828
/ocminutes.h
44485fb6890f50adef619c89d300e761d02bd8e2
[]
no_license
othelarian/othy_clock3
42b06d77775e0afc61053f46382e6823a21a501c
f006393c4a77b50c8294c44f3023e128cb141711
refs/heads/master
2021-01-22T23:00:45.997609
2017-04-21T15:28:14
2017-04-21T15:28:14
85,596,919
1
0
null
null
null
null
UTF-8
C++
false
false
544
h
#ifndef OCMINUTES_H #define OCMINUTES_H #include <QQuickItem> #include <QQuickPaintedItem> #include "ocsettings.h" // OCminutesTicks class ################# class OCminutesTicks : public QQuickPaintedItem { Q_OBJECT public: OCminutesTicks(QQuickItem *parent = 0); void paint(QPainter *painter); // }; // OCminutesCog class ################### class OCminutesCog : public QQuickPaintedItem { Q_OBJECT public: OCminutesCog(QQuickItem *parent = 0); void paint(QPainter *painter); // }; #endif // OCMINUTES_H
[ "le.maitre.killian@gmail.com" ]
le.maitre.killian@gmail.com
778aef1fa47dba76184954eff0a2a748af79690f
2d568794c70ab5b8f5bae284c757be4fbf230bcd
/0018-4sum.cpp
d450b3b3c1b78adaa4ee7f6255b77f4a5d54ed6d
[ "MIT" ]
permissive
lwcM/leetcode_solution
5fc3d3a943db97a415a1f987954caf4aa9de7566
a5e714a9785fd94e530396d93c81f71fd8b9c1b6
refs/heads/master
2020-03-28T12:54:01.669006
2018-09-20T06:39:10
2018-09-20T06:39:10
148,344,855
2
0
null
null
null
null
UTF-8
C++
false
false
1,069
cpp
static const auto __=[]{ ios::sync_with_stdio(false); cin.tie(nullptr); return nullptr; }(); class Solution { public: vector<vector<int>> fourSum(vector<int>& nums, int target) { sort(nums.begin(), nums.end()); vector<vector<int>> v; for(int i=0; i<nums.size(); i++) { if(i && nums[i-1]==nums[i]) continue; for(int j=i+1; j<nums.size(); j++) { if(j>i+1 && nums[j-1]==nums[j]) continue; int l=j+1, r=nums.size()-1; while(l<r) { int s = nums[i]+nums[j]+nums[l]+nums[r]; if(s < target) l++; else if(s > target) r--; else { v.push_back({nums[i], nums[j], nums[l], nums[r]}); while(l < r && nums[l] == nums[l+1]) l++; while(l < r && nums[r] == nums[r-1]) r--; l++; r--; } } } } return v; } };
[ "lwc@lwcs-MacBook-Pro.local" ]
lwc@lwcs-MacBook-Pro.local
feb0663c6a363b147cb749411c51b29f741190ca
be31580024b7fb89884cfc9f7e8b8c4f5af67cfa
/CTDL1/New folder/VC/VCWizards/CodeWiz/MFC/Simple/Templates/3082/dhtmldlg.cpp
a056084dd68e91ef4a54dc8fddd6e6eb9c099acd
[]
no_license
Dat0309/CTDL-GT1
eebb73a24bd4fecf0ddb8428805017e88e4ad9da
8b5a7ed4f98e5d553bf3c284cd165ae2bd7c5dcc
refs/heads/main
2023-06-09T23:04:49.994095
2021-06-23T03:34:47
2021-06-23T03:34:47
379,462,390
1
0
null
null
null
null
WINDOWS-1250
C++
false
false
3,016
cpp
// [!output IMPL_FILE]: archivo de implementación // #include "stdafx.h" [!if PROJECT_NAME_HEADER] #include "[!output PROJECT_NAME].h" [!endif] #include "[!output HEADER_FILE]" [!if !MERGE_FILE] #ifdef _DEBUG #define new DEBUG_NEW #endif [!endif] // Cuadro de diálogo de [!output CLASS_NAME] IMPLEMENT_DYNCREATE([!output CLASS_NAME], CDHtmlDialog) [!output CLASS_NAME]::[!output CLASS_NAME](CWnd* pParent /*=NULL*/) : CDHtmlDialog([!output CLASS_NAME]::IDD, [!output CLASS_NAME]::IDH, pParent) { [!if ACCESSIBILITY] #ifndef _WIN32_WCE EnableActiveAccessibility(); #endif [!endif] [!if AUTOMATION || CREATABLE] EnableAutomation(); [!endif] [!if CREATABLE] // El constructor llama a AfxOleLockApp para mantener la aplicación en ejecución // mientras el objeto de automatización OLE está activo. AfxOleLockApp(); [!endif] } [!output CLASS_NAME]::~[!output CLASS_NAME]() { [!if CREATABLE] // El destructor llama a AfxOleUnlockApp para terminar la aplicación // una vez creados todos los objetos con automatización OLE. AfxOleUnlockApp(); [!endif] } [!if AUTOMATION || CREATABLE] void [!output CLASS_NAME]::OnFinalRelease() { // Cuando se libera la última referencia para un objeto de automatización, // se llama a OnFinalRelease. La clase base eliminará automáticamente // el objeto. Se requiere limpieza adicional para el // objeto antes de llamar a la clase base. CDHtmlDialog::OnFinalRelease(); } [!endif] void [!output CLASS_NAME]::DoDataExchange(CDataExchange* pDX) { CDHtmlDialog::DoDataExchange(pDX); } BOOL [!output CLASS_NAME]::OnInitDialog() { CDHtmlDialog::OnInitDialog(); return TRUE; // devolver TRUE a menos que se establezca el foco en un control } BEGIN_MESSAGE_MAP([!output CLASS_NAME], CDHtmlDialog) END_MESSAGE_MAP() BEGIN_DHTML_EVENT_MAP([!output CLASS_NAME]) DHTML_EVENT_ONCLICK(_T("ButtonOK"), OnButtonOK) DHTML_EVENT_ONCLICK(_T("ButtonCancel"), OnButtonCancel) END_DHTML_EVENT_MAP() [!if AUTOMATION || CREATABLE] BEGIN_DISPATCH_MAP([!output CLASS_NAME], CDHtmlDialog) END_DISPATCH_MAP() // Nota: suministramos compatibilidad con IID_I[!output CLASS_NAME_ROOT] para admitir enlaces de seguridad de tipos // desde VBA. Este IID debe coincidir con el GUID asociado a la interfaz Dispinterface // del archivo .IDL. // {[!output DISPIID_REGISTRY_FORMAT]} static const IID IID_I[!output CLASS_NAME_ROOT] = [!output DISPIID_STATIC_CONST_GUID_FORMAT]; BEGIN_INTERFACE_MAP([!output CLASS_NAME], CDHtmlDialog) INTERFACE_PART([!output CLASS_NAME], IID_I[!output CLASS_NAME_ROOT], Dispatch) END_INTERFACE_MAP() [!endif] [!if CREATABLE] // {[!output CLSID_REGISTRY_FORMAT]} IMPLEMENT_OLECREATE([!output CLASS_NAME], "[!output TYPEID]", [!output CLSID_IMPLEMENT_OLECREATE_FORMAT]) [!endif] // Controladores de mensajes de [!output CLASS_NAME] HRESULT [!output CLASS_NAME]::OnButtonOK(IHTMLElement* /*pElement*/) { OnOK(); return S_OK; } HRESULT [!output CLASS_NAME]::OnButtonCancel(IHTMLElement* /*pElement*/) { OnCancel(); return S_OK; }
[ "71766267+Dat0309@users.noreply.github.com" ]
71766267+Dat0309@users.noreply.github.com
28fd3ad1b270540d5b40f132774f9490893279be
694df92026911544a83df9a1f3c2c6b321e86916
/c++/Inherit/VirtualFunctionWithException.cpp
f3529fca71cc3d3b3bcffa7c620b56ce584c4fd2
[ "MIT" ]
permissive
taku-xhift/labo
f485ae87f01c2f45e4ef1a2a919cda7e571e3f13
89dc28fdb602c7992c6f31920714225f83a11218
refs/heads/main
2021-12-10T21:19:29.152175
2021-08-14T21:08:51
2021-08-14T21:08:51
81,219,052
0
0
null
null
null
null
UTF-8
C++
false
false
287
cpp
#include <iostream> #include <typeinfo> class Base { virtual void print() = 0; }; class Derived : public Base { public: void print() throw() { std::cout << typeid(this).name() << std::endl; } }; int main() { Derived derived; derived.print(); }
[ "shishido_takuya@xhift.com" ]
shishido_takuya@xhift.com
d4c5984a537ef245ce7531679fa84ef42021bef5
96ee331287ddffd513ed3a0a1ba9f6ffb64119a7
/算法与数据结构/合并K个有序链表.cpp
1fe404f117dc387bae15894ca5de53d5a60a6613
[]
no_license
noahyzhang/IT-
be2c1f19cd27266563d273407ede1b1c7055b9d5
6e5657e52a56f9387318b4aa5357ea3b72d24c1d
refs/heads/master
2022-01-19T20:17:46.594942
2019-06-24T03:53:17
2019-06-24T03:53:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,339
cpp
#include<iostream> #include<vector> #include<string> #include<queue> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} ListNode* List(vector<int>& vec) { ListNode* head = new ListNode(vec[0]); ListNode* tmp = head; for (int i = 1; i < vec.size(); ++i) { tmp->next = new ListNode(vec[i]); tmp = tmp->next; } return head; } }; class Solution { public: ListNode* mergeKLists(vector<ListNode*>& lists) { priority_queue<int,vector<int>,greater<int>> pri_qu; for (int i = 0; i < lists.size(); ++i) { ListNode* tmp = lists[i]; while (tmp != nullptr) { pri_qu.push(tmp->val); tmp = tmp->next; } } ListNode* head = new ListNode(0); ListNode* tmp_head = head; while (!pri_qu.empty()) { tmp_head->next = new ListNode(pri_qu.top()); tmp_head = tmp_head->next; pri_qu.pop(); } return head->next; } }; #if 0 int main() { ListNode ln(0); vector<ListNode*> vec; vector<int> tmp{ 1,4,5 }; ListNode* str = ln.List(tmp); vec.push_back(str); tmp={ 1,3,4 }; str = ln.List(tmp); vec.push_back(str); tmp = { 2,6 }; str = ln.List(tmp); vec.push_back(str); Solution sn; ListNode* res = sn.mergeKLists(vec); while (res != nullptr) { std::cout << res->val << std::endl; res = res->next; } return 0; } #endif
[ "13572252156@163.com" ]
13572252156@163.com
abdfc8de00cc3aa13d2c44d5d40b28cd2b107e60
cad35287bc893aaef3761af2079a4ad08db2299c
/client/cpp/src/tarscli/util/include/util/tc_enable_shared_from_this.h
187f0f1ba37526f89cfc5aaae4decd9908564330
[ "Apache-2.0" ]
permissive
foolishantcat/CxxDBC
3eafb94b6c1532a2ac236392be8544182206a9e9
f0f9e95baad72318e7fe53231aeca2ffa4a8b574
refs/heads/master
2021-09-25T21:23:11.977712
2018-10-25T17:19:46
2018-10-25T17:19:46
272,710,881
1
0
Apache-2.0
2020-06-16T13:08:34
2020-06-16T13:08:33
null
UTF-8
C++
false
false
2,167
h
/** * Tencent is pleased to support the open source community by making Tars available. * * Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ #ifndef __TC_ENABLE_SHARED_FROM_THIS_H__ #define __TC_ENABLE_SHARED_FROM_THIS_H__ #include "tc_shared_ptr.h" namespace tars { template <class T> class TC_EnableSharedFromThis { public: TC_SharedPtr<T> sharedFromThis() { TC_SharedPtr<T> p(m_this, m_owner_use_count); return p; } TC_SharedPtr<const T> sharedFromThis() const { TC_SharedPtr<const T> p(m_this, m_owner_use_count); return p; } protected: TC_EnableSharedFromThis() : m_this(NULL) , m_owner_use_count(NULL) { } TC_EnableSharedFromThis(const TC_EnableSharedFromThis&) { } TC_EnableSharedFromThis& operator=(const TC_EnableSharedFromThis&) { return *this; } ~TC_EnableSharedFromThis() { } private: template <typename U> void acceptOwner(const TC_SharedPtr<U>& p) const { if (m_owner_use_count == NULL) { m_owner_use_count = p.m_pn; m_this = p.get(); } } mutable T *m_this; mutable detail::tc_shared_count_base *m_owner_use_count; template <class X, class U> friend void detail::tc_sp_enable_shared_from_this(const TC_SharedPtr<X> *pp, const TC_EnableSharedFromThis<U> *px); }; } #endif
[ "cxxjava@163.com" ]
cxxjava@163.com
8fc0ec893dff64d8bfd3e2eb740e5433193f81b2
e5474f6051792fd2aaeb970bb9ce0fe6d4ea656c
/include/sigma/graphics/opengl/static_mesh_manager.hpp
20834adcc969313907a27b7387fff43dc30ca6d2
[]
no_license
sigma-engine/sigma-opengl
2906c65e8b1591ce204b6725c494df916f523d95
f38c8fb891f4324690b95ad73906cba077363b79
refs/heads/master
2020-03-28T09:38:47.614165
2019-03-31T16:32:25
2019-03-31T16:32:25
148,048,703
0
0
null
null
null
null
UTF-8
C++
false
false
1,934
hpp
#ifndef SIGMA_ENGINE_STATIC_MESH_MANAGER_HPP #define SIGMA_ENGINE_STATIC_MESH_MANAGER_HPP #include <sigma/graphics/static_mesh.hpp> #include <sigma/buddy_array_allocator.hpp> #include <sigma/config.hpp> #include <sigma/resource/cache.hpp> #include <glad/glad.h> #include <cstddef> #define VERTEX_BLOCK_SIZE 64 #define MAX_VERTEX_BLOCKS 512 #define INDEX_BLOCK_SIZE 63 #define MAX_INDEX_BLOCKS 1040 namespace sigma { namespace opengl { class static_mesh_manager { public: struct mesh_buffer { std::size_t batch_index = -1; std::size_t base_vertex = 0; std::size_t base_index = 0; }; static_mesh_manager(resource::cache<graphics::static_mesh>& static_mesh_cache); static_mesh_manager(static_mesh_manager&&) = default; static_mesh_manager& operator=(static_mesh_manager&&) = default; ~static_mesh_manager(); std::size_t batch_size() const; void bind_batch(std::size_t batch); std::pair<graphics::static_mesh*, mesh_buffer> acquire(const resource::handle<graphics::static_mesh>& hndl); private: static_mesh_manager(const static_mesh_manager&) = delete; static_mesh_manager& operator=(const static_mesh_manager&) = delete; resource::cache<graphics::static_mesh>& static_mesh_cache_; std::vector<mesh_buffer> static_meshes_; struct buffer_batch { GLuint vertex_array = 0; // MAX_VERTEX_BLOCKS blocks of VERTEX_BLOCK_SIZE vertices. buddy_array_allocator vertex_allocator { MAX_VERTEX_BLOCKS }; GLuint vertex_buffer = 0; // MAX_INDEX_BLOCKS blocks of INDEX_BLOCK_SIZE indicies. buddy_array_allocator index_allocator { MAX_INDEX_BLOCKS }; GLuint index_buffer = 0; }; std::vector<buffer_batch> batches_; }; } } #endif // SIGMA_ENGINE_STATIC_MESH_MANAGER_HPP
[ "siegelaaron94@gmail.com" ]
siegelaaron94@gmail.com
15f494bd7f799352f6018d9f93f3a4861bec5e4b
43119a707e0ab4790a4bda74bb40f1715f906b56
/Regular_Batch/1b_HelloWorld_EXPLAINED.cpp
f2f22b1517f79b68e51afb376235961d0c544317
[]
no_license
gouthamkrishnakv/csea-secondyr-workshop
6098a56f9d7bc1a8c2a1007fa2bcc0fe6179d2b9
296005a5f1c30e702d3bdce032964bc95d92654c
refs/heads/master
2023-01-29T03:52:18.993832
2019-01-08T18:32:37
2019-01-08T18:32:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
997
cpp
// YOUR FIRST PROGRAM // ANYTHING STARTING WITH A '#'IS CALLED A PREPROCESSOR DIRECTIVE. // THIS TELLS THE COMPILER WHAT TO DO BEFORE COMPILATION, // LIKE ADDING OTHER LIBRARIES, DEFINING MACROS (WE'LL GO THROUGH THAT LATER). // 'include' DIRECTIVE TELLS THE COMPILER WHICH ALL LIBRARIES TO INCLUDE BEFORE EXECUTION // WE INCLUDED THE LIBRARY 'iostream' TO ENABLE INPUT/OUTPUT FOR THE PROGRAM. // 'IOSTREAM' MANAGES INPUT OUTPUT STREAMS. #include <iostream> // 'std' MANAGES STANDARD I/O METHODS HERE. MAKES cout & cin WORK. using namespace std; // main FUNCTION --> START OF EVERY PROGRAM, PROGRAM STARTS BY EXECUTING CODE FROM main FUNCTION int main() { // cout --> Used to output the file onto the terminal cout << "Hello World!\n"; // EVERY PROGRAM ENDS WHEN THE MAIN FUNCTION RETURNS A VALUE, IN THIS CASE 0. // 0 IS TRADITIONALLY EXPECTED TO BE RETURNED BY THE PROGRAM IF THE PROGRAM // WORKED PROPERLY. YOU CAN RETURN ANY INTEGER VALUE HERE THOUGH. return 0; }
[ "gauthamkrishna9991@live.com" ]
gauthamkrishna9991@live.com
4e33ca5c39bf307186c60a7d5203e063d72f154a
864431c315f13c034b11c1475bb5baf2a81cbd9f
/Kernel/ThreadBlockers.cpp
d1e8b2cbb567bf6eefcf28911debf029c95a68e9
[ "BSD-2-Clause" ]
permissive
zbennett10/serenity
de653b4db637b9e62f817813192105c515359bc4
47a4a5ac1d3631a3df0a2b9f8c242b2decec826a
refs/heads/master
2023-02-19T03:35:48.662438
2021-01-21T10:34:46
2021-01-21T10:35:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
25,936
cpp
/* * Copyright (c) 2020, The SerenityOS developers. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <Kernel/FileSystem/FileDescription.h> #include <Kernel/Net/Socket.h> #include <Kernel/Process.h> #include <Kernel/Scheduler.h> #include <Kernel/Thread.h> //#define WAITBLOCK_DEBUG namespace Kernel { bool Thread::Blocker::set_block_condition(Thread::BlockCondition& block_condition, void* data) { ASSERT(!m_block_condition); if (block_condition.add_blocker(*this, data)) { m_block_condition = &block_condition; m_block_data = data; return true; } return false; } Thread::Blocker::~Blocker() { ScopedSpinLock lock(m_lock); if (m_block_condition) m_block_condition->remove_blocker(*this, m_block_data); } void Thread::Blocker::begin_blocking(Badge<Thread>) { ScopedSpinLock lock(m_lock); ASSERT(!m_is_blocking); ASSERT(!m_blocked_thread); m_blocked_thread = Thread::current(); m_is_blocking = true; } auto Thread::Blocker::end_blocking(Badge<Thread>, bool did_timeout) -> BlockResult { ScopedSpinLock lock(m_lock); // if m_is_blocking is false here, some thread forced to // unblock us when we get here. This is only called from the // thread that was blocked. ASSERT(Thread::current() == m_blocked_thread); m_is_blocking = false; m_blocked_thread = nullptr; was_unblocked(did_timeout); return block_result(); } Thread::JoinBlocker::JoinBlocker(Thread& joinee, KResult& try_join_result, void*& joinee_exit_value) : m_joinee(joinee) , m_joinee_exit_value(joinee_exit_value) { { // We need to hold our lock to avoid a race where try_join succeeds // but the joinee is joining immediately ScopedSpinLock lock(m_lock); try_join_result = joinee.try_join([&]() { if (!set_block_condition(joinee.m_join_condition)) m_should_block = false; }); m_join_error = try_join_result.is_error(); if (m_join_error) m_should_block = false; } } void Thread::JoinBlocker::not_blocking(bool timeout_in_past) { if (!m_should_block) { // set_block_condition returned false, so unblock was already called ASSERT(!timeout_in_past); return; } // If we should have blocked but got here it must have been that the // timeout was already in the past. So we need to ask the BlockCondition // to supply us the information. We cannot hold the lock as unblock // could be called by the BlockCondition at any time! ASSERT(timeout_in_past); m_joinee->m_join_condition.try_unblock(*this); } bool Thread::JoinBlocker::unblock(void* value, bool from_add_blocker) { { ScopedSpinLock lock(m_lock); if (m_did_unblock) return false; m_did_unblock = true; m_joinee_exit_value = value; do_set_interrupted_by_death(); } if (!from_add_blocker) unblock_from_blocker(); return true; } Thread::QueueBlocker::QueueBlocker(WaitQueue& wait_queue, const char* block_reason) : m_block_reason(block_reason) { if (!set_block_condition(wait_queue, Thread::current())) m_should_block = false; } Thread::QueueBlocker::~QueueBlocker() { } bool Thread::QueueBlocker::unblock() { { ScopedSpinLock lock(m_lock); if (m_did_unblock) return false; m_did_unblock = true; } unblock_from_blocker(); return true; } Thread::FutexBlocker::FutexBlocker(FutexQueue& futex_queue, u32 bitset) : m_bitset(bitset) { if (!set_block_condition(futex_queue, Thread::current())) m_should_block = false; } Thread::FutexBlocker::~FutexBlocker() { } void Thread::FutexBlocker::finish_requeue(FutexQueue& futex_queue) { ASSERT(m_lock.own_lock()); set_block_condition_raw_locked(&futex_queue); // We can now releas the lock m_lock.unlock(m_relock_flags); } bool Thread::FutexBlocker::unblock_bitset(u32 bitset) { { ScopedSpinLock lock(m_lock); if (m_did_unblock || (bitset != FUTEX_BITSET_MATCH_ANY && (m_bitset & bitset) == 0)) return false; m_did_unblock = true; } unblock_from_blocker(); return true; } bool Thread::FutexBlocker::unblock(bool force) { { ScopedSpinLock lock(m_lock); if (m_did_unblock) return force; m_did_unblock = true; } unblock_from_blocker(); return true; } Thread::FileDescriptionBlocker::FileDescriptionBlocker(FileDescription& description, BlockFlags flags, BlockFlags& unblocked_flags) : m_blocked_description(description) , m_flags(flags) , m_unblocked_flags(unblocked_flags) { m_unblocked_flags = BlockFlags::None; if (!set_block_condition(description.block_condition())) m_should_block = false; } bool Thread::FileDescriptionBlocker::unblock(bool from_add_blocker, void*) { auto unblock_flags = m_blocked_description->should_unblock(m_flags); if (unblock_flags == BlockFlags::None) return false; { ScopedSpinLock lock(m_lock); if (m_did_unblock) return false; m_did_unblock = true; m_unblocked_flags = unblock_flags; } if (!from_add_blocker) unblock_from_blocker(); return true; } void Thread::FileDescriptionBlocker::not_blocking(bool timeout_in_past) { if (!m_should_block) { // set_block_condition returned false, so unblock was already called ASSERT(!timeout_in_past); return; } // If we should have blocked but got here it must have been that the // timeout was already in the past. So we need to ask the BlockCondition // to supply us the information. We cannot hold the lock as unblock // could be called by the BlockCondition at any time! ASSERT(timeout_in_past); // Just call unblock here because we will query the file description // for the data and don't need any input from the FileBlockCondition. // However, it's possible that if timeout_in_past is true then FileBlockCondition // may call us at any given time, so our call to unblock here may fail. // Either way, unblock will be called at least once, which provides // all the data we need. unblock(false, nullptr); } const FileDescription& Thread::FileDescriptionBlocker::blocked_description() const { return m_blocked_description; } Thread::AcceptBlocker::AcceptBlocker(FileDescription& description, BlockFlags& unblocked_flags) : FileDescriptionBlocker(description, (BlockFlags)((u32)BlockFlags::Accept | (u32)BlockFlags::Exception), unblocked_flags) { } Thread::ConnectBlocker::ConnectBlocker(FileDescription& description, BlockFlags& unblocked_flags) : FileDescriptionBlocker(description, (BlockFlags)((u32)BlockFlags::Connect | (u32)BlockFlags::Exception), unblocked_flags) { } Thread::WriteBlocker::WriteBlocker(FileDescription& description, BlockFlags& unblocked_flags) : FileDescriptionBlocker(description, (BlockFlags)((u32)BlockFlags::Write | (u32)BlockFlags::Exception), unblocked_flags) { } auto Thread::WriteBlocker::override_timeout(const BlockTimeout& timeout) -> const BlockTimeout& { auto& description = blocked_description(); if (description.is_socket()) { auto& socket = *description.socket(); if (socket.has_send_timeout()) { m_timeout = BlockTimeout(false, &socket.send_timeout(), timeout.start_time(), timeout.clock_id()); if (timeout.is_infinite() || (!m_timeout.is_infinite() && m_timeout.absolute_time() < timeout.absolute_time())) return m_timeout; } } return timeout; } Thread::ReadBlocker::ReadBlocker(FileDescription& description, BlockFlags& unblocked_flags) : FileDescriptionBlocker(description, (BlockFlags)((u32)BlockFlags::Read | (u32)BlockFlags::Exception), unblocked_flags) { } auto Thread::ReadBlocker::override_timeout(const BlockTimeout& timeout) -> const BlockTimeout& { auto& description = blocked_description(); if (description.is_socket()) { auto& socket = *description.socket(); if (socket.has_receive_timeout()) { m_timeout = BlockTimeout(false, &socket.receive_timeout(), timeout.start_time(), timeout.clock_id()); if (timeout.is_infinite() || (!m_timeout.is_infinite() && m_timeout.absolute_time() < timeout.absolute_time())) return m_timeout; } } return timeout; } Thread::SleepBlocker::SleepBlocker(const BlockTimeout& deadline, timespec* remaining) : m_deadline(deadline) , m_remaining(remaining) { } auto Thread::SleepBlocker::override_timeout(const BlockTimeout& timeout) -> const BlockTimeout& { ASSERT(timeout.is_infinite()); // A timeout should not be provided // To simplify things only use the sleep deadline. return m_deadline; } void Thread::SleepBlocker::not_blocking(bool timeout_in_past) { // SleepBlocker::should_block should always return true, so timeout // in the past is the only valid case when this function is called ASSERT(timeout_in_past); calculate_remaining(); } void Thread::SleepBlocker::was_unblocked(bool did_timeout) { Blocker::was_unblocked(did_timeout); calculate_remaining(); } void Thread::SleepBlocker::calculate_remaining() { if (!m_remaining) return; auto time_now = TimeManagement::the().current_time(m_deadline.clock_id()).value(); if (time_now < m_deadline.absolute_time()) timespec_sub(m_deadline.absolute_time(), time_now, *m_remaining); else *m_remaining = {}; } Thread::BlockResult Thread::SleepBlocker::block_result() { auto result = Blocker::block_result(); if (result == Thread::BlockResult::InterruptedByTimeout) return Thread::BlockResult::WokeNormally; return result; } Thread::SelectBlocker::SelectBlocker(FDVector& fds) : m_fds(fds) { for (auto& fd_entry : m_fds) { fd_entry.unblocked_flags = FileBlocker::BlockFlags::None; if (!m_should_block) continue; if (!fd_entry.description->block_condition().add_blocker(*this, &fd_entry)) m_should_block = false; } } Thread::SelectBlocker::~SelectBlocker() { for (auto& fd_entry : m_fds) fd_entry.description->block_condition().remove_blocker(*this, &fd_entry); } void Thread::SelectBlocker::not_blocking(bool timeout_in_past) { // Either the timeout was in the past or we didn't add all blockers ASSERT(timeout_in_past || !m_should_block); ScopedSpinLock lock(m_lock); if (!m_did_unblock) { m_did_unblock = true; if (!timeout_in_past) { auto count = collect_unblocked_flags(); ASSERT(count > 0); } } } bool Thread::SelectBlocker::unblock(bool from_add_blocker, void* data) { ASSERT(data); // data is a pointer to an entry in the m_fds vector auto& fd_info = *static_cast<FDInfo*>(data); { ScopedSpinLock lock(m_lock); if (m_did_unblock) return false; auto unblock_flags = fd_info.description->should_unblock(fd_info.block_flags); if (unblock_flags == BlockFlags::None) return false; m_did_unblock = true; // We need to store unblock_flags here, otherwise someone else // affecting this file descriptor could change the information // between now and when was_unblocked is called! fd_info.unblocked_flags = unblock_flags; } // Only do this once for the first one if (!from_add_blocker) unblock_from_blocker(); return true; } size_t Thread::SelectBlocker::collect_unblocked_flags() { size_t count = 0; for (auto& fd_entry : m_fds) { ASSERT(fd_entry.block_flags != FileBlocker::BlockFlags::None); // unblock will have set at least the first descriptor's unblock // flags that triggered the unblock. Make sure we don't discard that // information as it may have changed by now! if (fd_entry.unblocked_flags == FileBlocker::BlockFlags::None) fd_entry.unblocked_flags = fd_entry.description->should_unblock(fd_entry.block_flags); if (fd_entry.unblocked_flags != FileBlocker::BlockFlags::None) count++; } return count; } void Thread::SelectBlocker::was_unblocked(bool did_timeout) { Blocker::was_unblocked(did_timeout); if (!did_timeout && !was_interrupted()) { { ScopedSpinLock lock(m_lock); ASSERT(m_did_unblock); } size_t count = collect_unblocked_flags(); // If we were blocked and didn't time out, we should have at least one unblocked fd! ASSERT(count > 0); } } Thread::WaitBlockCondition::ProcessBlockInfo::ProcessBlockInfo(NonnullRefPtr<Process>&& process, WaitBlocker::UnblockFlags flags, u8 signal) : process(move(process)) , flags(flags) , signal(signal) { } Thread::WaitBlockCondition::ProcessBlockInfo::~ProcessBlockInfo() { } void Thread::WaitBlockCondition::try_unblock(Thread::WaitBlocker& blocker) { ScopedSpinLock lock(m_lock); // We if we have any processes pending for (size_t i = 0; i < m_processes.size(); i++) { auto& info = m_processes[i]; // We need to call unblock as if we were called from add_blocker // so that we don't trigger a context switch by yielding! if (info.was_waited && blocker.is_wait()) continue; // This state was already waited on, do not unblock if (blocker.unblock(info.process, info.flags, info.signal, true)) { if (blocker.is_wait()) { if (info.flags == Thread::WaitBlocker::UnblockFlags::Terminated) { m_processes.remove(i); #ifdef WAITBLOCK_DEBUG dbg() << "WaitBlockCondition[" << m_process << "] terminated, remove " << *info.process; #endif } else { #ifdef WAITBLOCK_DEBUG dbg() << "WaitBlockCondition[" << m_process << "] terminated, mark as waited " << *info.process; #endif info.was_waited = true; } } break; } } } void Thread::WaitBlockCondition::disowned_by_waiter(Process& process) { ScopedSpinLock lock(m_lock); if (m_finalized) return; for (size_t i = 0; i < m_processes.size();) { auto& info = m_processes[i]; if (info.process == &process) { do_unblock([&](Blocker& b, void*, bool&) { ASSERT(b.blocker_type() == Blocker::Type::Wait); auto& blocker = static_cast<WaitBlocker&>(b); bool did_unblock = blocker.unblock(info.process, WaitBlocker::UnblockFlags::Disowned, 0, false); ASSERT(did_unblock); // disowning must unblock everyone return true; }); #ifdef WAITBLOCK_DEBUG dbg() << "WaitBlockCondition[" << m_process << "] disowned " << *info.process; #endif m_processes.remove(i); continue; } i++; } } bool Thread::WaitBlockCondition::unblock(Process& process, WaitBlocker::UnblockFlags flags, u8 signal) { ASSERT(flags != WaitBlocker::UnblockFlags::Disowned); bool did_unblock_any = false; bool did_wait = false; bool was_waited_already = false; ScopedSpinLock lock(m_lock); if (m_finalized) return false; if (flags != WaitBlocker::UnblockFlags::Terminated) { // First check if this state was already waited on for (auto& info : m_processes) { if (info.process == &process) { was_waited_already = info.was_waited; break; } } } do_unblock([&](Blocker& b, void*, bool&) { ASSERT(b.blocker_type() == Blocker::Type::Wait); auto& blocker = static_cast<WaitBlocker&>(b); if (was_waited_already && blocker.is_wait()) return false; // This state was already waited on, do not unblock if (blocker.unblock(process, flags, signal, false)) { did_wait |= blocker.is_wait(); // anyone requesting a wait did_unblock_any = true; return true; } return false; }); // If no one has waited (yet), or this wasn't a wait, or if it's anything other than // UnblockFlags::Terminated then add it to your list if (!did_unblock_any || !did_wait || flags != WaitBlocker::UnblockFlags::Terminated) { bool updated_existing = false; for (auto& info : m_processes) { if (info.process == &process) { ASSERT(info.flags != WaitBlocker::UnblockFlags::Terminated); info.flags = flags; info.signal = signal; info.was_waited = did_wait; #ifdef WAITBLOCK_DEBUG dbg() << "WaitBlockCondition[" << m_process << "] update " << process << " flags: " << (int)flags << " mark as waited: " << info.was_waited; #endif updated_existing = true; break; } } if (!updated_existing) { #ifdef WAITBLOCK_DEBUG dbg() << "WaitBlockCondition[" << m_process << "] add " << process << " flags: " << (int)flags; #endif m_processes.append(ProcessBlockInfo(process, flags, signal)); } } return did_unblock_any; } bool Thread::WaitBlockCondition::should_add_blocker(Blocker& b, void*) { // NOTE: m_lock is held already! if (m_finalized) return false; ASSERT(b.blocker_type() == Blocker::Type::Wait); auto& blocker = static_cast<WaitBlocker&>(b); // See if we can match any process immediately for (size_t i = 0; i < m_processes.size(); i++) { auto& info = m_processes[i]; if (blocker.unblock(info.process, info.flags, info.signal, true)) { // Only remove the entry if UnblockFlags::Terminated if (info.flags == Thread::WaitBlocker::UnblockFlags::Terminated && blocker.is_wait()) m_processes.remove(i); return false; } } return true; } void Thread::WaitBlockCondition::finalize() { ScopedSpinLock lock(m_lock); ASSERT(!m_finalized); m_finalized = true; // Clear the list of threads here so we can drop the references to them m_processes.clear(); // No more waiters, drop the last reference immediately. This may // cause us to be destructed ourselves! ASSERT(m_process.ref_count() > 0); m_process.unref(); } Thread::WaitBlocker::WaitBlocker(int wait_options, idtype_t id_type, pid_t id, KResultOr<siginfo_t>& result) : m_wait_options(wait_options) , m_id_type(id_type) , m_waitee_id(id) , m_result(result) , m_should_block(!(m_wait_options & WNOHANG)) { switch (id_type) { case P_PID: { m_waitee = Process::from_pid(m_waitee_id); if (!m_waitee || m_waitee->ppid() != Process::current()->pid()) { m_result = ECHILD; m_error = true; return; } break; } case P_PGID: { m_waitee_group = ProcessGroup::from_pgid(m_waitee_id); if (!m_waitee_group) { m_result = ECHILD; m_error = true; return; } break; } case P_ALL: break; default: ASSERT_NOT_REACHED(); } // NOTE: unblock may be called within set_block_condition, in which // case it means that we already have a match without having to block. // In that case set_block_condition will return false. if (m_error || !set_block_condition(Process::current()->wait_block_condition())) m_should_block = false; } void Thread::WaitBlocker::not_blocking(bool timeout_in_past) { ASSERT(timeout_in_past || !m_should_block); if (!m_error) Process::current()->wait_block_condition().try_unblock(*this); } void Thread::WaitBlocker::was_unblocked(bool) { bool got_sigchld, try_unblock; { ScopedSpinLock lock(m_lock); try_unblock = !m_did_unblock; got_sigchld = m_got_sigchild; } if (try_unblock) Process::current()->wait_block_condition().try_unblock(*this); // If we were interrupted by SIGCHLD (which gets special handling // here) we're not going to return with EINTR. But we're going to // deliver SIGCHLD (only) here. auto* current_thread = Thread::current(); if (got_sigchld && current_thread->state() != State::Stopped) current_thread->try_dispatch_one_pending_signal(SIGCHLD); } void Thread::WaitBlocker::do_was_disowned() { ASSERT(!m_did_unblock); m_did_unblock = true; m_result = ECHILD; } void Thread::WaitBlocker::do_set_result(const siginfo_t& result) { ASSERT(!m_did_unblock); m_did_unblock = true; m_result = result; if (do_get_interrupted_by_signal() == SIGCHLD) { // This makes it so that wait() will return normally despite the // fact that SIGCHLD was delivered. Calling do_clear_interrupted_by_signal // will disable dispatching signals in Thread::block and prevent // it from returning with EINTR. We will then manually dispatch // SIGCHLD (and only SIGCHLD) in was_unblocked. m_got_sigchild = true; do_clear_interrupted_by_signal(); } } bool Thread::WaitBlocker::unblock(Process& process, UnblockFlags flags, u8 signal, bool from_add_blocker) { ASSERT(flags != UnblockFlags::Terminated || signal == 0); // signal argument should be ignored for Terminated switch (m_id_type) { case P_PID: ASSERT(m_waitee); if (process.pid() != m_waitee_id) return false; break; case P_PGID: ASSERT(m_waitee_group); if (process.pgid() != m_waitee_group->pgid()) return false; break; case P_ALL: if (flags == UnblockFlags::Disowned) { // Generic waiter won't be unblocked by disown return false; } break; default: ASSERT_NOT_REACHED(); } switch (flags) { case UnblockFlags::Terminated: if (!(m_wait_options & WEXITED)) return false; break; case UnblockFlags::Stopped: if (!(m_wait_options & WSTOPPED)) return false; if (!(m_wait_options & WUNTRACED) && !process.is_traced()) return false; break; case UnblockFlags::Continued: if (!(m_wait_options & WCONTINUED)) return false; if (!(m_wait_options & WUNTRACED) && !process.is_traced()) return false; break; case UnblockFlags::Disowned: ScopedSpinLock lock(m_lock); // Disowning must unblock anyone waiting for this process explicitly if (!m_did_unblock) do_was_disowned(); return true; } if (flags == UnblockFlags::Terminated) { ASSERT(process.is_dead()); ScopedSpinLock lock(m_lock); if (m_did_unblock) return false; // Up until this point, this function may have been called // more than once! do_set_result(process.wait_info()); } else { siginfo_t siginfo; memset(&siginfo, 0, sizeof(siginfo)); { ScopedSpinLock lock(g_scheduler_lock); // We need to gather the information before we release the sheduler lock! siginfo.si_signo = SIGCHLD; siginfo.si_pid = process.pid().value(); siginfo.si_uid = process.uid(); siginfo.si_status = signal; switch (flags) { case UnblockFlags::Terminated: case UnblockFlags::Disowned: ASSERT_NOT_REACHED(); case UnblockFlags::Stopped: siginfo.si_code = CLD_STOPPED; break; case UnblockFlags::Continued: siginfo.si_code = CLD_CONTINUED; break; } } ScopedSpinLock lock(m_lock); if (m_did_unblock) return false; // Up until this point, this function may have been called // more than once! do_set_result(siginfo); } if (!from_add_blocker) { // Only call unblock if we weren't called from within set_block_condition! ASSERT(flags != UnblockFlags::Disowned); unblock_from_blocker(); } // Because this may be called from add_blocker, in which case we should // not be actually trying to unblock the thread (because it hasn't actually // been blocked yet), we need to return true anyway return true; } }
[ "kling@serenityos.org" ]
kling@serenityos.org
56aa4a9b3c5b73f7db659a71b55d7b97b06292fc
48e7dfc263778cc53d56e055f5c4c48fa1d29efc
/Source/Aren/Pawns/CampPawn.cpp
da0b6e989db45ea7ced068f818c488845624b4d9
[]
no_license
JBeluche/aren
11955c84e6c26148c67bfbd2de21716fb4012061
32f76a073b4193f080c840d640e6541673242dfb
refs/heads/master
2023-06-06T18:00:25.485477
2021-07-08T13:50:47
2021-07-08T13:50:47
339,785,757
0
0
null
null
null
null
UTF-8
C++
false
false
946
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "Aren/Pawns/CampPawn.h" #include "GameFramework/SpringArmComponent.h" #include "Camera/CameraComponent.h" // Sets default values ACampPawn::ACampPawn() { // Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = false; SpringArmComponent = CreateDefaultSubobject<USpringArmComponent>(TEXT("Spring Arm")); RootComponent = SpringArmComponent; CameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("Camera")); CameraComponent->SetupAttachment(RootComponent); } // Called when the game starts or when spawned void ACampPawn::BeginPlay() { Super::BeginPlay(); } // Called to bind functionality to input void ACampPawn::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); }
[ "j.beluche@outlook.com" ]
j.beluche@outlook.com
9fb62648e7f50d9df404100717c76480710acc92
0b63fa8325233e25478b76d0b4a9a6ee3070056d
/src/appleseed/foundation/utility/xmlelement.h
9f827ae98500567f674b88dbbd2763b9b0655cc4
[ "MIT" ]
permissive
hipopotamo-hipotalamo/appleseed
e8c61ccec64baf01b6aeb3cde4dd3031d37ece17
eaf07e3e602218a35711e7495ac633ce210c6078
refs/heads/master
2020-12-07T02:39:27.454003
2013-10-29T13:10:59
2013-10-29T13:10:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,307
h
// // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #ifndef APPLESEED_FOUNDATION_UTILITY_XMLELEMENT_H #define APPLESEED_FOUNDATION_UTILITY_XMLELEMENT_H // appleseed.foundation headers. #include "foundation/utility/containers/dictionary.h" #include "foundation/utility/foreach.h" #include "foundation/utility/indenter.h" #include "foundation/utility/string.h" // Standard headers. #include <cassert> #include <cstdio> #include <string> #include <utility> #include <vector> namespace foundation { // // A class representing a XML element. // class XMLElement { public: // Constructor, opens the element. XMLElement( const std::string& name, std::FILE* file, Indenter& indenter); // Destructor, closes the element. ~XMLElement(); // Append an attribute to the element. template <typename T> void add_attribute( const std::string& name, const T& value); // Write the element. void write(const bool has_content); // Close the element. void close(); private: typedef std::pair<std::string, std::string> Attribute; typedef std::vector<Attribute> AttributeVector; const std::string m_name; std::FILE* m_file; Indenter& m_indenter; AttributeVector m_attributes; bool m_opened; }; // // An utility function to write a dictionary to an XML file. // // Example: a dictionary containing two scalar values "x" and "y" // and a child dictionary "nested" containing a scalar value "z" // will be written as follow: // // <parameter name="x" value="17" /> // <parameter name="y" value="42" /> // <parameters name="nested"> // <parameter name="z" value="66" /> // </parameters> // void write_dictionary( const Dictionary& dictionary, std::FILE* file, Indenter& indenter); // // Implementation. // inline XMLElement::XMLElement( const std::string& name, std::FILE* file, Indenter& indenter) : m_name(name) , m_file(file) , m_indenter(indenter) , m_opened(false) { } inline XMLElement::~XMLElement() { close(); } template <typename T> void XMLElement::add_attribute( const std::string& name, const T& value) { assert(!m_opened); m_attributes.push_back(std::make_pair(name, to_string(value))); } inline void XMLElement::write(const bool has_content) { assert(!m_opened); std::fprintf(m_file, "%s<%s", m_indenter.c_str(), m_name.c_str()); for (const_each<AttributeVector> i = m_attributes; i; ++i) { const std::string attribute_value = replace_special_xml_characters(i->second); std::fprintf(m_file, " %s=\"%s\"", i->first.c_str(), attribute_value.c_str()); } if (has_content) { std::fprintf(m_file, ">\n"); ++m_indenter; m_opened = true; } else { std::fprintf(m_file, " />\n"); } } inline void XMLElement::close() { if (m_opened) { --m_indenter; std::fprintf(m_file, "%s</%s>\n", m_indenter.c_str(), m_name.c_str()); m_opened = false; } } inline void write_dictionary( const Dictionary& dictionary, std::FILE* file, Indenter& indenter) { for (const_each<StringDictionary> i = dictionary.strings(); i; ++i) { XMLElement element("parameter", file, indenter); element.add_attribute("name", i->name()); element.add_attribute("value", i->value<std::string>()); element.write(false); } for (const_each<DictionaryDictionary> i = dictionary.dictionaries(); i; ++i) { XMLElement element("parameters", file, indenter); element.add_attribute("name", i->name()); element.write(true); write_dictionary(i->value(), file, indenter); } } } // namespace foundation #endif // !APPLESEED_FOUNDATION_UTILITY_XMLELEMENT_H
[ "beaune@aist.enst.fr" ]
beaune@aist.enst.fr
a0297eb043e3e7166b311fe4ffb9e638e304d3b0
51ea7d94c07acce8afd538a2b1b011a8c2082362
/programs/dataSource/cdatatransfer.cpp
bd59d1295272b307d223296e1ae19207025736b9
[]
no_license
noachain/dapp
29ecb9c5606c804289bdfbe3a3bdea9c46f8a62f
27dfcb63b988d771e792dd7282feb22a27809028
refs/heads/master
2020-03-21T22:27:42.632232
2018-06-29T09:19:33
2018-06-29T09:19:33
139,127,915
0
0
null
null
null
null
UTF-8
C++
false
false
685
cpp
#include "cdatatransfer.h" using namespace std; CDataTransfer::CDataTransfer() { } void CDataTransfer::initIpfs() { } void CDataTransfer::uploadMetadata(const std::string &strUrl, int eLoadType) { } void CDataTransfer::downloadMetadata(const std::string &strIpfsHash, int eDownloadSaveType) { } void CDataTransfer::uploadCiphertext(const string &strUrl, int eLoadType) { } void CDataTransfer::downloadCiphertext(const string &strIpfsHase, int eDownloadSaveType) { } void CDataTransfer::uploadFhlibContent(const FHEcontext *context, const FHEPubKey *pkey) { } void CDataTransfer::downloadFhlibContent(FHEcontext *context, FHEPubKey *pkey, const string &strIpfsHash) { }
[ "paizzj@126.com" ]
paizzj@126.com
ff77aa8f6b1e8b328486db160b5d90fc4c76cbee
aa887833c7c5fc6557dae37eef325e14743bbbd3
/3.cpp
a4a0d6f8a24fdb56c568ba5a35a5d247faeac153
[]
no_license
qpwo2468/github-upload
f28dba6949e2d7d4f5d674282ed4f389fa45b0e3
e7e1e921aa10ee8b5e37d3afa2c75c52154c814d
refs/heads/master
2022-10-23T04:43:53.000605
2020-06-05T02:18:59
2020-06-05T02:18:59
269,505,187
0
0
null
null
null
null
GB18030
C++
false
false
1,987
cpp
/* 题目: 输入一个链表,按链表从尾到头的顺序返回一个ArrayList。 思路: 1. 使用栈保存链表,然后存入vector 2. 使用递归操作(写法简单,但不推荐,容易爆) 3. 直接存入vector, 然后反转 4. 反转链表存入vector */ #include <iostream> #include <vector> #include <stack> #include <algorithm> using namespace std; struct ListNode { int val; struct ListNode* next; ListNode(int x) : val(x), next(nullptr) {} }; //1 vector<int> printListFromTailToHead(ListNode* head) { stack<int> data; vector<int> result; while (head != NULL) { data.push(head->val); head = head->next; } int size = data.size(); for (int i = 0; i < size; i++) { result.push_back(data.top()); data.pop(); } return result; } //2 vector<int >result; vector<int> printListFromTailToHead(ListNode* head) { if (head != NULL) { if(head->next != NULL) printListFromTailToHead(head->next); result.push_back(head->val); } return result; } //3 vector<int> printListFromTailToHead(ListNode* head) { vector<int> result; while (head != NULL) { result.push_back(head->val); head = head->next; } for (int i = 0; i < result.size() / 2; i++) { int temp = result[i]; result[i] = result[result.size() - i - 1]; result[result.size() - i - 1] = temp; } return result; } //4 vector<int> printListFromTailToHead(ListNode* head) { vector<int> result; struct ListNode* newHead; struct ListNode* temp; struct ListNode* node = NULL; while (head != NULL) { temp = head->next; newHead = head; newHead->next = node; node = newHead; head = temp; } while (newHead != NULL) { result.push_back(newHead->val); newHead = newHead->next; } return result; }
[ "songyj@7invensun.com" ]
songyj@7invensun.com
24a8ec802831ae3a87b95a5f69c8013751f4b74e
d9fa902ccf801f9ab78b316e35573e21328754e8
/src/Werk/Utility/Action.cpp
a315f24b5bbafdd634a1bd7fd8cb947485fabd88
[ "MIT" ]
permissive
kelvinxue/Werk
9f3d3925067c7303a2a73cc02aed98a17e7229b5
d972df393d0e2945ea3d2a388c11e4421b9db5d9
refs/heads/master
2020-03-27T14:54:05.134853
2018-01-05T02:04:55
2018-01-05T02:04:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,234
cpp
/* * Copyright (c) 2015-2018 Agalmic Ventures LLC (www.agalmicventures.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "Action.hpp" namespace werk { NullAction NULL_ACTION("Null"); }
[ "ihutchinson@agalmicventures.com" ]
ihutchinson@agalmicventures.com
06f44310aedad1cb8e3ce34061e376fea99bd70d
6446c6e0649895e8b8fc6442e334f92641df4d15
/branches/0.5.2.Stoepsel/EScript/Statements/SetAttribute.cpp
46d9f2062d3605043c9f2125eb0ed48d1a67c366
[]
no_license
BackupTheBerlios/escript-svn
e33b5dc2192de09b62078cfcec38ad8eec61747a
36b2e5f69adb768214cd05204a47cf03c09eba9e
refs/heads/master
2016-08-04T17:36:45.234689
2014-01-06T20:08:03
2014-01-06T20:08:03
40,668,676
0
0
null
null
null
null
UTF-8
C++
false
false
3,431
cpp
// SetAttribute.cpp // This file is part of the EScript programming language. // See copyright notice in EScript.h // ------------------------------------------------------ #include "SetAttribute.h" #include "../Runtime/Runtime.h" #include "../Objects/Void.h" #include <iostream> using namespace EScript; //! (ctor) SetAttribute::SetAttribute(Object * obj,identifierId _attrId,Object * valueExp,assignType_t _assignType,int _line): objRef(obj),valueExpRef(valueExp),attrId(_attrId),assignType(_assignType),line(_line) { //ctor } //! (dtor) SetAttribute::~SetAttribute() { //dtor } //! ---|> [Object] std::string SetAttribute::toString()const { std::string s=""; if (!objRef.isNull()) { s+=objRef.toString(); } else s+="_"; s+="."+identifierIdToString(attrId); switch(assignType){ case ASSIGN: s+="="; break; case SET_OBJ_ATTRIBUTE: s+=":="; break; case SET_TYPE_ATTRIBUTE: s+="::="; break; } s+="("+valueExpRef.toString()+") "; return s; } //! ---|> [Object] Object * SetAttribute::execute(Runtime & rt) { if(line>0) rt.setCurrentLine(line); ObjRef valueRef=NULL; if (!valueExpRef.isNull()) { valueRef=rt.executeObj(valueExpRef.get()); if(!rt.assertNormalState(this)) return NULL; /// Bug[20070703] fixed: if(!valueRef.isNull()){ valueRef=valueRef->getRefOrCopy(); }else{ valueRef=Void::get(); } } /// Local variable if (objRef.isNull()) { rt.assignToVariable(attrId,valueRef.get()); return valueRef.detachAndDecrease(); } /// obj.ident ObjRef obj2=rt.executeObj(objRef.get()); if(!rt.assertNormalState(this)) return NULL; if(obj2.isNull()) obj2=Void::get(); if(assignType == ASSIGN){ if(!obj2->assignAttribute(attrId,valueRef.get())){ rt.warn(std::string("Unkown attribute \"")+identifierIdToString(attrId)+"\" ("+ (objRef.isNull()?"":objRef->toDbgString())+"."+identifierIdToString(attrId)+"="+(valueRef.isNull()?"":valueRef->toDbgString())+")"); if(!obj2->setObjAttribute(attrId,valueRef.get())){ rt.warn(std::string("Can't set object attribute \"")+identifierIdToString(attrId)+"\" ("+ (objRef.isNull()?"":objRef->toDbgString())+"."+identifierIdToString(attrId)+"="+(valueRef.isNull()?"":valueRef->toDbgString())+")"); } } }else if(assignType == SET_OBJ_ATTRIBUTE){ if(!obj2->setObjAttribute(attrId,valueRef.get())) rt.warn(std::string("Can't set object attribute \"")+identifierIdToString(attrId)+"\" ("+ (objRef.isNull()?"":objRef->toDbgString())+"."+identifierIdToString(attrId)+"="+(valueRef.isNull()?"":valueRef->toDbgString())+")"); }else if(assignType == SET_TYPE_ATTRIBUTE){ Type * t=obj2.toType<Type>(); if(t){ t->setTypeAttribute(attrId,valueRef.get()); }else{ rt.warn(std::string("Can not set typeAttr to non-Type-Object: \"")+identifierIdToString(attrId)+"\" ("+ (objRef.isNull()?"":objRef->toDbgString())+"."+identifierIdToString(attrId)+"="+(valueRef.isNull()?"":valueRef->toDbgString())+")" +"Setting objAttr instead."); if(!obj2->setObjAttribute(attrId,valueRef.get())){ rt.warn(std::string("Can't set object attribute \"")+identifierIdToString(attrId)+"\" ("+ (objRef.isNull()?"":objRef->toDbgString())+"."+identifierIdToString(attrId)+"="+(valueRef.isNull()?"":valueRef->toDbgString())+")"); } } } return valueRef.detachAndDecrease(); }
[ "claudiusj@5693b1fc-3b75-4070-9b6b-3ce3692a40d5" ]
claudiusj@5693b1fc-3b75-4070-9b6b-3ce3692a40d5
2bc968f11026d8035bf2914bd44da2bfd5d37a7b
04248e705f7ccd9b7900a880b445261b98286cc6
/project/src/skinning/skeleton_joint.hpp
9b079fe04683bcd241f78d72f132419d53988651
[]
no_license
jeanyves-yang/skinning
68360bb5727c59fc9725ea2b6460504a7b284d61
3a37b79e24bf19c48461e7039c1fb62126f2d1fb
refs/heads/master
2021-01-10T08:59:11.976023
2015-11-18T16:48:06
2015-11-18T16:48:06
46,427,539
7
0
null
null
null
null
UTF-8
C++
false
false
1,244
hpp
/* ** TP CPE Lyon ** Copyright (C) 2015 Damien Rohmer ** ** 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/>. */ #pragma once #ifndef SKELETON_JOINT_HPP #define SKELETON_JOINT_HPP #include "../lib/3d/vec3.hpp" #include "../lib/3d/quaternion.hpp" namespace cpe { /** A geometrical joint storing a 3D position and an orientation as a quaternion. */ struct skeleton_joint { skeleton_joint(); skeleton_joint(vec3 const& position_param,quaternion const& orientation_param); /** 3D position of the joint */ vec3 position; /** Orientation of the joint */ quaternion orientation; }; } #endif
[ "jean-yves.yang@mastertp" ]
jean-yves.yang@mastertp
73bdbfd715f3ccc7607bcd04c76a594ad1c15ad5
6df0e4923493e9b8576df58c4615fe7d9041895a
/DWT.cpp
3c7d87f3ad4e734745a7ed36e1b2532b72f31199
[]
no_license
liyuglikz/CoSaMP
3dc80e2a301d762fd58df1c48578e6d4a2425b4c
1a4d3c55017a96af21edcf31784d324567dd5f81
refs/heads/master
2020-03-28T22:10:32.040859
2015-07-28T16:41:38
2015-07-28T16:41:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,197
cpp
#include <math.h> #include <iostream> #include "head.h" //using namespace std; int shift=4; double *h, *h1; double p_alfa, p_beta, p_gama, p_delta, p_kesa,p_t=0.730174 ; void filterset(double t) { h = new double [9]; h1 = new double [7]; *h = (8*t*t*t-6*t*t+3*t)/(1+2*t)*(1/32.)*sqrt(2.0); *(h+1) = (-16*t*t*t+20*t*t-12*t+3)/(1+2*t)*(1/32.)*sqrt(2.0); *(h+2) = (2*t-3)/(1+2*t)*(1/8.)*sqrt(2.0); *(h+3) = (16*t*t*t-20*t*t+28*t+5)/(1+2*t)*(1/32.)*sqrt(2.0); *(h+4) = (-8*t*t*t+6*t*t+5*t+20)/(1+2*t)*(1/16.)*sqrt(2.0); *(h+5) = *(h+3); *(h+6) = *(h+2); *(h+7) = *(h+1); *(h+8) = *(h+0); double r0, r1, s0, t0; r0 = (*(h+4))-2*(*h)*(*(h+3))/(*(h+1)); r1 = (*(h+2))-(*h)-(*h)*(*(h+3))/(*(h+1)); s0 = (*(h+3))-(*(h+1))-(*(h+1))*r0/r1; t0 = r0-2*r1; p_alfa = (*h)/(*(h+1)); p_beta = (*(h+1))/r1; p_gama = r1/s0; p_delta = s0/t0; p_kesa = t0; } void Dwt1D(double *buffer, int buflen) { int i; int itemp; double *d, *s, *p; p = new double [buflen+2*shift]; d = new double [(buflen>>1)+shift]; s = new double [(buflen>>1)+shift]; for (i=0; i<(buflen>>1)+shift; i++){ itemp = i-(shift>>1); *(d+i) = *(p+shift+2*itemp+1) + p_alfa*( *(p+shift+2*itemp)+*(p+shift+2*itemp+2) ); } for (i=0; i<(buflen>>1)+shift-1; i++){ itemp = i+1-(shift>>1); *(s+i+1) = *(p+shift+2*itemp) + p_beta*( *(d+i+1)+*(d+i+1-1) ); } for (i=0; i<(buflen>>1)+shift-1; i++){ //itemp = i-(shift>>1); *(p+shift+(buflen>>1)+i) = *(d+i) + p_gama*( *(s+i)+*(s+i+1)); } /* s2 */ for (i=0; i<(buflen>>1)+shift-1; i++){ // itemp = i-(shift>>1); *(p+i+1) = *(s+i+1) + p_delta*(*(p+(buflen>>1)+shift+i+1) + *(p+(buflen>>1)+shift+i+1-1) ); } /* d3 */ for (i=0; i<(buflen>>1); i++) *(d+i) = *(p+i+(buflen>>1)+shift+(shift>>1)) +p_kesa*(1-p_kesa)*(*(p+i+(shift>>1))); /* s3 */ for (i=0; i<(buflen>>1); i++) *(s+i) = *(p+i+(shift>>1)) -1/p_kesa*(*(d+i)); /* d4 */ for (i=0; i<(buflen>>1); i++) *(buffer+i+(buflen>>1)) = *(d+i) +(p_kesa-1)*(*(s+i)); /* s4 */ for (i=0; i<(buflen>>1); i++) *(buffer+i) = *(s+i) + *(buffer+i+(buflen>>1)); /* for (i=0; i<(buflen>>1); i++){ *(buffer+i) = p_kesa*(*(p+i+(shift>>1))); *(buffer+i+(buflen>>1)) = 1/p_kesa*(*(p+i+(buflen>>1)+shift+(shift>>1))); } */ delete []p; delete []d; delete []s; } void IDwt1D(double *buffer, int buflen) { int i; double *p1, *p2, *s, *d; p1 = new double [(buflen>>1)+shift]; p2 = new double [(buflen>>1)+shift]; s = new double [(buflen>>1)+shift]; d = new double [(buflen>>1)+shift]; /* s3 */ for (i=0; i<(buflen>>1); i++) *(s+i) = *(buffer+i) - *(buffer+i+(buflen>>1)); /* d3 */ for (i=0; i<(buflen>>1); i++) *(d+i) =*(buffer+i+(buflen>>1))- (p_kesa-1)*(*(s+i)); /* s2 */ for (i=0; i<(buflen>>1); i++) *(buffer+i) = *(s+i) + (1/p_kesa)*(*(d+i)); /* d2 */ for (i=0; i<(buflen>>1); i++) *(buffer+i+(buflen>>1)) = *(d+i) - p_kesa*(1-p_kesa)*(*(buffer+i)); for (i=0; i<(shift>>1); i++){ p1[i] = buffer[i+(buflen>>1)-(shift>>1)]; p1[i+(shift>>1)+(buflen>>1)] = buffer[i]; p2[i] = buffer[i+buflen-(shift>>1)]; p2[i+(shift>>1)+(buflen>>1)] = buffer[i+(buflen>>1)]; } for (i=0; i<(buflen>>1); i++){ p1[i+(shift>>1)] = buffer[i]; p2[i+(shift>>1)] = buffer[i+(buflen>>1)]; } for (i=0; i<(shift>>1); i++){ p1[i] = buffer[(shift>>1)-i]; p1[i+(shift>>1)+(buflen>>1)] = buffer[(buflen>>1)-i-1]; p2[i] = buffer[(buflen>>1)+(shift>>1)-i-1]; p2[i+(shift>>1)+(buflen>>1)] = buffer[buflen-i-2]; } for (i=0; i<(buflen>>1); i++){ p1[i+(shift>>1)] = buffer[i]; p2[i+(shift>>1)] = buffer[i+(buflen>>1)]; } /* s1 */ for (i=0; i<(buflen>>1)+shift-1; i++) *(s+i+1) = *(p1+i+1) - p_delta*( *(p2+i+1) + *(p2+i+1-1)); /* d1 */ for (i=0; i<(buflen>>1)+shift-1; i++) *(d+i) = *(p2+i) - p_gama*(*(s+i) + *(s+i+1)); /* p1 = s0 */ for (i=0; i<(buflen>>1)+shift-1; i++) *(p1+i+1) = *(s+i+1) - p_beta*( *(d+i+1)+*(d+i+1-1)); /* p2 = d0 */ for (i=0; i<(buflen>>1)+shift-1; i++) *(p2+i) = *(d+i) - p_alfa*(*(p1+i) + *(p1+i+1)); for (i=0; i<(buflen>>1); i++){ *(buffer+2*i) = *(p1+i+(shift>>1)) ; *(buffer+2*i+1) = *(p2+i+(shift>>1)); } delete []p1; delete []p2; delete []s; delete []d; } void DwtND(double buffer[], int height, int width, int lv) { int i,j,k; int nheight,nwidth; for ( k=0; k<lv; k++){ nheight=height>>k; nwidth=width>>k; double *pdata; pdata = new double [nwidth]; for (i=0; i<nheight; i++){ for(j=0; j<nwidth; j++) *(pdata+j) = *(buffer+i*width+j); Dwt1D(pdata,nwidth); for(j=0; j<nwidth; j++) *(buffer+i*width+j) = *(pdata+j); } delete []pdata; double *p1data; p1data = new double [nheight]; for(j=0; j<nwidth; j++){ for (i=0; i<nheight; i++) *(p1data+i)=*(buffer+i*width+j); Dwt1D(p1data,nheight); for(i=0; i<nwidth; i++) *(buffer+i*width+j) = *(p1data+i); } delete []p1data; } } void IDwtND(double buffer[], int height, int width, int lv) { int i,j,k; int nheight,nwidth; for (k=0; k<lv; k++){ nheight=height>>(lv-k-1); nwidth=width>>(lv-k-1); double *pdata; pdata = new double [nheight]; for(j=0; j<nwidth; j++){ for (i=0; i<nheight; i++) *(pdata+i) = *(buffer+i*width+j); IDwt1D(pdata,nheight); for(i=0; i<nwidth; i++) *(buffer+i*width+j) = *(pdata+i); } delete []pdata; double *p1data; p1data = new double [nwidth]; for (i=0; i<nheight; i++){ for(j=0; j<nwidth; j++) *(p1data+j)=*(buffer+i*width+j); IDwt1D(p1data,nwidth); for(j=0; j<nwidth; j++) *(buffer+i*width+j) = *(p1data+j); } delete []p1data; } } void Adjust(double *ImageData,int bmpHeight,int bmpWidth, double *SparseMat,short *OutData) { double fTempBufforDisp, MaxPixVal,MinPixVal,Diff; int x,y; MaxPixVal=ImageData[0]; MinPixVal=ImageData[0]; for( y=0; y<bmpHeight; y++) { for( x=0; x<bmpWidth; x++) { if(MaxPixVal< ImageData[y*bmpWidth+x]) MaxPixVal=ImageData[y*bmpWidth+x]; if(MinPixVal>ImageData[y*bmpWidth+x]) MinPixVal=ImageData[y*bmpWidth+x]; SparseMat[y*bmpWidth+x]=ImageData[y*bmpWidth+x]; } } Diff=MaxPixVal-MinPixVal; for( y=0;y<bmpHeight/2;y++) for( x=0;x<bmpWidth;x++) { fTempBufforDisp=ImageData[y*bmpWidth+x]; fTempBufforDisp-=MinPixVal; fTempBufforDisp*=255; fTempBufforDisp/=Diff; OutData[y*bmpWidth+x]=(short) fTempBufforDisp; } for( y=bmpHeight/2;y<bmpHeight;y++) for( x=0;x<bmpWidth;x++) { fTempBufforDisp=ImageData[y*bmpWidth+x]; fTempBufforDisp-=MinPixVal; fTempBufforDisp*=255; fTempBufforDisp/=Diff; OutData[y*bmpWidth+x]=(short) fTempBufforDisp; } for( y=bmpHeight*3/4;y<bmpHeight;y++) for( x=0;x<bmpWidth/2;x++) { fTempBufforDisp=ImageData[y*bmpWidth+x]; fTempBufforDisp-=MinPixVal; fTempBufforDisp*=255; fTempBufforDisp/=Diff; OutData[y*bmpWidth+x]=(short) fTempBufforDisp; } for( y=bmpHeight/2;y<bmpHeight*3/4;y++) for( x=0;x<bmpWidth/2;x++) { fTempBufforDisp=ImageData[y*bmpWidth+x]; fTempBufforDisp-=MinPixVal; fTempBufforDisp*=255; fTempBufforDisp/=Diff; OutData[y*bmpWidth+x]=(short) fTempBufforDisp; } }
[ "jtao@cct.lsu.edu" ]
jtao@cct.lsu.edu
1e8ddc2f2fca3bf8b4f5b56b50f707a29d7c36d3
28f0faf491453700d8a0e0dfa1fbcb7e0d088544
/OpenGL/PointLight.cpp
d0c743cb6ab545d2160dea9dfe60d2547934644e
[]
no_license
Zoreno/OpenGLTest
492755d9e91b03baf2d640a20e9af1e1cd27df66
8cab00671e9ece224f5554489527d15aba70997c
refs/heads/master
2021-01-11T15:42:37.196670
2017-03-03T00:31:25
2017-03-03T00:31:25
79,905,346
0
0
null
null
null
null
UTF-8
C++
false
false
791
cpp
#include "PointLight.h" PointLight::PointLight( const glm::vec3& position, const glm::vec3& ambient, const glm::vec3& diffuse, const glm::vec3& specular, float constant, float linear, float quadratic) : position(position), ambient(ambient), diffuse(diffuse), specular(specular), constant(constant), linear(linear), quadratic(quadratic) {} glm::vec3 PointLight::getPosition() const { return position; } float PointLight::getConstant() const { return constant; } float PointLight::getLinear() const { return linear; } float PointLight::getQuadratic() const { return quadratic; } glm::vec3 PointLight::getAmbient() const { return ambient; } glm::vec3 PointLight::getDiffuse() const { return diffuse; } glm::vec3 PointLight::getSpecular() const { return specular; }
[ "metallica317@spray.se" ]
metallica317@spray.se
7897d4f4f641cbf4f1b95b5b42715112a1727630
fe91ffa11707887e4cdddde8f386a8c8e724aa58
/net/reporting/reporting_delivery_agent_unittest.cc
893cdd61eb28ee88d3b2d31eceb564afdc674162
[ "BSD-3-Clause" ]
permissive
akshaymarch7/chromium
78baac2b45526031846ccbaeca96c639d1d60ace
d273c844a313b1e527dec0d59ce70c95fd2bd458
refs/heads/master
2023-02-26T23:48:03.686055
2020-04-15T01:20:07
2020-04-15T01:20:07
255,778,651
2
1
BSD-3-Clause
2020-04-15T02:04:56
2020-04-15T02:04:55
null
UTF-8
C++
false
false
21,755
cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/reporting/reporting_delivery_agent.h" #include <vector> #include "base/json/json_reader.h" #include "base/test/simple_test_tick_clock.h" #include "base/test/values_test_util.h" #include "base/time/time.h" #include "base/timer/mock_timer.h" #include "base/values.h" #include "net/base/backoff_entry.h" #include "net/base/network_isolation_key.h" #include "net/reporting/reporting_cache.h" #include "net/reporting/reporting_report.h" #include "net/reporting/reporting_test_util.h" #include "net/reporting/reporting_uploader.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" #include "url/origin.h" namespace net { namespace { class ReportingDeliveryAgentTest : public ReportingTestBase { protected: ReportingDeliveryAgentTest() { ReportingPolicy policy; policy.endpoint_backoff_policy.num_errors_to_ignore = 0; policy.endpoint_backoff_policy.initial_delay_ms = 60000; policy.endpoint_backoff_policy.multiply_factor = 2.0; policy.endpoint_backoff_policy.jitter_factor = 0.0; policy.endpoint_backoff_policy.maximum_backoff_ms = -1; policy.endpoint_backoff_policy.entry_lifetime_ms = 0; policy.endpoint_backoff_policy.always_use_initial_delay = false; UsePolicy(policy); } const NetworkIsolationKey kNik_ = NetworkIsolationKey::Todo(); const GURL kUrl_ = GURL("https://origin/path"); const GURL kSubdomainUrl_ = GURL("https://sub.origin/path"); const url::Origin kOrigin_ = url::Origin::Create(GURL("https://origin/")); const GURL kEndpoint_ = GURL("https://endpoint/"); const std::string kUserAgent_ = "Mozilla/1.0"; const std::string kGroup_ = "group"; const std::string kType_ = "type"; const base::Time kExpires_ = base::Time::Now() + base::TimeDelta::FromDays(7); const ReportingEndpointGroupKey kGroupKey_ = ReportingEndpointGroupKey(kNik_, kOrigin_, kGroup_); }; TEST_F(ReportingDeliveryAgentTest, SuccessfulImmediateUpload) { base::DictionaryValue body; body.SetString("key", "value"); ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_)); cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_, body.CreateDeepCopy(), 0, tick_clock()->NowTicks(), 0); // Upload is automatically started when cache is modified. ASSERT_EQ(1u, pending_uploads().size()); EXPECT_EQ(kEndpoint_, pending_uploads()[0]->url()); { auto value = pending_uploads()[0]->GetValue(); base::ListValue* list; ASSERT_TRUE(value->GetAsList(&list)); EXPECT_EQ(1u, list->GetSize()); base::DictionaryValue* report; ASSERT_TRUE(list->GetDictionary(0, &report)); EXPECT_EQ(5u, report->size()); ExpectDictIntegerValue(0, *report, "age"); ExpectDictStringValue(kType_, *report, "type"); ExpectDictStringValue(kUrl_.spec(), *report, "url"); ExpectDictStringValue(kUserAgent_, *report, "user_agent"); ExpectDictDictionaryValue(body, *report, "body"); } pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS); // Successful upload should remove delivered reports. std::vector<const ReportingReport*> reports; cache()->GetReports(&reports); EXPECT_TRUE(reports.empty()); { const ReportingEndpoint::Statistics stats = GetEndpointStatistics(kGroupKey_, kEndpoint_); EXPECT_EQ(1, stats.attempted_uploads); EXPECT_EQ(1, stats.successful_uploads); EXPECT_EQ(1, stats.attempted_reports); EXPECT_EQ(1, stats.successful_reports); } // TODO(dcreager): Check that BackoffEntry was informed of success. } TEST_F(ReportingDeliveryAgentTest, SuccessfulImmediateSubdomainUpload) { base::DictionaryValue body; body.SetString("key", "value"); ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_, OriginSubdomains::INCLUDE)); cache()->AddReport(kNik_, kSubdomainUrl_, kUserAgent_, kGroup_, kType_, body.CreateDeepCopy(), 0, tick_clock()->NowTicks(), 0); // Upload is automatically started when cache is modified. ASSERT_EQ(1u, pending_uploads().size()); EXPECT_EQ(kEndpoint_, pending_uploads()[0]->url()); { auto value = pending_uploads()[0]->GetValue(); base::ListValue* list; ASSERT_TRUE(value->GetAsList(&list)); EXPECT_EQ(1u, list->GetSize()); base::DictionaryValue* report; ASSERT_TRUE(list->GetDictionary(0, &report)); EXPECT_EQ(5u, report->size()); ExpectDictIntegerValue(0, *report, "age"); ExpectDictStringValue(kType_, *report, "type"); ExpectDictStringValue(kSubdomainUrl_.spec(), *report, "url"); ExpectDictStringValue(kUserAgent_, *report, "user_agent"); ExpectDictDictionaryValue(body, *report, "body"); } pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS); // Successful upload should remove delivered reports. std::vector<const ReportingReport*> reports; cache()->GetReports(&reports); EXPECT_TRUE(reports.empty()); { const ReportingEndpoint::Statistics stats = GetEndpointStatistics(kGroupKey_, kEndpoint_); EXPECT_EQ(1, stats.attempted_uploads); EXPECT_EQ(1, stats.successful_uploads); EXPECT_EQ(1, stats.attempted_reports); EXPECT_EQ(1, stats.successful_reports); } // TODO(dcreager): Check that BackoffEntry was informed of success. } TEST_F(ReportingDeliveryAgentTest, SuccessfulImmediateSubdomainUploadWithOverwrittenEndpoint) { base::DictionaryValue body; body.SetString("key", "value"); ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_, OriginSubdomains::INCLUDE)); cache()->AddReport(kNik_, kSubdomainUrl_, kUserAgent_, kGroup_, kType_, body.CreateDeepCopy(), 0, tick_clock()->NowTicks(), 0); // Upload is automatically started when cache is modified. ASSERT_EQ(1u, pending_uploads().size()); // Change the endpoint group to exclude subdomains. ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_, OriginSubdomains::EXCLUDE)); pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS); { const ReportingEndpoint::Statistics stats = GetEndpointStatistics(kGroupKey_, kEndpoint_); EXPECT_EQ(1, stats.attempted_uploads); EXPECT_EQ(1, stats.successful_uploads); EXPECT_EQ(1, stats.attempted_reports); EXPECT_EQ(1, stats.successful_reports); } // Successful upload should remove delivered reports. std::vector<const ReportingReport*> reports; cache()->GetReports(&reports); EXPECT_TRUE(reports.empty()); } TEST_F(ReportingDeliveryAgentTest, SuccessfulDelayedUpload) { base::DictionaryValue body; body.SetString("key", "value"); // Trigger and complete an upload to start the delivery timer. ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_)); cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_, body.CreateDeepCopy(), 0, tick_clock()->NowTicks(), 0); pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS); // Add another report to upload after a delay. cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_, body.CreateDeepCopy(), 0, tick_clock()->NowTicks(), 0); EXPECT_TRUE(delivery_timer()->IsRunning()); delivery_timer()->Fire(); ASSERT_EQ(1u, pending_uploads().size()); EXPECT_EQ(kEndpoint_, pending_uploads()[0]->url()); { auto value = pending_uploads()[0]->GetValue(); base::ListValue* list; ASSERT_TRUE(value->GetAsList(&list)); EXPECT_EQ(1u, list->GetSize()); base::DictionaryValue* report; ASSERT_TRUE(list->GetDictionary(0, &report)); EXPECT_EQ(5u, report->size()); ExpectDictIntegerValue(0, *report, "age"); ExpectDictStringValue(kType_, *report, "type"); ExpectDictStringValue(kUrl_.spec(), *report, "url"); ExpectDictStringValue(kUserAgent_, *report, "user_agent"); ExpectDictDictionaryValue(body, *report, "body"); } pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS); { const ReportingEndpoint::Statistics stats = GetEndpointStatistics(kGroupKey_, kEndpoint_); EXPECT_EQ(2, stats.attempted_uploads); EXPECT_EQ(2, stats.successful_uploads); EXPECT_EQ(2, stats.attempted_reports); EXPECT_EQ(2, stats.successful_reports); } // Successful upload should remove delivered reports. std::vector<const ReportingReport*> reports; cache()->GetReports(&reports); EXPECT_TRUE(reports.empty()); // TODO(juliatuttle): Check that BackoffEntry was informed of success. } TEST_F(ReportingDeliveryAgentTest, FailedUpload) { ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_)); cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_, std::make_unique<base::DictionaryValue>(), 0, tick_clock()->NowTicks(), 0); EXPECT_TRUE(delivery_timer()->IsRunning()); delivery_timer()->Fire(); ASSERT_EQ(1u, pending_uploads().size()); pending_uploads()[0]->Complete(ReportingUploader::Outcome::FAILURE); { const ReportingEndpoint::Statistics stats = GetEndpointStatistics(kGroupKey_, kEndpoint_); EXPECT_EQ(1, stats.attempted_uploads); EXPECT_EQ(0, stats.successful_uploads); EXPECT_EQ(1, stats.attempted_reports); EXPECT_EQ(0, stats.successful_reports); } // Failed upload should increment reports' attempts. std::vector<const ReportingReport*> reports; cache()->GetReports(&reports); ASSERT_EQ(1u, reports.size()); EXPECT_EQ(1, reports[0]->attempts); // Since endpoint is now failing, an upload won't be started despite a pending // report. ASSERT_TRUE(pending_uploads().empty()); EXPECT_TRUE(delivery_timer()->IsRunning()); delivery_timer()->Fire(); EXPECT_TRUE(pending_uploads().empty()); { const ReportingEndpoint::Statistics stats = GetEndpointStatistics(kGroupKey_, kEndpoint_); EXPECT_EQ(1, stats.attempted_uploads); EXPECT_EQ(0, stats.successful_uploads); EXPECT_EQ(1, stats.attempted_reports); EXPECT_EQ(0, stats.successful_reports); } } TEST_F(ReportingDeliveryAgentTest, DisallowedUpload) { // This mimics the check that is controlled by the BACKGROUND_SYNC permission // in a real browser profile. context()->test_delegate()->set_disallow_report_uploads(true); static const int kAgeMillis = 12345; base::DictionaryValue body; body.SetString("key", "value"); ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_)); cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_, body.CreateDeepCopy(), 0, tick_clock()->NowTicks(), 0); tick_clock()->Advance(base::TimeDelta::FromMilliseconds(kAgeMillis)); EXPECT_TRUE(delivery_timer()->IsRunning()); delivery_timer()->Fire(); // We should not try to upload the report, since we weren't given permission // for this origin. EXPECT_TRUE(pending_uploads().empty()); { const ReportingEndpoint::Statistics stats = GetEndpointStatistics(kGroupKey_, kEndpoint_); EXPECT_EQ(0, stats.attempted_uploads); EXPECT_EQ(0, stats.successful_uploads); EXPECT_EQ(0, stats.attempted_reports); EXPECT_EQ(0, stats.successful_reports); } // Disallowed reports should NOT have been removed from the cache. std::vector<const ReportingReport*> reports; cache()->GetReports(&reports); EXPECT_EQ(1u, reports.size()); } TEST_F(ReportingDeliveryAgentTest, RemoveEndpointUpload) { static const url::Origin kDifferentOrigin = url::Origin::Create(GURL("https://origin2/")); static const ReportingEndpointGroupKey kOtherGroupKey( NetworkIsolationKey(), kDifferentOrigin, kGroup_); ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_)); ASSERT_TRUE(SetEndpointInCache(kOtherGroupKey, kEndpoint_, kExpires_)); cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_, std::make_unique<base::DictionaryValue>(), 0, tick_clock()->NowTicks(), 0); EXPECT_TRUE(delivery_timer()->IsRunning()); delivery_timer()->Fire(); ASSERT_EQ(1u, pending_uploads().size()); pending_uploads()[0]->Complete(ReportingUploader::Outcome::REMOVE_ENDPOINT); // "Remove endpoint" upload should remove endpoint from *all* origins and // increment reports' attempts. std::vector<const ReportingReport*> reports; cache()->GetReports(&reports); ASSERT_EQ(1u, reports.size()); EXPECT_EQ(1, reports[0]->attempts); EXPECT_FALSE(FindEndpointInCache(kGroupKey_, kEndpoint_)); EXPECT_FALSE(FindEndpointInCache(kOtherGroupKey, kEndpoint_)); // Since endpoint is now failing, an upload won't be started despite a pending // report. EXPECT_TRUE(delivery_timer()->IsRunning()); delivery_timer()->Fire(); EXPECT_TRUE(pending_uploads().empty()); } TEST_F(ReportingDeliveryAgentTest, ConcurrentRemove) { ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_)); cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_, std::make_unique<base::DictionaryValue>(), 0, tick_clock()->NowTicks(), 0); EXPECT_TRUE(delivery_timer()->IsRunning()); delivery_timer()->Fire(); ASSERT_EQ(1u, pending_uploads().size()); // Remove the report while the upload is running. std::vector<const ReportingReport*> reports; cache()->GetReports(&reports); EXPECT_EQ(1u, reports.size()); const ReportingReport* report = reports[0]; EXPECT_FALSE(cache()->IsReportDoomedForTesting(report)); // Report should appear removed, even though the cache has doomed it. cache()->RemoveReports(reports, ReportingReport::Outcome::UNKNOWN); cache()->GetReports(&reports); EXPECT_TRUE(reports.empty()); EXPECT_TRUE(cache()->IsReportDoomedForTesting(report)); // Completing upload shouldn't crash, and report should still be gone. pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS); cache()->GetReports(&reports); EXPECT_TRUE(reports.empty()); } TEST_F(ReportingDeliveryAgentTest, ConcurrentRemoveDuringPermissionsCheck) { // Pause the permissions check, so that we can try to remove some reports // while we're in the middle of verifying that we can upload them. (This is // similar to the previous test, but removes the reports during a different // part of the upload process.) context()->test_delegate()->set_pause_permissions_check(true); ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_)); cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_, std::make_unique<base::DictionaryValue>(), 0, tick_clock()->NowTicks(), 0); ASSERT_TRUE(context()->test_delegate()->PermissionsCheckPaused()); // Remove the report while the upload is running. std::vector<const ReportingReport*> reports; cache()->GetReports(&reports); EXPECT_EQ(1u, reports.size()); const ReportingReport* report = reports[0]; EXPECT_FALSE(cache()->IsReportDoomedForTesting(report)); // Report should appear removed, even though the cache has doomed it. cache()->RemoveReports(reports, ReportingReport::Outcome::UNKNOWN); cache()->GetReports(&reports); EXPECT_TRUE(reports.empty()); EXPECT_TRUE(cache()->IsReportDoomedForTesting(report)); // Completing upload shouldn't crash, and report should still be gone. context()->test_delegate()->ResumePermissionsCheck(); ASSERT_EQ(1u, pending_uploads().size()); pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS); cache()->GetReports(&reports); EXPECT_TRUE(reports.empty()); } // Test that the agent will combine reports destined for the same endpoint, even // if the reports are from different origins. TEST_F(ReportingDeliveryAgentTest, BatchReportsFromDifferentOriginsToSameEndpoint) { static const GURL kDifferentUrl("https://origin2/path"); static const url::Origin kDifferentOrigin = url::Origin::Create(kDifferentUrl); const ReportingEndpointGroupKey kDifferentGroupKey(NetworkIsolationKey(), kDifferentOrigin, kGroup_); ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_)); ASSERT_TRUE(SetEndpointInCache(kDifferentGroupKey, kEndpoint_, kExpires_)); // Trigger and complete an upload to start the delivery timer. cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_, std::make_unique<base::DictionaryValue>(), 0, tick_clock()->NowTicks(), 0); pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS); // Now that the delivery timer is running, these reports won't be immediately // uploaded. cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_, std::make_unique<base::DictionaryValue>(), 0, tick_clock()->NowTicks(), 0); cache()->AddReport(kNik_, kDifferentUrl, kUserAgent_, kGroup_, kType_, std::make_unique<base::DictionaryValue>(), 0, tick_clock()->NowTicks(), 0); EXPECT_EQ(0u, pending_uploads().size()); // When we fire the delivery timer, we should NOT batch these two reports into // a single upload, since each upload must only contain reports about a single // origin. EXPECT_TRUE(delivery_timer()->IsRunning()); delivery_timer()->Fire(); ASSERT_EQ(2u, pending_uploads().size()); pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS); pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS); EXPECT_EQ(0u, pending_uploads().size()); } // Test that the agent won't start a second upload to the same endpoint for a // particular origin while one is pending, but will once it is no longer // pending. TEST_F(ReportingDeliveryAgentTest, SerializeUploadsToEndpoint) { ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_)); cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_, std::make_unique<base::DictionaryValue>(), 0, tick_clock()->NowTicks(), 0); EXPECT_TRUE(delivery_timer()->IsRunning()); delivery_timer()->Fire(); EXPECT_EQ(1u, pending_uploads().size()); cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_, std::make_unique<base::DictionaryValue>(), 0, tick_clock()->NowTicks(), 0); EXPECT_TRUE(delivery_timer()->IsRunning()); delivery_timer()->Fire(); ASSERT_EQ(1u, pending_uploads().size()); pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS); EXPECT_EQ(0u, pending_uploads().size()); EXPECT_TRUE(delivery_timer()->IsRunning()); delivery_timer()->Fire(); ASSERT_EQ(1u, pending_uploads().size()); pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS); EXPECT_EQ(0u, pending_uploads().size()); } // Test that the agent won't start a second upload for an (origin, group) while // one is pending, even if a different endpoint is available, but will once the // original delivery is complete and the (origin, group) is no longer pending. TEST_F(ReportingDeliveryAgentTest, SerializeUploadsToGroup) { static const GURL kDifferentEndpoint("https://endpoint2/"); ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_)); ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kDifferentEndpoint, kExpires_)); cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_, std::make_unique<base::DictionaryValue>(), 0, tick_clock()->NowTicks(), 0); EXPECT_TRUE(delivery_timer()->IsRunning()); delivery_timer()->Fire(); EXPECT_EQ(1u, pending_uploads().size()); cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_, std::make_unique<base::DictionaryValue>(), 0, tick_clock()->NowTicks(), 0); EXPECT_TRUE(delivery_timer()->IsRunning()); delivery_timer()->Fire(); ASSERT_EQ(1u, pending_uploads().size()); pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS); EXPECT_EQ(0u, pending_uploads().size()); EXPECT_TRUE(delivery_timer()->IsRunning()); delivery_timer()->Fire(); ASSERT_EQ(1u, pending_uploads().size()); pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS); EXPECT_EQ(0u, pending_uploads().size()); } // Tests that the agent will start parallel uploads to different groups within // the same origin. TEST_F(ReportingDeliveryAgentTest, ParallelizeUploadsAcrossGroups) { static const GURL kDifferentEndpoint("https://endpoint2/"); static const std::string kDifferentGroup("group2"); const ReportingEndpointGroupKey kDifferentGroupKey(NetworkIsolationKey(), kOrigin_, kDifferentGroup); ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_)); ASSERT_TRUE( SetEndpointInCache(kDifferentGroupKey, kDifferentEndpoint, kExpires_)); cache()->AddReport(kNik_, kUrl_, kUserAgent_, kGroup_, kType_, std::make_unique<base::DictionaryValue>(), 0, tick_clock()->NowTicks(), 0); cache()->AddReport(kNik_, kUrl_, kUserAgent_, kDifferentGroup, kType_, std::make_unique<base::DictionaryValue>(), 0, tick_clock()->NowTicks(), 0); EXPECT_TRUE(delivery_timer()->IsRunning()); delivery_timer()->Fire(); ASSERT_EQ(2u, pending_uploads().size()); pending_uploads()[1]->Complete(ReportingUploader::Outcome::SUCCESS); pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS); EXPECT_EQ(0u, pending_uploads().size()); } } // namespace } // namespace net
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
bc0679f28b5ee780523ba98919ca70e73b655901
8726add10e5cfcb399b68456e1068c0e09fd8111
/HelloWorld.cxx
3a7e0a3bfa2ddc3c807504a2b55d499622f3f726
[]
no_license
El-Sadeh/DDS-Hello-world
f537b6737af0e13d03c85eab2f918a8cee288731
64e1a4aeae59200c9f1b1a6aec34d4c24f795f59
refs/heads/master
2020-08-21T21:10:27.894170
2019-10-24T05:11:44
2019-10-24T05:11:44
216,246,407
0
0
null
2019-10-22T11:27:50
2019-10-19T17:41:30
C++
UTF-8
C++
false
false
6,819
cxx
/* WARNING: THIS FILE IS AUTO-GENERATED. DO NOT MODIFY. This file was generated from HelloWorld.idl using "rtiddsgen". The rtiddsgen tool is part of the RTI Connext distribution. For more information, type 'rtiddsgen -help' at a command shell or consult the RTI Connext manual. */ #include <iosfwd> #include <iomanip> #include "rti/topic/cdr/Serialization.hpp" #include "HelloWorld.hpp" #include "HelloWorldPlugin.hpp" #include <rti/util/ostream_operators.hpp> // ---- TemperatureStruct: TemperatureStruct::TemperatureStruct() : m_temp_ (0) { } TemperatureStruct::TemperatureStruct ( int16_t temp) : m_temp_( temp ) { } #ifdef RTI_CXX11_RVALUE_REFERENCES #ifdef RTI_CXX11_NO_IMPLICIT_MOVE_OPERATIONS TemperatureStruct::TemperatureStruct(TemperatureStruct&& other_) OMG_NOEXCEPT :m_temp_ (std::move(other_.m_temp_)) { } TemperatureStruct& TemperatureStruct::operator=(TemperatureStruct&& other_) OMG_NOEXCEPT { TemperatureStruct tmp(std::move(other_)); swap(tmp); return *this; } #endif #endif void TemperatureStruct::swap(TemperatureStruct& other_) OMG_NOEXCEPT { using std::swap; swap(m_temp_, other_.m_temp_); } bool TemperatureStruct::operator == (const TemperatureStruct& other_) const { if (m_temp_ != other_.m_temp_) { return false; } return true; } bool TemperatureStruct::operator != (const TemperatureStruct& other_) const { return !this->operator ==(other_); } // --- Getters and Setters: ------------------------------------------------- int16_t& TemperatureStruct::temp() OMG_NOEXCEPT { return m_temp_; } const int16_t& TemperatureStruct::temp() const OMG_NOEXCEPT { return m_temp_; } void TemperatureStruct::temp(int16_t value) { m_temp_ = value; } std::ostream& operator << (std::ostream& o,const TemperatureStruct& sample) { rti::util::StreamFlagSaver flag_saver (o); o <<"["; o << "temp: " << sample.temp() ; o <<"]"; return o; } // --- Type traits: ------------------------------------------------- namespace rti { namespace topic { template<> struct native_type_code<TemperatureStruct> { static DDS_TypeCode * get() { static RTIBool is_initialized = RTI_FALSE; static DDS_TypeCode_Member TemperatureStruct_g_tc_members[1]= { { (char *)"temp",/* Member name */ { 0,/* Representation ID */ DDS_BOOLEAN_FALSE,/* Is a pointer? */ -1, /* Bitfield bits */ NULL/* Member type code is assigned later */ }, 0, /* Ignored */ 0, /* Ignored */ 0, /* Ignored */ NULL, /* Ignored */ RTI_CDR_REQUIRED_MEMBER, /* Is a key? */ DDS_PUBLIC_MEMBER,/* Member visibility */ 1, NULL/* Ignored */ } }; static DDS_TypeCode TemperatureStruct_g_tc = {{ DDS_TK_STRUCT,/* Kind */ DDS_BOOLEAN_FALSE, /* Ignored */ -1, /*Ignored*/ (char *)"TemperatureStruct", /* Name */ NULL, /* Ignored */ 0, /* Ignored */ 0, /* Ignored */ NULL, /* Ignored */ 1, /* Number of members */ TemperatureStruct_g_tc_members, /* Members */ DDS_VM_NONE /* Ignored */ }}; /* Type code for TemperatureStruct*/ if (is_initialized) { return &TemperatureStruct_g_tc; } TemperatureStruct_g_tc_members[0]._representation._typeCode = (RTICdrTypeCode *)&DDS_g_tc_short; is_initialized = RTI_TRUE; return &TemperatureStruct_g_tc; } }; // native_type_code const dds::core::xtypes::StructType& dynamic_type<TemperatureStruct>::get() { return static_cast<const dds::core::xtypes::StructType&>( rti::core::native_conversions::cast_from_native<dds::core::xtypes::DynamicType>( *(native_type_code<TemperatureStruct>::get()))); } } } namespace dds { namespace topic { void topic_type_support<TemperatureStruct>:: register_type( dds::domain::DomainParticipant& participant, const std::string& type_name) { rti::domain::register_type_plugin( participant, type_name, TemperatureStructPlugin_new, TemperatureStructPlugin_delete); } std::vector<char>& topic_type_support<TemperatureStruct>::to_cdr_buffer( std::vector<char>& buffer, const TemperatureStruct& sample) { // First get the length of the buffer unsigned int length = 0; RTIBool ok = TemperatureStructPlugin_serialize_to_cdr_buffer( NULL, &length, &sample); rti::core::check_return_code( ok ? DDS_RETCODE_OK : DDS_RETCODE_ERROR, "Failed to calculate cdr buffer size"); // Create a vector with that size and copy the cdr buffer into it buffer.resize(length); ok = TemperatureStructPlugin_serialize_to_cdr_buffer( &buffer[0], &length, &sample); rti::core::check_return_code( ok ? DDS_RETCODE_OK : DDS_RETCODE_ERROR, "Failed to copy cdr buffer"); return buffer; } void topic_type_support<TemperatureStruct>::from_cdr_buffer(TemperatureStruct& sample, const std::vector<char>& buffer) { RTIBool ok = TemperatureStructPlugin_deserialize_from_cdr_buffer( &sample, &buffer[0], static_cast<unsigned int>(buffer.size())); rti::core::check_return_code(ok ? DDS_RETCODE_OK : DDS_RETCODE_ERROR, "Failed to create TemperatureStruct from cdr buffer"); } void topic_type_support<TemperatureStruct>::reset_sample(TemperatureStruct& sample) { rti::topic::reset_sample(sample.temp()); } void topic_type_support<TemperatureStruct>::allocate_sample(TemperatureStruct& sample, int, int) { } } }
[ "elelbaz10@hotmail.com" ]
elelbaz10@hotmail.com
add2850a9928772499918a9ae1ff604212d0ea80
cf1e0056e6ae530ff8ef1d25df3d973dea16bb0c
/Source/GA/GAAudioManager.cpp
6267f4b0a03001f5427c2da40507a5dee980826c
[ "Apache-2.0" ]
permissive
JackHarb89/ga2014
aa8c2a6ed4cb7031e8688dcfab6b66d013746c53
2d63e0f423ede52071605039a64eed4db792cb43
refs/heads/master
2016-09-06T08:49:36.178535
2014-08-08T05:28:59
2014-08-08T05:28:59
32,894,085
1
0
null
null
null
null
UTF-8
C++
false
false
180
cpp
#include "GA.h" #include "GAEnemy.h" #include "GAAudioManager.h" AGAAudioManager::AGAAudioManager(const class FPostConstructInitializeProperties& PCIP) : Super(PCIP) { }
[ "Jack_Harb@gmx.de@435454b9-d0bb-46eb-8854-52d2cd3ebfb7" ]
Jack_Harb@gmx.de@435454b9-d0bb-46eb-8854-52d2cd3ebfb7
09484d18a46e402660bdad767decead2a5a7551b
dba51dd933ab25e691adba397c064b48804196a9
/tdef-list/main.cpp
6964ac560ef6a1a393abffde226d1a969745465a
[ "MIT" ]
permissive
Alirezaies/DataStructures
342fd04688beecee2f2dcea5cc77d1f0fd583f84
2a4558edede6e412e06d918ec8c8c89d1cb28c64
refs/heads/master
2021-01-23T16:50:23.870217
2017-07-01T07:17:42
2017-07-01T07:17:42
93,306,127
1
0
null
null
null
null
UTF-8
C++
false
false
360
cpp
#include "include/TArray.h" #include <iostream> using namespace std; int main(){ TArray s(10); s.append('C'); s.append('F'); s.append('H'); s.Traverse(); cout<<"==========="<<endl; cout<<"Item 0: "<<s.getItem(0)<<endl; cout<<"==========="<<endl; s.add('K', 0); s.add('K', 2); s.Traverse(); return 0; }
[ "sadegh@webgo.ir" ]
sadegh@webgo.ir
e068ef174f7e2324f4cd6bed5f74587bea5693cc
f7eab131cd86ba217db9d8246024150931a68011
/034.Search.for.a.Range.cpp
a7929db79ae0c3d2cd3df16cefb42b854f8d056c
[ "Unlicense" ]
permissive
limingjie/LeetCode
068cee66139a176c798db3caa84541221211fe2d
0a303ed71276fb1f94988a4b360f49a6a94a325a
refs/heads/master
2016-08-03T15:18:02.697782
2015-09-16T10:44:13
2015-09-16T10:44:13
42,525,617
0
0
null
null
null
null
UTF-8
C++
false
false
996
cpp
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { int l = 0; int h = nums.size() - 1; int m; vector<int> result; // find first while (l <= h) { m = l + (h - l) / 2; if (nums[m] >= target) { h = m - 1; } else { l = m + 1; } } if (l >= nums.size() || nums[l] != target) { result.push_back(-1); result.push_back(-1); return result; } result.push_back(l); h = nums.size() - 1; // find last while (l <= h) { m = l + (h - l) / 2; if (nums[m] <= target) { l = m + 1; } else { h = m - 1; } } result.push_back(l - 1); return result; } };
[ "limingjie@outlook.com" ]
limingjie@outlook.com
43f455b59616b809d377b57037d6f12e48ae83e1
d69d609c0c80aade62c98f583c671dc0b27d0b27
/Public_const_and_structs.h
b59f2a22882951cf9eab0f4547b1fb63f101be95
[]
no_license
shakedguy/Tetris_Project
a525d6332153df3d75e4ce59dd452fbe106024a7
235827d5308e6bb35d41ba4e69557dabcea04cea
refs/heads/master
2023-05-08T15:56:13.000791
2021-05-31T20:10:08
2021-05-31T20:10:08
350,011,730
0
0
null
2021-04-28T16:14:13
2021-03-21T13:47:41
C++
UTF-8
C++
false
false
1,191
h
/*************************************** Header file for the consts and structs of all the project. ***************************************/ #ifndef _CONSTS_STRUCTS_H_ #define _CONSTS_STRUCTS_H_ /* In this file all the const parameters of the project will be written, * so if we will want to change sizes, locations or characters of objects, * we can do it from here and will not have to change each file of the relevant class */ #include <iostream> #include "io_utils.h" #include <random> #include <stdio.h> #include <vector> #include <map> #include <array> #include <list> #include <fstream> #include <string> #include "Colors.h" #include <time.h> using std::cin; using std::cout; using std::endl; using std::array; using std::vector; using std::string; using std::map; using std::list; using std::pair; #define EMPTY_CELL ' '// Define the character of the empty cell in the board using ushort = unsigned short int; using uint = unsigned int; using sint = short int; using uchar = unsigned char; // Define the numbers that represent steps as consts enum Keys { COUNTER_CLOCKWISE, CLOCKWISE, DROP, MOVE_LEFT, MOVE_RIGHT, DEFAULT, STOP, SPEED_MODE = 42, ESC = 27 }; #endif
[ "shakedguy94@gmail.com" ]
shakedguy94@gmail.com
9ce16692f7e6562d181eb15eee5e75d15b3ffec8
09c8013df6d4ca010706b5de1ec48b259f395e76
/MiniJVM/include/buffer.h
e8b2b7682316b4eb60a964a3cc4cf94e780fa5b8
[ "MIT" ]
permissive
lanrobin/minijvm
e048270c571327d4972678e1f0215b90684c477e
d6056012494656669a6665c981e6b23d8d121df8
refs/heads/master
2022-09-09T08:13:00.287176
2020-05-31T14:25:33
2020-05-31T14:25:33
258,674,691
0
0
null
null
null
null
UTF-8
C++
false
false
1,016
h
#ifndef __JVM_BUFFER_READER__ #define __JVM_BUFFER_READER__ #include "base_type.h" #include "platform.h" #include <iostream> using std::istream; struct Buffer { private: u1* buffer; size_t read_pos; size_t buffer_size; // 这个有可能没有。 wstring mappingFromFile; public: Buffer(istream& is, const wstring & fromFile = std::wstring()); Buffer(const char* buf, size_t offset, size_t count, const wstring& fromFile = std::wstring()); u1 readu1(); u2 readu2(); u4 readu4(); u1 peaku1(); u2 peaku2(); u4 peaku4(); size_t rewind(size_t count); size_t size() const; size_t pos() const; void resetReadPos(); void dumpToFile(const string& path); void dumpToFile(const wstring& path); wstring getMappingFile() const { return mappingFromFile; } ~Buffer(); private: void init(const char* buf, size_t offset, size_t count); public: static shared_ptr<Buffer> fromFile(const string& filePath); static shared_ptr<Buffer> fromFile(const wstring& filePath); }; #endif //__JVM_BUFFER_READER__
[ "rorbbin@gmail.com" ]
rorbbin@gmail.com
3703b6060c6d655d7e1c7042266c4650f760b1b6
0c2b97c6ded5fdec68cb1496d8e26d19d74c856a
/12_13/12_13main.cpp
a328ed06220010e0fd9ad05cacee9832db29e62c
[]
no_license
17mappingchengguo/cheng_guo
bcce55d9fe0fb89712d6345bdd705d92b8c4b6e4
470ec8357ab81df941eb1c461373ebf280044799
refs/heads/master
2020-04-02T06:25:36.368439
2019-04-21T11:57:20
2019-04-21T11:57:20
154,147,470
0
0
null
null
null
null
UTF-8
C++
false
false
1,091
cpp
#include <iostream> #include <vector> #include "Shape.h" #include "TwoDimensionalShape.h" #include "ThreeDimensionalShape.h" #include "Circle.h" #include "Square.h" #include "Sphere.h" #include "Cube.h" using namespace std; int main() { vector < Shape * > shapes( 4 ); shapes[ 0 ] = new Circle( 3.5, 6, 9 ); shapes[ 1 ] = new Square( 12, 2, 2 ); shapes[ 2 ] = new Sphere( 5, 1.5, 4.5 ); shapes[ 3 ] = new Cube( 2.2 ); for ( int i = 0; i < 4; i++ ) { cout << *shapes[ i ] << endl; TwoDimensionalShape *twoDimensionalShapePtr = dynamic_cast < TwoDimensionalShape * > ( shapes[ i ] ); if ( twoDimensionalShapePtr != 0 ) cout << "Area: " << twoDimensionalShapePtr->getArea() << endl; ThreeDimensionalShape *threeDimensionalShapePtr = dynamic_cast < ThreeDimensionalShape * > ( shapes[ i ] ); if ( threeDimensionalShapePtr != 0 ) cout << "Area: " << threeDimensionalShapePtr->getArea() << "\nVolume: " << threeDimensionalShapePtr->getVolume() << endl; cout << endl; } }
[ "2186479577@qq.com" ]
2186479577@qq.com
d083605808c6abdb36dc6b1e45c6ed168b9da357
0308ca5b152a082c1a206a1a136fd45e79b48143
/usvao/prototype/ipac/stk/include/ipac/stk/json/JSONOutput.inl
f4ab03c33a14c768e89e0a8e989a038a856410c4
[]
no_license
Schwarzam/usvirtualobservatory
b609bf21a09c187b70e311a4c857516284049c31
53fe6c14cc9312d048326acfa25377e3eac59858
refs/heads/master
2022-03-28T23:38:58.847018
2019-11-27T16:05:47
2019-11-27T16:05:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,685
inl
/************************************************************************* Copyright (c) 2014, California Institute of Technology, Pasadena, California, under cooperative agreement 0834235 between the California Institute of Technology and the National Science Foundation/National Aeronautics and Space Administration. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions of this BSD 3-clause license are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This software was developed by the Infrared Processing and Analysis Center (IPAC) for the Virtual Astronomical Observatory (VAO), jointly funded by NSF and NASA, and managed by the VAO, LLC, a non-profit 501(c)(3) organization registered in the District of Columbia and a collaborative effort of the Association of Universities for Research in Astronomy (AURA) and the Associated Universities, Inc. (AUI). *************************************************************************/ /** \file \brief Inline and templated member function definitions for JSONOutput.h \author Serge Monkewitz */ #ifndef IPAC_STK_JSON_JSONOUTPUT_H_ # error This file must be included from ipac/stk/json/JSONOutput.h #else # ifndef IPAC_STK_JSON_JSONOUTPUT_INL_ # define IPAC_STK_JSON_JSONOUTPUT_INL_ #include <sstream> namespace ipac { namespace stk { namespace json { /** Returns the formatting options for this JSONOutput. */ inline FormattingOptions const & JSONOutput::getFormattingOptions() const { return _opts; } /** Returns the underlying output stream or null. */ inline std::ostream * JSONOutput::getOutputStream() { return _out; } /** Returns the underlying Value or a null Value. */ inline Value const JSONOutput::getValue() const { return _value; } /** Outputs the given object. A free function \code outputJSON(T const &, JSONOutput &) \endcode must have been defined in order for compilation to succeed. */ template <typename T> inline JSONOutput & JSONOutput::value(T const & val) { Transaction tx(*this); outputJSON(val, *this); tx.commit(); return *this; } //@{ /** Outputs the value pointed to or null. */ template <typename T> inline JSONOutput & JSONOutput::value(T const * val) { if (!val) { return value(); } return value(*val); } template <typename T> inline JSONOutput & JSONOutput::value(boost::shared_ptr<T> const & val) { return value(val.get()); } template <typename T> inline JSONOutput & JSONOutput::value(boost::shared_ptr<T const> const & val) { return value(val.get()); } template <typename T> inline JSONOutput & JSONOutput::value(boost::scoped_ptr<T> val) { return value(val.get()); } template <typename T> inline JSONOutput & JSONOutput::value(boost::scoped_ptr<T const> val) { return value(val.get()); } //@} /** Outputs the values in the given range as a JSON array. */ template <typename ForwardsIterator> JSONOutput & JSONOutput::array(ForwardsIterator begin, ForwardsIterator end) { Transaction tx(*this); array(); for (; begin != end; ++begin) { value(*begin); } close(); tx.commit(); return *this; } /** Outputs \c k/v as a key/value pair in a JSON object. */ template <typename T> JSONOutput & JSONOutput::pair(std::string const & k, T const & v) { Transaction tx(*this); key(k); value(v); tx.commit(); return *this; } /** Outputs \c kv as a key/value pair in a JSON object. */ template <typename T> inline JSONOutput & JSONOutput::pair(std::pair<std::string const, T> const & kv) { return pair(kv.first, kv.second); } /** Outputs a map<std::string, T> as a JSON object. */ template <typename T> JSONOutput & JSONOutput::object(std::map<std::string, T> const & map) { typedef typename std::map<std::string, T>::const_iterator MapIter; Transaction tx(*this); object(); for (MapIter i(map.begin()), e(map.end()); i != e; ++i) { pair(*i); } close(); tx.commit(); return *this; } /** Returns a JSON string representation of \c obj. A free function \code outputJSON(T const &, JSONOutput &) \endcode must have been defined in order for compilation to succeed. */ template <typename T> std::string const JSONOutput::toString(T const & obj, FormattingOptions const & opts) { std::ostringstream oss; JSONOutput out(oss, opts); outputJSON(obj, out); return oss.str(); } /** Returns a representation of \c obj as a heirarchical value. A free function \code outputJSON(T const &, JSONOutput &) \endcode must have been defined in order for compilation to succeed. */ template <typename T> Value const JSONOutput::toValue(T const & obj) { JSONOutput out(true); outputJSON(obj, out); return out.getValue(); } /** Closes all currently open JSON objects and arrays. */ inline JSONOutput & JSONOutput::closeAll() { return close(_stack.size()); } inline std::string const JSONOutput::encode(char const * s) { return encode(std::string(s)); } inline std::string const JSONOutput::encode(char const * s, size_t n) { return encode(std::string(s, n)); } inline void JSONOutput::indent() { indent(_stack.size()); } }}} // namespace ipac::stk::json # endif // IPAC_STK_JSON_JSONOUTPUT_INL_ #endif // IPAC_STK_JSON_JSONOUTPUT_H_
[ "usvirtualobservatory@5a1e9bf7-f4d4-f7d4-5b89-e7d39643c4b5" ]
usvirtualobservatory@5a1e9bf7-f4d4-f7d4-5b89-e7d39643c4b5
4b0321d406120bee0ba9ff0f82c28212b0d64088
4f371e57ae035bd57c3de5c6190274d271c26d33
/cpp/binary.cpp
ecd95a483e945e646c5fde247f184f3d96d2a9e0
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
jailuthra/misc
3df82fde3d28156099153a8f658da349d1cf4a85
782d6a8e6154f1a52a3b818bde26ac07e00912c2
refs/heads/master
2021-05-16T02:34:19.860380
2019-10-07T08:22:21
2020-04-22T01:37:04
6,692,678
0
1
MIT
2020-04-22T01:37:06
2012-11-14T18:34:08
C
UTF-8
C++
false
false
881
cpp
#include<iostream> using namespace std; int main() { int i, n, num, beg, end, mid, a[100], pos, flag=0; cout << "Enter the size of the array: "; cin >> n; cout << "Enter the elements in ascending order of magnitude, one by one:\n"; for (i=0; i<n; i++) cin >> a[i]; beg = 0; end = n-1; mid = (beg + end)/2; cout << "Enter the number to search for: "; cin >> num; do { if (num == a[mid]) { pos = mid+1; flag = 1; break; } else if (num < a[mid]) end = mid-1; else if (num > a[mid]) beg = mid+1; mid = (beg + end)/2; } while (beg != end); if (flag == 1) cout << "\nThe number was found at position: " << pos << endl; else cout << "\nThe number was not found in the given array" << endl; return 0; }
[ "me@jailuthra.in" ]
me@jailuthra.in
6ea9b7e7db52f6f90ef820f1dda19e797104e93a
8e389f896a61cb2abab75616f0f2223aef6eeae7
/count-occurences-of-anagrams.cpp
7eae3f802d3908fadf4e8e29dc22af72edf4f035
[]
no_license
PrateekRanjanSingh/Algorithms
92304ebef9eb9835e7af1906adf9fb7cc3d5332b
0cf2a326da21207e0083fd73e407f412b3910c09
refs/heads/master
2020-04-09T03:02:23.247855
2019-07-31T07:05:26
2019-07-31T07:05:26
159,966,672
0
0
null
null
null
null
UTF-8
C++
false
false
721
cpp
#include <bits/stdc++.h> #define MAX 256 using namespace std; bool compare(int ar1[],int ar2[]) { for(int i = 0;i<256;i++) { if(ar1[i]!=ar2[i]) return false; } return true; } int main() { //code int t; cin >> t; while(t--) { string s,c; cin >> s >> c; int ar1[256] = {0}; int ar2[256] = {0}; for(auto x: c) { ar2[x]++; } int count = 0; for(int i = 0;i<c.length();i++) { ar1[s[i]]++; } if(compare(ar1,ar2)) count++; for(int i = c.length();i<s.length();i++) { ar1[s[i]]++; ar1[s[i-c.length()]]--; if(compare(ar1,ar2)) count++; } cout << count << endl; } return 0; }
[ "prateekranjansingh@gmail.com" ]
prateekranjansingh@gmail.com
d415f2987b6e9639fec55ee23c1a7ab5dd2f6a9b
2fa764b33e15edd3b53175456f7df61a594f0bb5
/appseed/aura/primitive/collection/collection_key_sort_array.cpp
f721b925a3dd0ee6d24ede3e4e4f74bb2740a6c7
[]
no_license
PeterAlfonsLoch/app
5f6ac8f92d7f468bc99e0811537380fcbd828f65
268d0c7083d9be366529e4049adedc71d90e516e
refs/heads/master
2021-01-01T17:44:15.914503
2017-07-23T16:58:08
2017-07-23T16:58:08
98,142,329
1
0
null
2017-07-24T02:44:10
2017-07-24T02:44:10
null
UTF-8
C++
false
false
25
cpp
//#include "framework.h"
[ "camilox_porting_to_android@ca2.cc" ]
camilox_porting_to_android@ca2.cc
a764755d2c576c94078e700ec70790a0ed24c099
33c4e40cb9a97b289229140d258dc934e70582a8
/mcg/src/external/BSR/include/concurrent/threads/synchronization/synchronizables/synchronizable.hh
c9499d83db9e2f25649d3f67e8c93e2ea4864695
[ "AGPL-3.0-or-later", "AGPL-3.0-only", "BSD-2-Clause-Views", "BSD-2-Clause" ]
permissive
jinlinyi/rcnn-depth
f6930ceee71593b1fd6cc9ab21cc6b9143f61962
c00da4a8b3df43a5df5e44d1820feb30bd6b2d7d
refs/heads/master
2020-03-27T02:06:14.194595
2018-09-01T05:16:09
2018-09-01T05:16:09
145,766,652
0
0
BSD-2-Clause
2018-08-22T21:49:47
2018-08-22T21:49:47
null
UTF-8
C++
false
false
2,906
hh
/* * Synchronizable interface. * * This abstract base class provides an interface for controlling read and * write access to objects by different threads. A thread requesting a * particular type of access is suspended until that request is granted. */ #ifndef CONCURRENT__THREADS__SYNCHRONIZATION__SYNCHRONIZABLES__SYNCHRONIZABLE_HH #define CONCURRENT__THREADS__SYNCHRONIZATION__SYNCHRONIZABLES__SYNCHRONIZABLE_HH namespace concurrent { namespace threads { namespace synchronization { namespace synchronizables { /* * Abstract base class for synchronization capabilities. */ class synchronizable { public: /* * Constructor. */ synchronizable(); /* * Destructor. */ virtual ~synchronizable(); /* * Claim/release exclusive access (abstract interface). */ virtual void abstract_lock() const = 0; virtual void abstract_unlock() const = 0; /* * Claim/release read access (abstract interface). */ virtual void abstract_read_lock() const = 0; virtual void abstract_read_unlock() const = 0; /* * Claim/release write access (abstract interface). */ virtual void abstract_write_lock() const = 0; virtual void abstract_write_unlock() const = 0; /* * Claim/release exclusive access to two synchronizable objects. */ static void lock(const synchronizable&, const synchronizable&); static void unlock(const synchronizable&, const synchronizable&); /* * Claim/release read access to two synchronizable objects. */ static void read_lock(const synchronizable&, const synchronizable&); static void read_unlock(const synchronizable&, const synchronizable&); /* * Claim/release write access to two synchronizable objects. */ static void write_lock(const synchronizable&, const synchronizable&); static void write_unlock(const synchronizable&, const synchronizable&); /* * Claim/release read access to the first object and write access to the * second. */ static void read_write_lock(const synchronizable&, const synchronizable&); static void read_write_unlock(const synchronizable&, const synchronizable&); protected: /* * Constructor. * Initialize the synchronizable object to have the given id. */ explicit synchronizable(unsigned long); /* * Get identity of synchronizable object. */ inline unsigned long syn_id() const; private: /* * Identity of synchronizable object. */ unsigned long _id; /* * Issue the next available identity. * The zero id is reserved for unsynchronized objects. */ static unsigned long id_next(); }; /* * Get identity of synchronizable object. */ inline unsigned long synchronizable::syn_id() const { return _id; } } /* namespace synchronizables */ } /* namespace synchronization */ } /* namespace threads */ } /* namespace concurrent */ #endif
[ "saurabhgupta.iitd@gmail.com" ]
saurabhgupta.iitd@gmail.com
8c872a2c984629f3c7a84c4d2b438c5fdd743f0c
354fa96a6a33fb5f590b61b946490393fae832e9
/test/thread_pool_test.cpp
c1f1d22c40776eb4fd0fb0d9f26eedeb04b0e7ba
[]
no_license
hpplinux/Mushroom
d0b23937496b01f09749638ee4e0a8e261b2c0d7
10f373f2266894a4d9dc6f505a05a3510bfde733
refs/heads/master
2021-01-13T03:18:33.789001
2016-11-30T08:20:23
2016-11-30T08:20:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,261
cpp
/** * > Author: UncP * > Mail: 770778010@qq.com * > Github: https://www.github.com/UncP/Mushroom * > Description: * * > Created Time: 2016-10-17 13:50:46 **/ #include <iostream> #include <fstream> #include "../src/db.hpp" #include "../src/iterator.hpp" #include "../src/thread_pool.hpp" int main(int argc, char **argv) { using namespace Mushroom; const char *file = "../data/Str.txt"; const int key_len = 10; const int total = (argc == 2) ? atoi(argv[1]) : 10; MushroomDB db("mushroom", key_len); KeySlice::SetStringFormat([](const KeySlice *key) { return std::string(key->Data()) + " "; }); std::ifstream in; in.open(file); assert(in.is_open()); std::string val; ThreadPool pool(new FiniteQueue<Task>()); char *buf[total]; KeySlice *key = nullptr; for (int i = 0; !in.eof() && i < total; ++i) { buf[i] = new char[BTreePage::PageByte + key_len]; in >> val; key = (KeySlice *)buf[i]; memcpy(key->Data(), val.c_str(), key_len); pool.AddTask(Task(&BTree::Put, (BTree *)db.Btree(), key)); } pool.Clear(); Iterator it(db.Btree()); assert(it.CheckBtree()); assert(db.Btree()->KeyCheck(in, total)); in.close(); for (int i = 0; i != total; ++i) delete [] buf[i]; db.Close(); return 0; }
[ "770778010@qq.com" ]
770778010@qq.com
399e8343414249682be50d7d0d63ba261f42847e
ca3449d1291ae8e93f88a56c5c9032103f730106
/LilEngie/Core/src/Entity/Components/Text.h
df0fd9d91cfcaffcb24d3f3e27d1aab6483c6f3a
[ "MIT" ]
permissive
Nordaj/LilEngie
f1d38304ffabb55f2d21272179db0d3b2697e6c4
453cee13c45ae33abe2665e1446fc90e67b1117a
refs/heads/master
2020-03-18T17:28:15.097151
2018-09-02T04:10:48
2018-09-02T04:10:48
135,031,092
0
0
null
null
null
null
UTF-8
C++
false
false
241
h
#pragma once #include <string> #include <glm/glm.hpp> #include <Entity/Component.h> #include <Graphics/Text/TextRenderer.h> class Text : public Component { public: TextRenderer renderer; Text(GameObject *obj); COMPONENT_ID("Text") };
[ "Nordajnapmach@gmail.com" ]
Nordajnapmach@gmail.com
c3a5f92df2a2d2bc7a423324c71eea4f6ea27e9f
b1fa90f76f916d29b5d68b7048268f4d8b71c111
/src/lightspeed/base/serialize/pointers.h
c6d9b38d7a217b03af7f28c9f18396efd49cabaf
[ "MIT" ]
permissive
ondra-novak/lightspeed
742092dbf5925027a7c4281f61b008fcd18a40e5
21028adb7e47bebd264e02978da5edd7463ef621
refs/heads/master
2021-01-24T06:35:55.151750
2019-12-13T12:56:21
2019-12-13T12:56:21
27,496,470
2
2
null
2015-08-19T14:50:36
2014-12-03T16:32:35
C++
UTF-8
C++
false
false
3,393
h
#pragma once #include "basicTypes.h" #include "serializer.h" #include "../containers/optional.h" namespace LightSpeed { ///Interface to serialize pointer /** Interface need define type of used serializer and type of base, which is common to all objects that will be serialized by this interface. Interface itself can be bind to the another base, but there must be possibility to make dynamic_cast between the bases. * @tparam Serializer type of serializer used to serialize pointer * @rparam BaseT common base type */ template<typename Serializer, typename BaseT> class IPointerSerializer: public IService { public: ///Destructor virtual ~IPointerSerializer () {} ///Loads instance from the archive /** * @param arch archive to read, must be in loading state * @return pointer to created instance or NULL (it is valid value) */ virtual BaseT *load(Serializer &arch) const = 0; ///Stores instance to the archive /** * @param arch archive to write into. Must be in storing state * @param instance instance to store */ virtual void store(Serializer &arch, const BaseT *instance) const = 0; ///Destroyes the instance /** Because caller don't have information about creation and allocation of the instance, it cannot call delete to destroy instance. This function must handle destroying. * @param instance instance to destroy */ virtual void destroy(BaseT *instance) const = 0; virtual TypeInfo getInterfaceType() const { return typeid(IPointerSerializer); } }; ///Specialization to serialize pointer /** * When pointer is serialized, it need to solve situation, when * pointer points to derived class. Then it is not possible to simply * call serialize method, because it will serialize only base part * of the object, and mostly it can be impossible to serialize pointer, * when it is abstract interface. * * This specialization expects section that defines implementation of * the IPointerSerializer interface. Implementation must implement * methods load(), store() and destroy() to handle pointer serialization * It also can choose best way, how to create object, especially, ho * to allocate object, because serializer itself doesn't define allocator * to allocate these objects. * * @param Type of pointer that is expected in the serialization script. * * @section requires Requires * * It requires IPointerSerializer::AsSection instance, that contains * pointer to an object implementing IPointerSerializer for given pointer type. * Note that you have to declare separate section for every type of the * pointer that can appear in the serialization script. To allow * sharing one instance of IPointerSerializer between many base-pointer * types, you can use class SrlzPtrConvert * * SrlzPtrConvert<Serializer,From,To> * * * */ template<typename T> class Serializable<T *> { public: template<typename Serializer> static void serialize(T *& object, Serializer &arch) { SrAttr<IPointerSerializer<Serializer,T> > pser(arch); if (arch.storing()) { pser->store(arch,object); } else if (arch.loading()) { T *tmp = pser->load(arch); std::swap(tmp,object); pser->destroy(tmp); } } }; }
[ "ondra-novak@email.cz" ]
ondra-novak@email.cz
0b6c87acc4c06776cf09ff9f17e424c76b60008e
e97481996e8d4b58e1c390fb41ffa5166acff0ff
/nall/mosaic/parser.hpp
5d68cd83f0503db28a83fb1d0759137a7665716c
[ "ISC" ]
permissive
kode54/resampler_iir
9dafd38fbe5f3a903933a826b73f37fd0228dc0a
95671c6735e964c8dd93dd0fc96cdbdc137aa4db
refs/heads/master
2021-01-20T18:20:34.052590
2016-06-04T01:04:07
2016-06-04T01:04:07
60,292,227
3
0
null
null
null
null
UTF-8
C++
false
false
4,613
hpp
#pragma once namespace nall { namespace mosaic { struct parser { //export from bitstream to canvas auto load(bitstream& stream, uint64_t offset, context& ctx, uint width, uint height) -> void { canvas.allocate(width, height); canvas.fill(ctx.paddingColor); parse(1, stream, offset, ctx, width, height); } //import from canvas to bitstream auto save(bitstream& stream, uint64_t offset, context& ctx) -> bool { if(stream.readonly) return false; parse(0, stream, offset, ctx, canvas.width(), canvas.height()); return true; } private: auto read(uint x, uint y) const -> uint32_t { uint addr = y * canvas.width() + x; if(addr >= canvas.width() * canvas.height()) return 0u; auto buffer = (uint32_t*)canvas.data(); return buffer[addr]; } auto write(uint x, uint y, uint32_t data) -> void { uint addr = y * canvas.width() + x; if(addr >= canvas.width() * canvas.height()) return; auto buffer = (uint32_t*)canvas.data(); buffer[addr] = data; } auto parse(bool load, bitstream& stream, uint64_t offset, context& ctx, uint width, uint height) -> void { stream.endian = ctx.endian; uint canvasWidth = width / (ctx.mosaicWidth * ctx.tileWidth * ctx.blockWidth + ctx.paddingWidth); uint canvasHeight = height / (ctx.mosaicHeight * ctx.tileHeight * ctx.blockHeight + ctx.paddingHeight); uint bitsPerBlock = ctx.depth * ctx.blockWidth * ctx.blockHeight; uint objectOffset = 0; for(uint objectY = 0; objectY < canvasHeight; objectY++) { for(uint objectX = 0; objectX < canvasWidth; objectX++) { if(objectOffset >= ctx.count && ctx.count > 0) break; uint objectIX = objectX * ctx.objectWidth(); uint objectIY = objectY * ctx.objectHeight(); objectOffset++; uint mosaicOffset = 0; for(uint mosaicY = 0; mosaicY < ctx.mosaicHeight; mosaicY++) { for(uint mosaicX = 0; mosaicX < ctx.mosaicWidth; mosaicX++) { uint mosaicData = ctx.mosaic(mosaicOffset, mosaicOffset); uint mosaicIX = (mosaicData % ctx.mosaicWidth) * (ctx.tileWidth * ctx.blockWidth); uint mosaicIY = (mosaicData / ctx.mosaicWidth) * (ctx.tileHeight * ctx.blockHeight); mosaicOffset++; uint tileOffset = 0; for(uint tileY = 0; tileY < ctx.tileHeight; tileY++) { for(uint tileX = 0; tileX < ctx.tileWidth; tileX++) { uint tileData = ctx.tile(tileOffset, tileOffset); uint tileIX = (tileData % ctx.tileWidth) * ctx.blockWidth; uint tileIY = (tileData / ctx.tileWidth) * ctx.blockHeight; tileOffset++; uint blockOffset = 0; for(uint blockY = 0; blockY < ctx.blockHeight; blockY++) { for(uint blockX = 0; blockX < ctx.blockWidth; blockX++) { if(load) { uint palette = 0; for(uint n = 0; n < ctx.depth; n++) { uint index = blockOffset++; if(ctx.order == 1) index = (index % ctx.depth) * ctx.blockWidth * ctx.blockHeight + (index / ctx.depth); palette |= stream.read(offset + ctx.block(index, index)) << n; } write( objectIX + mosaicIX + tileIX + blockX, objectIY + mosaicIY + tileIY + blockY, ctx.palette(palette, palette) ); } else /* save */ { uint32_t palette = read( objectIX + mosaicIX + tileIX + blockX, objectIY + mosaicIY + tileIY + blockY ); for(uint n = 0; n < ctx.depth; n++) { uint index = blockOffset++; if(ctx.order == 1) index = (index % ctx.depth) * ctx.blockWidth * ctx.blockHeight + (index / ctx.depth); stream.write(offset + ctx.block(index, index), palette & 1); palette >>= 1; } } } //blockX } //blockY offset += ctx.blockStride; } //tileX offset += ctx.blockOffset; } //tileY offset += ctx.tileStride; } //mosaicX offset += ctx.tileOffset; } //mosaicY offset += ctx.mosaicStride; } //objectX offset += ctx.mosaicOffset; } //objectY } image canvas; }; }}
[ "kode54@gmail.com" ]
kode54@gmail.com
6180943f293eae98e8e8b668b157f908c98a6829
240c51a603afb9d587c0bb24fc05fb15c9c5138f
/sketchbook/libraries/Motor/Motor.h
3e5107e34610e01238b3af5bbe4f1b32d2d262a4
[]
no_license
RingOfFireOrg/FT2014
b8a294ccb4cb860dfb7fb8204bf28a383dfc27d8
dec11c8572db0cf48a8fa7652e6cf78c6749c4dc
refs/heads/master
2021-01-19T14:07:35.183855
2014-12-18T02:58:15
2014-12-18T02:58:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
903
h
/* * This is the implementation file that goes with Motor.h * It gives control of a motor attached to DFRobotics Motor Shield for the * Arduino. The constructor needs the pin numbers for the enable pin * that controls direction (HIGH/LOW) and for the pwm pin that controls * speed. It should work for pretty much any pwm controlled motor even with * other controllers. * author - Rob Mackie * date - 10/20/2013 */ #ifndef __MOTOR__ #define __MOTOR__ #include "Arduino.h" class Motor { public: enum motor_id_t {MOTOR_1, MOTOR_2}; Motor(motor_id_t motor_id); void setup(void); void forward(unsigned char speed); void reverse(unsigned char speed); void stop(void); protected: static int const FORWARD = HIGH; static int const REVERSE = LOW; Motor(int e, int m); private: int direction_pin; int speed_pin; }; #endif //__MOTOR__
[ "slaveofschool@gmail.com" ]
slaveofschool@gmail.com
247af74cbb0d64d50a0ca0aee0c463afa9762cef
bc1c43d7ebb8fbb23d022f1554e1639285f276b2
/osl/core/osl/progress.cc
7a6d672794eaa5141fb5f78503c67e51a15fbe9e
[]
no_license
ai5/gpsfish
d1eafdece0c7c203c32603892ff9263a8fbcba59
b6ed91f77478fdb51b8747e2fcd78042d79271d5
refs/heads/master
2020-12-24T06:54:11.062234
2016-07-02T20:42:10
2016-07-02T20:42:10
62,468,733
1
0
null
null
null
null
UTF-8
C++
false
false
23,869
cc
#include "osl/progress.h" #include "osl/eval/weights.h" #include "osl/eval/midgame.h" #include "osl/eval/minorPiece.h" #include "osl/additionalEffect.h" #include "osl/bits/centering5x3.h" #include "osl/oslConfig.h" #include <iostream> #include <fstream> bool osl::progress::ml:: operator==(const NewProgressData& l, const NewProgressData& r) { return l.progresses == r.progresses && l.attack5x5_progresses == r.attack5x5_progresses && l.stand_progresses == r.stand_progresses && l.effect_progresses == r.effect_progresses && l.defenses == r.defenses && l.rook == r.rook && l.bishop == r.bishop && l.gold == r.gold && l.silver == r.silver && l.promoted == r.promoted && l.king_relative_attack == r.king_relative_attack && l.king_relative_defense == r.king_relative_defense && l.non_pawn_ptype_attacked_pair == r.non_pawn_ptype_attacked_pair && l.non_pawn_ptype_attacked_pair_eval == r.non_pawn_ptype_attacked_pair_eval; } osl::CArray<int, 81*15*10> osl::progress::ml::NewProgress::attack_relative; osl::CArray<int, 81*15*10> osl::progress::ml::NewProgress::defense_relative; osl::CArray<int, osl::Piece::SIZE> osl::progress::ml::NewProgress::stand_weight; osl::CArray<int, 1125> osl::progress::ml::NewProgress::attack5x5_weight; osl::CArray<int, 5625> osl::progress::ml::NewProgress::attack5x5_x_weight; osl::CArray<int, 10125> osl::progress::ml::NewProgress::attack5x5_y_weight; osl::CArray<int, 75> osl::progress::ml::NewProgress::effectstate_weight; osl::CArray<int, 4284> osl::progress::ml::NewProgress::king_relative_weight; osl::CArray<int, 262144> osl::progress::ml::NewProgress::attacked_ptype_pair_weight; osl::CArray<int, 10> osl::progress::ml::NewProgress::pawn_facing_weight; osl::CArray<int, 16> osl::progress::ml::NewProgress::promotion37_weight; osl::CArray<int, 56> osl::progress::ml::NewProgress::piecestand7_weight; int osl::progress::ml::NewProgress::max_progress; bool osl::progress::ml::NewProgress::initialized_flag; bool osl::progress::ml::NewProgress::setUp(const char *filename) { if (initialized_flag) return true; static CArray<int, 25> effect_weight; static CArray<int, 225> effect_x_weight, effect_y_weight; static CArray<int, 25> effect_defense_weight; static CArray<int, 225> effect_per_effect; static CArray<int, 225> effect_per_effect_defense; static CArray<int, 2025> effect_per_effect_y, effect_per_effect_x; std::ifstream is(filename); int read_count = 0; osl::eval::ml::Weights weights(25); for (size_t i = 0; i < weights.dimension(); ++i) { int val; is >> val; effect_weight[i] = val; ++read_count; } for (size_t i = 0; i < 225; ++i) { int val; is >> val; effect_x_weight[i] = val; ++read_count; } for (size_t i = 0; i < 225; ++i) { int val; is >> val; effect_y_weight[i] = val; ++read_count; } weights.resetDimension(25); for (size_t i = 0; i < weights.dimension(); ++i) { int val; is >> val; effect_defense_weight[i] = val; ++read_count; } weights.resetDimension(225); for (size_t i = 0; i < weights.dimension(); ++i) { int val; is >> val; effect_per_effect[i] = val; ++read_count; } weights.resetDimension(225); for (size_t i = 0; i < weights.dimension(); ++i) { int val; is >> val; effect_per_effect_defense[i] = val; ++read_count; } weights.resetDimension(2025); for (size_t i = 0; i < weights.dimension(); ++i) { int val; is >> val; effect_per_effect_y[i] = val; ++read_count; } weights.resetDimension(2025); for (size_t i = 0; i < weights.dimension(); ++i) { int val; is >> val; effect_per_effect_x[i] = val; ++read_count; } weights.resetDimension(Piece::SIZE); for (size_t i = 0; i < weights.dimension(); ++i) { int val; is >> val; stand_weight[i] = val; ++read_count; } weights.resetDimension(1125); for (size_t i = 0; i < weights.dimension(); ++i) { int val; is >> val; attack5x5_weight[i] = val; ++read_count; } weights.resetDimension(75); for (size_t i = 0; i < weights.dimension(); ++i) { int val; is >> val; effectstate_weight[i] = val; ++read_count; } weights.resetDimension(5625); for (size_t i = 0; i < weights.dimension(); ++i) { int val; is >> val; attack5x5_x_weight[i] = val; ++read_count; } weights.resetDimension(10125); for (size_t i = 0; i < weights.dimension(); ++i) { int val; is >> val; attack5x5_y_weight[i] = val; ++read_count; } weights.resetDimension(4284); for (size_t i = 0; i < weights.dimension(); ++i) { int val; is >> val; king_relative_weight[i] = val; ++read_count; } weights.resetDimension(262144); for (size_t i = 0; i < weights.dimension(); ++i) { int val; is >> val; attacked_ptype_pair_weight[i] = val; ++read_count; } weights.resetDimension(10); for (size_t i = 0; i < weights.dimension(); ++i) { int val; is >> val; pawn_facing_weight[i] = val; ++read_count; } weights.resetDimension(16); for (size_t i = 0; i < weights.dimension(); ++i) { int val; is >> val; promotion37_weight[i] = val; ++read_count; } weights.resetDimension(56); for (size_t i = 0; i < weights.dimension(); ++i) { int val; is >> val; piecestand7_weight[i] = val; ++read_count; } { int val; is >> val; max_progress = val; ++read_count; #ifdef EVAL_QUAD while (((max_progress/ProgressScale) % 3) && max_progress > 0) --max_progress; #endif } for(int king_x=1;king_x<=9;king_x++){ for(int king_y=1;king_y<=9;king_y++){ Square king(king_x,king_y); int king_index=(king_x-1)*9+king_y-1; const Square center = Centering5x3::adjustCenter(king); const int min_x = center.x() - 2; const int min_y = center.y() - 1; int i=0; for (int dx=0; dx<5; ++dx) { for (int dy=0; dy<3; ++dy,++i) { const Square target(min_x+dx,min_y+dy); int index0=king_index*15+i; int index_a=index0*10; int index_d=index0*10; attack_relative[index_a]= effect_weight[index<BLACK>(king, target)] + effect_x_weight[indexX<BLACK>(king, target)] + effect_y_weight[indexY<BLACK>(king, target)]; defense_relative[index_d]= effect_defense_weight[index<BLACK>(king, target)]; for(int count=0;count<=8;count++){ attack_relative[index_a+count+1]= effect_per_effect[indexPerEffect<BLACK>(king, target, count)] + effect_per_effect_y[indexPerEffectY<BLACK>(king, target, count)] + effect_per_effect_x[indexPerEffectX<BLACK>(king, target, count)]; defense_relative[index_d+count+1]= effect_per_effect_defense[indexPerEffect<BLACK>(king, target, count)]; } } } } } for(int king_x=1;king_x<=5;king_x++) for(int promoted=0;promoted<=4;promoted++) for(int silver=0;silver<=4;silver++) for(int gold=0;gold<=4;gold++) for(int bishop=0;bishop<=2;bishop++) for(int rook=0;rook<=2;rook++){ int index0=promoted + 5 * (silver + 5 * (gold + 5 * (bishop + 3 * rook))); int index1=king_x - 1 + 5 * (promoted + 5 * (silver + 5 * (gold + 5 * (bishop + 3 * rook)))); attack5x5_x_weight[index1]+=attack5x5_weight[index0]; } for (int i=0; i<PTYPE_SIZE*2*PTYPE_SIZE; ++i) for (int j=i+1; j<PTYPE_SIZE*2*PTYPE_SIZE; ++j) { attacked_ptype_pair_weight[eval::ml::NonPawnAttackedPtypePair::index2(j,i)] = attacked_ptype_pair_weight[eval::ml::NonPawnAttackedPtypePair::index2(i,j)]; } // set sum of [1..i] into [i], keep [0] as is. for (int i=2; i<10; ++i) pawn_facing_weight[i] += pawn_facing_weight[i-1]; initialized_flag = static_cast<bool>(is); if (!initialized_flag) { std::cerr << "Failed to load NewProgress data " << read_count << " from file " << filename << std::endl; } return initialized_flag; } bool osl::progress::ml::NewProgress::setUp() { return setUp(defaultFilename().c_str()); } std::string osl::progress::ml::NewProgress::defaultFilename() { std::string filename = OslConfig::home(); filename += "/data/progress.txt"; return filename; } template <osl::Player P> void osl::progress::ml::NewProgress::progressOne( const NumEffectState &state, int &attack, int &defense) { const Square king = state.kingSquare<P>(); const Square center = Centering5x3::adjustCenter(king); const int min_x = center.x() - 2; const int min_y = center.y() - 1; attack = defense = 0; Square kingRel=king; if(P==WHITE){ kingRel=kingRel.rotate180(); } int index0=((kingRel.x()-1)*9+kingRel.y()-1)*15; int index_a=index0*10 + (P==WHITE ? 10*14 : 0); for (int dx=0; dx<5; ++dx) { for (int dy=0; dy<3; ++dy) { const Square target(min_x+dx,min_y+dy); const int attack_count = state.countEffect(alt(P), target); const int defense_count = state.countEffect(P, target); attack += attack_count *attack_relative[index_a]+ attack_relative[index_a+std::min(attack_count,8)+1]; defense += defense_count * defense_relative[index_a]+ defense_relative[index_a+std::min(defense_count,8)+1]; if(P==BLACK){ index_a+=10; } else{ index_a-=10; } } } } template <osl::Player P> void osl::progress::ml::NewProgress::updateAttack5x5PiecesAndState( const NumEffectState &state) { const Square king = state.kingSquare<P>(); const int min_x = std::max(1, king.x() - 2); const int max_x = std::min(9, king.x() + 2); const int min_y = std::max(1, king.y() - 2); const int max_y = std::min(9, king.y() + 2); effect_progresses[P] = 0; PieceMask mask; for (int y = min_y; y <= max_y; ++y) { for (int x = min_x; x <= max_x; ++x) { const Square target(x, y); const NumBitmapEffect effect = state.effectSetAt(target); const int effect_diff = effect.countEffect(alt(P)) - effect.countEffect(P); const int x_diff = std::abs(x - king.x()); const int y_diff = (P == WHITE ? king.y() - y : y - king.y()); int index = std::max(std::min(effect_diff, 2), -2) + 2 + 5 * x_diff + 5 * 3 * (y_diff + 2); effect_progresses[P] += effectstate_weight[index]; mask |= effect; } } updateAttack5x5Pieces<P>(mask, state); } template <osl::Player P> void osl::progress::ml::NewProgress::updateAttack5x5Pieces( PieceMask mask, const NumEffectState& state) { const Player attack = alt(P); mask &= state.piecesOnBoard(attack); rook[attack] = mask.selectBit<ROOK>().countBit(); bishop[attack] = mask.selectBit<BISHOP>().countBit(); gold[attack] = mask.selectBit<GOLD>().countBit(); silver[attack] = (mask & ~state.promotedPieces()).selectBit<SILVER>().countBit(); PieceMask promoted_pieces = mask & state.promotedPieces(); promoted_pieces.clearBit<ROOK>(); promoted_pieces.clearBit<BISHOP>(); promoted[attack] = std::min(promoted_pieces.countBit(), 4); } template <osl::Player P> int osl::progress::ml::NewProgress::attack5x5Value( const NumEffectState &state) const { const Player attack = alt(P); int king_x = state.kingSquare<P>().x(); if (king_x > 5) king_x = 10 - king_x; const int king_y = (P == BLACK ? state.kingSquare<P>().y() : 10 - state.kingSquare<P>().y()); return (attack5x5_x_weight[index5x5x( rook[attack] + state.countPiecesOnStand<ROOK>(attack), bishop[attack] + state.countPiecesOnStand<BISHOP>(attack), gold[attack] + state.countPiecesOnStand<GOLD>(attack), silver[attack] + state.countPiecesOnStand<SILVER>(attack), promoted[attack], king_x)] + attack5x5_y_weight[index5x5y( rook[attack] + state.countPiecesOnStand<ROOK>(attack), bishop[attack] + state.countPiecesOnStand<BISHOP>(attack), gold[attack] + state.countPiecesOnStand<GOLD>(attack), silver[attack] + state.countPiecesOnStand<SILVER>(attack), promoted[attack], king_y)]); } void osl::progress::ml::NewProgress::updatePieceKingRelativeBonus( const NumEffectState &state) { const CArray<Square,2> kings = {{ state.kingSquare(BLACK), state.kingSquare(WHITE), }}; king_relative_attack.fill(0); king_relative_defense.fill(0); for (int i = 0; i < Piece::SIZE; ++i) { const Piece piece = state.pieceOf(i); if (piece.ptype() == osl::KING || !piece.isOnBoard()) continue; Player pl = piece.owner(); const int index_attack = indexRelative(piece.owner(), kings[alt(pl)], piece); const int index_defense = indexRelative(piece.owner(), kings[pl], piece) + 2142; king_relative_attack[pl] += king_relative_weight[index_attack]; king_relative_defense[pl] += king_relative_weight[index_defense]; } } template <osl::Player Owner> void osl::progress::ml::NewProgress:: updateNonPawnAttackedPtypePairOne(const NumEffectState& state) { PieceMask attacked = state.effectedMask(alt(Owner)) & state.piecesOnBoard(Owner); attacked.reset(state.kingPiece<Owner>().number()); mask_t ppawn = state.promotedPieces().getMask<PAWN>() & attacked.selectBit<PAWN>(); attacked.clearBit<PAWN>(); attacked.orMask(PtypeFuns<PAWN>::indexNum, ppawn); PieceVector pieces; while (attacked.any()) { const Piece piece = state.pieceOf(attacked.takeOneBit()); pieces.push_back(piece); } typedef eval::ml::NonPawnAttackedPtypePair feature_t; int result = 0; MultiInt result_eval; for (size_t i=0; i<pieces.size(); ++i) { const int i0 = feature_t::index1(state, pieces[i]); result += attacked_ptype_pair_weight[feature_t::index2(0,i0)]; for (size_t j=i+1; j<pieces.size(); ++j) { const int i1 = feature_t::index1(state, pieces[j]); result += attacked_ptype_pair_weight[feature_t::index2(i0,i1)]; if (Owner == BLACK) result_eval += feature_t::table[feature_t::index2(i0, i1)]; else result_eval -= feature_t::table[feature_t::index2(i0, i1)]; } } non_pawn_ptype_attacked_pair[Owner] = result; non_pawn_ptype_attacked_pair_eval[Owner] = result_eval; } void osl::progress::ml::NewProgress:: updateNonPawnAttackedPtypePair(const NumEffectState& state) { updateNonPawnAttackedPtypePairOne<BLACK>(state); updateNonPawnAttackedPtypePairOne<WHITE>(state); } void osl::progress::ml::NewProgress:: updatePawnFacing(const NumEffectState& state) { PieceMask attacked = state.effectedMask(WHITE) & state.piecesOnBoard(BLACK); mask_t pawn = attacked.selectBit<PAWN>() & ~(state.promotedPieces().getMask<PAWN>()); int count = 0; while (pawn.any()) { const Piece p(state.pieceOf(pawn.takeOneBit()+PtypeFuns<PAWN>::indexNum*32)); if (state.hasEffectByPtypeStrict<PAWN>(WHITE, p.square())) ++count; } pawn_facing = pawn_facing_weight[count]; } template <osl::Player P> void osl::progress::ml:: NewProgress::promotion37One(const NumEffectState& state, int rank) { typedef eval::ml::Promotion37 feature_t; CArray<int,PTYPE_SIZE> count = {{ 0 }}; for (int x=1; x<=9; ++x) { const Square target(x, rank); if (! state[target].isEmpty()) continue; int a = state.countEffect(P, target); const int d = state.countEffect(alt(P), target); if (a > 0 && a == d) a += AdditionalEffect::hasEffect(state, target, P); if (a <= d) continue; const Ptype ptype = state.findCheapAttack(P, target).ptype(); if (isPiece(ptype) && ! isPromoted(ptype)) count[ptype]++; } for (int p=PTYPE_BASIC_MIN; p<=PTYPE_MAX; ++p) { if (count[p] > 0) { promotion37 += promotion37_weight[p]; promotion37_eval += feature_t::table[p]*sign(P); } if (count[p] > 1) { promotion37 += promotion37_weight[p-8]*(count[p]-1); promotion37_eval += feature_t::table[p-8]*(sign(P)*(count[p]-1)); } } } void osl::progress::ml::NewProgress:: updatePromotion37(const NumEffectState& state) { promotion37 = 0; promotion37_eval = MultiInt(); promotion37One<BLACK>(state, 3); promotion37One<WHITE>(state, 7); } void osl::progress::ml::NewProgress:: updatePieceStand7(const NumEffectState& state) { piecestand7 = 0; for (int z=0; z<2; ++z) { CArray<int,7> stand = {{ 0 }}; int filled = 0; for (Ptype ptype: PieceStand::order) if (state.hasPieceOnStand(indexToPlayer(z), ptype)) stand[filled++] = ptype-PTYPE_BASIC_MIN; for (int i=0; i<std::min(7,filled+1); ++i) piecestand7 += piecestand7_weight[stand[i] + 8*i]; } } osl::progress::ml::NewProgress::NewProgress( const NumEffectState &state) { assert(initialized_flag); progressOne<BLACK>(state, progresses[BLACK], defenses[WHITE]); progressOne<WHITE>(state, progresses[WHITE], defenses[BLACK]); updateAttack5x5PiecesAndState<BLACK>(state); updateAttack5x5PiecesAndState<WHITE>(state); attack5x5_progresses[BLACK] = attack5x5Value<BLACK>(state); attack5x5_progresses[WHITE] = attack5x5Value<WHITE>(state); stand_progresses.fill(0); for (Ptype ptype: PieceStand::order) { const int black_count = state.countPiecesOnStand(BLACK, ptype); const int white_count = state.countPiecesOnStand(WHITE, ptype); for (int j = 0; j < black_count; ++j) { stand_progresses[WHITE] += stand_weight[Ptype_Table.getIndexMin(ptype) + j]; } for (int j = 0; j < white_count; ++j) { stand_progresses[BLACK] += stand_weight[Ptype_Table.getIndexMin(ptype) + j]; } } updatePieceKingRelativeBonus(state); updateNonPawnAttackedPtypePair(state); updatePawnFacing(state); updatePromotion37(state); updatePieceStand7(state); } template<osl::Player P> inline void osl::progress::ml::NewProgress::updateMain( const NumEffectState &new_state, Move last_move) { const Player altP=alt(P); assert(new_state.turn()==altP); assert(last_move.player()==P); const Square kb = new_state.kingSquare<BLACK>(), kw = new_state.kingSquare<WHITE>(); const BoardMask mb = new_state.changedEffects(BLACK), mw = new_state.changedEffects(WHITE); const bool king_move = last_move.ptype() == KING; if ((king_move && altP == BLACK) || mb.anyInRange(Board_Mask_Table5x3_Center.mask(kw)) || mw.anyInRange(Board_Mask_Table5x3_Center.mask(kw))) { progressOne<WHITE>(new_state,progresses[WHITE],defenses[BLACK]); } if ((king_move && altP == WHITE) || mw.anyInRange(Board_Mask_Table5x3_Center.mask(kb)) || mb.anyInRange(Board_Mask_Table5x3_Center.mask(kb))) { progressOne<BLACK>(new_state,progresses[BLACK],defenses[WHITE]); } const Ptype captured = last_move.capturePtype(); if (last_move.isDrop()) { const int count = new_state.countPiecesOnStand(P, last_move.ptype()) + 1; const int value = stand_weight[Ptype_Table.getIndexMin(last_move.ptype()) + count - 1]; stand_progresses[altP] -= value; } else if (captured != PTYPE_EMPTY) { Ptype ptype = unpromote(captured); const int count = new_state.countPiecesOnStand(P, ptype); const int value = stand_weight[(Ptype_Table.getIndexMin(ptype) + count - 1)]; stand_progresses[altP] += value; } if (king_move) { updatePieceKingRelativeBonus(new_state); } else { const CArray<Square,2> kings = {{ new_state.kingSquare(BLACK), new_state.kingSquare(WHITE), }}; if (!last_move.isDrop()) { const int index_attack = indexRelative<P>(kings[altP], last_move.oldPtype(), last_move.from()); const int index_defense = indexRelative<P>(kings[P], last_move.oldPtype(), last_move.from()) + 2142; king_relative_attack[P] -= king_relative_weight[index_attack]; king_relative_defense[P] -= king_relative_weight[index_defense]; } { const int index_attack = indexRelative<P>(kings[altP], last_move.ptype(), last_move.to()); const int index_defense = indexRelative<P>(kings[P], last_move.ptype(), last_move.to()) + 2142; king_relative_attack[P] += king_relative_weight[index_attack]; king_relative_defense[P] += king_relative_weight[index_defense]; } if (captured != PTYPE_EMPTY) { const int index_attack = indexRelative<altP>(kings[P], captured, last_move.to()); const int index_defense = indexRelative<altP>(kings[altP], captured, last_move.to()) + 2142; king_relative_attack[altP] -= king_relative_weight[index_attack]; king_relative_defense[altP] -= king_relative_weight[index_defense]; } } updateNonPawnAttackedPtypePair(new_state); updatePawnFacing(new_state); updatePromotion37(new_state); updatePieceStand7(new_state); } template<osl::Player P> void osl::progress::ml::NewProgress::updateSub( const NumEffectState &new_state, Move last_move) { const Player altP=alt(P); assert(new_state.turn()==altP); if (last_move.isPass()) return; const Square kb = new_state.kingSquare<BLACK>(), kw = new_state.kingSquare<WHITE>(); const BoardMask mb = new_state.changedEffects(BLACK), mw = new_state.changedEffects(WHITE); const bool king_move = last_move.ptype() == KING; const Ptype captured = last_move.capturePtype(); if ((king_move && altP == BLACK) || mb.anyInRange(Board_Mask_Table5x5.mask(kw)) || mw.anyInRange(Board_Mask_Table5x5.mask(kw))) { updateAttack5x5PiecesAndState<WHITE>(new_state); attack5x5_progresses[WHITE] = attack5x5Value<WHITE>(new_state); } else if (altP == WHITE &&(last_move.isDrop() || captured != PTYPE_EMPTY)) { attack5x5_progresses[WHITE] = attack5x5Value<WHITE>(new_state); } if ((king_move && altP == WHITE) || mw.anyInRange(Board_Mask_Table5x5.mask(kb)) || mb.anyInRange(Board_Mask_Table5x5.mask(kb))) { updateAttack5x5PiecesAndState<BLACK>(new_state); attack5x5_progresses[BLACK] = attack5x5Value<BLACK>(new_state); } else if (altP == BLACK && (last_move.isDrop() || captured != PTYPE_EMPTY)) { attack5x5_progresses[BLACK] = attack5x5Value<BLACK>(new_state); } updateMain<P>(new_state, last_move); } osl::progress::ml::NewProgressDebugInfo osl::progress::ml::NewProgress::debugInfo() const { NewProgressDebugInfo info; info.black_values[NewProgressDebugInfo::ATTACK_5X3] = progresses[0]; info.black_values[NewProgressDebugInfo::DEFENSE_5X3] = defenses[0]; info.black_values[NewProgressDebugInfo::ATTACK5X5] = attack5x5_progresses[0]; info.black_values[NewProgressDebugInfo::STAND] = stand_progresses[0]; info.black_values[NewProgressDebugInfo::EFFECT5X5] = effect_progresses[0]; info.black_values[NewProgressDebugInfo::KING_RELATIVE_ATTACK] = king_relative_attack[0]; info.black_values[NewProgressDebugInfo::KING_RELATIVE_DEFENSE] = king_relative_defense[0]; info.black_values[NewProgressDebugInfo::NON_PAWN_ATTACKED_PAIR] = non_pawn_ptype_attacked_pair[0]; info.white_values[NewProgressDebugInfo::ATTACK_5X3] = progresses[1]; info.white_values[NewProgressDebugInfo::DEFENSE_5X3] = defenses[1]; info.white_values[NewProgressDebugInfo::ATTACK5X5] = attack5x5_progresses[1]; info.white_values[NewProgressDebugInfo::STAND] = stand_progresses[1]; info.white_values[NewProgressDebugInfo::EFFECT5X5] = effect_progresses[1]; info.white_values[NewProgressDebugInfo::KING_RELATIVE_ATTACK] = king_relative_attack[1]; info.white_values[NewProgressDebugInfo::KING_RELATIVE_DEFENSE] = king_relative_defense[1]; info.white_values[NewProgressDebugInfo::NON_PAWN_ATTACKED_PAIR] = non_pawn_ptype_attacked_pair[1]; return info; } namespace osl { namespace progress { namespace ml { template void osl::progress::ml::NewProgress::updateSub<osl::BLACK>(const NumEffectState &new_state,Move last_move); template void osl::progress::ml::NewProgress::updateSub<osl::WHITE>(const NumEffectState &new_state,Move last_move); } } } // ;;; Local Variables: // ;;; mode:c++ // ;;; c-basic-offset:2 // ;;; End:
[ "taibarax@gmail.com" ]
taibarax@gmail.com
022392c4c105dc5e097c76117bc9271712296625
081153422168d9feb8795a8ebeeb6b4414b74ae2
/Source/PluginEditor.cpp
1f6e2793c2cb2b4ce9c04837cf8be5e29aa2d623
[]
no_license
sam-trolland/AudioMidiRecorderPlugin
c17cc5ec6d6178ce1d6ec7215143f903d9f85718
64ee869a936dd7c08007eb0f89efd7e363b91a52
refs/heads/master
2023-06-29T04:15:41.819901
2021-02-24T07:23:35
2021-02-24T07:23:35
341,801,566
1
0
null
null
null
null
UTF-8
C++
false
false
3,908
cpp
/* ============================================================================== This file contains the basic framework code for a JUCE plugin editor. ============================================================================== */ #include "PluginProcessor.h" #include "PluginEditor.h" //============================================================================== AudioMidiRecorderPluginProcessorEditor::AudioMidiRecorderPluginProcessorEditor (AudioMidiRecorderPluginProcessor& p) : AudioProcessorEditor (&p), audioProcessor (p) { // Make sure that before the constructor has finished, you've set the // editor's size to whatever you need it to be. setSize (200, 200); // GUI Elements /* midiVolume.setSliderStyle(juce::Slider::LinearBarVertical); midiVolume.setRange(0.0, 127.0, 1.0); midiVolume.setTextBoxStyle(juce::Slider::NoTextBox, false, 90, 0); midiVolume.setPopupDisplayEnabled(true, false, this); midiVolume.setTextValueSuffix(" Volume"); midiVolume.setValue(1.0); addAndMakeVisible(&midiVolume); // Add control to GUI midiVolume.addListener(this); */ // Setup Record Button addAndMakeVisible(recordButton); recordButton.addListener(this); recordButton.setButtonText("Record"); recordButton.setColour(TextButton::buttonColourId,Colours::green); } AudioMidiRecorderPluginProcessorEditor::~AudioMidiRecorderPluginProcessorEditor() { } //============================================================================== void AudioMidiRecorderPluginProcessorEditor::paint (juce::Graphics& g) { // (Our component is opaque, so we must completely fill the background with a solid colour) g.fillAll (getLookAndFeel().findColour (juce::ResizableWindow::backgroundColourId)); g.setColour (juce::Colours::white); g.setFont (15.0f); g.drawFittedText ("Midi Volume", 0, 0, getWidth(), 30, juce::Justification::centred, 1); } void AudioMidiRecorderPluginProcessorEditor::resized() { // This is generally where you'll want to lay out the positions of any // subcomponents in your editor.. // GUI Components //midiVolume.setBounds(40, 30, 20, getHeight() - 60); recordButton.setBounds(0,0,getWidth(),getHeight()); } void AudioMidiRecorderPluginProcessorEditor::buttonClicked (Button* button) { if (!recording){ // Start Recording // Setup Recording Driectory auto docsDir = File::getSpecialLocation (File::userDocumentsDirectory); auto parentDir = File(docsDir.getFullPathName()+"/AudioMidiRecordings" ); parentDir.createDirectory(); // Audio Recording File (Swap between .wav and .ogg formats here) audioRecordingFile = parentDir.getNonexistentChildFile("recording", ".wav"); //Wav Audio File Format //audioRecordingFile = parentDir.getNonexistentChildFile("dinverno_system_recording", ".ogg"); //OGG Audio File Format // Midi Recording File (same name as audio file - will overwrite if file exists) midiRecordingFile = parentDir.getChildFile(audioRecordingFile.getFileNameWithoutExtension()+".mid"); // Tell Audio Processor to start recording audioProcessor.startRecordingAudio(audioRecordingFile); audioProcessor.startRecordingMidi(midiRecordingFile); // Update GUI recordButton.setButtonText("Stop Recording"); recordButton.setColour(TextButton::buttonColourId,Colours::red); recording = true; }else{ // Stop Recording // Tell Audio Processor to Stop Recording audioProcessor.stopRecordingAudio(); audioProcessor.stopRecordingMidi(); // Update GUI recordButton.setButtonText("Record"); recordButton.setColour(TextButton::buttonColourId,Colours::green); recording = false; } }
[ "sam.trolland@gmail.com" ]
sam.trolland@gmail.com
0152fabf06fffcd99982919d88c4184a4955b8f8
e6559df51c2a14256962c3757073a491ea66de7c
/URI/1884 - Lutando Contra os Rajasi.cpp
4831a3903716bcb8ba5aa31b7ddf0cbe49bf9c87
[]
no_license
Maycon708/Maratona
c30eaedc3ee39d69582b0ed1a60f31ad8d666d43
b6d07582544c230e67c23a20e1a1be99d4b47576
refs/heads/master
2020-04-25T23:37:53.992330
2019-02-28T17:10:25
2019-02-28T17:10:25
143,191,679
0
0
null
null
null
null
UTF-8
C++
false
false
1,530
cpp
#include <bits/stdc++.h> #define INF 0x3F3F3F3F #define rep(i, a, b) for(int i = int(a); i < int(b); i++) #define it(i, a) for( typeof( a.begin() ) i = a.begin(); i != a.end(); i++ ) #define pb push_back #define pi 3.1415926535897932384626433832795028841971 #define debug(x) cout << #x << " = " << x << endl; #define debug2(x,y) cout << #x << " = " << x << " --- " << #y << " = " << y << "\n"; #define debugM( x, l, c ) { rep( i, 0, l ){ rep( j, 0, c ) cout << x[i][j] << " "; printf("\n");}} #define all(S) (S).begin(), (S).end() #define MAXV 1010000 #define MAXN 110 #define F first #define S second #define EPS 1e-9 #define mk make_pair using namespace std; typedef long long int ll; typedef pair <ll, ll> ii; inline bool cmp( ii a, ii b ){ int dif = a.F - b.F - a.S + b.S; if( dif ) return ( a.F - a.S ) < ( b.F - b.S ); return a.F > b.F; } inline bool cmp2( ii a, ii b ){ if( a.F != b.F ) return a.F < b.F; return a.S < b.S; } int main(){ ll t, n, h, k, g, r; scanf("%lld", &t ); while( t-- ){ vector < ii > l, p; scanf("%lld%lld%lld", &n, &h, &k ); rep( i, 0, n ){ scanf("%lld%lld", &g, &r ); if( g <= r ) l.pb( ii( g, r ) ); else p.pb( ii( g, r ) ); } sort( all( l ), cmp2 ); ll cnt = 0; rep( i, 0, l.size() ){ if( h >= l[i].F ){ h = ( h - l[i].F + l[i].S ); cnt++; } } sort( all( p ), cmp ); rep( i, 0, p.size() ){ if( h >= p[i].F ){ h = ( h - p[i].F + p[i].S ); cnt++; } } if( cnt + k >= n ) printf("Y\n"); else printf("N\n"); } }
[ "mayconalves@gea.inatel.br" ]
mayconalves@gea.inatel.br
2e970856caac6a2998f677547a6f6b4688adfa2d
64f0586e989f1b02b4543d696b4d2b308aa8046f
/DemoGame2D/DemoGame2D/Common_Fuc.h
a93871ad4f56d1921d3e0961b4d2efa32cc820d5
[]
no_license
hado-569/GameFirePlane
7b1ec457bd16bcb92bb67cb3e4724e9a1e3bce93
bf4f225568696dac89f639a911056ffd22488dcd
refs/heads/main
2023-01-22T11:43:55.513239
2020-11-22T12:18:19
2020-11-22T12:18:19
315,029,722
0
0
null
null
null
null
UTF-8
C++
false
false
1,094
h
#ifndef _COMMON_FUNC_H_ #define _COMMON_FUNC_H_ #include <iostream> #include <Windows.h> #include <SDL.h> #include <string> #include <SDL_image.h> #include <SDL_ttf.h> const int BKG_WIDTH(4000); const int BKG_HEIGHT(702); const int SCREEN_WIDTH(1000); const int SCREEN_HEIGHT(702); const int SCREEN_BPP(32); const int NUM_THREATS =2; static SDL_Surface* g_screen = NULL; static SDL_Surface* g_bkground = NULL; static SDL_Surface* g_bkground2 = NULL; static SDL_Surface* g_bkground3 = NULL; static SDL_Surface* g_img_menu = NULL; /*SDL_Surface* g_playerImage = NULL;*/ static SDL_Event g_event; namespace CommonFunctionSDL { SDL_Surface* LoadImage(std::string file_path); SDL_Rect ApplySurface(SDL_Surface* src, SDL_Surface* des, int x, int y); void ApplySurface2(SDL_Surface* src, SDL_Surface* des, SDL_Rect* clip, int x ,int y); void Cleanup(); bool CheckColision(const SDL_Rect& object1, const SDL_Rect& object2); int ShowMenu(SDL_Surface* des, TTF_Font* font); bool CheckForcusWithRect(const int& x, const int& y, const SDL_Rect& rect); } #endif // !_COMMON_FUNC_H_
[ "tonglao686@gmail.com" ]
tonglao686@gmail.com
ccc94a2b3da68d09a83b0aeed6a8c9d01c9ec120
092dd56a1bf9357466c05d0f5aedf240cec1a27b
/tests/mmstests/linearelasticity/nofaults-3d/GravityRefState3D.hh
8ffafb49979afe54de969d5806487c507b2e0d3c
[ "MIT" ]
permissive
rwalkerlewis/pylith
cef02d5543e99a3e778a1c530967e6b5f1d5dcba
c5f872c6afff004a06311d36ac078133a30abd99
refs/heads/main
2023-08-24T18:27:30.877550
2023-06-21T22:03:01
2023-06-21T22:03:01
154,047,591
0
0
MIT
2018-10-21T20:05:59
2018-10-21T20:05:59
null
UTF-8
C++
false
false
1,153
hh
// -*- C++ -*- // // ---------------------------------------------------------------------- // // Brad T. Aagaard, U.S. Geological Survey // Charles A. Williams, GNS Science // Matthew G. Knepley, University at Buffalo // // This code was developed as part of the Computational Infrastructure // for Geodynamics (http://geodynamics.org). // // Copyright (c) 2010-2022 University of California, Davis // // See LICENSE.md for license information. // // ---------------------------------------------------------------------- // #include <portinfo> #include "TestLinearElasticity.hh" // USES TestLinearElasticity_Data namespace pylith { class GravityRefState3D; } class pylith::GravityRefState3D { public: // Data factory methods static TestLinearElasticity_Data* TetP1(void); static TestLinearElasticity_Data* TetP2(void); static TestLinearElasticity_Data* TetP3(void); static TestLinearElasticity_Data* HexQ1(void); static TestLinearElasticity_Data* HexQ2(void); static TestLinearElasticity_Data* HexQ3(void); private: GravityRefState3D(void); ///< Not implemented }; // GravityRefState3D // End of file
[ "baagaard@usgs.gov" ]
baagaard@usgs.gov